text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { extractQueryStringObjectFromUrl, UpdatePolicy, HttpHeaders, HttpRequestMethod, MimeType, } from '../../../utils'; import { Page, Request, Route } from 'playwright'; export type ResponseData = | Record<string, unknown> | Record<string, never> | string | undefined | unknown; export type PostData = Record<string, unknown> | string | undefined | null | unknown; export type QueryString = Record<string, string>; export interface RequestInfos { request: Request; queryString: QueryString; postData: PostData; sharedContext: unknown; } /** * Be able to intercept a given http request url and provide a mocked response. * The mock will be selected only if all provided matchers return true. * When a matcher is not provided, it always default to true. * When multiple mocks are selected, the last one is taken (like in CSS): * this enables you to override existing mocks on specific conditions. * @export * @interface FluentMock */ export interface FluentMock { /** * Mock friendly name. Useful when you are debugging your mocks. * By default it will be set to 'not set' if you forgot to give your mock a name. * @type {string} * @memberof FluentMock */ displayName: string; /** * Predicate acting on the http request url. * If you return true for the input url, then the request will be mocked accordingly to the responseType. * If you return false, the the request will never be mocked and other matchers will never be called. * @memberof FluentMock */ urlMatcher: (url: string) => boolean; /** * Optional predicate acting on the http request method. * This predicate will be called only if the predicate urlMatcher returns true. * If you do not set a methodMatcher, a default one that always returns true is provided. * @memberof FluentMock */ methodMatcher: (method: HttpRequestMethod) => boolean; /** * Optional predicate acting on the query string. * This predicate will be called only if the predicate urlMatcher returns true. * If you do not set a queryStringMatcher, a default one that always returns true is provided. * * @memberof FluentMock */ queryStringMatcher: (queryString: QueryString) => boolean; /** * Optional predicate acting on the post data sent by the http request. * This predicate will be called only if the predicate urlMatcher returns true. * If you do not set a postDataMatcher, a default one that always returns true is provided. * * @memberof FluentMock */ postDataMatcher: (postData: PostData) => boolean; /** * Optional predicate acting on the shared context. * This predicate will be called only if all predicates {@link urlMatcher}, {@link queryStringMatcher}, {@link postDataMatcher}, returns true. * If you do not set a contextMatcher, a default one that always returns true is provided. * A mock can update the shared context on any method passing a {@link RequestInfos} object. * A context matcher should be used when the mock response depends on the requests history, * for example when the mock must respond only to the nth request given by the urlMatcher. * * @memberof FluentMock */ contextMatcher: (context: unknown) => boolean; /** * Optional predicate acting on custom conditions from the request and/or the query string and/or the post data and/or the shared context. * This predicate will be called only if the predicate urlMatcher returns true. * If you do not set a customMatcher, a default one that always returns true is provided. * * @memberof FluentMock */ customMatcher: (requestInfos: RequestInfos) => boolean; /** * Add or modify the headers that will be sent with the mocked response. * * @memberof FluentMock */ enrichResponseHeaders: (headers: HttpHeaders) => HttpHeaders; /** * Define the response type of the mocked request. * If you do not set a responseType, a default one will be infered from the provided jsonResponse or rawResponse. * * @type {('json' | 'string' | 'javascript' | 'empty' | 'continue')} * @memberof FluentMock */ responseType: 'json' | 'string' | 'javascript' | 'empty' | 'continue'; /** * Http response status. Can be a function that returns a number. * defaults to 200. * * @memberof FluentMock */ status: number | ((requestInfos: RequestInfos) => number); /** * Build your own json response. * This method will be called only if responseType is 'json'. * @memberof FluentMock */ jsonResponse: (requestInfos: RequestInfos) => ResponseData; /** * Build your own string response. * This method will be called only if responseType is 'string' or 'javascript'. * * @memberof FluentMock */ rawResponse: (requestInfos: RequestInfos) => string; /** * Delay the response by the given number of milliseconds. * Defaults to 0. * * @type {number} * @memberof FluentMock */ delayInMilliseconds: number; /** * Optional callback to update the data source of the mocked response. * When provided, this method will be called automatically when * 1°) the mock is found to be outdated by the helper {@link getOutdatedMocks}) * 2°) and the call to {@link lastUpdated} gives a date that is older than the {@link updatePolicy} * @memberof FluentMock */ updateData: (requestInfos: RequestInfos, response: ResponseData) => void; /** * Optional callback to get the last update of the data source used to mock the response. * This method will be called automatically when the mock is found to be outdated by the helper {@link getOutdatedMocks}) * Defaults to the current date. * * @type {Date} * @memberof FluentMock */ lastUpdated: () => Date; /** * Update policy for the data source of the mocked response. * Defaults to 'always'. * * @type {UpdatePolicy} * @memberof FluentMock */ updatePolicy: UpdatePolicy; } export function noopVoidFunc(): void { // do nothing } export function getPostDataOf(request: Request): PostData { try { return request.postDataJSON(); } catch (error) { return request.postData(); } } export const passthroughMock: FluentMock = { displayName: 'passthroughMock', urlMatcher: () => true, methodMatcher: () => true, queryStringMatcher: () => true, postDataMatcher: () => true, contextMatcher: () => true, customMatcher: () => true, enrichResponseHeaders: (headers: HttpHeaders) => headers, responseType: 'continue', status: 200, jsonResponse: () => { return {}; }, rawResponse: () => '', delayInMilliseconds: 0, updateData: noopVoidFunc, lastUpdated: () => new Date(), updatePolicy: 'always', }; export interface WithMocksOptions { onMockFound: (mock: Partial<FluentMock>, requestInfos: RequestInfos) => void; onMockNotFound: (requestInfos: RequestInfos) => void; onInternalError: (error: Error, mock: Partial<FluentMock>, requestInfos: RequestInfos) => void; } export const defaultMocksOptions: WithMocksOptions = { // eslint-disable-next-line @typescript-eslint/no-empty-function onMockNotFound: () => {}, // eslint-disable-next-line @typescript-eslint/no-empty-function onMockFound: () => {}, // eslint-disable-next-line @typescript-eslint/no-empty-function onInternalError: () => {}, }; export function getMockStatus(mock: Partial<FluentMock>, requestInfos: RequestInfos): number { if (typeof mock.status === 'function') { return mock.status(requestInfos); } if (typeof mock.status === 'number') { return mock.status; } return 200; } export function inferMockResponseTypeIfNeeded(mock: Partial<FluentMock>): Partial<FluentMock> { if (mock.responseType) { return mock; } if (typeof mock.jsonResponse === 'function' && typeof mock.rawResponse !== 'function') { return { ...mock, responseType: 'json', }; } if (typeof mock.rawResponse === 'function' && typeof mock.jsonResponse !== 'function') { return { ...mock, responseType: 'string', }; } if (typeof mock.rawResponse !== 'function' && typeof mock.jsonResponse !== 'function') { return { ...mock, responseType: 'empty', }; } return mock; } export function spreadMissingProperties(mock: Partial<FluentMock>): FluentMock { return { ...passthroughMock, displayName: 'not set', ...mock }; } export interface RouteOptions { /** * Response body. */ body: string | Buffer; /** * If set, equals to setting `Content-Type` response header. */ contentType: string; /** * Response headers. Header values will be converted to a string. */ headers: { [key: string]: string }; /** * File path to respond with. The content type will be inferred from file extension. If `path` is a relative path, then it * is resolved relative to the current working directory. */ path: string; /** * Response status code, defaults to `200`. */ status: number; } async function fullfillRouteWithMock( mock: FluentMock, route: Route, options: Partial<RouteOptions>, ): Promise<void> { if (mock.delayInMilliseconds > 0) { setTimeout(() => route.fulfill(options), mock.delayInMilliseconds); return; } route.fulfill(options); } export async function withMocks( mocks: () => Partial<FluentMock>[], context: () => unknown, options: Partial<WithMocksOptions>, page: Page | undefined, ): Promise<void> { if (typeof mocks !== 'function') { throw new Error(`mocks must be a function that returns an array of FluentMock objects.`); } if (!Array.isArray(mocks())) { throw new Error(`mocks must be a function that returns an array of FluentMock objects.`); } if (!page) { throw new Error(`Cannot intercept requests with mocks because no browser has been launched`); } const mockOptions: WithMocksOptions = { ...defaultMocksOptions, ...options, }; await page.route( (uri) => { if (mocks().length === 0) { return false; } const mockExists = mocks() .map(inferMockResponseTypeIfNeeded) .map(spreadMissingProperties) .map((mock) => mock.urlMatcher(uri.toString())) .some((match) => match === true); return mockExists; }, (route, request) => { const requestMethod = request.method() as HttpRequestMethod; const url = request.url(); const queryString = extractQueryStringObjectFromUrl(url) as QueryString; const postData = getPostDataOf(request); const sharedContext = context(); const requestInfos: RequestInfos = { request, queryString, postData, sharedContext }; const mock = mocks() .map(inferMockResponseTypeIfNeeded) .map(spreadMissingProperties) .filter((mock) => mock.urlMatcher(url)) .filter((mock) => mock.methodMatcher(requestMethod)) .filter((mock) => mock.queryStringMatcher(queryString)) .filter((mock) => mock.postDataMatcher(postData)) .filter((mock) => mock.contextMatcher(sharedContext)) .filter((mock) => mock.customMatcher(requestInfos)) .pop(); if (!mock) { mockOptions.onMockNotFound(requestInfos); route.continue(); return; } if (mock.responseType === 'continue' && mock.delayInMilliseconds === 0) { route.continue(); return; } if (mock.responseType === 'continue' && mock.delayInMilliseconds > 0) { setTimeout(() => route.continue(), mock.delayInMilliseconds); return; } if (mock.responseType === 'json') { const responseObject = mock.jsonResponse(requestInfos); const headers = mock.enrichResponseHeaders({ 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', }); const status = getMockStatus(mock, requestInfos); const body = JSON.stringify(responseObject); const contentType: MimeType = 'application/json'; mockOptions.onMockFound(mock, requestInfos); fullfillRouteWithMock(mock, route, { status, headers, contentType, body }); return; } if (mock.responseType === 'string') { const headers = mock.enrichResponseHeaders({ 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', }); const status = getMockStatus(mock, requestInfos); const body = mock.rawResponse(requestInfos); const contentType: MimeType = 'text/plain'; mockOptions.onMockFound(mock, requestInfos); fullfillRouteWithMock(mock, route, { status, headers, contentType, body }); return; } if (mock.responseType === 'empty') { const headers = mock.enrichResponseHeaders({ 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', }); const status = getMockStatus(mock, requestInfos); const body = ''; const contentType: MimeType = 'text/plain'; mockOptions.onMockFound(mock, requestInfos); fullfillRouteWithMock(mock, route, { status, headers, contentType, body }); return; } if (mock.responseType === 'javascript') { const headers = mock.enrichResponseHeaders({ 'access-control-allow-methods': '*', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Allow-Origin': '*', }); const status = getMockStatus(mock, requestInfos); const body = mock.rawResponse(requestInfos); const contentType: MimeType = 'application/javascript'; mockOptions.onMockFound(mock, requestInfos); fullfillRouteWithMock(mock, route, { status, headers, contentType, body }); return; } throw new Error(`mock with response type '${mock.responseType}' is not yet implemented`); }, ); }
the_stack
import path from "path"; import util from "util"; import blessed from "blessed"; import WebSocket from "ws"; // import timer from "timers/promises" import minimist from "minimist"; import * as logWriter from "./logWriter"; import { Client, Room } from "colyseus.js"; // TODO: use "timers/promises" instead (drop Node.js v14) const timer = { setTimeout(milliseconds: number, ...args: any) { return new Promise((resolve) => setTimeout(resolve, milliseconds, ...args)); } } const argv = minimist(process.argv.slice(2)); // const packageJson = import("../package.json"); const packageJson = { name: "@colyseus/loadtest", version: "0.14" }; function displayHelpAndExit() { console.log(`${packageJson.name} v${packageJson.version} Options: --endpoint: WebSocket endpoint for all connections (default: ws://localhost:2567) --room: room handler name (you can also use --roomId instead to join by id) --roomId: room id (specify instead of --room) [--numClients]: number of connections to open (default is 1) [--delay]: delay to start each connection (in milliseconds) [--project]: specify a tsconfig.json file path [--reestablishAllDelay]: delay for closing and re-establishing all connections (in milliseconds) [--retryFailed]: delay to retry failed connections (in milliseconds) [--output]: specify an output file (default to loadtest.log) Example: colyseus-loadtest example/bot.ts --endpoint ws://localhost:2567 --room state_handler`); process.exit(); } if (argv.help) { displayHelpAndExit(); } const options = { endpoint: argv.endpoint || `ws://localhost:2567`, roomName: argv.room, roomId: argv.roomId, numClients: argv.numClients || 1, scriptFile: argv._[0] && path.resolve(argv._[0]), delay: argv.delay || 0, logLevel: argv.logLevel?.toLowerCase() || "all", // TODO: not being used atm reestablishAllDelay: argv.reestablishAllDelay || 0, retryFailed: argv.retryFailed || 0, output: path.resolve(argv.output || "loadtest.log"), } if (!options.scriptFile) { console.error("❌ You must specify a script file."); console.error(""); displayHelpAndExit(); } const scriptModule = import(options.scriptFile); const connections: Room[] = []; if (!options.roomName && !options.roomId) { console.error("❌ You need to specify a room with either one of the '--room' or '--roomId' options."); console.error(""); displayHelpAndExit(); } if (options.output) { logWriter.create(options.output); logWriter.write(`@colyseus/loadtest\n${Object.keys(options) .filter(key => options[key]) .map((key) => `${key}: ${options[key]}`).join('\n')}`) } const screen = blessed.screen({ smartCSR: true }); const headerBox = blessed.box({ label: ` ⚔ ${packageJson.name} ${packageJson.version} ⚔ `, top: 0, left: 0, width: "70%", height: 'shrink', children: [ blessed.text({ top: 1, left: 1, tags: true, content: `{yellow-fg}endpoint:{/yellow-fg} ${options.endpoint}` }), blessed.text({ top: 2, left: 1, tags: true, content: `{yellow-fg}room:{/yellow-fg} ${options.roomName ?? options.roomId}` }), blessed.text({ top: 3, left: 1, tags: true, content: `{yellow-fg}serialization method:{/yellow-fg} ...` }), blessed.text({ top: 4, left: 1, tags: true, content: `{yellow-fg}time elapsed:{/yellow-fg} ...` }), ], border: { type: 'line' }, style: { label: { fg: 'cyan' }, border: { fg: 'green' } } }); const currentStats = { connected: 0, failed: 0, }; const totalStats = { connected: 0, failed: 0, errors: 0, }; const successfulConnectionBox = blessed.text({ top: 2, left: 1, tags: true, content: `{yellow-fg}connected:{/yellow-fg} ${currentStats.connected}` }); const failedConnectionBox = blessed.text({ top: 3, left: 1, tags: true, content: `{yellow-fg}failed:{/yellow-fg} ${currentStats.failed}` }); const clientsBox = blessed.box({ label: ' clients ', left: "70%", width: "30%", height: 'shrink', children: [ blessed.text({ top: 1, left: 1, tags: true, content: `{yellow-fg}numClients:{/yellow-fg} ${options.numClients}` }), successfulConnectionBox, failedConnectionBox ], border: { type: 'line' }, tags: true, style: { label: { fg: 'cyan' }, border: { fg: 'green' }, } }) const processingBox = blessed.box({ label: ' processing ', top: 6, left: "70%", width: "30%", height: 'shrink', border: { type: 'line' }, children: [ blessed.text({ top: 1, left: 1, tags: true, content: `{yellow-fg}memory:{/yellow-fg} ...` }), blessed.text({ top: 2, left: 1, tags: true, content: `{yellow-fg}cpu:{/yellow-fg} ...` }), // blessed.text({ top: 1, left: 1, content: `memory: ${process.memoryUsage().heapUsed} / ${process.memoryUsage().heapTotal}` }) ], tags: true, style: { label: { fg: 'cyan' }, border: { fg: 'green' }, } }); const networkingBox = blessed.box({ label: ' networking ', top: 11, left: "70%", width: "30%", border: { type: 'line' }, children: [ blessed.text({ top: 1, left: 1, tags: true, content: `{yellow-fg}bytes received:{/yellow-fg} ...` }), blessed.text({ top: 2, left: 1, tags: true, content: `{yellow-fg}bytes sent:{/yellow-fg} ...` }), // blessed.text({ top: 1, left: 1, content: `memory: ${process.memoryUsage().heapUsed} / ${process.memoryUsage().heapTotal}` }) ], tags: true, style: { label: { fg: 'cyan' }, border: { fg: 'green' }, } }); const logBox = blessed.box({ label: ' logs ', top: 7, width: "70%", padding: 1, border: { type: 'line' }, tags: true, style: { label: { fg: 'cyan' }, border: { fg: 'green' }, }, // scroll scrollable: true, input: true, alwaysScroll: true, scrollbar: { style: { bg: "green" }, track: { bg: "gray" } }, keys: true, vi: true, mouse: true }); screen.key(['escape', 'q', 'C-c'], (ch, key) => beforeExit("SIGINT")); // Quit on Escape, q, or Control-C. screen.title = "@colyseus/loadtest"; screen.append(headerBox); screen.append(clientsBox); screen.append(logBox); screen.append(processingBox); screen.append(networkingBox); screen.render(); const log = console.log; const warn = console.warn; const info = console.info; const error = console.error; console.log = function(...args) { logBox.content = args.map(arg => util.inspect(arg)).join(" ") + "\n" + logBox.content; screen.render(); }; console.warn = function(...args) { logBox.content = `{yellow-fg}${args.map(arg => util.inspect(arg)).join(" ")}{/yellow-fg}\n${logBox.content}`; screen.render(); }; console.info = function(...args) { logBox.content = `{blue-fg}${args.map(arg => util.inspect(arg)).join(" ")}{/blue-fg}\n${logBox.content}`; screen.render(); }; console.error = function(...args) { totalStats.errors++; logBox.content = `{red-fg}${args.map(arg => util.inspect(arg)).join(" ")}{/red-fg}\n${logBox.content}`; screen.render(); }; process.on("uncaughtException", (e) => { error(e); process.exit(); }); let isExiting = false; async function beforeExit(signal: NodeJS.Signals, closeCode: number = 0) { log("Writing log file..."); if (isExiting) { return; } else { isExiting = true; } const hasError = (closeCode > 0); await logWriter.write(`Finished. Summary: Successful connections: ${totalStats.connected} Failed connections: ${totalStats.failed} Total errors: ${totalStats.errors}`, true /* closing */) process.exit(hasError ? 1 : 0); } // trap process signals process.once('exit', (code) => beforeExit("SIGINT", code)); ['SIGINT', 'SIGTERM', 'SIGUSR2'].forEach((signal) => process.once(signal as NodeJS.Signals, (signal) => beforeExit(signal))); function formatBytes (bytes) { if (bytes < 1024) { return `${bytes} b`; } else if (bytes < Math.pow(1024, 2)) { return `${(bytes / 1024).toFixed(2)} kb`; } else if (bytes < Math.pow(1024, 4)) { return `${(bytes / 1024 / 1024).toFixed(2)} MB`; } } function elapsedTime(inputSeconds) { const days = Math.floor(inputSeconds / (60 * 60 * 24)); const hours = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60)); const minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60); const seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60); let ddhhmmss = ''; if (days > 0) { ddhhmmss += days + ' day '; } if (hours > 0) { ddhhmmss += hours + ' hour '; } if (minutes > 0) { ddhhmmss += minutes + ' minutes '; } if (seconds > 0) { ddhhmmss += seconds + ' seconds '; } return ddhhmmss || "..."; } /** * Update memory / cpu usage */ const loadTestStartTime = Date.now(); let startTime = process.hrtime() let startUsage = process.cpuUsage() let bytesReceived: number = 0; let bytesSent: number = 0; setInterval(() => { /** * Program elapsed time */ const elapsedTimeText = (headerBox.children[3] as blessed.Widgets.TextElement); elapsedTimeText.content = `{yellow-fg}time elapsed:{/yellow-fg} ${elapsedTime(Math.round((Date.now() - loadTestStartTime) / 1000))}`; /** * Memory / CPU Usage */ const memoryText = (processingBox.children[0] as blessed.Widgets.TextElement); memoryText.content = `{yellow-fg}memory:{/yellow-fg} ${(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)} MB`; var elapTime = process.hrtime(startTime) var elapUsage = process.cpuUsage(startUsage) var elapTimeMS = elapTime[0] * 1000 + elapTime[1] / 1000000; var elapUserMS = elapUsage.user / 1000; var elapSystMS = elapUsage.system / 1000; var cpuPercent = (100 * (elapUserMS + elapSystMS) / elapTimeMS).toFixed(1); const cpuText = (processingBox.children[1] as blessed.Widgets.TextElement); cpuText.content = `{yellow-fg}cpu:{/yellow-fg} ${cpuPercent}%`; screen.render(); startTime = process.hrtime() startUsage = process.cpuUsage() /** * Networking */ const bytesReceivedBox = (networkingBox.children[0] as blessed.Widgets.TextElement); bytesReceivedBox.content = `{yellow-fg}bytes received:{/yellow-fg} ${formatBytes(bytesReceived)}` const bytesSentBox = (networkingBox.children[1] as blessed.Widgets.TextElement); bytesSentBox.content = `{yellow-fg}bytes sent:{/yellow-fg} ${formatBytes(bytesSent)}` }, 1000); function handleError (message) { if (message) { console.error(message); logWriter.write(message); } currentStats.failed++; totalStats.failed++; failedConnectionBox.content = `{red-fg}failed:{/red-fg} ${currentStats.failed}`; screen.render(); } async function connect(scripting: any, i: number) { const tryReconnect = () => { if (options.retryFailed > 0) { setTimeout(() => connect(scripting, i), options.retryFailed); } }; const client = new Client(options.endpoint); const clientOptions = (typeof (scripting.requestJoinOptions) === "function") ? await scripting.requestJoinOptions.call(client, i) : {}; (options.roomName ? client.joinOrCreate(options.roomName, clientOptions) : client.joinById(options.roomId, clientOptions)).then(room => { connections.push(room); // display serialization method in the UI const serializerIdText = (headerBox.children[2] as blessed.Widgets.TextElement); serializerIdText.content = `{yellow-fg}serialization method:{/yellow-fg} ${room.serializerId}`; const ws: WebSocket = (room.connection.transport as any).ws; ws.addEventListener('message', (event) => { bytesReceived += new Uint8Array(event.data).length; }); // overwrite original send function to trap sent bytes. const _send = ws.send; ws.send = function (data: ArrayBuffer) { bytesSent += data.byteLength; _send.call(ws, data); } currentStats.connected++; totalStats.connected++; successfulConnectionBox.content = `{yellow-fg}connected:{/yellow-fg} ${currentStats.connected}`; screen.render(); room.onError.once(handleError); room.onLeave.once((code) => { currentStats.connected--; successfulConnectionBox.content = `{yellow-fg}connected:{/yellow-fg} ${currentStats.connected}`; screen.render(); if (code > 1000) { tryReconnect(); } }); if (scripting.onJoin) { scripting.onJoin.call(room); } if (scripting.onLeave) { room.onLeave(scripting.onLeave.bind(room)); } if (scripting.onError) { room.onError(scripting.onError.bind(room)); } if (scripting.onStateChange) { room.onStateChange(scripting.onStateChange.bind(room)); } }).catch((err) => { handleError(err); tryReconnect(); }); } async function connectAll(scripting: any) { for (let i = 0; i < options.numClients; i++) { connect(scripting, i); if (options.delay > 0) { await timer.setTimeout(options.delay); } } } async function reestablishAll(scripting: any) { // drop all connections, wait for acknowledgement connections.map((connection) => connection.connection.close()); // clear array connections.splice(0, connections.length); connections.length = 0; // connect again await connectAll(scripting); } try { (async () => { const scripting = await scriptModule; await connectAll(scripting); if (options.reestablishAllDelay > 0) { while (true) { // wait for delay await timer.setTimeout(options.reestablishAllDelay); await reestablishAll(scripting); } } })(); } catch(e) { error(e.stack); }
the_stack
import { Cookware, Ingredient, Recipe, Timer } from 'cooklang' import { TextFileView, setIcon, TFile, Keymap, WorkspaceLeaf, ViewStateResult, Notice } from 'obsidian' import { CookLangSettings } from './settings'; import { Howl } from 'howler'; import alarmMp3 from './alarm.mp3' import timerMp3 from './timer.mp3' // This is the custom view export class CookView extends TextFileView { settings: CookLangSettings; previewEl: HTMLElement; sourceEl: HTMLElement; editor: CodeMirror.Editor; recipe: Recipe; changeModeButton: HTMLElement; currentView: 'source' | 'preview'; alarmAudio:Howl timerAudio:Howl constructor(leaf: WorkspaceLeaf, settings: CookLangSettings) { super(leaf); this.settings = settings; this.alarmAudio = new Howl({ src: [alarmMp3], loop: false, preload: true }); this.timerAudio = new Howl({ src: [timerMp3], loop: true, preload: true }); // Add Preview Mode Container this.previewEl = this.contentEl.createDiv({ cls: 'cook-preview-view', attr: { 'style': 'display: none' } }); // Add Source Mode Container this.sourceEl = this.contentEl.createDiv({ cls: 'cook-source-view', attr: { 'style': 'display: block' } }); // Create CodeMirror Editor with specific config this.editor = CodeMirror.fromTextArea(this.sourceEl.createEl('textarea', { cls: 'cook-cm-editor' }), { lineNumbers: (this.app.vault as any).getConfig('showLineNumber'), lineWrapping: (this.app.vault as any).getConfig('lineWrap'), scrollbarStyle: null, keyMap: "default", theme: "obsidian" }); } onload() { // Save file on change this.editor.on('change', () => { this.requestSave(); }); // add the action to switch between source and preview mode this.changeModeButton = this.addAction('lines-of-text', 'Preview (Ctrl+Click to open in new pane)', (evt) => this.switchMode(evt), 17); // undocumented: Get the current default view mode to switch to let defaultViewMode = (this.app.vault as any).getConfig('defaultViewMode'); this.setState({ ...this.getState(), mode: defaultViewMode }, {}); } getState(): any { return super.getState(); } setState(state: any, result: ViewStateResult): Promise<void>{ // console.log(state); return super.setState(state, result).then(() => { if (state.mode) this.switchMode(state.mode); }); } // function to switch between source and preview mode switchMode(arg: 'source' | 'preview' | MouseEvent) { let mode = arg; // if force mode not provided, switch to opposite of current mode if (!mode || mode instanceof MouseEvent) mode = this.currentView === 'source' ? 'preview' : 'source'; if (arg instanceof MouseEvent) { if (Keymap.isModEvent(arg)) { this.app.workspace.duplicateLeaf(this.leaf).then(() => { const viewState = this.app.workspace.activeLeaf?.getViewState(); if (viewState) { viewState.state = { ...viewState.state, mode: mode }; this.app.workspace.activeLeaf?.setViewState(viewState); } }); } else { this.setState({ ...this.getState(), mode: mode }, {}); } } else { // switch to preview mode if (mode === 'preview') { this.currentView = 'preview'; setIcon(this.changeModeButton, 'pencil'); this.changeModeButton.setAttribute('aria-label', 'Edit (Ctrl+Click to edit in new pane)'); this.renderPreview(this.recipe); this.previewEl.style.setProperty('display', 'block'); this.sourceEl.style.setProperty('display', 'none'); } // switch to source mode else { this.currentView = 'source'; setIcon(this.changeModeButton, 'lines-of-text'); this.changeModeButton.setAttribute('aria-label', 'Preview (Ctrl+Click to open in new pane)'); this.previewEl.style.setProperty('display', 'none'); this.sourceEl.style.setProperty('display', 'block'); this.editor.refresh(); } } } // get the data for save getViewData() { this.data = this.editor.getValue(); // may as well parse the recipe while we're here. this.recipe = new Recipe(this.data); return this.data; } // load the data into the view async setViewData(data: string, clear: boolean) { this.data = data; if (clear) { this.editor.swapDoc(CodeMirror.Doc(data, "text/x-cook")) this.editor.clearHistory(); } this.editor.setValue(data); this.recipe = new Recipe(data); // if we're in preview view, also render that if (this.currentView === 'preview') this.renderPreview(this.recipe); } // clear the editor, etc clear() { this.previewEl.empty(); this.editor.setValue(''); this.editor.clearHistory(); this.recipe = new Recipe(); this.data = null; } getDisplayText() { if (this.file) return this.file.basename; else return "Cooklang (no file)"; } canAcceptExtension(extension: string) { return extension == 'cook'; } getViewType() { return "cook"; } // when the view is resized, refresh CodeMirror (thanks Licat!) onResize() { this.editor.refresh(); } // icon for the view getIcon() { return "document-cook"; } // render the preview view renderPreview(recipe: Recipe) { // clear the preview before adding the rest this.previewEl.empty(); // we can't render what we don't have... if (!recipe) return; if(this.settings.showImages) { // add any files following the cooklang conventions to the recipe object // https://org/docs/spec/#adding-pictures const otherFiles: TFile[] = this.file.parent.children.filter(f => (f instanceof TFile) && (f.basename == this.file.basename || f.basename.startsWith(this.file.basename + '.')) && f.name != this.file.name) as TFile[]; otherFiles.forEach(f => { // convention specifies JPEGs and PNGs. Added GIFs as well. Why not? if (f.extension == "jpg" || f.extension == "jpeg" || f.extension == "png" || f.extension == "gif") { // main recipe image if (f.basename == this.file.basename) recipe.image = f; else { const split = f.basename.split('.'); // individual step images let s:number; if (split.length == 2 && (s = parseInt(split[1])) >= 0 && s < recipe.steps.length) { recipe.steps[s].image = f; } } } }) // if there is a main image, put it as a banner image at the top if (recipe.image) { const img = this.previewEl.createEl('img', { cls: 'main-image' }); img.src = this.app.vault.getResourcePath(recipe.image); } } if(this.settings.showIngredientList) { // Add the Ingredients header this.previewEl.createEl('h2', { cls: 'ingredients-header', text: 'Ingredients' }); // Add the ingredients list const ul = this.previewEl.createEl('ul', { cls: 'ingredients' }); recipe.ingredients.forEach(ingredient => { const li = ul.createEl('li'); if (ingredient.amount !== null) { li.createEl('span', { cls: 'amount', text: ingredient.amount}); li.appendText(' '); } if (ingredient.units !== null) { li.createEl('span', { cls: 'unit', text: ingredient.units}); li.appendText(' '); } li.appendText(ingredient.name); }) } if(this.settings.showCookwareList) { // Add the Cookware header this.previewEl.createEl('h2', { cls: 'cookware-header', text: 'Cookware' }); // Add the Cookware list const ul = this.previewEl.createEl('ul', { cls: 'cookware' }); recipe.cookware.forEach(item => { ul.createEl('li', { text: item.name }); }) } if (this.settings.showTimersList) { // Add the Cookware header this.previewEl.createEl('h2', { cls: 'timers-header', text: 'Timers' }); // Add the Cookware list const ul = this.previewEl.createEl('ul', { cls: 'timers' }); recipe.timers.forEach(item => { const li = ul.createEl('li'); const a = li.createEl('a', { cls: 'timer', attr: { 'data-timer': item.seconds } }) if (item.name) { a.createEl('span', { cls: 'timer-name', text: item.name }) a.appendText(' '); } a.appendText('(') if (item.amount !== null) { a.createEl('span', { cls: 'amount', text: item.amount }); a.appendText(' '); } if (item.units !== null) { a.createEl('span', { cls: 'unit', text: item.units }); } a.appendText(')') a.addEventListener('click', (ev) => { //@ts-ignore const timerSeconds: number = parseFloat(a.dataset.timer) this.makeTimer(a, timerSeconds, item.name); }) }) } if(this.settings.showTotalTime) { let time = recipe.calculateTotalTime(); if(time > 0) { // Add the Timers header this.previewEl.createEl('h2', { cls: 'time-header', text: 'Total Time' }); this.previewEl.createEl('p', { cls: 'time', text: this.formatTime(time) }); } } // add the method header this.previewEl.createEl('h2', { cls: 'method-header', text: 'Method' }); // add the method list const mol = this.previewEl.createEl('ol', { cls: 'method' }); recipe.steps.forEach(step => { const mli = mol.createEl('li'); const mp = mli.createEl('p'); step.line.forEach(s => { if (typeof s === "string") mp.append(s); else if (s instanceof Ingredient) { const ispan = mp.createSpan({ cls: 'ingredient' }); if (this.settings.showQuantitiesInline) { if (s.amount) { ispan.createSpan({ cls: 'amount', text: s.amount }); ispan.appendText(' '); } if (s.units) { ispan.createSpan({ cls: 'unit', text: s.units }); ispan.appendText(' '); } } ispan.appendText(s.name) } else if (s instanceof Cookware) { mp.createSpan({ cls: 'ingredient', text: s.name }); } else if (s instanceof Timer) { const containerSpan = mp.createSpan() const tspan = containerSpan.createSpan({ cls: 'timer', attr: { 'data-timer': s.seconds } }); tspan.createSpan({ cls: 'time-amount', text: s.amount }); tspan.appendText(' '); tspan.createSpan({ cls: 'time-unit', text: s.units }); if (this.settings.showTimersInline) { tspan.addEventListener('click', (ev) => { //@ts-ignore const timerSeconds: number = parseFloat(tspan.dataset.timer) this.makeTimer(tspan, timerSeconds, s.name); }) } } }); if (this.settings.showImages && step.image) { const img = mli.createEl('img', { cls: 'method-image' }); img.src = this.app.vault.getResourcePath(step.image); } }); } makeTimer(el: Element, seconds: number, name: string) { if (el.nextElementSibling && el.nextElementSibling.hasClass('countdown')) { // this timer already exists. Play/pause it? (el.nextElementSibling.querySelector('button:first-child') as HTMLElement).click() return; } const timerAudioId = this.settings.timersTick ? this.timerAudio?.play() : null; const timerContainerEl = el.createSpan({cls:'countdown'}) if (el.nextSibling) el.parentElement.insertBefore(el.nextSibling, timerContainerEl) else el.parentElement.appendChild(timerContainerEl) const pauseEl = timerContainerEl.createEl('button', { text: 'pause', cls: 'pause-button' }) const stopEl = timerContainerEl.createEl('button', { text: 'stop', cls: 'stop-button' }) const timerEl = timerContainerEl.createSpan({ text: this.formatTimeForTimer(seconds), attr: { 'data-percent': 100 } }); let end = new Date(new Date().getTime() + (seconds * 1000)) let interval: NodeJS.Timeout let stop: Function = () => { if (this.settings.timersTick) this.timerAudio?.stop(timerAudioId); clearInterval(interval) timerContainerEl.remove() } interval = setInterval(this.updateTimer.bind(this), 500, timerEl, seconds, end, stop, name) let paused = false; let remaining:number = null; pauseEl.addEventListener('click', (ev) => { if (paused) { end = new Date(new Date().getTime() + remaining) this.updateTimer(timerEl, seconds, end, stop, name) interval = setInterval(this.updateTimer.bind(this), 500, timerEl, seconds, end, stop, name) if (this.settings.timersTick) this.timerAudio?.play(timerAudioId) pauseEl.setText('pause') pauseEl.className = 'pause-button' paused = false } else { clearInterval(interval); remaining = end.getTime() - new Date().getTime() if (this.settings.timersTick) this.timerAudio?.pause(timerAudioId) pauseEl.setText('resume') pauseEl.className = 'resume-button' paused = true; } }) stopEl.addEventListener('click', () => stop()) } updateTimer(el: Element, totalSeconds:number, end: Date, stop: Function, name: string) { const now = new Date() const time = (end.getTime() - now.getTime()) / 1000 if (time <= 0) { new Notice(name ? `${name} timer has finished!` : `Timer has finished!`); if (this.settings.timersRing) this.alarmAudio?.play() stop() } el.setText(this.formatTimeForTimer(time)) el.setAttr('data-percent', Math.floor((time / totalSeconds) * 100)) } formatTime(time: number, showSeconds:boolean = false) { let seconds = Math.floor(time % 60); let minutes = Math.floor(time / 60); let hours = Math.floor(minutes / 60); minutes = minutes % 60; let result = ""; if (hours > 0) result += hours + " hours "; if (minutes > 0) result += minutes + " minutes "; if (showSeconds && seconds > 0) result += seconds + " seconds "; return result; } formatTimeForTimer(time: number) { let seconds = Math.floor(time % 60); let minutes = Math.floor(time / 60); let hours = Math.floor(minutes / 60); minutes = minutes % 60; let result = ""; if (hours > 0) result += hours; if (hours > 0 && minutes >= 0) result += ":"; if (hours > 0 && minutes >= 0 && minutes < 10) result += "0"; if (minutes > 0) result += minutes; if (minutes > 0) result += ":"; if (minutes > 0 && seconds >= 0 && seconds < 10) result += "0"; if ( seconds >= 0) result += seconds; return result; } }
the_stack
import * as React from "react" import * as ReactDOM from "react-dom" import { observable, action, reaction, runInAction, IReactionDisposer, } from "mobx" import { observer } from "mobx-react" import { HeaderSearch } from "./HeaderSearch" import classnames from "classnames" import { flatten } from "../clientUtils/Util" import { bind } from "decko" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import { faSearch } from "@fortawesome/free-solid-svg-icons/faSearch" import { faBars } from "@fortawesome/free-solid-svg-icons/faBars" import { faExternalLinkAlt } from "@fortawesome/free-solid-svg-icons/faExternalLinkAlt" import { faAngleDown } from "@fortawesome/free-solid-svg-icons/faAngleDown" import { faAngleUp } from "@fortawesome/free-solid-svg-icons/faAngleUp" import { faEnvelopeOpenText } from "@fortawesome/free-solid-svg-icons/faEnvelopeOpenText" import { AmazonMenu } from "./AmazonMenu" import { NewsletterSubscriptionForm, NewsletterSubscriptionContext, } from "./NewsletterSubscription" import { CategoryWithEntries, EntryMeta } from "../clientUtils/owidTypes" import { SiteAnalytics } from "./SiteAnalytics" import { ENV } from "../settings/clientSettings" const analytics = new SiteAnalytics(ENV) @observer class Header extends React.Component<{ categories: CategoryWithEntries[] baseUrl: string }> { @observable.ref dropdownIsOpen = false dropdownOpenTimeoutId?: number // ID of the timeout that will set isOpen to true dropdownCloseTimeoutId?: number // ID of the timeout that will set isOpen to false dropdownLastOpened?: number // Timestamp of the last time isOpen was set to true // Mobile menu toggles @observable showSearch = false @observable showCategories = false @observable showNewsletterSubscription = false dispose!: IReactionDisposer componentDidMount() { this.dispose = reaction( () => this.dropdownIsOpen, () => { if (this.dropdownIsOpen) this.dropdownLastOpened = Date.now() } ) } componentWillUnmount() { this.dispose() } @action.bound onToggleSearch() { this.showSearch = !this.showSearch } @action.bound onToggleCategories() { this.showCategories = !this.showCategories } @action.bound onToggleNewsletterSubscription() { this.showNewsletterSubscription = !this.showNewsletterSubscription } @action.bound setOpen(open: boolean) { this.dropdownIsOpen = open this.clearOpenTimeout() this.clearCloseTimeout() } @action.bound scheduleOpenTimeout(delay: number) { this.dropdownOpenTimeoutId = window.setTimeout(() => { this.setOpen(true) analytics.logSiteClick("header-open-menu", "Articles by topic") }, delay) this.clearCloseTimeout() } @action.bound scheduleCloseTimeout(delay: number) { this.dropdownCloseTimeoutId = window.setTimeout( () => this.setOpen(false), delay ) this.clearOpenTimeout() } @action.bound clearOpenTimeout() { if (this.dropdownOpenTimeoutId) { clearTimeout(this.dropdownOpenTimeoutId) this.dropdownOpenTimeoutId = undefined } } @action.bound clearCloseTimeout() { if (this.dropdownCloseTimeoutId) { clearTimeout(this.dropdownCloseTimeoutId) this.dropdownCloseTimeoutId = undefined } } @action.bound onDropdownButtonClick( event: React.MouseEvent<HTMLAnchorElement> ) { event.preventDefault() // Only close the menu if it's been open for a while, to avoid accidentally closing it while it's appearing. if ( this.dropdownIsOpen && this.dropdownLastOpened !== undefined && this.dropdownLastOpened + 500 < Date.now() ) { this.setOpen(false) } else { this.setOpen(true) } } render() { const { categories, baseUrl } = this.props return ( <> <div className="wrapper site-navigation-bar"> <div className="site-logo"> <a href="/" data-track-note="header-navigation"> Our World <br /> in Data </a> </div> <nav className="site-navigation"> <div className="topics-button-wrapper"> <a href="/#entries" className={classnames("topics-button", { active: this.dropdownIsOpen, })} onMouseEnter={() => this.scheduleOpenTimeout(200) } onMouseLeave={() => this.scheduleCloseTimeout(100) } onClick={this.onDropdownButtonClick} > <div className="label"> Articles <br /> <strong>by topic</strong> </div> <div className="icon"> <svg width="12" height="6"> <path d="M0,0 L12,0 L6,6 Z" fill="currentColor" /> </svg> </div> </a> <DesktopTopicsMenu categories={categories} isOpen={this.dropdownIsOpen} onMouseEnter={() => this.setOpen(true)} onMouseLeave={() => this.scheduleCloseTimeout(350) } /> </div> <div> <div className="site-primary-navigation"> <HeaderSearch /> <ul className="site-primary-links"> <li> <a href="/blog" data-track-note="header-navigation" > Latest </a> </li> <li> <a href="/about" data-track-note="header-navigation" > About </a> </li> <li> <a href="/donate" data-track-note="header-navigation" > Donate </a> </li> </ul> </div> <div className="site-secondary-navigation"> <ul className="site-secondary-links"> <li> <a href="/charts" data-track-note="header-navigation" > All charts </a> </li> {/* <li><a href="/teaching" data-track-note="header-navigation">Teaching Hub</a></li> */} <li> <a href="https://sdg-tracker.org" data-track-note="header-navigation" > Sustainable Development Goals Tracker </a> </li> </ul> </div> </div> </nav> <div className="header-logos-wrapper"> <a href="https://www.oxfordmartin.ox.ac.uk/global-development" className="oxford-logo" > <img src={`${baseUrl}/oms-logo.svg`} alt="Oxford Martin School logo" /> </a> <a href="https://global-change-data-lab.org/" className="gcdl-logo" > <img src={`${baseUrl}/gcdl-logo.svg`} alt="Global Change Data Lab logo" /> </a> </div> <div className="mobile-site-navigation"> <button onClick={this.onToggleSearch} data-track-note="mobile-search-button" > <FontAwesomeIcon icon={faSearch} /> </button> <button onClick={this.onToggleNewsletterSubscription} data-track-note="mobile-newsletter-button" > <FontAwesomeIcon icon={faEnvelopeOpenText} /> </button> <button onClick={this.onToggleCategories} data-track-note="mobile-hamburger-button" > <FontAwesomeIcon icon={faBars} /> </button> </div> </div> {this.showSearch && ( <div className="search-dropdown sm-only"> <form id="search-nav" action="/search" method="GET"> <input type="search" name="q" placeholder="Search..." autoFocus /> </form> </div> )} {this.showNewsletterSubscription && ( <div className="newsletter-subscription"> <div className="box"> <NewsletterSubscriptionForm context={ NewsletterSubscriptionContext.MobileMenu } /> </div> </div> )} {this.showCategories && ( <MobileTopicsMenu categories={this.props.categories} /> )} </> ) } } const renderEntry = (entry: EntryMeta): JSX.Element => { return ( <li key={entry.slug}> <a href={`/${entry.slug}`} className="item" data-track-note="header-navigation" > <span className="label">{entry.title}</span> </a> </li> ) } const allEntries = (category: CategoryWithEntries): EntryMeta[] => { // combine "direct" entries and those from subcategories return [ ...category.entries, ...flatten( category.subcategories.map((subcategory) => subcategory.entries) ), ] } @observer class DesktopTopicsMenu extends React.Component<{ categories: CategoryWithEntries[] isOpen: boolean onMouseEnter: (ev: React.MouseEvent<HTMLDivElement>) => void onMouseLeave: (ev: React.MouseEvent<HTMLDivElement>) => void }> { @observable.ref private activeCategory?: CategoryWithEntries private submenuRef: React.RefObject<HTMLUListElement> = React.createRef() @action.bound private setCategory(category?: CategoryWithEntries) { this.activeCategory = category } @bind private onActivate(categorySlug: string) { if (!categorySlug) return const category = this.props.categories.find( (cat) => cat.slug === categorySlug ) if (category) this.setCategory(category) } @bind private onDeactivate(categorySlug: string) { if (!categorySlug) return const category = this.props.categories.find( (cat) => cat.slug === categorySlug ) if (category === this.activeCategory) this.setCategory(undefined) } render() { const { activeCategory } = this const { categories, isOpen, onMouseEnter, onMouseLeave } = this.props let sizeClass = "" if (activeCategory) { sizeClass = // Count root and subcategories entries activeCategory.subcategories.reduce( (acc: number, subcategory) => subcategory.entries.length + acc, activeCategory.entries.length ) > 10 ? "two-column" : "one-column" } return ( <div className={classnames("topics-dropdown", sizeClass, { open: isOpen, })} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} aria-hidden={isOpen} > <div className="menu"> <AmazonMenu onActivate={this.onActivate} onDeactivate={this.onDeactivate} submenuRect={ this.submenuRef.current && this.submenuRef.current.getBoundingClientRect() } > <ul> {categories.map((category) => ( <li key={category.slug} className={ category === activeCategory ? "active item" : "item" } data-submenu-id={category.slug} > <span className="label"> {category.name} </span> <span className="icon"> <svg width="5" height="10"> <path d="M0,0 L5,5 L0,10 Z" fill="currentColor" /> </svg> </span> </li> ))} <hr /> <a href="http://sdg-tracker.org" className="item" data-submenu-id data-track-note="header-navigation" > <span className="label"> Sustainable Development Goals Tracker </span> <span className="icon"> <FontAwesomeIcon icon={faExternalLinkAlt} /> </span> </a> {/* An extra "Index" menu item, for when we have the Index page. */} {/* <a href="/index" className="item" data-track-note="header-navigation"> <span className="label">Index of all topics</span> <span className="icon"> <FontAwesomeIcon icon={faExternalLinkAlt} /> </span> </a> */} </ul> </AmazonMenu> </div> <ul className="submenu" ref={this.submenuRef}> {activeCategory && allEntries(activeCategory).map((entry) => renderEntry(entry) )} </ul> </div> ) } } @observer class MobileTopicsMenu extends React.Component<{ categories: CategoryWithEntries[] }> { @observable.ref private activeCategory?: CategoryWithEntries @action.bound private toggleCategory(category: CategoryWithEntries) { if (this.activeCategory === category) this.activeCategory = undefined else this.activeCategory = category } render() { const { categories } = this.props const { activeCategory } = this return ( <div className="mobile-topics-dropdown sm-only"> <ul> <li className="header"> <h2>Topics</h2> </li> {categories.map((category) => ( <li key={category.slug} className={`category ${ activeCategory === category ? "expanded" : "" }`} > <a onClick={() => this.toggleCategory(category)}> <span className="label-wrapper"> <span className="label"> {category.name} </span> <span className="entries-muted"> {allEntries(category) .map((entry) => entry.title) .join(", ")} </span> </span> <span className="icon"> <FontAwesomeIcon icon={ activeCategory === category ? faAngleUp : faAngleDown } /> </span> </a> {activeCategory === category && ( <div className="subcategory-menu"> <ul> {allEntries(category).map((entry) => renderEntry(entry) )} </ul> </div> )} </li> ))} <li className="end-link"> <a href="/charts" data-track-note="header-navigation"> Charts </a> </li> <li className="end-link"> <a href="/teaching" data-track-note="header-navigation"> Teaching Hub </a> </li> <li className="end-link"> <a href="https://sdg-tracker.org" data-track-note="header-navigation" > Sustainable Development Goals Tracker </a> </li> <li className="end-link"> <a href="/blog" data-track-note="header-navigation"> Latest </a> </li> <li className="end-link"> <a href="/about" data-track-note="header-navigation"> About </a> </li> <li className="end-link"> <a href="/donate" data-track-note="header-navigation"> Donate </a> </li> </ul> </div> ) } } @observer class SiteHeaderMenus extends React.Component<{ baseUrl: string }> { @observable private width!: number @observable.ref private categories: CategoryWithEntries[] = [] @action.bound private onResize() { this.width = window.innerWidth } private async getEntries() { const json = await ( await fetch("/headerMenu.json", { method: "GET", credentials: "same-origin", headers: { Accept: "application/json", }, }) ).json() runInAction(() => (this.categories = json.categories)) } componentDidMount() { this.getEntries() this.onResize() window.addEventListener("resize", this.onResize) } componentWillUnmount() { window.removeEventListener("resize", this.onResize) } render() { return ( <Header categories={this.categories} baseUrl={this.props.baseUrl} /> ) } } export const runHeaderMenus = (baseUrl: string) => ReactDOM.render( <SiteHeaderMenus baseUrl={baseUrl} />, document.querySelector(".site-header") )
the_stack
import * as npath from 'path' import errorLogTraverse from '../util/ErrorLogTraverse' import * as t from '@babel/types' import {isStaticRes} from '../util/util' import {geneOrder} from '../util/util' import configure from '../configure' import {setEntryModuleInfo} from '../util/cacheModuleInfos' import * as fse from "fs-extra"; import * as path from "path"; export default function (ast, filepath, webpackContext) { const appJSON: any = { pages: [ ], window: { "backgroundTextStyle":"light", 'backgroundColor': '#E9E9E9', 'enablePullDownRefresh': false, }, } const moduleMap = {} const pngMap = {} const pageInfos = [] const tabInfos = [] const go = geneOrder('_') errorLogTraverse(ast, { enter: path => { if (path.type === 'StringLiteral' && isStaticRes((path.node as t.StringLiteral).value) ) { const pp = path.parentPath if (pp.type === 'VariableDeclarator') { // @ts-ignore pngMap[pp.node.id.name] = path.node.value pp.parentPath.remove() } return } if (path.type === 'ImportDeclaration') { const pnode = path.node as t.ImportDeclaration const source = pnode.source.value const rs = getRealSource(source, filepath) const originPath = getOriginPath(rs, filepath) const specifiers = pnode.specifiers specifiers.forEach(spe => { const name = spe.local.name moduleMap[name] = { originPath, // @ts-ignore attri: spe.imported ? spe.imported.name: 'default', source: source, }//originPath }) return } // require 目录 小程序不支持需要处理 // @ts-ignore if (path.type === 'CallExpression' && path.node.callee.type === 'Identifier' && path.node.callee.name === 'require' ) { // @ts-ignore const source = path.node.arguments[0].value const rs = getRealSource(source, filepath) const originPath = getOriginPath(rs, filepath) // @ts-ignore const id = path.parentPath.node.id if (id.type === 'Identifier') { moduleMap[id.name] = { originPath, attri: '', source: source, } } else if (id.type === 'ObjectPattern') { id.properties.map(pro => { if (pro.type === 'ObjectProperty') { moduleMap[pro.value.name] = { originPath, attri: pro.key.name, source: source, } } }) } return } }, exit: path => { if ( path.type === 'JSXAttribute' // @ts-ignore && (path.node.name.name === 'image' || path.node.name.name === 'selectedImage') // @ts-ignore && path.parentPath.node.name.name === 'TabRouter' ) { // @ts-ignore const v = path.node.value if (v.type === 'JSXExpressionContainer') { const picName = v.expression.name // @ts-ignore path.node.value = t.stringLiteral(pngMap[picName]) } return } // @ts-ignore if (path.type === 'JSXOpeningElement' && path.node.name.name === 'Route') { let compAttri = null let key = null let subpage = null const pnode = path.node as t.JSXOpeningElement pnode.attributes.forEach(ele => { ele = ele as t.JSXAttribute if (ele.name.name === 'component') { compAttri = ele } if (ele.name.name === 'key') { if (ele.value.type === 'JSXExpressionContainer' && ele.value.expression.type === 'StringLiteral') { key = ele.value.expression.value } if (ele.value.type === 'StringLiteral') { key = ele.value.value } } if (ele.name.name === 'subpage') { if (ele.value.type === 'JSXExpressionContainer' && ele.value.expression.type === 'StringLiteral') { subpage = ele.value.expression.value } if (ele.value.type === 'StringLiteral') { subpage = ele.value.value } } }) const name = compAttri.value.expression.name pageInfos.push({ comp: name, subpage: subpage, key: key, }) pnode.attributes.push(t.jsxAttribute(t.jsxIdentifier('diuu'), t.stringLiteral(go.next))) if (subpage) { // 分包的依赖将会被处理为异步加载,固这里需要处理其引用,以免报错 path.node.name.name = 'view' path.parentPath.node.closingElement && (path.parentPath.node.closingElement.name.name = 'view') // @ts-ignore pnode.attributes = pnode.attributes.filter(attri => attri.name.name !== 'component') } return } // @ts-ignore if (path.type === 'JSXOpeningElement' && path.node.name.name === 'TabRouter') { const pp = path.parentPath // @ts-ignore const children = pp.node.children let initKey = null for(let i = 0; i< children.length; i++) { const child = children[i] if (child.type === 'JSXElement' && child.openingElement.name.name === 'Route') { const oe = child.openingElement const keyAttr = oe.attributes.filter(ele => ele.name.name === 'key')[0] if (keyAttr.value.type === 'JSXExpressionContainer' && keyAttr.value.expression.type === 'StringLiteral') { initKey = keyAttr.value.expression.value } if (keyAttr.value.type === 'StringLiteral') { initKey = keyAttr.value.value } break } } const tabBarElement: any = { initKey: initKey, } const pnode = path.node as t.JSXOpeningElement pnode.attributes.forEach(attri => { attri = attri as t.JSXAttribute const v = (attri.value as t.StringLiteral).value if (attri.name.name === 'text') { tabBarElement.text = v } if (attri.name.name === 'image') { tabBarElement.iconPath = v } if (attri.name.name === 'selectedImage') { tabBarElement.selectedIconPath = v } }) tabInfos.push(tabBarElement) pnode.attributes.push(t.jsxAttribute(t.jsxIdentifier('diuu'), t.stringLiteral(go.next))) return } if (path.type === 'JSXOpeningElement') { const jsxOp = path.node as t.JSXOpeningElement const key = go.next jsxOp.attributes.push( t.jsxAttribute(t.jsxIdentifier('diuu'), t.stringLiteral(key)) ) return } if (path.type === 'JSXAttribute' && (path.node as t.JSXAttribute).name.name === 'wxNavigationOptions' ) { const value = (path.node as t.JSXAttribute).value if (value.type === 'JSXExpressionContainer' && value.expression.type === 'ObjectExpression' ) { const v = value.expression const props = v.properties for(let i = 0; i < props.length; i++) { const p = props[i] as t.ObjectProperty const k = p.key.name const v = (p.value as t.StringLiteral).value appJSON.window[k] = v } } return } } }) const tabBarList = getTabbarList(tabInfos, pageInfos, moduleMap) if (tabBarList.length > 0) { appJSON.tabBar = { list: tabBarList, } } const { historyMap, pageCompPaths, pagePaths, pages, subpackages, removeModules, ensureStatements, allChunks } = miscPageInfos(pageInfos, moduleMap) configure.allChunks = allChunks appJSON.pages = pages if (subpackages.length > 0) { appJSON.subpackages = subpackages } errorLogTraverse(ast, { exit: path => { if (path.type === 'ExportDefaultDeclaration') { // @ts-ignore if (path.node.declaration.type === 'ClassDeclaration') { // TODO 可能存在其他情况吗 // @ts-ignore path.node.declaration.type = 'ClassExpression' } path.replaceWith( t.variableDeclaration('const', [ // @ts-ignore t.variableDeclarator(t.identifier('RNAppClass'), path.node.declaration) ]) ) } if (path.type === 'ImportDeclaration') { const pnode = path.node as t.ImportDeclaration const source = pnode.source.value if (removeModules.has(source)) { path.remove() } return } if (path.type === 'CallExpression' && path.node.callee.type === 'Identifier' && path.node.callee.name === 'require' ) { // @ts-ignore const source = path.node.arguments[0].value if (removeModules.has(source)) { path.parentPath.parentPath.remove() } return } // module.exports = A => const RNAppClass = A if (path.type === 'AssignmentExpression' // @ts-ignore && path.node.operator === '=' // @ts-ignore && path.node.left.type === 'MemberExpression' // @ts-ignore && path.node.left.object.name === 'module' // @ts-ignore && path.node.left.property.name === 'exports' ) { path.parentPath.replaceWith( t.variableDeclaration('const', [ // @ts-ignore t.variableDeclarator(t.identifier('RNAppClass'), path.node.right) ]) ) } if (path.type === 'Program') { /* 导出 RNApp 实例 * const RNApp = new RNAppClass() * RNApp.childContext = RNApp.getChildContext ? RNApp.getChildContext() : {} * export default RNApp */ const pnode = path.node as t.Program // be lazy pnode.body.push( t.expressionStatement( t.identifier(`React.renderApp(RNAppClass)`) ) ) /** * 初始化路由 */ // be lazy pnode.body.push( t.expressionStatement( t.identifier(`wx._historyConfig = ${JSON.stringify(historyMap, null)}`) ) ) // be lazy pnode.body.push(t.expressionStatement(t.assignmentExpression( '=', t.identifier('wx._pageCompMaps'), t.objectExpression(pageCompPaths) ))) pnode.body.push( t.expressionStatement( t.identifier(`wx._getCompByPath = function(path) { return new Promise((resolve) =>{ if (wx._pageCompMaps[path]) { resolve(wx._pageCompMaps[path]) } else { wx._pageCompMaps[path] = resolve } }) }`) ) ) ensureStatements.forEach(state => { pnode.body.push(state) }) } } }) setEntryModuleInfo(filepath, { appJSON, }) return { entryAst: ast, allCompSet: new Set(pagePaths) } } function getOriginPath(source, filepath) { const originPath = npath .resolve(npath.dirname(filepath), source) .replace(configure.inputFullpath + npath.sep, '') .replace(/\\/g, '/') // 考虑win平台 return originPath } function getRealSource(source, filepath) { if (npath.extname(source) !== '') { return source } // 小程序不支持require/import 一个目录 if (source.startsWith('/') || source.startsWith('./') || source.startsWith('../') ) { return getFinalSource(filepath, source) } else { return source } } /** * 获取 最终的导入路径,如果导入的是目录,需要补全index * @param filepath * @param source */ export function getFinalSource(filepath, source) { const originalPath = path .resolve(path.dirname(filepath), source) if (fse.existsSync(originalPath)) { return `${source}/index` } return source } function getTabbarList(tabInfos, pageInfos, moduleMap) { const tabBarList = [] for (let i = 0; i < tabInfos.length; i++) { const tabInfo = tabInfos[i] const initKey = tabInfo.initKey const initCompInfo = pageInfos.filter(info => info.key === initKey)[0] // tab页必需在主包 initCompInfo.subpage = null const projectRelativePath = moduleMap[initCompInfo.comp].originPath tabBarList.push({ pagePath: projectRelativePath, text: tabInfo.text, iconPath: tabInfo.iconPath, selectedIconPath: tabInfo.selectedIconPath }) } return tabBarList } function miscPageInfos(pageInfos, moduleMap) { const pages = [] const subpages = {} const pagePaths = [] const historyMap = {} const pageCompPaths = [] const allChunks = ['_rn_'] const removeModules = new Set() for (let i = 0; i < pageInfos.length; i++) { const info = pageInfos[i] const {comp, subpage, key} = info const projectRelativePath = moduleMap[comp].originPath pagePaths.push(projectRelativePath) if (!subpage) { pages.push(projectRelativePath) historyMap[key] = `/${projectRelativePath}` pageCompPaths.push(t.objectProperty( t.stringLiteral(projectRelativePath), t.identifier(comp) )) } else { if (!subpages[subpage]) { subpages[subpage] = [] } subpages[subpage].push(comp) removeModules.add(moduleMap[comp].source) historyMap[key] = `/${subpage}/${projectRelativePath}` } } const ensureStatements = [] const subpackages = [] const allSubPages = Object.keys(subpages) for(let i = 0; i < allSubPages.length; i ++ ) { const subpage = allSubPages[i] allChunks.push(`${subpage}/_rn_`) const allComps = subpages[subpage] const depsStr = allComps.map(comp => `"${moduleMap[comp].source}"`) .join(',') let requireStr = allComps.map(comp => { const {source, attri} = moduleMap[comp] return `var ${comp} = require("${source}")${attri ? `.${attri}`: ''}` }).join(';') const pageCompResolve = allComps.map(comp => { return ` compOrResolve = wx._pageCompMaps["${moduleMap[comp].originPath}"]; if (typeof compOrResolve === "function") { compOrResolve(${comp}); }; wx._pageCompMaps["${moduleMap[comp].originPath}"] = ${comp}; ` }).join(';') let callbackStr = `(require) => {${requireStr}; var compOrResolve; ${pageCompResolve}}` let chunkName = `"${subpage}/_rn_"` const ensureStatement = t.expressionStatement(t.identifier(`require.ensure([${depsStr}], ${callbackStr}, ${chunkName});`)) ensureStatements.push(ensureStatement) subpackages.push({ root: subpage, name: subpage, pages: allComps.map(comp => moduleMap[comp].originPath) }) } return { pages, subpackages, ensureStatements, removeModules, pagePaths, historyMap, pageCompPaths, allChunks, } }
the_stack
namespace ts.projectSystem { describe("unittests:: tsserver:: Semantic operations on partialSemanticServer", () => { function setup() { const file1: File = { path: `${tscWatch.projectRoot}/a.ts`, content: `import { y, cc } from "./b"; import { something } from "something"; class c { prop = "hello"; foo() { return this.prop; } }` }; const file2: File = { path: `${tscWatch.projectRoot}/b.ts`, content: `export { cc } from "./c"; import { something } from "something"; export const y = 10;` }; const file3: File = { path: `${tscWatch.projectRoot}/c.ts`, content: `export const cc = 10;` }; const something: File = { path: `${tscWatch.projectRoot}/node_modules/something/index.d.ts`, content: "export const something = 10;" }; const configFile: File = { path: `${tscWatch.projectRoot}/tsconfig.json`, content: "{}" }; const host = createServerHost([file1, file2, file3, something, libFile, configFile]); const session = createSession(host, { serverMode: LanguageServiceMode.PartialSemantic, useSingleInferredProject: true }); return { host, session, file1, file2, file3, something, configFile }; } it("open files are added to inferred project even if config file is present and semantic operations succeed", () => { const { host, session, file1, file2 } = setup(); const service = session.getProjectService(); openFilesForSession([file1], session); checkNumberOfProjects(service, { inferredProjects: 1 }); const project = service.inferredProjects[0]; checkProjectActualFiles(project, [libFile.path, file1.path]); // no imports are resolved verifyCompletions(); openFilesForSession([file2], session); checkNumberOfProjects(service, { inferredProjects: 1 }); checkProjectActualFiles(project, [libFile.path, file1.path, file2.path]); verifyCompletions(); function verifyCompletions() { assert.isTrue(project.languageServiceEnabled); checkWatchedFiles(host, emptyArray); checkWatchedDirectories(host, emptyArray, /*recursive*/ true); checkWatchedDirectories(host, emptyArray, /*recursive*/ false); const response = session.executeCommandSeq<protocol.CompletionsRequest>({ command: protocol.CommandTypes.Completions, arguments: protocolFileLocationFromSubstring(file1, "prop", { index: 1 }) }).response as protocol.CompletionEntry[]; assert.deepEqual(response, [ completionEntry("foo", ScriptElementKind.memberFunctionElement), completionEntry("prop", ScriptElementKind.memberVariableElement), ]); } function completionEntry(name: string, kind: ScriptElementKind): protocol.CompletionEntry { return { name, kind, kindModifiers: "", sortText: Completions.SortText.LocationPriority, hasAction: undefined, insertText: undefined, isPackageJsonImport: undefined, isImportStatementCompletion: undefined, isRecommended: undefined, replacementSpan: undefined, source: undefined, data: undefined, sourceDisplay: undefined, isSnippet: undefined, }; } }); it("throws on unsupported commands", () => { const { session, file1 } = setup(); const service = session.getProjectService(); openFilesForSession([file1], session); let hasException = false; const request: protocol.SemanticDiagnosticsSyncRequest = { type: "request", seq: 1, command: protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { file: file1.path } }; try { session.executeCommand(request); } catch (e) { assert.equal(e.message, `Request: semanticDiagnosticsSync not allowed in LanguageServiceMode.PartialSemantic`); hasException = true; } assert.isTrue(hasException); hasException = false; const project = service.inferredProjects[0]; try { project.getLanguageService().getSemanticDiagnostics(file1.path); } catch (e) { assert.equal(e.message, `LanguageService Operation: getSemanticDiagnostics not allowed in LanguageServiceMode.PartialSemantic`); hasException = true; } assert.isTrue(hasException); }); it("allows syntactic diagnostic commands", () => { const file1: File = { path: `${tscWatch.projectRoot}/a.ts`, content: `if (a < (b + c) { }` }; const configFile: File = { path: `${tscWatch.projectRoot}/tsconfig.json`, content: `{}` }; const expectedErrorMessage = "')' expected."; const host = createServerHost([file1, libFile, configFile]); const session = createSession(host, { serverMode: LanguageServiceMode.PartialSemantic, useSingleInferredProject: true, logger: createLoggerWithInMemoryLogs() }); const service = session.getProjectService(); openFilesForSession([file1], session); const request: protocol.SyntacticDiagnosticsSyncRequest = { type: "request", seq: 1, command: protocol.CommandTypes.SyntacticDiagnosticsSync, arguments: { file: file1.path } }; const response = session.executeCommandSeq(request).response as protocol.SyntacticDiagnosticsSyncResponse["body"]; assert.isDefined(response); assert.equal(response!.length, 1); assert.equal((response![0] as protocol.Diagnostic).text, expectedErrorMessage); const project = service.inferredProjects[0]; const diagnostics = project.getLanguageService().getSyntacticDiagnostics(file1.path); assert.isTrue(diagnostics.length === 1); assert.equal(diagnostics[0].messageText, expectedErrorMessage); verifyGetErrRequest({ session, host, files: [file1], skip: [{ semantic: true, suggestion: true }] }); baselineTsserverLogs("partialSemanticServer", "syntactic diagnostics are returned with no error", session); }); it("should not include auto type reference directives", () => { const { host, session, file1 } = setup(); const atTypes: File = { path: `/node_modules/@types/somemodule/index.d.ts`, content: "export const something = 10;" }; host.ensureFileOrFolder(atTypes); const service = session.getProjectService(); openFilesForSession([file1], session); checkNumberOfProjects(service, { inferredProjects: 1 }); const project = service.inferredProjects[0]; checkProjectActualFiles(project, [libFile.path, file1.path]); // Should not contain atTypes }); it("should not include referenced files from unopened files", () => { const file1: File = { path: `${tscWatch.projectRoot}/a.ts`, content: `///<reference path="b.ts"/> ///<reference path="${tscWatch.projectRoot}/node_modules/something/index.d.ts"/> function fooA() { }` }; const file2: File = { path: `${tscWatch.projectRoot}/b.ts`, content: `///<reference path="./c.ts"/> ///<reference path="${tscWatch.projectRoot}/node_modules/something/index.d.ts"/> function fooB() { }` }; const file3: File = { path: `${tscWatch.projectRoot}/c.ts`, content: `function fooC() { }` }; const something: File = { path: `${tscWatch.projectRoot}/node_modules/something/index.d.ts`, content: "function something() {}" }; const configFile: File = { path: `${tscWatch.projectRoot}/tsconfig.json`, content: "{}" }; const host = createServerHost([file1, file2, file3, something, libFile, configFile]); const session = createSession(host, { serverMode: LanguageServiceMode.PartialSemantic, useSingleInferredProject: true }); const service = session.getProjectService(); openFilesForSession([file1], session); checkNumberOfProjects(service, { inferredProjects: 1 }); const project = service.inferredProjects[0]; checkProjectActualFiles(project, [libFile.path, file1.path]); // no resolve }); it("should not crash when external module name resolution is reused", () => { const { session, file1, file2, file3 } = setup(); const service = session.getProjectService(); openFilesForSession([file1], session); checkNumberOfProjects(service, { inferredProjects: 1 }); const project = service.inferredProjects[0]; checkProjectActualFiles(project, [libFile.path, file1.path]); // Close the file that contains non relative external module name and open some file that doesnt have non relative external module import closeFilesForSession([file1], session); openFilesForSession([file3], session); checkProjectActualFiles(project, [libFile.path, file3.path]); // Open file with non relative external module name openFilesForSession([file2], session); checkProjectActualFiles(project, [libFile.path, file2.path, file3.path]); }); it("should not create autoImportProvider or handle package jsons", () => { const angularFormsDts: File = { path: "/node_modules/@angular/forms/forms.d.ts", content: "export declare class PatternValidator {}", }; const angularFormsPackageJson: File = { path: "/node_modules/@angular/forms/package.json", content: `{ "name": "@angular/forms", "typings": "./forms.d.ts" }`, }; const tsconfig: File = { path: "/tsconfig.json", content: `{ "compilerOptions": { "module": "commonjs" } }`, }; const packageJson: File = { path: "/package.json", content: `{ "dependencies": { "@angular/forms": "*", "@angular/core": "*" } }` }; const indexTs: File = { path: "/index.ts", content: "" }; const host = createServerHost([angularFormsDts, angularFormsPackageJson, tsconfig, packageJson, indexTs, libFile]); const session = createSession(host, { serverMode: LanguageServiceMode.PartialSemantic, useSingleInferredProject: true }); const service = session.getProjectService(); openFilesForSession([indexTs], session); const project = service.inferredProjects[0]; assert.isFalse(project.autoImportProviderHost); assert.isUndefined(project.getPackageJsonAutoImportProvider()); assert.deepEqual(project.getPackageJsonsForAutoImport(), emptyArray); }); it("should support go-to-definition on module specifiers", () => { const { session, file1, file2 } = setup(); openFilesForSession([file1], session); const response = session.executeCommandSeq<protocol.DefinitionAndBoundSpanRequest>({ command: protocol.CommandTypes.DefinitionAndBoundSpan, arguments: protocolFileLocationFromSubstring(file1, `"./b"`) }).response as protocol.DefinitionInfoAndBoundSpan; assert.isDefined(response); assert.deepEqual(response.definitions, [{ file: file2.path, start: { line: 1, offset: 1 }, end: { line: 1, offset: 1 }, }]); }); }); }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [shield](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsshield.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Shield extends PolicyStatement { public servicePrefix = 'shield'; /** * Statement provider for service [shield](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsshield.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 authorize the DDoS Response team to access the specified Amazon S3 bucket containing your flow logs * * Access Level: Write * * Dependent actions: * - s3:GetBucketPolicy * - s3:PutBucketPolicy * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_AssociateDRTLogBucket.html */ public toAssociateDRTLogBucket() { return this.to('AssociateDRTLogBucket'); } /** * Grants permission to authorize the DDoS Response team using the specified role, to access your AWS account to assist with DDoS attack mitigation during potential attacks * * Access Level: Write * * Dependent actions: * - iam:GetRole * - iam:ListAttachedRolePolicies * - iam:PassRole * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_AssociateDRTRole.html */ public toAssociateDRTRole() { return this.to('AssociateDRTRole'); } /** * Grants permission to add health-based detection to the Shield Advanced protection for a resource * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * Dependent actions: * - route53:GetHealthCheck * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_AssociateHealthCheck.html */ public toAssociateHealthCheck() { return this.to('AssociateHealthCheck'); } /** * Grants permission to initialize proactive engagement and set the list of contacts for the DDoS Response Team (DRT) to use * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_AssociateProactiveEngagementDetails.html */ public toAssociateProactiveEngagementDetails() { return this.to('AssociateProactiveEngagementDetails'); } /** * Grants permission to activate DDoS protection service for a given resource ARN * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_CreateProtection.html */ public toCreateProtection() { return this.to('CreateProtection'); } /** * Grants permission to create a grouping of protected resources so they can be handled as a collective * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_CreateProtectionGroup.html */ public toCreateProtectionGroup() { return this.to('CreateProtectionGroup'); } /** * Grants permission to activate subscription * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_CreateSubscription.html */ public toCreateSubscription() { return this.to('CreateSubscription'); } /** * Grants permission to delete an existing protection * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DeleteProtection.html */ public toDeleteProtection() { return this.to('DeleteProtection'); } /** * Grants permission to remove the specified protection group * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DeleteProtectionGroup.html */ public toDeleteProtectionGroup() { return this.to('DeleteProtectionGroup'); } /** * Grants permission to deactivate subscription * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DeleteSubscription.html */ public toDeleteSubscription() { return this.to('DeleteSubscription'); } /** * Grants permission to get attack details * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DescribeAttack.html */ public toDescribeAttack() { return this.to('DescribeAttack'); } /** * Grants permission to describe information about the number and type of attacks AWS Shield has detected in the last year * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DescribeAttackStatistics.html */ public toDescribeAttackStatistics() { return this.to('DescribeAttackStatistics'); } /** * Grants permission to describe the current role and list of Amazon S3 log buckets used by the DDoS Response team to access your AWS account while assisting with attack mitigation * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DescribeDRTAccess.html */ public toDescribeDRTAccess() { return this.to('DescribeDRTAccess'); } /** * Grants permission to list the email addresses that the DRT can use to contact you during a suspected attack * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DescribeEmergencyContactSettings.html */ public toDescribeEmergencyContactSettings() { return this.to('DescribeEmergencyContactSettings'); } /** * Grants permission to get protection details * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DescribeProtection.html */ public toDescribeProtection() { return this.to('DescribeProtection'); } /** * Grants permission to describe the specification for the specified protection group * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DescribeProtectionGroup.html */ public toDescribeProtectionGroup() { return this.to('DescribeProtectionGroup'); } /** * Grants permission to get subscription details, such as start time * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DescribeSubscription.html */ public toDescribeSubscription() { return this.to('DescribeSubscription'); } /** * Grants permission to remove authorization from the DDoS Response Team (DRT) to notify contacts about escalations * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DisableProactiveEngagement.html */ public toDisableProactiveEngagement() { return this.to('DisableProactiveEngagement'); } /** * Grants permission to remove the DDoS Response team's access to the specified Amazon S3 bucket containing your flow logs * * Access Level: Write * * Dependent actions: * - s3:DeleteBucketPolicy * - s3:GetBucketPolicy * - s3:PutBucketPolicy * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DisassociateDRTLogBucket.html */ public toDisassociateDRTLogBucket() { return this.to('DisassociateDRTLogBucket'); } /** * Grants permission to remove the DDoS Response team's access to your AWS account * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DisassociateDRTRole.html */ public toDisassociateDRTRole() { return this.to('DisassociateDRTRole'); } /** * Grants permission to remove health-based detection from the Shield Advanced protection for a resource * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_DisassociateHealthCheck.html */ public toDisassociateHealthCheck() { return this.to('DisassociateHealthCheck'); } /** * Grants permission to authorize the DDoS Response Team (DRT) to use email and phone to notify contacts about escalations * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_EnableProactiveEngagement.html */ public toEnableProactiveEngagement() { return this.to('EnableProactiveEngagement'); } /** * Grants permission to get subscription state * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_GetSubscriptionState.html */ public toGetSubscriptionState() { return this.to('GetSubscriptionState'); } /** * Grants permission to list all existing attacks * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_ListAttacks.html */ public toListAttacks() { return this.to('ListAttacks'); } /** * Grants permission to retrieve the protection groups for the account * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_ListProtectionGroups.html */ public toListProtectionGroups() { return this.to('ListProtectionGroups'); } /** * Grants permission to list all existing protections * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_ListProtections.html */ public toListProtections() { return this.to('ListProtections'); } /** * Grants permission to retrieve the resources that are included in the protection group * * Access Level: List * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_ListResourcesInProtectionGroup.html */ public toListResourcesInProtectionGroup() { return this.to('ListResourcesInProtectionGroup'); } /** * Grants permission to get information about AWS tags for a specified Amazon Resource Name (ARN) in AWS Shield * * Access Level: Read * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to add or updates tags for a resource in AWS Shield * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove tags from a resource in AWS Shield * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update the details of the list of email addresses that the DRT can use to contact you during a suspected attack * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_UpdateEmergencyContactSettings.html */ public toUpdateEmergencyContactSettings() { return this.to('UpdateEmergencyContactSettings'); } /** * Grants permission to update an existing protection group * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_UpdateProtectionGroup.html */ public toUpdateProtectionGroup() { return this.to('UpdateProtectionGroup'); } /** * Grants permission to update the details of an existing subscription * * Access Level: Write * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_UpdateSubscription.html */ public toUpdateSubscription() { return this.to('UpdateSubscription'); } protected accessLevelList: AccessLevelList = { "Write": [ "AssociateDRTLogBucket", "AssociateDRTRole", "AssociateHealthCheck", "AssociateProactiveEngagementDetails", "CreateProtection", "CreateProtectionGroup", "CreateSubscription", "DeleteProtection", "DeleteProtectionGroup", "DeleteSubscription", "DisableProactiveEngagement", "DisassociateDRTLogBucket", "DisassociateDRTRole", "DisassociateHealthCheck", "EnableProactiveEngagement", "UpdateEmergencyContactSettings", "UpdateProtectionGroup", "UpdateSubscription" ], "Read": [ "DescribeAttack", "DescribeAttackStatistics", "DescribeDRTAccess", "DescribeEmergencyContactSettings", "DescribeProtection", "DescribeProtectionGroup", "DescribeSubscription", "GetSubscriptionState", "ListTagsForResource" ], "List": [ "ListAttacks", "ListProtectionGroups", "ListProtections", "ListResourcesInProtectionGroup" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type attack to the statement * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_AttackDetail.html * * @param id - Identifier for the id. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onAttack(id: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:shield::${Account}:attack/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type protection to the statement * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_Protection.html * * @param id - Identifier for the id. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onProtection(id: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:shield::${Account}:protection/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type protection-group to the statement * * https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_ProtectionGroup.html * * @param id - Identifier for the id. * @param account - Account of the resource; defaults to empty string: all accounts. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onProtectionGroup(id: string, account?: string, partition?: string) { var arn = 'arn:${Partition}:shield::${Account}:protection-group/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import { SuggestionCostMapDef } from '../models/suggestionCostsDef'; import { DEFAULT_COMPOUNDED_WORD_SEPARATOR } from '../suggestions/suggestCollector'; export type WeightedRepMapTrie = Record<string, WeightedRepTrieNode>; const matchPossibleWordSeparators = /[+∙•・●]/g; interface WeightedRepTrieNode { /** The nested Trie nodes */ r?: WeightedRepMapTrie | undefined; /** The cost to replace */ rep?: number | undefined; /** The cost to swap */ swap?: number | undefined; } /** * Costs are minimized while penalties are maximized. */ interface Cost { /** * The cost of an operation * `c'' = min(c, c')` */ c?: number | undefined; /** * The penalties applied * `p'' = max(p, p')` */ p?: number | undefined; } interface TrieCost extends Cost { /** nested trie nodes */ n?: Record<string, TrieCost>; } interface TrieTrieCost { /** nested trie nodes */ n?: Record<string, TrieTrieCost>; /** root of cost trie */ t?: Record<string, TrieCost>; } export interface CostPosition { // Word to start with a: string; // offset within `a` ai: number; // Word to end with b: string; // offset within `b` bi: number; // accumulated cost to this point. c: number; // accumulated penalties to this point. p: number; } export interface WeightMap { readonly insDel: TrieCost; readonly replace: TrieTrieCost; readonly swap: TrieTrieCost; readonly adjustments: Map<string, PenaltyAdjustment>; calcInsDelCosts(pos: CostPosition): Iterable<CostPosition>; calcSwapCosts(pos: CostPosition): Iterable<CostPosition>; calcReplaceCosts(pos: CostPosition): Iterable<CostPosition>; calcAdjustment(word: string): number; } export interface PenaltyAdjustment { /** Penalty Identifier */ id: string; /** RegExp Pattern to match */ regexp: RegExp; /** Penalty to apply */ penalty: number; } export function createWeightMap(...defs: SuggestionCostMapDef[]): WeightMap { const map = _createWeightMap(); addDefsToWeightMap(map, defs); return map; } export function addDefToWeightMap( map: WeightMap, def: SuggestionCostMapDef, ...defs: SuggestionCostMapDef[] ): WeightMap; export function addDefToWeightMap(map: WeightMap, ...defs: SuggestionCostMapDef[]): WeightMap { return addDefsToWeightMap(map, defs); } export function addAdjustment(map: WeightMap, ...adjustments: PenaltyAdjustment[]): WeightMap; export function addAdjustment(map: WeightMap, adjustment: PenaltyAdjustment): WeightMap; export function addAdjustment(map: WeightMap, ...adjustments: PenaltyAdjustment[]): WeightMap { for (const adj of adjustments) { map.adjustments.set(adj.id, adj); } return map; } export function addDefsToWeightMap(map: WeightMap, defs: SuggestionCostMapDef[]): WeightMap { function addSet(set: string[], def: SuggestionCostMapDef) { addSetToTrieCost(map.insDel, set, def.insDel, def.penalty); addSetToTrieTrieCost(map.replace, set, def.replace, def.penalty); addSetToTrieTrieCost(map.swap, set, def.swap, def.penalty); } for (const _def of defs) { const def = normalizeDef(_def); const mapSets = splitMap(def); mapSets.forEach((s) => addSet(s, def)); } return map; } function _createWeightMap(): WeightMap { return new _WeightedMap(); } function lowest(a: number | undefined, b: number | undefined): number | undefined { if (a === undefined) return b; if (b === undefined) return a; return a <= b ? a : b; } function highest(a: number | undefined, b: number | undefined): number | undefined { if (a === undefined) return b; if (b === undefined) return a; return a >= b ? a : b; } function normalize(s: string): Set<string> { const f = new Set([s]); f.add(s.normalize('NFC')); f.add(s.normalize('NFD')); return f; } export function* splitMapSubstringsIterable(map: string): Iterable<string> { let seq = ''; let mode = 0; for (const char of map) { if (mode && char === ')') { yield* normalize(seq); mode = 0; continue; } if (mode) { seq += char; continue; } if (char === '(') { mode = 1; seq = ''; continue; } yield* normalize(char); } } export function splitMapSubstrings(map: string): string[] { return [...splitMapSubstringsIterable(map)]; } /** * Splits a WeightedMapDef.map * @param map */ function splitMap(def: Pick<SuggestionCostMapDef, 'map'>): string[][] { const { map } = def; const sets = map.split('|'); return sets.map(splitMapSubstrings).filter((s) => s.length > 0); } function addToTrieCost(trie: TrieCost, str: string, cost: number, penalties: number | undefined): void { if (!str) return; let t = trie; for (const c of str) { const n = (t.n = t.n || Object.create(null)); t = n[c] = n[c] || Object.create(null); } t.c = lowest(t.c, cost); t.p = highest(t.p, penalties); } function addToTrieTrieCost( trie: TrieTrieCost, left: string, right: string, cost: number, penalties: number | undefined ): void { let t = trie; for (const c of left) { const n = (t.n = t.n || Object.create(null)); t = n[c] = n[c] || Object.create(null); } const trieCost = (t.t = t.t || Object.create(null)); addToTrieCost(trieCost, right, cost, penalties); } function addSetToTrieCost(trie: TrieCost, set: string[], cost: number | undefined, penalties: number | undefined) { if (cost === undefined) return; for (const str of set) { addToTrieCost(trie, str, cost, penalties); } } function addSetToTrieTrieCost( trie: TrieTrieCost, set: string[], cost: number | undefined, penalties: number | undefined ) { if (cost === undefined) return; for (const left of set) { for (const right of set) { if (left === right) continue; addToTrieTrieCost(trie, left, right, cost, penalties); } } } function* searchTrieNodes<T extends { n?: Record<string, T> }>(trie: T, str: string, i: number) { const len = str.length; for (let n = trie.n; i < len && n; ) { const t = n[str[i]]; if (!t) return; ++i; yield { i, t }; n = t.n; } } function* walkTrieNodes<T extends { n?: Record<string, T> }>( t: T | undefined, s: string ): Generator<{ s: string; t: T }> { if (!t) return; yield { s, t }; if (!t.n) return; for (const [k, v] of Object.entries(t.n)) { yield* walkTrieNodes(v, s + k); } } function* walkTrieCost(trie: TrieCost): Generator<{ s: string; c: number; p: number | undefined }> { for (const { s, t } of walkTrieNodes(trie, '')) { if (t.c) { yield { s, c: t.c, p: t.p }; } } } function* walkTrieTrieCost(trie: TrieTrieCost): Generator<{ a: string; b: string; c: number; p: number | undefined }> { for (const { s: a, t } of walkTrieNodes(trie, '')) { if (t.t) { for (const { s: b, c, p } of walkTrieCost(t.t)) { yield { a, b, c, p }; } } } } interface MatchTrieCost { i: number; c: number; p: number; } function* findTrieCostPrefixes(trie: TrieCost, str: string, i: number): Iterable<MatchTrieCost> { for (const n of searchTrieNodes(trie, str, i)) { const { c, p } = n.t; if (c !== undefined) { yield { i: n.i, c, p: p || 0 }; } } } interface MatchTrieTrieCost { i: number; t: TrieCost; } function* findTrieTrieCostPrefixes(trie: TrieTrieCost, str: string, i: number): Iterable<MatchTrieTrieCost> { for (const n of searchTrieNodes(trie, str, i)) { const t = n.t.t; if (t !== undefined) { yield { i: n.i, t }; } } } class _WeightedMap implements WeightMap { insDel: TrieCost = {}; replace: TrieTrieCost = {}; swap: TrieTrieCost = {}; adjustments = new Map<string, PenaltyAdjustment>(); *calcInsDelCosts(pos: CostPosition): Iterable<CostPosition> { const { a, ai, b, bi, c, p } = pos; for (const del of findTrieCostPrefixes(this.insDel, a, ai)) { yield { a, b, ai: del.i, bi, c: c + del.c, p: p + del.p }; } for (const ins of findTrieCostPrefixes(this.insDel, b, bi)) { yield { a, b, ai, bi: ins.i, c: c + ins.c, p: p + ins.p }; } } *calcReplaceCosts(pos: CostPosition): Iterable<CostPosition> { // Search for matching substrings in `a` to be replaced by // matching substrings from `b`. All substrings start at their // respective `ai`/`bi` positions. const { a, ai, b, bi, c, p } = pos; for (const del of findTrieTrieCostPrefixes(this.replace, a, ai)) { for (const ins of findTrieCostPrefixes(del.t, b, bi)) { yield { a, b, ai: del.i, bi: ins.i, c: c + ins.c, p: p + ins.p }; } } } *calcSwapCosts(pos: CostPosition): Iterable<CostPosition> { const { a, ai, b, bi, c, p } = pos; const swap = this.swap; for (const left of findTrieTrieCostPrefixes(swap, a, ai)) { for (const right of findTrieCostPrefixes(left.t, a, left.i)) { const sw = a.slice(left.i, right.i) + a.slice(ai, left.i); if (b.slice(bi).startsWith(sw)) { const len = sw.length; yield { a, b, ai: ai + len, bi: bi + len, c: c + right.c, p: p + right.p }; } } } } calcAdjustment(word: string): number { let penalty = 0; for (const adj of this.adjustments.values()) { if (adj.regexp.global) { for (const _m of word.matchAll(adj.regexp)) { penalty += adj.penalty; } } else if (adj.regexp.test(word)) { penalty += adj.penalty; } } return penalty; } } function prettyPrintInsDel(trie: TrieCost, pfx = '', indent = ' '): string { function* walk() { for (const { s, c, p } of walkTrieCost(trie)) { const pm = p ? ` + ${p}` : ''; yield indent + `(${s}) = ${c}${pm}`; } } return ['InsDel:', ...[...walk()].sort()].map((line) => pfx + line + '\n').join(''); } export function prettyPrintReplace(trie: TrieTrieCost, pfx = '', indent = ' '): string { function* walk() { for (const { a, b, c, p } of walkTrieTrieCost(trie)) { const pm = p ? ` + ${p}` : ''; yield indent + `(${a}) -> (${b}) = ${c}${pm}`; } } return ['Replace:', ...[...walk()].sort()].map((line) => pfx + line + '\n').join(''); } export function prettyPrintSwap(trie: TrieTrieCost, pfx = '', indent = ' '): string { function* walk() { for (const { a, b, c, p } of walkTrieTrieCost(trie)) { const pm = p ? ` + ${p}` : ''; yield indent + `(${a}) <-> (${b}) = ${c}${pm}`; } } return ['Swap:', ...[...walk()].sort()].map((line) => pfx + line + '\n').join(''); } export function prettyPrintWeightMap(map: WeightMap): string { return [prettyPrintInsDel(map.insDel), prettyPrintReplace(map.replace), prettyPrintSwap(map.swap)].join('\n'); } export function lookupReplaceCost(map: WeightMap, a: string, b: string): undefined | number { const trie = map.replace; let tt: TrieTrieCost | undefined = trie; for (let ai = 0; ai < a.length && tt; ++ai) { tt = tt.n?.[a[ai]]; } if (!tt) return undefined; let t: TrieCost | undefined = tt.t; for (let bi = 0; bi < b.length && t; ++bi) { t = t.n?.[b[bi]]; } return t?.c; } function normalizeDef(def: SuggestionCostMapDef): SuggestionCostMapDef { const { map, ...rest } = def; return { ...rest, map: normalizeMap(map) }; } function normalizeMap(map: string): string { return map.replace(matchPossibleWordSeparators, DEFAULT_COMPOUNDED_WORD_SEPARATOR); } export const __testing__ = { findTrieCostPrefixes, findTrieTrieCostPrefixes, normalizeDef, splitMap, splitMapSubstrings, };
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class DataExchange extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: DataExchange.Types.ClientConfiguration) config: Config & DataExchange.Types.ClientConfiguration; /** * This operation cancels a job. Jobs can be cancelled only when they are in the WAITING state. */ cancelJob(params: DataExchange.Types.CancelJobRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation cancels a job. Jobs can be cancelled only when they are in the WAITING state. */ cancelJob(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation creates a data set. */ createDataSet(params: DataExchange.Types.CreateDataSetRequest, callback?: (err: AWSError, data: DataExchange.Types.CreateDataSetResponse) => void): Request<DataExchange.Types.CreateDataSetResponse, AWSError>; /** * This operation creates a data set. */ createDataSet(callback?: (err: AWSError, data: DataExchange.Types.CreateDataSetResponse) => void): Request<DataExchange.Types.CreateDataSetResponse, AWSError>; /** * This operation creates an event action. */ createEventAction(params: DataExchange.Types.CreateEventActionRequest, callback?: (err: AWSError, data: DataExchange.Types.CreateEventActionResponse) => void): Request<DataExchange.Types.CreateEventActionResponse, AWSError>; /** * This operation creates an event action. */ createEventAction(callback?: (err: AWSError, data: DataExchange.Types.CreateEventActionResponse) => void): Request<DataExchange.Types.CreateEventActionResponse, AWSError>; /** * This operation creates a job. */ createJob(params: DataExchange.Types.CreateJobRequest, callback?: (err: AWSError, data: DataExchange.Types.CreateJobResponse) => void): Request<DataExchange.Types.CreateJobResponse, AWSError>; /** * This operation creates a job. */ createJob(callback?: (err: AWSError, data: DataExchange.Types.CreateJobResponse) => void): Request<DataExchange.Types.CreateJobResponse, AWSError>; /** * This operation creates a revision for a data set. */ createRevision(params: DataExchange.Types.CreateRevisionRequest, callback?: (err: AWSError, data: DataExchange.Types.CreateRevisionResponse) => void): Request<DataExchange.Types.CreateRevisionResponse, AWSError>; /** * This operation creates a revision for a data set. */ createRevision(callback?: (err: AWSError, data: DataExchange.Types.CreateRevisionResponse) => void): Request<DataExchange.Types.CreateRevisionResponse, AWSError>; /** * This operation deletes an asset. */ deleteAsset(params: DataExchange.Types.DeleteAssetRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation deletes an asset. */ deleteAsset(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation deletes a data set. */ deleteDataSet(params: DataExchange.Types.DeleteDataSetRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation deletes a data set. */ deleteDataSet(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation deletes the event action. */ deleteEventAction(params: DataExchange.Types.DeleteEventActionRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation deletes the event action. */ deleteEventAction(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation deletes a revision. */ deleteRevision(params: DataExchange.Types.DeleteRevisionRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation deletes a revision. */ deleteRevision(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation returns information about an asset. */ getAsset(params: DataExchange.Types.GetAssetRequest, callback?: (err: AWSError, data: DataExchange.Types.GetAssetResponse) => void): Request<DataExchange.Types.GetAssetResponse, AWSError>; /** * This operation returns information about an asset. */ getAsset(callback?: (err: AWSError, data: DataExchange.Types.GetAssetResponse) => void): Request<DataExchange.Types.GetAssetResponse, AWSError>; /** * This operation returns information about a data set. */ getDataSet(params: DataExchange.Types.GetDataSetRequest, callback?: (err: AWSError, data: DataExchange.Types.GetDataSetResponse) => void): Request<DataExchange.Types.GetDataSetResponse, AWSError>; /** * This operation returns information about a data set. */ getDataSet(callback?: (err: AWSError, data: DataExchange.Types.GetDataSetResponse) => void): Request<DataExchange.Types.GetDataSetResponse, AWSError>; /** * This operation retrieves information about an event action. */ getEventAction(params: DataExchange.Types.GetEventActionRequest, callback?: (err: AWSError, data: DataExchange.Types.GetEventActionResponse) => void): Request<DataExchange.Types.GetEventActionResponse, AWSError>; /** * This operation retrieves information about an event action. */ getEventAction(callback?: (err: AWSError, data: DataExchange.Types.GetEventActionResponse) => void): Request<DataExchange.Types.GetEventActionResponse, AWSError>; /** * This operation returns information about a job. */ getJob(params: DataExchange.Types.GetJobRequest, callback?: (err: AWSError, data: DataExchange.Types.GetJobResponse) => void): Request<DataExchange.Types.GetJobResponse, AWSError>; /** * This operation returns information about a job. */ getJob(callback?: (err: AWSError, data: DataExchange.Types.GetJobResponse) => void): Request<DataExchange.Types.GetJobResponse, AWSError>; /** * This operation returns information about a revision. */ getRevision(params: DataExchange.Types.GetRevisionRequest, callback?: (err: AWSError, data: DataExchange.Types.GetRevisionResponse) => void): Request<DataExchange.Types.GetRevisionResponse, AWSError>; /** * This operation returns information about a revision. */ getRevision(callback?: (err: AWSError, data: DataExchange.Types.GetRevisionResponse) => void): Request<DataExchange.Types.GetRevisionResponse, AWSError>; /** * This operation lists a data set's revisions sorted by CreatedAt in descending order. */ listDataSetRevisions(params: DataExchange.Types.ListDataSetRevisionsRequest, callback?: (err: AWSError, data: DataExchange.Types.ListDataSetRevisionsResponse) => void): Request<DataExchange.Types.ListDataSetRevisionsResponse, AWSError>; /** * This operation lists a data set's revisions sorted by CreatedAt in descending order. */ listDataSetRevisions(callback?: (err: AWSError, data: DataExchange.Types.ListDataSetRevisionsResponse) => void): Request<DataExchange.Types.ListDataSetRevisionsResponse, AWSError>; /** * This operation lists your data sets. When listing by origin OWNED, results are sorted by CreatedAt in descending order. When listing by origin ENTITLED, there is no order and the maxResults parameter is ignored. */ listDataSets(params: DataExchange.Types.ListDataSetsRequest, callback?: (err: AWSError, data: DataExchange.Types.ListDataSetsResponse) => void): Request<DataExchange.Types.ListDataSetsResponse, AWSError>; /** * This operation lists your data sets. When listing by origin OWNED, results are sorted by CreatedAt in descending order. When listing by origin ENTITLED, there is no order and the maxResults parameter is ignored. */ listDataSets(callback?: (err: AWSError, data: DataExchange.Types.ListDataSetsResponse) => void): Request<DataExchange.Types.ListDataSetsResponse, AWSError>; /** * This operation lists your event actions. */ listEventActions(params: DataExchange.Types.ListEventActionsRequest, callback?: (err: AWSError, data: DataExchange.Types.ListEventActionsResponse) => void): Request<DataExchange.Types.ListEventActionsResponse, AWSError>; /** * This operation lists your event actions. */ listEventActions(callback?: (err: AWSError, data: DataExchange.Types.ListEventActionsResponse) => void): Request<DataExchange.Types.ListEventActionsResponse, AWSError>; /** * This operation lists your jobs sorted by CreatedAt in descending order. */ listJobs(params: DataExchange.Types.ListJobsRequest, callback?: (err: AWSError, data: DataExchange.Types.ListJobsResponse) => void): Request<DataExchange.Types.ListJobsResponse, AWSError>; /** * This operation lists your jobs sorted by CreatedAt in descending order. */ listJobs(callback?: (err: AWSError, data: DataExchange.Types.ListJobsResponse) => void): Request<DataExchange.Types.ListJobsResponse, AWSError>; /** * This operation lists a revision's assets sorted alphabetically in descending order. */ listRevisionAssets(params: DataExchange.Types.ListRevisionAssetsRequest, callback?: (err: AWSError, data: DataExchange.Types.ListRevisionAssetsResponse) => void): Request<DataExchange.Types.ListRevisionAssetsResponse, AWSError>; /** * This operation lists a revision's assets sorted alphabetically in descending order. */ listRevisionAssets(callback?: (err: AWSError, data: DataExchange.Types.ListRevisionAssetsResponse) => void): Request<DataExchange.Types.ListRevisionAssetsResponse, AWSError>; /** * This operation lists the tags on the resource. */ listTagsForResource(params: DataExchange.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: DataExchange.Types.ListTagsForResourceResponse) => void): Request<DataExchange.Types.ListTagsForResourceResponse, AWSError>; /** * This operation lists the tags on the resource. */ listTagsForResource(callback?: (err: AWSError, data: DataExchange.Types.ListTagsForResourceResponse) => void): Request<DataExchange.Types.ListTagsForResourceResponse, AWSError>; /** * This operation starts a job. */ startJob(params: DataExchange.Types.StartJobRequest, callback?: (err: AWSError, data: DataExchange.Types.StartJobResponse) => void): Request<DataExchange.Types.StartJobResponse, AWSError>; /** * This operation starts a job. */ startJob(callback?: (err: AWSError, data: DataExchange.Types.StartJobResponse) => void): Request<DataExchange.Types.StartJobResponse, AWSError>; /** * This operation tags a resource. */ tagResource(params: DataExchange.Types.TagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation tags a resource. */ tagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation removes one or more tags from a resource. */ untagResource(params: DataExchange.Types.UntagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation removes one or more tags from a resource. */ untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * This operation updates an asset. */ updateAsset(params: DataExchange.Types.UpdateAssetRequest, callback?: (err: AWSError, data: DataExchange.Types.UpdateAssetResponse) => void): Request<DataExchange.Types.UpdateAssetResponse, AWSError>; /** * This operation updates an asset. */ updateAsset(callback?: (err: AWSError, data: DataExchange.Types.UpdateAssetResponse) => void): Request<DataExchange.Types.UpdateAssetResponse, AWSError>; /** * This operation updates a data set. */ updateDataSet(params: DataExchange.Types.UpdateDataSetRequest, callback?: (err: AWSError, data: DataExchange.Types.UpdateDataSetResponse) => void): Request<DataExchange.Types.UpdateDataSetResponse, AWSError>; /** * This operation updates a data set. */ updateDataSet(callback?: (err: AWSError, data: DataExchange.Types.UpdateDataSetResponse) => void): Request<DataExchange.Types.UpdateDataSetResponse, AWSError>; /** * This operation updates the event action. */ updateEventAction(params: DataExchange.Types.UpdateEventActionRequest, callback?: (err: AWSError, data: DataExchange.Types.UpdateEventActionResponse) => void): Request<DataExchange.Types.UpdateEventActionResponse, AWSError>; /** * This operation updates the event action. */ updateEventAction(callback?: (err: AWSError, data: DataExchange.Types.UpdateEventActionResponse) => void): Request<DataExchange.Types.UpdateEventActionResponse, AWSError>; /** * This operation updates a revision. */ updateRevision(params: DataExchange.Types.UpdateRevisionRequest, callback?: (err: AWSError, data: DataExchange.Types.UpdateRevisionResponse) => void): Request<DataExchange.Types.UpdateRevisionResponse, AWSError>; /** * This operation updates a revision. */ updateRevision(callback?: (err: AWSError, data: DataExchange.Types.UpdateRevisionResponse) => void): Request<DataExchange.Types.UpdateRevisionResponse, AWSError>; } declare namespace DataExchange { export interface Action { ExportRevisionToS3?: AutoExportRevisionToS3RequestDetails; } export type Arn = string; export interface AssetDestinationEntry { /** * The unique identifier for the asset. */ AssetId: Id; /** * The S3 bucket that is the destination for the asset. */ Bucket: __string; /** * The name of the object in Amazon S3 for the asset. */ Key?: __string; } export interface AssetDetails { S3SnapshotAsset?: S3SnapshotAsset; } export interface AssetEntry { /** * The ARN for the asset. */ Arn: Arn; /** * Information about the asset, including its size. */ AssetDetails: AssetDetails; /** * The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. */ AssetType: AssetType; /** * The date and time that the asset was created, in ISO 8601 format. */ CreatedAt: Timestamp; /** * The unique identifier for the data set associated with this asset. */ DataSetId: Id; /** * The unique identifier for the asset. */ Id: Id; /** * The name of the asset. When importing from Amazon S3, the S3 object key is used as the asset name. When exporting to Amazon S3, the asset name is used as default target S3 object key. */ Name: AssetName; /** * The unique identifier for the revision associated with this asset. */ RevisionId: Id; /** * The asset ID of the owned asset corresponding to the entitled asset being viewed. This parameter is returned when an asset owner is viewing the entitled copy of its owned asset. */ SourceId?: Id; /** * The date and time that the asset was last updated, in ISO 8601 format. */ UpdatedAt: Timestamp; } export type AssetName = string; export interface AssetSourceEntry { /** * The S3 bucket that's part of the source of the asset. */ Bucket: __string; /** * The name of the object in Amazon S3 for the asset. */ Key: __string; } export type AssetType = "S3_SNAPSHOT"|string; export interface AutoExportRevisionDestinationEntry { /** * The S3 bucket that is the destination for the event action. */ Bucket: __string; /** * A string representing the pattern for generated names of the individual assets in the revision. For more information about key patterns, see Key patterns when exporting revisions. */ KeyPattern?: __string; } export interface AutoExportRevisionToS3RequestDetails { Encryption?: ExportServerSideEncryption; RevisionDestination: AutoExportRevisionDestinationEntry; } export interface CancelJobRequest { /** * The unique identifier for a job. */ JobId: __string; } export type Code = "ACCESS_DENIED_EXCEPTION"|"INTERNAL_SERVER_EXCEPTION"|"MALWARE_DETECTED"|"RESOURCE_NOT_FOUND_EXCEPTION"|"SERVICE_QUOTA_EXCEEDED_EXCEPTION"|"VALIDATION_EXCEPTION"|"MALWARE_SCAN_ENCRYPTED_FILE"|string; export interface CreateDataSetRequest { /** * The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. */ AssetType: AssetType; /** * A description for the data set. This value can be up to 16,348 characters long. */ Description: Description; /** * The name of the data set. */ Name: Name; /** * A data set tag is an optional label that you can assign to a data set when you create it. Each tag consists of a key and an optional value, both of which you define. When you use tagging, you can also use tag-based access control in IAM policies to control access to these data sets and revisions. */ Tags?: MapOf__string; } export interface CreateDataSetResponse { /** * The ARN for the data set. */ Arn?: Arn; /** * The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. */ AssetType?: AssetType; /** * The date and time that the data set was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * The description for the data set. */ Description?: Description; /** * The unique identifier for the data set. */ Id?: Id; /** * The name of the data set. */ Name?: Name; /** * A property that defines the data set as OWNED by the account (for providers) or ENTITLED to the account (for subscribers). */ Origin?: Origin; /** * If the origin of this data set is ENTITLED, includes the details for the product on AWS Marketplace. */ OriginDetails?: OriginDetails; /** * The data set ID of the owned data set corresponding to the entitled data set being viewed. This parameter is returned when a data set owner is viewing the entitled copy of its owned data set. */ SourceId?: Id; /** * The tags for the data set. */ Tags?: MapOf__string; /** * The date and time that the data set was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface CreateEventActionRequest { /** * What occurs after a certain event. */ Action: Action; /** * What occurs to start an action. */ Event: Event; } export interface CreateEventActionResponse { /** * What occurs after a certain event. */ Action?: Action; /** * The ARN for the event action. */ Arn?: Arn; /** * The date and time that the event action was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * What occurs to start an action. */ Event?: Event; /** * The unique identifier for the event action. */ Id?: Id; /** * The date and time that the event action was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface CreateJobRequest { /** * The details for the CreateJob request. */ Details: RequestDetails; /** * The type of job to be created. */ Type: Type; } export interface CreateJobResponse { /** * The ARN for the job. */ Arn?: Arn; /** * The date and time that the job was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * Details about the job. */ Details?: ResponseDetails; /** * The errors associated with jobs. */ Errors?: ListOfJobError; /** * The unique identifier for the job. */ Id?: Id; /** * The state of the job. */ State?: State; /** * The job type. */ Type?: Type; /** * The date and time that the job was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface CreateRevisionRequest { /** * An optional comment about the revision. */ Comment?: __stringMin0Max16384; /** * The unique identifier for a data set. */ DataSetId: __string; /** * A revision tag is an optional label that you can assign to a revision when you create it. Each tag consists of a key and an optional value, both of which you define. When you use tagging, you can also use tag-based access control in IAM policies to control access to these data sets and revisions. */ Tags?: MapOf__string; } export interface CreateRevisionResponse { /** * The ARN for the revision */ Arn?: Arn; /** * An optional comment about the revision. */ Comment?: __stringMin0Max16384; /** * The date and time that the revision was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * The unique identifier for the data set associated with this revision. */ DataSetId?: Id; /** * To publish a revision to a data set in a product, the revision must first be finalized. Finalizing a revision tells AWS Data Exchange that your changes to the assets in the revision are complete. After it's in this read-only state, you can publish the revision to your products. Finalized revisions can be published through the AWS Data Exchange console or the AWS Marketplace Catalog API, using the StartChangeSet AWS Marketplace Catalog API action. When using the API, revisions are uniquely identified by their ARN. */ Finalized?: __boolean; /** * The unique identifier for the revision. */ Id?: Id; /** * The revision ID of the owned revision corresponding to the entitled revision being viewed. This parameter is returned when a revision owner is viewing the entitled copy of its owned revision. */ SourceId?: Id; /** * The tags for the revision. */ Tags?: MapOf__string; /** * The date and time that the revision was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface DataSetEntry { /** * The ARN for the data set. */ Arn: Arn; /** * The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. */ AssetType: AssetType; /** * The date and time that the data set was created, in ISO 8601 format. */ CreatedAt: Timestamp; /** * The description for the data set. */ Description: Description; /** * The unique identifier for the data set. */ Id: Id; /** * The name of the data set. */ Name: Name; /** * A property that defines the data set as OWNED by the account (for providers) or ENTITLED to the account (for subscribers). */ Origin: Origin; /** * If the origin of this data set is ENTITLED, includes the details for the product on AWS Marketplace. */ OriginDetails?: OriginDetails; /** * The data set ID of the owned data set corresponding to the entitled data set being viewed. This parameter is returned when a data set owner is viewing the entitled copy of its owned data set. */ SourceId?: Id; /** * The date and time that the data set was last updated, in ISO 8601 format. */ UpdatedAt: Timestamp; } export interface DeleteAssetRequest { /** * The unique identifier for an asset. */ AssetId: __string; /** * The unique identifier for a data set. */ DataSetId: __string; /** * The unique identifier for a revision. */ RevisionId: __string; } export interface DeleteDataSetRequest { /** * The unique identifier for a data set. */ DataSetId: __string; } export interface DeleteEventActionRequest { /** * The unique identifier for the event action. */ EventActionId: __string; } export interface DeleteRevisionRequest { /** * The unique identifier for a data set. */ DataSetId: __string; /** * The unique identifier for a revision. */ RevisionId: __string; } export type Description = string; export interface Details { ImportAssetFromSignedUrlJobErrorDetails?: ImportAssetFromSignedUrlJobErrorDetails; ImportAssetsFromS3JobErrorDetails?: ListOfAssetSourceEntry; } export interface Event { RevisionPublished?: RevisionPublished; } export interface EventActionEntry { /** * What occurs after a certain event. */ Action: Action; /** * The ARN for the event action. */ Arn: Arn; /** * The date and time that the event action was created, in ISO 8601 format. */ CreatedAt: Timestamp; /** * What occurs to start an action. */ Event: Event; /** * The unique identifier for the event action. */ Id: Id; /** * The date and time that the event action was last updated, in ISO 8601 format. */ UpdatedAt: Timestamp; } export interface ExportAssetToSignedUrlRequestDetails { /** * The unique identifier for the asset that is exported to a signed URL. */ AssetId: Id; /** * The unique identifier for the data set associated with this export job. */ DataSetId: Id; /** * The unique identifier for the revision associated with this export request. */ RevisionId: Id; } export interface ExportAssetToSignedUrlResponseDetails { /** * The unique identifier for the asset associated with this export job. */ AssetId: Id; /** * The unique identifier for the data set associated with this export job. */ DataSetId: Id; /** * The unique identifier for the revision associated with this export response. */ RevisionId: Id; /** * The signed URL for the export request. */ SignedUrl?: __string; /** * The date and time that the signed URL expires, in ISO 8601 format. */ SignedUrlExpiresAt?: Timestamp; } export interface ExportAssetsToS3RequestDetails { /** * The destination for the asset. */ AssetDestinations: ListOfAssetDestinationEntry; /** * The unique identifier for the data set associated with this export job. */ DataSetId: Id; /** * Encryption configuration for the export job. */ Encryption?: ExportServerSideEncryption; /** * The unique identifier for the revision associated with this export request. */ RevisionId: Id; } export interface ExportAssetsToS3ResponseDetails { /** * The destination in Amazon S3 where the asset is exported. */ AssetDestinations: ListOfAssetDestinationEntry; /** * The unique identifier for the data set associated with this export job. */ DataSetId: Id; /** * Encryption configuration of the export job. */ Encryption?: ExportServerSideEncryption; /** * The unique identifier for the revision associated with this export response. */ RevisionId: Id; } export interface ExportRevisionsToS3RequestDetails { /** * The unique identifier for the data set associated with this export job. */ DataSetId: Id; /** * Encryption configuration for the export job. */ Encryption?: ExportServerSideEncryption; /** * The destination for the revision. */ RevisionDestinations: ListOfRevisionDestinationEntry; } export interface ExportRevisionsToS3ResponseDetails { /** * The unique identifier for the data set associated with this export job. */ DataSetId: Id; /** * Encryption configuration of the export job. */ Encryption?: ExportServerSideEncryption; /** * The destination in Amazon S3 where the revision is exported. */ RevisionDestinations: ListOfRevisionDestinationEntry; } export interface ExportServerSideEncryption { /** * The Amazon Resource Name (ARN) of the AWS KMS key you want to use to encrypt the Amazon S3 objects. This parameter is required if you choose aws:kms as an encryption type. */ KmsKeyArn?: __string; /** * The type of server side encryption used for encrypting the objects in Amazon S3. */ Type: ServerSideEncryptionTypes; } export interface GetAssetRequest { /** * The unique identifier for an asset. */ AssetId: __string; /** * The unique identifier for a data set. */ DataSetId: __string; /** * The unique identifier for a revision. */ RevisionId: __string; } export interface GetAssetResponse { /** * The ARN for the asset. */ Arn?: Arn; /** * Information about the asset, including its size. */ AssetDetails?: AssetDetails; /** * The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. */ AssetType?: AssetType; /** * The date and time that the asset was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * The unique identifier for the data set associated with this asset. */ DataSetId?: Id; /** * The unique identifier for the asset. */ Id?: Id; /** * The name of the asset When importing from Amazon S3, the S3 object key is used as the asset name. When exporting to Amazon S3, the asset name is used as default target S3 object key. */ Name?: AssetName; /** * The unique identifier for the revision associated with this asset. */ RevisionId?: Id; /** * The asset ID of the owned asset corresponding to the entitled asset being viewed. This parameter is returned when an asset owner is viewing the entitled copy of its owned asset. */ SourceId?: Id; /** * The date and time that the asset was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface GetDataSetRequest { /** * The unique identifier for a data set. */ DataSetId: __string; } export interface GetDataSetResponse { /** * The ARN for the data set. */ Arn?: Arn; /** * The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. */ AssetType?: AssetType; /** * The date and time that the data set was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * The description for the data set. */ Description?: Description; /** * The unique identifier for the data set. */ Id?: Id; /** * The name of the data set. */ Name?: Name; /** * A property that defines the data set as OWNED by the account (for providers) or ENTITLED to the account (for subscribers). */ Origin?: Origin; /** * If the origin of this data set is ENTITLED, includes the details for the product on AWS Marketplace. */ OriginDetails?: OriginDetails; /** * The data set ID of the owned data set corresponding to the entitled data set being viewed. This parameter is returned when a data set owner is viewing the entitled copy of its owned data set. */ SourceId?: Id; /** * The tags for the data set. */ Tags?: MapOf__string; /** * The date and time that the data set was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface GetEventActionRequest { /** * The unique identifier for the event action. */ EventActionId: __string; } export interface GetEventActionResponse { /** * What occurs after a certain event. */ Action?: Action; /** * The ARN for the event action. */ Arn?: Arn; /** * The date and time that the event action was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * What occurs to start an action. */ Event?: Event; /** * The unique identifier for the event action. */ Id?: Id; /** * The date and time that the event action was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface GetJobRequest { /** * The unique identifier for a job. */ JobId: __string; } export interface GetJobResponse { /** * The ARN for the job. */ Arn?: Arn; /** * The date and time that the job was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * Details about the job. */ Details?: ResponseDetails; /** * The errors associated with jobs. */ Errors?: ListOfJobError; /** * The unique identifier for the job. */ Id?: Id; /** * The state of the job. */ State?: State; /** * The job type. */ Type?: Type; /** * The date and time that the job was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface GetRevisionRequest { /** * The unique identifier for a data set. */ DataSetId: __string; /** * The unique identifier for a revision. */ RevisionId: __string; } export interface GetRevisionResponse { /** * The ARN for the revision */ Arn?: Arn; /** * An optional comment about the revision. */ Comment?: __stringMin0Max16384; /** * The date and time that the revision was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * The unique identifier for the data set associated with this revision. */ DataSetId?: Id; /** * To publish a revision to a data set in a product, the revision must first be finalized. Finalizing a revision tells AWS Data Exchange that your changes to the assets in the revision are complete. After it's in this read-only state, you can publish the revision to your products. Finalized revisions can be published through the AWS Data Exchange console or the AWS Marketplace Catalog API, using the StartChangeSet AWS Marketplace Catalog API action. When using the API, revisions are uniquely identified by their ARN. */ Finalized?: __boolean; /** * The unique identifier for the revision. */ Id?: Id; /** * The revision ID of the owned revision corresponding to the entitled revision being viewed. This parameter is returned when a revision owner is viewing the entitled copy of its owned revision. */ SourceId?: Id; /** * The tags for the revision. */ Tags?: MapOf__string; /** * The date and time that the revision was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export type Id = string; export interface ImportAssetFromSignedUrlJobErrorDetails { AssetName: AssetName; } export interface ImportAssetFromSignedUrlRequestDetails { /** * The name of the asset. When importing from Amazon S3, the S3 object key is used as the asset name. */ AssetName: AssetName; /** * The unique identifier for the data set associated with this import job. */ DataSetId: Id; /** * The Base64-encoded Md5 hash for the asset, used to ensure the integrity of the file at that location. */ Md5Hash: __stringMin24Max24PatternAZaZ094AZaZ092AZaZ093; /** * The unique identifier for the revision associated with this import request. */ RevisionId: Id; } export interface ImportAssetFromSignedUrlResponseDetails { /** * The name for the asset associated with this import response. */ AssetName: AssetName; /** * The unique identifier for the data set associated with this import job. */ DataSetId: Id; /** * The Base64-encoded Md5 hash for the asset, used to ensure the integrity of the file at that location. */ Md5Hash?: __stringMin24Max24PatternAZaZ094AZaZ092AZaZ093; /** * The unique identifier for the revision associated with this import response. */ RevisionId: Id; /** * The signed URL. */ SignedUrl?: __string; /** * The time and date at which the signed URL expires, in ISO 8601 format. */ SignedUrlExpiresAt?: Timestamp; } export interface ImportAssetsFromS3RequestDetails { /** * Is a list of S3 bucket and object key pairs. */ AssetSources: ListOfAssetSourceEntry; /** * The unique identifier for the data set associated with this import job. */ DataSetId: Id; /** * The unique identifier for the revision associated with this import request. */ RevisionId: Id; } export interface ImportAssetsFromS3ResponseDetails { /** * Is a list of Amazon S3 bucket and object key pairs. */ AssetSources: ListOfAssetSourceEntry; /** * The unique identifier for the data set associated with this import job. */ DataSetId: Id; /** * The unique identifier for the revision associated with this import response. */ RevisionId: Id; } export interface JobEntry { /** * The ARN for the job. */ Arn: Arn; /** * The date and time that the job was created, in ISO 8601 format. */ CreatedAt: Timestamp; /** * Details of the operation to be performed by the job, such as export destination details or import source details. */ Details: ResponseDetails; /** * Errors for jobs. */ Errors?: ListOfJobError; /** * The unique identifier for the job. */ Id: Id; /** * The state of the job. */ State: State; /** * The job type. */ Type: Type; /** * The date and time that the job was last updated, in ISO 8601 format. */ UpdatedAt: Timestamp; } export interface JobError { /** * The code for the job error. */ Code: Code; Details?: Details; /** * The name of the limit that was reached. */ LimitName?: JobErrorLimitName; /** * The value of the exceeded limit. */ LimitValue?: __double; /** * The message related to the job error. */ Message: __string; /** * The unique identifier for the resource related to the error. */ ResourceId?: __string; /** * The type of resource related to the error. */ ResourceType?: JobErrorResourceTypes; } export type JobErrorLimitName = "Assets per revision"|"Asset size in GB"|string; export type JobErrorResourceTypes = "REVISION"|"ASSET"|"DATA_SET"|string; export interface ListDataSetRevisionsRequest { /** * The unique identifier for a data set. */ DataSetId: __string; /** * The maximum number of results returned by a single call. */ MaxResults?: MaxResults; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: __string; } export interface ListDataSetRevisionsResponse { /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: NextToken; /** * The asset objects listed by the request. */ Revisions?: ListOfRevisionEntry; } export interface ListDataSetsRequest { /** * The maximum number of results returned by a single call. */ MaxResults?: MaxResults; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: __string; /** * A property that defines the data set as OWNED by the account (for providers) or ENTITLED to the account (for subscribers). */ Origin?: __string; } export interface ListDataSetsResponse { /** * The data set objects listed by the request. */ DataSets?: ListOfDataSetEntry; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: NextToken; } export interface ListEventActionsRequest { /** * The unique identifier for the event source. */ EventSourceId?: __string; /** * The maximum number of results returned by a single call. */ MaxResults?: MaxResults; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: __string; } export interface ListEventActionsResponse { /** * The event action objects listed by the request. */ EventActions?: ListOfEventActionEntry; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: NextToken; } export interface ListJobsRequest { /** * The unique identifier for a data set. */ DataSetId?: __string; /** * The maximum number of results returned by a single call. */ MaxResults?: MaxResults; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: __string; /** * The unique identifier for a revision. */ RevisionId?: __string; } export interface ListJobsResponse { /** * The jobs listed by the request. */ Jobs?: ListOfJobEntry; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: NextToken; } export type ListOfAssetDestinationEntry = AssetDestinationEntry[]; export type ListOfAssetSourceEntry = AssetSourceEntry[]; export type ListOfRevisionDestinationEntry = RevisionDestinationEntry[]; export interface ListRevisionAssetsRequest { /** * The unique identifier for a data set. */ DataSetId: __string; /** * The maximum number of results returned by a single call. */ MaxResults?: MaxResults; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: __string; /** * The unique identifier for a revision. */ RevisionId: __string; } export interface ListRevisionAssetsResponse { /** * The asset objects listed by the request. */ Assets?: ListOfAssetEntry; /** * The token value retrieved from a previous call to access the next page of results. */ NextToken?: NextToken; } export interface ListTagsForResourceRequest { /** * An Amazon Resource Name (ARN) that uniquely identifies an AWS resource. */ ResourceArn: __string; } export interface ListTagsForResourceResponse { /** * A label that consists of a customer-defined key and an optional value. */ Tags?: MapOf__string; } export type MaxResults = number; export type Name = string; export type NextToken = string; export type Origin = "OWNED"|"ENTITLED"|string; export interface OriginDetails { ProductId: __string; } export interface RequestDetails { /** * Details about the export to signed URL request. */ ExportAssetToSignedUrl?: ExportAssetToSignedUrlRequestDetails; /** * Details about the export to Amazon S3 request. */ ExportAssetsToS3?: ExportAssetsToS3RequestDetails; /** * Details about the export to Amazon S3 request. */ ExportRevisionsToS3?: ExportRevisionsToS3RequestDetails; /** * Details about the import from signed URL request. */ ImportAssetFromSignedUrl?: ImportAssetFromSignedUrlRequestDetails; /** * Details about the import from Amazon S3 request. */ ImportAssetsFromS3?: ImportAssetsFromS3RequestDetails; } export interface ResponseDetails { /** * Details for the export to signed URL response. */ ExportAssetToSignedUrl?: ExportAssetToSignedUrlResponseDetails; /** * Details for the export to Amazon S3 response. */ ExportAssetsToS3?: ExportAssetsToS3ResponseDetails; /** * Details for the export revisions to Amazon S3 response. */ ExportRevisionsToS3?: ExportRevisionsToS3ResponseDetails; /** * Details for the import from signed URL response. */ ImportAssetFromSignedUrl?: ImportAssetFromSignedUrlResponseDetails; /** * Details for the import from Amazon S3 response. */ ImportAssetsFromS3?: ImportAssetsFromS3ResponseDetails; } export interface RevisionDestinationEntry { /** * The S3 bucket that is the destination for the assets in the revision. */ Bucket: __string; /** * A string representing the pattern for generated names of the individual assets in the revision. For more information about key patterns, see Key patterns when exporting revisions. */ KeyPattern?: __string; /** * The unique identifier for the revision. */ RevisionId: Id; } export interface RevisionEntry { /** * The ARN for the revision. */ Arn: Arn; /** * An optional comment about the revision. */ Comment?: __stringMin0Max16384; /** * The date and time that the revision was created, in ISO 8601 format. */ CreatedAt: Timestamp; /** * The unique identifier for the data set associated with this revision. */ DataSetId: Id; /** * To publish a revision to a data set in a product, the revision must first be finalized. Finalizing a revision tells AWS Data Exchange that your changes to the assets in the revision are complete. After it's in this read-only state, you can publish the revision to your products. Finalized revisions can be published through the AWS Data Exchange console or the AWS Marketplace Catalog API, using the StartChangeSet AWS Marketplace Catalog API action. When using the API, revisions are uniquely identified by their ARN. */ Finalized?: __boolean; /** * The unique identifier for the revision. */ Id: Id; /** * The revision ID of the owned revision corresponding to the entitled revision being viewed. This parameter is returned when a revision owner is viewing the entitled copy of its owned revision. */ SourceId?: Id; /** * The date and time that the revision was last updated, in ISO 8601 format. */ UpdatedAt: Timestamp; } export interface RevisionPublished { DataSetId: Id; } export interface S3SnapshotAsset { /** * The size of the S3 object that is the object. */ Size: __doubleMin0; } export type ServerSideEncryptionTypes = "aws:kms"|"AES256"|string; export interface StartJobRequest { /** * The unique identifier for a job. */ JobId: __string; } export interface StartJobResponse { } export type State = "WAITING"|"IN_PROGRESS"|"ERROR"|"COMPLETED"|"CANCELLED"|"TIMED_OUT"|string; export interface TagResourceRequest { /** * An Amazon Resource Name (ARN) that uniquely identifies an AWS resource. */ ResourceArn: __string; /** * A label that consists of a customer-defined key and an optional value. */ Tags: MapOf__string; } export type Timestamp = Date; export type Type = "IMPORT_ASSETS_FROM_S3"|"IMPORT_ASSET_FROM_SIGNED_URL"|"EXPORT_ASSETS_TO_S3"|"EXPORT_ASSET_TO_SIGNED_URL"|"EXPORT_REVISIONS_TO_S3"|string; export interface UntagResourceRequest { /** * An Amazon Resource Name (ARN) that uniquely identifies an AWS resource. */ ResourceArn: __string; /** * The key tags. */ TagKeys: ListOf__string; } export interface UpdateAssetRequest { /** * The unique identifier for an asset. */ AssetId: __string; /** * The unique identifier for a data set. */ DataSetId: __string; /** * The name of the asset. When importing from Amazon S3, the S3 object key is used as the asset name. When exporting to Amazon S3, the asset name is used as default target S3 object key. */ Name: AssetName; /** * The unique identifier for a revision. */ RevisionId: __string; } export interface UpdateAssetResponse { /** * The ARN for the asset. */ Arn?: Arn; /** * Information about the asset, including its size. */ AssetDetails?: AssetDetails; /** * The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. */ AssetType?: AssetType; /** * The date and time that the asset was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * The unique identifier for the data set associated with this asset. */ DataSetId?: Id; /** * The unique identifier for the asset. */ Id?: Id; /** * The name of the asset When importing from Amazon S3, the S3 object key is used as the asset name. When exporting to Amazon S3, the asset name is used as default target S3 object key. */ Name?: AssetName; /** * The unique identifier for the revision associated with this asset. */ RevisionId?: Id; /** * The asset ID of the owned asset corresponding to the entitled asset being viewed. This parameter is returned when an asset owner is viewing the entitled copy of its owned asset. */ SourceId?: Id; /** * The date and time that the asset was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface UpdateDataSetRequest { /** * The unique identifier for a data set. */ DataSetId: __string; /** * The description for the data set. */ Description?: Description; /** * The name of the data set. */ Name?: Name; } export interface UpdateDataSetResponse { /** * The ARN for the data set. */ Arn?: Arn; /** * The type of file your data is stored in. Currently, the supported asset type is S3_SNAPSHOT. */ AssetType?: AssetType; /** * The date and time that the data set was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * The description for the data set. */ Description?: Description; /** * The unique identifier for the data set. */ Id?: Id; /** * The name of the data set. */ Name?: Name; /** * A property that defines the data set as OWNED by the account (for providers) or ENTITLED to the account (for subscribers). */ Origin?: Origin; /** * If the origin of this data set is ENTITLED, includes the details for the product on AWS Marketplace. */ OriginDetails?: OriginDetails; /** * The data set ID of the owned data set corresponding to the entitled data set being viewed. This parameter is returned when a data set owner is viewing the entitled copy of its owned data set. */ SourceId?: Id; /** * The date and time that the data set was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface UpdateEventActionRequest { /** * What occurs after a certain event. */ Action?: Action; /** * The unique identifier for the event action. */ EventActionId: __string; } export interface UpdateEventActionResponse { /** * What occurs after a certain event. */ Action?: Action; /** * The ARN for the event action. */ Arn?: Arn; /** * The date and time that the event action was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * What occurs to start an action. */ Event?: Event; /** * The unique identifier for the event action. */ Id?: Id; /** * The date and time that the event action was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export interface UpdateRevisionRequest { /** * An optional comment about the revision. */ Comment?: __stringMin0Max16384; /** * The unique identifier for a data set. */ DataSetId: __string; /** * Finalizing a revision tells AWS Data Exchange that your changes to the assets in the revision are complete. After it's in this read-only state, you can publish the revision to your products. */ Finalized?: __boolean; /** * The unique identifier for a revision. */ RevisionId: __string; } export interface UpdateRevisionResponse { /** * The ARN for the revision. */ Arn?: Arn; /** * An optional comment about the revision. */ Comment?: __stringMin0Max16384; /** * The date and time that the revision was created, in ISO 8601 format. */ CreatedAt?: Timestamp; /** * The unique identifier for the data set associated with this revision. */ DataSetId?: Id; /** * To publish a revision to a data set in a product, the revision must first be finalized. Finalizing a revision tells AWS Data Exchange that changes to the assets in the revision are complete. After it's in this read-only state, you can publish the revision to your products. Finalized revisions can be published through the AWS Data Exchange console or the AWS Marketplace Catalog API, using the StartChangeSet AWS Marketplace Catalog API action. When using the API, revisions are uniquely identified by their ARN. */ Finalized?: __boolean; /** * The unique identifier for the revision. */ Id?: Id; /** * The revision ID of the owned revision corresponding to the entitled revision being viewed. This parameter is returned when a revision owner is viewing the entitled copy of its owned revision. */ SourceId?: Id; /** * The date and time that the revision was last updated, in ISO 8601 format. */ UpdatedAt?: Timestamp; } export type __boolean = boolean; export type __double = number; export type __doubleMin0 = number; export type ListOfAssetEntry = AssetEntry[]; export type ListOfDataSetEntry = DataSetEntry[]; export type ListOfEventActionEntry = EventActionEntry[]; export type ListOfJobEntry = JobEntry[]; export type ListOfJobError = JobError[]; export type ListOfRevisionEntry = RevisionEntry[]; export type ListOf__string = __string[]; export type MapOf__string = {[key: string]: __string}; export type __string = string; export type __stringMin0Max16384 = string; export type __stringMin24Max24PatternAZaZ094AZaZ092AZaZ093 = string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2017-07-25"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the DataExchange client. */ export import Types = DataExchange; } export = DataExchange;
the_stack
import { usGovernmentAuthentication, authentication, v32Authentication, v31Authentication, } from '../../constants/authEndpoints'; import { createBotFrameworkAuthenticationMiddleware } from './botFrameworkAuthentication'; const mockGetKey = jest.fn().mockResolvedValue(`openIdMetadataKey`); jest.mock('../../utils/openIdMetadata', () => ({ OpenIdMetadata: jest.fn().mockImplementation(() => ({ getKey: mockGetKey, })), })); let mockDecode; let mockVerify; jest.mock('jsonwebtoken', () => ({ get decode() { return mockDecode; }, get verify() { return mockVerify; }, })); describe('botFrameworkAuthenticationMiddleware', () => { const authMiddleware = createBotFrameworkAuthenticationMiddleware(jest.fn().mockResolvedValue(true)); const mockNext: any = jest.fn(() => null); const mockStatus = jest.fn(() => null); const mockEnd = jest.fn(() => null); let mockPayload; beforeEach(() => { mockNext.mockClear(); mockEnd.mockClear(); mockStatus.mockClear(); mockDecode = jest.fn(() => ({ header: { kid: 'someKeyId', }, payload: mockPayload, })); mockVerify = jest.fn(() => 'verifiedJwt'); mockGetKey.mockClear(); }); it('should call the next middleware and return if there is no auth header', async () => { const mockHeader = jest.fn(() => false); const req: any = { header: mockHeader }; const result = await authMiddleware(req, null, mockNext); expect(result).toBeUndefined(); expect(mockHeader).toHaveBeenCalled(); expect(mockNext).toHaveBeenCalled(); }); it('should return a 401 if the token is not provided in the header', async () => { mockDecode = jest.fn(() => null); const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockHeader).toHaveBeenCalled(); expect(mockDecode).toHaveBeenCalledWith('someToken', { complete: true }); expect(mockStatus).toHaveBeenCalledWith(401); expect(mockEnd).toHaveBeenCalled(); }); it('should return a 401 if a government bot provides a token in an unknown format', async () => { mockPayload = { aud: usGovernmentAuthentication.botTokenAudience, ver: '99.9', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockStatus).toHaveBeenCalledWith(401); expect(mockEnd).toHaveBeenCalled(); }); it('should authenticate with a v1.0 gov token', async () => { mockPayload = { aud: usGovernmentAuthentication.botTokenAudience, ver: '1.0', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: usGovernmentAuthentication.botTokenAudience, clockTolerance: 300, issuer: usGovernmentAuthentication.tokenIssuerV1, }); expect(req.jwt).toBe('verifiedJwt'); expect(mockNext).toHaveBeenCalled(); }); it('should authenticate with a v2.0 gov token', async () => { mockPayload = { aud: usGovernmentAuthentication.botTokenAudience, ver: '2.0', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: usGovernmentAuthentication.botTokenAudience, clockTolerance: 300, issuer: usGovernmentAuthentication.tokenIssuerV2, }); expect(req.jwt).toBe('verifiedJwt'); expect(mockNext).toHaveBeenCalled(); }); it('should return a 401 if verifying a gov jwt token fails', async () => { mockPayload = { aud: usGovernmentAuthentication.botTokenAudience, ver: '1.0', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; mockVerify = jest.fn(() => { throw new Error('unverifiedJwt'); }); const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: usGovernmentAuthentication.botTokenAudience, clockTolerance: 300, issuer: usGovernmentAuthentication.tokenIssuerV1, }); expect(req.jwt).toBeUndefined(); expect(mockNext).not.toHaveBeenCalled(); expect(mockStatus).toHaveBeenCalledWith(401); expect(mockEnd).toHaveBeenCalled(); }); it(`should return a 500 if a bot's token can't be retrieved from openId metadata`, async () => { mockPayload = { aud: 'not gov', ver: '1.0', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; // key should come back as falsy mockGetKey.mockResolvedValueOnce(null); const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockStatus).toHaveBeenCalledWith(500); expect(mockEnd).toHaveBeenCalled(); }); it('should return a 401 if a bot provides a token in an unknown format', async () => { mockPayload = { aud: 'not gov', ver: '99.9', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockStatus).toHaveBeenCalledWith(401); expect(mockEnd).toHaveBeenCalled(); expect(mockNext).not.toHaveBeenCalled(); }); it('should authenticate with a v1.0 token', async () => { mockPayload = { aud: 'not gov', ver: '1.0', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: authentication.botTokenAudience, clockTolerance: 300, issuer: v32Authentication.tokenIssuerV1, }); expect(req.jwt).toBe('verifiedJwt'); expect(mockNext).toHaveBeenCalled(); }); it('should authenticate with a v2.0 token', async () => { mockPayload = { aud: 'not gov', ver: '2.0', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: authentication.botTokenAudience, clockTolerance: 300, issuer: v32Authentication.tokenIssuerV2, }); expect(req.jwt).toBe('verifiedJwt'); expect(mockNext).toHaveBeenCalled(); }); it('should attempt authentication with v3.1 characteristics if v3.2 auth fails', async () => { mockPayload = { aud: 'not gov', ver: '1.0', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; // verification attempt with v3.2 token characteristics should fail mockVerify.mockImplementationOnce(() => { throw new Error('unverifiedJwt'); }); const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockVerify).toHaveBeenCalledTimes(2); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: authentication.botTokenAudience, clockTolerance: 300, issuer: v32Authentication.tokenIssuerV1, }); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: authentication.botTokenAudience, clockTolerance: 300, issuer: v31Authentication.tokenIssuer, }); expect(req.jwt).toBe('verifiedJwt'); expect(mockNext).toHaveBeenCalled(); }); it('should return a 401 if auth with both v3.1 & v3.2 token characteristics fail', async () => { mockPayload = { aud: 'not gov', ver: '1.0', }; const mockHeader = jest.fn(() => 'Bearer someToken'); const req: any = { header: mockHeader }; const res: any = { status: mockStatus, end: mockEnd, }; mockVerify // verification attempt with v3.2 token characteristics should fail .mockImplementationOnce(() => { throw new Error('unverifiedJwt'); }) // second attempt with v3.1 token characteristics should also fail .mockImplementationOnce(() => { throw new Error('unverifiedJwt'); }); const result = await authMiddleware(req, res, mockNext); expect(result).toBeUndefined(); expect(mockVerify).toHaveBeenCalledTimes(2); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: authentication.botTokenAudience, clockTolerance: 300, issuer: v32Authentication.tokenIssuerV1, }); expect(mockVerify).toHaveBeenCalledWith('someToken', 'openIdMetadataKey', { audience: authentication.botTokenAudience, clockTolerance: 300, issuer: v31Authentication.tokenIssuer, }); expect(mockStatus).toHaveBeenCalledWith(401); expect(mockEnd).toHaveBeenCalled(); expect(req.jwt).toBeUndefined(); expect(mockNext).not.toHaveBeenCalled(); }); });
the_stack
import React from 'react'; import { LargeMessage, notify, notifDelete } from 'giu'; import { merge, addLast, omit, updateIn, setIn, mergeIn } from 'timm'; import { v4 as uuidv4 } from 'uuid'; import classnames from 'classnames'; import axios from 'axios'; import type { Config, Key, Keys, Translation } from '../types'; import { localGet, localSet } from '../gral/localStorage'; import { UNSCOPED } from '../gral/constants'; import { simplifyStringWithCache } from '../gral/helpers'; import TranslationTable from './110-TranslationTable'; import Toolbar from './105-Toolbar'; const POLL_INTERVAL = 5e3; const API_TIMEOUT = 20e3; // ============================================== // Declarations // ============================================== type Props = { scope?: string | null; apiUrl: string; height: number /* table content height in pixels (-1 sets it to unlimited; 0 expands it to use the full viewport) */; }; type State = { config: Config | null; langs: string[]; fetching: boolean; parsing: boolean; fatalError: boolean; keys: Keys; scope: string | undefined; filter: string; tUpdated: number | null; selectedKeyId: string | null; quickFind: string; }; // ============================================== // Component // ============================================== class Translator extends React.Component<Props, State> { state: State = { config: null, langs: [] as string[], fetching: false, parsing: false, fatalError: false, keys: {} as Keys, scope: this.props.scope === null ? UNSCOPED : this.props.scope, filter: 'ALL' as string, tUpdated: null, selectedKeyId: null, quickFind: '', }; pollInterval!: number; api = axios.create({ baseURL: this.props.apiUrl, timeout: API_TIMEOUT }); componentDidMount() { this.fetchData(); this.pollInterval = setInterval(this.fetchData, POLL_INTERVAL); } componentWillUnmount() { clearInterval(this.pollInterval); } // ============================================== render() { const { parsing } = this.state; const { keys, allScopes } = this.processData(); return ( <div className={classnames('mady-translator', { parsing, 'full-height': this.props.height === 0, })} > {this.renderToolbar(allScopes)} {this.renderTable(keys, allScopes)} </div> ); } renderToolbar(allScopes: string[]) { return ( <Toolbar quickFind={this.state.quickFind} showScopeMenu={this.props.scope === undefined} scopes={allScopes} scope={this.state.scope} filter={this.state.filter} onClickParse={this.onClickParse} onClickDeleteUnused={this.onClickDeleteUnused} onChangeQuickFind={(quickFind: string) => this.setState({ quickFind })} onChangeScope={(scope: string | undefined) => this.setState({ scope })} onChangeFilter={(filter: string) => this.setState({ filter })} /> ); } renderTable(keys: Keys, allScopes: string[]) { if (this.state.fatalError) return ( <LargeMessage> The translation service is currently unavailable. Please try again later! </LargeMessage> ); const { tUpdated, config, langs, parsing } = this.state; if (tUpdated == null || config == null) return <LargeMessage>Loading data…</LargeMessage>; const shownKeyIds = Object.keys(keys); return ( <TranslationTable config={config!} langs={langs} keys={keys} shownKeyIds={shownKeyIds} scopes={allScopes} selectedKeyId={this.state.selectedKeyId} parsing={parsing} height={this.props.height} onAddLang={this.onAddLang} onRemoveLang={this.onRemoveLang} onSelectKey={this.onSelectKey} onDeleteKey={this.onDeleteKey} onDeleteTranslation={this.onDeleteTranslation} onUpdateTranslation={this.onUpdateTranslation} onCreateTranslation={this.onCreateTranslation} autoTranslate={this.autoTranslate} /> ); } // ============================================== onClickParse = async () => { try { this.setState({ parsing: true }); await this.api.get('/parse'); await this.fetchData(); } catch (err) { notify({ type: 'error', icon: 'code', title: 'Parse failed', msg: 'Check the console...', }); throw err; } finally { this.setState({ parsing: false }); } }; onClickDeleteUnused = async () => { try { await this.api.get('/deleteUnused'); await this.fetchData(); } catch (err) { notify({ type: 'error', icon: 'code', title: 'Delete unused failed', msg: 'Check the console...', }); throw err; } }; onAddLang = (lang: string) => { const langs = addLast(this.state.langs, lang); localSet('langs', langs); this.setState({ langs }, () => this.fetchData({ force: true })); }; onRemoveLang = (lang: string) => { const langs = this.state.langs.filter((o) => o !== lang); localSet('langs', langs); this.setState({ langs }); }; onSelectKey = (selectedKeyId: string) => { this.setState({ selectedKeyId }); }; onDeleteKey = async (id: string) => { const { keys } = this.state; if (!keys[id]) throw new Error(`Cannot delete key (not found): ${id}`); this.mutateData({ optimisticState: { keys: omit(keys, id) }, description: 'Delete message', url: `/key/${id}`, method: 'patch', body: { isDeleted: true }, icon: 'times', }); }; onDeleteTranslation = async (keyId: string, lang: string) => { const { keys } = this.state; const key = keys[keyId]; if (!key) throw new Error(`Cannot delete translation (key not found): ${keyId}`); const translation = key.translations[lang]; if (!translation) throw new Error( `Cannot delete translation (translation for ${lang} not found): ${keyId}` ); const { id } = translation; this.mutateData({ optimisticState: { keys: updateIn(keys, [keyId, 'translations'], (o) => omit(o, lang) ) as Keys, }, description: 'Delete translation', url: `/translation/${id}`, method: 'patch', body: { isDeleted: true }, icon: 'times', }); }; onUpdateTranslation = async ( keyId: string, lang: string, updates: Partial<Translation> ) => { const { keys } = this.state; const key = keys[keyId]; if (!key) throw new Error(`Cannot update translation (key not found): ${keyId}`); const translation = key.translations[lang]; if (!translation) throw new Error( `Cannot update translation (translation for ${lang} not found): ${keyId}` ); const { id } = translation; this.mutateData({ optimisticState: { keys: mergeIn(keys, [keyId, 'translations', lang], updates) as Keys, }, description: 'Update translation', url: `/translation/${id}`, method: 'patch', body: updates, icon: 'pencil-alt', }); }; onCreateTranslation = async (keyId: string, lang: string, text: string) => { const { keys } = this.state; const key = keys[keyId]; if (!key) throw new Error(`Cannot create translation (key not found): ${keyId}`); const translation = { id: uuidv4(), lang, translation: text, keyId, }; this.mutateData({ optimisticState: { keys: setIn(keys, [keyId, 'translations', lang], translation) as Keys, }, description: 'Create translation', url: `/translation`, method: 'post', body: translation, icon: 'pencil-alt', }); }; // ============================================== fetchData = async ({ force }: { force?: boolean } = {}) => { if (this.state.fetching || this.state.fatalError) return; try { // Fetch config if (!this.state.config) { this.setState({ fetching: true }); const config = await this.fetchConfig(); const langs = calcInitialLangs(config); this.setState({ config, langs }); await delay(0); // make sure state has already been updated } // Fetch only update time, check it and bail out if // there's nothing new const curTUpdated = this.state.tUpdated; if (!force && curTUpdated != null) { const tUpdated = await this.fetchTUpdated(); if (tUpdated == null) return; if (tUpdated <= curTUpdated) return; } // Fetch data if (!this.state.fetching) this.setState({ fetching: true }); const { keys, tUpdated } = await this.fetchTranslations(); this.setState({ keys, tUpdated }); } finally { if (this.state.fetching) this.setState({ fetching: false }); } }; fetchConfig = async () => { try { const res = await this.api.get('/config'); return res.data as Config; } catch (err) { notify({ type: 'error', icon: 'language', title: "Could not fetch Mady's config", msg: 'Please try again later!', }); this.setState({ fatalError: true }); throw err; } }; fetchTUpdated = async () => { try { const res = await this.api.get('/tUpdated'); const { tUpdated } = res.data; notifDelete('tUpdateError'); return tUpdated as number; } catch (err) { notifDelete('tUpdateError'); notify({ id: 'tUpdateError', type: 'warn', icon: 'wifi', title: 'Having connectivity problems', msg: 'Please check your network!', }); return null; } }; fetchTranslations = async () => { try { const { langs, config } = this.state; const { scope } = this.props; const langParam = langs.join(',') || config!.originalLang; let url = `/keysAndTranslations/${langParam}`; if (scope !== undefined) url += `?scope=${scope || ''}`; const res = await this.api.get(url); const keysArr = res.data.keys as Key[]; const tUpdated = res.data.tUpdated as number; // Prepare keys keysArr.sort(keyComparator); const keys: Keys = {}; keysArr.forEach((key) => { if (key.scope == null) key.scope = UNSCOPED; keys[key.id] = key; }); return { keys, tUpdated }; } catch (err) { notify({ type: 'error', icon: 'comment', iconFamily: 'far', title: 'Could not fetch translations', msg: 'Please try again later!', }); throw err; } }; autoTranslate = async (lang: string, text: string) => { try { const res = await this.api.post('/autoTranslate', { lang, text }); return res.data; } catch (err) { notify({ type: 'error', icon: 'google', iconFamily: 'fab', title: 'Cannot autotranslate now', msg: 'Please try again later!', }); return null; } }; // Very simple and optimistic mutator (does not handle queues, etc -- a far cry // from GraphQL! But SIMPLE) mutateData = async (options: { optimisticState: Partial<State>; description: string; url: string; method: string; body?: any; icon?: string; iconFamily?: string; }) => { const { optimisticState, url, method } = options; const originalState = this.state; if (optimisticState) this.setState(optimisticState as State); try { const api: any = this.api; ['post', 'put', 'patch'].indexOf(method) >= 0 ? await api[method](url, options.body) : await api[method](url); } catch (err) { this.setState(originalState); notify({ type: 'error', icon: options.icon, iconFamily: options.iconFamily, title: `${options.description} failed`, msg: 'Please try again later!', }); } }; // ============================================== processData = () => { const targetScope = this.state.scope; const quickFind = simplifyStringWithCache(this.state.quickFind); const { langs, filter } = this.state; const keys0 = this.state.keys; const keys: Keys = {}; const ids = Object.keys(keys0); let prevKey = null; const allScopesObj: Record<string, boolean> = {}; for (let i = 0; i < ids.length; i++) { const id = ids[i]; let key = keys0[id]; // Apply filters: scope, quick-find, filter const { scope } = key; allScopesObj[scope] = true; if (targetScope != null && scope !== targetScope) continue; if (quickFind && !this.matchesQuickFind(key, quickFind, langs)) continue; const shownTranslations = langs .map((lang) => key.translations[lang]) .filter((o) => o != null && o.translation); const isUnused = key.unusedSince != null; const isTranslated = shownTranslations.length >= langs.length; const isFuzzy = shownTranslations.filter((o) => o.fuzzy).length > 0; if (filter === 'UNUSED' && !isUnused) continue; if (filter === 'FUZZY' && !isFuzzy) continue; if (filter === 'UNTRANSLATED' && isTranslated) continue; // Everything OK, add to list key = merge(key, { seqStarts: !prevKey || !key.seq || key.scope !== prevKey.scope || key.context !== prevKey.context, isUnused, isTranslated, isFuzzy, }); prevKey = key; keys[id] = key; } return { keys, allScopes: Object.keys(allScopesObj) }; }; matchesQuickFind = (key: Key, find: string, langs: string[]) => { const simplify = simplifyStringWithCache; if (key.scope && simplify(key.scope).indexOf(find) >= 0) return true; if (key.context && simplify(key.context).indexOf(find) >= 0) return true; if (key.text && simplify(key.text).indexOf(find) >= 0) return true; const { translations } = key; for (let i = 0; i < langs.length; i++) { const text = translations[langs[i]]?.translation; if (text && simplify(text).indexOf(find) >= 0) return true; } return false; }; } // ============================================== const calcInitialLangs = (config: Config) => { const sysLangs = config.langs; let langs = localGet('langs') as string[]; if (langs == null) { langs = config.langs.filter((o) => o !== config.originalLang); if (!langs.length) langs = config.langs; } langs = langs.filter((o) => sysLangs.indexOf(o) >= 0); localSet('langs', langs); return langs; }; const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); // Sort keys by scope > context > seq > text > id const keyComparator = (a: Key, b: Key) => { if (a == null || b == null) return 0; const aScope = a.scope ? simplifyStringWithCache(a.scope) : ''; const bScope = b.scope ? simplifyStringWithCache(b.scope) : ''; if (aScope && !bScope) return -1; if (!aScope && bScope) return +1; if (aScope !== bScope) return aScope < bScope ? -1 : +1; const aContext = a.context ? simplifyStringWithCache(a.context) : ''; const bContext = b.context ? simplifyStringWithCache(b.context) : ''; if (aContext !== bContext) return aContext < bContext ? -1 : +1; const aSeq = a.seq; const bSeq = b.seq; if (aSeq != null && bSeq != null && aSeq !== bSeq) { return aSeq < bSeq ? -1 : +1; } const aText = a.text ? simplifyStringWithCache(a.text) : ''; const bText = b.text ? simplifyStringWithCache(b.text) : ''; if (aText !== bText) return aText < bText ? -1 : +1; return comparator(a.id, b.id); }; const comparator = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); // ============================================== // Public // ============================================== export default Translator;
the_stack
import { CreateContextAndInputs, LogCallback, ResultCallback } from '../src/Context'; import { Context } from "../src/public/Interfaces"; import { FunctionInfo } from '../src/FunctionInfo'; import { AzureFunctionsRpcMessages as rpc } from '../azure-functions-language-worker-protobuf/src/rpc'; import * as sinon from 'sinon'; import { expect } from 'chai'; import 'mocha'; import { isFunction } from 'util'; const timerTriggerInput: rpc.IParameterBinding = { name: "myTimer", data: { json: JSON.stringify({ "Schedule":{ }, "ScheduleStatus": { "Last":"2016-10-04T10:15:00+00:00", "LastUpdated":"2016-10-04T10:16:00+00:00", "Next":"2016-10-04T10:20:00+00:00" }, "IsPastDue":false }) } }; describe('Context', () => { let _context: Context; let _logger: any; let _resultCallback: any; beforeEach(() => { let info: FunctionInfo = new FunctionInfo({ name: 'test' }); let msg: rpc.IInvocationRequest = { functionId: 'id', invocationId: '1', inputData: [] }; _logger = sinon.spy(); _resultCallback = sinon.spy(); let v1WorkerBehavior = false; let { context, inputs } = CreateContextAndInputs(info, msg, _logger, _resultCallback, v1WorkerBehavior); _context = context; }); it ('camelCases timer trigger input when appropriate', async () => { var msg: rpc.IInvocationRequest = <rpc.IInvocationRequest> { functionId: 'id', invocationId: '1', inputData: [timerTriggerInput] }; let info: FunctionInfo = new FunctionInfo({ name: 'test', bindings: { myTimer: { type: "timerTrigger", direction: 0, dataType: 0 } } }); // Node.js Worker V2 behavior let workerV2Outputs = CreateContextAndInputs(info, msg, _logger, _resultCallback, false); let myTimerWorkerV2 = workerV2Outputs.inputs[0]; expect(myTimerWorkerV2.schedule).to.be.empty; expect(myTimerWorkerV2.scheduleStatus.last).to.equal("2016-10-04T10:15:00+00:00"); expect(myTimerWorkerV2.scheduleStatus.lastUpdated).to.equal("2016-10-04T10:16:00+00:00"); expect(myTimerWorkerV2.scheduleStatus.next).to.equal("2016-10-04T10:20:00+00:00"); expect(myTimerWorkerV2.isPastDue).to.equal(false); // Node.js Worker V1 behavior let workerV1Outputs = CreateContextAndInputs(info, msg, _logger, _resultCallback, true); let myTimerWorkerV1 = workerV1Outputs.inputs[0]; expect(myTimerWorkerV1.Schedule).to.be.empty; expect(myTimerWorkerV1.ScheduleStatus.Last).to.equal("2016-10-04T10:15:00+00:00"); expect(myTimerWorkerV1.ScheduleStatus.LastUpdated).to.equal("2016-10-04T10:16:00+00:00"); expect(myTimerWorkerV1.ScheduleStatus.Next).to.equal("2016-10-04T10:20:00+00:00"); expect(myTimerWorkerV1.IsPastDue).to.equal(false); }); it ('Does not add sys to bindingData for non-http', async () => { var msg: rpc.IInvocationRequest = <rpc.IInvocationRequest> { functionId: 'id', invocationId: '1', inputData: [timerTriggerInput] }; let info: FunctionInfo = new FunctionInfo({ name: 'test', bindings: { req: { type: "http", direction: 0, dataType: 1 } } }); let { context } = CreateContextAndInputs(info, msg, _logger, _resultCallback, false); expect(context.bindingData.sys).to.be.undefined; expect(context.bindingData.invocationId).to.equal("1"); expect(context.invocationId).to.equal("1"); }); it ('Adds correct sys properties for bindingData and http', async () => { var inputDataValue: rpc.IParameterBinding = { name: "req", data: { http: { body: { string: "blahh" } } } }; var msg: rpc.IInvocationRequest = <rpc.IInvocationRequest> { functionId: 'id', invocationId: '1', inputData: [inputDataValue] }; let info: FunctionInfo = new FunctionInfo({ name: 'test', bindings: { req: { type: "http", direction: 0, dataType: 1 } } }); let { context } = CreateContextAndInputs(info, msg, _logger, _resultCallback, false); const { bindingData } = context; expect(bindingData.sys.methodName).to.equal("test"); expect(bindingData.sys.randGuid).to.not.be.undefined; expect(bindingData.sys.utcNow).to.not.be.undefined; expect(bindingData.invocationId).to.equal("1"); expect(context.invocationId).to.equal("1"); }); it ('Adds correct header and query properties for bindingData and http using nullable values', async () => { var inputDataValue: rpc.IParameterBinding = { name: "req", data: { http: { body: { string: "blahh" }, nullableHeaders: { header1: { value: "value1" }, header2: { value: "" } }, nullableQuery: { query1: { value: "value1" }, query2: { value: undefined } } } } }; var msg: rpc.IInvocationRequest = <rpc.IInvocationRequest> { functionId: 'id', invocationId: '1', inputData: [inputDataValue] }; let info: FunctionInfo = new FunctionInfo({ name: 'test', bindings: { req: { type: "http", direction: 0, dataType: 1 } } }); let { context } = CreateContextAndInputs(info, msg, _logger, _resultCallback, false); const { bindingData } = context; expect(bindingData.invocationId).to.equal("1"); expect(bindingData.headers.header1).to.equal("value1"); expect(bindingData.headers.header2).to.equal(""); expect(bindingData.query.query1).to.equal("value1"); expect(bindingData.query.query2).to.equal(""); expect(context.invocationId).to.equal("1"); }); it ('Adds correct header and query properties for bindingData and http using non-nullable values', async () => { var inputDataValue: rpc.IParameterBinding = { name: "req", data: { http: { body: { string: "blahh" }, headers: { header1: "value1" }, query: { query1: "value1" } } } }; var msg: rpc.IInvocationRequest = <rpc.IInvocationRequest> { functionId: 'id', invocationId: '1', inputData: [inputDataValue] }; let info: FunctionInfo = new FunctionInfo({ name: 'test', bindings: { req: { type: "http", direction: 0, dataType: 1 } } }); let { context } = CreateContextAndInputs(info, msg, _logger, _resultCallback, false); const { bindingData } = context; expect(bindingData.invocationId).to.equal("1"); expect(bindingData.headers.header1).to.equal("value1"); expect(bindingData.query.query1).to.equal("value1"); expect(context.invocationId).to.equal("1"); }); it ('async function logs error on calling context.done', async () => { await callUserFunc(BasicAsync.asyncAndCallback, _context); sinon.assert.calledOnce(_logger); sinon.assert.calledWith(_logger, rpc.RpcLog.Level.Error, rpc.RpcLog.RpcLogCategory.User, "Error: Choose either to return a promise or call 'done'. Do not use both in your script."); }); it ('async function calls callback and returns value without context.done', async () => { await callUserFunc(BasicAsync.asyncPlainFunction, _context); sinon.assert.calledOnce(_resultCallback); sinon.assert.calledWith(_resultCallback, null, { bindings: { }, return: "hello" }); }); it ('function logs error on calling context.done more than once', () => { callUserFunc(BasicCallback.callbackTwice, _context); sinon.assert.calledOnce(_logger); sinon.assert.calledWith(_logger, rpc.RpcLog.Level.Error, rpc.RpcLog.RpcLogCategory.User, "Error: 'done' has already been called. Please check your script for extraneous calls to 'done'."); }); it ('function logs error on calling context.log after context.done() called', () => { callUserFunc(BasicCallback.callbackOnce, _context); _context.log(""); sinon.assert.calledTwice(_logger); sinon.assert.calledWith(_logger, rpc.RpcLog.Level.Warning, rpc.RpcLog.RpcLogCategory.System, "Warning: Unexpected call to 'log' on the context object after function execution has completed. Please check for asynchronous calls that are not awaited or calls to 'done' made before function execution completes. Function name: test. Invocation Id: 1. Learn more: https://go.microsoft.com/fwlink/?linkid=2097909 "); }); it ('function logs error on calling context.log from non-awaited async call', async () => { await callUserFunc(BasicAsync.asyncPlainFunction, _context); _context.log(""); sinon.assert.calledTwice(_logger); sinon.assert.calledWith(_logger, rpc.RpcLog.Level.Warning, rpc.RpcLog.RpcLogCategory.System, "Warning: Unexpected call to 'log' on the context object after function execution has completed. Please check for asynchronous calls that are not awaited or calls to 'done' made before function execution completes. Function name: test. Invocation Id: 1. Learn more: https://go.microsoft.com/fwlink/?linkid=2097909 "); }); it ('function calls callback correctly with bindings', () => { callUserFunc(BasicCallback.callbackOnce, _context); sinon.assert.calledOnce(_resultCallback); sinon.assert.calledWith(_resultCallback, undefined, { bindings: { hello: "world" }, return: undefined }); }); it ('empty function does not call callback', () => { callUserFunc(BasicCallback.callbackNone, _context); sinon.assert.notCalled(_resultCallback); }); }) // async test functions class BasicAsync { public static async asyncAndCallback(context: Context) { context.done(); } public static async asyncPlainFunction(context: Context) { return "hello"; } } // sync test functions class BasicCallback { public static callbackTwice(context) { context.done(); context.done(); } public static callbackOnce(context) { context.bindings = { "hello": "world" }; context.done(); } public static callbackNone(context) { } } // Does logic in WorkerChannel to call the user function function callUserFunc(myFunc, context: Context): Promise<any> { let result = myFunc(context); if (result && isFunction(result.then)) { result = result.then(result => (<any>context.done)(null, result, true)) .catch(err => (<any>context.done)(err, null, true)); } return result; }
the_stack
import R2Error from '../../../model/errors/R2Error'; import ManifestV2 from '../../../model/ManifestV2'; import FileTree from '../../../model/file/FileTree'; import * as path from 'path'; import FsProvider from '../../../providers/generic/file/FsProvider'; import Profile from '../../../model/Profile'; import FileWriteError from '../../../model/errors/FileWriteError'; import ModMode from '../../../model/enums/ModMode'; import PathResolver from '../../manager/PathResolver'; import ProfileInstallerProvider from '../../../providers/ror2/installing/ProfileInstallerProvider'; import FileUtils from '../../../utils/FileUtils'; import ManagerInformation from '../../../_managerinf/ManagerInformation'; import ModLoaderPackageMapping from '../../../model/installing/ModLoaderPackageMapping'; import GameManager from '../../../model/game/GameManager'; import { MOD_LOADER_VARIANTS } from './ModLoaderVariantRecord'; import { RuleType } from '../../../r2mm/installing/InstallationRules'; let fs: FsProvider; const modModeExtensions: string[] = [".dll", ".language", "skin.cfg", ".hotmod", ".h3mod", ".deli", ".ros"]; export default class BepInExProfileInstaller extends ProfileInstallerProvider { private rule: RuleType; constructor(rule: RuleType) { super(rule); fs = FsProvider.instance; this.rule = rule; } /** * Uninstalls a mod by looking through the top level of profile/BepInEx/* * Any folder inside * locations with the mod name will be deleted. * @param mod * @param profile */ public async uninstallMod(mod: ManifestV2, profile: Profile): Promise<R2Error | null> { const activeGame = GameManager.activeGame; const bepInExVariant = MOD_LOADER_VARIANTS[activeGame.internalFolderName]; if (bepInExVariant.find(value => value.packageName.toLowerCase() === mod.getName().toLowerCase())) { try { for (const file of (await fs.readdir(profile.getPathOfProfile()))) { const filePath = path.join(profile.getPathOfProfile(), file); if ((await fs.lstat(filePath)).isFile()) { if (file.toLowerCase() !== 'mods.yml') { await fs.unlink(filePath); } } } } catch(e) { const err: Error = e; return new FileWriteError( 'Failed to delete BepInEx file from profile root', err.message, 'Is the game still running?' ); } } const bepInExLocation: string = path.join(profile.getPathOfProfile(), 'BepInEx'); if (await fs.exists(bepInExLocation)) { try { for (const file of (await fs.readdir(bepInExLocation))) { if ((await fs.lstat(path.join(bepInExLocation, file))).isDirectory()) { for (const folder of (await fs.readdir(path.join(bepInExLocation, file)))) { const folderPath: string = path.join(bepInExLocation, file, folder); if (folder === mod.getName() && (await fs.lstat(folderPath)).isDirectory()) { await FileUtils.emptyDirectory(folderPath); await fs.rmdir(folderPath); } } } } } catch (e) { const err: Error = e; return new R2Error( "Failed to remove files", err.message, 'Is the game still running? If so, close it and try again.' ); } } return Promise.resolve(null); } public async disableMod(mod: ManifestV2, profile: Profile): Promise<R2Error | void> { const bepInExLocation: string = path.join(profile.getPathOfProfile(), 'BepInEx'); const files: FileTree | R2Error = await FileTree.buildFromLocation(bepInExLocation); if (files instanceof R2Error) { return files; } return await this.applyModMode(mod, files, profile, bepInExLocation, ModMode.DISABLED); } public async enableMod(mod: ManifestV2, profile: Profile): Promise<R2Error | void> { const bepInExLocation: string = path.join(profile.getPathOfProfile(), 'BepInEx'); const files: FileTree | R2Error = await FileTree.buildFromLocation(bepInExLocation); if (files instanceof R2Error) { return Promise.resolve(files); } return await this.applyModMode(mod, files, profile, bepInExLocation, ModMode.ENABLED); } async applyModMode(mod: ManifestV2, tree: FileTree, profile: Profile, location: string, mode: number): Promise<R2Error | void> { const files: string[] = []; for (const directory of tree.getDirectories()) { if (directory.getDirectoryName() !== mod.getName()) { const applyError = await this.applyModMode(mod, directory, profile, path.join(location, directory.getDirectoryName()), mode); if (applyError instanceof R2Error) { return applyError; } } else { files.push(...directory.getRecursiveFiles()); } } for (const file of files) { try { if (mode === ModMode.DISABLED) { for (const ext of modModeExtensions) { if (file.toLowerCase().endsWith(ext)) { await fs.rename(file, file + '.old'); } } } else if (mode === ModMode.ENABLED) { for (const ext of modModeExtensions) { if (file.toLowerCase().endsWith(ext + ".old")) { await fs.rename(file, file.substring(0, file.length - ('.old').length)); } } } } catch(e) { const err: Error = e; return new R2Error( `Failed to rename file ${file} with ModMode of ${mode}`, err.message, 'Ensure that the game is closed.' ); } } } // No need to implement because ComputedProfileInstaller.ts should handle. async getDescendantFiles(tree: FileTree | null, location: string): Promise<string[]> { return []; } public async installMod(mod: ManifestV2, profile: Profile): Promise<R2Error | null> { const cacheDirectory = path.join(PathResolver.MOD_ROOT, 'cache'); const cachedLocationOfMod: string = path.join(cacheDirectory, mod.getName(), mod.getVersionNumber().toString()); const activeGame = GameManager.activeGame; const bepInExVariant = MOD_LOADER_VARIANTS[activeGame.internalFolderName]; const variant = bepInExVariant.find(value => value.packageName.toLowerCase() === mod.getName().toLowerCase()); if (variant !== undefined) { return this.installModLoader(cachedLocationOfMod, variant, profile); } return this.installForManifestV2(mod, profile, cachedLocationOfMod); } async installForManifestV2(mod: ManifestV2, profile: Profile, location: string): Promise<R2Error | null> { const files: FileTree | R2Error = await FileTree.buildFromLocation(location); if (files instanceof R2Error) { return files; } const result = await this.resolveBepInExTree(profile, location, path.basename(location), mod, files); if (result instanceof R2Error) { return result; } return null; } async resolveBepInExTree(profile: Profile, location: string, folderName: string, mod: ManifestV2, tree: FileTree): Promise<R2Error | void> { const endFolderNames = Object.keys(this.rule.rules); // Check if BepInExTree is end. const matchingEndFolderName = endFolderNames.find((folder: string) => folder.toLowerCase() === folderName.toLowerCase()); if (matchingEndFolderName !== undefined) { let profileLocation: string; if (folderName.toLowerCase() !== 'config') { profileLocation = path.join(profile.getPathOfProfile(), this.rule.rules[matchingEndFolderName], mod.getName()); } else { profileLocation = path.join(profile.getPathOfProfile(), this.rule.rules[matchingEndFolderName]); } try { await FileUtils.ensureDirectory(profileLocation); try { await fs.copyFolder( location, profileLocation ); // Copy is complete, end recursive tree. return; } catch(e) { const err: Error = e; return new FileWriteError( `Failed to move mod: ${mod.getName()} with directory of: ${profileLocation}`, err.message, `Is the game still running? If not, try running ${ManagerInformation.APP_NAME} as an administrator` ); } } catch(e) { const err: Error = e; return new FileWriteError( `Failed to create directories for: ${profileLocation}`, err.message, `Is the game still running? If not, try running ${ManagerInformation.APP_NAME} as an administrator` ); } } // If no match for (const file of tree.getFiles()) { let profileLocation: string; if (file.toLowerCase().endsWith('.mm.dll')) { profileLocation = path.join(profile.getPathOfProfile(), 'BepInEx', 'monomod', mod.getName()); } else { profileLocation = path.join(profile.getPathOfProfile(), this.rule._defaultPath, mod.getName()); } try { await FileUtils.ensureDirectory(profileLocation); try { await fs.copyFile( file, path.join(profileLocation, path.basename(file)) ); // Copy is complete; } catch(e) { if (e instanceof R2Error) { return e; } else { const err: Error = e; return new FileWriteError( `Failed to move mod: ${mod.getName()} with file: ${path.join(location, file)}`, err.message, `Is the game still running? If not, try running ${ManagerInformation.APP_NAME} as an administrator` ); } } } catch(e) { if (e instanceof R2Error) { return e; } else { const err: Error = e; return new FileWriteError( `Failed to create directories for: ${profileLocation}`, err.message, `Try running ${ManagerInformation.APP_NAME} as an administrator` ); } } } const directories = tree.getDirectories(); for (const directory of directories) { const resolveError: R2Error | void = await this.resolveBepInExTree( profile, path.join(location, directory.getDirectoryName()), directory.getDirectoryName(), mod, directory ); if (resolveError instanceof R2Error) { return resolveError; } } } async installModLoader(bieLocation: string, bepInExVariant: ModLoaderPackageMapping, profile: Profile): Promise<R2Error | null> { const location = path.join(bieLocation, bepInExVariant.rootFolder); const files: FileTree | R2Error = await FileTree.buildFromLocation(location); if (files instanceof R2Error) { return files; } for (const file of files.getFiles()) { try { await fs.copyFile(file, path.join(profile.getPathOfProfile(), path.basename(file))); } catch(e) { if (e instanceof R2Error) { return e; } const err: Error = e; return new FileWriteError( `Failed to copy file for BepInEx installation: ${file}`, err.message, `Is the game still running? If not, try running ${ManagerInformation.APP_NAME} as an administrator` ); } } for (const directory of files.getDirectories()) { try { await fs.copyFolder( path.join(location, directory.getDirectoryName()), path.join(profile.getPathOfProfile(), path.basename(directory.getDirectoryName())) ); } catch(e) { const err: Error = e; return new FileWriteError( `Failed to copy folder for BepInEx installation: ${directory.getDirectoryName()}`, err.message, `Is the game still running? If not, try running ${ManagerInformation.APP_NAME} as an administrator` ); } } try { await fs.copyFile( path.join(bieLocation, "icon.png"), path.join(profile.getPathOfProfile(), "BepInEx", "core", "icon.png") ); }catch(e) { const err: Error = e; return new FileWriteError( `Failed to copy icon asset for BepInEx installation`, err.message, `Is the game still running? If not, try running ${ManagerInformation.APP_NAME} as an administrator` ); } return Promise.resolve(null); } }
the_stack
import fs from 'fs-extra'; import getUnixUtcTimestamp from 'oc-get-unix-utc-timestamp'; import path from 'path'; import ComponentsCache from './components-cache'; import getComponentsDetails from './components-details'; import registerTemplates from './register-templates'; import settings from '../../resources/settings'; import strings from '../../resources'; import * as validator from './validators'; import getPromiseBasedAdapter from './storage-adapter'; import * as versionHandler from './version-handler'; import errorToString from '../../utils/error-to-string'; import { Component, Config, Repository } from '../../types'; import { StorageAdapter } from 'oc-storage-adapters-utils'; const packageInfo = fs.readJsonSync( path.join(__dirname, '..', '..', '..', 'package.json') ); export default function repository(conf: Config): Repository { const cdn: StorageAdapter = !conf.local && (getPromiseBasedAdapter(conf.storage.adapter(conf.storage.options)) as any); const options = !conf.local ? conf.storage.options : null; const repositorySource = conf.local ? 'local repository' : cdn.adapterType + ' cdn'; const componentsCache = ComponentsCache(conf, cdn); const componentsDetails = getComponentsDetails(conf, cdn); const getFilePath = (component: string, version: string, filePath: string) => `${options!.componentsDir}/${component}/${version}/${filePath}`; const { templatesHash, templatesInfo } = registerTemplates(conf.templates); const local = { getCompiledView(componentName: string): string { if (componentName === 'oc-client') { return fs .readFileSync( path.join( __dirname, '../../components/oc-client/_package/template.js' ) ) .toString(); } return fs .readFileSync( path.join(conf.path, `${componentName}/_package/template.js`) ) .toString(); }, getComponents(): string[] { const validComponents = conf.components || fs.readdirSync(conf.path).filter(file => { const isDir = fs.lstatSync(path.join(conf.path, file)).isDirectory(); const isValidComponent = isDir ? fs .readdirSync(path.join(conf.path, file)) .filter(file => file === '_package').length === 1 : false; return isValidComponent; }); validComponents.push('oc-client'); return validComponents; }, getComponentVersions(componentName: string): Promise<string[]> { if (componentName === 'oc-client') { return Promise.all([ fs .readJson(path.join(__dirname, '../../../package.json')) .then(x => x.version) ]); } if (!local.getComponents().includes(componentName)) { return Promise.reject( strings.errors.registry.COMPONENT_NOT_FOUND( componentName, repositorySource ) ); } return Promise.all([ fs .readJson(path.join(conf.path, `${componentName}/package.json`)) .then(x => x.version) ]); }, getDataProvider(componentName: string) { const ocClientServerPath = '../../components/oc-client/_package/server.js'; const filePath = componentName === 'oc-client' ? path.join(__dirname, ocClientServerPath) : path.join(conf.path, `${componentName}/_package/server.js`); return { content: fs.readFileSync(filePath).toString(), filePath }; } }; const repository = { getCompiledView(componentName: string, componentVersion: string) { if (conf.local) { return Promise.resolve(local.getCompiledView(componentName)); } return cdn.getFile( getFilePath(componentName, componentVersion, 'template.js') ); }, async getComponent(componentName: string, componentVersion?: string) { const allVersions = await repository.getComponentVersions(componentName); if (allVersions.length === 0) { throw strings.errors.registry.COMPONENT_NOT_FOUND( componentName, repositorySource ); } const version = versionHandler.getAvailableVersion( componentVersion, allVersions ); if (!version) { throw strings.errors.registry.COMPONENT_VERSION_NOT_FOUND( componentName, componentVersion || '', repositorySource ); } const component = await repository .getComponentInfo(componentName, version) .catch(err => { throw `component not available: ${errorToString(err)}`; }); return Object.assign(component, { allVersions }); }, getComponentInfo(componentName: string, componentVersion: string) { if (conf.local) { let componentInfo: Component; if (componentName === 'oc-client') { componentInfo = fs.readJsonSync( path.join( __dirname, '../../components/oc-client/_package/package.json' ) ); } else { componentInfo = fs.readJsonSync( path.join(conf.path, `${componentName}/_package/package.json`) ); } if (componentInfo.version === componentVersion) { return Promise.resolve(componentInfo); } else { // eslint-disable-next-line prefer-promise-reject-errors return Promise.reject('version not available'); } } return cdn.getJson<Component>( getFilePath(componentName, componentVersion, 'package.json'), false ); }, getComponentPath(componentName: string, componentVersion: string) { const prefix = conf.local ? conf.baseUrl : `${options!['path']}${options!.componentsDir}/`; return `${prefix}${componentName}/${componentVersion}/`; }, async getComponents() { if (conf.local) { return local.getComponents(); } const { components } = await componentsCache.get(); return Object.keys(components); }, getComponentsDetails() { if (conf.local) { // when in local this won't get called return Promise.resolve(null) as any; } return componentsDetails.get(); }, async getComponentVersions(componentName: string) { if (conf.local) { return local.getComponentVersions(componentName); } const res = await componentsCache.get(); return res.components[componentName] ? res.components[componentName] : []; }, async getDataProvider(componentName: string, componentVersion: string) { if (conf.local) { return local.getDataProvider(componentName); } const filePath = getFilePath( componentName, componentVersion, 'server.js' ); const content = await cdn.getFile(filePath); return { content, filePath }; }, getStaticClientPath: () => `${options!['path']}${getFilePath( 'oc-client', packageInfo.version, 'src/oc-client.min.js' )}`, getStaticClientMapPath: () => `${options!['path']}${getFilePath( 'oc-client', packageInfo.version, 'src/oc-client.min.map' )}`, getStaticFilePath: ( componentName: string, componentVersion: string, filePath: string ) => `${repository.getComponentPath(componentName, componentVersion)}${ conf.local ? settings.registry.localStaticRedirectorPath : '' }${filePath}`, getTemplatesInfo: () => templatesInfo, getTemplate: (type: string) => templatesHash[type], async init() { if (conf.local) { // when in local this won't get called return 'ok' as any; } const componentsList = await componentsCache.load(); return componentsDetails.refresh(componentsList); }, async publishComponent( pkgDetails: any, componentName: string, componentVersion: string ) { if (conf.local) { throw { code: strings.errors.registry.LOCAL_PUBLISH_NOT_ALLOWED_CODE, msg: strings.errors.registry.LOCAL_PUBLISH_NOT_ALLOWED }; } if (!validator.validateComponentName(componentName)) { throw { code: strings.errors.registry.COMPONENT_NAME_NOT_VALID_CODE, msg: strings.errors.registry.COMPONENT_NAME_NOT_VALID }; } if (!validator.validateVersion(componentVersion)) { throw { code: strings.errors.registry.COMPONENT_VERSION_NOT_VALID_CODE, msg: strings.errors.registry.COMPONENT_VERSION_NOT_VALID( componentVersion ) }; } const validationResult = validator.validatePackageJson( Object.assign(pkgDetails, { componentName, customValidator: conf.publishValidation }) ); if (!validationResult.isValid) { throw { code: strings.errors.registry.COMPONENT_PUBLISHVALIDATION_FAIL_CODE, msg: strings.errors.registry.COMPONENT_PUBLISHVALIDATION_FAIL( String(validationResult.error) ) }; } const componentVersions = await repository.getComponentVersions( componentName ); if ( !versionHandler.validateNewVersion(componentVersion, componentVersions) ) { throw { code: strings.errors.registry.COMPONENT_VERSION_ALREADY_FOUND_CODE, msg: strings.errors.registry.COMPONENT_VERSION_ALREADY_FOUND( componentName, componentVersion, repositorySource ) }; } pkgDetails.packageJson.oc.date = getUnixUtcTimestamp(); await fs.writeJson( path.join(pkgDetails.outputFolder, 'package.json'), pkgDetails.packageJson ); await cdn.putDir( pkgDetails.outputFolder, `${options!.componentsDir}/${componentName}/${componentVersion}` ); const componentsList = await componentsCache.refresh(); return componentsDetails.refresh(componentsList); } }; return repository; }
the_stack
import rule, { RULE_NAME } from '../../../lib/rules/await-fire-event'; import { createRuleTester } from '../test-utils'; const ruleTester = createRuleTester(); const COMMON_FIRE_EVENT_METHODS: string[] = [ 'click', 'change', 'focus', 'blur', 'keyDown', ]; ruleTester.run(RULE_NAME, rule, { valid: [ ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('fire event method not called is valid', () => { fireEvent.${fireEventMethod} }) `, })), ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('await promise from fire event method is valid', async () => { await fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, })), ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('await several promises from fire event methods is valid', async () => { await fireEvent.${fireEventMethod}(getByLabelText('username')) await fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, })), ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('await promise kept in a var from fire event method is valid', async () => { const promise = fireEvent.${fireEventMethod}(getByLabelText('username')) await promise }) `, })), ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('chain then method to promise from fire event method is valid', async (done) => { fireEvent.${fireEventMethod}(getByLabelText('username')) .then(() => { done() }) }) `, })), ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('chain then method to several promises from fire event methods is valid', async (done) => { fireEvent.${fireEventMethod}(getByLabelText('username')).then(() => { fireEvent.${fireEventMethod}(getByLabelText('username')).then(() => { done() }) }) }) `, })), `import { fireEvent } from '@testing-library/vue' test('fireEvent methods wrapped with Promise.all are valid', async () => { await Promise.all([ fireEvent.blur(getByText('Click me')), fireEvent.click(getByText('Click me')), ]) }) `, ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('return promise from fire event methods is valid', () => { function triggerEvent() { doSomething() return fireEvent.${fireEventMethod}(getByLabelText('username')) } }) `, })), ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('await promise returned from function wrapping fire event method is valid', () => { function triggerEvent() { doSomething() return fireEvent.${fireEventMethod}(getByLabelText('username')) } await triggerEvent() }) `, })), ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent } from 'somewhere-else' test('unhandled promise from fire event not related to TL is valid', async () => { fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, })), ...COMMON_FIRE_EVENT_METHODS.map((fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent } from 'test-utils' test('await promise from fire event method imported from custom module is valid', async () => { await fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, })), // edge case for coverage: // valid use case without call expression // so there is no innermost function scope found ` import { fireEvent } from 'test-utils' test('edge case for innermost function without call expression', async () => { function triggerEvent() { doSomething() return fireEvent.focus(getByLabelText('username')) } const reassignedFunction = triggerEvent }) `, ], invalid: [ ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('unhandled promise from fire event method is invalid', async () => { fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, errors: [ { line: 4, column: 9, endColumn: 19 + fireEventMethod.length, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, ], } as const) ), ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ code: ` import { fireEvent as testingLibraryFireEvent } from '@testing-library/vue' test('unhandled promise from aliased fire event method is invalid', async () => { testingLibraryFireEvent.${fireEventMethod}(getByLabelText('username')) }) `, errors: [ { line: 4, column: 9, endColumn: 33 + fireEventMethod.length, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, ], } as const) ), ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ code: ` import * as testingLibrary from '@testing-library/vue' test('unhandled promise from wildcard imported fire event method is invalid', async () => { testingLibrary.fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, errors: [ { line: 4, column: 9, endColumn: 34 + fireEventMethod.length, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, ], } as const) ), ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('several unhandled promises from fire event methods is invalid', async () => { fireEvent.${fireEventMethod}(getByLabelText('username')) fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, errors: [ { line: 4, column: 9, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, { line: 5, column: 9, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, ], } as const) ), ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent } from '@testing-library/vue' test('unhandled promise from fire event method with aggressive reporting opted-out is invalid', async () => { fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, errors: [ { line: 4, column: 9, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, ], } as const) ), ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent } from 'test-utils' test( 'unhandled promise from fire event method imported from custom module with aggressive reporting opted-out is invalid', () => { fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, errors: [ { line: 6, column: 9, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, ], } as const) ), ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ settings: { 'testing-library/utils-module': 'test-utils', }, code: ` import { fireEvent } from '@testing-library/vue' test( 'unhandled promise from fire event method imported from default module with aggressive reporting opted-out is invalid', () => { fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, errors: [ { line: 6, column: 9, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, ], } as const) ), ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test( 'unhandled promise from fire event method kept in a var is invalid', () => { const promise = fireEvent.${fireEventMethod}(getByLabelText('username')) }) `, errors: [ { line: 6, column: 25, messageId: 'awaitFireEvent', data: { name: fireEventMethod }, }, ], } as const) ), ...COMMON_FIRE_EVENT_METHODS.map( (fireEventMethod) => ({ code: ` import { fireEvent } from '@testing-library/vue' test('unhandled promise returned from function wrapping fire event method is invalid', () => { function triggerEvent() { doSomething() return fireEvent.${fireEventMethod}(getByLabelText('username')) } triggerEvent() }) `, errors: [ { line: 9, column: 9, messageId: 'fireEventWrapper', data: { name: fireEventMethod }, }, ], } as const) ), ], });
the_stack
import { merge } from '../common/common'; import tween, { Tween } from '../common/tween'; import { ChartData, Types } from '../common/types'; let uniqueId = 0; function generateUniqueId() { return `shoot-${uniqueId++}`; } const PI = 2 * Math.PI; const { sin, cos, atan, sqrt } = Math; const pow2 = function (x: number) { return Math.pow(x, 2); }; function random() { return Math.random() * 5 + 2.5; } interface PositionPoint { x: number; y: number; } export type getPositionFun = (d: Types.LooseObject) => PositionPoint; interface ShootConfig { width: number; height: number; autoUpdate?: boolean; maxFps?: number; interval?: number; // 单次飞线总时间 dTime?: number; // 单条飞线预计的时间 shootDurable?: boolean; // batch: false; shootTime?: {// 飞行过程中的各个时间 值域[0, 1] fromTime?: number; // 出发时间(瞬时) fromStop?: number; // 出发点保留时间(持续) fromFade?: number; // 出发点消失所用时间(持续) toBegin?: number; // 到达目标点的时间(瞬时) toTime?: number; // 到达点显示所用时间(持续) toStop?: number; // 到达点停留持续时间(持续) toFade?: number; // 到达点消失所用时间(持续) }; fromRadius?: number; // 出发点半径 toRadius?: number; // 到达点半径 fromBorder?: number; // 出发点边框宽度 toBorder?: number; // 到达点边框宽度 shootPointColor?: { fromPoint?: string; // 出发点颜色 fromShadow?: string; // 出发点阴影颜色 toPoint?: string; // 到达点颜色 toShadow?: string; // 到达点阴影颜色 }; lineWidth?: number; // 飞线宽度 lineColor?: { from?: string; // 线出发颜色 to?: string; // 线到达颜色 }; bullet?: { r?: number; // 弹头半径 length?: number; // 弹头长度 color?: string; shadowColor?: string; }; keys?: { from?: string; to?: string; fromValue?: string; toValue?: string; curvature?: string; // 曲率半径,值越大越平坦 }; } class Shoot { sCtx: CanvasRenderingContext2D; tween: Tween; constructor(private canvas: HTMLCanvasElement, private getPosition: getPositionFun, protected config: ShootConfig) { // this.uuid = generateUniqueId(); this.getPosition = getPosition; this.config = merge({ autoUpdate: true, maxFps: 60, interval: 10000, // 单次飞线总时间 dTime: 4000, // 单条飞线预计的时间 // batch: false, shootTime: {// 飞行过程中的各个时间 值域[0, 1] fromTime: 0, // 出发时间(瞬时) fromStop: 0.4, // 出发点保留时间(持续) fromFade: 0.1, // 出发点消失所用时间(持续) toBegin: 0.3, // 到达目标点的时间(瞬时) toTime: 0.1, // 到达点显示所用时间(持续) toStop: 0, // 到达点停留持续时间(持续) toFade: 0.1, // 到达点消失所用时间(持续) }, fromRadius: 3, // 出发点半径 toRadius: 3, // 到达点半径 fromBorder: 1, // 出发点边框宽度 toBorder: 1, // 到达点边框宽度 shootPointColor: { fromPoint: '46, 133, 255', // 出发点颜色 fromShadow: '46, 133, 255', // 出发点阴影颜色 toPoint: '46, 133, 255', // 到达点颜色 toShadow: '46, 133, 255', // 到达点阴影颜色 }, lineWidth: 2, // 飞线宽度 lineColor: { from: '46, 133, 255', // 线出发颜色 to: '46, 133, 255', // 线到达颜色 }, bullet: { r: 2.5, // 弹头半径 length: 20, // 弹头长度 color: 'rgb(46, 133, 255)', shadowColor: 'rgb(46, 133, 255)', }, keys: { from: 'from', to: 'to', fromValue: 'fromValue', toValue: 'toValue', curvature: 'curvature', // 曲率半径,值越大越平坦 }, }, config); canvas.width = this.config.width; canvas.height = this.config.height; // 射击canvas层 this.canvas = canvas; this.sCtx = this.canvas.getContext('2d'); this.sCtx.lineWidth = this.config.lineWidth; } // 清除画布 clear(ctx: CanvasRenderingContext2D) { const { width, height } = this.config; ctx.clearRect(0, 0, width, height); } changeSize(w: number, h: number) { this.config.width = w; this.config.height = h; this.canvas.width = w; this.canvas.height = h; // 更新uuid让动画更新 // this.uuid = generateUniqueId(); } draw(data: ChartData) { if (!data || data.length === 0) { return; } const self = this; const { dTime } = self.config; // 由于要保证interval时间内完成全部动画 const { interval } = self.config; const { autoUpdate } = self.config; const { maxFps } = self.config; const times = (interval / dTime) >> 0; const { keys } = self.config; const { sCtx } = self; const shoots: any[] = []; const shootMap: { [key: string]: PositionPoint[] } = {}; const time = self.config.shootTime; const l = data.length; const getPosition = self.getPosition; let fCo: PositionPoint; let tCo: PositionPoint; let s: any; // 先清除画布 self.clear(sCtx); for (let i = 0; i < l; i++) { const d = data[i]; fCo = { ...d[keys.from] }; tCo = { ...d[keys.to] }; // 设置了 getPosition 函数,需要处理一遍 if (getPosition) { const fP = getPosition(fCo); fCo.x = fP.x; fCo.y = fP.y; const tP = getPosition(tCo); tCo.x = tP.x; tCo.y = tP.y; } // const fromCityName = d[keys.from]; // const toCityName = d[keys.to]; // // if (typeof fromCityName === 'object') { // fCo = fromCityName; // } else { // // 获取出发城市在画布上的坐标 // fCo = self.map.getCoord(fromCityName); // } // // if (typeof toCityName === 'object') { // tCo = toCityName; // } else { // // 获取到达城市在画布上的坐标 // tCo = self.map.getCoord(toCityName); // } if (fCo && tCo) { const color = {}; // 如果数据带有颜色配置 if (d._color) { Object.assign(color, d._color); } s = self.emit(fCo, tCo, d, color, time); s.index = (times - 1) * Math.random(); // 判断是否是多点同时射击一个点 if (!shootMap[s.index]) { shootMap[s.index] = []; } shootMap[s.index].forEach((city) => { if (city === tCo) { // 正在被攻击 s.shooting = true; } }); if (!s.shooting) { shootMap[s.index].push(tCo); } shoots.push(s); } } this.tween = tween(generateUniqueId(), { duration: interval, autoUpdate, maxFps, }, (t) => { self.clear(self.sCtx); shoots.forEach((shootFunction) => { shootFunction(t * times - shootFunction.index); }); }); } emit(fCo: PositionPoint, tCo: PositionPoint, data: { [x: string]: number; }, color: {}, time: { fromTime?: number; fromStop?: number; fromFade?: number; toBegin?: number; toTime?: number; toStop?: number; toFade?: number; }) { const self = this; const { keys } = self.config; // 发射出现时间段 const { fromTime } = time; // 发射停留时间段 const { fromStop } = time; // 发射消失时间段 const { fromFade } = time; // 击中开始时间点 const { toBegin } = time; // 击中出现时间段 const { toTime } = time; // 击中停留时间段 const { toStop } = time; // 击中消失时间段 const { toFade } = time; // 发射消失时间点 const fromFadeBegin = fromTime + fromStop; // 命中消失时间点 const toFadeBegin = toBegin + toTime + toStop; // 发射半径 const fr = self.config.fromRadius; const tr = self.config.toRadius; const h = data[keys.curvature] || random(); const { shootDurable } = self.config; let s: any; s = function (t: number) { if (fCo) { // 出发: // 1. 出现 if (t < fromTime) { self.from(fCo, fr, color)(t / fromTime); // 2. 停留 } else if (t > fromTime && t < fromFadeBegin) { self.from(fCo, fr, color)(1); // 3. 消失 } else if (t > fromFadeBegin) { self.from(fCo, fr, color, true)((t - fromFadeBegin) / fromFade); } } if (tCo) { // 轨迹 if (t >= fromTime && t < toBegin) { // 出发 - 到达瞬间 self.track(fCo, tCo, false, color, h)((t - fromTime) / (toBegin - fromTime)); } else if (t > toBegin && t < toFadeBegin) { // 到达后停留 // TODO add by kaihong.tkh if (shootDurable) { let time = -(t - fromTime) / (toBegin - fromTime); time -= Math.floor(time); time = 1 - time; self.track(fCo, tCo, true, color, h)(time); } else { self.track(fCo, tCo, true, color, h)(0); } } else if (t > toFadeBegin && t < toFadeBegin + toFade) { // 停留后消失时间 self.track(fCo, tCo, true, color, h)((t - toFadeBegin) / toFade); } // 如果不是正在被射击 if (!s.shooting) { // 到达: // 1. 放大 if (t >= toBegin && t < (toBegin + toTime)) { if (!s.to) { s.to = true; } self.to(tCo, tr, color)((t - toBegin) / toTime); // 2. 停留 } else if (t > (toBegin + toTime) && t < toFadeBegin) { self.to(tCo, tr, color)(1); // 3. 消失 } else if (t >= toFadeBegin) { self.to(tCo, tr, color, true, 3)((t - toFadeBegin) / toFade); } } } }; return s; } // CHECK zoom 没有传入 from(co: PositionPoint, r: number, color: { fColor?: any; }, zoom?: boolean) { const self = this; const c = `rgba(${color.fColor || this.config.shootPointColor.fromPoint},`; const b = self.config.fromBorder; const { sCtx } = self; return function (t: number) { if (t > 1 || t < 0) { return; } if (zoom) { t = 1 - t; } sCtx.save(); // 画背景圆 sCtx.beginPath(); sCtx.strokeStyle = `${c + t})`; sCtx.lineWidth = b * t; sCtx.fillStyle = `${c}0.3)`; // shadow sCtx.shadowColor = `rgba(${color.fColor || self.config.shootPointColor.fromShadow},1)`; sCtx.shadowBlur = 5; sCtx.shadowOffsetX = 0; sCtx.shadowOffsetY = 0; sCtx.arc(co.x, co.y, r * t, 0, PI); sCtx.fill(); sCtx.stroke(); // 画中心圆 sCtx.beginPath(); sCtx.fillStyle = `${c}1)`; sCtx.arc(co.x, co.y, 2 * t, 0, PI); sCtx.fill(); sCtx.restore(); }; } // CHECK anticlockwise 没有传入 to(co: PositionPoint, r: number, color: { tColor?: any; }, zoom?: boolean, n?: number, anticlockwise?: undefined) { const self = this; const c = `rgba(${color.tColor || this.config.shootPointColor.toPoint},`; const b = self.config.toBorder; const { sCtx } = self; return function (t: number) { let rad = 0; if (t > 1 || t < 0) { return; } sCtx.save(); // 每次转的角度 if (n) { rad = n * PI * t; if (anticlockwise) { rad = -rad; } } if (zoom) { t = 1 - t; } // 画背景圆 sCtx.beginPath(); sCtx.fillStyle = `${c}0.3)`; sCtx.arc(co.x, co.y, r * t, 0, PI); sCtx.fill(); // 画离散弧线 sCtx.beginPath(); sCtx.strokeStyle = `${c + t})`; sCtx.lineWidth = b * t; // shadow sCtx.shadowColor = `rgba(${color.tColor || self.config.shootPointColor.toShadow},1)`; sCtx.shadowBlur = 10; sCtx.shadowOffsetX = 0; sCtx.shadowOffsetY = 0; sCtx.arc(co.x, co.y, r * t, rad, PI / 6 + rad); sCtx.moveTo(co.x + r * cos(PI / 3 + rad) * t, co.y + r * sin(PI / 3 + rad) * t); sCtx.arc(co.x, co.y, r * t, PI / 3 + rad, PI / 2 + rad); sCtx.moveTo(co.x + r * cos(PI * 2 / 3 + rad) * t, co.y + r * sin(PI * 2 / 3 + rad) * t); sCtx.arc(co.x, co.y, r * t, PI * 2 / 3 + rad, PI * 5 / 6 + rad); sCtx.stroke(); // 画中心圆 sCtx.beginPath(); sCtx.fillStyle = `${c}1)`; sCtx.arc(co.x, co.y, 2 * t, 0, PI); sCtx.fill(); sCtx.restore(); }; } // CHECK overview 没有传入 track(fCo: PositionPoint, tCo: PositionPoint, fade: boolean, color: { fColor?: any; tColor?: any; bullet?: any; }, h: number, overview?: boolean) { const self = this; const { sCtx: ctx } = self; const fColor = `rgba(${color.fColor || self.config.lineColor.from},`; const tColor = `rgba(${color.tColor || self.config.lineColor.to},`; // (x1, y1) 出发点,(x2, y2) 到达点 const x1 = fCo.x; const y1 = fCo.y; const x2 = tCo.x; const y2 = tCo.y; // 求法线方程 // y = j * x + k const dx = (x1 + x2) / 2; const dy = (y1 + y2) / 2; const j = (x1 - x2) / (y2 - y1); const k = dy - j * dx; // d用来控制弧线的弧度 const d = sqrt(pow2(x1 - x2) + pow2(y1 - y2)) / h; const rad = atan(j); const cx = d * cos(rad); // 渐变 const gradient = ctx.createLinearGradient(x1, y1, x2, y2); const bulletR = this.config.bullet.r; const bulletLen = this.config.bullet.length; const { shootDurable } = self.config; // 控制点坐标 let x3 = (x1 + x2) / 2 + cx; let y3 = j * x3 + k; if (isNaN(j) || j > 10 ) { // 水平方向 x3 = dx; y3 = dy - h - dx / 20; } else if (Math.abs(j) < 0.1) { // 竖直方向 x3 = y1 < y2 ? dx + h + dy / 20 : dx - h - dy / 20; y3 = dy; } else if (Math.abs(j) >= 1) { // 之后的两个条件判断请画象限图理解。。。估计明天我也忘记为什么要这么写了 y3 = dy - cx; x3 = (y3 - k) / j; } else if (j > 0) { x3 = (x1 + x2) / 2 - cx; y3 = j * x3 + k; } return function (t: number) { // 移动点坐标 let x0; let y0; // 贝塞尔曲线切线斜率 let kx; let ky; // 蒙板起始坐标 let rx; let ry; // 蒙板半径 let r; let gradientOpacity = 0.7; if (t > 1 || t < 0) { return; } // TODO:最好加上一个透明度变化的动画 if (!overview) { if (fade) { // 避免出现科学计数法,rgba中的透明值不能设为科学计数法 gradientOpacity = (1 - t) < 0.01 ? 0.01 : (1 - t); } else { gradientOpacity = t < 0.01 ? 0.01 : t; } if (shootDurable) { gradientOpacity = 1; // add by kaihong.tkh 线不需要渐变 } } // 贝塞尔曲线方程 x0 = (1 - t) * (1 - t) * x1 + 2 * t * (1 - t) * x3 + t * t * x2; y0 = (1 - t) * (1 - t) * y1 + 2 * t * (1 - t) * y3 + t * t * y2; // 贝塞尔曲线切线方程 kx = -2 * x1 * (1 - t) + 2 * x3 * (1 - 2 * t) + 2 * x2 * t; ky = -2 * y1 * (1 - t) + 2 * y3 * (1 - 2 * t) + 2 * y2 * t; rx = (x1 + x0) / 2; ry = (y1 + y0) / 2; r = sqrt(pow2(x1 - x0) + pow2(y1 - y0)) / 2; ctx.save(); gradient.addColorStop(0, `${fColor + gradientOpacity})`); gradient.addColorStop(1, `${tColor + gradientOpacity})`); if (!fade && !overview) { // 创建圆形蒙板 ctx.arc(rx, ry, r, 0, PI); ctx.clip(); } ctx.beginPath(); ctx.globalCompositeOperation = 'lighter'; ctx.strokeStyle = gradient; ctx.lineWidth = self.config.lineWidth; ctx.moveTo(x1, y1); ctx.quadraticCurveTo(x3, y3, x2, y2); ctx.stroke(); ctx.restore(); let a = atan(ky / kx); // 计算旋转角度 if (ky > 0 && kx < 0) { a += PI / 2; } else if (ky < 0 && kx < 0) { a -= PI / 2; } // TODO add by kaihong.tkh if (shootDurable) { self.drawBullet(x0, y0, a, color.bullet, bulletR, bulletLen); } else if (!fade && !overview) { // ky/kx 为切线斜率 self.drawBullet(x0, y0, a, color.bullet, bulletR, bulletLen); } }; } drawBullet(x: number, y: number, a: number, color: string, r: number, len: number) { const self = this; const { sCtx } = self; sCtx.save(); sCtx.translate(x, y); sCtx.rotate(a); sCtx.translate(-x, -y); sCtx.beginPath(); sCtx.globalCompositeOperation = 'lighter'; // shadow sCtx.shadowColor = this.config.bullet.shadowColor; sCtx.shadowBlur = 20; sCtx.shadowOffsetX = 0; sCtx.shadowOffsetY = 0; sCtx.fillStyle = color || this.config.bullet.color; sCtx.arc(x, y, r, -PI / 4, PI / 4); sCtx.lineTo(x - len, y); sCtx.closePath(); sCtx.fill(); sCtx.restore(); } update(time: number) { if (this.tween && this.tween.update) { this.tween.update(time); } } destroy() { this.clear(this.sCtx); this.tween && this.tween.destroy(); } } export default Shoot;
the_stack
import express from 'express' import adminUser from '../controllers/admin/adminUsers' // 后台用户 import users from '../controllers/admin/users' // 前台用户 import userRoleAuthority from '../controllers/admin/userRoleAuthority' // 前台用户角色权限 import articles from '../controllers/admin/articles' // 文章 import articleTag from '../controllers/admin/articleTag' // 文章标签 import articleColumn from '../controllers/admin/articleColumn' // 文章专栏 (专栏为官方) import articleBlog from '../controllers/admin/articleBlog' // 个人文章专栏 (专栏为个人) import picture from '../controllers/admin/picture' // 图片管理 import upload from '../controllers/admin/upload' // 上传 import adminRoleAuthority from '../controllers/admin/adminRoleAuthority' // 后台角色权限 import articleComment from '../controllers/admin/articleComment' // 文章评论 import adminSystemLog from '../controllers/admin/adminSystemLog' // 系统日志 import system from '../controllers/admin/system' // 系统配置 import adminIndex from '../controllers/admin/adminIndex' // 登录tokens import options from '../controllers/admin/options' // options 可增加选项栏 import dynamicTopic from '../controllers/admin/dynamicTopic' // 动态专题 import dynamicComment from '../controllers/admin/dynamicComment' // 动态专评论 import dynamics from '../controllers/admin/dynamics' // 动态 import book from '../controllers/admin/book' // 小书章节 import books from '../controllers/admin/books' // 小书 import bookComment from '../controllers/admin/bookComment' // 小书章节评论 import booksComment from '../controllers/admin/booksComment' // 小书评价 // 此文件所有接口都是后台管理员操作前后台数据所用 import uploadUse from '../utils/upload/index' import multerUse from '../utils/upload/multer' const router = express.Router() const verifyAuthority = require('../utils/verifyAuthority') // 权限验证 const tokens = require('../utils/tokens') // 登录tokens /* 前台用户 */ // 获取用户列表 router.get( '/user/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, users.getUserList ) // 更新用户资料 router.post( '/user/edit', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, users.editUser ) // 删除用户 router.post( '/user/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, users.deleteUser ) // 待审核用户头像列表 router.get( '/user/avatar-review-list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, users.getAvatarReview ) // 审核用户头像 router.post( '/user/avatar-review-set', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, users.set_avatar_review ) // 禁言用户 router.post( '/user/ban', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, users.banUser ) /* 文章管理 */ router.post( '/article/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articles.getArticleList ) // 更新文章 router.post( '/article/edit', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articles.editArticle ) // 删除文章 router.post( '/article/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articles.deleteArticle ) /* 文章标签管理 */ /* 获取所有标签 */ router.get( '/article-tag/all', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleTag.getArticleTagAll ) /* 根据分页获取标签 */ router.get( '/article-tag/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleTag.getArticleTagList ) /* 文章创建标签 */ router.post( '/article-tag/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleTag.createArticleTag ) /* 文章更新标签 */ router.post( '/article-tag/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleTag.updateArticleTag ) /* 文章删除标签 */ router.post( '/article-tag/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleTag.deleteArticleTag ) /* 文章专栏管理 (专栏为官方) */ router.get( '/article-column/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleColumn.getArticleColumnList ) /* 文章创建专栏 */ router.post( '/article-column/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleColumn.createArticleColumn ) /* 文章更新专栏 */ router.post( '/article-column/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleColumn.updateArticleColumn ) /* 文章删除专栏 */ router.post( '/article-column/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleColumn.deleteArticleColumn ) /* 个人专栏管理 (专栏为个人) */ router.get( '/article-blog/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleBlog.getArticleBlogList ) /* 个人更新专栏 */ router.post( '/article-blog/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleBlog.updateArticleBlog ) /* 文章专题管理 (专题为个人) */ // 用户标签管理 /* 根据分页获取用户角色 */ router.get( '/user-role/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.getUserRoleList ) // 获取所有用户角色 router.get( '/user-role/all', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.getUserRoleAll ) // 创建用户角色 router.post( '/user-role/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.createUserRole ) /* 用户更新用户角色 */ router.post( '/user-role/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.updateUserRole ) /* 用户删除用户角色 */ router.post( '/user-role/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.deleteUserRole ) // 获取用户权限列表 router.get( '/user-authority/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.getUserAuthorityList ) // 创建用户权限 router.post( '/user-authority/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.createUserAuthority ) // 更新用户权限 router.post( '/user-authority/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.updateUserAuthority ) // 删除用户权限 router.post( '/user-authority/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.deleteUserAuthority ) // 设置用户角色权限 router.post( '/user-role-authority/set', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, userRoleAuthority.setUserRoleAuthority ) /* 图片管理 */ router.get( '/picture/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, picture.getPictureList ) /* 图片创建 */ router.post( '/picture/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, picture.createPicture ) /* 图片更新 */ router.post( '/picture/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, picture.updatePicture ) /* 图片删除 */ router.post( '/picture/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, picture.deletePicture ) // 文章评论模块 // 评论分页列表 router.post( '/article-comment/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleComment.getCommentList ) // 文章评论数据更新 router.post( '/article-comment/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleComment.updateComment ) // 文章评论数据删除 router.post( '/article-comment/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, articleComment.deleteComment ) /** * 上传 */ router.post( '/upload/picture', tokens.ClientVerifyToken, multerUse('admin').single('file'), uploadUse, upload.uploadPicture ) // 用户修改头像 post /** * 首页数据 */ router.get( '/admin-index/statistics', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminIndex.adminIndexStatistics ) /** * 管理员用户 */ // 登录 router.post('/sign-in', adminUser.adminSignIn) // 创建管理员用户 router.post( '/admin-user/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminUser.createAdminUser ) // 更新管理员用户 router.post( '/admin-user/edit', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminUser.editAdminUser ) // 删除管理员用户 router.post( '/admin-user/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminUser.deleteAdminUser ) // 获取管理员用户信息 router.post( '/admin-user/info', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminUser.getAdminUserInfo ) // 获取管理员用户列表 router.get( '/admin-user/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminUser.getAdminUserList ) /** * 后台角色 */ // 获取分页角色列表 router.get( '/admin-role/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.getAdminRoleList ) // 获取全部角色 router.get( '/admin-role/all', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.getAdminRoleAll ) // 创建角色 router.post( '/admin-role/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.createAdminRole ) // 删除角色 router.post( '/admin-role/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.deleteAdminRole ) // 更新角色 router.post( '/admin-role/edit', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.editAdminRole ) /** * 后台角色用户关联 */ // 创建或者修改用户角色关联 router.post( '/admin-user-role/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.createAdminUserRole ) /** * 后台权限 */ // 获取权限列表 router.get( '/admin-authority/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.getAdminAuthorityList ) // 创建权限 router.post( '/admin-authority/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.createAdminAuthority ) // 更新权限 router.post( '/admin-authority/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.updateAdminAuthority ) // 删除权限 router.post( '/admin-authority/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.deleteAdminAuthority ) /** * 后台角色权限关联 */ // 设置后台角色权限 router.post( '/admin-role-authority/set', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminRoleAuthority.setAdminRoleAuthority ) /** * 后台系统日志 */ // 获取系统日志列表 router.get( '/admin-system-log/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminSystemLog.getAdminSystemLogList ) // 获取系统配置 router.get( '/system-config/info', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, system.getSystemInfo ) // 更新系统配置 router.post( '/system-config/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, system.updateSystemInfo ) // 删除系统日志 router.post( '/admin-system-log/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, adminSystemLog.deleteAdminSystemLog ) // 获取网站配置项列表 router.get( '/options/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, options.QueryOptions ) // 创建网站配置项 router.post( '/options/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, options.createOptions ) // 更新网站配置项 router.post( '/options/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, options.updateOptions ) // 删除网站配置项 router.post( '/options/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, options.deleteOptions ) /* 动态话题管理 */ /* 获取所有话题 */ router.get( '/dynamic-topic/all', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamicTopic.getDynamicTopicAll ) /* 根据分页获取话题 */ router.get( '/dynamic-topic/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamicTopic.getDynamicTopicList ) /* 文章创建话题 */ router.post( '/dynamic-topic/create', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamicTopic.createDynamicTopic ) /* 文章更新话题 */ router.post( '/dynamic-topic/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamicTopic.updateDynamicTopic ) /* 文章删除话题 */ router.post( '/dynamic-topic/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamicTopic.deleteDynamicTopic ) /* 动态汇总 */ router.post( '/dynamic/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamics.getDynamicList ) // 更新动态 router.post( '/dynamic/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamics.updateDynamic ) // 删除动态 router.post( '/dynamic/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamics.deleteDynamic ) // 动态评论模块 // 评论分页列表 router.post( '/dynamic-comment/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamicComment.getCommentList ) // 动态评论数据更新 router.post( '/dynamic-comment/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamicComment.updateComment ) // 动态评论数据删除 router.post( '/dynamic-comment/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, dynamicComment.deleteComment ) // 2019.10.11 新增 // ---- 小书章节 /* 小书章节管理 */ router.post( '/book/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, book.getBookList ) // 更新小书章节 router.post( '/book/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, book.updateBook ) // 删除小书章节 router.post( '/book/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, book.deleteBook ) // ---- 小书 router.post( '/books/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, books.getBooksList ) // 更新小书章节 router.post( '/books/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, books.updateBooks ) // 删除小书章节 router.post( '/books/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, books.deleteBooks ) // 小书评论模块 // 小书评论分页列表 router.post( '/books-comment/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, booksComment.getCommentList ) // 小书文章评论数据更新 router.post( '/books-comment/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, booksComment.updateComment ) // 小书文章评论数据删除 router.post( '/books-comment/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, booksComment.deleteComment ) // 小书章节评论模块 // 小书评论分页列表 router.post( '/book-comment/list', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, bookComment.getCommentList ) // 小书文章评论数据更新 router.post( '/book-comment/update', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, bookComment.updateComment ) // 小书文章评论数据删除 router.post( '/book-comment/delete', tokens.AdminVerifyToken, verifyAuthority.AdminCheck, bookComment.deleteComment ) router.get( '/system-config/theme-list', tokens.AdminVerifyToken, system.getSystemTheme ) module.exports = router
the_stack
import {Label} from '@microsoft/bf-dispatcher'; import {LabelType} from '@microsoft/bf-dispatcher'; import {Result} from '@microsoft/bf-dispatcher'; import {ILabelArrayAndMap} from '@microsoft/bf-dispatcher'; import {PredictionStructureWithScoreLabelString, PredictionType} from '@microsoft/bf-dispatcher'; import {PredictionStructureWithScoreLabelObject} from '@microsoft/bf-dispatcher'; import {StructTextLabelObjects} from '@microsoft/bf-dispatcher'; import {StructTextLabelStrings} from '@microsoft/bf-dispatcher'; import {LabelResolver} from './labelresolver'; import {Utility} from './utility'; import {Utility as UtilityDispatcher} from '@microsoft/bf-dispatcher'; export class UtilityLabelResolver { public static toObfuscateLabelTextInReportUtilityLabelResolver: boolean = true; public static resetLabelResolverSettingIgnoreSameExample( ignoreSameExample: boolean = true, resetAll: boolean = false): any { const ignoreSameExampleObject: { ignore_same_example: boolean; } = { ignore_same_example: ignoreSameExample, }; Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), ignoreSameExample=${ignoreSameExample}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), resetAll=${resetAll}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), ignoreSameExampleObject=${ignoreSameExampleObject}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), ignoreSameExampleObject.ignore_same_example=${ignoreSameExampleObject.ignore_same_example}`); const ignoreSameExampleObjectJson: string = Utility.jsonStringify(ignoreSameExampleObject); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), ignoreSameExampleObjectJson=${ignoreSameExampleObjectJson}`); LabelResolver.setRuntimeParams(ignoreSameExampleObjectJson, resetAll); Utility.debuggingLog(`ready to call Utility.getConfigJson(), LabelResolver.LabelResolver=${LabelResolver.LabelResolver}`); return LabelResolver.getConfigJson(); } public static resetLabelResolverSettingUseCompactEmbeddings( fullEmbeddings: boolean = false, resetAll: boolean = false): any { const useCompactEmbeddingsObject: { use_compact_embeddings: boolean; } = { use_compact_embeddings: !fullEmbeddings, }; Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), fullEmbeddings=${fullEmbeddings}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), resetAll=${resetAll}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), useCompactEmbeddingsObject=${useCompactEmbeddingsObject}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), useCompactEmbeddingsObject.use_compact_embeddings=${useCompactEmbeddingsObject.use_compact_embeddings}`); const useCompactEmbeddingsObjectJson: string = Utility.jsonStringify(useCompactEmbeddingsObject); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), useCompactEmbeddingsObjectJson=${useCompactEmbeddingsObjectJson}`); LabelResolver.setRuntimeParams(useCompactEmbeddingsObjectJson, resetAll); Utility.debuggingLog(`ready to call Utility.getConfigJson(), LabelResolver.LabelResolver=${LabelResolver.LabelResolver}`); return LabelResolver.getConfigJson(); } public static resetLabelResolverSettingKnnK( knnK: number = 1, resetAll: boolean = false): any { const knnKObject: { knn_k: number; } = { knn_k: knnK, }; Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), knnK=${knnK}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), resetAll=${resetAll}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), knnKObject=${knnKObject}`); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), knnKObject.knn_k=${knnKObject.knn_k}`); const knnKObjectJson: string = Utility.jsonStringify(knnKObject); Utility.debuggingLog(`ready to call LabelResolver.setRuntimeParams(), knnKObjectJson=${knnKObjectJson}`); LabelResolver.setRuntimeParams(knnKObjectJson, resetAll); Utility.debuggingLog(`ready to call Utility.getConfigJson(), LabelResolver.LabelResolver=${LabelResolver.LabelResolver}`); return LabelResolver.getConfigJson(); } // eslint-disable-next-line max-params // eslint-disable-next-line complexity public static scoreBatchStringLabels( utteranceLabelsPairArray: StructTextLabelStrings[], labelArrayAndMap: ILabelArrayAndMap, multiLabelPredictionThreshold: number, unknownLabelPredictionThreshold: number): PredictionStructureWithScoreLabelString[] { // ----------------------------------------------------------------------- Utility.debuggingLog('UtilityLabelResolver.scoreBatchStringLabels(), entering'); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), multiLabelPredictionThreshold="${multiLabelPredictionThreshold}"`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), unknownLabelPredictionThreshold="${unknownLabelPredictionThreshold}"`); } // ----------------------------------------------------------------------- // ---- NOTE-FOR-DEBUGGING-ONLY ---- Utility.resetToPrintDetailedDebuggingLogToConsole(true); // ---- NOTE-FOR-FUTURE ---- const hasUnknownLabelInMapAlready: boolean = Utility.UnknownLabel in labelArrayAndMap.stringMap; // ----------------------------------------------------------------------- const utterances: string[] = utteranceLabelsPairArray.map((x: StructTextLabelStrings) => x.text); const predictionStructureWithScoreLabelStringArray: PredictionStructureWithScoreLabelString[] = []; if (UtilityDispatcher.isEmptyStringArray(utterances)) { return predictionStructureWithScoreLabelStringArray; } const scoreResultsBatch: any = LabelResolver.scoreBatch(utterances, LabelType.Intent); if (utterances.length !== scoreResultsBatch.length) { UtilityDispatcher.debuggingNamedThrow2( 'utterances.length !== scoreResultsBatch.length', utterances.length, scoreResultsBatch.length, 'utterances.length', 'scoreResultsBatch.length'); } UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchStringLabels()', utterances.length, 'utterances.length'); UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchStringLabels()', scoreResultsBatch.length, 'scoreResultsBatch.length'); if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchStringLabels()', utterances, 'utterances'); } if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchStringLabels()', scoreResultsBatch, 'scoreResultsBatch'); } // ----------------------------------------------------------------------- for (let index: number = 0; index < scoreResultsBatch.length; index++) { // --------------------------------------------------------------------- const utteranceLabels: StructTextLabelStrings = utteranceLabelsPairArray[index]; const scoreResults: any = scoreResultsBatch[index]; if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchStringLabels()', index, 'index'); UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchStringLabels()', utteranceLabels, 'utteranceLabels'); UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchStringLabels()', scoreResults.length, 'scoreResults.length'); UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchStringLabels()', scoreResults, 'scoreResults'); } // --------------------------------------------------------------------- if (utteranceLabels) { // ------------------------------------------------------------------- const utterance: string = utteranceLabels.text; if (Utility.isEmptyString(utterance)) { Utility.debuggingThrow('UtilityLabelResolver.scoreBatchStringLabels() failed to produce a prediction for an empty utterance'); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), utterance=${utterance}`); } // ------------------------------------------------------------------- const labels: string[] = utteranceLabels.labels; const labelsIndexes: number[] = labels.map((x: string) => Utility.carefullyAccessStringMap( labelArrayAndMap.stringMap, x)); const labelsStringArray: string[] = labels.map((label: string) => Utility.outputString( label, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver)); // ------------------------------------------------------------------- const labelsConcatenated: string = Utility.concatenateDataArrayToDelimitedString( labelsStringArray); const labelsConcatenatedToHtmlTable: string = Utility.concatenateDataArrayToHtmlTable( '', // ---- 'Label', labelsStringArray); /** ---- NOTE-FOR-REFERENCE-ALTERNATIVE-LOGIC ---- * if (Utility.toPrintDetailedDebuggingLogToConsole) { * Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), before calling LabelResolver.score(), utterance=${utterance}`); * } * // Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), before calling LabelResolver.score(), utterance=${utterance}`); * const scoreResults: any = LabelResolver.score(utterance, LabelType.Intent); * // Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), after calling LabelResolver.LabelResolver.score(), utterance=${utterance}`); */ if (!scoreResults) { Utility.debuggingThrow(`UtilityLabelResolver.scoreBatchStringLabels() failed to produce a prediction for utterance "${utterance}"`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), scoreResults=${Utility.jsonStringify(scoreResults)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), scoreResults.length=${scoreResults.length}`); } const scoreResultArray: Result[] = Utility.scoreResultsToArray(scoreResults, labelArrayAndMap.stringMap); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), scoreResultArray=${Utility.jsonStringify(scoreResultArray)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), scoreResultArray.length=${scoreResultArray.length}`); } // ------------------------------------------------------------------- const scoreArray: number[] = scoreResultArray.map( (x: Result) => x.score); const argMax: { 'indexesMax': number[]; 'max': number } = ((multiLabelPredictionThreshold > 0) ? Utility.getIndexesOnMaxOrEntriesOverThreshold(scoreArray, multiLabelPredictionThreshold) : Utility.getIndexesOnMaxEntries(scoreArray)); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), argMax.indexesMax=${Utility.jsonStringify(argMax.indexesMax)}`); } const labelsPredictedScore: number = argMax.max; let labelsPredictedIndexes: number[] = argMax.indexesMax; let labelsPredicted: string[] = labelsPredictedIndexes.map((x: number) => scoreResultArray[x].label.name); const labelsPredictedStringArray: string[] = labelsPredicted.map((label: string) => Utility.outputString( label, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver)); let labelsPredictedClosestText: string[] = labelsPredictedIndexes.map((x: number) => scoreResultArray[x].closesttext); const unknownPrediction: boolean = labelsPredictedScore < unknownLabelPredictionThreshold; if (unknownPrediction) { labelsPredictedIndexes = [Utility.carefullyAccessStringMap(labelArrayAndMap.stringMap, Utility.UnknownLabel)]; labelsPredicted = [Utility.UnknownLabel]; labelsPredictedClosestText = []; } // ------------------------------------------------------------------- if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), labelsPredictedIndexes=${Utility.jsonStringify(labelsPredictedIndexes)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), labelsPredicted=${Utility.jsonStringify(labelsPredicted)}`); } // ------------------------------------------------------------------- const labelsPredictedConcatenated: string = Utility.concatenateDataArrayToDelimitedString( labelsPredictedStringArray); const labelsPredictedConcatenatedToHtmlTable: string = Utility.concatenateDataArrayToHtmlTable( '', // ---- 'Label', labelsPredictedStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), labelsPredictedConcatenated="${Utility.jsonStringify(labelsPredictedConcatenated)}"`); } const labelsPredictedEvaluation: number = Utility.evaluateMultiLabelSubsetPrediction(labels, labelsPredicted); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), labelsPredictedEvaluation="${labelsPredictedEvaluation}"`); } const predictedScoreStructureHtmlTable: string = Utility.selectedScoreResultsToHtmlTable( scoreResultArray, labelsPredictedIndexes, unknownLabelPredictionThreshold, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver, '', ['Label', 'Score', 'Closest Example'], ['30%', '10%', '60%']); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), predictedScoreStructureHtmlTable="${predictedScoreStructureHtmlTable}"`); } const labelsScoreStructureHtmlTable: string = Utility.selectedScoreResultsToHtmlTable( scoreResultArray, labelsIndexes, unknownLabelPredictionThreshold, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver, '', ['Label', 'Score', 'Closest Example'], ['30%', '10%', '60%']); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), labelsScoreStructureHtmlTable="${labelsScoreStructureHtmlTable}"`); } predictionStructureWithScoreLabelStringArray.push(new PredictionStructureWithScoreLabelString( utterance, labelsPredictedEvaluation, labels, labelsConcatenated, labelsConcatenatedToHtmlTable, labelsIndexes, labelsPredicted, labelsPredictedConcatenated, labelsPredictedConcatenatedToHtmlTable, labelsPredictedIndexes, labelsPredictedScore, labelsPredictedClosestText, scoreResultArray, scoreArray, predictedScoreStructureHtmlTable, labelsScoreStructureHtmlTable)); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), finished scoring for utterance "${utterance}"`); } // ---- NOTE ---- debugging ouput. if (Utility.toPrintDetailedDebuggingLogToConsole) { for (const result of scoreResults) { // eslint-disable-next-line max-depth if (result) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), result=${Utility.jsonStringify(result)}`); const closesttext: string = result.closesttext; const score: number = result.score; const label: any = result.label; const labelname: string = label.name; const labeltype: LabelType = label.labeltype; const span: any = label.span; const offset: number = span.offset; const length: number = span.length; Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), closesttext=${closesttext}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), score=${score}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), label=${Utility.jsonStringify(label)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), Object.keys(label)=${Object.keys(label)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), label.name=${labelname}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), label.labeltype=${labeltype}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), span=${Utility.jsonStringify(span)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), Object.keys(span)=${Object.keys(span)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), label.span.offset=${offset}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(), label.span.length=${length}`); } } } if ((predictionStructureWithScoreLabelStringArray.length % Utility.NumberOfInstancesPerProgressDisplayBatchForIntent) === 0) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(): Added predictionStructureWithScoreLabelStringArray.length=${predictionStructureWithScoreLabelStringArray.length}`); } // ------------------------------------------------------------------- } // --------------------------------------------------------------------- } // ----------------------------------------------------------------------- Utility.debuggingLog(`UtilityLabelResolver.scoreBatchStringLabels(): Total added predictionStructureWithScoreLabelStringArray.length=${predictionStructureWithScoreLabelStringArray.length}`); // Utility.debuggingLog('UtilityLabelResolver.scoreBatchStringLabels(), leaving'); // ----------------------------------------------------------------------- return predictionStructureWithScoreLabelStringArray; } // eslint-disable-next-line max-params // eslint-disable-next-line complexity public static scoreBatchObjectLabels( utteranceLabelsPairArray: StructTextLabelObjects[], labelArrayAndMap: ILabelArrayAndMap, multiLabelPredictionThreshold: number, unknownLabelPredictionThreshold: number): PredictionStructureWithScoreLabelObject[] { // ----------------------------------------------------------------------- if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), multiLabelPredictionThreshold="${multiLabelPredictionThreshold}"`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), unknownLabelPredictionThreshold="${unknownLabelPredictionThreshold}"`); } Utility.debuggingLog('UtilityLabelResolver.scoreBatchObjectLabels(), entering'); // ----------------------------------------------------------------------- // ---- NOTE-FOR-DEBUGGING-ONLY ---- Utility.resetToPrintDetailedDebuggingLogToConsole(true); // ---- NOTE-FOR-FUTURE ---- const hasUnknownLabelInMapAlready: boolean = Utility.UnknownLabel in labelArrayAndMap.stringMap; // ----------------------------------------------------------------------- const utterances: string[] = utteranceLabelsPairArray.map((x: StructTextLabelObjects) => x.text); const predictionStructureWithScoreLabelObjectArray: PredictionStructureWithScoreLabelObject[] = []; if (UtilityDispatcher.isEmptyStringArray(utterances)) { return predictionStructureWithScoreLabelObjectArray; } const scoreResultsBatch: any = LabelResolver.scoreBatch(utterances, LabelType.Entity); if (utterances.length !== scoreResultsBatch.length) { UtilityDispatcher.debuggingNamedThrow2( 'utterances.length !== scoreResultsBatch.length', utterances.length, scoreResultsBatch.length, 'utterances.length', 'scoreResultsBatch.length'); } UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchObjectLabels()', utterances.length, 'utterances.length'); UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchObjectLabels()', scoreResultsBatch.length, 'scoreResultsBatch.length'); if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchObjectLabels()', utterances, 'utterances'); } if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchObjectLabels()', scoreResultsBatch, 'scoreResultsBatch'); } // ----------------------------------------------------------------------- for (let index: number = 0; index < scoreResultsBatch.length; index++) { // --------------------------------------------------------------------- const utteranceLabels: StructTextLabelObjects = utteranceLabelsPairArray[index]; const scoreResults: any = scoreResultsBatch[index]; if (UtilityDispatcher.toPrintDetailedDebuggingLogToConsole) { UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchObjectLabels()', index, 'index'); UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchObjectLabels()', utteranceLabels, 'utteranceLabels'); UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchObjectLabels()', scoreResults.length, 'scoreResults.length'); UtilityDispatcher.debuggingNamedLog1('UtilityLabelResolver.scoreBatchObjectLabels()', scoreResults, 'scoreResults'); } // --------------------------------------------------------------------- if (utteranceLabels) { // ------------------------------------------------------------------- const utterance: string = utteranceLabels.text; if (Utility.isEmptyString(utterance)) { Utility.debuggingThrow('UtilityLabelResolver.scoreBatchObjectLabels() failed to produce a prediction for an empty utterance'); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), utterance=${utterance}`); } // ------------------------------------------------------------------- const labels: Label[] = utteranceLabels.labels; const labelsIndexes: number[] = labels.map((x: Label) => Utility.carefullyAccessStringMap( labelArrayAndMap.stringMap, x.name)); const labelsStringArray: string[] = labels.map((label: Label) => Utility.outputLabelString( label, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver)); // ------------------------------------------------------------------- const labelsConcatenated: string = Utility.concatenateDataArrayToDelimitedString( labelsStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsConcatenated=${labelsConcatenated}`); } const labelsConcatenatedToHtmlTable: string = Utility.concatenateDataArrayToHtmlTable( '', // ---- 'Label', labelsStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsConcatenatedToHtmlTable=${labelsConcatenatedToHtmlTable}`); } /** ---- NOTE-FOR-REFERENCE-ALTERNATIVE-LOGIC ---- * if (Utility.toPrintDetailedDebuggingLogToConsole) { * Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), before calling LabelResolver.score(), utterance=${utterance}`); * } * // Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), before calling LabelResolver.score(), utterance=${utterance}`); * const scoreResults: any = LabelResolver.score(utterance, LabelType.Entity); * // Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), after calling LabelResolver.LabelResolver.score(), utterance=${utterance}`); */ if (!scoreResults) { Utility.debuggingThrow(`UtilityLabelResolver.scoreBatchObjectLabels() failed to produce a prediction for utterance "${utterance}"`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), scoreResults=${Utility.jsonStringify(scoreResults)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), scoreResults.length=${scoreResults.length}`); } // Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), before calling Utility.scoreResultsToArray(), utterance=${utterance}`); const scoreResultArray: Result[] = Utility.scoreResultsToArray(scoreResults, labelArrayAndMap.stringMap); // Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), after calling Utility.scoreResultsToArray(), utterance=${utterance}`); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), scoreResultArray.length=${scoreResultArray.length}`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), scoreResultArray)=${Utility.jsonStringify(scoreResultArray)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), scoreResultArray.length=${scoreResultArray.length}`); } // ------------------------------------------------------------------- const scoreResultArrayFiltered: Result[] = scoreResultArray.filter((x: Result) => (x !== undefined)); // ------------------------------------------------------------------- const scoreArrayFiltered: number[] = scoreResultArrayFiltered.map( (x: Result) => ((x === undefined) ? 0 : x.score)); let argMax: { 'indexesMax': number[]; 'max': number } = {indexesMax: [], max: 0}; if (!Utility.isEmptyNumberArray(scoreArrayFiltered)) { argMax = ((multiLabelPredictionThreshold > 0) ? Utility.getIndexesOnMaxOrEntriesOverThreshold(scoreArrayFiltered, multiLabelPredictionThreshold) : Utility.getIndexesOnMaxEntries(scoreArrayFiltered)); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), argMax.indexesMax=${Utility.jsonStringify(argMax.indexesMax)}`); } // ------------------------------------------------------------------- const labelsPredictedScoreMax: number = argMax.max; const labelsPredictedIndexesMax: number[] = argMax.indexesMax; /** ---- NOTE-FOR-REFERENCE-all-entity-prediction-is-included-no-need-for-ArgMax-and-UNKNOWN-threshold ---- * let labelsPredictedMax: Label[] = * labelsPredictedIndexesMax.map((x: number) => scoreResultArray[x].label); */ // ------------------------------------------------------------------- const labelsPredicted: Label[] = scoreResultArrayFiltered.map((x: Result) => x.label); const labelsPredictedIndexes: number[] = labelsPredicted.map((x: Label) => Utility.carefullyAccessStringMap( labelArrayAndMap.stringMap, x.name)); const labelsPredictedStringArray: string[] = labelsPredicted.map((label: Label) => Utility.outputLabelString( label, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver)); // ------------------------------------------------------------------- const labelsPredictedClosestText: string[] = labelsPredictedIndexesMax.map((x: number) => scoreResultArrayFiltered[x].closesttext); /** ---- NOTE-FOR-REFERENCE-all-entity-prediction-is-included-no-need-for-ArgMax-and-UNKNOWN-threshold ---- * const unknownPrediction: boolean = labelsPredictedScoreMax < unknownLabelPredictionThreshold; * if (unknownPrediction) { * labelsPredictedIndexesMax = [Utility.carefullyAccessStringMap(labelArrayAndMap.stringMap, Utility.UnknownLabel)]; * labelsPredictedMax = [Label.newLabel(LabelType.Entity, Utility.UnknownLabel, 0, 0)]; * labelsPredictedClosestText = []; * } */ // ------------------------------------------------------------------- if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsPredictedIndexes=${Utility.jsonStringify(labelsPredictedIndexes)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsPredicted=${Utility.jsonStringify(labelsPredicted)}`); } // ------------------------------------------------------------------- const labelsPredictedConcatenated: string = Utility.concatenateDataArrayToDelimitedString( labelsPredictedStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsPredictedConcatenated=${labelsPredictedConcatenated}`); } const labelsPredictedConcatenatedToHtmlTable: string = Utility.concatenateDataArrayToHtmlTable( '', // ---- 'Label', labelsPredictedStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsPredictedConcatenatedToHtmlTable=${labelsPredictedConcatenatedToHtmlTable}`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsPredictedConcatenated="${Utility.jsonStringify(labelsPredictedConcatenated)}"`); } let labelsPredictedEvaluation: number = Utility.evaluateMultiLabelObjectExactPrediction(labels, labelsPredicted); if (labelsPredictedEvaluation === PredictionType.TrueNegative) { labelsPredictedEvaluation = PredictionType.FalseNegative; // ---- NOTE ----override the default logic, for entity, there is no true negative. } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsPredictedEvaluation="${labelsPredictedEvaluation}"`); } /** ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- * const predictedScoreStructureHtmlTable: string = * labelsPredictedConcatenatedToHtmlTable; */ const predictedScoreStructureHtmlTable: string = Utility.selectedScoreResultsToHtmlTable( scoreResultArrayFiltered, [...(new Array(scoreResultArrayFiltered.length)).keys()], // ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- labelsPredictedIndexes, unknownLabelPredictionThreshold, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver, '', ['Label', 'Score', 'Closest Example'], ['30%', '10%', '60%']); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), predictedScoreStructureHtmlTable="${predictedScoreStructureHtmlTable}"`); } // ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- const labelsScoreStructureHtmlTable: string = labelsConcatenatedToHtmlTable; /** ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- * const labelsScoreStructureHtmlTable: string = Utility.selectedScoreResultsToHtmlTable( * scoreResultArrayFiltered, * [...(new Array(scoreResultArrayFiltered.length)).keys()], // ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- labelsIndexes, * unknownLabelPredictionThreshold, * UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver, * '', * ['Label', 'Score', 'Closest Example'], * ['30%', '10%', '60%']); * if (Utility.toPrintDetailedDebuggingLogToConsole) { * Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), labelsScoreStructureHtmlTable="${labelsScoreStructureHtmlTable}"`); * } */ predictionStructureWithScoreLabelObjectArray.push(new PredictionStructureWithScoreLabelObject( utterance, labelsPredictedEvaluation, labels, labelsConcatenated, labelsConcatenatedToHtmlTable, labelsIndexes, labelsPredicted, labelsPredictedConcatenated, labelsPredictedConcatenatedToHtmlTable, labelsPredictedIndexes, labelsPredictedScoreMax, labelsPredictedClosestText, scoreResultArrayFiltered, scoreArrayFiltered, predictedScoreStructureHtmlTable, labelsScoreStructureHtmlTable)); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), finished scoring for utterance "${utterance}"`); } // ---- NOTE ---- debugging ouput. if (Utility.toPrintDetailedDebuggingLogToConsole) { for (const result of scoreResults) { // eslint-disable-next-line max-depth if (result) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), result=${Utility.jsonStringify(result)}`); const closesttext: string = result.closesttext; const score: number = result.score; const label: any = result.label; const labelname: string = label.name; const labeltype: LabelType = label.labeltype; const span: any = label.span; const offset: number = span.offset; const length: number = span.length; Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), closesttext=${closesttext}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), score=${score}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), label=${Utility.jsonStringify(label)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), Object.keys(label)=${Object.keys(label)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), label.name=${labelname}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), label.labeltype=${labeltype}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), span=${Utility.jsonStringify(span)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), Object.keys(span)=${Object.keys(span)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), label.span.offset=${offset}`); Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(), label.span.length=${length}`); } } } if ((predictionStructureWithScoreLabelObjectArray.length % Utility.NumberOfInstancesPerProgressDisplayBatchForEntity) === 0) { Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(): Added predictionStructureWithScoreLabelObjectArray.length=${predictionStructureWithScoreLabelObjectArray.length}`); } // ------------------------------------------------------------------- } // --------------------------------------------------------------------- } // ----------------------------------------------------------------------- Utility.debuggingLog(`UtilityLabelResolver.scoreBatchObjectLabels(): Total added predictionStructureWithScoreLabelObjectArray.length=${predictionStructureWithScoreLabelObjectArray.length}`); // Utility.debuggingLog('UtilityLabelResolver.scoreBatchObjectLabels(), leaving'); // ----------------------------------------------------------------------- return predictionStructureWithScoreLabelObjectArray; } // eslint-disable-next-line max-params // eslint-disable-next-line complexity public static scoreStringLabels( utteranceLabelsPairArray: StructTextLabelStrings[], labelArrayAndMap: ILabelArrayAndMap, multiLabelPredictionThreshold: number, unknownLabelPredictionThreshold: number): PredictionStructureWithScoreLabelString[] { // ----------------------------------------------------------------------- // Utility.debuggingLog('UtilityLabelResolver.scoreStringLabels(), entering'); // ----------------------------------------------------------------------- // ---- NOTE-FOR-DEBUGGING-ONLY ---- Utility.toPrintDetailedDebuggingLogToConsole = true; // ---- NOTE-FOR-FUTURE ---- const hasUnknownLabelInMapAlready: boolean = Utility.UnknownLabel in labelArrayAndMap.stringMap; // ----------------------------------------------------------------------- const predictionStructureWithScoreLabelStringArray: PredictionStructureWithScoreLabelString[] = []; for (const utteranceLabels of utteranceLabelsPairArray) { // --------------------------------------------------------------------- if (utteranceLabels) { const utterance: string = utteranceLabels.text; if (Utility.isEmptyString(utterance)) { Utility.debuggingThrow('UtilityLabelResolver.scoreStringLabels() failed to produce a prediction for an empty utterance'); } // Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), utterance=${utterance}`); // ------------------------------------------------------------------- const labels: string[] = utteranceLabels.labels; const labelsIndexes: number[] = labels.map((x: string) => Utility.carefullyAccessStringMap( labelArrayAndMap.stringMap, x)); const labelsStringArray: string[] = labels.map((label: string) => Utility.outputString( label, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver)); // ------------------------------------------------------------------- const labelsConcatenated: string = Utility.concatenateDataArrayToDelimitedString( labelsStringArray); const labelsConcatenatedToHtmlTable: string = Utility.concatenateDataArrayToHtmlTable( '', // ---- 'Label', labelsStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), before calling LabelResolver.score(), utterance=${utterance}`); } // Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), before calling LabelResolver.score(), utterance=${utterance}`); const scoreResults: any = LabelResolver.score(utterance, LabelType.Intent); // Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), after calling LabelResolver.LabelResolver.score(), utterance=${utterance}`); if (!scoreResults) { Utility.debuggingThrow(`UtilityLabelResolver.scoreStringLabels() failed to produce a prediction for utterance "${utterance}"`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), scoreResults=${Utility.jsonStringify(scoreResults)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), scoreResults.length=${scoreResults.length}`); } const scoreResultArray: Result[] = Utility.scoreResultsToArray(scoreResults, labelArrayAndMap.stringMap); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), scoreResultArray=${Utility.jsonStringify(scoreResultArray)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), scoreResultArray.length=${scoreResultArray.length}`); } // ------------------------------------------------------------------- const scoreArray: number[] = scoreResultArray.map( (x: Result) => x.score); const argMax: { 'indexesMax': number[]; 'max': number } = ((multiLabelPredictionThreshold > 0) ? Utility.getIndexesOnMaxOrEntriesOverThreshold(scoreArray, multiLabelPredictionThreshold) : Utility.getIndexesOnMaxEntries(scoreArray)); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), argMax.indexesMax=${Utility.jsonStringify(argMax.indexesMax)}`); } const labelsPredictedScore: number = argMax.max; let labelsPredictedIndexes: number[] = argMax.indexesMax; let labelsPredicted: string[] = labelsPredictedIndexes.map((x: number) => scoreResultArray[x].label.name); const labelsPredictedStringArray: string[] = labelsPredicted.map((label: string) => Utility.outputString( label, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver)); let labelsPredictedClosestText: string[] = labelsPredictedIndexes.map((x: number) => scoreResultArray[x].closesttext); const unknownPrediction: boolean = labelsPredictedScore < unknownLabelPredictionThreshold; if (unknownPrediction) { labelsPredictedIndexes = [Utility.carefullyAccessStringMap(labelArrayAndMap.stringMap, Utility.UnknownLabel)]; labelsPredicted = [Utility.UnknownLabel]; labelsPredictedClosestText = []; } // ------------------------------------------------------------------- if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), labelsPredictedIndexes=${Utility.jsonStringify(labelsPredictedIndexes)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), labelsPredicted=${Utility.jsonStringify(labelsPredicted)}`); } // ------------------------------------------------------------------- const labelsPredictedConcatenated: string = Utility.concatenateDataArrayToDelimitedString( labelsPredictedStringArray); const labelsPredictedConcatenatedToHtmlTable: string = Utility.concatenateDataArrayToHtmlTable( '', // ---- 'Label', labelsPredictedStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), labelsPredictedConcatenated="${Utility.jsonStringify(labelsPredictedConcatenated)}"`); } const labelsPredictedEvaluation: number = Utility.evaluateMultiLabelSubsetPrediction(labels, labelsPredicted); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), labelsPredictedEvaluation="${labelsPredictedEvaluation}"`); } const predictedScoreStructureHtmlTable: string = Utility.selectedScoreResultsToHtmlTable( scoreResultArray, labelsPredictedIndexes, unknownLabelPredictionThreshold, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver, '', ['Label', 'Score', 'Closest Example'], ['30%', '10%', '60%']); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), predictedScoreStructureHtmlTable="${predictedScoreStructureHtmlTable}"`); } const labelsScoreStructureHtmlTable: string = Utility.selectedScoreResultsToHtmlTable( scoreResultArray, labelsIndexes, unknownLabelPredictionThreshold, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver, '', ['Label', 'Score', 'Closest Example'], ['30%', '10%', '60%']); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), labelsScoreStructureHtmlTable="${labelsScoreStructureHtmlTable}"`); } predictionStructureWithScoreLabelStringArray.push(new PredictionStructureWithScoreLabelString( utterance, labelsPredictedEvaluation, labels, labelsConcatenated, labelsConcatenatedToHtmlTable, labelsIndexes, labelsPredicted, labelsPredictedConcatenated, labelsPredictedConcatenatedToHtmlTable, labelsPredictedIndexes, labelsPredictedScore, labelsPredictedClosestText, scoreResultArray, scoreArray, predictedScoreStructureHtmlTable, labelsScoreStructureHtmlTable)); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), finished scoring for utterance "${utterance}"`); } // ---- NOTE ---- debugging ouput. if (Utility.toPrintDetailedDebuggingLogToConsole) { for (const result of scoreResults) { // eslint-disable-next-line max-depth if (result) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), result=${Utility.jsonStringify(result)}`); const closesttext: string = result.closesttext; const score: number = result.score; const label: any = result.label; const labelname: string = label.name; const labeltype: LabelType = label.labeltype; const span: any = label.span; const offset: number = span.offset; const length: number = span.length; Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), closesttext=${closesttext}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), score=${score}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), label=${Utility.jsonStringify(label)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), Object.keys(label)=${Object.keys(label)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), label.name=${labelname}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), label.labeltype=${labeltype}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), span=${Utility.jsonStringify(span)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), Object.keys(span)=${Object.keys(span)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), label.span.offset=${offset}`); Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(), label.span.length=${length}`); } } } if ((predictionStructureWithScoreLabelStringArray.length % Utility.NumberOfInstancesPerProgressDisplayBatchForIntent) === 0) { Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(): Added predictionStructureWithScoreLabelStringArray.length=${predictionStructureWithScoreLabelStringArray.length}`); } } // --------------------------------------------------------------------- } Utility.debuggingLog(`UtilityLabelResolver.scoreStringLabels(): Total added predictionStructureWithScoreLabelStringArray.length=${predictionStructureWithScoreLabelStringArray.length}`); // Utility.debuggingLog('UtilityLabelResolver.scoreStringLabels(), leaving'); // ----------------------------------------------------------------------- return predictionStructureWithScoreLabelStringArray; } // eslint-disable-next-line max-params // eslint-disable-next-line complexity public static scoreObjectLabels( utteranceLabelsPairArray: StructTextLabelObjects[], labelArrayAndMap: ILabelArrayAndMap, multiLabelPredictionThreshold: number, unknownLabelPredictionThreshold: number): PredictionStructureWithScoreLabelObject[] { // ----------------------------------------------------------------------- // Utility.debuggingLog('UtilityLabelResolver.scoreObjectLabels(), entering'); // ----------------------------------------------------------------------- // ---- NOTE-FOR-DEBUGGING-ONLY ---- Utility.toPrintDetailedDebuggingLogToConsole = true; // ---- NOTE-FOR-FUTURE ---- const hasUnknownLabelInMapAlready: boolean = Utility.UnknownLabel in labelArrayAndMap.stringMap; const predictionStructureWithScoreLabelObjectArray: PredictionStructureWithScoreLabelObject[] = []; if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), unknownLabelPredictionThreshold="${unknownLabelPredictionThreshold}"`); } for (const utteranceLabels of utteranceLabelsPairArray) { // --------------------------------------------------------------------- if (utteranceLabels) { const utterance: string = utteranceLabels.text; if (Utility.isEmptyString(utterance)) { Utility.debuggingThrow('UtilityLabelResolver.scoreObjectLabels() failed to produce a prediction for an empty utterance'); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), utterance=${utterance}`); } // ------------------------------------------------------------------- const labels: Label[] = utteranceLabels.labels; const labelsIndexes: number[] = labels.map((x: Label) => Utility.carefullyAccessStringMap( labelArrayAndMap.stringMap, x.name)); const labelsStringArray: string[] = labels.map((label: Label) => Utility.outputLabelString( label, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver)); // ------------------------------------------------------------------- const labelsConcatenated: string = Utility.concatenateDataArrayToDelimitedString( labelsStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsConcatenated=${labelsConcatenated}`); } const labelsConcatenatedToHtmlTable: string = Utility.concatenateDataArrayToHtmlTable( '', // ---- 'Label', labelsStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsConcatenatedToHtmlTable=${labelsConcatenatedToHtmlTable}`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), before calling LabelResolver.score(), utterance=${utterance}`); } // Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), before calling LabelResolver.score(), utterance=${utterance}`); const scoreResults: any = LabelResolver.score(utterance, LabelType.Entity); // Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), after calling LabelResolver.LabelResolver.score(), utterance=${utterance}`); if (!scoreResults) { Utility.debuggingThrow(`UtilityLabelResolver.scoreObjectLabels() failed to produce a prediction for utterance "${utterance}"`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), scoreResults=${Utility.jsonStringify(scoreResults)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), scoreResults.length=${scoreResults.length}`); } // Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), before calling Utility.scoreResultsToArray(), utterance=${utterance}`); const scoreResultArray: Result[] = Utility.scoreResultsToArray(scoreResults, labelArrayAndMap.stringMap); // Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), after calling Utility.scoreResultsToArray(), utterance=${utterance}`); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), scoreResultArray.length=${scoreResultArray.length}`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), scoreResultArray)=${Utility.jsonStringify(scoreResultArray)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), scoreResultArray.length=${scoreResultArray.length}`); } // ------------------------------------------------------------------- const scoreResultArrayFiltered: Result[] = scoreResultArray.filter((x: Result) => (x !== undefined)); // ------------------------------------------------------------------- const scoreArrayFiltered: number[] = scoreResultArrayFiltered.map( (x: Result) => ((x === undefined) ? 0 : x.score)); let argMax: { 'indexesMax': number[]; 'max': number } = {indexesMax: [], max: 0}; if (!Utility.isEmptyNumberArray(scoreArrayFiltered)) { argMax = ((multiLabelPredictionThreshold > 0) ? Utility.getIndexesOnMaxOrEntriesOverThreshold(scoreArrayFiltered, multiLabelPredictionThreshold) : Utility.getIndexesOnMaxEntries(scoreArrayFiltered)); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), argMax.indexesMax=${Utility.jsonStringify(argMax.indexesMax)}`); } // ------------------------------------------------------------------- const labelsPredictedScoreMax: number = argMax.max; const labelsPredictedIndexesMax: number[] = argMax.indexesMax; /** ---- NOTE-FOR-REFERENCE-all-entity-prediction-is-included-no-need-for-ArgMax-and-UNKNOWN-threshold ---- * let labelsPredictedMax: Label[] = * labelsPredictedIndexesMax.map((x: number) => scoreResultArray[x].label); */ // ------------------------------------------------------------------- const labelsPredicted: Label[] = scoreResultArrayFiltered.map((x: Result) => x.label); const labelsPredictedIndexes: number[] = labelsPredicted.map((x: Label) => Utility.carefullyAccessStringMap( labelArrayAndMap.stringMap, x.name)); const labelsPredictedStringArray: string[] = labelsPredicted.map((label: Label) => Utility.outputLabelString( label, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver)); // ------------------------------------------------------------------- const labelsPredictedClosestText: string[] = labelsPredictedIndexesMax.map((x: number) => scoreResultArrayFiltered[x].closesttext); /** ---- NOTE-FOR-REFERENCE-all-entity-prediction-is-included-no-need-for-ArgMax-and-UNKNOWN-threshold ---- * const unknownPrediction: boolean = labelsPredictedScoreMax < unknownLabelPredictionThreshold; * if (unknownPrediction) { * labelsPredictedIndexesMax = [Utility.carefullyAccessStringMap(labelArrayAndMap.stringMap, Utility.UnknownLabel)]; * labelsPredictedMax = [Label.newLabel(LabelType.Entity, Utility.UnknownLabel, 0, 0)]; * labelsPredictedClosestText = []; * } */ // ------------------------------------------------------------------- if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsPredictedIndexes=${Utility.jsonStringify(labelsPredictedIndexes)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsPredicted=${Utility.jsonStringify(labelsPredicted)}`); } // ------------------------------------------------------------------- const labelsPredictedConcatenated: string = Utility.concatenateDataArrayToDelimitedString( labelsPredictedStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsPredictedConcatenated=${labelsPredictedConcatenated}`); } const labelsPredictedConcatenatedToHtmlTable: string = Utility.concatenateDataArrayToHtmlTable( '', // ---- 'Label', labelsPredictedStringArray); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsPredictedConcatenatedToHtmlTable=${labelsPredictedConcatenatedToHtmlTable}`); } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsPredictedConcatenated="${Utility.jsonStringify(labelsPredictedConcatenated)}"`); } let labelsPredictedEvaluation: number = Utility.evaluateMultiLabelObjectExactPrediction(labels, labelsPredicted); if (labelsPredictedEvaluation === PredictionType.TrueNegative) { labelsPredictedEvaluation = PredictionType.FalseNegative; // ---- NOTE ----override the default logic, for entity, there is no true negative. } if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsPredictedEvaluation="${labelsPredictedEvaluation}"`); } /** ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- * const predictedScoreStructureHtmlTable: string = * labelsPredictedConcatenatedToHtmlTable; */ const predictedScoreStructureHtmlTable: string = Utility.selectedScoreResultsToHtmlTable( scoreResultArrayFiltered, [...(new Array(scoreResultArrayFiltered.length)).keys()], // ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- labelsPredictedIndexes, unknownLabelPredictionThreshold, UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver, '', ['Label', 'Score', 'Closest Example'], ['30%', '10%', '60%']); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), predictedScoreStructureHtmlTable="${predictedScoreStructureHtmlTable}"`); } // ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- const labelsScoreStructureHtmlTable: string = labelsConcatenatedToHtmlTable; /** ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- * const labelsScoreStructureHtmlTable: string = Utility.selectedScoreResultsToHtmlTable( * scoreResultArrayFiltered, * [...(new Array(scoreResultArrayFiltered.length)).keys()], // ---- NOTE-MAY-NOT-HAVE-SCORE-FOR-ALL-LABELS ---- labelsIndexes, * unknownLabelPredictionThreshold, * UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver, * '', * ['Label', 'Score', 'Closest Example'], * ['30%', '10%', '60%']); * if (Utility.toPrintDetailedDebuggingLogToConsole) { * Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), labelsScoreStructureHtmlTable="${labelsScoreStructureHtmlTable}"`); * } */ predictionStructureWithScoreLabelObjectArray.push(new PredictionStructureWithScoreLabelObject( utterance, labelsPredictedEvaluation, labels, labelsConcatenated, labelsConcatenatedToHtmlTable, labelsIndexes, labelsPredicted, labelsPredictedConcatenated, labelsPredictedConcatenatedToHtmlTable, labelsPredictedIndexes, labelsPredictedScoreMax, labelsPredictedClosestText, scoreResultArrayFiltered, scoreArrayFiltered, predictedScoreStructureHtmlTable, labelsScoreStructureHtmlTable)); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), finished scoring for utterance "${utterance}"`); } // ---- NOTE ---- debugging ouput. if (Utility.toPrintDetailedDebuggingLogToConsole) { for (const result of scoreResults) { // eslint-disable-next-line max-depth if (result) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), result=${Utility.jsonStringify(result)}`); const closesttext: string = result.closesttext; const score: number = result.score; const label: any = result.label; const labelname: string = label.name; const labeltype: LabelType = label.labeltype; const span: any = label.span; const offset: number = span.offset; const length: number = span.length; Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), closesttext=${closesttext}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), score=${score}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), label=${Utility.jsonStringify(label)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), Object.keys(label)=${Object.keys(label)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), label.name=${labelname}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), label.labeltype=${labeltype}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), span=${Utility.jsonStringify(span)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), Object.keys(span)=${Object.keys(span)}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), label.span.offset=${offset}`); Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(), label.span.length=${length}`); } } } if ((predictionStructureWithScoreLabelObjectArray.length % Utility.NumberOfInstancesPerProgressDisplayBatchForEntity) === 0) { Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(): Added predictionStructureWithScoreLabelObjectArray.length=${predictionStructureWithScoreLabelObjectArray.length}`); } } // --------------------------------------------------------------------- } Utility.debuggingLog(`UtilityLabelResolver.scoreObjectLabels(): Total added predictionStructureWithScoreLabelObjectArray.length=${predictionStructureWithScoreLabelObjectArray.length}`); // Utility.debuggingLog('UtilityLabelResolver.scoreObjectLabels(), leaving'); // ----------------------------------------------------------------------- return predictionStructureWithScoreLabelObjectArray; } public static resetFlagToObfuscateLabelTextInReportUtilityLabelResolver(flag: boolean) { UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver = flag; } }
the_stack
import { createApiService, AppListCloudPage, BrowserActions, FilterProps, GroupIdentityService, IdentityService, LocalStorageUtil, LoginPage, ProcessDefinitionsService, ProcessInstancesService, QueryService, StringUtil, TasksService } from '@alfresco/adf-testing'; import { browser } from 'protractor'; import { ProcessCloudDemoPage } from './../pages/process-cloud-demo.page'; import { TasksCloudDemoPage } from './../pages/tasks-cloud-demo.page'; import { NavigationBarPage } from '../../core/pages/navigation-bar.page'; import { EditProcessFilterConfiguration } from './../config/edit-process-filter.config'; import { ProcessListCloudConfiguration } from './../config/process-list-cloud.config'; describe('Process list cloud', () => { // en-US values for the process status const PROCESS_STATUS = { ALL: 'All', RUNNING: 'Running', SUSPENDED: 'Suspended', COMPLETED: 'Completed' }; // en-US values for the sort direction const SORT_DIRECTION = { ASC: 'Ascending', DESC: 'Descending' }; describe('Process List', () => { const loginSSOPage = new LoginPage(); const navigationBarPage = new NavigationBarPage(); const appListCloudComponent = new AppListCloudPage(); const processCloudDemoPage = new ProcessCloudDemoPage(); const editProcessFilter = processCloudDemoPage.editProcessFilterCloudComponent(); const processList = processCloudDemoPage.processListCloudComponent(); const tasksCloudDemoPage = new TasksCloudDemoPage(); const apiService = createApiService(); const identityService = new IdentityService(apiService); const groupIdentityService = new GroupIdentityService(apiService); const processDefinitionService = new ProcessDefinitionsService(apiService); const processInstancesService = new ProcessInstancesService(apiService); const queryService = new QueryService(apiService); const tasksService = new TasksService(apiService); const processListCloudConfiguration = new ProcessListCloudConfiguration(); const editProcessFilterConfiguration = new EditProcessFilterConfiguration(); const processListCloudConfigFile = processListCloudConfiguration.getConfiguration(); const editProcessFilterConfigFile = editProcessFilterConfiguration.getConfiguration(); let completedProcess, runningProcessInstance, switchProcessInstance, noOfApps, testUser, groupInfo, anotherProcessInstance; const candidateBaseApp = browser.params.resources.ACTIVITI_CLOUD_APPS.CANDIDATE_BASE_APP.name; beforeAll(async () => { await apiService.loginWithProfile('identityAdmin'); testUser = await identityService.createIdentityUserWithRole( [identityService.ROLES.ACTIVITI_USER]); groupInfo = await groupIdentityService.getGroupInfoByGroupName('hr'); await identityService.addUserToGroup(testUser.idIdentityService, groupInfo.id); await apiService.login(testUser.username, testUser.password); const processDefinition = await processDefinitionService .getProcessDefinitionByName(browser.params.resources.ACTIVITI_CLOUD_APPS.CANDIDATE_BASE_APP.processes.candidateGroupProcess, candidateBaseApp); const anotherProcessDefinition = await processDefinitionService .getProcessDefinitionByName(browser.params.resources.ACTIVITI_CLOUD_APPS.CANDIDATE_BASE_APP.processes.anotherCandidateGroupProcess, candidateBaseApp); await processInstancesService.createProcessInstance(processDefinition.entry.key, candidateBaseApp); runningProcessInstance = await processInstancesService.createProcessInstance(processDefinition.entry.key, candidateBaseApp, { 'name': StringUtil.generateRandomString(), 'businessKey': StringUtil.generateRandomString() }); anotherProcessInstance = await processInstancesService.createProcessInstance(anotherProcessDefinition.entry.key, candidateBaseApp, { 'name': StringUtil.generateRandomString(), 'businessKey': StringUtil.generateRandomString() }); switchProcessInstance = await processInstancesService.createProcessInstance(processDefinition.entry.key, candidateBaseApp, { 'name': StringUtil.generateRandomString(), 'businessKey': StringUtil.generateRandomString() }); completedProcess = await processInstancesService.createProcessInstance(processDefinition.entry.key, candidateBaseApp, { 'name': StringUtil.generateRandomString(), 'businessKey': StringUtil.generateRandomString() }); const task = await queryService.getProcessInstanceTasks(completedProcess.entry.id, candidateBaseApp); const claimedTask = await tasksService.claimTask(task.list.entries[0].entry.id, candidateBaseApp); await tasksService.completeTask(claimedTask.entry.id, candidateBaseApp); await loginSSOPage.login(testUser.username, testUser.password); await LocalStorageUtil.setConfigField('adf-edit-process-filter', JSON.stringify(editProcessFilterConfigFile)); await LocalStorageUtil.setConfigField('adf-cloud-process-list', JSON.stringify(processListCloudConfigFile)); }); afterAll(async () => { await apiService.login(testUser.username, testUser.password); await processInstancesService.deleteProcessInstance(anotherProcessInstance.entry.id, candidateBaseApp); await apiService.loginWithProfile('identityAdmin'); await identityService.deleteIdentityUser(testUser.idIdentityService); }); beforeEach(async () => { await navigationBarPage.navigateToProcessServicesCloudPage(); await appListCloudComponent.checkApsContainer(); await appListCloudComponent.goToApp(candidateBaseApp); await tasksCloudDemoPage.taskListCloudComponent().checkTaskListIsLoaded(); await processCloudDemoPage.processFilterCloudComponent.clickOnProcessFilters(); }); async function setFilter(props: FilterProps): Promise<void> { await editProcessFilter.setFilter(props); await waitTillContentLoaded(); } async function waitTillContentLoaded() { await processList.getDataTable().waitTillContentLoaded(); } it('[C290069] Should display processes ordered by name when Name is selected from sort dropdown', async () => { await setFilter({ status: PROCESS_STATUS.RUNNING }); await setFilter({ sort: 'Name' }); await setFilter({ order: SORT_DIRECTION.ASC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.ASC, 'Name')).toBe(true); await setFilter({ order: SORT_DIRECTION.DESC}); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.DESC, 'Name')).toBe(true); }); it('[C291783] Should display processes ordered by id when Id is selected from sort dropdown', async () => { await setFilter({ status: PROCESS_STATUS.RUNNING }); await setFilter({ sort: 'Id'}); await setFilter({ order: SORT_DIRECTION.ASC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.ASC, 'Id')).toBe(true); await setFilter({ order: SORT_DIRECTION.DESC}); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.DESC, 'Id')).toBe(true); }); it('[C305054] Should display processes ordered by status when Status is selected from sort dropdown', async () => { await setFilter({ status: PROCESS_STATUS.ALL }); await setFilter({ sort: 'Status' }); await setFilter({ order: SORT_DIRECTION.ASC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.ASC, 'Status')).toBe(true); await setFilter({ order: SORT_DIRECTION.DESC}); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.DESC, 'Status')).toBe(true); }); it('[C305054] Should display processes ordered by started by when Started By is selected from sort dropdown', async () => { await setFilter({ status: PROCESS_STATUS.ALL }); await setFilter({ sort: 'Started by' }); await setFilter({ order: SORT_DIRECTION.ASC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.ASC, 'Started by')).toBe(true); await setFilter({ order: SORT_DIRECTION.DESC}); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.DESC, 'Started by')).toBe(true); }); it('[C305054] Should display processes ordered by processdefinitionid date when ProcessDefinitionId is selected from sort dropdown', async () => { await setFilter({ status: PROCESS_STATUS.ALL }); await setFilter({ sort: 'ProcessDefinitionId' }); await setFilter({ order: SORT_DIRECTION.ASC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.ASC, 'Process Definition Id')).toBe(true); await setFilter({ order: SORT_DIRECTION.DESC}); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.DESC, 'Process Definition Id')).toBe(true); }); it('[C305054] Should display processes ordered by processdefinitionkey date when ProcessDefinitionKey is selected from sort dropdown', async () => { await setFilter({ status: PROCESS_STATUS.ALL }); await setFilter({ sort: 'ProcessDefinitionKey' }); await setFilter({ order: SORT_DIRECTION.ASC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.ASC, 'Process Definition Key')).toBe(true); await setFilter({ order: SORT_DIRECTION.DESC}); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.DESC, 'Process Definition Key')).toBe(true); }); it('[C305054] Should display processes ordered by last modified date when Last Modified is selected from sort dropdown', async () => { await setFilter({ status: PROCESS_STATUS.ALL }); await setFilter({ sort: 'Last Modified' }); await setFilter({ order: SORT_DIRECTION.ASC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.ASC, 'Last Modified')).toBe(true); await setFilter({ order: SORT_DIRECTION.DESC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.DESC, 'Last Modified')).toBe(true); }); it('[C305054] Should display processes ordered by business key date when BusinessKey is selected from sort dropdown', async () => { await setFilter({ status: PROCESS_STATUS.ALL }); await setFilter({ sort: 'Business Key' }); await setFilter({ order: SORT_DIRECTION.ASC }); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.ASC, 'Business Key')).toBe(true); await setFilter({ order: SORT_DIRECTION.DESC}); await expect(await processList.getDataTable().checkListIsSorted(SORT_DIRECTION.DESC, 'Business Key')).toBe(true); }); it('[C297697] The value of the filter should be preserved when saving it', async () => { await processCloudDemoPage.processFilterCloudComponent.clickAllProcessesFilter(); await editProcessFilter.openFilter(); await editProcessFilter.setProcessInstanceId(completedProcess.entry.id); await editProcessFilter.saveAs('New'); await expect(await processCloudDemoPage.processFilterCloudComponent.getActiveFilterName()).toBe('New'); await processList.checkContentIsDisplayedById(completedProcess.entry.id); await expect(await processList.getDataTable().numberOfRows()).toBe(1); await editProcessFilter.openFilter(); await expect(await editProcessFilter.getProcessInstanceId()).toEqual(completedProcess.entry.id); }); it('[C297646] Should display the filter dropdown fine , after switching between saved filters', async () => { await editProcessFilter.openFilter(); noOfApps = await editProcessFilter.getNumberOfAppNameOptions(); await expect(await editProcessFilter.checkAppNamesAreUnique()).toBe(true); await BrowserActions.closeMenuAndDialogs(); await editProcessFilter.setStatusFilterDropDown(PROCESS_STATUS.RUNNING); await editProcessFilter.setAppNameDropDown(candidateBaseApp); await editProcessFilter.setProcessInstanceId(runningProcessInstance.entry.id); await waitTillContentLoaded(); await processList.checkContentIsDisplayedById(runningProcessInstance.entry.id); await expect(await editProcessFilter.getNumberOfAppNameOptions()).toBe(noOfApps); await expect(await editProcessFilter.checkAppNamesAreUnique()).toBe(true); await BrowserActions.closeMenuAndDialogs(); await editProcessFilter.saveAs('SavedFilter'); await expect(await processCloudDemoPage.processFilterCloudComponent.getActiveFilterName()).toBe('SavedFilter'); await editProcessFilter.openFilter(); await expect(await editProcessFilter.getProcessInstanceId()).toEqual(runningProcessInstance.entry.id); await editProcessFilter.setStatusFilterDropDown(PROCESS_STATUS.RUNNING); await editProcessFilter.setAppNameDropDown(candidateBaseApp); await editProcessFilter.setProcessInstanceId(switchProcessInstance.entry.id); await waitTillContentLoaded(); await processList.checkContentIsDisplayedById(switchProcessInstance.entry.id); await editProcessFilter.saveAs('SwitchFilter'); await expect(await processCloudDemoPage.processFilterCloudComponent.getActiveFilterName()).toBe('SwitchFilter'); await editProcessFilter.openFilter(); await expect(await editProcessFilter.getProcessInstanceId()).toEqual(switchProcessInstance.entry.id); await expect(await editProcessFilter.getNumberOfAppNameOptions()).toBe(noOfApps); await expect(await editProcessFilter.checkAppNamesAreUnique()).toBe(true); await BrowserActions.closeMenuAndDialogs(); }); }); });
the_stack
import Opt = require('../../Opt'); import util = require('../../util/index'); import fs = require("fs"); import path = require("path"); import mkdirp = require("mkdirp"); var webpack = require("webpack"); import depMan=require("./dependencyManager"); import fsutil=require("../../util/fsutil"); var tsc = require('typescript-compiler'); import cp = require('child_process') import devUtil = require('../../devUtil/devUtils') var initializerFileName = 'raml1Parser'; var initializerTypescriptFileName = initializerFileName + '.ts'; var bundledJSFileName = initializerFileName + '.js'; var browserBundleJSFileName = 'raml-1-parser.js'; //import aUtils = require("./automation/impl/automationUtils"); export function deployBundle(dstPath:string,tmpFolder:string, uglify:boolean=false):Promise<void>{ var outputFolder = path.resolve(dstPath,'src'); mkdirp.sync(outputFolder); mkdirp.sync(tmpFolder); var setterPath = path.resolve(tmpFolder, initializerTypescriptFileName); var targetDir = path.dirname(setterPath); mkdirp.sync(targetDir); fs.writeFileSync(setterPath,getRamlModuleCode()); tsc.compile([ setterPath ], '-m commonjs'); var plugins = uglify ? [ new webpack.optimize.UglifyJsPlugin({ minimize: true, compress: {} }) ] : []; var config = { context: tmpFolder, entry: path.resolve(tmpFolder, bundledJSFileName), output: { path: outputFolder, filename: "raml1Parser.js", libraryTarget: "commonjs2" }, externals: [ { "buffer" : true, "concat-stream" : true, "esprima" : true, "fs" : true, "http-response-object" : true, "json-schema-compatibility" : true, "json-stable-stringify" : true, "know-your-http-well" : true, "loophole" : true, "lrucache" : true, "media-typer" : true, "path" : true, "pluralize" : true, "then-request" : true, "typescript" : true, "underscore" : true, "url": true, "xmldom" : true, "xmlhttprequest": true, "xhr2": true, "z-schema" : true, } ], plugins: plugins, module: { loaders: [ { test: /\.json$/, loader: "json" } ] }, node: { console: false, global: true, process: true, Buffer: true, __filename: true, __dirname: true, setImmediate: true } }; return new Promise<void>(function(resolve, reject) { webpack(config, function (err, stats) { if (err) { Promise.reject(err); } var bundlePath = path.resolve(outputFolder, 'raml1Parser.js'); var content = fs.readFileSync(bundlePath).toString(); var contentPatched = content.replace('module.exports = require("typescript");', "module.exports = {};"); fs.writeFileSync(bundlePath, contentPatched); console.log("Webpack Building Bundle:"); console.log(stats.toString({reasons: true, errorDetails: true})); Promise.resolve(); }); }); } function installNodeModules(path : string) { console.log("Installing node modules for :" + path); devUtil.execProcess("npm install", path, false, true, "Installing node modules", "Finished installing node modules"); console.log("Finished installing node modules for :" + path); } function webPackForBrowser(commonJSBundlePath : string, targetFileName : string, callback?:()=>void) { console.log("Preparing to Webpack browser bundle:"); var plugins = []; var folder = path.dirname(commonJSBundlePath); var file = path.basename(commonJSBundlePath); var config = { context: folder, entry: commonJSBundlePath, output: { path: folder, library: ['RAML', 'Parser'], filename: targetFileName, libraryTarget: "umd" }, plugins: plugins, module: { loaders: [ { test: /\.json$/, loader: "json" } ] } }; webpack(config, function(err, stats) { if(err) { console.log(err.message); return; } console.log("Webpack Building Browser Bundle:"); console.log(stats.toString({reasons : true, errorDetails: true})); if(callback) { callback(); } }); } function copyStaticBrowserPackageContents(browserDestinationPath : string, packageJsonPath: string) { var browserStaticPackagePath = path.resolve(__dirname, "../../../js_parser/static/browser_package"); if(!fs.existsSync(browserStaticPackagePath)) { console.log("Can not find static browser package: " + browserStaticPackagePath); return; } var packageJsonContents = fs.readFileSync(packageJsonPath).toString(); var config = JSON.parse(packageJsonContents); var moduleVersion = config.version; var bowerJsonContents = fs.readFileSync(path.resolve(browserStaticPackagePath, "bower.json")).toString(); var updatedBowerJsonContents = bowerJsonContents.replace("$version", moduleVersion); fs.writeFileSync(path.resolve(browserDestinationPath, "bower.json"), updatedBowerJsonContents) fsutil.copyDirSyncRecursive(path.resolve(browserDestinationPath, "examples"), path.resolve(browserStaticPackagePath, "examples")); } function createBrowserPackage(bundlePath:string, browserDestinationPath: string, tmpFolder:string, callback?:()=>void) { mkdirp.sync(bundlePath); mkdirp.sync(browserDestinationPath); var browserBundlingTmpFolder = path.resolve(tmpFolder, "browser_bundling"); mkdirp.sync(browserBundlingTmpFolder); var bundledCommonJSFilePath = path.resolve(bundlePath, "src/"+bundledJSFileName); var tempCommonJSFilePath = path.resolve(browserBundlingTmpFolder, bundledJSFileName); fsutil.copyFileSync(bundledCommonJSFilePath, tempCommonJSFilePath) var bundledPackageJson = path.resolve(bundlePath, "package.json"); var tmpPackageJson = path.resolve(browserBundlingTmpFolder, "package.json"); fsutil.copyFileSync(bundledPackageJson, tmpPackageJson); fsutil.copyDirSyncRecursive(path.resolve(browserBundlingTmpFolder,"web-tools"), path.resolve(bundlePath,"web-tools")); copyStaticBrowserPackageContents(browserDestinationPath, bundledPackageJson); installNodeModules(browserBundlingTmpFolder); webPackForBrowser(tempCommonJSFilePath, browserBundleJSFileName, function(){ console.log("Copying webpacked browser bundle to destination") var source = path.resolve(browserBundlingTmpFolder, browserBundleJSFileName); var target = path.resolve(browserDestinationPath, browserBundleJSFileName); fsutil.copyFileSync(source, target); if(callback) callback(); }); } function generateTypings(dstPath:string,tmpFolder:string){ mkdirp.sync(tmpFolder); var ramlModulePath = path.resolve(tmpFolder, initializerTypescriptFileName); fs.writeFileSync(ramlModulePath,getRamlModuleCode()); var dm = new depMan.DependencyManager(); dm.transportDependencies(ramlModulePath, path.resolve(tmpFolder,'../../'), tmpFolder, './'); //Object.keys(dm.modules).forEach(x=>console.log(x)); var compileLog = tsc.compile([ ramlModulePath ], '-m commonjs -d'); //console.log(compileLog); fsutil.copyDirSyncRecursive( path.resolve(dstPath,'parser-typings'), tmpFolder, { forceDelete:true }, x => fs.lstatSync(x).isDirectory() || util.stringEndsWith(x,'.d.ts') ); } function generateDocumentation(dstPath:string,tmpFolder){ var projectFolder = __dirname; while(!fs.existsSync(path.resolve(projectFolder,"gulpfile.js"))){ projectFolder = path.resolve(projectFolder,"../"); } var themeFolder = path.resolve(projectFolder,'src/devUtil/documentation'); console.log('Generating documentation...'); var docGenTmpFolder = path.resolve(tmpFolder, 'documentation'); mkdirp.sync(docGenTmpFolder) var callPath = "typedoc" + " --out " + docGenTmpFolder + " " + path.resolve(projectFolder,'./src/index.ts') + " --theme " + themeFolder + " --includeDeclarations" + " --name \"RAML JS Parser 2\"" + " --module commonjs"; devUtil.execProcess( callPath, process.cwd() ); var docGenDstFolder = path.resolve(dstPath, 'documentation'); fs.readdirSync(docGenTmpFolder).map(x=>path.resolve(docGenDstFolder,x)).forEach(x=>fsutil.removeDirSyncRecursive(x)); fsutil.copyDirSyncRecursive(docGenDstFolder,docGenTmpFolder); console.log('Documentation has been copied to ' + docGenDstFolder); } function getRamlModuleCode():string{ return ` import apiLoader = require('../../src/ramlscript/apiLoader'); import json2lowlevel = require('../../src/parser/jsyaml/json2lowLevel') import RamlWrapper = require('../../src/parser/artifacts/raml10parser') import parserCore = require('../../src/parser/wrapped-ast/parserCore') import Opt = require('../../src/Opt'); import typeSystem=require("../../src/parser/definition-system/typeSystem"); export function loadApiSync( apiPath:string, extensionsAndOverlays?:string[], options?:parserCore.Options):RamlWrapper.Api{ return RamlWrapper.loadApiSync(apiPath,extensionsAndOverlays,options); } export function loadApi( apiPath:string, extensionsAndOverlays?:string[], options?:parserCore.Options):Promise<RamlWrapper.Api>{ return RamlWrapper.loadApi(apiPath,extensionsAndOverlays,options); } export function loadRAMLSync( apiPath:string, extensionsAndOverlays?:string[], options?:parserCore.Options):RamlWrapper.RAMLLanguageElement{ return RamlWrapper.loadRAMLSync(apiPath,extensionsAndOverlays,options); } export function loadRAML( apiPath:string, extensionsAndOverlays?:string[], options?:parserCore.Options):Promise<RamlWrapper.RAMLLanguageElement>{ return RamlWrapper.loadRAML(apiPath,extensionsAndOverlays,options); } /** * Gets AST node by runtime type, if runtime type matches any. * @param runtimeType - runtime type to find the match for */ export function getLanguageElementByRuntimeType(runtimeType : typeSystem.ITypeDefinition) : parserCore.BasicNode { return RamlWrapper.getLanguageElementByRuntimeType(runtimeType); } `; } var dstPath; var browserDstPath; var skipSources = false; var args:string[] = process.argv; for(var i = 0 ; i < args.length ; i++){ if(args[i]=='-dstPath' && i < args.length-1){ dstPath = args[i+1] } if(args[i]=='-browserDstPath' && i < args.length-1){ browserDstPath = args[i+1] } if(args[i]=='-skipSources'){ skipSources = true; } } if(dstPath==null) { dstPath = path.resolve(process.cwd(),"packagedParser"); } var tmpFolder = path.resolve(process.cwd(), '____parser_package_tmp'); var typingsFolder = path.resolve(tmpFolder, 'typings'); var bundleFolder = path.resolve(tmpFolder, 'bundle'); var cleanup = function ():void { console.log('Removing ' + tmpFolder + ' ...'); fsutil.removeDirSyncRecursive(tmpFolder); console.log('Folder has been removed: ' + tmpFolder); } if (skipSources) { dstPath = path.resolve(dstPath,"../"); generateDocumentation(dstPath, tmpFolder); cleanup(); } else { generateTypings(dstPath, typingsFolder); deployBundle(dstPath, bundleFolder).then(()=> { generateDocumentation(dstPath, tmpFolder); if (browserDstPath) { createBrowserPackage(dstPath, browserDstPath, tmpFolder, ()=> { cleanup() }); } else { cleanup(); } }); }
the_stack
import { emptyArray } from "../platform.js"; import { Notifier, Subscriber, SubscriberSet } from "./notifier.js"; import { Observable } from "./observable.js"; import { Updates } from "./update-queue.js"; /** * A splice map is a representation of how a previous array of items * was transformed into a new array of items. Conceptually it is a list of * tuples of * * (index, removed, addedCount) * * which are kept in ascending index order of. The tuple represents that at * the |index|, |removed| sequence of items were removed, and counting forward * from |index|, |addedCount| items were added. * @public */ export class Splice { /** * Indicates that this splice represents a complete array reset. */ public reset?: boolean; /** * Creates a splice. * @param index - The index that the splice occurs at. * @param removed - The items that were removed. * @param addedCount - The number of items that were added. */ public constructor( public index: number, public removed: any[], public addedCount: number ) {} /** * Adjusts the splice index based on the provided array. * @param array - The array to adjust to. * @returns The same splice, mutated based on the reference array. */ public adjustTo(array: any[]): this { let index = this.index; const arrayLength = array.length; if (index > arrayLength) { index = arrayLength - this.addedCount; } else if (index < 0) { index = arrayLength + this.removed.length + index - this.addedCount; } this.index = index < 0 ? 0 : index; return this; } } /** * Indicates what level of feature support the splice * strategy provides. * @public */ export const SpliceStrategySupport = Object.freeze({ /** * Only supports resets. */ reset: 1, /** * Supports tracking splices and resets. */ splice: 2, /** * Supports tracking splices and resets, while applying some form * of optimization, such as merging, to the splices. */ optimized: 3, } as const); /** * The available values for SpliceStrategySupport. * @public */ export type SpliceStrategySupport = typeof SpliceStrategySupport[keyof typeof SpliceStrategySupport]; /** * An approach to tracking changes in an array. * @public */ export interface SpliceStrategy { /** * The level of feature support the splice strategy provides. */ readonly support: SpliceStrategySupport; /** * Normalizes the splices before delivery to array change subscribers. * @param previous - The previous version of the array if a reset has taken place. * @param current - The current version of the array. * @param changes - The set of changes tracked against the array. */ normalize( previous: unknown[] | undefined, current: unknown[], changes: Splice[] | undefined ): readonly Splice[]; /** * Performs and tracks a pop operation on an array. * @param array - The array to track the change for. * @param observer - The observer to register the change with. * @param pop - The operation to perform. * @param args - The arguments for the operation. */ pop( array: any[], observer: ArrayObserver, pop: typeof Array.prototype.pop, args: any[] ): any; /** * Performs and tracks a push operation on an array. * @param array - The array to track the change for. * @param observer - The observer to register the change with. * @param push - The operation to perform. * @param args - The arguments for the operation. */ push( array: any[], observer: ArrayObserver, push: typeof Array.prototype.push, args: any[] ): any; /** * Performs and tracks a reverse operation on an array. * @param array - The array to track the change for. * @param observer - The observer to register the change with. * @param reverse - The operation to perform. * @param args - The arguments for the operation. */ reverse( array: any[], observer: ArrayObserver, reverse: typeof Array.prototype.reverse, args: any[] ): any; /** * Performs and tracks a shift operation on an array. * @param array - The array to track the change for. * @param observer - The observer to register the change with. * @param shift - The operation to perform. * @param args - The arguments for the operation. */ shift( array: any[], observer: ArrayObserver, shift: typeof Array.prototype.shift, args: any[] ): any; /** * Performs and tracks a sort operation on an array. * @param array - The array to track the change for. * @param observer - The observer to register the change with. * @param sort - The operation to perform. * @param args - The arguments for the operation. */ sort( array: any[], observer: ArrayObserver, sort: typeof Array.prototype.sort, args: any[] ): any[]; /** * Performs and tracks a splice operation on an array. * @param array - The array to track the change for. * @param observer - The observer to register the change with. * @param splice - The operation to perform. * @param args - The arguments for the operation. */ splice( array: any[], observer: ArrayObserver, splice: typeof Array.prototype.splice, args: any[] ): any; /** * Performs and tracks an unshift operation on an array. * @param array - The array to track the change for. * @param observer - The observer to register the change with. * @param unshift - The operation to perform. * @param args - The arguments for the operation. */ unshift( array: any[], observer: ArrayObserver, unshift: typeof Array.prototype.unshift, args: any[] ): any[]; } const reset = new Splice(0, emptyArray as any, 0); reset.reset = true; const resetSplices = [reset]; let defaultSpliceStrategy: SpliceStrategy = Object.freeze({ support: SpliceStrategySupport.splice, normalize( previous: unknown[] | undefined, current: unknown[], changes: Splice[] | undefined ): readonly Splice[] { return previous === void 0 ? changes ?? emptyArray : resetSplices; }, pop( array: any[], observer: ArrayObserver, pop: typeof Array.prototype.pop, args: any[] ) { const notEmpty = array.length > 0; const result = pop.apply(array, args); if (notEmpty) { observer.addSplice(new Splice(array.length, [result], 0)); } return result; }, push( array: any[], observer: ArrayObserver, push: typeof Array.prototype.push, args: any[] ): any { const result = push.apply(array, args); observer.addSplice( new Splice(array.length - args.length, [], args.length).adjustTo(array) ); return result; }, reverse( array: any[], observer: ArrayObserver, reverse: typeof Array.prototype.reverse, args: any[] ): any { const result = reverse.apply(array, args); observer.reset(array); return result; }, shift( array: any[], observer: ArrayObserver, shift: typeof Array.prototype.shift, args: any[] ): any { const notEmpty = array.length > 0; const result = shift.apply(array, args); if (notEmpty) { observer.addSplice(new Splice(0, [result], 0)); } return result; }, sort( array: any[], observer: ArrayObserver, sort: typeof Array.prototype.sort, args: any[] ): any[] { const result = sort.apply(array, args); observer.reset(array); return result; }, splice( array: any[], observer: ArrayObserver, splice: typeof Array.prototype.splice, args: any[] ): any { const result = splice.apply(array, args); observer.addSplice( new Splice(+args[0], result, args.length > 2 ? args.length - 2 : 0).adjustTo( array ) ); return result; }, unshift( array: any[], observer: ArrayObserver, unshift: typeof Array.prototype.unshift, args: any[] ): any[] { const result = unshift.apply(array, args); observer.addSplice(new Splice(0, [], args.length).adjustTo(array)); return result; }, }); /** * Functionality related to tracking changes in arrays. * @public */ export const SpliceStrategy = Object.freeze({ /** * A set of changes that represent a full array reset. */ reset: resetSplices, /** * Sets the default strategy to use for array observers. * @param strategy - The splice strategy to use. */ setDefaultStrategy(strategy: SpliceStrategy) { defaultSpliceStrategy = strategy; }, } as const); function setNonEnumerable(target: any, property: string, value: any): void { Reflect.defineProperty(target, property, { value, enumerable: false, }); } /** * Observes array lengths. * @public */ export interface LengthObserver extends Subscriber { /** * The length of the observed array. */ length: number; } /** * An observer for arrays. * @public */ export interface ArrayObserver extends SubscriberSet { /** * The strategy to use for tracking changes. */ strategy: SpliceStrategy | null; /** * The length observer for the array. */ readonly lengthObserver: LengthObserver; /** * Adds a splice to the list of changes. * @param splice - The splice to add. */ addSplice(splice: Splice): void; /** * Indicates that a reset change has occurred. * @param oldCollection - The collection as it was before the reset. */ reset(oldCollection: any[] | undefined): void; /** * Flushes the changes to subscribers. */ flush(): void; } class DefaultArrayObserver extends SubscriberSet implements ArrayObserver { private oldCollection: any[] | undefined = void 0; private splices: Splice[] | undefined = void 0; private needsQueue: boolean = true; private _strategy: SpliceStrategy | null = null; private _lengthObserver: LengthObserver | undefined = void 0; public get strategy(): SpliceStrategy | null { return this._strategy; } public set strategy(value: SpliceStrategy | null) { this._strategy = value; } public get lengthObserver(): LengthObserver { let observer = this._lengthObserver; if (observer === void 0) { const array = this.subject; this._lengthObserver = observer = { length: array.length, handleChange() { if (this.length !== array.length) { this.length = array.length; Observable.notify(observer, "length"); } }, }; this.subscribe(observer); } return observer; } call: () => void = this.flush; constructor(subject: any[]) { super(subject); setNonEnumerable(subject, "$fastController", this); } public subscribe(subscriber: Subscriber): void { this.flush(); super.subscribe(subscriber); } public addSplice(splice: Splice) { if (this.splices === void 0) { this.splices = [splice]; } else { this.splices.push(splice); } this.enqueue(); } public reset(oldCollection: any[] | undefined): void { this.oldCollection = oldCollection; this.enqueue(); } public flush(): void { const splices = this.splices; const oldCollection = this.oldCollection; if (splices === void 0 && oldCollection === void 0) { return; } this.needsQueue = true; this.splices = void 0; this.oldCollection = void 0; this.notify( (this._strategy ?? defaultSpliceStrategy).normalize( oldCollection, this.subject, splices ) ); } private enqueue(): void { if (this.needsQueue) { this.needsQueue = false; Updates.enqueue(this); } } } let enabled = false; /** * An observer for arrays. * @public */ export const ArrayObserver = Object.freeze({ /** * Enables the array observation mechanism. * @remarks * Array observation is enabled automatically when using the * {@link RepeatDirective}, so calling this API manually is * not typically necessary. */ enable(): void { if (enabled) { return; } enabled = true; Observable.setArrayObserverFactory( (collection: any[]): Notifier => new DefaultArrayObserver(collection) ); const proto = Array.prototype; if (!(proto as any).$fastPatch) { setNonEnumerable(proto, "$fastPatch", 1); [ proto.pop, proto.push, proto.reverse, proto.shift, proto.sort, proto.splice, proto.unshift, ].forEach(method => { proto[method.name] = function (...args) { const o = this.$fastController as ArrayObserver; return o === void 0 ? method.apply(this, args) : (o.strategy ?? defaultSpliceStrategy)[method.name]( this, o, method, args ); }; }); } }, } as const); /** * Enables observing the length of an array. * @param array - The array to observe the length of. * @returns The length of the array. * @public */ export function length<T>(array: readonly T[]): number { if (!array) { return 0; } let arrayObserver = (array as any).$fastController as ArrayObserver; if (arrayObserver === void 0) { ArrayObserver.enable(); arrayObserver = Observable.getNotifier<ArrayObserver>(array); } Observable.track(arrayObserver.lengthObserver, "length"); return array.length; }
the_stack
import { PlateEditor } from '@udecode/plate-core'; import { jsx } from '@udecode/plate-test-utils'; import { createPlateTestEditor } from '../../../core/src/common/__tests__/createPlateTestEditor'; import { createTablePlugin } from './createTablePlugin'; jsx; describe('onKeyDownTable', () => { // https://github.com/udecode/editor-protocol/issues/26 describe('when arrow up from a cell', () => { it('should move selection to cell above', async () => { const input = (( <editor> <htable> <htr> <htd>11</htd> <htd>12</htd> </htr> <htr> <htd> 21 <cursor /> </htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const output = (( <editor> <htable> <htr> <htd> <cursor /> 11 </htd> <htd>12</htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const [editor, { triggerKeyboardEvent }] = await createPlateTestEditor({ editor: input, plugins: [createTablePlugin()], }); await triggerKeyboardEvent('ArrowUp'); expect(editor.selection).toEqual(output.selection); }); }); // https://github.com/udecode/editor-protocol/issues/27 describe('when arrow down from a cell', () => { it('should move selection to cell below', async () => { const input = (( <editor> <htable> <htr> <htd> 11 <cursor /> </htd> <htd>12</htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const output = (( <editor> <htable> <htr> <htd>11</htd> <htd>12</htd> </htr> <htr> <htd> <cursor /> 21 </htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const [editor, { triggerKeyboardEvent }] = await createPlateTestEditor({ editor: input, plugins: [createTablePlugin()], }); await triggerKeyboardEvent('ArrowDown'); expect(editor.selection).toEqual(output.selection); }); }); // https://github.com/udecode/editor-protocol/issues/28 describe('when arrow up from a cell in first row', () => { it('should move selection before table', async () => { const input = (( <editor> <hp>test</hp> <htable> <htr> <htd>11</htd> <htd> 12 <cursor /> </htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const output = (( <editor> <hp> test <cursor /> </hp> <htable> <htr> <htd>11</htd> <htd>12</htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const [editor, { triggerKeyboardEvent }] = await createPlateTestEditor({ editor: input, plugins: [createTablePlugin()], }); await triggerKeyboardEvent('ArrowUp'); expect(editor.selection).toEqual(output.selection); }); }); // https://github.com/udecode/editor-protocol/issues/29 describe('when arrow down from a cell in last row', () => { it('should move selection after table', async () => { const input = (( <editor> <htable> <htr> <htd>11</htd> <htd>12</htd> </htr> <htr> <htd> 21 <cursor /> </htd> <htd>22</htd> </htr> </htable> <hp>test</hp> </editor> ) as any) as PlateEditor; const output = (( <editor> <htable> <htr> <htd>11</htd> <htd>12</htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> <hp> <cursor /> test </hp> </editor> ) as any) as PlateEditor; const [editor, { triggerKeyboardEvent }] = await createPlateTestEditor({ editor: input, plugins: [createTablePlugin()], }); await triggerKeyboardEvent('ArrowDown'); expect(editor.selection).toEqual(output.selection); }); }); // https://github.com/udecode/editor-protocol/issues/30 describe('when shift+down in a cell', () => { it('should add cell below to selection', async () => { const input = (( <editor> <htable> <htr> <htd> <cursor /> 11 </htd> <htd>12</htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const output = (( <editor> <htable> <htr> <htd> <anchor /> 11 </htd> <htd>12</htd> </htr> <htr> <htd> <focus /> 21 </htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const [editor, { triggerKeyboardEvent }] = await createPlateTestEditor({ editor: input, plugins: [createTablePlugin()], }); await triggerKeyboardEvent('shift+ArrowDown'); expect(editor.selection).toEqual(output.selection); }); }); // https://github.com/udecode/editor-protocol/issues/31 describe('when shift+up in a cell', () => { it('should add cell above to selection', async () => { const input = (( <editor> <htable> <htr> <htd>11</htd> <htd>12</htd> </htr> <htr> <htd> 21 <cursor /> </htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const output = (( <editor> <htable> <htr> <htd> <anchor /> 11 </htd> <htd>12</htd> </htr> <htr> <htd> <focus /> 21 </htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const [editor, { triggerKeyboardEvent }] = await createPlateTestEditor({ editor: input, plugins: [createTablePlugin()], }); await triggerKeyboardEvent('shift+ArrowUp'); expect(editor.selection).toEqual(output.selection); }); }); // https://github.com/udecode/editor-protocol/issues/15 describe('when shift+right in a cell', () => { it('should add cell right to selection', async () => { const input = (( <editor> <htable> <htr> <htd> <cursor /> 11 </htd> <htd>12</htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const output = (( <editor> <htable> <htr> <htd> <anchor /> 11 </htd> <htd> <focus /> 12 </htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const [editor, { triggerKeyboardEvent }] = await createPlateTestEditor({ editor: input, plugins: [createTablePlugin()], }); await triggerKeyboardEvent('shift+ArrowRight'); expect(editor.selection).toEqual(output.selection); }); }); // https://github.com/udecode/editor-protocol/issues/17 describe('when shift+left in a cell', () => { it('should add cell left to selection', async () => { const input = (( <editor> <htable> <htr> <htd>11</htd> <htd> 12 <cursor /> </htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const output = (( <editor> <htable> <htr> <htd> <anchor /> 11 </htd> <htd> <focus /> 12 </htd> </htr> <htr> <htd>21</htd> <htd>22</htd> </htr> </htable> </editor> ) as any) as PlateEditor; const [editor, { triggerKeyboardEvent }] = await createPlateTestEditor({ editor: input, plugins: [createTablePlugin()], }); await triggerKeyboardEvent('shift+ArrowLeft'); expect(editor.selection).toEqual(output.selection); }); }); });
the_stack
import { Component, EventEmitter, Input, NgModule, OnDestroy, Output, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, Injector, forwardRef, HostListener, AfterViewInit } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"; import {JigsawCheckBoxModule} from "../checkbox/index"; import {ArrayCollection} from "../../common/core/data/array-collection"; import {CallbackRemoval} from "../../common/core/utils/common-utils"; import {AbstractJigsawComponent} from "../../common/common"; import {CheckBoxStatus} from "../checkbox/typings"; import {TranslateHelper} from "../../common/core/utils/translate-helper"; import {TranslateModule, TranslateService} from '@ngx-translate/core'; import {InternalUtils} from "../../common/core/utils/internal-utils"; import {Subscription} from 'rxjs'; import {TimeGr, TimeService} from "../../common/service/time.service"; import {JigsawTileSelectModule} from "../list-and-tile/tile"; import {JigsawFloatModule} from "../../common/directive/float/float"; import {Time} from "../../common/service/time.types"; import {JigsawRadioLiteModule} from "../radio/radio-lite"; export type TimeSectionInfo = { section: string, isSelected: boolean } export type WeekAndDaySectionInfo = { label?: string | number, value: number, lastDay?: boolean } /** * @internal */ export type TimeSection = { time?: string[], week?: WeekAndDaySectionInfo[], date?: WeekAndDaySectionInfo[], everyday?: boolean } export type TimeSectionValue = TimeSection; @Component({ selector: 'jigsaw-time-section-picker, j-time-section-picker', template: ` <div class="jigsaw-time-section-picker-line" [class.jigsaw-time-section-picker-multiple]="multipleSelect"> <j-checkbox *ngIf="multipleSelect" [(checked)]="_$amTimeCheck" (checkedChange)="_$changeAmPmState($event, 'am')"></j-checkbox> <ul> <li *ngFor="let section of _$amTimeSection" (click)="_$timeSelect(section)" [class.jigsaw-time-section-picker-selected]="section.isSelected"></li> </ul> <div class="jigsaw-time-section-picker-hour"> <span *ngFor="let time of _$amTimeline">{{time}}</span> </div> </div> <div class="jigsaw-time-section-picker-line" [class.jigsaw-time-section-picker-multiple]="multipleSelect"> <j-checkbox *ngIf="multipleSelect" [(checked)]="_$pmTimeCheck" (checkedChange)="_$changeAmPmState($event, 'pm')"></j-checkbox> <ul [class.jigsaw-time-section-picker-multiple]="multipleSelect"> <li *ngFor="let section of _$pmTimeSection" (click)="_$timeSelect(section)" [class.jigsaw-time-section-picker-selected]="section.isSelected"></li> </ul> <div class="jigsaw-time-section-picker-hour"> <span *ngFor="let time of _$pmTimeline">{{time}}</span> </div> </div> `, host: { '[class.jigsaw-time-section-picker]': 'true' }, changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawTimeSectionPicker extends AbstractJigsawComponent implements OnDestroy { constructor(private _cdr: ChangeDetectorRef, // @RequireMarkForCheck 需要用到,勿删 private _injector: Injector) { super(); } /** * @internal */ public _$amTimeline = Array.from(new Array(13)).map((item, i) => `${i < 10 ? '0' : ''}${i}:00`); /** * @internal */ public _$pmTimeline = Array.from(new Array(13)).map((item, i) => `${i + 12}:00`); /** * @internal */ public _$amTimeSection: TimeSectionInfo[] = Array.from(new Array(12)).map((item, i) => ({ section: `${this._$amTimeline[i]}-${this._$amTimeline[i + 1]}`, isSelected: false })); /** * @internal */ public _$pmTimeSection: TimeSectionInfo[] = Array.from(new Array(12)).map((item, i) => ({ section: `${this._$pmTimeline[i]}-${this._$pmTimeline[i + 1]}`, isSelected: false })); /** * @internal */ public _$amTimeCheck: CheckBoxStatus; /** * @internal */ public _$pmTimeCheck: CheckBoxStatus; private _value: ArrayCollection<string> = new ArrayCollection(); private _valueOnRefreshRemoval: CallbackRemoval; /** * @NoMarkForCheckRequired */ @Input() public get value(): ArrayCollection<string> { return this._value; } public set value(value: ArrayCollection<string>) { if (!(value instanceof Array || value instanceof ArrayCollection) || this.value == value) return; if (value instanceof Array) { value = new ArrayCollection(value); } this._value = value; if (this._valueOnRefreshRemoval) { this._valueOnRefreshRemoval(); } this._valueOnRefreshRemoval = this._value.onRefresh(() => { this._changeSelectViewByValue(); }); this._changeSelectViewByValue(); } /** * @NoMarkForCheckRequired */ @Input() public multipleSelect: boolean = true; @Output() public valueChange = new EventEmitter(); /** * @internal */ public _$timeSelect(sectionInfo: TimeSectionInfo) { if (this.multipleSelect) { sectionInfo.isSelected = !sectionInfo.isSelected; this._checkAmPmSelect(); } else { sectionInfo.isSelected = true; this._changeAmPmSingleSelect(sectionInfo); } this._updateValueBySection(sectionInfo); this._updateValue(); this._cdr.markForCheck(); } private _changeSelectViewByValue() { this._updateSelectState(this._$amTimeSection); this._updateSelectState(this._$pmTimeSection); this._checkAmPmSelect(); this._cdr.markForCheck(); } private _updateSelectState(timeSection: TimeSectionInfo[]) { timeSection.forEach(s => { s.isSelected = !!this.value.find(v => v == s.section) }) } private _checkAmPmSelect() { this._$amTimeCheck = this._getCheckState(this._$amTimeSection); this._$pmTimeCheck = this._getCheckState(this._$pmTimeSection); } private _getCheckState(sections: TimeSectionInfo[]): CheckBoxStatus { return sections.every(s => !!s.isSelected) ? CheckBoxStatus.checked : sections.some(s => !!s.isSelected) ? CheckBoxStatus.indeterminate : CheckBoxStatus.unchecked; } /** * @internal */ public _$changeAmPmState($event, type: 'am' | 'pm') { const timeSection = type == 'am' ? this._$amTimeSection : this._$pmTimeSection; timeSection.forEach(sectionInfo => { sectionInfo.isSelected = !!$event; this._updateValueBySection(sectionInfo); }); this._updateValue(); this._cdr.markForCheck(); } private _updateValueBySection(sectionInfo: TimeSectionInfo) { if (this.multipleSelect) { const found = this.value.find(v => v == sectionInfo.section); if (sectionInfo.isSelected && !found) { this.value.push(sectionInfo.section); } else if (!sectionInfo.isSelected && found) { let index = this.value.findIndex(v => v == sectionInfo.section); this.value.splice(index, 1); } } else { this.value.splice(0, this.value.length, sectionInfo.section) } } private _updateValue() { this.value.sort(); this.valueChange.emit(this.value); } private _changeAmPmSingleSelect(sectionInfo: TimeSectionInfo) { this._singleSelectChange(sectionInfo, this._$amTimeSection); this._singleSelectChange(sectionInfo, this._$pmTimeSection); } private _singleSelectChange(sectionInfo: TimeSectionInfo, sections: TimeSectionInfo[]) { sections.forEach(s => { if (s.section != sectionInfo.section) { s.isSelected = false } }) } ngOnDestroy(): void { super.ngOnDestroy(); if (this._valueOnRefreshRemoval) { this._valueOnRefreshRemoval(); } } } @Component({ selector: 'jigsaw-week-section-picker, j-week-section-picker', template: ` <j-checkbox *ngIf="multipleSelect" [(checked)]="_$selectState" (checkedChange)="_$toggleSelectAll($event)">{{'timeSection.selectAll' | translate}}</j-checkbox> <j-tile trackItemBy="value" [(selectedItems)]="value" [multipleSelect]="multipleSelect" (selectedItemsChange)="_$selectChange($event)"> <j-tile-option *ngFor="let week of _$weekList" [value]="week" width="42" height="26"> {{week.label}} </j-tile-option> </j-tile> `, host: { '[class.jigsaw-week-section-picker]': 'true' }, changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawWeekSectionPicker extends AbstractJigsawComponent implements OnDestroy, OnInit { constructor(private _translateService: TranslateService, private _cdr: ChangeDetectorRef, // @RequireMarkForCheck 需要用到,勿删 private _injector: Injector) { super(); this._langChangeSubscriber = TranslateHelper.languageChangEvent.subscribe(langInfo => { TimeService.setLocale(langInfo.curLang); this._$weekList = this._createWeekList(); }); let browserLang = _translateService.getBrowserLang(); _translateService.setDefaultLang(browserLang); TimeService.setLocale(browserLang); this._$weekList = this._createWeekList(); } private _value: ArrayCollection<WeekAndDaySectionInfo> | WeekAndDaySectionInfo[]; /** * @NoMarkForCheckRequired */ @Input() public get value(): ArrayCollection<WeekAndDaySectionInfo> | WeekAndDaySectionInfo[] { return this._value; } public set value(value: ArrayCollection<WeekAndDaySectionInfo> | WeekAndDaySectionInfo[]) { this._value = value; this._setSelectState(); this._cdr.markForCheck(); } /** * @NoMarkForCheckRequired */ @Input() public multipleSelect: boolean = true; @Output() public valueChange = new EventEmitter<ArrayCollection<WeekAndDaySectionInfo> | WeekAndDaySectionInfo[]>(); private _langChangeSubscriber: Subscription; /** * @internal */ public _$selectState: CheckBoxStatus; /** * @internal */ public _$weekList: WeekAndDaySectionInfo[]; private _createWeekList() { return TimeService.getWeekdaysShort().map((week, index) => ({label: week, value: index})); } /** * @internal */ public _$toggleSelectAll($event) { if ($event == CheckBoxStatus.checked) { this.value = new ArrayCollection([...this._$weekList]); } else if ($event == CheckBoxStatus.unchecked) { this.value = new ArrayCollection([]); } this.valueChange.emit(this.value); } /** * @internal */ public _$selectChange($event) { $event.sort((a, b) => a.value - b.value); this.valueChange.emit($event); this._setSelectState(); } private _setSelectState() { this._$selectState = !this.value || this.value.length == 0 ? CheckBoxStatus.unchecked : this.value.length == this._$weekList.length ? CheckBoxStatus.checked : CheckBoxStatus.indeterminate; this._cdr.markForCheck(); } ngOnInit() { super.ngOnInit(); if (this.value) { this._setSelectState(); } } ngOnDestroy() { super.ngOnDestroy(); if (this._langChangeSubscriber) { this._langChangeSubscriber.unsubscribe(); this._langChangeSubscriber = null; } } } @Component({ selector: 'jigsaw-day-section-picker, j-day-section-picker', template: ` <div class="jigsaw-day-section-picker-wrapper"> <div class="jigsaw-day-section-picker-checkbox" *ngIf="multipleSelect" k> <j-checkbox [(checked)]="_$selectState" (checkedChange)="_$toggleSelectAll($event)">{{'timeSection.selectAll' | translate}}</j-checkbox> </div> <div class="jigsaw-day-section-picker-tile"> <j-tile trackItemBy="value,lastDay" [(selectedItems)]="value" [multipleSelect]="multipleSelect" (selectedItemsChange)="_$selectChange($event)"> <ng-container *ngFor="let day of _$dayList"> <j-tile-option *ngIf="!day.lastDay; else lastDay" [value]="day" width="26" height="26"> {{day.label}} </j-tile-option> <ng-template #lastDay> <j-tile-option *ngIf="showLastDay" [value]="day" jigsaw-float [jigsawFloatTarget]="lastDayTooltip" jigsawFloatPosition="topLeft" height="26" [jigsawFloatOptions]="{borderType: 'pointer'}"> {{day.label}} </j-tile-option> </ng-template> </ng-container> </j-tile> </div> </div> <ng-template #lastDayTooltip> <div class="jigsaw-day-section-picker-tooltip"> {{'timeSection.lastDayTooltip' | translate}} </div> </ng-template> `, host: { '[class.jigsaw-day-section-picker]': 'true', '[style.width]': 'width' }, changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawDaySectionPicker extends AbstractJigsawComponent implements OnDestroy, OnInit { constructor(private _translateService: TranslateService, private _cdr: ChangeDetectorRef, // @RequireMarkForCheck 需要用到,勿删 private _injector: Injector) { super(); this._langChangeSubscriber = TranslateHelper.languageChangEvent.subscribe(langInfo => { this._$dayList = this._createDayList(); }); let browserLang = _translateService.getBrowserLang(); _translateService.setDefaultLang(browserLang); } private _langChangeSubscriber: Subscription; private _value: ArrayCollection<WeekAndDaySectionInfo> | WeekAndDaySectionInfo[]; /** * @NoMarkForCheckRequired */ @Input() public get value(): ArrayCollection<WeekAndDaySectionInfo> | WeekAndDaySectionInfo[] { return this._value; } public set value(value: ArrayCollection<WeekAndDaySectionInfo> | WeekAndDaySectionInfo[]) { this._value = value; if (this.initialized) { this._setSelectState(); this._cdr.markForCheck(); } } @Output() public valueChange = new EventEmitter<ArrayCollection<WeekAndDaySectionInfo> | WeekAndDaySectionInfo[]>(); /** * @NoMarkForCheckRequired */ @Input() public showLastDay: boolean; /** * @NoMarkForCheckRequired */ @Input() public currentTime: Time; /** * @NoMarkForCheckRequired */ @Input() public multipleSelect: boolean = true; /** * @internal */ public _$selectState: CheckBoxStatus; /** * @internal */ public _$dayList: WeekAndDaySectionInfo[]; private _createDayList() { return Array.from(new Array(32)).map((item, index) => { return index == 31 ? { label: this._translateService.instant('timeSection.lastDay'), value: this._getLastDayOfCurMonth(), lastDay: true } : {label: index + 1, value: index + 1} }); } private _getLastDayOfCurMonth() { let date = this.currentTime ? this.currentTime : 'now'; let curDay = TimeService.convertValue(date, TimeGr.date); let lastDate = TimeService.getLastDateOfMonth(TimeService.getYear(curDay), TimeService.getMonth(curDay)); return TimeService.getDay(lastDate); } /** * @internal */ public _$toggleSelectAll($event) { if ($event == CheckBoxStatus.checked) { let days = this._$dayList.slice(0, this._$dayList.length - (this.showLastDay ? 0 : 1)); this.value = new ArrayCollection([...days]); } else if ($event == CheckBoxStatus.unchecked) { this.value = new ArrayCollection([]); } this.valueChange.emit(this.value); } /** * @internal */ public _$selectChange($event) { $event.sort((a, b) => a.value - b.value); this.valueChange.emit($event); this._setSelectState(); } private _setSelectState() { this._$selectState = !this.value || this.value.length == 0 ? CheckBoxStatus.unchecked : this.value.length == (this.showLastDay ? this._$dayList.length : this._$dayList.length - 1) ? CheckBoxStatus.checked : CheckBoxStatus.indeterminate; } ngOnInit() { super.ngOnInit(); this._$dayList = this._createDayList(); if (this.value) { this._setSelectState(); } } ngOnDestroy() { super.ngOnDestroy(); if (this._langChangeSubscriber) { this._langChangeSubscriber.unsubscribe(); this._langChangeSubscriber = null; } } } @Component({ selector: 'jigsaw-time-section, j-time-section', template: ` <div class="jigsaw-time-section-wrapper" [class.jigsaw-time-section-horizontal]="layout == 'horizontal'"> <div class="jigsaw-time-section-time" *ngIf="showHour"> <span class="jigsaw-time-section-time-title">{{'timeSection.timeTitle' | translate}}</span> <j-time-section-picker [(value)]="_$timeValue" [multipleSelect]="multipleHour" (valueChange)="_$selectChange()"> </j-time-section-picker> </div> <div class="jigsaw-time-section-switch-wrapper" *ngIf="showWeek || showDate || showEveryday"> <div class="jigsaw-time-section-switch" *ngIf="_$switchList && _$switchList.length > 1"> <jigsaw-radios-lite [(value)]="_$selectType" (valueChange)="_$selectChange()" [data]="_$switchList" trackItemBy="value"> </jigsaw-radios-lite> </div> <div *ngIf="_$byMonth" class="jigsaw-time-section-month"> <j-day-section-picker [(value)]="_$dateValue" [showLastDay]="showLastDay" [currentTime]="currentTime" [multipleSelect]="multipleDate" (valueChange)="_$selectChange()"> </j-day-section-picker> </div> <div *ngIf="_$byWeek" class="jigsaw-time-section-week"> <j-week-section-picker [(value)]="_$weekValue" [multipleSelect]="multipleDate" (valueChange)="_$selectChange()"> </j-week-section-picker> </div> <div *ngIf="_$useEveryday" class="jigsaw-time-section-everyday"> </div> </div> </div> `, host: { '[class.jigsaw-time-section]': 'true', '[style.width]': 'width' }, providers: [ {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => JigsawTimeSection), multi: true}, ], changeDetection: ChangeDetectionStrategy.OnPush }) export class JigsawTimeSection extends AbstractJigsawComponent implements OnDestroy, AfterViewInit, ControlValueAccessor { constructor(private _translateService: TranslateService, private _cdr: ChangeDetectorRef, // @RequireMarkForCheck 需要用到,勿删 private _injector: Injector) { super(); this._langChangeSubscriber = TranslateHelper.languageChangEvent.subscribe(langInfo => { this._updateSwitchList(); }); _translateService.setDefaultLang(_translateService.getBrowserLang()); } private _langChangeSubscriber: Subscription; /** * @internal */ public _$switchList; /** * @internal */ public _$selectType; /** * @internal */ public _$timeValue; /** * @internal */ public _$weekValue; /** * @internal */ public _$dateValue; /** * @internal */ public get _$byMonth(): boolean { return (this._$switchList && this._$switchList.length > 1 && this._$selectType && this._$selectType.value == 0) || (this.showDate && !this.showEveryday && !this.showWeek); } /** * @internal */ public get _$byWeek(): boolean { return (this._$switchList && this._$switchList.length > 1 && this._$selectType && this._$selectType.value == 1) || (this.showWeek && !this.showEveryday && !this.showDate); } /** * @internal */ public get _$useEveryday(): boolean { return (this._$switchList && this._$switchList.length > 1 && this._$selectType && this._$selectType.value == 2) || (this.showEveryday && !this.showWeek && !this.showDate); } private _value: TimeSection; /** * @NoMarkForCheckRequired */ @Input() public get value(): TimeSection { return this._value; } public set value(value: TimeSection) { if (!value || value == this._value) { return; } this._value = value; this.update(); } public update(): void { if (!this.initialized) { return; } if (this.value) { this._$timeValue = this.value.time; this._$weekValue = this.value.week; this._$dateValue = this.value.date; } // 注意这个if过后,this._$selectType的值有可能是undefined if (this._$switchList) { if (this.value && this.value.everyday) { this._$selectType = this._$switchList.find(type => type.value == 2); } else if (this._$weekValue) { this._$selectType = this._$switchList.find(type => type.value == 1); } else { this._$selectType = this._$switchList.find(type => type.value == 0); } } this._cdr.markForCheck(); } /** * @NoMarkForCheckRequired */ @Input() public showLastDay: boolean; /** * @NoMarkForCheckRequired */ @Input() public currentTime: Time; /** * @NoMarkForCheckRequired */ @Input() public layout: 'horizontal' | 'vertical' = 'vertical'; /** * @NoMarkForCheckRequired */ @Input() public showHour: boolean = true; private _showDate: boolean = true; /** * @NoMarkForCheckRequired */ @Input() public get showDate(): boolean { return this._showDate; } public set showDate(value: boolean) { this._showDate = !!value; this._updateSwitchList(); } private _showWeek: boolean = true; /** * @NoMarkForCheckRequired */ @Input() public get showWeek(): boolean { return this._showWeek; } public set showWeek(value: boolean) { this._showWeek = !!value; this._updateSwitchList(); } private _showEveryday: boolean = false; /** * @NoMarkForCheckRequired */ @Input() public get showEveryday(): boolean { return this._showEveryday; } public set showEveryday(value: boolean) { this._showEveryday = !!value; this._updateSwitchList(); } /** * @NoMarkForCheckRequired */ @Input() public multipleHour: boolean = true; /** * @NoMarkForCheckRequired */ @Input() public multipleDate: boolean = true; @Output() public valueChange = new EventEmitter<TimeSection>(); private _updateSwitchList() { this._$switchList = []; if (this.showDate) { this._$switchList.push({label: this._translateService.instant('timeSection.switchMonth'), value: 0}); } if (this.showWeek) { this._$switchList.push({label: this._translateService.instant('timeSection.switchWeek'), value: 1}); } if (this.showEveryday) { this._$switchList.push({label: this._translateService.instant('timeSection.switchEveryday'), value: 2}); } this._$selectType = this._$selectType ? this._$switchList.find(s => s.value == this._$selectType.value) : this._$switchList[0]; } /** * @internal */ public _$selectChange() { const value = {}; if (this.showHour) { Object.assign(value, {time: this._$timeValue}); } if (this._$byMonth) { Object.assign(value, {date: this._$dateValue}); } else if (this._$byWeek) { Object.assign(value, {week: this._$weekValue}) } else if (this._$useEveryday) { Object.assign(value, {everyday: true}) } this.writeValue(value); } public writeValue(value: any): void { this._value = value; this.valueChange.emit(value); this._propagateChange(this._value); } ngAfterViewInit() { this._updateSwitchList(); this.update(); } ngOnDestroy() { super.ngOnDestroy(); if (this._langChangeSubscriber) { this._langChangeSubscriber.unsubscribe(); this._langChangeSubscriber = null; } } private _propagateChange: any = () => { }; private _onTouched: any = () => { }; public registerOnChange(fn: any): void { this._propagateChange = fn; } public registerOnTouched(fn: any): void { this._onTouched = fn; } @HostListener('click') onClickTrigger(): void { this._onTouched(); } } @NgModule({ declarations: [JigsawTimeSection, JigsawTimeSectionPicker, JigsawWeekSectionPicker, JigsawDaySectionPicker], imports: [ JigsawCheckBoxModule, JigsawTileSelectModule, JigsawFloatModule, JigsawRadioLiteModule, TranslateModule.forChild() ], exports: [JigsawTimeSection, JigsawTimeSectionPicker, JigsawWeekSectionPicker, JigsawDaySectionPicker] }) export class JigsawTimeSectionModule { constructor(translateService: TranslateService) { TimeService.deFineZhLocale(); InternalUtils.initI18n(translateService, 'timeSection', { zh: { selectAll: "全选", lastDay: "最后一天", lastDayTooltip: "当前月份的最后一天", timeTitle: '时间', switchMonth: '按月', switchWeek: '按周', switchEveryday: '每天' }, en: { selectAll: 'Select All', lastDay: "Last Day", lastDayTooltip: "The last day of the current month", timeTitle: 'Time', switchMonth: 'Month Day', switchWeek: 'Week Day', switchEveryday: 'Everyday' } }); translateService.setDefaultLang(translateService.getBrowserLang()); } }
the_stack
import { AdbWrapper, DeviceInfo, PackageInfo } from 'electron/platform/android/adb-wrapper'; import { AndroidFriendlyDeviceNameProvider } from 'electron/platform/android/android-friendly-device-name-provider'; import { AndroidServiceApkInfo, AndroidServiceApkLocator, AndroidServicePackageName, } from 'electron/platform/android/android-service-apk-locator'; import { AndroidDeviceConfigurator } from 'electron/platform/android/setup/android-device-configurator'; import { IMock, Mock, MockBehavior, Times } from 'typemoq'; describe('AndroidDeviceConfigurator', () => { const testDeviceId: string = 'emulator-12345'; const servicePackageName: string = AndroidServicePackageName; const testApkPackage: string = './Some/Path/SomePackage.apk'; const testApkInfo: AndroidServiceApkInfo = { path: testApkPackage, versionName: '1.2.3', }; const accessibilityServiceName: string = 'accessibility'; const mediaProjectionServiceName: string = 'media_projection'; const serviceIsRunningResponseSnippet: string = 'label=Accessibility Insights'; let adbWrapperMock: IMock<AdbWrapper>; let apkLocatorMock: IMock<AndroidServiceApkLocator>; let friendlyDeviceNameProviderMock: IMock<AndroidFriendlyDeviceNameProvider>; let testSubject: AndroidDeviceConfigurator; beforeEach(() => { adbWrapperMock = Mock.ofType<AdbWrapper>(undefined, MockBehavior.Strict); apkLocatorMock = Mock.ofType<AndroidServiceApkLocator>(undefined, MockBehavior.Strict); friendlyDeviceNameProviderMock = Mock.ofType<AndroidFriendlyDeviceNameProvider>( undefined, MockBehavior.Strict, ); testSubject = new AndroidDeviceConfigurator( adbWrapperMock.object, apkLocatorMock.object, friendlyDeviceNameProviderMock.object, ); testSubject.setSelectedDevice(testDeviceId); }); function verifyAllMocks(): void { adbWrapperMock.verifyAll(); apkLocatorMock.verifyAll(); friendlyDeviceNameProviderMock.verifyAll(); } it('getConnectedDevices propagates thrown errors', async () => { const expectedMessage = 'Error thrown during getDevices'; adbWrapperMock .setup(m => m.getConnectedDevices()) .throws(new Error(expectedMessage)) .verifiable(Times.once()); await expect(testSubject.getConnectedDevices()).rejects.toThrowError(expectedMessage); verifyAllMocks(); }); it('getConnectedDevices returns info from AdbWrapper and friendly device names', async () => { const rawFriendlyName1 = 'an emulator'; const rawFriendlyName2 = 'a device'; const friendlyName2 = 'A branded device'; const expectedDevices: DeviceInfo[] = [ { id: 'emulator1', isEmulator: true, friendlyName: rawFriendlyName1, }, { id: 'phone123', isEmulator: false, friendlyName: rawFriendlyName2, }, ]; adbWrapperMock .setup(m => m.getConnectedDevices()) .returns(() => Promise.resolve(expectedDevices)) .verifiable(Times.once()); friendlyDeviceNameProviderMock .setup(m => m.getFriendlyName(rawFriendlyName1)) .returns(() => rawFriendlyName1) .verifiable(Times.once()); friendlyDeviceNameProviderMock .setup(m => m.getFriendlyName(rawFriendlyName2)) .returns(() => friendlyName2) .verifiable(Times.once()); const actualDevices = await testSubject.getConnectedDevices(); expect(actualDevices[0].id).toBe(expectedDevices[0].id); expect(actualDevices[0].isEmulator).toBe(expectedDevices[0].isEmulator); expect(actualDevices[0].friendlyName).toBe(rawFriendlyName1); expect(actualDevices[1].id).toBe(expectedDevices[1].id); expect(actualDevices[1].isEmulator).toBe(expectedDevices[1].isEmulator); expect(actualDevices[1].friendlyName).toBe(friendlyName2); verifyAllMocks(); }); it('setSelectedDevice changes value', async () => { // Note that we test this indirectly since can't read it const expectedDevice = 'another device'; const expectedMessage = 'Error thrown during hasRequiredServiceVersion'; adbWrapperMock .setup(m => m.getPackageInfo(expectedDevice, servicePackageName)) .throws(new Error(expectedMessage)) .verifiable(Times.once()); testSubject.setSelectedDevice(expectedDevice); await expect(testSubject.hasRequiredServiceVersion()).rejects.toThrowError(expectedMessage); verifyAllMocks(); }); it('hasRequiredServiceVersion propagates thrown errors', async () => { const expectedMessage = 'Error thrown during hasRequiredServiceVersion'; adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .throws(new Error(expectedMessage)) .verifiable(Times.once()); await expect(testSubject.hasRequiredServiceVersion()).rejects.toThrowError(expectedMessage); verifyAllMocks(); }); it('hasRequiredServiceVersion returns false if installed package has no versionName', async () => { const packageInfo: PackageInfo = {}; adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .returns(() => Promise.resolve(packageInfo)) .verifiable(Times.once()); const success = await testSubject.hasRequiredServiceVersion(); expect(success).toBe(false); verifyAllMocks(); }); it('hasRequiredServiceVersion returns false if versionNames are different', async () => { const packageInfo: PackageInfo = { versionName: '1.2.2', }; apkLocatorMock .setup(m => m.locateBundledApk()) .returns(() => Promise.resolve(testApkInfo)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .returns(() => Promise.resolve(packageInfo)) .verifiable(Times.once()); const success = await testSubject.hasRequiredServiceVersion(); expect(success).toBe(false); verifyAllMocks(); }); it('hasRequiredServiceVersion returns true if versionNames are same', async () => { const packageInfo: PackageInfo = { versionName: '1.2.3', }; apkLocatorMock .setup(m => m.locateBundledApk()) .returns(() => Promise.resolve(testApkInfo)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .returns(() => Promise.resolve(packageInfo)) .verifiable(Times.once()); const success = await testSubject.hasRequiredServiceVersion(); expect(success).toBe(true); verifyAllMocks(); }); it('installRequiredServiceVersion propagates thrown errors', async () => { const expectedMessage = 'Error thrown during installRequiredServiceVersion'; adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .throws(new Error(expectedMessage)) .verifiable(Times.once()); await expect(testSubject.installRequiredServiceVersion()).rejects.toThrowError( expectedMessage, ); verifyAllMocks(); }); it('installRequiredServiceVersion installs (no uninstall) if installed version does not exist', async () => { const installedPackageInfo: PackageInfo = {}; apkLocatorMock .setup(m => m.locateBundledApk()) .returns(() => Promise.resolve(testApkInfo)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .returns(() => Promise.resolve(installedPackageInfo)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.installService(testDeviceId, testApkPackage)) .verifiable(Times.once()); await testSubject.installRequiredServiceVersion(); verifyAllMocks(); }); it('installRequiredServiceVersion installs (no uninstall) if installed version is older than Apk version', async () => { const installedPackageInfo: PackageInfo = { versionName: '1.2.2', }; apkLocatorMock .setup(m => m.locateBundledApk()) .returns(() => Promise.resolve(testApkInfo)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .returns(() => Promise.resolve(installedPackageInfo)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.installService(testDeviceId, testApkPackage)) .verifiable(Times.once()); await testSubject.installRequiredServiceVersion(); verifyAllMocks(); }); it('installRequiredServiceVersion installs (no uninstall) if installed version is same as Apk version', async () => { const installedPackageInfo: PackageInfo = { versionName: '1.2.3', }; adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .returns(() => Promise.resolve(installedPackageInfo)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.installService(testDeviceId, testApkPackage)) .verifiable(Times.once()); apkLocatorMock .setup(m => m.locateBundledApk()) .returns(() => Promise.resolve(testApkInfo)) .verifiable(Times.once()); await testSubject.installRequiredServiceVersion(); verifyAllMocks(); }); it('installRequiredServiceVersion uninstalls then installs if installed version is newer than Apk version', async () => { let callbackCount: number = 0; let uninstallOrder: number = undefined; let installOrder: number = undefined; const installedPackageInfo: PackageInfo = { versionName: '1.2.4', }; adbWrapperMock .setup(m => m.getPackageInfo(testDeviceId, servicePackageName)) .returns(() => Promise.resolve(installedPackageInfo)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.uninstallService(testDeviceId, servicePackageName)) .callback(() => { uninstallOrder = callbackCount++; }) .verifiable(Times.once()); adbWrapperMock .setup(m => m.installService(testDeviceId, testApkPackage)) .callback(() => { installOrder = callbackCount++; }) .verifiable(Times.once()); apkLocatorMock .setup(m => m.locateBundledApk()) .returns(() => Promise.resolve(testApkInfo)) .verifiable(Times.once()); await testSubject.installRequiredServiceVersion(); expect(uninstallOrder).toBe(0); expect(installOrder).toBe(1); expect(callbackCount).toBe(2); verifyAllMocks(); }); it('hasRequiredPermissions propagates thrown errors', async () => { const expectedMessage = 'Error thrown during hasRequiredPermissions'; adbWrapperMock .setup(m => m.hasPermission( testDeviceId, accessibilityServiceName, serviceIsRunningResponseSnippet, ), ) .throws(new Error(expectedMessage)) .verifiable(Times.once()); await expect(testSubject.hasRequiredPermissions()).rejects.toThrowError(expectedMessage); verifyAllMocks(); }); it('hasRequiredPermissions returns false if service is not running', async () => { adbWrapperMock .setup(m => m.hasPermission( testDeviceId, accessibilityServiceName, serviceIsRunningResponseSnippet, ), ) .returns(() => Promise.resolve(false)) .verifiable(Times.once()); const success = await testSubject.hasRequiredPermissions(); expect(success).toBe(false); verifyAllMocks(); }); it('hasRequiredPermissions returns false if service is running without screenshot permission', async () => { adbWrapperMock .setup(m => m.hasPermission( testDeviceId, accessibilityServiceName, serviceIsRunningResponseSnippet, ), ) .returns(() => Promise.resolve(true)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.hasPermission(testDeviceId, mediaProjectionServiceName, servicePackageName), ) .returns(() => Promise.resolve(false)) .verifiable(Times.once()); const success = await testSubject.hasRequiredPermissions(); expect(success).toBe(false); verifyAllMocks(); }); it('hasRequiredPermissions returns true if service is running with screenshot permission', async () => { adbWrapperMock .setup(m => m.hasPermission( testDeviceId, accessibilityServiceName, serviceIsRunningResponseSnippet, ), ) .returns(() => Promise.resolve(true)) .verifiable(Times.once()); adbWrapperMock .setup(m => m.hasPermission(testDeviceId, mediaProjectionServiceName, servicePackageName), ) .returns(() => Promise.resolve(true)) .verifiable(Times.once()); const success = await testSubject.hasRequiredPermissions(); expect(success).toBe(true); verifyAllMocks(); }); it('fetchDeviceConfig fetches config from adb', async () => { const testConfigResponse = { deviceName: 'test-device', packageName: 'test-identifier', }; const testConfig = { deviceName: 'test-device', appIdentifier: 'test-identifier', }; adbWrapperMock .setup(m => m.readContent(testDeviceId, `content://${servicePackageName}/config`)) .returns(() => Promise.resolve(JSON.stringify(testConfigResponse))) .verifiable(Times.once()); const config = await testSubject.fetchDeviceConfig(); expect(config).toEqual(testConfig); verifyAllMocks(); }); it('fetchDeviceConfig fetches propagates errors', async () => { const expectedError = 'error from ADB'; adbWrapperMock .setup(m => m.readContent(testDeviceId, `content://${servicePackageName}/config`)) .throws(new Error(expectedError)) .verifiable(Times.once()); await expect(testSubject.fetchDeviceConfig()).rejects.toThrowError(expectedError); verifyAllMocks(); }); it('grantOverlayPermission propagates thrown errors', async () => { // This test has the side effect of ensuring grantOverlayPermission is called // So there is no need for a separate test. const expectedMessage = 'Error thrown during grantOverlayPermission'; adbWrapperMock .setup(m => m.grantPermission( testDeviceId, servicePackageName, 'android.permission.SYSTEM_ALERT_WINDOW', ), ) .throws(new Error(expectedMessage)) .verifiable(Times.once()); await expect(testSubject.grantOverlayPermission()).rejects.toThrowError(expectedMessage); verifyAllMocks(); }); });
the_stack
import { dia } from 'jointjs'; import { Flo } from './flo-common'; import * as _ from 'lodash'; import * as _$ from 'jquery'; const joint: any = Flo.joint; const $: any = _$; const isChrome: boolean = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); const isFF: boolean = navigator.userAgent.indexOf('Firefox') > 0; const IMAGE_W = 120; const IMAGE_H = 35; const ERROR_MARKER_SIZE: dia.Size = {width: 16, height: 16}; const HANDLE_SIZE: dia.Size = {width: 10, height: 10}; const HANDLE_ICON_MAP: Map<string, string> = new Map<string, string>(); const REMOVE = 'remove'; HANDLE_ICON_MAP.set(REMOVE, 'icons/delete.svg'); const DECORATION_ICON_MAP: Map<string, string> = new Map<string, string>(); const ERROR = 'error'; DECORATION_ICON_MAP.set(ERROR, 'icons/error.svg'); export function loadShapes() { joint.shapes.flo = {}; joint.shapes.flo.NODE_TYPE = 'sinspctr.IntNode'; joint.shapes.flo.LINK_TYPE = 'sinspctr.Link'; joint.shapes.flo.DECORATION_TYPE = 'decoration'; joint.shapes.flo.HANDLE_TYPE = 'handle'; // joint.util.cloneDeep = (obj: any) => { // return _.cloneDeepWith(obj, (o) => { // if (_.isObject(o) && !_.isPlainObject(o)) { // return o; // } // }); // }; joint.util.filter.redscale = (args: Shapes.FilterOptions) => { let amount = Number.isFinite(args.amount) ? args.amount : 1; return _.template( '<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 ${d} ${e} ${f} ${g} 0 0 ${h} ${i} ${k} 0 0 0 0 0 1 0"/></filter>', <any>{ a: 1 - 0.96 * amount, b: 0.95 * amount, c: 0.01 * amount, d: 0.3 * amount, e: 0.2 * amount, f: 1 - 0.9 * amount, g: 0.7 * amount, h: 0.05 * amount, i: 0.05 * amount, k: 1 - 0.1 * amount } ); }; joint.util.filter.orangescale = (args: Shapes.FilterOptions) => { let amount = Number.isFinite(args.amount) ? args.amount : 1; return _.template( '<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 ${d} ${e} ${f} ${g} 0 ${h} ${i} ${k} ${l} 0 0 0 0 0 1 0"/></filter>', <any>{ a: 1.0 + 0.5 * amount, b: 1.4 * amount, c: 0.2 * amount, d: 0.3 * amount, e: 0.3 * amount, f: 1 + 0.05 * amount, g: 0.2 * amount, h: 0.15 * amount, i: 0.3 * amount, k: 0.3 * amount, l: 1 - 0.6 * amount } ); }; joint.shapes.flo.Node = joint.shapes.basic.Generic.extend({ markup: '<g class="shape"><image class="image" /></g>' + '<rect class="border-white"/>' + '<rect class="border"/>' + '<rect class="box"/>' + '<text class="label"/>' + '<text class="label2"></text>' + '<rect class="input-port" />' + '<rect class="output-port"/>' + '<rect class="output-port-cover"/>', defaults: joint.util.deepSupplement({ type: joint.shapes.flo.NODE_TYPE, position: {x: 0, y: 0}, size: { width: IMAGE_W, height: IMAGE_H }, attrs: { '.': { magnet: false }, // rounded edges around image '.border': { refWidth: 1, refHeight: 1, rx: 3, ry: 3, 'fill-opacity': 0, // see through stroke: '#eeeeee', 'stroke-width': 0 }, '.box': { refWidth: 1, refHeight: 1, rx: 3, ry: 3, //'fill-opacity': 0, // see through stroke: '#6db33f', fill: '#eeeeee', 'stroke-width': 1 }, '.input-port': { idp: 'input', port: 'input', height: 8, width: 8, magnet: true, fill: '#eeeeee', transform: 'translate(' + -4 + ',' + ((IMAGE_H / 2 ) - 4) + ')', stroke: '#34302d', 'stroke-width': 1 }, '.output-port': { id: 'output', port: 'output', height: 8, width: 8, magnet: true, fill: '#eeeeee', transform: 'translate(' + (IMAGE_W - 4) + ',' + ((IMAGE_H / 2) - 4) + ')', stroke: '#34302d', 'stroke-width': 1 }, '.label': { 'text-anchor': 'middle', 'ref-x': 0.5, // jointjs specific: relative position to ref'd element // 'ref-y': -12, // jointjs specific: relative position to ref'd element 'ref-y': 0.3, ref: '.border', // jointjs specific: element for ref-x, ref-y fill: 'black', 'font-size': 14 }, '.label2': { 'text': '\u21d2', 'text-anchor': 'middle', 'ref-x': 0.15, // jointjs specific: relative position to ref'd element 'ref-y': 0.2, // jointjs specific: relative position to ref'd element ref: '.border', // jointjs specific: element for ref-x, ref-y // transform: 'translate(' + (IMAGE_W/2) + ',' + (IMAGE_H/2) + ')', fill: 'black', 'font-size': 24 }, '.shape': { }, '.image': { refWidth: 1, refHeight: 1, } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.flo.Link = joint.dia.Link.extend({ defaults: joint.util.deepSupplement({ type: joint.shapes.flo.LINK_TYPE, attrs: { '.connection': { stroke: '#34302d', 'stroke-width': 2 }, // Lots of alternatives that have been played with: // '.smoooth': true // '.marker-source': { stroke: '#9B59B6', fill: '#9B59B6', d: 'M24.316,5.318,9.833,13.682,9.833,5.5,5.5,5.5,5.5,25.5,9.833,25.5,9.833,17.318,24.316,25.682z' }, // '.marker-target': { stroke: '#F39C12', fill: '#F39C12', d: 'M14.615,4.928c0.487-0.986,1.284-0.986,1.771,0l2.249,4.554c0.486,0.986,1.775,1.923,2.864,2.081l5.024,0.73c1.089,0.158,1.335,0.916,0.547,1.684l-3.636,3.544c-0.788,0.769-1.28,2.283-1.095,3.368l0.859,5.004c0.186,1.085-0.459,1.553-1.433,1.041l-4.495-2.363c-0.974-0.512-2.567-0.512-3.541,0l-4.495,2.363c-0.974,0.512-1.618,0.044-1.432-1.041l0.858-5.004c0.186-1.085-0.307-2.6-1.094-3.368L3.93,13.977c-0.788-0.768-0.542-1.525,0.547-1.684l5.026-0.73c1.088-0.158,2.377-1.095,2.864-2.081L14.615,4.928z' }, // '.connection': { 'stroke':'black'}, // '.': { filter: { name: 'dropShadow', args: { dx: 1, dy: 1, blur: 2 } } }, // '.connection': { 'stroke-width': 10, 'stroke-linecap': 'round' }, // This means: moveto 10 0, lineto 0 5, lineto, 10 10 closepath(z) // '.marker-target': { d: 'M 5 0 L 0 7 L 5 14 z', stroke: '#34302d','stroke-width': 1}, // '.marker-target': { d: 'M 14 2 L 9,2 L9,0 L 0,7 L 9,14 L 9,12 L 14,12 z', 'stroke-width': 1, fill: '#34302d', stroke: '#34302d'}, // '.marker-source': {d: 'M 5 0 L 5,10 L 0,10 L 0,0 z', 'stroke-width': 0, fill: '#34302d', stroke: '#34302d'}, // '.marker-target': { stroke: '#E74C3C', fill: '#E74C3C', d: 'M 10 0 L 0 5 L 10 10 z' }, '.marker-arrowheads': { display: 'none' }, '.tool-options': { display: 'none' } }, // connector: { name: 'normalDimFix' } }, joint.dia.Link.prototype.defaults) }); joint.shapes.flo.LinkView = joint.dia.LinkView.extend({ options: joint.util.deepSupplement({ linkToolsOffset: 0.5, shortLinkLength: 40 }, joint.dia.LinkView.prototype.options), updateToolsPosition: function() { // Overriden to support relative offset for tools placement. // If offset is between 0 and 1 then percentage of the connection length will be used to offset the tools group if (this.options.linkToolsOffset < 1 && this.options.linkToolsOffset > 0) { let connectionLength = this.getConnectionLength(); const relativeOffset = this.options.linkToolsOffset this.options.linkToolsOffset = connectionLength * relativeOffset; const returnValue = joint.dia.LinkView.prototype.updateToolsPosition.apply(this, arguments); this.options.linkToolsOffset = relativeOffset; return returnValue; } else { return joint.dia.LinkView.prototype.updateToolsPosition.apply(this, arguments); } }, _beforeArrowheadMove: function() { if (this.model.get('source').id) { this._oldSource = this.model.get('source'); } if (this.model.get('target').id) { this._oldTarget = this.model.get('target'); } joint.dia.LinkView.prototype._beforeArrowheadMove.apply(this, arguments); }, _afterArrowheadMove: function() { joint.dia.LinkView.prototype._afterArrowheadMove.apply(this, arguments); if (!this.model.get('source').id) { if (this._oldSource) { this.model.set('source', this._oldSource); } else { this.model.remove(); } } if (!this.model.get('target').id) { if (this._oldTarget) { this.model.set('target', this._oldTarget); } else { this.model.remove(); } } delete this._oldSource; delete this._oldTarget; } }); // TODO: must do cleanup for the `mainElementView' joint.shapes.flo.ElementView = joint.dia.ElementView.extend({ // canShowTooltip: true, beingDragged: false, // _tempZorder: 0, _tempOpacity: 1.0, _hovering: false, dragLinkStart: function(evt: any, magnet: any, x: number, y: number) { this.model.startBatch('add-link'); const linkView = this.addLinkFromMagnet(magnet, x, y); // backwards compatiblity events joint.dia.CellView.prototype.pointerdown.apply(linkView, [evt, x, y]); linkView.notify('link:pointerdown', evt, x, y); /*** START MAIN DIFF ***/ const sourceOrTarget = $(magnet).attr('port') === 'input' ? 'source' : 'target'; linkView.eventData(evt, linkView.startArrowheadMove(sourceOrTarget, { whenNotAllowed: 'remove' })); /*** END MAIN DIFF ***/ this.eventData(evt, { linkView: linkView }); }, addLinkFromMagnet: function(magnet: any, x: number, y: number) { const paper = this.paper; const graph = paper.model; const link = paper.getDefaultLink(this, magnet); let sourceEnd, targetEnd: any; /*** START MAIN DIFF ***/ if ($(magnet).attr('port') === 'input') { sourceEnd = { x: x, y: y }; targetEnd = this.getLinkEnd(magnet, x, y, link, 'target'); } else { sourceEnd = this.getLinkEnd(magnet, x, y, link, 'source'); targetEnd = { x: x, y: y }; } /*** END MAIN DIFF ***/ link.set({ source: sourceEnd, target: targetEnd }).addTo(graph, { async: false, ui: true }); return link.findView(paper); }, // pointerdown: function(evt: any, x: number, y: number) { // // this.canShowTooltip = false; // // this.hideTooltip(); // this.beingDragged = false; // this._tempOpacity = this.model.attr('./opacity'); // // this.model.trigger('batch:start'); // // if ( // target is a valid magnet start linking // evt.target.getAttribute('magnet') && // this.paper.options.validateMagnet.call(this.paper, this, evt.target) // ) { // let link = this.paper.getDefaultLink(this, evt.target); // if ($(evt.target).attr('port') === 'input') { // link.set({ // source: { x: x, y: y }, // target: { // id: this.model.id, // selector: this.getSelector(evt.target), // port: evt.target.getAttribute('port') // } // }); // } else { // link.set({ // source: { // id: this.model.id, // selector: this.getSelector(evt.target), // port: evt.target.getAttribute('port') // }, // target: { x: x, y: y } // }); // } // this.paper.model.addCell(link); // this._linkView = this.paper.findViewByModel(link); // if ($(evt.target).attr('port') === 'input') { // this._linkView.startArrowheadMove('source'); // } else { // this._linkView.startArrowheadMove('target'); // } // this.paper.__creatingLinkFromPort = true; // } else { // this._dx = x; // this._dy = y; // joint.dia.CellView.prototype.pointerdown.apply(this, arguments); // } // }, drag: function(evt: MouseEvent, x: number, y: number) { let interactive = _.isFunction(this.options.interactive) ? this.options.interactive(this, 'pointermove') : this.options.interactive; if (interactive !== false) { this.paper.trigger('dragging-node-over-canvas', {type: Flo.DnDEventType.DRAG, view: this, event: evt}); } joint.dia.ElementView.prototype.drag.apply(this, arguments); }, dragEnd: function(evt: MouseEvent, x: number, y: number) { // jshint ignore:line this.paper.trigger('dragging-node-over-canvas', {type: Flo.DnDEventType.DROP, view: this, event: evt}); joint.dia.ElementView.prototype.dragEnd.apply(this, arguments); }, // events: { // // Tooltips on the elements in the graph // 'mouseenter': function(evt: MouseEvent) { // if (this.canShowTooltip) { // this.showTooltip(evt.pageX, evt.pageY); // } // if (!this._hovering && !this.paper.__creatingLinkFromPort) { // this._hovering = true; // if (isChrome || isFF) { // this._tempZorder = this.model.get('z'); // this.model.toFront({deep: true}); // } // } // }, // 'mouseleave': function() { // this.hideTooltip(); // if (this._hovering) { // this._hovering = false; // if (isChrome || isFF) { // this.model.set('z', this._tempZorder); // var z = this._tempZorder; // this.model.getEmbeddedCells({breadthFirst: true}).forEach(function(cell: dia.Cell) { // cell.set('z', ++z); // }); // } // } // }, // 'mousemove': function(evt: MouseEvent) { // this.moveTooltip(evt.pageX, evt.pageY); // } // }, // showTooltip: function(x: number, y: number) { // var mousex = x + 10; // var mousey = y + 10; // // var nodeTooltip: HTMLElement; // if (this.model instanceof joint.dia.Element && this.model.get('metadata')) { // nodeTooltip = document.createElement('div'); // $(nodeTooltip).addClass('node-tooltip'); // // $(nodeTooltip).appendTo($('body')).fadeIn('fast'); // $(nodeTooltip).addClass('tooltip-description'); // var nodeTitle = document.createElement('div'); // $(nodeTooltip).append(nodeTitle); // var nodeDescription = document.createElement('div'); // $(nodeTooltip).append(nodeDescription); // // var model = this.model; // // if (model.attr('metadata/name')) { // var typeSpan = document.createElement('span'); // $(typeSpan).addClass('tooltip-title-type'); // $(nodeTitle).append(typeSpan); // $(typeSpan).text(model.attr('metadata/name')); // if (model.attr('metadata/group')) { // var groupSpan = document.createElement('span'); // $(groupSpan).addClass('tooltip-title-group'); // $(nodeTitle).append(groupSpan); // $(groupSpan).text('(' + model.attr('metadata/group') + ')'); // } // } // // model.get('metadata').get('description').then(function(description: string) { // $(nodeDescription).text(description); // }, function(error: any) { // if (error) { // Logger.error(error); // } // }); // // // defaultValue // if (!model.attr('metadata/metadata/hide-tooltip-options')) { // model.get('metadata')?.get('properties').then(function(metaProps: any) { // var props = model.attr('props'); // array of {'name':,'value':} // if (metaProps && props) { // Object.keys(props).sort().forEach(function(propertyName) { // if (metaProps[propertyName]) { // var optionRow = document.createElement('div'); // var optionName = document.createElement('span'); // var optionDescription = document.createElement('span'); // $(optionName).addClass('node-tooltip-option-name'); // $(optionDescription).addClass('node-tooltip-option-description'); // $(optionName).text(metaProps[propertyName].name); // $(optionDescription).text(props[propertyName]);//nodeOptionData[i].description); // $(optionRow).append(optionName); // $(optionRow).append(optionDescription); // $(nodeTooltip).append(optionRow); // } // // This was the code to add every parameter in: // // $(optionName).addClass('node-tooltip-option-name'); // // $(optionDescription).addClass('node-tooltip-option-description'); // // $(optionName).text(metaProps[propertyName].name); // // $(optionDescription).text(metaProps[propertyName].description); // // $(optionRow).append(optionName); // // $(optionRow).append(optionDescription); // // $(nodeTooltip).append(optionRow); // }); // } // }, function(error: any) { // if (error) { // Logger.error(error); // } // }); // } // // $('.node-tooltip').css({ top: mousey, left: mousex }); // } else if (this.model.get('type') === joint.shapes.flo.DECORATION_TYPE && this.model.attr('./kind') === 'error') { // Logger.debug('mouse enter: ERROR box=' + JSON.stringify(this.model.getBBox())); // nodeTooltip = document.createElement('div'); // var errors = this.model.attr('messages'); // if (errors && errors.length > 0) { // $(nodeTooltip).addClass('error-tooltip'); // $(nodeTooltip).appendTo($('body')).fadeIn('fast'); // var header = document.createElement('p'); // $(header).text('Errors:'); // $(nodeTooltip).append(header); // for (var i = 0;i < errors.length; i++) { // var errorElement = document.createElement('li'); // $(errorElement).text(errors[i]); // $(nodeTooltip).append(errorElement); // } // $('.error-tooltip').css({ top: mousey, left: mousex }); // } // } // }, // hideTooltip: function() { // $('.node-tooltip').remove(); // $('.error-tooltip').remove(); // }, // moveTooltip: function(x: number, y: number) { // $('.node-tooltip') // .css({ top: y + 10, left: x + 10 }); // $('.error-tooltip') // .css({ top: y + 10, left: x + 10 }); // } }); joint.shapes.flo.ErrorDecoration = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><image/></g></g>', defaults: joint.util.deepSupplement({ type: joint.shapes.flo.DECORATION_TYPE, size: ERROR_MARKER_SIZE, attrs: { 'image': ERROR_MARKER_SIZE } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.flo.PaletteGroupHeader = joint.shapes.basic.Generic.extend({ // The path is the open/close arrow, defaults to vertical (open) markup: '<g class="scalable"><rect/></g><text/><g class="rotatable"><path d="m 10 10 l 5 8.7 l 5 -8.7 z"/></g>', defaults: joint.util.deepSupplement({ type: 'palette.groupheader', size: {width: 170, height: 30}, position: {x: 0, y: 0}, attrs: { 'rect': { fill: '#34302d', 'stroke-width': 1, stroke: '#6db33f', 'follow-scale': true, width: 80, height: 40 }, 'text': { text: '', fill: '#eeeeee', 'ref-x': 0.5, 'ref-y': 7, 'x-alignment': 'middle', 'font-size': 18/*, 'font-weight': 'bold', 'font-variant': 'small-caps', 'text-transform': 'capitalize'*/ }, 'path': { fill: 'white', 'stroke-width': 2, stroke: 'white'/*,transform:'rotate(90,15,15)'*/} }, // custom properties isOpen: true }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.flo.NoMatchesFound = joint.shapes.basic.Generic.extend({ // The path is the open/close arrow, defaults to vertical (open) markup: '<g class="scalable"><rect class="no-matches-label-border"/></g><rect class="no-mathes-label-bg"/><text class="no-matches-label"/>', defaults: joint.util.deepSupplement({ size: {width: 170, height: 30}, position: {x: 0, y: 0}, attrs: { '.no-matches-label-border': { refWidth: 1, refHeight: 1, refX: 0, refY: 0, }, '.no-macthes-label-bg': { ref: '.no-matches-label', refWidth: 10, refHeight: 2, 'follow-scale': true }, '.no-matches-label': { text: 'No results found.', ref: '.no-matches-label-border', refY: 0.5, refY2: 5, yAlignment: 'middle', }, }, }, joint.shapes.basic.Generic.prototype.defaults) }); } export namespace Constants { export const REMOVE_HANDLE_TYPE = REMOVE; export const PROPERTIES_HANDLE_TYPE = 'properties'; export const ERROR_DECORATION_KIND = ERROR; export const PALETTE_CONTEXT = 'palette'; export const CANVAS_CONTEXT = 'canvas'; export const FEEDBACK_CONTEXT = 'feedback'; } export namespace Shapes { export interface CreationParams extends Flo.CreationParams { renderer?: Flo.Renderer; paper?: dia.Paper; graph?: dia.Graph; } export interface ElementCreationParams extends CreationParams { position?: dia.Point; } export interface LinkCreationParams extends CreationParams { source: Flo.LinkEnd; target: Flo.LinkEnd; } export interface EmbeddedChildCreationParams extends CreationParams { parent: dia.Cell; position?: dia.Point; } export interface DecorationCreationParams extends EmbeddedChildCreationParams { kind: string; messages: Array<string>; } export interface HandleCreationParams extends EmbeddedChildCreationParams { kind: string; } export interface FilterOptions { amount: number; [propName: string]: any; } export class Factory { /** * Create a JointJS node that embeds extra metadata (properties). */ static createNode(params: ElementCreationParams): dia.Element { let renderer = params.renderer; let paper = params.paper; let metadata = params.metadata; let position = params.position; let props = params.props; let graph = params.graph || (params.paper ? params.paper.model : undefined); let node: dia.Element; if (!position) { position = {x: 0, y: 0}; } if (renderer && _.isFunction(renderer.createNode)) { node = renderer.createNode({graph, paper}, metadata, props); } else { node = new joint.shapes.flo.Node(); if (metadata) { node.attr('.label/text', metadata.name); } } node.set('type', joint.shapes.flo.NODE_TYPE); if (position) { node.set('position', position); } if (props) { Array.from(props.keys()).forEach(key => node.attr(`props/${key}`, props!.get(key))); } node.set('metadata', metadata); if (graph) { graph.addCell(node); } if (renderer && _.isFunction(renderer.initializeNewNode)) { let descriptor: Flo.ViewerDescriptor = { paper: paper, graph: graph }; renderer.initializeNewNode(node, descriptor); } return node; } static createLink(params: LinkCreationParams): dia.Link { let renderer = params.renderer; let paper = params.paper; let metadata = params.metadata; let source = params.source; let target = params.target; let props = params.props; let graph = params.graph || (params.paper ? params.paper.model : undefined); let link: dia.Link; if (renderer && _.isFunction(renderer.createLink)) { link = renderer.createLink(source, target, metadata, props); } else { link = new joint.shapes.flo.Link(); } if (source) { link.set('source', source); } if (target) { link.set('target', target); } link.set('type', joint.shapes.flo.LINK_TYPE); if (metadata) { link.set('metadata', metadata); } if (props) { Array.from(props.keys()).forEach(key => link.attr(`props/${key}`, props!.get(key))); } if (graph) { graph.addCell(link); } if (renderer && _.isFunction(renderer.initializeNewLink)) { let descriptor: Flo.ViewerDescriptor = { paper: paper, graph: graph }; renderer.initializeNewLink(link, descriptor); } // prevent creation of link breaks link.attr('.marker-vertices/display', 'none'); return link; } static createDecoration(params: DecorationCreationParams): dia.Element { let renderer = params.renderer; let paper = params.paper; let parent = params.parent; let kind = params.kind; let messages = params.messages; let location = params.position; let graph = params.graph || (params.paper ? params.paper.model : undefined); let decoration: dia.Element; if (renderer && _.isFunction(renderer.createDecoration)) { decoration = renderer.createDecoration(kind, parent); } if (decoration) { decoration.set('type', joint.shapes.flo.DECORATION_TYPE); if ((isChrome || isFF) && parent && typeof parent.get('z') === 'number') { decoration.set('z', parent.get('z') + 1); } decoration.attr('./kind', kind); decoration.attr('messages', messages); if (graph) { graph.addCell(decoration); } parent.embed(decoration); if (renderer && _.isFunction(renderer.initializeNewDecoration)) { let descriptor: Flo.ViewerDescriptor = { paper: paper, graph: graph }; renderer.initializeNewDecoration(decoration, descriptor); } return decoration; } } static createHandle(params: HandleCreationParams): dia.Element { let renderer = params.renderer; let paper = params.paper; let parent = params.parent; let kind = params.kind; let location = params.position; let graph = params.graph || (params.paper ? params.paper.model : undefined); let handle: dia.Element; if (!location) { location = {x: 0, y: 0}; } if (renderer && _.isFunction(renderer.createHandle)) { handle = renderer.createHandle(kind, parent); } else { handle = new joint.shapes.flo.ErrorDecoration({ size: HANDLE_SIZE, attrs: { 'image': { 'xlink:href': HANDLE_ICON_MAP.get(kind) } } }); } handle.set('type', joint.shapes.flo.HANDLE_TYPE); handle.set('position', location); if ((isChrome || isFF) && parent && typeof parent.get('z') === 'number') { handle.set('z', parent.get('z') + 1); } handle.attr('./kind', kind); if (graph) { graph.addCell(handle); } parent.embed(handle); if (renderer && _.isFunction(renderer.initializeNewHandle)) { let descriptor: Flo.ViewerDescriptor = { paper: paper, graph: graph }; renderer.initializeNewHandle(handle, descriptor); } return handle; } } } loadShapes();
the_stack
import { VSBuffer } from 'vs/base/common/buffer'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IStringDictionary } from 'vs/base/common/collections'; import { Event } from 'vs/base/common/event'; import { deepClone } from 'vs/base/common/objects'; import { URI } from 'vs/base/common/uri'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { FileOperationError, FileOperationResult, IFileContent, IFileService, IFileStat } from 'vs/platform/files/common/files'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; import { AbstractInitializer, AbstractSynchroniser, IAcceptResult, IFileResourcePreview, IMergeResult } from 'vs/platform/userDataSync/common/abstractSynchronizer'; import { areSame, IMergeResult as ISnippetsMergeResult, merge } from 'vs/platform/userDataSync/common/snippetsMerge'; import { Change, IRemoteUserData, ISyncData, ISyncResourceHandle, IUserDataSyncBackupStoreService, IUserDataSynchroniser, IUserDataSyncLogService, IUserDataSyncEnablementService, IUserDataSyncStoreService, SyncResource, USER_DATA_SYNC_SCHEME } from 'vs/platform/userDataSync/common/userDataSync'; interface ISnippetsResourcePreview extends IFileResourcePreview { previewResult: IMergeResult; } interface ISnippetsAcceptedResourcePreview extends IFileResourcePreview { acceptResult: IAcceptResult; } export class SnippetsSynchroniser extends AbstractSynchroniser implements IUserDataSynchroniser { protected readonly version: number = 1; private readonly snippetsFolder: URI; constructor( @IEnvironmentService environmentService: IEnvironmentService, @IFileService fileService: IFileService, @IStorageService storageService: IStorageService, @IUserDataSyncStoreService userDataSyncStoreService: IUserDataSyncStoreService, @IUserDataSyncBackupStoreService userDataSyncBackupStoreService: IUserDataSyncBackupStoreService, @IUserDataSyncLogService logService: IUserDataSyncLogService, @IConfigurationService configurationService: IConfigurationService, @IUserDataSyncEnablementService userDataSyncEnablementService: IUserDataSyncEnablementService, @ITelemetryService telemetryService: ITelemetryService, @IUriIdentityService uriIdentityService: IUriIdentityService, ) { super(SyncResource.Snippets, fileService, environmentService, storageService, userDataSyncStoreService, userDataSyncBackupStoreService, userDataSyncEnablementService, telemetryService, logService, configurationService, uriIdentityService); this.snippetsFolder = environmentService.snippetsHome; this._register(this.fileService.watch(environmentService.userRoamingDataHome)); this._register(this.fileService.watch(this.snippetsFolder)); this._register(Event.filter(this.fileService.onDidFilesChange, e => e.affects(this.snippetsFolder))(() => this.triggerLocalChange())); } protected async generateSyncPreview(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, isRemoteDataFromCurrentMachine: boolean): Promise<ISnippetsResourcePreview[]> { const local = await this.getSnippetsFileContents(); const localSnippets = this.toSnippetsContents(local); const remoteSnippets: IStringDictionary<string> | null = remoteUserData.syncData ? this.parseSnippets(remoteUserData.syncData) : null; // Use remote data as last sync data if last sync data does not exist and remote data is from same machine lastSyncUserData = lastSyncUserData === null && isRemoteDataFromCurrentMachine ? remoteUserData : lastSyncUserData; const lastSyncSnippets: IStringDictionary<string> | null = lastSyncUserData && lastSyncUserData.syncData ? this.parseSnippets(lastSyncUserData.syncData) : null; if (remoteSnippets) { this.logService.trace(`${this.syncResourceLogLabel}: Merging remote snippets with local snippets...`); } else { this.logService.trace(`${this.syncResourceLogLabel}: Remote snippets does not exist. Synchronizing snippets for the first time.`); } const mergeResult = merge(localSnippets, remoteSnippets, lastSyncSnippets); return this.getResourcePreviews(mergeResult, local, remoteSnippets || {}); } protected async hasRemoteChanged(lastSyncUserData: IRemoteUserData): Promise<boolean> { const lastSyncSnippets: IStringDictionary<string> | null = lastSyncUserData.syncData ? this.parseSnippets(lastSyncUserData.syncData) : null; if (lastSyncSnippets === null) { return true; } const local = await this.getSnippetsFileContents(); const localSnippets = this.toSnippetsContents(local); const mergeResult = merge(localSnippets, lastSyncSnippets, lastSyncSnippets); return Object.keys(mergeResult.remote.added).length > 0 || Object.keys(mergeResult.remote.updated).length > 0 || mergeResult.remote.removed.length > 0 || mergeResult.conflicts.length > 0; } protected async getMergeResult(resourcePreview: ISnippetsResourcePreview, token: CancellationToken): Promise<IMergeResult> { return resourcePreview.previewResult; } protected async getAcceptResult(resourcePreview: ISnippetsResourcePreview, resource: URI, content: string | null | undefined, token: CancellationToken): Promise<IAcceptResult> { /* Accept local resource */ if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }))) { return { content: resourcePreview.fileContent ? resourcePreview.fileContent.value.toString() : null, localChange: Change.None, remoteChange: resourcePreview.fileContent ? resourcePreview.remoteContent !== null ? Change.Modified : Change.Added : Change.Deleted }; } /* Accept remote resource */ if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }))) { return { content: resourcePreview.remoteContent, localChange: resourcePreview.remoteContent !== null ? resourcePreview.fileContent ? Change.Modified : Change.Added : Change.Deleted, remoteChange: Change.None, }; } /* Accept preview resource */ if (this.extUri.isEqualOrParent(resource, this.syncPreviewFolder)) { if (content === undefined) { return { content: resourcePreview.previewResult.content, localChange: resourcePreview.previewResult.localChange, remoteChange: resourcePreview.previewResult.remoteChange, }; } else { return { content, localChange: content === null ? resourcePreview.fileContent !== null ? Change.Deleted : Change.None : Change.Modified, remoteChange: content === null ? resourcePreview.remoteContent !== null ? Change.Deleted : Change.None : Change.Modified }; } } throw new Error(`Invalid Resource: ${resource.toString()}`); } protected async applyResult(remoteUserData: IRemoteUserData, lastSyncUserData: IRemoteUserData | null, resourcePreviews: [ISnippetsResourcePreview, IAcceptResult][], force: boolean): Promise<void> { const accptedResourcePreviews: ISnippetsAcceptedResourcePreview[] = resourcePreviews.map(([resourcePreview, acceptResult]) => ({ ...resourcePreview, acceptResult })); if (accptedResourcePreviews.every(({ localChange, remoteChange }) => localChange === Change.None && remoteChange === Change.None)) { this.logService.info(`${this.syncResourceLogLabel}: No changes found during synchronizing snippets.`); } if (accptedResourcePreviews.some(({ localChange }) => localChange !== Change.None)) { // back up all snippets await this.updateLocalBackup(accptedResourcePreviews); await this.updateLocalSnippets(accptedResourcePreviews, force); } if (accptedResourcePreviews.some(({ remoteChange }) => remoteChange !== Change.None)) { remoteUserData = await this.updateRemoteSnippets(accptedResourcePreviews, remoteUserData, force); } if (lastSyncUserData?.ref !== remoteUserData.ref) { // update last sync this.logService.trace(`${this.syncResourceLogLabel}: Updating last synchronized snippets...`); await this.updateLastSyncUserData(remoteUserData); this.logService.info(`${this.syncResourceLogLabel}: Updated last synchronized snippets`); } for (const { previewResource } of accptedResourcePreviews) { // Delete the preview try { await this.fileService.del(previewResource); } catch (e) { /* ignore */ } } } private getResourcePreviews(snippetsMergeResult: ISnippetsMergeResult, localFileContent: IStringDictionary<IFileContent>, remoteSnippets: IStringDictionary<string>): ISnippetsResourcePreview[] { const resourcePreviews: Map<string, ISnippetsResourcePreview> = new Map<string, ISnippetsResourcePreview>(); /* Snippets added remotely -> add locally */ for (const key of Object.keys(snippetsMergeResult.local.added)) { const previewResult: IMergeResult = { content: snippetsMergeResult.local.added[key], hasConflicts: false, localChange: Change.Added, remoteChange: Change.None, }; resourcePreviews.set(key, { fileContent: null, localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }), localContent: null, remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }), remoteContent: remoteSnippets[key], previewResource: this.extUri.joinPath(this.syncPreviewFolder, key), previewResult, localChange: previewResult.localChange, remoteChange: previewResult.remoteChange, acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }) }); } /* Snippets updated remotely -> update locally */ for (const key of Object.keys(snippetsMergeResult.local.updated)) { const previewResult: IMergeResult = { content: snippetsMergeResult.local.updated[key], hasConflicts: false, localChange: Change.Modified, remoteChange: Change.None, }; resourcePreviews.set(key, { localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }), fileContent: localFileContent[key], localContent: localFileContent[key].value.toString(), remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }), remoteContent: remoteSnippets[key], previewResource: this.extUri.joinPath(this.syncPreviewFolder, key), previewResult, localChange: previewResult.localChange, remoteChange: previewResult.remoteChange, acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }) }); } /* Snippets removed remotely -> remove locally */ for (const key of snippetsMergeResult.local.removed) { const previewResult: IMergeResult = { content: null, hasConflicts: false, localChange: Change.Deleted, remoteChange: Change.None, }; resourcePreviews.set(key, { localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }), fileContent: localFileContent[key], localContent: localFileContent[key].value.toString(), remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }), remoteContent: null, previewResource: this.extUri.joinPath(this.syncPreviewFolder, key), previewResult, localChange: previewResult.localChange, remoteChange: previewResult.remoteChange, acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }) }); } /* Snippets added locally -> add remotely */ for (const key of Object.keys(snippetsMergeResult.remote.added)) { const previewResult: IMergeResult = { content: snippetsMergeResult.remote.added[key], hasConflicts: false, localChange: Change.None, remoteChange: Change.Added, }; resourcePreviews.set(key, { localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }), fileContent: localFileContent[key], localContent: localFileContent[key].value.toString(), remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }), remoteContent: null, previewResource: this.extUri.joinPath(this.syncPreviewFolder, key), previewResult, localChange: previewResult.localChange, remoteChange: previewResult.remoteChange, acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }) }); } /* Snippets updated locally -> update remotely */ for (const key of Object.keys(snippetsMergeResult.remote.updated)) { const previewResult: IMergeResult = { content: snippetsMergeResult.remote.updated[key], hasConflicts: false, localChange: Change.None, remoteChange: Change.Modified, }; resourcePreviews.set(key, { localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }), fileContent: localFileContent[key], localContent: localFileContent[key].value.toString(), remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }), remoteContent: remoteSnippets[key], previewResource: this.extUri.joinPath(this.syncPreviewFolder, key), previewResult, localChange: previewResult.localChange, remoteChange: previewResult.remoteChange, acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }) }); } /* Snippets removed locally -> remove remotely */ for (const key of snippetsMergeResult.remote.removed) { const previewResult: IMergeResult = { content: null, hasConflicts: false, localChange: Change.None, remoteChange: Change.Deleted, }; resourcePreviews.set(key, { localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }), fileContent: null, localContent: null, remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }), remoteContent: remoteSnippets[key], previewResource: this.extUri.joinPath(this.syncPreviewFolder, key), previewResult, localChange: previewResult.localChange, remoteChange: previewResult.remoteChange, acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }) }); } /* Snippets with conflicts */ for (const key of snippetsMergeResult.conflicts) { const previewResult: IMergeResult = { content: localFileContent[key] ? localFileContent[key].value.toString() : null, hasConflicts: true, localChange: localFileContent[key] ? Change.Modified : Change.Added, remoteChange: remoteSnippets[key] ? Change.Modified : Change.Added }; resourcePreviews.set(key, { localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }), fileContent: localFileContent[key] || null, localContent: localFileContent[key] ? localFileContent[key].value.toString() : null, remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }), remoteContent: remoteSnippets[key] || null, previewResource: this.extUri.joinPath(this.syncPreviewFolder, key), previewResult, localChange: previewResult.localChange, remoteChange: previewResult.remoteChange, acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }) }); } /* Unmodified Snippets */ for (const key of Object.keys(localFileContent)) { if (!resourcePreviews.has(key)) { const previewResult: IMergeResult = { content: localFileContent[key] ? localFileContent[key].value.toString() : null, hasConflicts: false, localChange: Change.None, remoteChange: Change.None }; resourcePreviews.set(key, { localResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }), fileContent: localFileContent[key] || null, localContent: localFileContent[key] ? localFileContent[key].value.toString() : null, remoteResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' }), remoteContent: remoteSnippets[key] || null, previewResource: this.extUri.joinPath(this.syncPreviewFolder, key), previewResult, localChange: previewResult.localChange, remoteChange: previewResult.remoteChange, acceptedResource: this.extUri.joinPath(this.syncPreviewFolder, key).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }) }); } } return [...resourcePreviews.values()]; } async getAssociatedResources({ uri }: ISyncResourceHandle): Promise<{ resource: URI; comparableResource: URI }[]> { let content = await super.resolveContent(uri); if (content) { const syncData = this.parseSyncData(content); if (syncData) { const snippets = this.parseSnippets(syncData); const result = []; for (const snippet of Object.keys(snippets)) { const resource = this.extUri.joinPath(uri, snippet); const comparableResource = this.extUri.joinPath(this.snippetsFolder, snippet); const exists = await this.fileService.exists(comparableResource); result.push({ resource, comparableResource: exists ? comparableResource : this.extUri.joinPath(this.syncPreviewFolder, snippet).with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' }) }); } return result; } } return []; } override async resolveContent(uri: URI): Promise<string | null> { if (this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'remote' })) || this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'local' })) || this.extUri.isEqualOrParent(uri, this.syncPreviewFolder.with({ scheme: USER_DATA_SYNC_SCHEME, authority: 'accepted' }))) { return this.resolvePreviewContent(uri); } let content = await super.resolveContent(uri); if (content) { return content; } content = await super.resolveContent(this.extUri.dirname(uri)); if (content) { const syncData = this.parseSyncData(content); if (syncData) { const snippets = this.parseSnippets(syncData); return snippets[this.extUri.basename(uri)] || null; } } return null; } async hasLocalData(): Promise<boolean> { try { const localSnippets = await this.getSnippetsFileContents(); if (Object.keys(localSnippets).length) { return true; } } catch (error) { /* ignore error */ } return false; } private async updateLocalBackup(resourcePreviews: IFileResourcePreview[]): Promise<void> { const local: IStringDictionary<IFileContent> = {}; for (const resourcePreview of resourcePreviews) { if (resourcePreview.fileContent) { local[this.extUri.basename(resourcePreview.localResource!)] = resourcePreview.fileContent; } } await this.backupLocal(JSON.stringify(this.toSnippetsContents(local))); } private async updateLocalSnippets(resourcePreviews: ISnippetsAcceptedResourcePreview[], force: boolean): Promise<void> { for (const { fileContent, acceptResult, localResource, remoteResource, localChange } of resourcePreviews) { if (localChange !== Change.None) { const key = remoteResource ? this.extUri.basename(remoteResource) : this.extUri.basename(localResource!); const resource = this.extUri.joinPath(this.snippetsFolder, key); // Removed if (localChange === Change.Deleted) { this.logService.trace(`${this.syncResourceLogLabel}: Deleting snippet...`, this.extUri.basename(resource)); await this.fileService.del(resource); this.logService.info(`${this.syncResourceLogLabel}: Deleted snippet`, this.extUri.basename(resource)); } // Added else if (localChange === Change.Added) { this.logService.trace(`${this.syncResourceLogLabel}: Creating snippet...`, this.extUri.basename(resource)); await this.fileService.createFile(resource, VSBuffer.fromString(acceptResult.content!), { overwrite: force }); this.logService.info(`${this.syncResourceLogLabel}: Created snippet`, this.extUri.basename(resource)); } // Updated else { this.logService.trace(`${this.syncResourceLogLabel}: Updating snippet...`, this.extUri.basename(resource)); await this.fileService.writeFile(resource, VSBuffer.fromString(acceptResult.content!), force ? undefined : fileContent!); this.logService.info(`${this.syncResourceLogLabel}: Updated snippet`, this.extUri.basename(resource)); } } } } private async updateRemoteSnippets(resourcePreviews: ISnippetsAcceptedResourcePreview[], remoteUserData: IRemoteUserData, forcePush: boolean): Promise<IRemoteUserData> { const currentSnippets: IStringDictionary<string> = remoteUserData.syncData ? this.parseSnippets(remoteUserData.syncData) : {}; const newSnippets: IStringDictionary<string> = deepClone(currentSnippets); for (const { acceptResult, localResource, remoteResource, remoteChange } of resourcePreviews) { if (remoteChange !== Change.None) { const key = localResource ? this.extUri.basename(localResource) : this.extUri.basename(remoteResource!); if (remoteChange === Change.Deleted) { delete newSnippets[key]; } else { newSnippets[key] = acceptResult.content!; } } } if (!areSame(currentSnippets, newSnippets)) { // update remote this.logService.trace(`${this.syncResourceLogLabel}: Updating remote snippets...`); remoteUserData = await this.updateRemoteUserData(JSON.stringify(newSnippets), forcePush ? null : remoteUserData.ref); this.logService.info(`${this.syncResourceLogLabel}: Updated remote snippets`); } return remoteUserData; } private parseSnippets(syncData: ISyncData): IStringDictionary<string> { return JSON.parse(syncData.content); } private toSnippetsContents(snippetsFileContents: IStringDictionary<IFileContent>): IStringDictionary<string> { const snippets: IStringDictionary<string> = {}; for (const key of Object.keys(snippetsFileContents)) { snippets[key] = snippetsFileContents[key].value.toString(); } return snippets; } private async getSnippetsFileContents(): Promise<IStringDictionary<IFileContent>> { const snippets: IStringDictionary<IFileContent> = {}; let stat: IFileStat; try { stat = await this.fileService.resolve(this.snippetsFolder); } catch (e) { // No snippets if (e instanceof FileOperationError && e.fileOperationResult === FileOperationResult.FILE_NOT_FOUND) { return snippets; } else { throw e; } } for (const entry of stat.children || []) { const resource = entry.resource; const extension = this.extUri.extname(resource); if (extension === '.json' || extension === '.code-snippets') { const key = this.extUri.relativePath(this.snippetsFolder, resource)!; const content = await this.fileService.readFile(resource); snippets[key] = content; } } return snippets; } } export class SnippetsInitializer extends AbstractInitializer { constructor( @IFileService fileService: IFileService, @IEnvironmentService environmentService: IEnvironmentService, @IUserDataSyncLogService logService: IUserDataSyncLogService, @IUriIdentityService uriIdentityService: IUriIdentityService, ) { super(SyncResource.Snippets, environmentService, logService, fileService, uriIdentityService); } async doInitialize(remoteUserData: IRemoteUserData): Promise<void> { const remoteSnippets: IStringDictionary<string> | null = remoteUserData.syncData ? JSON.parse(remoteUserData.syncData.content) : null; if (!remoteSnippets) { this.logService.info('Skipping initializing snippets because remote snippets does not exist.'); return; } const isEmpty = await this.isEmpty(); if (!isEmpty) { this.logService.info('Skipping initializing snippets because local snippets exist.'); return; } for (const key of Object.keys(remoteSnippets)) { const content = remoteSnippets[key]; if (content) { const resource = this.extUri.joinPath(this.environmentService.snippetsHome, key); await this.fileService.createFile(resource, VSBuffer.fromString(content)); this.logService.info('Created snippet', this.extUri.basename(resource)); } } await this.updateLastSyncUserData(remoteUserData); } private async isEmpty(): Promise<boolean> { try { const stat = await this.fileService.resolve(this.environmentService.snippetsHome); return !stat.children?.length; } catch (error) { return (<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_NOT_FOUND; } } }
the_stack
import Dialog from '../Dialog'; import Client from '../../Client'; import JID from '../../JID'; import { IConnection } from '../../connection/Connection.interface'; import TableElement from '../util/TableElement'; import Translation from '../../util/Translation'; import Log from '../../util/Log'; import Account from '@src/Account'; import MultiUserContact from '@src/MultiUserContact'; import Form from '@connection/Form'; let multiUserJoinTemplate = require('../../../template/multiUserJoin.hbs'); const ENTER_KEY = 13; export default function (server?: string, room?: string) { new MultiUserJoinDialog(server, room); } class MultiUserJoinDialog { private account: Account; private connection: IConnection; private defaultNickname: string; private dialog: Dialog; private dom: JQuery<HTMLElement>; private accountElement: JQuery<HTMLElement>; private serverInputElement: JQuery<HTMLElement>; private roomInputElement: JQuery<HTMLElement>; private passwordInputElement: JQuery<HTMLElement>; private nicknameInputElement: JQuery<HTMLElement>; constructor(private server?: string, private room?: string) { let content = multiUserJoinTemplate({ accounts: Client.getAccountManager() .getAccounts() .map(account => ({ uid: account.getUid(), jid: account.getJID().bare, })), }); this.dialog = new Dialog(content); let dom = (this.dom = this.dialog.open()); this.accountElement = dom.find('select[name="account"]'); this.serverInputElement = dom.find('input[name="server"]'); this.roomInputElement = dom.find('input[name="room"]'); this.passwordInputElement = dom.find('input[name="password"]'); this.nicknameInputElement = dom.find('input[name="nickname"]'); if (server && room) { this.serverInputElement.val(server); this.roomInputElement.val(room); } else { this.updateAccount(Client.getAccountManager().getAccount().getUid()); } this.initializeInputElements(); } private updateAccount(id: string) { this.account = Client.getAccountManager().getAccount(id); this.connection = this.account.getConnection(); this.defaultNickname = this.connection.getJID().node; this.nicknameInputElement.attr('placeholder', this.defaultNickname); this.getMultiUserServices().then((services: JID[]) => { this.serverInputElement.val(services[0].full); this.serverInputElement.trigger('change'); $('#jsxc-serverlist select').empty(); services.forEach(service => { $('#jsxc-serverlist select').append($('<option>').text(service.domain)); }); }); } private initializeInputElements() { this.showContinueElements(); this.accountElement.on('change', () => { let accountId = <string>this.accountElement.val(); if (!this.server || !this.room) { this.updateAccount(accountId); } }); this.serverInputElement.on('change', () => { this.dom.find('.jsxc-inputinfo.jsxc-server').text('').hide(); let jid = new JID(<string>this.serverInputElement.val(), ''); this.getMultiUserRooms(jid); }); this.dom .find('input[type="text"], input[type="password"]') .keydown(() => { this.emptyStatusElement(); this.showContinueElements(); }) .keyup(ev => { if (ev.which === ENTER_KEY) { this.continueHandler(ev); } }); this.dom.find('.jsxc-continue').click(this.continueHandler); this.dom.find('.jsxc-join').click(this.joinHandler); } private showContinueElements() { this.dom.find('.jsxc-continue').show(); this.dom.find('.jsxc-join').hide(); } private showJoinElements() { this.dom.find('.jsxc-continue').hide(); this.dom.find('.jsxc-join').show(); } private getMultiUserServices() { let ownJid = this.connection.getJID(); let serverJid = new JID('', ownJid.domain, ''); let discoInfoRepository = this.account.getDiscoInfoRepository(); return this.connection .getDiscoService() .getDiscoItems(serverJid) .then(stanza => { let promises = []; $(stanza) .find('item') .each((index, element) => { let jid = new JID('', $(element).attr('jid'), ''); //@TODO cache let promise = discoInfoRepository .requestDiscoInfo(jid) .then(discoInfo => { return discoInfoRepository.hasFeature(discoInfo, 'http://jabber.org/protocol/muc'); }) .then(hasFeature => { return hasFeature ? jid : undefined; }) .catch(stanza => { const from = $(stanza).attr('from') || ''; Log.info(`Ignore ${from} as MUC provider, because could not load disco info.`); }); promises.push(promise); }); return Promise.all(promises).then(results => { return results .filter(jid => typeof jid !== 'undefined') .sort(function compare(a, b) { if (!a.domain || !b.domain) { return 0; } if (a.domain.startsWith('conference') && !b.domain.startsWith('conference')) { return -1; } if (!a.domain.startsWith('conference') && b.domain.startsWith('conference')) { return +1; } return a.domain.localeCompare(b.domain); }); }); }); } private getMultiUserRooms(server: JID) { Log.debug('Load room list for ' + server.bare); let roomInfoElement = this.dom.find('.jsxc-inputinfo.jsxc-room'); roomInfoElement.show(); roomInfoElement.addClass('jsxc-waiting'); roomInfoElement.text(Translation.t('Rooms_are_loaded')); this.connection .getDiscoService() .getDiscoItems(server) .then(this.parseRoomList) .catch(this.parseRoomListError) .then(() => { roomInfoElement.removeClass('jsxc-waiting'); }); } private parseRoomList = stanza => { // workaround: chrome does not display dropdown arrow for dynamically filled datalists $('#jsxc-roomlist select').empty(); $(stanza) .find('item') .each(function () { let optionElement = $('<option>'); let jid = new JID($(this).attr('jid')); let name = $(this).attr('name') || jid.node; optionElement.text(name); optionElement.attr('data-jid', jid.full); optionElement.attr('value', jid.node); $('#jsxc-roomlist select').append(optionElement); }); let set = $(stanza).find('set[xmlns="http://jabber.org/protocol/rsm"]'); let roomInfoElement = this.dom.find('.jsxc-inputinfo.jsxc-room'); if (set.length > 0) { let count = set.find('count').text() || '?'; roomInfoElement.text( Translation.t('Could_load_only', { count, }) ); } else { roomInfoElement.text('').hide(); } }; private parseRoomListError = stanza => { let serverInfoElement = this.dom.find('.jsxc-inputinfo.jsxc-server'); let roomInfoElement = this.dom.find('.jsxc-inputinfo.jsxc-room'); let errTextMsg = $(stanza).find('error text').text() || null; Log.warn('Could not load rooms', errTextMsg); if (errTextMsg) { serverInfoElement.show().text(errTextMsg); } roomInfoElement.text('').hide(); $('#jsxc-roomlist select').empty(); }; private continueHandler = ev => { ev.preventDefault(); this.testAndLoadRoomInfo(); return false; }; private async testAndLoadRoomInfo() { this.dom.find('input, select').prop('disabled', true); try { const jid = await this.testInputValues(); const hasRoomInfo = await this.requestRoomInfo(jid); if (hasRoomInfo) { await this.requestMemberList(jid); } this.showJoinElements(); } catch (msg) { this.dom.find('input, select').prop('disabled', false); this.setStatusMessage(typeof msg === 'string' ? msg : Translation.t('Can_not_probe_room'), 'warning'); Log.warn('Error while probing room', msg); } } private testInputValues(): Promise<JID> { let room = <string>this.roomInputElement.val(); let server = this.serverInputElement.val() ? this.serverInputElement.val() : this.serverInputElement.attr('placeholder'); if (!room || !room.match(/^[^"&\'\/:<>@\s]+$/i)) { this.roomInputElement.addClass('jsxc-invalid').keyup(function () { if ($(this).val()) { $(this).removeClass('jsxc-invalid'); } }); return Promise.reject('MUC room JID invalid'); } if (this.serverInputElement.hasClass('jsxc-invalid')) { return Promise.reject('MUC server invalid'); } if (!room.match(/@(.*)$/)) { room += '@' + server; } let roomJid = new JID(room); if (this.account.getContact(roomJid)) { return Promise.reject('You_already_joined_this_room'); } this.dom.find('input[name="room-jid"]').val(room); return Promise.resolve(roomJid); } private requestRoomInfo = async (room: JID) => { this.setWaitingMessage('Loading_room_information'); const discoService = this.connection.getDiscoService(); try { const stanza = await discoService.getDiscoInfo(room); const roomInfoElement = this.parseRoomInfo(stanza); this.setStatusElement(roomInfoElement); } catch (errorStanza) { if ($(errorStanza).find('item-not-found').length > 0) { this.setStatusMessage(Translation.t('Room_not_found_')); return false; } await Promise.reject('I was not able to get any room information.'); } return true; }; private parseRoomInfo = stanza => { let roomInfoElement = $('<div>'); roomInfoElement.append(`<p>${Translation.t('This_room_is')}</p>`); //@TODO test for feature with muc ns let tableElement = new TableElement(2); $(stanza) .find('feature') .each((index, featureElement) => { let feature = $(featureElement).attr('var'); //@REVIEW true? if (feature !== '' && true && feature.indexOf('muc_') === 0) { tableElement.appendRow(Translation.t(`${feature}.keyword`), Translation.t(`${feature}.description`)); } if (feature === 'muc_passwordprotected') { this.passwordInputElement.parents('.form-group').removeClass('jsxc-hidden'); this.passwordInputElement.attr('required', 'required'); this.passwordInputElement.addClass('jsxc-invalid'); } }); let name = $(stanza).find('identity').attr('name'); let subject = $(stanza).find('field[var="muc#roominfo_subject"]').attr('label'); let form = Form.fromXML(stanza); let fields = form.getFields(); fields.forEach(field => { if (!field.getLabel()) { return; } let value = field.getType() === 'boolean' ? field.getValues()[0] === '1' ? Translation.t('Yes') : Translation.t('No') : field.getValues().join(', '); tableElement.appendRow(field.getLabel(), value); }); tableElement.appendRow('Name', name); tableElement.appendRow('Subject', subject); roomInfoElement.append(tableElement.get()); roomInfoElement.append($('<input type="hidden" name="room-name">').val(name)); roomInfoElement.append($('<input type="hidden" name="room-subject">').val(subject)); return roomInfoElement; }; private requestMemberList = (room: JID) => { return this.connection .getDiscoService() .getDiscoItems(room) .then(stanza => { let memberJids = $(stanza) .find('item') .map((index, element) => $(element).attr('jid')) .get(); let row = $('<tr>'); row.append($('<td>').text(Translation.t('Occupants'))); row.append( $('<td>').text(memberJids.length > 0 ? memberJids.join(', ') : Translation.t('Occupants_not_provided')) ); this.dom.find('.jsxc-status-container table').append(row); }); }; private joinHandler = ev => { ev.preventDefault(); //@TODO disable handler, show spinner let jid = new JID(<string>this.dom.find('input[name="room-jid"]').val()); let name = <string>this.dom.find('input[name="room-name"]').val() || undefined; let nickname = <string>this.nicknameInputElement.val() || this.defaultNickname; let password = <string>this.passwordInputElement.val() || undefined; let subject = <string>this.dom.find('input[name="room-subject"]').val() || undefined; let multiUserContact = new MultiUserContact(this.account, jid, name); multiUserContact.setNickname(nickname); multiUserContact.setBookmark(true); multiUserContact.setAutoJoin(true); multiUserContact.setPassword(password); multiUserContact.setSubject(subject); this.account.getContactManager().add(multiUserContact); multiUserContact.join(); multiUserContact.getChatWindowController().openProminently(); this.dialog.close(); return false; }; private setWaitingMessage(msg: string) { this.setStatusMessage(msg, 'waiting'); } private setStatusMessage(msg: string, level?: 'waiting' | 'warning') { let textElement = $('<p>').text(msg); if (level) { textElement.addClass('jsxc-' + level); } this.setStatusElement(textElement); } private setStatusElement(element) { let messageElement = this.dom.find('.jsxc-status-container'); messageElement.empty(); messageElement.append(element); } private emptyStatusElement() { this.dom.find('.jsxc-status-container').empty(); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; export const ResponseBase: msRest.CompositeMapper = { serializedName: "ResponseBase", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "ResponseBase", className: "ResponseBase", modelProperties: { _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const Identifiable: msRest.CompositeMapper = { serializedName: "Identifiable", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Identifiable", modelProperties: { ...ResponseBase.type.modelProperties, id: { readOnly: true, serializedName: "id", type: { name: "String" } } } } }; export const Response: msRest.CompositeMapper = { serializedName: "Response", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Response", modelProperties: { ...Identifiable.type.modelProperties, readLink: { readOnly: true, serializedName: "readLink", type: { name: "String" } }, webSearchUrl: { readOnly: true, serializedName: "webSearchUrl", type: { name: "String" } }, potentialAction: { readOnly: true, serializedName: "potentialAction", type: { name: "Sequence", element: { type: { name: "Composite", className: "Action" } } } }, immediateAction: { readOnly: true, serializedName: "immediateAction", type: { name: "Sequence", element: { type: { name: "Composite", className: "Action" } } } }, preferredClickthroughUrl: { readOnly: true, serializedName: "preferredClickthroughUrl", type: { name: "String" } }, adaptiveCard: { readOnly: true, serializedName: "adaptiveCard", type: { name: "String" } } } } }; export const Thing: msRest.CompositeMapper = { serializedName: "Thing", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Thing", modelProperties: { ...Response.type.modelProperties, url: { readOnly: true, serializedName: "url", type: { name: "String" } } } } }; export const CreativeWork: msRest.CompositeMapper = { serializedName: "CreativeWork", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "CreativeWork", modelProperties: { ...Thing.type.modelProperties, thumbnailUrl: { readOnly: true, serializedName: "thumbnailUrl", type: { name: "String" } }, about: { readOnly: true, serializedName: "about", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, mentions: { readOnly: true, serializedName: "mentions", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, provider: { readOnly: true, serializedName: "provider", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, creator: { readOnly: true, serializedName: "creator", type: { name: "Composite", className: "Thing" } }, text: { readOnly: true, serializedName: "text", type: { name: "String" } }, discussionUrl: { readOnly: true, serializedName: "discussionUrl", type: { name: "String" } }, commentCount: { readOnly: true, serializedName: "commentCount", type: { name: "Number" } }, mainEntity: { readOnly: true, serializedName: "mainEntity", type: { name: "Composite", className: "Thing" } }, headLine: { readOnly: true, serializedName: "headLine", type: { name: "String" } }, copyrightHolder: { readOnly: true, serializedName: "copyrightHolder", type: { name: "Composite", className: "Thing" } }, copyrightYear: { readOnly: true, serializedName: "copyrightYear", type: { name: "Number" } }, disclaimer: { readOnly: true, serializedName: "disclaimer", type: { name: "String" } }, isAccessibleForFree: { readOnly: true, serializedName: "isAccessibleForFree", type: { name: "Boolean" } }, genre: { readOnly: true, serializedName: "genre", type: { name: "Sequence", element: { type: { name: "String" } } } }, isFamilyFriendly: { readOnly: true, serializedName: "isFamilyFriendly", type: { name: "Boolean" } } } } }; export const Action: msRest.CompositeMapper = { serializedName: "Action", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Action", modelProperties: { ...CreativeWork.type.modelProperties, result: { readOnly: true, serializedName: "result", type: { name: "Sequence", element: { type: { name: "Composite", className: "Thing" } } } }, displayName: { readOnly: true, serializedName: "displayName", type: { name: "String" } }, isTopAction: { readOnly: true, serializedName: "isTopAction", type: { name: "Boolean" } }, serviceUrl: { readOnly: true, serializedName: "serviceUrl", type: { name: "String" } } } } }; export const SearchAction: msRest.CompositeMapper = { serializedName: "SearchAction", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "SearchAction", modelProperties: { ...Action.type.modelProperties, displayText: { readOnly: true, serializedName: "displayText", type: { name: "String" } }, query: { readOnly: true, serializedName: "query", type: { name: "String" } }, searchKind: { readOnly: true, serializedName: "searchKind", defaultValue: 'WebSearch', type: { name: "String" } } } } }; export const SuggestionsSuggestionGroup: msRest.CompositeMapper = { serializedName: "Suggestions/SuggestionGroup", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "SuggestionsSuggestionGroup", className: "SuggestionsSuggestionGroup", modelProperties: { name: { required: true, serializedName: "name", defaultValue: 'Unknown', type: { name: "String" } }, searchSuggestions: { required: true, serializedName: "searchSuggestions", type: { name: "Sequence", element: { type: { name: "Composite", className: "SearchAction" } } } }, _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const Answer: msRest.CompositeMapper = { serializedName: "Answer", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Answer", modelProperties: { ...Response.type.modelProperties } } }; export const SearchResultsAnswer: msRest.CompositeMapper = { serializedName: "SearchResultsAnswer", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "SearchResultsAnswer", modelProperties: { ...Answer.type.modelProperties, queryContext: { readOnly: true, serializedName: "queryContext", type: { name: "Composite", className: "QueryContext" } } } } }; export const Suggestions: msRest.CompositeMapper = { serializedName: "Suggestions", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "Suggestions", modelProperties: { ...SearchResultsAnswer.type.modelProperties, suggestionGroups: { required: true, serializedName: "suggestionGroups", type: { name: "Sequence", element: { type: { name: "Composite", className: "SuggestionsSuggestionGroup" } } } } } } }; export const QueryContext: msRest.CompositeMapper = { serializedName: "QueryContext", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "QueryContext", className: "QueryContext", modelProperties: { originalQuery: { required: true, serializedName: "originalQuery", type: { name: "String" } }, alteredQuery: { readOnly: true, serializedName: "alteredQuery", type: { name: "String" } }, alterationOverrideQuery: { readOnly: true, serializedName: "alterationOverrideQuery", type: { name: "String" } }, adultIntent: { readOnly: true, serializedName: "adultIntent", type: { name: "Boolean" } }, askUserForLocation: { readOnly: true, serializedName: "askUserForLocation", type: { name: "Boolean" } }, isTransactional: { readOnly: true, serializedName: "isTransactional", type: { name: "Boolean" } }, _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const ErrorModel: msRest.CompositeMapper = { serializedName: "Error", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "_type", clientName: "_type" }, uberParent: "ErrorModel", className: "ErrorModel", modelProperties: { code: { required: true, serializedName: "code", defaultValue: 'None', type: { name: "String" } }, message: { required: true, serializedName: "message", type: { name: "String" } }, moreDetails: { readOnly: true, serializedName: "moreDetails", type: { name: "String" } }, parameter: { readOnly: true, serializedName: "parameter", type: { name: "String" } }, value: { readOnly: true, serializedName: "value", type: { name: "String" } }, _type: { required: true, serializedName: "_type", type: { name: "String" } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", polymorphicDiscriminator: ResponseBase.type.polymorphicDiscriminator, uberParent: "ResponseBase", className: "ErrorResponse", modelProperties: { ...Response.type.modelProperties, errors: { required: true, serializedName: "errors", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorModel" } } } } } } }; export const discriminators = { 'ResponseBase.SearchAction' : SearchAction, 'Suggestions/SuggestionGroup' : SuggestionsSuggestionGroup, 'ResponseBase.Suggestions' : Suggestions, 'QueryContext' : QueryContext, 'ResponseBase.SearchResultsAnswer' : SearchResultsAnswer, 'ResponseBase.Answer' : Answer, 'ResponseBase.Thing' : Thing, 'ResponseBase.Action' : Action, 'ResponseBase.Response' : Response, 'ResponseBase.Identifiable' : Identifiable, 'Error' : ErrorModel, 'ResponseBase.ErrorResponse' : ErrorResponse, 'ResponseBase.CreativeWork' : CreativeWork, 'ResponseBase' : ResponseBase };
the_stack
import { notP } from "../../../Data/Bool" import { equals, notEquals } from "../../../Data/Eq" import { cnst, ident } from "../../../Data/Function" import { fmap, fmapF, mapReplace } from "../../../Data/Functor" import { over, set } from "../../../Data/Lens" import { consF, countWith, elem, elemF, filter, find, flength, fnull, foldr, isList, List, map, mapByIdKeyMap, notElem, notElemF, notNull, nub, subscript } from "../../../Data/List" import { all, ap, bind, bindF, ensure, fromJust, fromMaybe, guard, isJust, isNothing, join, Just, liftM2, listToMaybe, Maybe, maybe, maybeToList, Nothing, or, thenF } from "../../../Data/Maybe" import { add, gt, gte, inc, multiply } from "../../../Data/Num" import { alter, elems, foldrWithKey, isOrderedMap, lookup, lookupF, member, OrderedMap } from "../../../Data/OrderedMap" import { Record, RecordI } from "../../../Data/Record" import { filterMapListT, filterT, mapT } from "../../../Data/Transducer" import { Tuple } from "../../../Data/Tuple" import { traceShowId } from "../../../Debug/Trace" import { Aspect, CombatTechniqueGroupId, MagicalTradition, SkillGroup, SpecialAbilityGroup } from "../../Constants/Groups" import { AdvantageId, DisadvantageId, SkillId, SpecialAbilityId } from "../../Constants/Ids.gen" import { ActivatableDependent } from "../../Models/ActiveEntries/ActivatableDependent" import { ActivatableSkillDependent } from "../../Models/ActiveEntries/ActivatableSkillDependent" import { ActiveObject } from "../../Models/ActiveEntries/ActiveObject" import { SkillDependent } from "../../Models/ActiveEntries/SkillDependent" import { HeroModel, HeroModelRecord } from "../../Models/Hero/HeroModel" import { Pact } from "../../Models/Hero/Pact" import { Rules } from "../../Models/Hero/Rules" import { AdventurePointsCategories } from "../../Models/View/AdventurePointsCategories" import { InactiveActivatable, InactiveActivatableL } from "../../Models/View/InactiveActivatable" import { Advantage } from "../../Models/Wiki/Advantage" import { LiturgicalChant } from "../../Models/Wiki/LiturgicalChant" import { Skill } from "../../Models/Wiki/Skill" import { Spell } from "../../Models/Wiki/Spell" import { Application } from "../../Models/Wiki/sub/Application" import { SelectOption, SelectOptionL } from "../../Models/Wiki/sub/SelectOption" import { StaticData, StaticDataRecord } from "../../Models/Wiki/WikiModel" import { Activatable } from "../../Models/Wiki/wikiTypeHelpers" import { composeT } from "../compose" import { filterUnfamiliar } from "../Dependencies/TransferredUnfamiliarUtils" import { countActiveGroupEntries } from "../entryGroupUtils" import { getAllEntriesByGroup } from "../heroStateUtils" import { prefixSA } from "../IDUtils" import { getTraditionOfAspect } from "../Increasable/liturgicalChantUtils" import { isUnfamiliarSpell } from "../Increasable/spellUtils" import { pipe, pipe_ } from "../pipe" import { validateLevel, validatePrerequisites } from "../Prerequisites/validatePrerequisitesUtils" import { isEntryAvailable } from "../RulesUtils" import { sortRecordsByName } from "../sortBy" import { isNumber, isString, isStringM, misNumberM, misStringM } from "../typeCheckUtils" import { getMaxLevelForDecreaseEntry, getSermonsAndVisionsCount } from "./activatableActiveValidationUtils" import { isAdditionDisabled } from "./activatableInactiveValidationUtils" import { modifyByLevel } from "./activatableModifierUtils" import { countActiveSkillEntries } from "./activatableSkillUtils" import { isMaybeActive } from "./isActive" import { getActiveSecondarySelections, getActiveSelections, getActiveSelectionsMaybe, getRequiredSelections } from "./selectionUtils" import { getBlessedTradition, getMagicalTraditionsHeroEntries, mapBlessedNumIdToTradId } from "./traditionUtils" const SDA = StaticData.A const HA = HeroModel.A const AAL = Advantage.AL const LCA = LiturgicalChant.A const SpA = Spell.A const ADA = ActivatableDependent.A const ASDA = ActivatableSkillDependent.A const SkDA = SkillDependent.A const SOA = SelectOption.A const AppA = Application.A const AOA = ActiveObject.A const SpAL = Spell.AL const SA = Skill.A const RA = Rules.A const SOL = SelectOptionL const IAA = InactiveActivatable.A const IAL = InactiveActivatableL const PA = Pact.A const APCA = AdventurePointsCategories.A /** * `isNotActive :: Maybe ActivatableDependent -> SelectOption -> Bool` * * Test if the id of the passed select option is activated for the passed * `ActivatableDependent`. */ const isNotActive = pipe ( getActiveSelectionsMaybe, fromMaybe<List<string | number>> (List.empty), activeSelections => pipe ( SOA.id, notElemF (activeSelections) ) ) /** * `areNoSameActive :: Maybe ActivatableDependent -> SelectOption -> Bool` * * Test if a select option is not activated more than once for the passed * `ActivatableDependent`. */ const areNoSameActive = pipe ( getActiveSelectionsMaybe, fromMaybe<List<string | number>> (List.empty), activeSelections => pipe ( SOA.id, current_id => countWith (equals (current_id)) (activeSelections) < 2 ) ) /** * `isNotRequired :: Maybe ActivatableDependent -> SelectOption -> Bool` * * Test if the id of the passed select option is required for the passed * `ActivatableDependent`. */ const isNotRequired = pipe ( getRequiredSelections, fromMaybe<List<string | number | List<number>>> (List.empty), requiredSelections => pipe ( SOA.id, notElemF (requiredSelections) ) ) /** * `isNotRequiredNotActive :: Maybe ActivatableDependent -> SelectOption -> Bool` * * Test if the id of the passed select option is neither required nor activated * for the passed `ActivatableDependent`. */ const isNotRequiredNotActive = (mhero_entry: Maybe<Record<ActivatableDependent>>) => { const isNoActiveSelection = isNotActive (mhero_entry) const isNoRequiredSelection = isNotRequired (mhero_entry) return (e: Record<SelectOption>) => isNoActiveSelection (e) && isNoRequiredSelection (e) } /** * Increment the value at the specified key by `1`. If there is no value at that * key, the value will be set to `0`. */ const incMapVal = alter (pipe (maybe (1) (inc), Just)) const addChantToCounter = (chant: Record<LiturgicalChant>) => (mp: OrderedMap<number, number>) => foldr ((aspect: Aspect) => OrderedMap.insertWith (add) <number> (aspect) (1)) (mp) (LCA.aspects (chant)) const addSpellToCounter = pipe (SpA.property, incMapVal) const filterSkillsGte10 = filter (pipe (ASDA.value, gte (10))) const foldCounter = foldrWithKey<number, number, List<number>> (k => x => x >= 3 ? consF (k) : ident) (List.empty) /** * `getPropsWith3Gte10 :: Wiki -> Hero -> [Int]` * * Returns a list containing all properties where at least 3 spells with at * least SR 10 belong to. */ const getPropsWith3Gte10 = (staticData: StaticDataRecord) => pipe ( HA.spells, elems, filterSkillsGte10, mapByIdKeyMap (SDA.spells (staticData)), foldr (addSpellToCounter) (OrderedMap.empty), foldCounter ) /** * `getAspectsWith3Gte10 :: Wiki -> Hero -> [Int]` * * Returns a list containing all aspects where at least 3 chants with at least * SR 10 belong to. */ const getAspectsWith3Gte10 = (staticData: StaticDataRecord) => pipe ( HA.liturgicalChants, elems, filterSkillsGte10, traceShowId, mapByIdKeyMap (SDA.liturgicalChants (staticData)), traceShowId, foldr (addChantToCounter) (OrderedMap.empty), traceShowId, OrderedMap.foldrWithKey ((k: number) => (x: number) => (xs: List<number>) => x >= 3 ? consF (k) (xs) : xs) (List.empty), traceShowId, ) const isSocialSkill = (staticData: StaticDataRecord) => pipe ( SOA.id, ensure (isString), bindF (lookupF (SDA.skills (staticData))), fmap (pipe (SA.gr, equals (SkillGroup.Social))), or ) const isAddExistSkillSpecAllowed = (hero: HeroModelRecord) => (counter: OrderedMap<string | number, List<string | number>>) => (curr_select_id: string | number) => pipe_ ( curr_select_id, ensure (isString), bindF (lookupF (HA.skills (hero))), liftM2 ((apps: List<string | number>) => (skill: Record<SkillDependent>) => flength (apps) < 3 && SkDA.value (skill) >= (flength (apps) + 1) * 6) (lookupF (counter) (curr_select_id)), or ) const isAddNotExistSkillSpecAllowed = (hero: HeroModelRecord) => (curr_select_id: string | number) => pipe_ ( curr_select_id, ensure (isString), bindF (lookupF (HA.skills (hero))), fmap (skill => SkDA.value (skill) >= 6), or ) const is3or4 = (x: string | number): x is number => x === 3 || x === 4 /** * Modifies the select options of specific entries to match current conditions. */ const modifySelectOptions = (staticData: StaticDataRecord) => (hero: HeroModelRecord) => (hero_magical_traditions: List<Record<ActivatableDependent>>) => (wiki_entry: Activatable) => (mhero_entry: Maybe<Record<ActivatableDependent>>): ident<Maybe<List<Record<SelectOption>>>> => { const current_id = AAL.id (wiki_entry) const isAvailable = composeT ( filterT (isEntryAvailable (SDA.books (staticData)) (RA.enabledRuleBooks (HA.rules (hero))) (RA.enableAllRuleBooks (HA.rules (hero))) (SOA.src)), filterT (pipe ( SOA.prerequisites, Maybe.all (reqs => validatePrerequisites (staticData) (hero) (reqs) (current_id)) )) ) const isNoRequiredOrActiveSelection = composeT (isAvailable, filterT (isNotRequiredNotActive (mhero_entry))) const isNoRequiredSelection = composeT (isAvailable, filterT (isNotRequired (mhero_entry))) switch (current_id) { case AdvantageId.exceptionalSkill: { const hasLessThanTwoSameIdActiveSelections = filterT (areNoSameActive (mhero_entry)) return fmap (filterMapListT (composeT ( isNoRequiredSelection, hasLessThanTwoSameIdActiveSelections ))) } case DisadvantageId.personalityFlaw: { const unique_selections = maybe (List<number> ()) (pipe ( getActiveSelections, filter (isNumber), nub )) (mhero_entry) const isInfiniteActive: (id: number) => (x: Record<SelectOption>) => boolean = id => x => SOA.id (x) === id && elem (id) (unique_selections) const isPrejudiceAndActive = isInfiniteActive (7) const isUnworldlyAndActive = isInfiniteActive (8) const isNotActiveAndMaxNotReached: (x: Record<SelectOption>) => boolean = x => isNotActive (mhero_entry) (x) && isNotRequired (mhero_entry) (x) && flength (unique_selections) < 2 const filterOptions = composeT ( isAvailable, filterT (a => isPrejudiceAndActive (a) || isUnworldlyAndActive (a) || isNotActiveAndMaxNotReached (a)) ) return fmap (filterMapListT (filterOptions)) } case DisadvantageId.negativeTrait: case DisadvantageId.maimed: return fmap (filterMapListT (isNoRequiredOrActiveSelection)) case DisadvantageId.incompetent: { const isAdvActive = pipe (lookupF (HA.advantages (hero)), isMaybeActive) const isNotSocialSkill = notP (isSocialSkill (staticData)) return fmap (filterMapListT (composeT ( isNoRequiredOrActiveSelection, filterT (e => // Socially Adaptable and Inspire Confidence // require no Incompetence in social skills (isAdvActive (AdvantageId.sociallyAdaptable) || isAdvActive (AdvantageId.inspireConfidence) ? isNotSocialSkill (e) : true)) ))) } case SpecialAbilityId.skillSpecialization: { const mcounter = getActiveSecondarySelections (mhero_entry) return fmap (filterMapListT (composeT ( isNoRequiredSelection, filterT (e => { const curr_select_id = SOA.id (e) // if mcounter is available, mhero_entry must be a Just and thus // there can be active selections if (isJust (mcounter)) { const counter = fromJust (mcounter) if (member (curr_select_id) (counter)) { return isAddExistSkillSpecAllowed (hero) (counter) (curr_select_id) } } // otherwise we only need to check if the skill rating is at // least 6, as there can't be an activated selection. return isAddNotExistSkillSpecAllowed (hero) (curr_select_id) }), mapT (e => { const curr_select_id = SOA.id (e) const mcounts = bind (mcounter) (lookup (curr_select_id)) const adjustSelectOption = pipe ( over (SOL.cost) (isJust (mcounts) // Increase cost if there are active specializations // for the same skill ? fmap (multiply (flength (fromJust (mcounts)) + 1)) // otherwise return current cost : ident), over (SOL.applications) (fmap (filter (app => { const isInactive = all (notElem<number | string> (AppA.id (app))) (mcounts) const arePrerequisitesMet = validatePrerequisites (staticData) (hero) (maybeToList (AppA.prerequisite (app))) (current_id) return isInactive && arePrerequisitesMet }))) ) return adjustSelectOption (e) }) ))) } case prefixSA (SpecialAbilityId.traditionGuildMages): { return fmap (filterUnfamiliar (pipe ( SpA.tradition, trads => notElem (MagicalTradition.General) (trads) && notElem (MagicalTradition.GuildMages) (trads) )) (staticData)) } case SpecialAbilityId.propertyKnowledge: { const isValidProperty = filterT (pipe (SOA.id, elemF<string | number> (getPropsWith3Gte10 (staticData) (hero)))) return fmap (filterMapListT (composeT ( isNoRequiredOrActiveSelection, isValidProperty ))) } case SpecialAbilityId.propertyFocus: { const isActivePropertyKnowledge = filterT (notP (pipe_ ( hero, HA.specialAbilities, lookup<string> (SpecialAbilityId.propertyKnowledge), isNotActive ))) return fmap (filterMapListT (composeT ( isNoRequiredOrActiveSelection, isActivePropertyKnowledge ))) } case SpecialAbilityId.aspectKnowledge: { const valid_aspects = getAspectsWith3Gte10 (staticData) (hero) traceShowId (valid_aspects) const isAspectValid = pipe (SOA.id, elemF<string | number> (valid_aspects)) return maybe (ident as ident<Maybe<List<Record<SelectOption>>>>) ((blessed_trad: Record<ActivatableDependent>) => fmap (filterMapListT (composeT ( filterT (pipe ( SOA.id, ensure (isNumber), bindF (pipe ( getTraditionOfAspect, mapBlessedNumIdToTradId )), Maybe.elem (AAL.id (blessed_trad)) )), isNoRequiredOrActiveSelection, filterT (isAspectValid) )))) (getBlessedTradition (HA.specialAbilities (hero))) } case SpecialAbilityId.adaptionZauber: { const isWikiEntryFromUnfamiliarTrad = isUnfamiliarSpell (HA.transferredUnfamiliarSpells (hero)) (hero_magical_traditions) const isSpellAbove10 = pipe ( SOA.id, ensure (isString), bindF (lookupF (HA.spells (hero))), maybe (false) (pipe (ASDA.value, gte (10))) ) const isFromUnfamiliarTrad = pipe ( SOA.id, ensure (isString), bindF (lookupF (SDA.spells (staticData))), maybe (false) (isWikiEntryFromUnfamiliarTrad) ) return fmap (filterMapListT (composeT ( isNoRequiredOrActiveSelection, filterT (isSpellAbove10), filterT (isFromUnfamiliarTrad) ))) } case prefixSA (SpecialAbilityId.spellEnhancement): case prefixSA (SpecialAbilityId.chantEnhancement): { const getTargetHeroEntry = current_id === prefixSA (SpecialAbilityId.spellEnhancement) ? bindF (lookupF (HA.spells (hero))) : bindF (lookupF (HA.liturgicalChants (hero))) const getTargetWikiEntry: ((x: Maybe<string>) => Maybe<Record<Spell> | Record<LiturgicalChant>>) = current_id === prefixSA (SpecialAbilityId.spellEnhancement) ? bindF (lookupF (SDA.spells (staticData))) : bindF (lookupF (SDA.liturgicalChants (staticData))) const isNotUnfamiliar = (x: Record<Spell> | Record<LiturgicalChant>) => LiturgicalChant.is (x) || !isUnfamiliarSpell (HA.transferredUnfamiliarSpells (hero)) (hero_magical_traditions) (x) return fmap (foldr (isNoRequiredOrActiveSelection (e => { const mtarget_hero_entry = getTargetHeroEntry (SOA.target (e)) const mtarget_wiki_entry = getTargetWikiEntry (SOA.target (e)) if ( isJust (mtarget_wiki_entry) && isJust (mtarget_hero_entry) && isNotUnfamiliar (fromJust (mtarget_wiki_entry)) && ASDA.value (fromJust (mtarget_hero_entry)) >= maybe (0) (pipe (multiply (4), add (4))) (SOA.level (e)) ) { const target_wiki_entry = fromJust (mtarget_wiki_entry) return consF ( set (SOL.name) (`${SpAL.name (target_wiki_entry)}: ${SOA.name (e)}`) (e) ) } return ident as ident<List<Record<SelectOption>>> })) (List ())) } case SpecialAbilityId.languageSpecializations: { return pipe_ ( staticData, SDA.specialAbilities, lookup<string> (SpecialAbilityId.language), bindF (AAL.select), maybe (cnst (Nothing) as ident<Maybe<List<Record<SelectOption>>>>) (current_select => { const available_langs = // Pair: fst = sid, snd = current_level maybe (List<number> ()) (pipe ( ADA.active, foldr ((obj: Record<ActiveObject>) => pipe_ ( obj, AOA.tier, bindF (current_level => pipe_ ( guard (is3or4 (current_level)), thenF (AOA.sid (obj)), misNumberM, fmap (consF) )), fromMaybe ( ident as ident<List<number>> ) )) (List ()) )) (pipe_ ( hero, HA.specialAbilities, lookup<string> (SpecialAbilityId.language) )) const filterLanguages = foldr (isNoRequiredSelection (e => { const lang = find ((l: number) => l === SOA.id (e)) (available_langs) // a language must provide either a set of // possible specializations or an input where a // custom specialization can be entered. const provides_specific_or_input = Maybe.any (notNull) (SOA.specializations (e)) || isJust (SOA.specializationInput (e)) if (isJust (lang) && provides_specific_or_input) { return consF (e) } return ident as ident<List<Record<SelectOption>>> })) (List ()) return cnst (Just (filterLanguages (current_select))) }) ) } case SpecialAbilityId.madaschwesternStil: { return fmap (filterUnfamiliar (pipe ( SpA.tradition, trads => notElem (MagicalTradition.General) (trads) && notElem (MagicalTradition.Witches) (trads) )) (staticData)) } case SpecialAbilityId.scholarDesMagierkollegsZuHoningen: { const allowed_traditions = List ( MagicalTradition.Druids, MagicalTradition.Elves, MagicalTradition.Witches ) const mtransferred_spell_trads = pipe_ ( HA.specialAbilities (hero), lookup (prefixSA (SpecialAbilityId.traditionGuildMages)), bindF (pipe (ADA.active, listToMaybe)), bindF (pipe (AOA.sid, isStringM)), bindF (lookupF (SDA.spells (staticData))), fmap (SpA.tradition) ) if (isNothing (mtransferred_spell_trads)) { return ident } const transferred_spell_trads = fromJust (mtransferred_spell_trads) // Contains all allowed trads the first spell does not have const trad_diff = filter (notElemF (transferred_spell_trads)) (allowed_traditions) const has_transferred_all_traditions_allowed = fnull (trad_diff) return fmap (filterUnfamiliar (pipe ( SpA.tradition, has_transferred_all_traditions_allowed ? trads => notElem (MagicalTradition.General) (trads) && List.any (elemF (allowed_traditions)) (trads) : trads => notElem (MagicalTradition.General) (trads) && List.any (elemF (trad_diff)) (trads) )) (staticData)) } default: return fmap (filterMapListT (isNoRequiredOrActiveSelection)) } } type OtherOptionsModifier = ident<Record<InactiveActivatable>> const getSermonOrVisionCountMax = (hero: HeroModelRecord) => (adv_id: string) => (disadv_id: string) => modifyByLevel (3) (lookup (adv_id) (HA.advantages (hero))) (lookup (disadv_id) (HA.disadvantages (hero))) const modifyOtherOptions = (wiki: StaticDataRecord) => (hero: HeroModelRecord) => (adventure_points: Record<AdventurePointsCategories>) => (wiki_entry: Activatable) => (mhero_entry: Maybe<Record<ActivatableDependent>>): Maybe<OtherOptionsModifier> => { const current_id = AAL.id (wiki_entry) switch (current_id) { case DisadvantageId.wenigePredigten: return pipe_ ( SpecialAbilityGroup.Predigten, getSermonsAndVisionsCount (wiki) (hero), getMaxLevelForDecreaseEntry (3), set (IAL.maxLevel), Just ) case DisadvantageId.wenigeVisionen: return pipe_ ( SpecialAbilityGroup.Visionen, getSermonsAndVisionsCount (wiki) (hero), getMaxLevelForDecreaseEntry (3), set (IAL.maxLevel), Just ) case DisadvantageId.smallSpellSelection: { return pipe_ ( hero, countActiveSkillEntries ("spells"), getMaxLevelForDecreaseEntry (3), set (IAL.maxLevel), Just ) } case SpecialAbilityId.craftInstruments: { return join (liftM2 ( (woodworking: Record<SkillDependent>) => (metalworking: Record<SkillDependent>) => SkDA.value (woodworking) + SkDA.value (metalworking) >= 12 ? Just (ident) : Nothing ) (pipe (HA.skills, lookup<string> (SkillId.woodworking)) (hero)) (pipe (HA.skills, lookup<string> (SkillId.metalworking)) (hero))) } case SpecialAbilityId.hunter: { return pipe_ ( CombatTechniqueGroupId.Ranged, getAllEntriesByGroup (SDA.combatTechniques (wiki)) (HA.combatTechniques (hero)), filter (pipe (SkDA.value, gte (10))), flength, ensure (gt (0)), mapReplace (ident) ) } case prefixSA (SpecialAbilityId.traditionGuildMages): case SpecialAbilityId.traditionWitches: case SpecialAbilityId.traditionElves: case SpecialAbilityId.traditionDruids: case SpecialAbilityId.traditionIllusionist: case SpecialAbilityId.traditionQabalyaMage: case SpecialAbilityId.traditionGeoden: case SpecialAbilityId.traditionZauberalchimisten: case SpecialAbilityId.traditionSchelme: case SpecialAbilityId.traditionBrobimGeoden: { return pipe_ ( hero, HA.specialAbilities, getMagicalTraditionsHeroEntries, ensure (List.fnull), mapReplace (ident) ) } case SpecialAbilityId.propertyKnowledge: case SpecialAbilityId.aspectKnowledge: { return pipe_ ( wiki_entry, AAL.cost, bindF<number | List<number>, List<number>> (ensure (isList)), bindF (costs => subscript (costs) (maybe (0) (pipe (ADA.active, flength)) (mhero_entry))), fmap (pipe (Just, set (IAL.cost))) ) } case SpecialAbilityId.traditionChurchOfPraios: case SpecialAbilityId.traditionChurchOfRondra: case SpecialAbilityId.traditionChurchOfBoron: case SpecialAbilityId.traditionChurchOfHesinde: case SpecialAbilityId.traditionChurchOfPhex: case SpecialAbilityId.traditionChurchOfPeraine: case SpecialAbilityId.traditionChurchOfEfferd: case SpecialAbilityId.traditionChurchOfTravia: case SpecialAbilityId.traditionChurchOfFirun: case SpecialAbilityId.traditionChurchOfTsa: case SpecialAbilityId.traditionChurchOfIngerimm: case SpecialAbilityId.traditionChurchOfRahja: case SpecialAbilityId.traditionCultOfTheNamelessOne: case SpecialAbilityId.traditionChurchOfAves: case SpecialAbilityId.traditionChurchOfIfirn: case SpecialAbilityId.traditionChurchOfKor: case SpecialAbilityId.traditionChurchOfNandus: case SpecialAbilityId.traditionChurchOfSwafnir: case SpecialAbilityId.traditionCultOfNuminoru: { return pipe_ ( hero, HA.specialAbilities, getBlessedTradition, x => isJust (x) ? Nothing : Just (ident) ) } case SpecialAbilityId.recherchegespuer: { return pipe_ ( hero, HA.specialAbilities, lookup<string> (SpecialAbilityId.wissensdurst), fmap (ADA.active), bindF (listToMaybe), bindF (AOA.sid), misStringM, bindF (lookupF (SDA.skills (wiki))), bindF (skill => pipe ( bindF<number | List<number>, List<number>> (ensure (isList)), fmap (pipe ( map (add (SA.ic (skill))), Just, set (IAL.cost) )) ) (AAL.cost (wiki_entry))) ) } case SpecialAbilityId.predigtDerGemeinschaft: case SpecialAbilityId.predigtDerZuversicht: case SpecialAbilityId.predigtDesGottvertrauens: case SpecialAbilityId.predigtDesWohlgefallens: case SpecialAbilityId.predigtWiderMissgeschicke: { const isAdvActive = pipe (lookupF (HA.advantages (hero)), isMaybeActive) const max = getSermonOrVisionCountMax (hero) (AdvantageId.zahlreichePredigten) (DisadvantageId.wenigePredigten) const isLessThanMax = countActiveGroupEntries (wiki) (hero) (SpecialAbilityGroup.Predigten) < max return (isAdvActive (AdvantageId.prediger) && isLessThanMax) || isAdvActive (AdvantageId.blessed) ? Just (ident) : Nothing } case SpecialAbilityId.visionDerBestimmung: case SpecialAbilityId.visionDerEntrueckung: case SpecialAbilityId.visionDerGottheit: case SpecialAbilityId.visionDesSchicksals: case SpecialAbilityId.visionDesWahrenGlaubens: { const isAdvActive = pipe (lookupF (HA.advantages (hero)), isMaybeActive) const max = getSermonOrVisionCountMax (hero) (AdvantageId.zahlreicheVisionen) (DisadvantageId.wenigeVisionen) const isLessThanMax = countActiveGroupEntries (wiki) (hero) (SpecialAbilityGroup.Visionen) < max return (isAdvActive (AdvantageId.visionaer) && isLessThanMax) || isAdvActive (AdvantageId.blessed) ? Just (ident) : Nothing } case SpecialAbilityId.dunklesAbbildDerBuendnisgabe: { return pipe_ ( hero, HA.pact, fmap (pipe (PA.level, Just, set (IAL.maxLevel))) ) } case SpecialAbilityId.traditionArcaneBard: case SpecialAbilityId.traditionArcaneDancer: case SpecialAbilityId.traditionIntuitiveMage: case SpecialAbilityId.traditionSavant: case SpecialAbilityId.traditionAnimisten: { return APCA.spentOnMagicalAdvantages (adventure_points) <= 25 && APCA.spentOnMagicalDisadvantages (adventure_points) <= 25 && pipe_ ( hero, HA.specialAbilities, getMagicalTraditionsHeroEntries, fnull ) ? Just (ident) : Nothing } default: return Just (ident) } } /** * Calculates whether an Activatable is valid to add or not and, if valid, * calculates and filters necessary properties and selection lists. Returns a * Maybe of the result or `undefined` if invalid. */ export const getInactiveView = (staticData: StaticDataRecord) => (hero: HeroModelRecord) => (automatic_advantages: List<string>) => (required_apply_to_mag_actions: boolean) => (matching_script_and_lang_related: Tuple<[boolean, List<number>, List<number>]>) => (adventure_points: Record<AdventurePointsCategories>) => (validExtendedSpecialAbilities: List<string>) => (hero_magical_traditions: List<Record<ActivatableDependent>>) => (wiki_entry: Activatable) => (mhero_entry: Maybe<Record<ActivatableDependent>>): Maybe<Record<InactiveActivatable>> => { const current_id = AAL.id (wiki_entry) const current_prerequisites = AAL.prerequisites (wiki_entry) const max_level = isOrderedMap (current_prerequisites) ? validateLevel (staticData) (hero) (current_prerequisites) (maybe<ActivatableDependent["dependencies"]> (List ()) (ADA.dependencies) (mhero_entry)) (current_id) : Nothing const isNotValid = isAdditionDisabled (staticData) (hero) (required_apply_to_mag_actions) (validExtendedSpecialAbilities) (matching_script_and_lang_related) (wiki_entry) (mhero_entry) (max_level) if (!isNotValid) { return pipe_ ( wiki_entry, AAL.select, modifySelectOptions (staticData) (hero) (hero_magical_traditions) (wiki_entry) (mhero_entry), ensure (maybe (true) (notNull)), fmap (select_options => InactiveActivatable ({ id: current_id, name: SpAL.name (wiki_entry), cost: AAL.cost (wiki_entry), maxLevel: max_level, heroEntry: mhero_entry, wikiEntry: wiki_entry as Record<RecordI<Activatable>>, selectOptions: fmapF (select_options) (sortRecordsByName (staticData)), isAutomatic: List.elem (AAL.id (wiki_entry)) (automatic_advantages), })), ap (modifyOtherOptions (staticData) (hero) (adventure_points) (wiki_entry) (mhero_entry)), bindF (ensure (pipe (IAA.maxLevel, maybe (true) (notEquals (0))))) ) } return Nothing }
the_stack
import {Component, DebugElement, Provider, ViewChild} from '@angular/core'; import {async, ComponentFixture, fakeAsync, TestBed, flush, tick} from '@angular/core/testing'; import {FormsModule} from '@angular/forms'; import {By} from '@angular/platform-browser'; import {Platform} from '@angular/cdk/platform'; import { dispatchFakeEvent, dispatchTouchEvent, dispatchMouseEvent } from '@angular-mdc/web/testing'; import { MdcTextField, MdcTextFieldModule, MDC_TEXT_FIELD_DEFAULT_OPTIONS, } from './index'; import {MdcIconModule} from '@angular-mdc/web/icon'; function configureMdcTestingModule(declarations: any[], providers: Provider[] = []) { let platform: {isBrowser: boolean}; // Set the default Platform override that can be updated before component creation. platform = {isBrowser: true}; TestBed.configureTestingModule({ imports: [ MdcTextFieldModule, MdcIconModule, FormsModule, ], declarations: declarations, providers: [ {provide: Platform, useFactory: () => platform}, ...providers ], }).compileComponents(); } describe('MdcTextField', () => { let fixture: ComponentFixture<any>; let platform: {isBrowser: boolean}; beforeEach(async(() => { configureMdcTestingModule([ SimpleTextfield, TextFieldTestWithValue, TextFieldWithIcons, DefaultTextField ]); })); describe('Tests for SSR', () => { let testDebugElement: DebugElement; let testInstance: MdcTextField; let testComponent: SimpleTextfield; beforeEach(() => { // Set the default Platform override that can be updated before component creation. platform = {isBrowser: false}; fixture = TestBed.createComponent(SimpleTextfield); fixture.detectChanges(); testDebugElement = fixture.debugElement.query(By.directive(MdcTextField)); testInstance = testDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; }); it('#should have mdc-text-field by default', () => { expect(testDebugElement.nativeElement.classList) .toContain('mdc-text-field', 'Expected to have mdc-text-field'); }); }); describe('basic behaviors', () => { let textFieldDebugElement: DebugElement; let textFieldNativeElement: HTMLElement; let testInstance: MdcTextField; let testComponent: SimpleTextfield; beforeEach(() => { fixture = TestBed.createComponent(SimpleTextfield); fixture.detectChanges(); textFieldDebugElement = fixture.debugElement.query(By.directive(MdcTextField)); textFieldNativeElement = textFieldDebugElement.nativeElement; testInstance = textFieldDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; }); it('#should have mdc-text-field by default', () => { expect(textFieldDebugElement.nativeElement.classList) .toContain('mdc-text-field', 'Expected to have mdc-text-field class'); }); it('#should apply class fullwidth on property', fakeAsync(() => { testComponent.isFullwidth = true; fixture.detectChanges(); flush(); expect(textFieldDebugElement.nativeElement.classList.contains('mdc-text-field--fullwidth')).toBe(true); })); it('#should apply class outlined', fakeAsync(() => { testComponent.outlined = true; fixture.detectChanges(); flush(); expect(textFieldDebugElement.nativeElement.classList.contains('mdc-text-field--outlined')).toBe(true); })); it('#should apply class outlined and not set it again', fakeAsync(() => { testComponent.outlined = true; fixture.detectChanges(); flush(); expect(textFieldDebugElement.nativeElement.classList.contains('mdc-text-field--outlined')).toBe(true); testComponent.outlined = true; fixture.detectChanges(); expect(textFieldDebugElement.nativeElement.classList.contains('mdc-text-field--outlined')).toBe(true); })); it('#should not be disabled', fakeAsync(() => { expect(testInstance.disabled).toBeFalsy(); })); it('#should be disabled', fakeAsync(() => { testComponent.disabled = true; fixture.detectChanges(); flush(); expect(testInstance.disabled).toBe(true); })); it('#should not be read only', fakeAsync(() => { expect(testInstance.readonly).toBeFalsy(); })); it('#should be read only', fakeAsync(() => { testComponent.readonly = true; fixture.detectChanges(); flush(); expect(testInstance.readonly).toBe(true); })); it('#should set validity based on input element validity', fakeAsync(() => { testInstance.valid = true; testInstance.valid = true; // check to ensure it doesn't run change again fixture.detectChanges(); flush(); expect(testInstance.valid).toBe(true); })); it('#should set required to true', fakeAsync(() => { testComponent.required = true; fixture.detectChanges(); flush(); expect(testInstance.required).toBe(true); })); it('#should set required to true and valid to true', fakeAsync(() => { testInstance.valid = true; fixture.detectChanges(); testComponent.required = true; fixture.detectChanges(); expect(testInstance.required).toBe(true); })); it('#should set useNativeValidation to true', fakeAsync(() => { testComponent.useNativeValidation = true; testInstance.useNativeValidation = true; // check to ensure it doesn't run change again fixture.detectChanges(); flush(); expect(testInstance.useNativeValidation).toBe(true); expect(testInstance.isBadInput()).toBe(false); })); it('#should focus on underlying input element when focus() is called', fakeAsync(() => { testComponent.outlined = true; fixture.detectChanges(); expect(document.activeElement).not.toBe(testInstance._input.nativeElement); testInstance.focus(); fixture.detectChanges(); flush(); expect(document.activeElement).toBe(testInstance._input.nativeElement); })); it('change type', fakeAsync(() => { testComponent.myType = ''; fixture.detectChanges(); flush(); expect(testInstance.type).toBe('text'); })); it('add inputmode', fakeAsync(() => { testComponent.inputMode = 'tel'; fixture.detectChanges(); flush(); expect(testInstance.inputmode).toBe('tel'); })); it('handles blur event', fakeAsync(() => { textFieldNativeElement.blur(); fixture.detectChanges(); })); it('handles focus event', fakeAsync(() => { textFieldNativeElement.focus(); fixture.detectChanges(); })); it('handles click event', fakeAsync(() => { textFieldNativeElement.click(); fixture.detectChanges(); })); it('handles animationend event', fakeAsync(() => { dispatchFakeEvent(testInstance._floatingLabel!.elementRef.nativeElement, 'animationend'); })); it('handles transitionend event', fakeAsync(() => { testComponent.outlined = false; fixture.detectChanges(); flush(); dispatchFakeEvent(testInstance._lineRipple!.elementRef.nativeElement, 'transitionend'); })); it('expect trailing icon to be defined', fakeAsync(() => { expect(testInstance.trailingIcon).toBeDefined(); })); }); describe('textfield with icons', () => { let textFieldDebugElement: DebugElement; let textFieldNativeElement: HTMLElement; let testInstance: MdcTextField; let testComponent: TextFieldWithIcons; beforeEach(() => { fixture = TestBed.createComponent(TextFieldWithIcons); fixture.detectChanges(); textFieldDebugElement = fixture.debugElement.query(By.directive(MdcTextField)); textFieldNativeElement = textFieldDebugElement.nativeElement; testInstance = textFieldDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; }); it('#should be disabled', () => { testComponent.disabled = true; fixture.detectChanges(); expect(testInstance.disabled).toBe(true); }); }); describe('basic behaviors', () => { let textFieldDebugElement: DebugElement; let textFieldNativeElement: HTMLElement; let testInstance: MdcTextField; let testComponent: TextFieldTestWithValue; beforeEach(() => { fixture = TestBed.createComponent(TextFieldTestWithValue); fixture.detectChanges(); textFieldDebugElement = fixture.debugElement.query(By.directive(MdcTextField)); textFieldNativeElement = textFieldDebugElement.nativeElement; testInstance = textFieldDebugElement.componentInstance; testComponent = fixture.debugElement.componentInstance; }); it('#should set value to foo', fakeAsync(() => { testInstance.value = 'foo'; fixture.detectChanges(); flush(); expect(testInstance.value).toBe('foo'); })); it('#should call OnInput', fakeAsync(() => { spyOn(testComponent, 'onInput'); textFieldDebugElement.nativeElement.value = 'text'; dispatchFakeEvent(textFieldNativeElement, 'input'); fixture.detectChanges(); expect(testComponent.onInput).toHaveBeenCalledTimes(1); })); it('#should handle touch event', fakeAsync(() => { testInstance._input.nativeElement.focus(); fixture.detectChanges(); dispatchTouchEvent(textFieldNativeElement, 'touchstart'); fixture.detectChanges(); tick(300); dispatchTouchEvent(textFieldNativeElement, 'touchstart'); dispatchMouseEvent(testInstance._input.nativeElement, 'mousedown'); dispatchMouseEvent(testInstance._input.nativeElement, 'mousedown'); fixture.detectChanges(); tick(300); document.body.focus(); fixture.detectChanges(); })); }); }); it('should be able to provide default values through an injection token', () => { configureMdcTestingModule([DefaultTextField], [{ provide: MDC_TEXT_FIELD_DEFAULT_OPTIONS, useValue: { outlined: true } }]); const fixture = TestBed.createComponent(DefaultTextField); fixture.detectChanges(); const textfield = fixture.componentInstance.textfield; expect(textfield.outlined).toBe(true); }); it('should be able to provide default values through an injection token', () => { configureMdcTestingModule([DefaultTextField], [{ provide: MDC_TEXT_FIELD_DEFAULT_OPTIONS, useValue: { outlined: null } }]); const fixture = TestBed.createComponent(DefaultTextField); fixture.detectChanges(); const textfield = fixture.componentInstance.textfield; expect(textfield.outlined).toBe(false); }); @Component({ template: ` <mdc-form-field> <mdc-text-field [(ngModel)]="myModel" label="Username" [type]="myType" [inputmode]="inputMode" [tabIndex]="1" [charCounter]="charCounter" [outlined]="outlined" [value]="value" [fullwidth]="isFullwidth" [required]="required" [readonly]="readonly" [disabled]="disabled" [useNativeValidation]="useNativeValidation" (input)="onInput($event)" (change)="onChange($event)" (blur)="onBlur($event)"> <mdc-icon mdcTextFieldIcon leading>person</mdc-icon> <mdc-icon mdcTextFieldIcon trailing>person</mdc-icon> </mdc-text-field> </mdc-form-field> `, }) class SimpleTextfield { myModel: string = 'Test'; myType: string = 'text'; inputMode?: string; disabled: boolean; isFullwidth: boolean; outlined: boolean; required: boolean; readonly: boolean; useNativeValidation: boolean = false; charCounter: boolean = true; onInput(value: any) {} onChange(value: any) {} onBlur(event: any) {} } @Component({ template: ` <mdc-text-field label="Username" (input)="onInput($event)" (change)="onChange($event)" [value]="value"> </mdc-text-field> `, }) class TextFieldTestWithValue { value: string = 'my-test'; onInput: (value: any) => void = () => {}; onChange(value: any) {} } @Component({ template: ` <mdc-text-field [disabled]="disabled" label="Textfield with icon"> <mdc-icon mdcTextFieldIcon leading>phone</mdc-icon> </mdc-text-field>`, }) class TextFieldWithIcons { disabled: boolean = false; } @Component({ selector: 'default-text-field', template: `<mdc-text-field label="Example"></mdc-text-field>` }) class DefaultTextField { @ViewChild(MdcTextField) textfield!: MdcTextField; }
the_stack
import ee from 'event-emitter'; import { AlfrescoApiClient } from '../alfrescoApiClient'; import { AlfrescoApiConfig } from '../alfrescoApiConfig'; import { Authentication } from './authentication'; import { AuthenticationApi } from '../api/auth-rest-api/api/authentication.api'; import { AlfrescoApi } from '../alfrescoApi'; import { Storage } from '../storage'; declare const Buffer: any; declare const require: any; // tslint:disable-next-line const minimatch = require('minimatch'); declare let window: Window; export class Oauth2Auth extends AlfrescoApiClient { static readonly DEFAULT_AUTHORIZATION_URL = '/protocol/openid-connect/auth'; static readonly DEFAULT_TOKEN_URL = '/protocol/openid-connect/token'; static readonly DEFAULT_LOGOUT_URL = '/protocol/openid-connect/logout'; private refreshTokenIntervalPolling: any; private refreshTokenTimeoutIframe: any; private checkAccessToken = true; storage: Storage; hashFragmentParams: any; token: string; discovery: { loginUrl?: string; logoutUrl?: string; tokenEndpoint?: string; } = {}; authentications: Authentication = { 'oauth2': { accessToken: '' }, type: 'oauth2', 'basicAuth': {} }; iFrameHashListener: any; constructor(config: AlfrescoApiConfig, alfrescoApi: AlfrescoApi) { super(); this.storage = new Storage(); this.storage.setDomainPrefix(config.domainPrefix); this.className = 'Oauth2Auth'; if (config) { this.setConfig(config, alfrescoApi); } } setConfig(config: AlfrescoApiConfig, alfrescoApi: AlfrescoApi) { this.config = config; if (this.config.oauth2) { if (this.config.oauth2.host === undefined || this.config.oauth2.host === null) { throw 'Missing the required oauth2 host parameter'; } if (this.config.oauth2.clientId === undefined || this.config.oauth2.clientId === null) { throw 'Missing the required oauth2 clientId parameter'; } if (this.config.oauth2.scope === undefined || this.config.oauth2.scope === null) { throw 'Missing the required oauth2 scope parameter'; } if (this.config.oauth2.secret === undefined || this.config.oauth2.secret === null) { this.config.oauth2.secret = ''; } if ((this.config.oauth2.redirectUri === undefined || this.config.oauth2.redirectUri === null) && this.config.oauth2.implicitFlow) { throw 'Missing redirectUri required parameter'; } if (!this.config.oauth2.refreshTokenTimeout) { this.config.oauth2.refreshTokenTimeout = 300000; } if (!this.config.oauth2.redirectSilentIframeUri) { let context = ''; if (typeof window !== 'undefined') { context = window.location.origin; } this.config.oauth2.redirectSilentIframeUri = context + '/assets/silent-refresh.html'; } this.basePath = this.config.oauth2.host; //Auth Call this.host = this.config.oauth2.host; this.discoveryUrls(); if (this.hasContentProvider()) { this.exchangeTicketListener(alfrescoApi); } this.initOauth(); } } initOauth() { if (!this.config.oauth2.implicitFlow && this.isValidAccessToken()) { const accessToken = this.storage.getItem('access_token'); this.setToken(accessToken, null); } if (this.config.oauth2.implicitFlow) { this.checkFragment('nonce'); } } discoveryUrls() { this.discovery.loginUrl = this.host + (this.config.oauth2.authorizationUrl || Oauth2Auth.DEFAULT_AUTHORIZATION_URL); this.discovery.logoutUrl = this.host + (this.config.oauth2.logoutUrl || Oauth2Auth.DEFAULT_LOGOUT_URL); this.discovery.tokenEndpoint = this.host + (this.config.oauth2.tokenUrl || Oauth2Auth.DEFAULT_TOKEN_URL); } hasContentProvider(): boolean { return this.config.provider === 'ECM' || this.config.provider === 'ALL'; } checkFragment(nonceKey?: string, externalHash?: any): any {// jshint ignore:line this.hashFragmentParams = this.getHashFragmentParams(externalHash); if (this.hashFragmentParams && this.hashFragmentParams.error === undefined) { this.useFragmentTimeLogin(nonceKey); } else { this.refreshBrowserLogin(); } } private refreshBrowserLogin() { if (this.config.oauth2.silentLogin && !this.isPublicUrl()) { this.implicitLogin(); } if (this.isValidToken() && this.isValidAccessToken()) { let accessToken = this.storage.getItem('access_token'); this.setToken(accessToken, null); this.silentRefresh(); } } private useFragmentTimeLogin(nonceKey: string) { let accessToken = this.hashFragmentParams.access_token; let idToken = this.hashFragmentParams.id_token; let sessionState = this.hashFragmentParams.session_state; let expiresIn = this.hashFragmentParams.expires_in; if (!sessionState) { throw('session state not present'); } try { const jwt = this.processJWTToken(idToken, nonceKey); if (jwt) { this.storeIdToken(idToken, jwt.payload.exp); this.storeAccessToken(accessToken, expiresIn); this.authentications.basicAuth.username = jwt.payload.preferred_username; this.saveUsername(jwt.payload.preferred_username); this.silentRefresh(); return accessToken; } } catch (error) { throw('Validation JWT error' + error); } } isPublicUrl(): boolean { const publicUrls = this.config.oauth2.publicUrls || []; if (Array.isArray(publicUrls)) { return publicUrls.length > 0 && publicUrls.some((urlPattern: string) => minimatch(window.location.href, urlPattern)); } return false; } padBase64(base64data: any) { while (base64data.length % 4 !== 0) { base64data += '='; } return base64data; } processJWTToken(jwt: any, nonceKey: string): any { if (jwt) { const jwtArray = jwt.split('.'); const headerBase64 = this.padBase64(jwtArray[0]); const headerJson = this.b64DecodeUnicode(headerBase64); const header = JSON.parse(headerJson); const payloadBase64 = this.padBase64(jwtArray[1]); const payloadJson = this.b64DecodeUnicode(payloadBase64); const payload = JSON.parse(payloadJson); const savedNonce = this.storage.getItem(nonceKey); if (!payload.sub) { throw('Missing sub in JWT'); } if (payload.nonce !== savedNonce) { console.log('Failing nonce JWT is not corresponding' + payload.nonce); return; } return { idToken: jwt, payload: payload, header: header }; } } b64DecodeUnicode(b64string: string) { const base64 = b64string.replace(/\-/g, '+').replace(/\_/g, '/'); return decodeURIComponent( atob(base64) .split('') .map((c) => { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }) .join('') ); } storeIdToken(idToken: string, exp: number) { this.storage.setItem('id_token', idToken); this.storage.setItem('id_token_expires_at', Number(exp * 1000).toString()); this.storage.setItem('id_token_stored_at', Date.now().toString()); } storeAccessToken(accessToken: string, expiresIn: number, refreshToken?: string) { this.storage.setItem('access_token', accessToken); const expiresInMilliSeconds = expiresIn * 1000; const now = new Date(); const expiresAt = now.getTime() + expiresInMilliSeconds; this.storage.setItem('access_token_expires_in', expiresAt); this.storage.setItem('access_token_stored_at', Date.now().toString()); this.setToken(accessToken, refreshToken); } saveUsername(username: string) { if (this.storage.supportsStorage()) { this.storage.setItem('USERNAME', username); } } implicitLogin() { if (!this.isValidToken() || !this.isValidAccessToken()) { this.redirectLogin(); } } isValidToken(): boolean { let validToken = false; if (this.getIdToken()) { let expiresAt = this.storage.getItem('id_token_expires_at'), now = new Date(); if (expiresAt && parseInt(expiresAt, 10) >= now.getTime()) { validToken = true; } } return validToken; } isValidAccessToken(): boolean { let validAccessToken = false; if (this.getAccessToken()) { const expiresAt = this.storage.getItem('access_token_expires_in'); const now = new Date(); if (expiresAt && parseInt(expiresAt, 10) >= now.getTime()) { validAccessToken = true; } } return validAccessToken; } getIdToken(): string { return this.storage.getItem('id_token'); } getAccessToken(): string { return this.storage.getItem('access_token'); } redirectLogin(): void { if (this.config.oauth2.implicitFlow && typeof window !== 'undefined') { let href = this.composeImplicitLoginUrl(); window.location.href = href; this.emit('implicit_redirect', href); } } isRedirectionUrl() { return window.location.hash && window.location.hash.split('&')[0].indexOf('session_state') === -1; } genNonce(): string { let text = ''; const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (let i = 0; i < 40; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } composeImplicitLoginUrl(): string { let nonce = this.genNonce(); this.storage.setItem('nonce', nonce); const afterLoginUriSegment = this.isRedirectionUrl() ? window.location.hash : ''; if (afterLoginUriSegment && afterLoginUriSegment !== '/') { this.storage.setItem('loginFragment', afterLoginUriSegment.replace('#', '').trim()); } let separation = this.discovery.loginUrl.indexOf('?') > -1 ? '&' : '?'; return this.discovery.loginUrl + separation + 'client_id=' + encodeURIComponent(this.config.oauth2.clientId) + '&redirect_uri=' + encodeURIComponent(this.config.oauth2.redirectUri) + '&scope=' + encodeURIComponent(this.config.oauth2.scope) + '&response_type=' + encodeURIComponent('id_token token') + '&nonce=' + encodeURIComponent(nonce); } composeIframeLoginUrl(): string { let nonce = this.genNonce(); this.storage.setItem('refresh_nonce', nonce); let separation = this.discovery.loginUrl.indexOf('?') > -1 ? '&' : '?'; return this.discovery.loginUrl + separation + 'client_id=' + encodeURIComponent(this.config.oauth2.clientId) + '&redirect_uri=' + encodeURIComponent(this.config.oauth2.redirectSilentIframeUri) + '&scope=' + encodeURIComponent(this.config.oauth2.scope) + '&response_type=' + encodeURIComponent('id_token token') + '&nonce=' + encodeURIComponent(nonce) + '&prompt=none'; } hasHashCharacter(hash: string): boolean { return hash.indexOf('#') === 0; } startWithHashRoute(hash: string) { return hash.startsWith('#/'); } getHashFragmentParams(externalHash: string): string { let hashFragmentParams = null; if (typeof window !== 'undefined') { let hash; if (!externalHash) { hash = decodeURIComponent(window.location.hash); if (!this.startWithHashRoute(hash)) { window.location.hash = ''; } } else { hash = decodeURIComponent(externalHash); this.removeHashFromSilentIframe(); this.destroyIframe(); } if (this.hasHashCharacter(hash) && !this.startWithHashRoute(hash)) { const questionMarkPosition = hash.indexOf('?'); if (questionMarkPosition > -1) { hash = hash.substr(questionMarkPosition + 1); } else { hash = hash.substr(1); } hashFragmentParams = this.parseQueryString(hash); } } return hashFragmentParams; } parseQueryString(queryString: string): any { const data: { [key: string]: any } = {}; let pairs, pair, separatorIndex, escapedKey, escapedValue, key, value; if (queryString !== null) { pairs = queryString.split('&'); for (let i = 0; i < pairs.length; i++) { pair = pairs[i]; separatorIndex = pair.indexOf('='); if (separatorIndex === -1) { escapedKey = pair; escapedValue = null; } else { escapedKey = pair.substr(0, separatorIndex); escapedValue = pair.substr(separatorIndex + 1); } key = decodeURIComponent(escapedKey); value = decodeURIComponent(escapedValue); if (key.substr(0, 1) === '/') { key = key.substr(1); } data[key] = value; } } return data; } silentRefresh(): void { if (typeof document === 'undefined') { this.pollingRefreshToken(); return; } if (this.checkAccessToken) { this.destroyIframe(); this.createIframe(); this.checkAccessToken = false; return; } this.refreshTokenTimeoutIframe = setTimeout(() => { this.destroyIframe(); this.createIframe(); }, this.config.oauth2.refreshTokenTimeout); } removeHashFromSilentIframe() { let iframe: any = document.getElementById('silent_refresh_token_iframe'); if (iframe && iframe.contentWindow.location.hash) { iframe.contentWindow.location.hash = ''; } } createIframe() { const iframe = document.createElement('iframe'); iframe.id = 'silent_refresh_token_iframe'; let loginUrl = this.composeIframeLoginUrl(); iframe.setAttribute('src', loginUrl); iframe.style.display = 'none'; document.body.appendChild(iframe); this.iFrameHashListener = () => { let silentRefreshTokenIframe: any = document.getElementById('silent_refresh_token_iframe'); let hash = silentRefreshTokenIframe.contentWindow.location.hash; try { this.checkFragment('refresh_nonce', hash); } catch (e) { this.logOut(); } }; iframe.addEventListener('load', this.iFrameHashListener); } destroyIframe() { const iframe = document.getElementById('silent_refresh_token_iframe'); if (iframe) { iframe.removeEventListener('load', this.iFrameHashListener); document.body.removeChild(iframe); } } /** * login Alfresco API * @returns {Promise} A promise that returns {new authentication token} if resolved and {error} if rejected. * */ login(username: string, password: string): Promise<any> { return new Promise((resolve, reject) => { this.grantPasswordLogin(username, password, resolve, reject); }); } grantPasswordLogin(username: string, password: string, resolve: any, reject: any) { this.invalidateSession(); let postBody = {}, pathParams = {}, queryParams = {}; let headerParams = { 'Content-Type': 'application/x-www-form-urlencoded' }; let formParams = { username: username, password: password, grant_type: 'password', client_id: this.config.oauth2.clientId }; let contentTypes = ['application/x-www-form-urlencoded']; let accepts = ['application/json']; let promise = this.callCustomApi( this.discovery.tokenEndpoint, 'POST', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts ).then( (data: any) => { this.saveUsername(username); this.silentRefresh(); this.storeAccessToken(data.access_token, data.expires_in, data.refresh_token); resolve(data); }, (error) => { if (error.error && error.error.status === 401 || error.status === 401) { this.emit('unauthorized'); } this.emit('error'); reject(error.error); }); ee(promise); // jshint ignore:line } pollingRefreshToken() { this.refreshTokenIntervalPolling = setInterval(async () => { try { await this.refreshToken(); } catch (e) { /* continue regardless of error */ } }, this.config.oauth2.refreshTokenTimeout); this.refreshTokenIntervalPolling.unref(); } /** * Refresh the Token * */ refreshToken(): Promise<any> { let postBody = {}, pathParams = {}, queryParams = {}, formParams = {}; let auth = 'Basic ' + this.universalBtoa(this.config.oauth2.clientId + ':' + this.config.oauth2.secret); let headerParams = { 'Content-Type': 'application/x-www-form-urlencoded', 'Cache-Control': 'no-cache', 'Authorization': auth }; formParams = { grant_type: 'refresh_token', refresh_token: this.authentications.oauth2.refreshToken }; let contentTypes = ['application/x-www-form-urlencoded']; let accepts = ['application/json']; let promise = new Promise((resolve, reject) => { this.callCustomApi( this.discovery.tokenEndpoint, 'POST', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts ).then( (data: any) => { this.setToken(data.access_token, data.refresh_token); resolve(data); }, (error) => { if (error.error && error.error.status === 401) { this.emit('unauthorized'); } this.emit('error'); reject(error.error); }); }); ee(promise); // jshint ignore:line return promise; } universalBtoa(stringToConvert: string) { try { return btoa(stringToConvert); } catch (err) { return Buffer.from(stringToConvert).toString('base64'); } } /** * Set the current Token * */ setToken(token: string, refreshToken: string) { this.authentications.oauth2.accessToken = token; this.authentications.oauth2.refreshToken = refreshToken; this.authentications.basicAuth.password = null; this.token = token; if (token) { this.emit('token_issued'); this.emit('logged-in'); } } /** * Get the current Token * * */ getToken(): string { return this.token; } /** * return the Authentication * * @returns {Object} authentications * */ getAuthentication(): Authentication { return this.authentications; } /** * Change the Host * */ changeHost(host: string) { this.config.hostOauth2 = host; } /** * If the client is logged in return true * * @returns {Boolean} is logged in */ isLoggedIn(): boolean { return !!this.authentications.oauth2.accessToken; } /** * Logout **/ async logOut() { this.checkAccessToken = true; const id_token = this.getIdToken(); this.invalidateSession(); this.setToken(null, null); let separation = this.discovery.logoutUrl.indexOf('?') > -1 ? '&' : '?'; let redirectLogout = this.config.oauth2.redirectUriLogout || this.config.oauth2.redirectUri; let logoutUrl = this.discovery.logoutUrl + separation + 'post_logout_redirect_uri=' + encodeURIComponent(redirectLogout) + '&id_token_hint=' + encodeURIComponent(id_token); if (id_token != null && this.config.oauth2.implicitFlow && typeof window !== 'undefined') { window.location.href = logoutUrl; } } invalidateSession() { clearTimeout(this.refreshTokenTimeoutIframe); clearInterval(this.refreshTokenIntervalPolling); this.storage.removeItem('access_token'); this.storage.removeItem('access_token_expires_in'); this.storage.removeItem('access_token_stored_at'); this.storage.removeItem('id_token'); this.storage.removeItem('id_token'); this.storage.removeItem('id_token_claims_obj'); this.storage.removeItem('id_token_expires_at'); this.storage.removeItem('id_token_stored_at'); this.storage.removeItem('nonce'); } exchangeTicketListener(alfrescoApi: AlfrescoApi) { this.on('token_issued', async () => { const authContentApi: AuthenticationApi = new AuthenticationApi(alfrescoApi); authContentApi.apiClient.authentications = this.authentications; try { const ticketEntry = await authContentApi.getTicket(); this.config.ticketEcm = ticketEntry.entry.id; this.emit('ticket_exchanged'); } catch (e) { // continue regardless of error } }); } }
the_stack
import * as React from 'react' import SimpleMarkdown from 'simple-markdown' import * as Styles from '../../styles' import Text, {LineClampType} from '../text' import Box from '../box' import Markdown from '../markdown' import Emoji, {Props as EmojiProps} from '../emoji' import {emojiIndexByName} from './emoji-gen' import ServiceDecoration from './service-decoration' const wrapStyle = Styles.platformStyles({ isElectron: { whiteSpace: 'pre-wrap', wordBreak: 'break-word', } as const, }) const markdownStyles = Styles.styleSheetCreate( () => ({ bigTextBlockStyle: Styles.platformStyles({ isElectron: { ...wrapStyle, color: 'inherit', display: 'block', fontWeight: 'inherit', }, isMobile: { fontSize: 32, lineHeight: undefined, }, } as const), boldStyle: Styles.platformStyles({ common: { ...Styles.globalStyles.fontBold, }, isElectron: {color: 'inherit', ...wrapStyle}, isMobile: {color: undefined}, }), get codeSnippetBlockStyle() { return Styles.platformStyles({ common: { ...this.codeSnippetStyle, backgroundColor: Styles.globalColors.redLighter, marginBottom: Styles.globalMargins.xtiny, marginTop: Styles.globalMargins.xtiny, paddingBottom: Styles.globalMargins.xtiny, paddingLeft: Styles.globalMargins.tiny, paddingRight: Styles.globalMargins.tiny, paddingTop: Styles.globalMargins.xtiny, }, isElectron: { ...wrapStyle, color: Styles.globalColors.black, display: 'block', }, }) }, codeSnippetBlockTextStyle: Styles.platformStyles({ isMobile: { ...Styles.globalStyles.fontTerminal, backgroundColor: Styles.globalColors.redLighter, color: Styles.globalColors.black, fontSize: 15, }, }), codeSnippetStyle: Styles.platformStyles({ common: { ...Styles.globalStyles.fontTerminal, ...Styles.globalStyles.rounded, backgroundColor: Styles.globalColors.redLighter, color: Styles.globalColors.blueDarkOrBlueLight, paddingLeft: Styles.globalMargins.xtiny, paddingRight: Styles.globalMargins.xtiny, }, isElectron: { ...wrapStyle, fontSize: 12, }, isMobile: { fontSize: 15, }, }), italicStyle: Styles.platformStyles({ common: { fontStyle: 'italic', }, isElectron: {color: 'inherit', fontWeight: 'inherit', ...wrapStyle}, isMobile: {color: undefined, fontWeight: undefined}, }), linkStyle: Styles.platformStyles({ isElectron: { ...wrapStyle, fontWeight: 'inherit', }, isMobile: { fontWeight: undefined, }, }), neutralPreviewStyle: Styles.platformStyles({ isElectron: {color: 'inherit', fontWeight: 'inherit'}, isMobile: {color: Styles.globalColors.black_50, fontWeight: undefined}, }), quoteStyle: Styles.platformStyles({ common: { borderLeftColor: Styles.globalColors.grey, borderLeftWidth: 3, borderStyle: 'solid', }, isElectron: { display: 'block', paddingLeft: Styles.globalMargins.small, }, isMobile: { paddingLeft: Styles.globalMargins.tiny, }, }), strikeStyle: Styles.platformStyles({ isElectron: { ...wrapStyle, color: 'inherit', fontWeight: 'inherit', textDecoration: 'line-through', } as const, isMobile: { fontWeight: undefined, textDecorationLine: 'line-through', }, }), textBlockStyle: Styles.platformStyles({ isAndroid: {lineHeight: undefined}, isElectron: {color: 'inherit', display: 'block', fontWeight: 'inherit', ...wrapStyle}, } as const), wrapStyle, } as const) ) // TODO kill this when we remove the old markdown parser. This check is done at the parsing level. const EmojiIfExists = React.memo( ( props: EmojiProps & { paragraphTextClassName?: string style?: any allowFontScaling?: boolean lineClamp?: LineClampType } ) => { const emojiNameLower = props.emojiName.toLowerCase() const exists = !!emojiIndexByName[emojiNameLower] return exists ? ( <Emoji emojiName={emojiNameLower} size={props.size} allowFontScaling={props.allowFontScaling} /> ) : ( <Markdown paragraphTextClassName={props.paragraphTextClassName} style={props.style} lineClamp={props.lineClamp} allowFontScaling={props.allowFontScaling} > {props.emojiName} </Markdown> ) } ) const reactComponentsForMarkdownType = { Array: { // basically a port of the old reactFor which we used before react: ( arr: Array<SimpleMarkdown.SingleASTNode>, output: SimpleMarkdown.Output<any>, state: SimpleMarkdown.State ) => { var oldKey = state.key var result: Array<SimpleMarkdown.ReactElements> = [] // map nestedOutput over the ast, except group any text // nodes together into a single string output. var lastResult: string | null = null for (var i = 0; i < arr.length; i++) { state.key = '' + i var nodeOut = output(arr[i], state) if (typeof nodeOut === 'string' && typeof lastResult === 'string') { lastResult = lastResult + nodeOut result[result.length - 1] = lastResult } else { result.push(nodeOut) lastResult = nodeOut } } state.key = oldKey return result }, }, // On mobile we can't have raw text without a Text tag. So we make sure we are in a paragraph or we return a new text tag. If it's not mobile we can short circuit and just return the string blockQuote: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <Box key={state.key} style={markdownStyles.quoteStyle}> {output(node.content, {...state, inBlockQuote: true})} </Box> ), }, del: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <Text type="Body" key={state.key} style={Styles.collapseStyles([markdownStyles.strikeStyle, state.styleOverride.del])} allowFontScaling={state.allowFontScaling} > {output(node.content, state)} </Text> ), }, em: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <Text type="Body" key={state.key} style={Styles.collapseStyles([markdownStyles.italicStyle, state.styleOverride.em])} > {output(node.content, state)} </Text> ), }, emoji: { react: ( node: SimpleMarkdown.SingleASTNode, _output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => <Emoji emojiName={String(node.content).toLowerCase()} size={16} key={state.key} />, }, fence: { react: ( node: SimpleMarkdown.SingleASTNode, _output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => Styles.isMobile ? ( <Box key={state.key} style={markdownStyles.codeSnippetBlockTextStyle}> <Text type="Body" style={Styles.collapseStyles([ markdownStyles.codeSnippetBlockTextStyle, state.styleOverride.fence, ])} allowFontScaling={state.allowFontScaling} > {node.content} </Text> </Box> ) : ( <Text key={state.key} type="Body" style={Styles.collapseStyles([markdownStyles.codeSnippetBlockStyle, state.styleOverride.fence])} > {node.content} </Text> ), }, inlineCode: { react: ( node: SimpleMarkdown.SingleASTNode, _output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <Text type="Body" key={state.key} style={Styles.collapseStyles([markdownStyles.codeSnippetStyle, state.styleOverride.inlineCode])} allowFontScaling={state.allowFontScaling} > {node.content} </Text> ), }, newline: { react: ( _node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => !Styles.isMobile || state.inParagraph ? ( output({content: '\n', type: 'text'}, state) ) : ( <Text type="Body" key={state.key} style={Styles.collapseStyles([markdownStyles.textBlockStyle, state.styleOverride.paragraph])} allowFontScaling={state.allowFontScaling} > {'\n'} </Text> ), }, paragraph: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <Text className={state.paragraphTextClassName} type="Body" key={state.key} style={Styles.collapseStyles([markdownStyles.textBlockStyle, state.styleOverride.paragraph])} allowFontScaling={state.allowFontScaling} > {output(node.content, {...state, inParagraph: true})} </Text> ), }, serviceDecoration: { react: ( node: SimpleMarkdown.SingleASTNode, _output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <ServiceDecoration json={node.content} key={state.key} allowFontScaling={state.allowFontScaling} message={(state.markdownMeta && state.markdownMeta.message) || undefined} styleOverride={state.styleOverride} styles={markdownStyles} disableBigEmojis={false} disableEmojiAnimation={false} /> ), }, strong: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <Text type="BodySemibold" key={state.key} style={Styles.collapseStyles([markdownStyles.boldStyle, state.styleOverride.strong])} allowFontScaling={state.allowFontScaling} > {output(node.content, state)} </Text> ), }, text: SimpleMarkdown.defaultRules.text, } const passthroughForMarkdownType = Object.keys(reactComponentsForMarkdownType).reduce<{ [key: string]: SimpleMarkdown.ReactOutputRule | SimpleMarkdown.ReactArrayRule }>((obj, k) => { // keep special Array type if (k === 'Array') { obj[k] = reactComponentsForMarkdownType[k] } else { obj[k] = { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => typeof node.content !== 'object' ? SimpleMarkdown.defaultRules.text.react({content: node.content, type: 'text'}, output, state) : output(node.content, state), } } return obj }, {}) const bigEmojiOutput: SimpleMarkdown.Output<any> = SimpleMarkdown.outputFor( { ...reactComponentsForMarkdownType, emoji: { react: ( node: SimpleMarkdown.SingleASTNode, _output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <Emoji emojiName={String(node.content)} size={32} key={state.key} allowFontScaling={state.allowFontScaling} /> ), }, paragraph: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <Text type="Body" key={state.key} style={markdownStyles.bigTextBlockStyle} allowFontScaling={state.allowFontScaling} > {output(node.content, {...state, inParagraph: true})} </Text> ), }, }, 'react' ) const previewOutput: SimpleMarkdown.Output<any> = SimpleMarkdown.outputFor( { Array: SimpleMarkdown.defaultRules.Array, ...passthroughForMarkdownType, blockQuote: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => React.Children.toArray([output([{content: '> ', type: 'text'}], state), output(node.content, state)]), }, codeBlock: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => React.Children.toArray([output([{content: ' ', type: 'text'}], state), output(node.content, state)]), }, emoji: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => reactComponentsForMarkdownType.emoji.react(node, output, state), }, newline: { react: ( _node: SimpleMarkdown.SingleASTNode, _output: SimpleMarkdown.ReactOutput, _state: SimpleMarkdown.State ) => ' ', }, serviceDecoration: { react: ( node: SimpleMarkdown.SingleASTNode, _output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <ServiceDecoration json={node.content} key={state.key} allowFontScaling={state.allowFontScaling} styleOverride={state.styleOverride} styles={markdownStyles as any} disableBigEmojis={true} disableEmojiAnimation={true} /> ), }, text: SimpleMarkdown.defaultRules.text, }, 'react' ) const serviceOnlyOutput: SimpleMarkdown.Output<any> = SimpleMarkdown.outputFor( { Array: SimpleMarkdown.defaultRules.Array, ...passthroughForMarkdownType, emoji: { react: ( node: SimpleMarkdown.SingleASTNode, output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => reactComponentsForMarkdownType.emoji.react(node, output, state), }, serviceDecoration: { react: ( node: SimpleMarkdown.SingleASTNode, _output: SimpleMarkdown.ReactOutput, state: SimpleMarkdown.State ) => ( <ServiceDecoration json={node.content} key={state.key} allowFontScaling={state.allowFontScaling} styleOverride={state.styleOverride} styles={markdownStyles as any} disableBigEmojis={true} disableEmojiAnimation={true} /> ), }, text: SimpleMarkdown.defaultRules.text, }, 'react' ) const reactOutput: SimpleMarkdown.Output<any> = SimpleMarkdown.outputFor( reactComponentsForMarkdownType, 'react' ) export {EmojiIfExists, bigEmojiOutput, markdownStyles, previewOutput, reactOutput, serviceOnlyOutput}
the_stack
import { ComponentClass } from "react"; import Taro, { Component, Config } from "@tarojs/taro"; import { AtTabBar, AtIcon, AtSearchBar } from "taro-ui"; import classnames from "classnames"; import { View, Image, Text } from "@tarojs/components"; import { connect } from "@tarojs/redux"; import CLoading from "../../components/CLoading"; import api from "../../services/api"; import CMusic from "../../components/CMusic"; import { injectPlaySong } from "../../utils/decorators"; import { getSongInfo, updatePlayStatus } from "../../actions/song"; import { formatCount } from "../../utils/common"; import { songType } from "../../constants/commonType"; import "./index.scss"; type ListItemInfo = { id: number; coverImgUrl: string; name: string; trackCount: number; playCount: number; }; type PageStateProps = { song: songType; }; type PageDispatchProps = { getSongInfo: (object) => any; updatePlayStatus: (object) => any; }; type IProps = PageStateProps & PageDispatchProps; interface Page { props: IProps; } type PageState = { userInfo: { account: { id: number; }; level: number; profile: { avatarUrl: string; backgroundUrl: string; nickname: string; eventCount: number; newFollows: number; followeds: number; userId: number; }; }; current: number; userCreateList: Array<ListItemInfo>; userCollectList: Array<ListItemInfo>; searchValue: string; }; // interface Page { // props: PageStateProps; // } @injectPlaySong() @connect( ({ song }) => ({ song: song }), dispatch => ({ getSongInfo(object) { dispatch(getSongInfo(object)); }, updatePlayStatus(object) { dispatch(updatePlayStatus(object)); } }) ) class Page extends Component<IProps, PageState> { /** * 指定config的类型声明为: Taro.Config * * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型 * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型 */ config: Config = { navigationBarTitleText: "我的" }; constructor(props) { super(props); this.state = { userInfo: Taro.getStorageSync("userInfo"), current: 1, userCreateList: [], userCollectList: [], searchValue: "" }; } // componentWillReceiveProps (nextProps) { // console.log(this.props, nextProps) // } componentWillUnmount() {} componentDidShow() { if (!this.state.userInfo) { Taro.navigateTo({ url: "/pages/login/index" }); return; } this.getSubcount(); this.getUserDetail(); this.getPlayList(); } componentDidHide() {} getUserDetail() { const { userId } = this.state.userInfo.profile; api .get("/user/detail", { uid: userId }) .then(res => { res.data; this.setState({ userInfo: res.data }); }); } getPlayList() { const { userId } = this.state.userInfo.profile; api .get("/user/playlist", { uid: userId, limit: 300 }) .then(res => { if (res.data.playlist && res.data.playlist.length > 0) { this.setState({ userCreateList: res.data.playlist.filter( item => item.userId === userId ), userCollectList: res.data.playlist.filter( item => item.userId !== userId ) }); } }); } getSubcount() { api.get("/user/subcount").then(res => { console.log("res", res); }); } switchTab(value) { if (value !== 0) return; Taro.reLaunch({ url: "/pages/index/index" }); } showToast() { Taro.showToast({ title: "暂未实现,敬请期待", icon: "none" }); } goUserDetail() { return; // const { userId } = this.state.userInfo.profile // Taro.navigateTo({ // url: `/pages/user/index?id=${userId}` // }) } goSearch() { Taro.navigateTo({ url: `/pages/search/index` }); } jumpPage(name) { Taro.navigateTo({ url: `/pages/${name}/index` }); } jumpEventPage() { const { userId } = this.state.userInfo.profile; Taro.navigateTo({ url: `/pages/myEvents/index?uid=${userId}` }); } signOut() { Taro.clearStorage(); api.get("/logout").then(res => { console.log("退出登陆", res); }); Taro.redirectTo({ url: "/pages/login/index" }); } goDetail(item) { Taro.navigateTo({ url: `/pages/playListDetail/index?id=${item.id}&name=${item.name}` }); } render() { const { userInfo, userCreateList, userCollectList, searchValue } = this.state; const { currentSongInfo, isPlaying, canPlayList } = this.props.song; return ( <View className={classnames({ my_container: true, hasMusicBox: !!this.props.song.currentSongInfo.name })} > <CMusic songInfo={{ currentSongInfo, isPlaying, canPlayList }} isHome={true} onUpdatePlayStatus={this.props.updatePlayStatus.bind(this)} /> <View onClick={this.goSearch.bind(this)}> <AtSearchBar actionName="搜一下" disabled={true} value={searchValue} onChange={this.goSearch.bind(this)} /> </View> <View className="header"> <View className="header__left" onClick={this.goUserDetail.bind(this)}> <Image src={`${userInfo.profile.avatarUrl}?imageView&thumbnail=250x0`} className="header__img" /> <View className="header__info"> <View className="header__info__name"> {userInfo.profile.nickname} </View> <View> <Text className="header__info__level">LV.{userInfo.level}</Text> </View> </View> </View> <AtIcon prefixClass="fa" value="sign-out" size="30" color="#d43c33" className="exit_icon" onClick={this.signOut.bind(this)} ></AtIcon> </View> <View className="user_count"> <View className="user_count__sub" onClick={this.jumpEventPage.bind(this)} > <View className="user_count__sub--num"> {userInfo.profile.eventCount || 0} </View> <View>动态</View> </View> <View className="user_count__sub" onClick={this.jumpPage.bind(this, "myFocus")} > <View className="user_count__sub--num"> {userInfo.profile.newFollows || 0} </View> <View>关注</View> </View> <View className="user_count__sub" onClick={this.jumpPage.bind(this, "myFans")} > <View className="user_count__sub--num"> {userInfo.profile.followeds || 0} </View> <View>粉丝</View> </View> </View> <View className="user_brief"> <View className="user_brief__item"> <Image className="user_brief__item__img" src={require("../../assets/images/my/recent_play.png")} /> <View className="user_brief__item__text" onClick={this.jumpPage.bind(this, "recentPlay")} > <Text>最近播放</Text> <Text className="at-icon at-icon-chevron-right"></Text> </View> </View> <View className="user_brief__item"> <Image className="user_brief__item__img" src={require("../../assets/images/my/my_radio.png")} /> <View className="user_brief__item__text" onClick={this.showToast.bind(this)} > <Text>我的电台</Text> <Text className="at-icon at-icon-chevron-right"></Text> </View> </View> <View className="user_brief__item"> <Image className="user_brief__item__img" src={require("../../assets/images/my/my_collection_icon.png")} /> <View className="user_brief__item__text" onClick={this.showToast.bind(this)} > <Text>我的收藏</Text> <Text className="at-icon at-icon-chevron-right"></Text> </View> </View> </View> <View className="user_playlist"> <View className="user_playlist__title"> 我创建的歌单 <Text className="user_playlist__title__desc"> ({userCreateList.length}) </Text> </View> {userCreateList.length === 0 ? <CLoading /> : ""} <View> {userCreateList.map(item => ( <View key={item.id} className="user_playlist__item" onClick={this.goDetail.bind(this, item)} > <Image className="user_playlist__item__cover" src={`${item.coverImgUrl}?imageView&thumbnail=250x0`} /> <View className="user_playlist__item__info"> <View className="user_playlist__item__info__name"> {item.name} </View> <View className="user_playlist__item__info__count"> {item.trackCount}首, 播放{formatCount(item.playCount)}次 </View> </View> </View> ))} </View> </View> <View className="user_playlist"> <View className="user_playlist__title"> 我收藏的歌单 <Text className="user_playlist__title__desc"> ({userCollectList.length}) </Text> </View> {userCollectList.length === 0 ? <CLoading /> : ""} <View> {userCollectList.map(item => ( <View key={item.id} className="user_playlist__item" onClick={this.goDetail.bind(this, item)} > <Image className="user_playlist__item__cover" src={`${item.coverImgUrl}?imageView&thumbnail=250x0`} /> <View className="user_playlist__item__info"> <View className="user_playlist__item__info__name"> {item.name} </View> <View className="user_playlist__item__info__count"> {item.trackCount}首, 播放{formatCount(item.playCount)}次 </View> </View> </View> ))} </View> </View> <AtTabBar fixed selectedColor="#d43c33" tabList={[ { title: "发现", iconPrefixClass: "fa", iconType: "feed" }, { title: "我的", iconPrefixClass: "fa", iconType: "music" } ]} onClick={this.switchTab.bind(this)} current={this.state.current} /> </View> ); } } export default Page as ComponentClass<PageDispatchProps, PageState>;
the_stack
* XML element names. */ export module XmlElementNames { export var AllProperties: string = "AllProperties"; export var ParentFolderIds: string = "ParentFolderIds"; export var DistinguishedFolderId: string = "DistinguishedFolderId"; export var ItemId: string = "ItemId"; export var ItemIds: string = "ItemIds"; export var FolderId: string = "FolderId"; export var FolderIds: string = "FolderIds"; export var SourceId: string = "SourceId"; export var OccurrenceItemId: string = "OccurrenceItemId"; export var RecurringMasterItemId: string = "RecurringMasterItemId"; export var ItemShape: string = "ItemShape"; export var FolderShape: string = "FolderShape"; export var BaseShape: string = "BaseShape"; export var IndexedPageItemView: string = "IndexedPageItemView"; export var IndexedPageFolderView: string = "IndexedPageFolderView"; export var FractionalPageItemView: string = "FractionalPageItemView"; export var FractionalPageFolderView: string = "FractionalPageFolderView"; export var SeekToConditionPageItemView: string = "SeekToConditionPageItemView"; export var ResponseCode: string = "ResponseCode"; export var RootFolder: string = "RootFolder"; export var Folder: string = "Folder"; export var ContactsFolder: string = "ContactsFolder"; export var TasksFolder: string = "TasksFolder"; export var SearchFolder: string = "SearchFolder"; export var Folders: string = "Folders"; export var Item: string = "Item"; export var Items: string = "Items"; export var Message: string = "Message"; export var Mailbox: string = "Mailbox"; export var Body: string = "Body"; export var From: string = "From"; export var Sender: string = "Sender"; export var Name: string = "Name"; export var Address: string = "Address"; export var EmailAddress: string = "EmailAddress"; export var RoutingType: string = "RoutingType"; export var MailboxType: string = "MailboxType"; export var ToRecipients: string = "ToRecipients"; export var CcRecipients: string = "CcRecipients"; export var BccRecipients: string = "BccRecipients"; export var ReplyTo: string = "ReplyTo"; export var ConversationTopic: string = "ConversationTopic"; export var ConversationIndex: string = "ConversationIndex"; export var IsDeliveryReceiptRequested: string = "IsDeliveryReceiptRequested"; export var IsRead: string = "IsRead"; export var IsReadReceiptRequested: string = "IsReadReceiptRequested"; export var IsResponseRequested: string = "IsResponseRequested"; export var InternetMessageId: string = "InternetMessageId"; export var References: string = "References"; export var ParentItemId: string = "ParentItemId"; export var ParentFolderId: string = "ParentFolderId"; export var ChildFolderCount: string = "ChildFolderCount"; export var DisplayName: string = "DisplayName"; export var TotalCount: string = "TotalCount"; export var ItemClass: string = "ItemClass"; export var FolderClass: string = "FolderClass"; export var Subject: string = "Subject"; export var MimeContent: string = "MimeContent"; export var MimeContentUTF8: string = "MimeContentUTF8"; export var Sensitivity: string = "Sensitivity"; export var Attachments: string = "Attachments"; export var DateTimeReceived: string = "DateTimeReceived"; export var Size: string = "Size"; export var Categories: string = "Categories"; export var Importance: string = "Importance"; export var InReplyTo: string = "InReplyTo"; export var IsSubmitted: string = "IsSubmitted"; export var IsAssociated: string = "IsAssociated"; export var IsDraft: string = "IsDraft"; export var IsFromMe: string = "IsFromMe"; export var IsHidden: string = "IsHidden"; export var IsQuickContact: string = "IsQuickContact"; export var IsResend: string = "IsResend"; export var IsUnmodified: string = "IsUnmodified"; export var IsWritable: string = "IsWritable"; export var InternetMessageHeader: string = "InternetMessageHeader"; export var InternetMessageHeaders: string = "InternetMessageHeaders"; export var DateTimeSent: string = "DateTimeSent"; export var DateTimeCreated: string = "DateTimeCreated"; export var ResponseObjects: string = "ResponseObjects"; export var ReminderDueBy: string = "ReminderDueBy"; export var ReminderIsSet: string = "ReminderIsSet"; export var ReminderMinutesBeforeStart: string = "ReminderMinutesBeforeStart"; export var DisplayCc: string = "DisplayCc"; export var DisplayTo: string = "DisplayTo"; export var HasAttachments: string = "HasAttachments"; export var ExtendedProperty: string = "ExtendedProperty"; export var Culture: string = "Culture"; export var FileAttachment: string = "FileAttachment"; export var ItemAttachment: string = "ItemAttachment"; export var AttachmentIds: string = "AttachmentIds"; export var AttachmentId: string = "AttachmentId"; export var ContentType: string = "ContentType"; export var ContentLocation: string = "ContentLocation"; export var ContentId: string = "ContentId"; export var Content: string = "Content"; export var SavedItemFolderId: string = "SavedItemFolderId"; export var MessageText: string = "MessageText"; export var DescriptiveLinkKey: string = "DescriptiveLinkKey"; export var ItemChange: string = "ItemChange"; export var ItemChanges: string = "ItemChanges"; export var FolderChange: string = "FolderChange"; export var FolderChanges: string = "FolderChanges"; export var Updates: string = "Updates"; export var AppendToItemField: string = "AppendToItemField"; export var SetItemField: string = "SetItemField"; export var DeleteItemField: string = "DeleteItemField"; export var SetFolderField: string = "SetFolderField"; export var DeleteFolderField: string = "DeleteFolderField"; export var FieldURI: string = "FieldURI"; export var RootItemId: string = "RootItemId"; export var ReferenceItemId: string = "ReferenceItemId"; export var NewBodyContent: string = "NewBodyContent"; export var ReplyToItem: string = "ReplyToItem"; export var ReplyAllToItem: string = "ReplyAllToItem"; export var ForwardItem: string = "ForwardItem"; export var AcceptItem: string = "AcceptItem"; export var TentativelyAcceptItem: string = "TentativelyAcceptItem"; export var DeclineItem: string = "DeclineItem"; export var CancelCalendarItem: string = "CancelCalendarItem"; export var RemoveItem: string = "RemoveItem"; export var SuppressReadReceipt: string = "SuppressReadReceipt"; export var SuppressReadReceipts: string = "SuppressReadReceipts"; export var String: string = "String"; export var Start: string = "Start"; export var End: string = "End"; export var ProposedStart: string = "ProposedStart"; export var ProposedEnd: string = "ProposedEnd"; export var OriginalStart: string = "OriginalStart"; export var IsAllDayEvent: string = "IsAllDayEvent"; export var LegacyFreeBusyStatus: string = "LegacyFreeBusyStatus"; export var Location: string = "Location"; export var When: string = "When"; export var IsMeeting: string = "IsMeeting"; export var IsCancelled: string = "IsCancelled"; export var IsRecurring: string = "IsRecurring"; export var MeetingRequestWasSent: string = "MeetingRequestWasSent"; export var CalendarItemType: string = "CalendarItemType"; export var MyResponseType: string = "MyResponseType"; export var Organizer: string = "Organizer"; export var RequiredAttendees: string = "RequiredAttendees"; export var OptionalAttendees: string = "OptionalAttendees"; export var Resources: string = "Resources"; export var ConflictingMeetingCount: string = "ConflictingMeetingCount"; export var AdjacentMeetingCount: string = "AdjacentMeetingCount"; export var ConflictingMeetings: string = "ConflictingMeetings"; export var AdjacentMeetings: string = "AdjacentMeetings"; export var Duration: string = "Duration"; export var TimeZone: string = "TimeZone"; export var AppointmentReplyTime: string = "AppointmentReplyTime"; export var AppointmentSequenceNumber: string = "AppointmentSequenceNumber"; export var AppointmentState: string = "AppointmentState"; export var Recurrence: string = "Recurrence"; export var FirstOccurrence: string = "FirstOccurrence"; export var LastOccurrence: string = "LastOccurrence"; export var ModifiedOccurrences: string = "ModifiedOccurrences"; export var DeletedOccurrences: string = "DeletedOccurrences"; export var MeetingTimeZone: string = "MeetingTimeZone"; export var ConferenceType: string = "ConferenceType"; export var AllowNewTimeProposal: string = "AllowNewTimeProposal"; export var IsOnlineMeeting: string = "IsOnlineMeeting"; export var MeetingWorkspaceUrl: string = "MeetingWorkspaceUrl"; export var NetShowUrl: string = "NetShowUrl"; export var JoinOnlineMeetingUrl: string = "JoinOnlineMeetingUrl"; export var OnlineMeetingSettings: string = "OnlineMeetingSettings"; export var LobbyBypass: string = "LobbyBypass"; export var AccessLevel: string = "AccessLevel"; export var Presenters: string = "Presenters"; export var CalendarItem: string = "CalendarItem"; export var CalendarFolder: string = "CalendarFolder"; export var Attendee: string = "Attendee"; export var ResponseType: string = "ResponseType"; export var LastResponseTime: string = "LastResponseTime"; export var Occurrence: string = "Occurrence"; export var DeletedOccurrence: string = "DeletedOccurrence"; export var RelativeYearlyRecurrence: string = "RelativeYearlyRecurrence"; export var AbsoluteYearlyRecurrence: string = "AbsoluteYearlyRecurrence"; export var RelativeMonthlyRecurrence: string = "RelativeMonthlyRecurrence"; export var AbsoluteMonthlyRecurrence: string = "AbsoluteMonthlyRecurrence"; export var WeeklyRecurrence: string = "WeeklyRecurrence"; export var DailyRecurrence: string = "DailyRecurrence"; export var DailyRegeneration: string = "DailyRegeneration"; export var WeeklyRegeneration: string = "WeeklyRegeneration"; export var MonthlyRegeneration: string = "MonthlyRegeneration"; export var YearlyRegeneration: string = "YearlyRegeneration"; export var NoEndRecurrence: string = "NoEndRecurrence"; export var EndDateRecurrence: string = "EndDateRecurrence"; export var NumberedRecurrence: string = "NumberedRecurrence"; export var Interval: string = "Interval"; export var DayOfMonth: string = "DayOfMonth"; export var DayOfWeek: string = "DayOfWeek"; export var DaysOfWeek: string = "DaysOfWeek"; export var DayOfWeekIndex: string = "DayOfWeekIndex"; export var Month: string = "Month"; export var StartDate: string = "StartDate"; export var EndDate: string = "EndDate"; export var StartTime: string = "StartTime"; export var EndTime: string = "EndTime"; export var NumberOfOccurrences: string = "NumberOfOccurrences"; export var AssociatedCalendarItemId: string = "AssociatedCalendarItemId"; export var IsDelegated: string = "IsDelegated"; export var IsOutOfDate: string = "IsOutOfDate"; export var HasBeenProcessed: string = "HasBeenProcessed"; export var IsOrganizer: string = "IsOrganizer"; export var MeetingMessage: string = "MeetingMessage"; export var FileAs: string = "FileAs"; export var FileAsMapping: string = "FileAsMapping"; export var GivenName: string = "GivenName"; export var Initials: string = "Initials"; export var MiddleName: string = "MiddleName"; export var NickName: string = "Nickname"; export var CompleteName: string = "CompleteName"; export var CompanyName: string = "CompanyName"; export var EmailAddresses: string = "EmailAddresses"; export var PhysicalAddresses: string = "PhysicalAddresses"; export var PhoneNumbers: string = "PhoneNumbers"; export var PhoneNumber: string = "PhoneNumber"; export var AssistantName: string = "AssistantName"; export var Birthday: string = "Birthday"; export var BusinessHomePage: string = "BusinessHomePage"; export var Children: string = "Children"; export var Companies: string = "Companies"; export var ContactSource: string = "ContactSource"; export var Department: string = "Department"; export var Generation: string = "Generation"; export var ImAddresses: string = "ImAddresses"; export var ImAddress: string = "ImAddress"; export var JobTitle: string = "JobTitle"; export var Manager: string = "Manager"; export var Mileage: string = "Mileage"; export var OfficeLocation: string = "OfficeLocation"; export var PostalAddressIndex: string = "PostalAddressIndex"; export var Profession: string = "Profession"; export var SpouseName: string = "SpouseName"; export var Surname: string = "Surname"; export var WeddingAnniversary: string = "WeddingAnniversary"; export var HasPicture: string = "HasPicture"; export var Title: string = "Title"; export var FirstName: string = "FirstName"; export var LastName: string = "LastName"; export var Suffix: string = "Suffix"; export var FullName: string = "FullName"; export var YomiFirstName: string = "YomiFirstName"; export var YomiLastName: string = "YomiLastName"; export var Contact: string = "Contact"; export var Entry: string = "Entry"; export var Street: string = "Street"; export var City: string = "City"; export var State: string = "State"; export var SharePointSiteUrl: string = "SharePointSiteUrl"; export var Country: string = "Country"; export var CountryOrRegion: string = "CountryOrRegion"; export var PostalCode: string = "PostalCode"; export var PostOfficeBox: string = "PostOfficeBox"; export var Members: string = "Members"; export var Member: string = "Member"; export var AdditionalProperties: string = "AdditionalProperties"; export var ExtendedFieldURI: string = "ExtendedFieldURI"; export var Value: string = "Value"; export var Values: string = "Values"; export var ToFolderId: string = "ToFolderId"; export var ActualWork: string = "ActualWork"; export var AssignedTime: string = "AssignedTime"; export var BillingInformation: string = "BillingInformation"; export var ChangeCount: string = "ChangeCount"; export var CompleteDate: string = "CompleteDate"; export var Contacts: string = "Contacts"; export var DelegationState: string = "DelegationState"; export var Delegator: string = "Delegator"; export var DueDate: string = "DueDate"; export var IsAssignmentEditable: string = "IsAssignmentEditable"; export var IsComplete: string = "IsComplete"; export var IsTeamTask: string = "IsTeamTask"; export var Owner: string = "Owner"; export var PercentComplete: string = "PercentComplete"; export var Status: string = "Status"; export var StatusDescription: string = "StatusDescription"; export var TotalWork: string = "TotalWork"; export var Task: string = "Task"; export var MailboxCulture: string = "MailboxCulture"; export var MeetingRequestType: string = "MeetingRequestType"; export var IntendedFreeBusyStatus: string = "IntendedFreeBusyStatus"; export var MeetingRequest: string = "MeetingRequest"; export var MeetingResponse: string = "MeetingResponse"; export var MeetingCancellation: string = "MeetingCancellation"; export var ChangeHighlights: string = "ChangeHighlights"; export var HasLocationChanged: string = "HasLocationChanged"; export var HasStartTimeChanged: string = "HasStartTimeChanged"; export var HasEndTimeChanged: string = "HasEndTimeChanged"; export var BaseOffset: string = "BaseOffset"; export var Offset: string = "Offset"; export var Standard: string = "Standard"; export var Daylight: string = "Daylight"; export var Time: string = "Time"; export var AbsoluteDate: string = "AbsoluteDate"; export var UnresolvedEntry: string = "UnresolvedEntry"; export var ResolutionSet: string = "ResolutionSet"; export var Resolution: string = "Resolution"; export var DistributionList: string = "DistributionList"; export var DLExpansion: string = "DLExpansion"; export var IndexedFieldURI: string = "IndexedFieldURI"; export var PullSubscriptionRequest: string = "PullSubscriptionRequest"; export var PushSubscriptionRequest: string = "PushSubscriptionRequest"; export var StreamingSubscriptionRequest: string = "StreamingSubscriptionRequest"; export var EventTypes: string = "EventTypes"; export var EventType: string = "EventType"; export var Timeout: string = "Timeout"; export var Watermark: string = "Watermark"; export var SubscriptionId: string = "SubscriptionId"; export var SubscriptionIds: string = "SubscriptionIds"; export var StatusFrequency: string = "StatusFrequency"; export var URL: string = "URL"; export var CallerData: string = "CallerData"; export var Notification: string = "Notification"; export var Notifications: string = "Notifications"; export var PreviousWatermark: string = "PreviousWatermark"; export var MoreEvents: string = "MoreEvents"; export var TimeStamp: string = "TimeStamp"; export var UnreadCount: string = "UnreadCount"; export var OldParentFolderId: string = "OldParentFolderId"; export var CopiedEvent: string = "CopiedEvent"; export var CreatedEvent: string = "CreatedEvent"; export var DeletedEvent: string = "DeletedEvent"; export var ModifiedEvent: string = "ModifiedEvent"; export var MovedEvent: string = "MovedEvent"; export var NewMailEvent: string = "NewMailEvent"; export var StatusEvent: string = "StatusEvent"; export var FreeBusyChangedEvent: string = "FreeBusyChangedEvent"; export var ExchangeImpersonation: string = "ExchangeImpersonation"; export var ConnectingSID: string = "ConnectingSID"; export var OpenAsAdminOrSystemService: string = "OpenAsAdminOrSystemService"; export var LogonType: string = "LogonType"; export var BudgetType: string = "BudgetType"; export var ManagementRole: string = "ManagementRole"; export var UserRoles: string = "UserRoles"; export var ApplicationRoles: string = "ApplicationRoles"; export var Role: string = "Role"; export var SyncFolderId: string = "SyncFolderId"; export var SyncScope: string = "SyncScope"; export var SyncState: string = "SyncState"; export var Ignore: string = "Ignore"; export var MaxChangesReturned: string = "MaxChangesReturned"; export var Changes: string = "Changes"; export var IncludesLastItemInRange: string = "IncludesLastItemInRange"; export var IncludesLastFolderInRange: string = "IncludesLastFolderInRange"; export var Create: string = "Create"; export var Update: string = "Update"; export var Delete: string = "Delete"; export var ReadFlagChange: string = "ReadFlagChange"; export var SearchParameters: string = "SearchParameters"; export var SoftDeleted: string = "SoftDeleted"; export var Shallow: string = "Shallow"; export var Associated: string = "Associated"; export var BaseFolderId: string = "BaseFolderId"; export var BaseFolderIds: string = "BaseFolderIds"; export var SortOrder: string = "SortOrder"; export var FieldOrder: string = "FieldOrder"; export var CanDelete: string = "CanDelete"; export var CanRenameOrMove: string = "CanRenameOrMove"; export var MustDisplayComment: string = "MustDisplayComment"; export var HasQuota: string = "HasQuota"; export var IsManagedFoldersRoot: string = "IsManagedFoldersRoot"; export var ManagedFolderId: string = "ManagedFolderId"; export var Comment: string = "Comment"; export var StorageQuota: string = "StorageQuota"; export var FolderSize: string = "FolderSize"; export var HomePage: string = "HomePage"; export var ManagedFolderInformation: string = "ManagedFolderInformation"; export var CalendarView: string = "CalendarView"; export var PostedTime: string = "PostedTime"; export var PostItem: string = "PostItem"; export var RequestServerVersion: string = "RequestServerVersion"; export var PostReplyItem: string = "PostReplyItem"; export var CreateAssociated: string = "CreateAssociated"; export var CreateContents: string = "CreateContents"; export var CreateHierarchy: string = "CreateHierarchy"; export var Modify: string = "Modify"; export var Read: string = "Read"; export var EffectiveRights: string = "EffectiveRights"; export var LastModifiedName: string = "LastModifiedName"; export var LastModifiedTime: string = "LastModifiedTime"; export var ConversationId: string = "ConversationId"; export var UniqueBody: string = "UniqueBody"; export var BodyType: string = "BodyType"; export var NormalizedBodyType: string = "NormalizedBodyType"; export var UniqueBodyType: string = "UniqueBodyType"; export var AttachmentShape: string = "AttachmentShape"; export var UserId: string = "UserId"; export var UserIds: string = "UserIds"; export var CanCreateItems: string = "CanCreateItems"; export var CanCreateSubFolders: string = "CanCreateSubFolders"; export var IsFolderOwner: string = "IsFolderOwner"; export var IsFolderVisible: string = "IsFolderVisible"; export var IsFolderContact: string = "IsFolderContact"; export var EditItems: string = "EditItems"; export var DeleteItems: string = "DeleteItems"; export var ReadItems: string = "ReadItems"; export var PermissionLevel: string = "PermissionLevel"; export var CalendarPermissionLevel: string = "CalendarPermissionLevel"; export var SID: string = "SID"; export var PrimarySmtpAddress: string = "PrimarySmtpAddress"; export var DistinguishedUser: string = "DistinguishedUser"; export var PermissionSet: string = "PermissionSet"; export var Permissions: string = "Permissions"; export var Permission: string = "Permission"; export var CalendarPermissions: string = "CalendarPermissions"; export var CalendarPermission: string = "CalendarPermission"; export var GroupBy: string = "GroupBy"; export var AggregateOn: string = "AggregateOn"; export var Groups: string = "Groups"; export var GroupedItems: string = "GroupedItems"; export var GroupIndex: string = "GroupIndex"; export var ConflictResults: string = "ConflictResults"; export var Count: string = "Count"; export var OofSettings: string = "OofSettings"; export var UserOofSettings: string = "UserOofSettings"; export var OofState: string = "OofState"; export var ExternalAudience: string = "ExternalAudience"; export var AllowExternalOof: string = "AllowExternalOof"; export var InternalReply: string = "InternalReply"; export var ExternalReply: string = "ExternalReply"; export var Bias: string = "Bias"; export var DayOrder: string = "DayOrder"; export var Year: string = "Year"; export var StandardTime: string = "StandardTime"; export var DaylightTime: string = "DaylightTime"; export var MailboxData: string = "MailboxData"; export var MailboxDataArray: string = "MailboxDataArray"; export var Email: string = "Email"; export var AttendeeType: string = "AttendeeType"; export var ExcludeConflicts: string = "ExcludeConflicts"; export var FreeBusyViewOptions: string = "FreeBusyViewOptions"; export var SuggestionsViewOptions: string = "SuggestionsViewOptions"; export var FreeBusyView: string = "FreeBusyView"; export var TimeWindow: string = "TimeWindow"; export var MergedFreeBusyIntervalInMinutes: string = "MergedFreeBusyIntervalInMinutes"; export var RequestedView: string = "RequestedView"; export var FreeBusyViewType: string = "FreeBusyViewType"; export var CalendarEventArray: string = "CalendarEventArray"; export var CalendarEvent: string = "CalendarEvent"; export var BusyType: string = "BusyType"; export var MergedFreeBusy: string = "MergedFreeBusy"; export var WorkingHours: string = "WorkingHours"; export var WorkingPeriodArray: string = "WorkingPeriodArray"; export var WorkingPeriod: string = "WorkingPeriod"; export var StartTimeInMinutes: string = "StartTimeInMinutes"; export var EndTimeInMinutes: string = "EndTimeInMinutes"; export var GoodThreshold: string = "GoodThreshold"; export var MaximumResultsByDay: string = "MaximumResultsByDay"; export var MaximumNonWorkHourResultsByDay: string = "MaximumNonWorkHourResultsByDay"; export var MeetingDurationInMinutes: string = "MeetingDurationInMinutes"; export var MinimumSuggestionQuality: string = "MinimumSuggestionQuality"; export var DetailedSuggestionsWindow: string = "DetailedSuggestionsWindow"; export var CurrentMeetingTime: string = "CurrentMeetingTime"; export var GlobalObjectId: string = "GlobalObjectId"; export var SuggestionDayResultArray: string = "SuggestionDayResultArray"; export var SuggestionDayResult: string = "SuggestionDayResult"; export var Date: string = "Date"; export var DayQuality: string = "DayQuality"; export var SuggestionArray: string = "SuggestionArray"; export var Suggestion: string = "Suggestion"; export var MeetingTime: string = "MeetingTime"; export var IsWorkTime: string = "IsWorkTime"; export var SuggestionQuality: string = "SuggestionQuality"; export var AttendeeConflictDataArray: string = "AttendeeConflictDataArray"; export var UnknownAttendeeConflictData: string = "UnknownAttendeeConflictData"; export var TooBigGroupAttendeeConflictData: string = "TooBigGroupAttendeeConflictData"; export var IndividualAttendeeConflictData: string = "IndividualAttendeeConflictData"; export var GroupAttendeeConflictData: string = "GroupAttendeeConflictData"; export var NumberOfMembers: string = "NumberOfMembers"; export var NumberOfMembersAvailable: string = "NumberOfMembersAvailable"; export var NumberOfMembersWithConflict: string = "NumberOfMembersWithConflict"; export var NumberOfMembersWithNoData: string = "NumberOfMembersWithNoData"; export var SourceIds: string = "SourceIds"; export var AlternateId: string = "AlternateId"; export var AlternatePublicFolderId: string = "AlternatePublicFolderId"; export var AlternatePublicFolderItemId: string = "AlternatePublicFolderItemId"; export var DelegatePermissions: string = "DelegatePermissions"; export var ReceiveCopiesOfMeetingMessages: string = "ReceiveCopiesOfMeetingMessages"; export var ViewPrivateItems: string = "ViewPrivateItems"; export var CalendarFolderPermissionLevel: string = "CalendarFolderPermissionLevel"; export var TasksFolderPermissionLevel: string = "TasksFolderPermissionLevel"; export var InboxFolderPermissionLevel: string = "InboxFolderPermissionLevel"; export var ContactsFolderPermissionLevel: string = "ContactsFolderPermissionLevel"; export var NotesFolderPermissionLevel: string = "NotesFolderPermissionLevel"; export var JournalFolderPermissionLevel: string = "JournalFolderPermissionLevel"; export var DelegateUser: string = "DelegateUser"; export var DelegateUsers: string = "DelegateUsers"; export var DeliverMeetingRequests: string = "DeliverMeetingRequests"; export var MessageXml: string = "MessageXml"; export var UserConfiguration: string = "UserConfiguration"; export var UserConfigurationName: string = "UserConfigurationName"; export var UserConfigurationProperties: string = "UserConfigurationProperties"; export var Dictionary: string = "Dictionary"; export var DictionaryEntry: string = "DictionaryEntry"; export var DictionaryKey: string = "DictionaryKey"; export var DictionaryValue: string = "DictionaryValue"; export var XmlData: string = "XmlData"; export var BinaryData: string = "BinaryData"; export var FilterHtmlContent: string = "FilterHtmlContent"; export var ConvertHtmlCodePageToUTF8: string = "ConvertHtmlCodePageToUTF8"; export var UnknownEntries: string = "UnknownEntries"; export var UnknownEntry: string = "UnknownEntry"; export var PasswordExpirationDate: string = "PasswordExpirationDate"; export var Flag: string = "Flag"; export var PersonaPostalAddress: string = "PostalAddress"; export var PostalAddressType: string = "Type"; export var EnhancedLocation: string = "EnhancedLocation"; export var LocationDisplayName: string = "DisplayName"; export var LocationAnnotation: string = "Annotation"; export var LocationSource: string = "LocationSource"; export var LocationUri: string = "LocationUri"; export var Latitude: string = "Latitude"; export var Longitude: string = "Longitude"; export var Accuracy: string = "Accuracy"; export var Altitude: string = "Altitude"; export var AltitudeAccuracy: string = "AltitudeAccuracy"; export var FormattedAddress: string = "FormattedAddress"; export var Guid: string = "Guid"; export var PhoneCallId: string = "PhoneCallId"; export var DialString: string = "DialString"; export var PhoneCallInformation: string = "PhoneCallInformation"; export var PhoneCallState: string = "PhoneCallState"; export var ConnectionFailureCause: string = "ConnectionFailureCause"; export var SIPResponseCode: string = "SIPResponseCode"; export var SIPResponseText: string = "SIPResponseText"; export var WebClientReadFormQueryString: string = "WebClientReadFormQueryString"; export var WebClientEditFormQueryString: string = "WebClientEditFormQueryString"; export var Ids: string = "Ids"; export var Id: string = "Id"; export var TimeZoneDefinitions: string = "TimeZoneDefinitions"; export var TimeZoneDefinition: string = "TimeZoneDefinition"; export var Periods: string = "Periods"; export var Period: string = "Period"; export var TransitionsGroups: string = "TransitionsGroups"; export var TransitionsGroup: string = "TransitionsGroup"; export var Transitions: string = "Transitions"; export var Transition: string = "Transition"; export var AbsoluteDateTransition: string = "AbsoluteDateTransition"; export var RecurringDayTransition: string = "RecurringDayTransition"; export var RecurringDateTransition: string = "RecurringDateTransition"; export var DateTime: string = "DateTime"; export var TimeOffset: string = "TimeOffset"; export var Day: string = "Day"; export var TimeZoneContext: string = "TimeZoneContext"; export var StartTimeZone: string = "StartTimeZone"; export var EndTimeZone: string = "EndTimeZone"; export var ReceivedBy: string = "ReceivedBy"; export var ReceivedRepresenting: string = "ReceivedRepresenting"; export var Uid: string = "UID"; export var RecurrenceId: string = "RecurrenceId"; export var DateTimeStamp: string = "DateTimeStamp"; export var IsInline: string = "IsInline"; export var IsContactPhoto: string = "IsContactPhoto"; export var QueryString: string = "QueryString"; export var HighlightTerms: string = "HighlightTerms"; export var HighlightTerm: string = "Term"; export var HighlightTermScope: string = "Scope"; export var HighlightTermValue: string = "Value"; export var CalendarEventDetails: string = "CalendarEventDetails"; export var ID: string = "ID"; export var IsException: string = "IsException"; export var IsReminderSet: string = "IsReminderSet"; export var IsPrivate: string = "IsPrivate"; export var FirstDayOfWeek: string = "FirstDayOfWeek"; export var Verb: string = "Verb"; export var Parameter: string = "Parameter"; export var ReturnValue: string = "ReturnValue"; export var ReturnNewItemIds: string = "ReturnNewItemIds"; export var DateTimePrecision: string = "DateTimePrecision"; export var ConvertInlineImagesToDataUrls: string = "ConvertInlineImagesToDataUrls"; export var InlineImageUrlTemplate: string = "InlineImageUrlTemplate"; export var BlockExternalImages: string = "BlockExternalImages"; export var AddBlankTargetToLinks: string = "AddBlankTargetToLinks"; export var MaximumBodySize: string = "MaximumBodySize"; export var StoreEntryId: string = "StoreEntryId"; export var InstanceKey: string = "InstanceKey"; export var NormalizedBody: string = "NormalizedBody"; export var PolicyTag: string = "PolicyTag"; export var ArchiveTag: string = "ArchiveTag"; export var RetentionDate: string = "RetentionDate"; export var DisableReason: string = "DisableReason"; export var AppMarketplaceUrl: string = "AppMarketplaceUrl"; export var TextBody: string = "TextBody"; export var IconIndex: string = "IconIndex"; export var GlobalIconIndex: string = "GlobalIconIndex"; export var DraftItemIds: string = "DraftItemIds"; export var HasIrm: string = "HasIrm"; export var GlobalHasIrm: string = "GlobalHasIrm"; export var ApprovalRequestData: string = "ApprovalRequestData"; export var IsUndecidedApprovalRequest: string = "IsUndecidedApprovalRequest"; export var ApprovalDecision: string = "ApprovalDecision"; export var ApprovalDecisionMaker: string = "ApprovalDecisionMaker"; export var ApprovalDecisionTime: string = "ApprovalDecisionTime"; export var VotingOptionData: string = "VotingOptionData"; export var VotingOptionDisplayName: string = "DisplayName"; export var SendPrompt: string = "SendPrompt"; export var VotingInformation: string = "VotingInformation"; export var UserOptions: string = "UserOptions"; export var VotingResponse: string = "VotingResponse"; export var NumberOfDays: string = "NumberOfDays"; export var AcceptanceState: string = "AcceptanceState"; export var NlgEntityExtractionResult: string = "EntityExtractionResult"; export var NlgAddresses: string = "Addresses"; export var NlgAddress: string = "Address"; export var NlgMeetingSuggestions: string = "MeetingSuggestions"; export var NlgMeetingSuggestion: string = "MeetingSuggestion"; export var NlgTaskSuggestions: string = "TaskSuggestions"; export var NlgTaskSuggestion: string = "TaskSuggestion"; export var NlgBusinessName: string = "BusinessName"; export var NlgPeopleName: string = "PeopleName"; export var NlgEmailAddresses: string = "EmailAddresses"; export var NlgEmailAddress: string = "EmailAddress"; export var NlgEmailPosition: string = "Position"; export var NlgContacts: string = "Contacts"; export var NlgContact: string = "Contact"; export var NlgContactString: string = "ContactString"; export var NlgUrls: string = "Urls"; export var NlgUrl: string = "Url"; export var NlgPhoneNumbers: string = "PhoneNumbers"; export var NlgPhone: string = "Phone"; export var NlgAttendees: string = "Attendees"; export var NlgEmailUser: string = "EmailUser"; export var NlgLocation: string = "Location"; export var NlgSubject: string = "Subject"; export var NlgMeetingString: string = "MeetingString"; export var NlgStartTime: string = "StartTime"; export var NlgEndTime: string = "EndTime"; export var NlgTaskString: string = "TaskString"; export var NlgAssignees: string = "Assignees"; export var NlgPersonName: string = "PersonName"; export var NlgOriginalPhoneString: string = "OriginalPhoneString"; export var NlgPhoneString: string = "PhoneString"; export var NlgType: string = "Type"; export var NlgName: string = "Name"; export var NlgUserId: string = "UserId"; export var GetClientAccessToken: string = "GetClientAccessToken"; export var GetClientAccessTokenResponse: string = "GetClientAccessTokenResponse"; export var GetClientAccessTokenResponseMessage: string = "GetClientAccessTokenResponseMessage"; export var TokenRequests: string = "TokenRequests"; export var TokenRequest: string = "TokenRequest"; export var TokenType: string = "TokenType"; export var TokenValue: string = "TokenValue"; export var TTL: string = "TTL"; export var Tokens: string = "Tokens"; export var MarkAsJunk: string = "MarkAsJunk"; export var MarkAsJunkResponse: string = "MarkAsJunkResponse"; export var MarkAsJunkResponseMessage: string = "MarkAsJunkResponseMessage"; export var MovedItemId: string = "MovedItemId"; /* #region Persona */ export var CreationTime: string = "CreationTime"; export var People: string = "People"; export var Persona: string = "Persona"; export var PersonaId: string = "PersonaId"; export var PersonaShape: string = "PersonaShape"; export var RelevanceScore: string = "RelevanceScore"; export var TotalNumberOfPeopleInView: string = "TotalNumberOfPeopleInView"; export var FirstMatchingRowIndex: string = "FirstMatchingRowIndex"; export var FirstLoadedRowIndex: string = "FirstLoadedRowIndex"; export var YomiCompanyName: string = "YomiCompanyName"; export var Emails1: string = "Emails1"; export var Emails2: string = "Emails2"; export var Emails3: string = "Emails3"; export var HomeAddresses: string = "HomeAddresses"; export var BusinessAddresses: string = "BusinessAddresses"; export var OtherAddresses: string = "OtherAddresses"; export var BusinessPhoneNumbers: string = "BusinessPhoneNumbers"; export var BusinessPhoneNumbers2: string = "BusinessPhoneNumbers2"; export var AssistantPhoneNumbers: string = "AssistantPhoneNumbers"; export var TTYTDDPhoneNumbers: string = "TTYTDDPhoneNumbers"; export var HomePhones: string = "HomePhones"; export var HomePhones2: string = "HomePhones2"; export var MobilePhones: string = "MobilePhones"; export var MobilePhones2: string = "MobilePhones2"; export var CallbackPhones: string = "CallbackPhones"; export var CarPhones: string = "CarPhones"; export var HomeFaxes: string = "HomeFaxes"; export var OrganizationMainPhones: string = "OrganizationMainPhones"; export var OtherFaxes: string = "OtherFaxes"; export var OtherTelephones: string = "OtherTelephones"; export var OtherPhones2: string = "OtherPhones2"; export var Pagers: string = "Pagers"; export var RadioPhones: string = "RadioPhones"; export var TelexNumbers: string = "TelexNumbers"; export var WorkFaxes: string = "WorkFaxes"; export var FileAses: string = "FileAses"; export var CompanyNames: string = "CompanyNames"; export var DisplayNames: string = "DisplayNames"; export var DisplayNamePrefixes: string = "DisplayNamePrefixes"; export var GivenNames: string = "GivenNames"; export var MiddleNames: string = "MiddleNames"; export var Surnames: string = "Surnames"; export var Generations: string = "Generations"; export var Nicknames: string = "Nicknames"; export var YomiCompanyNames: string = "YomiCompanyNames"; export var YomiFirstNames: string = "YomiFirstNames"; export var YomiLastNames: string = "YomiLastNames"; export var Managers: string = "Managers"; export var AssistantNames: string = "AssistantNames"; export var Professions: string = "Professions"; export var SpouseNames: string = "SpouseNames"; export var Departments: string = "Departments"; export var Titles: string = "Titles"; export var ImAddresses2: string = "ImAddresses2"; export var ImAddresses3: string = "ImAddresses3"; export var DisplayNamePrefix: string = "DisplayNamePrefix"; export var DisplayNameFirstLast: string = "DisplayNameFirstLast"; export var DisplayNameLastFirst: string = "DisplayNameLastFirst"; export var DisplayNameFirstLastHeader: string = "DisplayNameFirstLastHeader"; export var DisplayNameLastFirstHeader: string = "DisplayNameLastFirstHeader"; export var IsFavorite: string = "IsFavorite"; export var Schools: string = "Schools"; export var Hobbies: string = "Hobbies"; export var Locations: string = "Locations"; export var OfficeLocations: string = "OfficeLocations"; export var BusinessHomePages: string = "BusinessHomePages"; export var PersonalHomePages: string = "PersonalHomePages"; export var ThirdPartyPhotoUrls: string = "ThirdPartyPhotoUrls"; export var Attribution: string = "Attribution"; export var Attributions: string = "Attributions"; export var StringAttributedValue: string = "StringAttributedValue"; export var DisplayNameFirstLastSortKey: string = "DisplayNameFirstLastSortKey"; export var DisplayNameLastFirstSortKey: string = "DisplayNameLastFirstSortKey"; export var CompanyNameSortKey: string = "CompanyNameSortKey"; export var HomeCitySortKey: string = "HomeCitySortKey"; export var WorkCitySortKey: string = "WorkCitySortKey"; export var FileAsId: string = "FileAsId"; export var FileAsIds: string = "FileAsIds"; export var HomeCity: string = "HomeCity"; export var WorkCity: string = "WorkCity"; export var PersonaType: string = "PersonaType"; export var Birthdays: string = "Birthdays"; export var BirthdaysLocal: string = "BirthdaysLocal"; export var WeddingAnniversaries: string = "WeddingAnniversaries"; export var WeddingAnniversariesLocal: string = "WeddingAnniversariesLocal"; export var OriginalDisplayName: string = "OriginalDisplayName"; /* #endregion */ /* #region People Insights */ export var Person: string = "Person"; export var Insights: string = "Insights"; export var Insight: string = "Insight"; export var InsightGroupType: string = "InsightGroupType"; export var InsightType: string = "InsightType"; export var InsightSourceType: string = "InsightSourceType"; export var InsightValue: string = "InsightValue"; export var InsightSource: string = "InsightSource"; export var UpdatedUtcTicks: string = "UpdatedUtcTicks"; export var StringInsightValue: string = "StringInsightValue"; export var ProfileInsightValue: string = "ProfileInsightValue"; export var JobInsightValue: string = "JobInsightValue"; export var UserProfilePicture: string = "UserProfilePicture"; export var EducationInsightValue: string = "EducationInsightValue"; export var SkillInsightValue: string = "SkillInsightValue"; export var DelveDoc: string = "DelveDoc"; export var CompanyInsightValue: string = "CompanyInsightValue"; export var ArrayOfInsightValue: string = "ArrayOfInsightValue"; export var InsightContent: string = "InsightContent"; export var SingleValueInsightContent: string = "SingleValueInsightContent"; export var MultiValueInsightContent: string = "MultiValueInsightContent"; export var ArrayOfInsight: string = "ArrayOfInsight"; export var PersonType: string = "PersonType"; export var SatoriId: string = "SatoriId"; export var DescriptionAttribution: string = "DescriptionAttribution"; export var ImageUrl: string = "ImageUrl"; export var ImageUrlAttribution: string = "ImageUrlAttribution"; export var YearFound: string = "YearFound"; export var FinanceSymbol: string = "FinanceSymbol"; export var WebsiteUrl: string = "WebsiteUrl"; export var Rank: string = "Rank"; export var Author: string = "Author"; export var Created: string = "Created"; export var DefaultEncodingURL: string = "DefaultEncodingURL"; export var FileType: string = "FileType"; export var Data: string = "Data"; export var ItemList: string = "ItemList"; export var Avatar: string = "Avatar"; export var JoinedUtcTicks: string = "JoinedUtcTicks"; export var Company: string = "Company"; export var StartUtcTicks: string = "StartUtcTicks"; export var EndUtcTicks: string = "EndUtcTicks"; export var Blob: string = "Blob"; export var PhotoSize: string = "PhotoSize"; export var Institute: string = "Institute"; export var Degree: string = "Degree"; export var Strength: string = "Strength"; /* #endregion */ /* #region Conversations */ export var Conversations: string = "Conversations"; export var Conversation: string = "Conversation"; export var UniqueRecipients: string = "UniqueRecipients"; export var GlobalUniqueRecipients: string = "GlobalUniqueRecipients"; export var UniqueUnreadSenders: string = "UniqueUnreadSenders"; export var GlobalUniqueUnreadSenders: string = "GlobalUniqueUnreadSenders"; export var UniqueSenders: string = "UniqueSenders"; export var GlobalUniqueSenders: string = "GlobalUniqueSenders"; export var LastDeliveryTime: string = "LastDeliveryTime"; export var GlobalLastDeliveryTime: string = "GlobalLastDeliveryTime"; export var GlobalCategories: string = "GlobalCategories"; export var FlagStatus: string = "FlagStatus"; export var GlobalFlagStatus: string = "GlobalFlagStatus"; export var GlobalHasAttachments: string = "GlobalHasAttachments"; export var MessageCount: string = "MessageCount"; export var GlobalMessageCount: string = "GlobalMessageCount"; export var GlobalUnreadCount: string = "GlobalUnreadCount"; export var GlobalSize: string = "GlobalSize"; export var ItemClasses: string = "ItemClasses"; export var GlobalItemClasses: string = "GlobalItemClasses"; export var GlobalImportance: string = "GlobalImportance"; export var GlobalInferredImportance: string = "GlobalInferredImportance"; export var GlobalItemIds: string = "GlobalItemIds"; export var ChangeType: string = "ChangeType"; export var ReadFlag: string = "ReadFlag"; export var TotalConversationsInView: string = "TotalConversationsInView"; export var IndexedOffset: string = "IndexedOffset"; export var ConversationShape: string = "ConversationShape"; export var MailboxScope: string = "MailboxScope"; // ApplyConversationAction export var ApplyConversationAction: string = "ApplyConversationAction"; export var ConversationActions: string = "ConversationActions"; export var ConversationAction: string = "ConversationAction"; export var ApplyConversationActionResponse: string = "ApplyConversationActionResponse"; export var ApplyConversationActionResponseMessage: string = "ApplyConversationActionResponseMessage"; export var EnableAlwaysDelete: string = "EnableAlwaysDelete"; export var ProcessRightAway: string = "ProcessRightAway"; export var DestinationFolderId: string = "DestinationFolderId"; export var ContextFolderId: string = "ContextFolderId"; export var ConversationLastSyncTime: string = "ConversationLastSyncTime"; export var AlwaysCategorize: string = "AlwaysCategorize"; export var AlwaysDelete: string = "AlwaysDelete"; export var AlwaysMove: string = "AlwaysMove"; export var Move: string = "Move"; export var Copy: string = "Copy"; export var SetReadState: string = "SetReadState"; export var SetRetentionPolicy: string = "SetRetentionPolicy"; export var DeleteType: string = "DeleteType"; export var RetentionPolicyType: string = "RetentionPolicyType"; export var RetentionPolicyTagId: string = "RetentionPolicyTagId"; // GetConversationItems export var FoldersToIgnore: string = "FoldersToIgnore"; export var ParentInternetMessageId: string = "ParentInternetMessageId"; export var ConversationNode: string = "ConversationNode"; export var ConversationNodes: string = "ConversationNodes"; export var MaxItemsToReturn: string = "MaxItemsToReturn"; /* #endregion */ /* #region TeamMailbox */ export var SetTeamMailbox: string = "SetTeamMailbox"; export var SetTeamMailboxResponse: string = "SetTeamMailboxResponse"; export var UnpinTeamMailbox: string = "UnpinTeamMailbox"; export var UnpinTeamMailboxResponse: string = "UnpinTeamMailboxResponse"; /* #endregion */ /* #region RoomList & Room */ export var RoomLists: string = "RoomLists"; export var Rooms: string = "Rooms"; export var Room: string = "Room"; export var RoomList: string = "RoomList"; export var RoomId: string = "Id"; /* #endregion */ /* #region Autodiscover */ export var Autodiscover: string = "Autodiscover"; export var BinarySecret: string = "BinarySecret"; export var Response: string = "Response"; export var User: string = "User"; export var LegacyDN: string = "LegacyDN"; export var DeploymentId: string = "DeploymentId"; export var Account: string = "Account"; export var AccountType: string = "AccountType"; export var Action: string = "Action"; export var To: string = "To"; export var RedirectAddr: string = "RedirectAddr"; export var RedirectUrl: string = "RedirectUrl"; export var Protocol: string = "Protocol"; export var Type: string = "Type"; export var Server: string = "Server"; export var OwnerSmtpAddress: string = "OwnerSmtpAddress"; export var ServerDN: string = "ServerDN"; export var ServerVersion: string = "ServerVersion"; export var ServerVersionInfo: string = "ServerVersionInfo"; export var AD: string = "AD"; export var AuthPackage: string = "AuthPackage"; export var MdbDN: string = "MdbDN"; export var EWSUrl: string = "EwsUrl"; // Server side emits "Ews", not "EWS". export var EwsPartnerUrl: string = "EwsPartnerUrl"; export var EmwsUrl: string = "EmwsUrl"; export var ASUrl: string = "ASUrl"; export var OOFUrl: string = "OOFUrl"; export var UMUrl: string = "UMUrl"; export var OABUrl: string = "OABUrl"; export var Internal: string = "Internal"; export var External: string = "External"; export var OWAUrl: string = "OWAUrl"; export var Error: string = "Error"; export var ErrorCode: string = "ErrorCode"; export var DebugData: string = "DebugData"; export var Users: string = "Users"; export var RequestedSettings: string = "RequestedSettings"; export var Setting: string = "Setting"; export var GetUserSettingsRequestMessage: string = "GetUserSettingsRequestMessage"; export var RequestedServerVersion: string = "RequestedServerVersion"; export var Request: string = "Request"; export var RedirectTarget: string = "RedirectTarget"; export var UserSettings: string = "UserSettings"; export var UserSettingErrors: string = "UserSettingErrors"; export var GetUserSettingsResponseMessage: string = "GetUserSettingsResponseMessage"; export var ErrorMessage: string = "ErrorMessage"; export var UserResponse: string = "UserResponse"; export var UserResponses: string = "UserResponses"; export var UserSettingError: string = "UserSettingError"; export var Domain: string = "Domain"; export var Domains: string = "Domains"; export var DomainResponse: string = "DomainResponse"; export var DomainResponses: string = "DomainResponses"; export var DomainSetting: string = "DomainSetting"; export var DomainSettings: string = "DomainSettings"; export var DomainStringSetting: string = "DomainStringSetting"; export var DomainSettingError: string = "DomainSettingError"; export var DomainSettingErrors: string = "DomainSettingErrors"; export var GetDomainSettingsRequestMessage: string = "GetDomainSettingsRequestMessage"; export var GetDomainSettingsResponseMessage: string = "GetDomainSettingsResponseMessage"; export var SettingName: string = "SettingName"; export var UserSetting: string = "UserSetting"; export var StringSetting: string = "StringSetting"; export var WebClientUrlCollectionSetting: string = "WebClientUrlCollectionSetting"; export var WebClientUrls: string = "WebClientUrls"; export var WebClientUrl: string = "WebClientUrl"; export var AuthenticationMethods: string = "AuthenticationMethods"; export var Url: string = "Url"; export var AlternateMailboxCollectionSetting: string = "AlternateMailboxCollectionSetting"; export var AlternateMailboxes: string = "AlternateMailboxes"; export var AlternateMailbox: string = "AlternateMailbox"; export var ProtocolConnectionCollectionSetting: string = "ProtocolConnectionCollectionSetting"; export var ProtocolConnections: string = "ProtocolConnections"; export var ProtocolConnection: string = "ProtocolConnection"; export var DocumentSharingLocationCollectionSetting: string = "DocumentSharingLocationCollectionSetting"; export var DocumentSharingLocations: string = "DocumentSharingLocations"; export var DocumentSharingLocation: string = "DocumentSharingLocation"; export var ServiceUrl: string = "ServiceUrl"; export var LocationUrl: string = "LocationUrl"; export var SupportedFileExtensions: string = "SupportedFileExtensions"; export var FileExtension: string = "FileExtension"; export var ExternalAccessAllowed: string = "ExternalAccessAllowed"; export var AnonymousAccessAllowed: string = "AnonymousAccessAllowed"; export var CanModifyPermissions: string = "CanModifyPermissions"; export var IsDefault: string = "IsDefault"; export var EncryptionMethod: string = "EncryptionMethod"; export var Hostname: string = "Hostname"; export var Port: string = "Port"; export var Version: string = "Version"; export var MajorVersion: string = "MajorVersion"; export var MinorVersion: string = "MinorVersion"; export var MajorBuildNumber: string = "MajorBuildNumber"; export var MinorBuildNumber: string = "MinorBuildNumber"; export var RequestedVersion: string = "RequestedVersion"; export var PublicFolderServer: string = "PublicFolderServer"; export var Ssl: string = "SSL"; export var SharingUrl: string = "SharingUrl"; export var EcpUrl: string = "EcpUrl"; export var EcpUrl_um: string = "EcpUrl-um"; export var EcpUrl_aggr: string = "EcpUrl-aggr"; export var EcpUrl_sms: string = "EcpUrl-sms"; export var EcpUrl_mt: string = "EcpUrl-mt"; export var EcpUrl_ret: string = "EcpUrl-ret"; export var EcpUrl_publish: string = "EcpUrl-publish"; export var EcpUrl_photo: string = "EcpUrl-photo"; export var ExchangeRpcUrl: string = "ExchangeRpcUrl"; export var EcpUrl_connect: string = "EcpUrl-connect"; export var EcpUrl_tm: string = "EcpUrl-tm"; export var EcpUrl_tmCreating: string = "EcpUrl-tmCreating"; export var EcpUrl_tmEditing: string = "EcpUrl-tmEditing"; export var EcpUrl_tmHiding: string = "EcpUrl-tmHiding"; export var SiteMailboxCreationURL: string = "SiteMailboxCreationURL"; export var EcpUrl_extinstall: string = "EcpUrl-extinstall"; export var PartnerToken: string = "PartnerToken"; export var PartnerTokenReference: string = "PartnerTokenReference"; export var ServerExclusiveConnect: string = "ServerExclusiveConnect"; export var AutoDiscoverSMTPAddress: string = "AutoDiscoverSMTPAddress"; export var CertPrincipalName: string = "CertPrincipalName"; export var GroupingInformation: string = "GroupingInformation"; /* #endregion */ /* #region InboxRule */ export var MailboxSmtpAddress: string = "MailboxSmtpAddress"; export var RuleId: string = "RuleId"; export var Priority: string = "Priority"; export var IsEnabled: string = "IsEnabled"; export var IsNotSupported: string = "IsNotSupported"; export var IsInError: string = "IsInError"; export var Conditions: string = "Conditions"; export var Exceptions: string = "Exceptions"; export var Actions: string = "Actions"; export var InboxRules: string = "InboxRules"; export var Rule: string = "Rule"; export var OutlookRuleBlobExists: string = "OutlookRuleBlobExists"; export var RemoveOutlookRuleBlob: string = "RemoveOutlookRuleBlob"; export var ContainsBodyStrings: string = "ContainsBodyStrings"; export var ContainsHeaderStrings: string = "ContainsHeaderStrings"; export var ContainsRecipientStrings: string = "ContainsRecipientStrings"; export var ContainsSenderStrings: string = "ContainsSenderStrings"; export var ContainsSubjectOrBodyStrings: string = "ContainsSubjectOrBodyStrings"; export var ContainsSubjectStrings: string = "ContainsSubjectStrings"; export var FlaggedForAction: string = "FlaggedForAction"; export var FromAddresses: string = "FromAddresses"; export var FromConnectedAccounts: string = "FromConnectedAccounts"; export var IsApprovalRequest: string = "IsApprovalRequest"; export var IsAutomaticForward: string = "IsAutomaticForward"; export var IsAutomaticReply: string = "IsAutomaticReply"; export var IsEncrypted: string = "IsEncrypted"; export var IsMeetingRequest: string = "IsMeetingRequest"; export var IsMeetingResponse: string = "IsMeetingResponse"; export var IsNDR: string = "IsNDR"; export var IsPermissionControlled: string = "IsPermissionControlled"; export var IsSigned: string = "IsSigned"; export var IsVoicemail: string = "IsVoicemail"; export var IsReadReceipt: string = "IsReadReceipt"; export var MessageClassifications: string = "MessageClassifications"; export var NotSentToMe: string = "NotSentToMe"; export var SentCcMe: string = "SentCcMe"; export var SentOnlyToMe: string = "SentOnlyToMe"; export var SentToAddresses: string = "SentToAddresses"; export var SentToMe: string = "SentToMe"; export var SentToOrCcMe: string = "SentToOrCcMe"; export var WithinDateRange: string = "WithinDateRange"; export var WithinSizeRange: string = "WithinSizeRange"; export var MinimumSize: string = "MinimumSize"; export var MaximumSize: string = "MaximumSize"; export var StartDateTime: string = "StartDateTime"; export var EndDateTime: string = "EndDateTime"; export var AssignCategories: string = "AssignCategories"; export var CopyToFolder: string = "CopyToFolder"; export var FlagMessage: string = "FlagMessage"; export var ForwardAsAttachmentToRecipients: string = "ForwardAsAttachmentToRecipients"; export var ForwardToRecipients: string = "ForwardToRecipients"; export var MarkImportance: string = "MarkImportance"; export var MarkAsRead: string = "MarkAsRead"; export var MoveToFolder: string = "MoveToFolder"; export var PermanentDelete: string = "PermanentDelete"; export var RedirectToRecipients: string = "RedirectToRecipients"; export var SendSMSAlertToRecipients: string = "SendSMSAlertToRecipients"; export var ServerReplyWithMessage: string = "ServerReplyWithMessage"; export var StopProcessingRules: string = "StopProcessingRules"; export var CreateRuleOperation: string = "CreateRuleOperation"; export var SetRuleOperation: string = "SetRuleOperation"; export var DeleteRuleOperation: string = "DeleteRuleOperation"; export var Operations: string = "Operations"; export var RuleOperationErrors: string = "RuleOperationErrors"; export var RuleOperationError: string = "RuleOperationError"; export var OperationIndex: string = "OperationIndex"; export var ValidationErrors: string = "ValidationErrors"; export var FieldValue: string = "FieldValue"; /* #endregion */ /* #region Restrictions */ export var Not: string = "Not"; export var Bitmask: string = "Bitmask"; export var Constant: string = "Constant"; export var Restriction: string = "Restriction"; export var Condition: string = "Condition"; export var Contains: string = "Contains"; export var Excludes: string = "Excludes"; export var Exists: string = "Exists"; export var FieldURIOrConstant: string = "FieldURIOrConstant"; export var And: string = "And"; export var Or: string = "Or"; export var IsEqualTo: string = "IsEqualTo"; export var IsNotEqualTo: string = "IsNotEqualTo"; export var IsGreaterThan: string = "IsGreaterThan"; export var IsGreaterThanOrEqualTo: string = "IsGreaterThanOrEqualTo"; export var IsLessThan: string = "IsLessThan"; export var IsLessThanOrEqualTo: string = "IsLessThanOrEqualTo"; /* #endregion */ /* #region Directory only contact properties */ export var PhoneticFullName: string = "PhoneticFullName"; export var PhoneticFirstName: string = "PhoneticFirstName"; export var PhoneticLastName: string = "PhoneticLastName"; export var Alias: string = "Alias"; export var Notes: string = "Notes"; export var Photo: string = "Photo"; export var UserSMIMECertificate: string = "UserSMIMECertificate"; export var MSExchangeCertificate: string = "MSExchangeCertificate"; export var DirectoryId: string = "DirectoryId"; export var ManagerMailbox: string = "ManagerMailbox"; export var DirectReports: string = "DirectReports"; /* #endregion */ /* #region Photos */ export var SizeRequested: string = "SizeRequested"; export var HasChanged: string = "HasChanged"; export var PictureData: string = "PictureData"; /* #endregion */ /* #region Request/response element names */ export var ResponseMessage: string = "ResponseMessage"; export var ResponseMessages: string = "ResponseMessages"; // FindConversation export var FindConversation: string = "FindConversation"; export var FindConversationResponse: string = "FindConversationResponse"; export var FindConversationResponseMessage: string = "FindConversationResponseMessage"; // GetConversationItems export var GetConversationItems: string = "GetConversationItems"; export var GetConversationItemsResponse: string = "GetConversationItemsResponse"; export var GetConversationItemsResponseMessage: string = "GetConversationItemsResponseMessage"; // FindItem export var FindItem: string = "FindItem"; export var FindItemResponse: string = "FindItemResponse"; export var FindItemResponseMessage: string = "FindItemResponseMessage"; // GetItem export var GetItem: string = "GetItem"; export var GetItemResponse: string = "GetItemResponse"; export var GetItemResponseMessage: string = "GetItemResponseMessage"; // CreateItem export var CreateItem: string = "CreateItem"; export var CreateItemResponse: string = "CreateItemResponse"; export var CreateItemResponseMessage: string = "CreateItemResponseMessage"; // SendItem export var SendItem: string = "SendItem"; export var SendItemResponse: string = "SendItemResponse"; export var SendItemResponseMessage: string = "SendItemResponseMessage"; // DeleteItem export var DeleteItem: string = "DeleteItem"; export var DeleteItemResponse: string = "DeleteItemResponse"; export var DeleteItemResponseMessage: string = "DeleteItemResponseMessage"; // UpdateItem export var UpdateItem: string = "UpdateItem"; export var UpdateItemResponse: string = "UpdateItemResponse"; export var UpdateItemResponseMessage: string = "UpdateItemResponseMessage"; // CopyItem export var CopyItem: string = "CopyItem"; export var CopyItemResponse: string = "CopyItemResponse"; export var CopyItemResponseMessage: string = "CopyItemResponseMessage"; // MoveItem export var MoveItem: string = "MoveItem"; export var MoveItemResponse: string = "MoveItemResponse"; export var MoveItemResponseMessage: string = "MoveItemResponseMessage"; // ArchiveItem export var ArchiveItem: string = "ArchiveItem"; export var ArchiveItemResponse: string = "ArchiveItemResponse"; export var ArchiveItemResponseMessage: string = "ArchiveItemResponseMessage"; export var ArchiveSourceFolderId: string = "ArchiveSourceFolderId"; // FindFolder export var FindFolder: string = "FindFolder"; export var FindFolderResponse: string = "FindFolderResponse"; export var FindFolderResponseMessage: string = "FindFolderResponseMessage"; // GetFolder export var GetFolder: string = "GetFolder"; export var GetFolderResponse: string = "GetFolderResponse"; export var GetFolderResponseMessage: string = "GetFolderResponseMessage"; // CreateFolder export var CreateFolder: string = "CreateFolder"; export var CreateFolderResponse: string = "CreateFolderResponse"; export var CreateFolderResponseMessage: string = "CreateFolderResponseMessage"; // DeleteFolder export var DeleteFolder: string = "DeleteFolder"; export var DeleteFolderResponse: string = "DeleteFolderResponse"; export var DeleteFolderResponseMessage: string = "DeleteFolderResponseMessage"; // EmptyFolder export var EmptyFolder: string = "EmptyFolder"; export var EmptyFolderResponse: string = "EmptyFolderResponse"; export var EmptyFolderResponseMessage: string = "EmptyFolderResponseMessage"; // UpdateFolder export var UpdateFolder: string = "UpdateFolder"; export var UpdateFolderResponse: string = "UpdateFolderResponse"; export var UpdateFolderResponseMessage: string = "UpdateFolderResponseMessage"; // CopyFolder export var CopyFolder: string = "CopyFolder"; export var CopyFolderResponse: string = "CopyFolderResponse"; export var CopyFolderResponseMessage: string = "CopyFolderResponseMessage"; // MoveFolder export var MoveFolder: string = "MoveFolder"; export var MoveFolderResponse: string = "MoveFolderResponse"; export var MoveFolderResponseMessage: string = "MoveFolderResponseMessage"; // MarkAllItemsAsRead export var MarkAllItemsAsRead: string = "MarkAllItemsAsRead"; export var MarkAllItemsAsReadResponse: string = "MarkAllItemsAsReadResponse"; export var MarkAllItemsAsReadResponseMessage: string = "MarkAllItemsAsReadResponseMessage"; // FindPeople export var FindPeople: string = "FindPeople"; export var FindPeopleResponse: string = "FindPeopleResponse"; export var FindPeopleResponseMessage: string = "FindPeopleResponseMessage"; // GetPeopleInsights export var GetPeopleInsights: string = "GetPeopleInsights"; export var GetPeopleInsightsResponse: string = "GetPeopleInsightsResponse"; export var GetPeopleInsightsResponseMessage: string = "GetPeopleInsightsResponseMessage"; // GetUserPhoto export var GetUserPhoto: string = "GetUserPhoto"; export var GetUserPhotoResponse: string = "GetUserPhotoResponse"; export var GetUserPhotoResponseMessage: string = "GetUserPhotoResponseMessage"; // GetAttachment export var GetAttachment: string = "GetAttachment"; export var GetAttachmentResponse: string = "GetAttachmentResponse"; export var GetAttachmentResponseMessage: string = "GetAttachmentResponseMessage"; // CreateAttachment export var CreateAttachment: string = "CreateAttachment"; export var CreateAttachmentResponse: string = "CreateAttachmentResponse"; export var CreateAttachmentResponseMessage: string = "CreateAttachmentResponseMessage"; // DeleteAttachment export var DeleteAttachment: string = "DeleteAttachment"; export var DeleteAttachmentResponse: string = "DeleteAttachmentResponse"; export var DeleteAttachmentResponseMessage: string = "DeleteAttachmentResponseMessage"; // ResolveNames export var ResolveNames: string = "ResolveNames"; export var ResolveNamesResponse: string = "ResolveNamesResponse"; export var ResolveNamesResponseMessage: string = "ResolveNamesResponseMessage"; // ExpandDL export var ExpandDL: string = "ExpandDL"; export var ExpandDLResponse: string = "ExpandDLResponse"; export var ExpandDLResponseMessage: string = "ExpandDLResponseMessage"; // Subscribe export var Subscribe: string = "Subscribe"; export var SubscribeResponse: string = "SubscribeResponse"; export var SubscribeResponseMessage: string = "SubscribeResponseMessage"; export var SubscriptionRequest: string = "SubscriptionRequest"; // Unsubscribe export var Unsubscribe: string = "Unsubscribe"; export var UnsubscribeResponse: string = "UnsubscribeResponse"; export var UnsubscribeResponseMessage: string = "UnsubscribeResponseMessage"; // GetEvents export var GetEvents: string = "GetEvents"; export var GetEventsResponse: string = "GetEventsResponse"; export var GetEventsResponseMessage: string = "GetEventsResponseMessage"; // GetStreamingEvents export var GetStreamingEvents: string = "GetStreamingEvents"; export var GetStreamingEventsResponse: string = "GetStreamingEventsResponse"; export var GetStreamingEventsResponseMessage: string = "GetStreamingEventsResponseMessage"; export var ConnectionStatus: string = "ConnectionStatus"; export var ErrorSubscriptionIds: string = "ErrorSubscriptionIds"; export var ConnectionTimeout: string = "ConnectionTimeout"; export var HeartbeatFrequency: string = "HeartbeatFrequency"; // SyncFolderItems export var SyncFolderItems: string = "SyncFolderItems"; export var SyncFolderItemsResponse: string = "SyncFolderItemsResponse"; export var SyncFolderItemsResponseMessage: string = "SyncFolderItemsResponseMessage"; // SyncFolderHierarchy export var SyncFolderHierarchy: string = "SyncFolderHierarchy"; export var SyncFolderHierarchyResponse: string = "SyncFolderHierarchyResponse"; export var SyncFolderHierarchyResponseMessage: string = "SyncFolderHierarchyResponseMessage"; // GetUserOofSettings export var GetUserOofSettingsRequest: string = "GetUserOofSettingsRequest"; export var GetUserOofSettingsResponse: string = "GetUserOofSettingsResponse"; // SetUserOofSettings export var SetUserOofSettingsRequest: string = "SetUserOofSettingsRequest"; export var SetUserOofSettingsResponse: string = "SetUserOofSettingsResponse"; // GetUserAvailability export var GetUserAvailabilityRequest: string = "GetUserAvailabilityRequest"; export var GetUserAvailabilityResponse: string = "GetUserAvailabilityResponse"; export var FreeBusyResponseArray: string = "FreeBusyResponseArray"; export var FreeBusyResponse: string = "FreeBusyResponse"; export var SuggestionsResponse: string = "SuggestionsResponse"; // GetRoomLists export var GetRoomListsRequest: string = "GetRoomLists"; export var GetRoomListsResponse: string = "GetRoomListsResponse"; // GetRooms export var GetRoomsRequest: string = "GetRooms"; export var GetRoomsResponse: string = "GetRoomsResponse"; // ConvertId export var ConvertId: string = "ConvertId"; export var ConvertIdResponse: string = "ConvertIdResponse"; export var ConvertIdResponseMessage: string = "ConvertIdResponseMessage"; // AddDelegate export var AddDelegate: string = "AddDelegate"; export var AddDelegateResponse: string = "AddDelegateResponse"; export var DelegateUserResponseMessageType: string = "DelegateUserResponseMessageType"; // RemoveDelegte export var RemoveDelegate: string = "RemoveDelegate"; export var RemoveDelegateResponse: string = "RemoveDelegateResponse"; // GetDelegate export var GetDelegate: string = "GetDelegate"; export var GetDelegateResponse: string = "GetDelegateResponse"; // UpdateDelegate export var UpdateDelegate: string = "UpdateDelegate"; export var UpdateDelegateResponse: string = "UpdateDelegateResponse"; // CreateUserConfiguration export var CreateUserConfiguration: string = "CreateUserConfiguration"; export var CreateUserConfigurationResponse: string = "CreateUserConfigurationResponse"; export var CreateUserConfigurationResponseMessage: string = "CreateUserConfigurationResponseMessage"; // DeleteUserConfiguration export var DeleteUserConfiguration: string = "DeleteUserConfiguration"; export var DeleteUserConfigurationResponse: string = "DeleteUserConfigurationResponse"; export var DeleteUserConfigurationResponseMessage: string = "DeleteUserConfigurationResponseMessage"; // GetUserConfiguration export var GetUserConfiguration: string = "GetUserConfiguration"; export var GetUserConfigurationResponse: string = "GetUserConfigurationResponse"; export var GetUserConfigurationResponseMessage: string = "GetUserConfigurationResponseMessage"; // UpdateUserConfiguration export var UpdateUserConfiguration: string = "UpdateUserConfiguration"; export var UpdateUserConfigurationResponse: string = "UpdateUserConfigurationResponse"; export var UpdateUserConfigurationResponseMessage: string = "UpdateUserConfigurationResponseMessage"; // PlayOnPhone export var PlayOnPhone: string = "PlayOnPhone"; export var PlayOnPhoneResponse: string = "PlayOnPhoneResponse"; // GetPhoneCallInformation export var GetPhoneCall: string = "GetPhoneCallInformation"; export var GetPhoneCallResponse: string = "GetPhoneCallInformationResponse"; // DisconnectCall export var DisconnectPhoneCall: string = "DisconnectPhoneCall"; export var DisconnectPhoneCallResponse: string = "DisconnectPhoneCallResponse"; // GetServerTimeZones export var GetServerTimeZones: string = "GetServerTimeZones"; export var GetServerTimeZonesResponse: string = "GetServerTimeZonesResponse"; export var GetServerTimeZonesResponseMessage: string = "GetServerTimeZonesResponseMessage"; // GetInboxRules export var GetInboxRules: string = "GetInboxRules"; export var GetInboxRulesResponse: string = "GetInboxRulesResponse"; // UpdateInboxRules export var UpdateInboxRules: string = "UpdateInboxRules"; export var UpdateInboxRulesResponse: string = "UpdateInboxRulesResponse"; // ExecuteDiagnosticMethod export var ExecuteDiagnosticMethod: string = "ExecuteDiagnosticMethod"; export var ExecuteDiagnosticMethodResponse: string = "ExecuteDiagnosticMethodResponse"; export var ExecuteDiagnosticMethodResponseMEssage: string = "ExecuteDiagnosticMethodResponseMessage"; //GetPasswordExpirationDate export var GetPasswordExpirationDateRequest: string = "GetPasswordExpirationDate"; export var GetPasswordExpirationDateResponse: string = "GetPasswordExpirationDateResponse"; // GetSearchableMailboxes export var GetSearchableMailboxes: string = "GetSearchableMailboxes"; export var GetSearchableMailboxesResponse: string = "GetSearchableMailboxesResponse"; // GetDiscoverySearchConfiguration export var GetDiscoverySearchConfiguration: string = "GetDiscoverySearchConfiguration"; export var GetDiscoverySearchConfigurationResponse: string = "GetDiscoverySearchConfigurationResponse"; // GetHoldOnMailboxes export var GetHoldOnMailboxes: string = "GetHoldOnMailboxes"; export var GetHoldOnMailboxesResponse: string = "GetHoldOnMailboxesResponse"; // SetHoldOnMailboxes export var SetHoldOnMailboxes: string = "SetHoldOnMailboxes"; export var SetHoldOnMailboxesResponse: string = "SetHoldOnMailboxesResponse"; // SearchMailboxes export var SearchMailboxes: string = "SearchMailboxes"; export var SearchMailboxesResponse: string = "SearchMailboxesResponse"; export var SearchMailboxesResponseMessage: string = "SearchMailboxesResponseMessage"; // GetNonIndexableItemDetails export var GetNonIndexableItemDetails: string = "GetNonIndexableItemDetails"; export var GetNonIndexableItemDetailsResponse: string = "GetNonIndexableItemDetailsResponse"; // GetNonIndexableItemStatistics export var GetNonIndexableItemStatistics: string = "GetNonIndexableItemStatistics"; export var GetNonIndexableItemStatisticsResponse: string = "GetNonIndexableItemStatisticsResponse"; // eDiscovery export var SearchQueries: string = "SearchQueries"; export var SearchQuery: string = "SearchQuery"; export var MailboxQuery: string = "MailboxQuery"; export var Query: string = "Query"; export var MailboxSearchScopes: string = "MailboxSearchScopes"; export var MailboxSearchScope: string = "MailboxSearchScope"; export var SearchScope: string = "SearchScope"; export var ResultType: string = "ResultType"; export var SortBy: string = "SortBy"; export var Order: string = "Order"; export var Language: string = "Language"; export var Deduplication: string = "Deduplication"; export var PageSize: string = "PageSize"; export var PageItemReference: string = "PageItemReference"; export var PageDirection: string = "PageDirection"; export var PreviewItemResponseShape: string = "PreviewItemResponseShape"; export var ExtendedProperties: string = "ExtendedProperties"; export var PageItemSize: string = "PageItemSize"; export var PageItemCount: string = "PageItemCount"; export var ItemCount: string = "ItemCount"; export var KeywordStats: string = "KeywordStats"; export var KeywordStat: string = "KeywordStat"; export var Keyword: string = "Keyword"; export var ItemHits: string = "ItemHits"; export var SearchPreviewItem: string = "SearchPreviewItem"; export var ChangeKey: string = "ChangeKey"; export var ParentId: string = "ParentId"; export var MailboxId: string = "MailboxId"; export var UniqueHash: string = "UniqueHash"; export var SortValue: string = "SortValue"; export var OwaLink: string = "OwaLink"; export var SmtpAddress: string = "SmtpAddress"; export var CreatedTime: string = "CreatedTime"; export var ReceivedTime: string = "ReceivedTime"; export var SentTime: string = "SentTime"; export var Preview: string = "Preview"; export var HasAttachment: string = "HasAttachment"; export var FailedMailboxes: string = "FailedMailboxes"; export var FailedMailbox: string = "FailedMailbox"; export var Token: string = "Token"; export var Refiners: string = "Refiners"; export var Refiner: string = "Refiner"; export var MailboxStats: string = "MailboxStats"; export var MailboxStat: string = "MailboxStat"; export var HoldId: string = "HoldId"; export var ActionType: string = "ActionType"; export var Mailboxes: string = "Mailboxes"; export var SearchFilter: string = "SearchFilter"; export var ReferenceId: string = "ReferenceId"; export var IsMembershipGroup: string = "IsMembershipGroup"; export var ExpandGroupMembership: string = "ExpandGroupMembership"; export var SearchableMailboxes: string = "SearchableMailboxes"; export var SearchableMailbox: string = "SearchableMailbox"; export var SearchMailboxesResult: string = "SearchMailboxesResult"; export var MailboxHoldResult: string = "MailboxHoldResult"; export var Statuses: string = "Statuses"; export var MailboxHoldStatuses: string = "MailboxHoldStatuses"; export var MailboxHoldStatus: string = "MailboxHoldStatus"; export var AdditionalInfo: string = "AdditionalInfo"; export var NonIndexableItemDetail: string = "NonIndexableItemDetail"; export var NonIndexableItemStatistic: string = "NonIndexableItemStatistic"; export var NonIndexableItemDetails: string = "NonIndexableItemDetails"; export var NonIndexableItemStatistics: string = "NonIndexableItemStatistics"; export var NonIndexableItemDetailsResult: string = "NonIndexableItemDetailsResult"; export var SearchArchiveOnly: string = "SearchArchiveOnly"; export var ErrorDescription: string = "ErrorDescription"; export var IsPartiallyIndexed: string = "IsPartiallyIndexed"; export var IsPermanentFailure: string = "IsPermanentFailure"; export var AttemptCount: string = "AttemptCount"; export var LastAttemptTime: string = "LastAttemptTime"; export var SearchId: string = "SearchId"; export var DiscoverySearchConfigurations: string = "DiscoverySearchConfigurations"; export var DiscoverySearchConfiguration: string = "DiscoverySearchConfiguration"; export var InPlaceHoldConfigurationOnly: string = "InPlaceHoldConfigurationOnly"; export var InPlaceHoldIdentity: string = "InPlaceHoldIdentity"; export var ItemHoldPeriod: string = "ItemHoldPeriod"; export var ManagedByOrganization: string = "ManagedByOrganization"; export var IsExternalMailbox: string = "IsExternalMailbox"; export var ExternalEmailAddress: string = "ExternalEmailAddress"; export var ExtendedAttributes: string = "ExtendedAttributes"; export var ExtendedAttribute: string = "ExtendedAttribute"; export var ExtendedAttributeName: string = "Name"; export var ExtendedAttributeValue: string = "Value"; export var SearchScopeType: string = "SearchScopeType"; /** per github issue #120 */ export var IncludeNonIndexableItems: string = "IncludeNonIndexableItems"; // GetAppManifests export var GetAppManifestsRequest: string = "GetAppManifests"; export var GetAppManifestsResponse: string = "GetAppManifestsResponse"; export var Manifests: string = "Manifests"; export var Manifest: string = "Manifest"; // GetAppManifests for TargetServerVersion > 2.5 export var Apps: string = "Apps"; export var App: string = "App"; export var Metadata: string = "Metadata"; export var ActionUrl: string = "ActionUrl"; export var AppStatus: string = "AppStatus"; export var EndNodeUrl: string = "EndNodeUrl"; // GetClientExtension/SetClientExtension export var GetClientExtensionRequest: string = "GetClientExtension"; export var ClientExtensionUserRequest: string = "UserParameters"; export var ClientExtensionUserEnabled: string = "UserEnabledExtensions"; export var ClientExtensionUserDisabled: string = "UserDisabledExtensions"; export var ClientExtensionRequestedIds: string = "RequestedExtensionIds"; export var ClientExtensionIsDebug: string = "IsDebug"; export var ClientExtensionRawMasterTableXml: string = "RawMasterTableXml"; export var GetClientExtensionResponse: string = "GetClientExtensionResponse"; export var ClientExtensionSpecificUsers: string = "SpecificUsers"; export var ClientExtensions: string = "ClientExtensions"; export var ClientExtension: string = "ClientExtension"; export var SetClientExtensionRequest: string = "SetClientExtension"; export var SetClientExtensionActions: string = "Actions"; export var SetClientExtensionAction: string = "Action"; export var SetClientExtensionResponse: string = "SetClientExtensionResponse"; export var SetClientExtensionResponseMessage: string = "SetClientExtensionResponseMessage"; // GetEncryptionConfiguration/SetEncryptionConfiguration export var GetEncryptionConfigurationRequest: string = "GetEncryptionConfiguration"; export var SetEncryptionConfigurationRequest: string = "SetEncryptionConfiguration"; export var EncryptionConfigurationImageBase64: string = "ImageBase64"; export var EncryptionConfigurationEmailText: string = "EmailText"; export var EncryptionConfigurationPortalText: string = "PortalText"; export var EncryptionConfigurationDisclaimerText: string = "DisclaimerText"; export var EncryptionConfigurationOTPEnabled: string = "OTPEnabled"; export var GetEncryptionConfigurationResponse: string = "GetEncryptionConfigurationResponse"; export var SetEncryptionConfigurationResponse: string = "SetEncryptionConfigurationResponse"; // GetOMEConfiguration/SetOMEConfiguration export var GetOMEConfigurationRequest: string = "GetOMEConfiguration"; export var SetOMEConfigurationRequest: string = "SetOMEConfiguration"; export var OMEConfigurationXml: string = "Xml"; export var GetOMEConfigurationResponse: string = "GetOMEConfigurationResponse"; export var SetOMEConfigurationResponse: string = "SetOMEConfigurationResponse"; // InstallApp export var InstallAppRequest: string = "InstallApp"; export var InstallAppResponse: string = "InstallAppResponse"; // UninstallApp export var UninstallAppRequest: string = "UninstallApp"; export var UninstallAppResponse: string = "UninstallAppResponse"; // DisableApp export var DisableAppRequest: string = "DisableApp"; export var DisableAppResponse: string = "DisableAppResponse"; // RegisterConsent export var RegisterConsentRequest: string = "RegisterConsent"; export var RegisterConsentResponse: string = "RegisterConsentResponse"; // GetAppMarketplaceUrl export var GetAppMarketplaceUrlRequest: string = "GetAppMarketplaceUrl"; export var GetAppMarketplaceUrlResponse: string = "GetAppMarketplaceUrlResponse"; // GetUserRetentionPolicyTags export var GetUserRetentionPolicyTags: string = "GetUserRetentionPolicyTags"; export var GetUserRetentionPolicyTagsResponse: string = "GetUserRetentionPolicyTagsResponse"; // MRM export var RetentionPolicyTags: string = "RetentionPolicyTags"; export var RetentionPolicyTag: string = "RetentionPolicyTag"; export var RetentionId: string = "RetentionId"; export var RetentionPeriod: string = "RetentionPeriod"; export var RetentionAction: string = "RetentionAction"; export var Description: string = "Description"; export var IsVisible: string = "IsVisible"; export var OptedInto: string = "OptedInto"; export var IsArchive: string = "IsArchive"; /* #endregion */ /* #region Groups */ // GetUserUnifiedGroups export var GetUserUnifiedGroups: string = "GetUserUnifiedGroups"; export var RequestedGroupsSets: string = "RequestedGroupsSets"; export var RequestedUnifiedGroupsSetItem: string = "RequestedUnifiedGroupsSet"; export var SortType: string = "SortType"; export var FilterType: string = "FilterType"; export var SortDirection: string = "SortDirection"; export var GroupsLimit: string = "GroupsLimit"; export var UserSmtpAddress: string = "UserSmtpAddress"; export var GetUserUnifiedGroupsResponseMessage: string = "GetUserUnifiedGroupsResponseMessage"; export var GroupsSets: string = "GroupsSets"; export var UnifiedGroupsSet: string = "UnifiedGroupsSet"; export var TotalGroups: string = "TotalGroups"; export var GroupsTag: string = "Groups"; export var UnifiedGroup: string = "UnifiedGroup"; export var MailboxGuid: string = "MailboxGuid"; export var LastVisitedTimeUtc: string = "LastVisitedTimeUtc"; export var AccessType: string = "AccessType"; export var ExternalDirectoryObjectId: string = "ExternalDirectoryObjectId"; // GetUnifiedGroupUnseenCount export var GetUnifiedGroupUnseenCount: string = "GetUnifiedGroupUnseenCount"; export var GroupIdentity: string = "GroupIdentity"; export var GroupIdentityType: string = "IdentityType"; export var GroupIdentityValue: string = "Value"; export var GetUnifiedGroupUnseenCountResponseMessage: string = "GetUnifiedGroupUnseenCountResponseMessage"; export var UnseenCount: string = "UnseenCount"; // SetUnifiedGroupLastVisitedTimeRequest export var SetUnifiedGroupLastVisitedTime: string = "SetUnifiedGroupLastVisitedTime"; export var SetUnifiedGroupLastVisitedTimeResponseMessage: string = "SetUnifiedGroupLastVisitedTimeResponseMessage"; /* #endregion */ /* #region SOAP element names */ export var SOAPEnvelopeElementName: string = "Envelope"; export var SOAPHeaderElementName: string = "Header"; export var SOAPBodyElementName: string = "Body"; export var SOAPFaultElementName: string = "Fault"; export var SOAPFaultCodeElementName: string = "faultcode"; export var SOAPFaultStringElementName: string = "faultstring"; export var SOAPFaultActorElementName: string = "faultactor"; export var SOAPDetailElementName: string = "detail"; export var EwsResponseCodeElementName: string = "ResponseCode"; export var EwsMessageElementName: string = "Message"; export var EwsLineElementName: string = "Line"; export var EwsPositionElementName: string = "Position"; export var EwsErrorCodeElementName: string = "ErrorCode"; // Generated by Availability export var EwsExceptionTypeElementName: string = "ExceptionType"; // Generated by UM /* #endregion */ }
the_stack
import nock from 'nock'; import {describe, it, afterEach} from 'mocha'; import {getPolicy, GitHubRepo, githubRawBase} from '../src/policy'; import assert from 'assert'; import sinon from 'sinon'; // eslint-disable-next-line node/no-extraneous-import import {Octokit} from '@octokit/rest'; nock.disableNetConnect(); const githubHost = 'https://api.github.com'; const octokit = new Octokit(); const policy = getPolicy(octokit, console); describe('policy', () => { afterEach(() => { sinon.restore(); nock.cleanAll(); }); it('should get a single repo metadata', async () => { const repo = 'googleapis/nodejs-storage'; const res = {hello: 'world'}; const scope = nock(githubHost).get(`/repos/${repo}`).reply(200, res); const metadata = await policy.getRepo(repo); assert.deepStrictEqual(metadata, res); scope.done(); }); it('should get a list of github repos based on search filter', async () => { const search = 'org:googleapis is:public archived:false'; const items = [{hello: 'world'}]; const res = {items}; const scope = nock(githubHost) .get(`/search/repositories?page=1&per_page=100&q=${search}`) .reply(200, res); const metadata = await policy.getRepos(search); assert.deepStrictEqual(metadata, items); scope.done(); }); it('should warn for incomplete test results', async () => { const search = 'org:googleapis is:public archived:false'; const res = {incomplete_results: true, items: []}; const scope = nock(githubHost) .get(`/search/repositories?page=1&per_page=100&q=${search}`) .reply(200, res); const stub = sinon.stub(console, 'warn'); await policy.getRepos(search); scope.done(); assert.ok(stub.getCalls()[0].firstArg.startsWith('Incomplete results')); }); it('should perform a basic file exists check', async () => { const file = 'test.file'; const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const rootUrl = `/${repo.full_name}/${repo.default_branch}/${file}`; const scope = nock(githubRawBase).get(rootUrl).reply(200); const exists = await policy.checkFileExists(repo, file, false); assert.ok(exists); scope.done(); }); it('should perform a file exists check in the .github dir', async () => { const file = 'test.file'; const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const rootUrl = `/${repo.full_name}/${repo.default_branch}/${file}`; const magicUrl = `/${repo.full_name}/${repo.default_branch}/.github/${file}`; const scope = nock(githubRawBase) .get(rootUrl) .reply(404) .get(magicUrl) .reply(200); const exists = await policy.checkFileExists(repo, file, true); assert.ok(exists); scope.done(); }); it('should check for renovate', async () => { const files = ['renovate.json', 'renovate.json5']; const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const scopes = files.map(file => { const fileUrl = `/${repo.full_name}/${repo.default_branch}/${file}`; const magicUrl = `/${repo.full_name}/${repo.default_branch}/.github/${file}`; return nock(githubRawBase) .get(fileUrl) .reply(200) .get(magicUrl) .reply(404); }); const hasRenovate = await policy.hasRenovate(repo); assert.ok(hasRenovate); scopes.forEach(x => x.done()); }); it('should check for CODEOWNERS', async () => { const file = 'CODEOWNERS'; const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const fileUrl = `/${repo.full_name}/${repo.default_branch}/${file}`; const magicUrl = `/${repo.full_name}/${repo.default_branch}/.github/${file}`; const scope = nock(githubRawBase) .get(fileUrl) .reply(200) .get(magicUrl) .reply(404); const good = await policy.hasCodeOwners(repo); assert.ok(good); scope.done(); }); it('should check for CODE_OF_CONDUCT', async () => { const file = 'CODE_OF_CONDUCT.md'; const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const fileUrl = `/${repo.full_name}/${repo.default_branch}/${file}`; const magicUrl = `/${repo.full_name}/${repo.default_branch}/.github/${file}`; const scope = nock(githubRawBase) .get(fileUrl) .reply(200) .get(magicUrl) .reply(404); const good = await policy.hasCodeOfConduct(repo); assert.ok(good); scope.done(); }); it('should check for SECURITY', async () => { const file = 'SECURITY.md'; const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const fileUrl = `/${repo.full_name}/${repo.default_branch}/${file}`; const magicUrl = `/${repo.full_name}/${repo.default_branch}/.github/${file}`; const scope = nock(githubRawBase) .get(fileUrl) .reply(200) .get(magicUrl) .reply(404); const good = await policy.hasSecurityPolicy(repo); assert.ok(good); scope.done(); }); it('should check for CONTRIBUTING.md', async () => { const file = 'CONTRIBUTING.md'; const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const fileUrl = `/${repo.full_name}/${repo.default_branch}/${file}`; const magicUrl = `/${repo.full_name}/${repo.default_branch}/.github/${file}`; const scope = nock(githubRawBase) .get(fileUrl) .reply(200) .get(magicUrl) .reply(404); const good = await policy.hasContributing(repo); assert.ok(good); scope.done(); }); it('should check happy path branch protection', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const res = { required_pull_request_reviews: { require_code_owner_reviews: true, }, required_status_checks: { contexts: ['check1'], }, }; const url = `/repos/${repo.full_name}/branches/${repo.default_branch}/protection`; const scope = nock(githubHost).get(url).reply(200, res); const good = await policy.hasBranchProtection(repo); assert.ok(good); scope.done(); }); it('should fail branch protection on non 2xx response', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const url = `/repos/${repo.full_name}/branches/${repo.default_branch}/protection`; const scope = nock(githubHost).get(url).reply(403); const good = await policy.hasBranchProtection(repo); assert.ok(!good); scope.done(); }); it('should fail branch protection on missing required reviews', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const res = { required_status_checks: { contexts: ['check1'], }, }; const url = `/repos/${repo.full_name}/branches/${repo.default_branch}/protection`; const scope = nock(githubHost).get(url).reply(200, res); const good = await policy.hasBranchProtection(repo); assert.ok(!good); scope.done(); }); it('should fail branch protection on missing CODEOWNERS', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const res = { required_pull_request_reviews: { required_approving_review_count: 1, }, required_status_checks: { contexts: ['check1'], }, }; const url = `/repos/${repo.full_name}/branches/${repo.default_branch}/protection`; const scope = nock(githubHost).get(url).reply(200, res); const good = await policy.hasBranchProtection(repo); assert.ok(!good); scope.done(); }); it('should fail branch protection on missing status checks', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', } as GitHubRepo; const res = { required_pull_request_reviews: { require_code_owner_reviews: true, required_approving_review_count: 1, }, }; const url = `/repos/${repo.full_name}/branches/${repo.default_branch}/protection`; const scope = nock(githubHost).get(url).reply(200, res); const good = await policy.hasBranchProtection(repo); assert.ok(!good); scope.done(); }); it('should check for disabled merge commits', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', allow_merge_commit: false, } as GitHubRepo; const disabled = await policy.hasMergeCommitsDisabled(repo); assert.ok(disabled); }); it('should check for a valid license', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', license: { key: 'beerpl', }, } as GitHubRepo; const isValid = await policy.hasLicense(repo); assert.ok(!isValid); }); it('should check for main as the default branch', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'master', } as GitHubRepo; const isValid = await policy.hasMainDefault(repo); assert.ok(!isValid); }); it('should check for all policy checks', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', license: { key: 'beerpl', }, language: 'ruby', } as GitHubRepo; // we've already individually tested all of these functions, so stub them const stubs = [ sinon.stub(policy, 'hasRenovate').resolves(true), sinon.stub(policy, 'hasLicense').resolves(true), sinon.stub(policy, 'hasCodeOfConduct').resolves(true), sinon.stub(policy, 'hasContributing').resolves(true), sinon.stub(policy, 'hasCodeOwners').resolves(true), sinon.stub(policy, 'hasBranchProtection').resolves(true), sinon.stub(policy, 'hasMergeCommitsDisabled').resolves(true), sinon.stub(policy, 'hasSecurityPolicy').resolves(true), sinon.stub(policy, 'hasMainDefault').resolves(true), ]; const result = await policy.checkRepoPolicy(repo); const [org, name] = repo.full_name.split('/'); const expected = { repo: name, org, topics: [], language: repo.language, hasRenovateConfig: true, hasValidLicense: true, hasCodeOfConduct: true, hasContributing: true, hasCodeowners: true, hasBranchProtection: true, hasMergeCommitsDisabled: true, hasSecurityPolicy: true, hasMainDefault: true, timestamp: result.timestamp, }; assert.deepStrictEqual(result, expected); stubs.forEach(x => assert.ok(x.calledOnce)); }); it('should raise error if grabbing file tracked by policy fails', async () => { const repo = { full_name: 'googleapis/nodejs-storage', default_branch: 'main', license: { key: 'beerpl', }, language: 'ruby', } as GitHubRepo; const getSecurityMd = nock('https://raw.githubusercontent.com') .get('/googleapis/nodejs-storage/main/SECURITY.md') .reply(200) .get('/googleapis/nodejs-storage/main/.github/SECURITY.md') .reply(502); // we've already individually tested all of these functions, so stub them const stubs = [ sinon.stub(policy, 'hasRenovate').resolves(true), sinon.stub(policy, 'hasLicense').resolves(true), sinon.stub(policy, 'hasCodeOfConduct').resolves(true), sinon.stub(policy, 'hasContributing').resolves(true), sinon.stub(policy, 'hasCodeOwners').resolves(true), sinon.stub(policy, 'hasBranchProtection').resolves(true), sinon.stub(policy, 'hasMergeCommitsDisabled').resolves(true), sinon.stub(policy, 'hasMainDefault').resolves(true), ]; await assert.rejects(policy.checkRepoPolicy(repo), /received 502 fetching/); getSecurityMd.done(); }); });
the_stack
import { TActiveSection, TActiveInspectorTab, IDescriptor, TTargetReference, TSelectDescriptorOperation, ITargetReference, TSubTypes, ITreeDataTabs, TPath, TFilterEvents, TImportItems, IInspectorState, TGenericViewType, TCodeViewType, IAMCoverter, TFontSizeSettings, IDescriptorSettings, ISettings } from "../model/types"; import { TState } from "../components/FilterButton/FilterButton"; import { IRootState } from "../../shared/store"; export interface ISetMainTab { type: "SET_MAIN_TAB" payload: TActiveSection } export interface ISetModeTab { type: "SET_MODE_TAB" payload: TActiveInspectorTab } export interface ISetTargetReference { type: "SET_TARGET_REFERENCE" payload: ITargetReference } export interface IAddDescriptorAction { type: "ADD_DESCRIPTOR" payload: { arg:IDescriptor, replace:boolean } } export interface ISetSelectedReferenceTypeAction { type: "SET_SELECTED_REFERENCE_TYPE_ACTION" payload: TTargetReference } export interface ISelectDescriptor { type: "SELECT_DESCRIPTOR" payload: { operation:TSelectDescriptorOperation uuid?: string crc?:number } } export interface IClearViewAction{ type: "CLEAR_VIEW" payload:{keep:boolean} } export interface IClearAction{ type: "CLEAR" payload:null } export interface IClearNonExistentAction{ type: "CLEAR_NON_EXISTENT" payload:null } export interface ILockDescAction{ type: "LOCK_DESC" payload: { lock:boolean,uuids:string[] } } export interface IPinDescAction{ type: "PIN_DESC" payload: { pin:boolean,uuids:string[] } } export interface IRemoveDescAction{ type: "REMOVE_DESC" payload:string[] } export interface IImportStateAction{ type: "IMPORT_STATE" payload:IRootState } export interface IImportItemsAction{ type: "IMPORT_ITEMS" payload: { items: IDescriptor[], kind: TImportItems } } export interface IImportReplaceAction{ type: "IMPORT_REPLACE" payload:null } export interface IExportSelectedDescAction{ type: "EXPORT_SELECTED_DESC" payload:null } export interface IExportAllDescAction{ type: "EXPORT_ALL_DESC" payload:null } export interface IExportStateAction{ type: "EXPORT_STATE" payload:null } export interface ISetFilterStateAction { type: "SET_FILTER_STATE" payload: { type: TTargetReference, subType: TSubTypes | "main", state: TState } } export interface ISetInspectorPathDiffAction{ type: "SET_INSPECTOR_PATH_DIFF" payload: { path: string[] mode: "replace"|"add" } } export interface ISetInspectorPathContentAction{ type: "SET_INSPECTOR_PATH_CONTENT" payload: { path: string[] mode: "replace"|"add" } } export interface ISetInspectorPathDOMAction{ type: "SET_INSPECTOR_PATH_DOM" payload: { path: string[] mode: "replace"|"add" } } export interface ISetExpandedPathAction{ type: "SET_EXPANDED_PATH", payload: { type: ITreeDataTabs path: TPath, expand: boolean recursive: boolean data:any } } export interface IListenerAction{ type:"SET_LISTENER", payload:boolean } export interface IAutoInspectorAction{ type:"SET_AUTO_INSPECTOR", payload:boolean } // filter export interface ISetSearchTermAction{ type: "SET_SEARCH_TERM_ACTION", payload: string|null } export interface ISetFilterType{ type: "SET_FILTER_TYPE", payload: TFilterEvents } export interface ISetIncludeAction{ type: "SET_INCLUDE_ACTION", payload: string[] } export interface ISetExcludeAction{ type: "SET_EXCLUDE_ACTION", payload: string[] } /* export interface IGroupSameAction{ type: "GROUP_SAME_ACTION", payload: boolean } */ export interface IFilterEventNameAction{ type: "FILTER_EVENT_NAME_ACTION", payload: { eventName: string, kind: "include" | "exclude", operation: "add" | "remove" } } export interface IReplaceWholeState{ type: "REPLACE_WHOLE_STATE", payload: IInspectorState } export interface ISetDispatcherValueAction{ type: "SET_DISPATCHER_VALUE", payload:string } export interface ISetRenameModeAction{ type: "SET_RENAME_MODE", payload: { uuid: string, on:boolean } } export interface IRenameDescriptorAction{ type: "RENAME_DESCRIPTOR", payload: { uuid: string, name:string } } export interface ISetDescriptorOptionsAction { type: "SET_DESCRIPTOR_OPTIONS", payload: { uuids: string[] | "default" options: Partial<IDescriptorSettings> } } export interface ISetInspectorViewAction { type: "SET_INSPECTOR_VIEW_ACTION", payload: { inspectorType: "content" | "diff" | "code" viewType: TGenericViewType | TCodeViewType } } export interface ISetColumnSizeAction{ type: "SET_COLUMN_SIZE_ACTION", payload:number } export interface ISetRecordRawAction{ type: "SET_RECORD_RAW", payload:boolean } export interface ISetMaximumItemsAction{ type: "SET_MAXIMUM_ITEMS", payload:string } export interface ISetAutoExpandLevelAction { type: "SET_AUTOEXPAND_LEVEL", payload: { level: number part: "DOM" | "content" | "diff" } } export interface IDontShowMarketplaceInfoAction{ type: "DONT_SHOW_MARKETPLACE_INFO_ACTION", payload:boolean } export interface ISetConverterInfoAction{ type: "SET_CONVERTER", payload: Partial<IAMCoverter> } export interface ISetFontSizeAction{ type: "SET_FONT_SIZE", payload: TFontSizeSettings } export interface ISetNeverRecordActionNamesAction{ type: "SET_NEVER_RECORD_ACTION_NAMES_ACTION", payload: string[] } export interface IToggleDescriptorsGroupingAction{ type: "TOGGLE_DESCRIPTORS_GROUPING", payload: "none" | "strict" | null } export interface ISetSettingsAction{ type: "SET_SETTINGS", payload: Partial<ISettings> } export function setSettingsAction(settings:Partial<ISettings>): ISetSettingsAction{ return { type: "SET_SETTINGS", payload: settings, }; } export function toggleDescriptorsGroupingAction(arg: "none" | "strict" | null = null): IToggleDescriptorsGroupingAction { return { type: "TOGGLE_DESCRIPTORS_GROUPING", payload: arg, }; } export function setNeverRecordActionNamesAction(value: string): ISetNeverRecordActionNamesAction { return { type: "SET_NEVER_RECORD_ACTION_NAMES_ACTION", payload: value.split(/[\n\r]/g).map(v => v.trim()), }; } export function setFontSizeAction(size: TFontSizeSettings):ISetFontSizeAction { return { type: "SET_FONT_SIZE", payload: size, }; } export function setConverterInfoAction(info: Partial<IAMCoverter>): ISetConverterInfoAction{ return { type: "SET_CONVERTER", payload: info, }; } export function setDontShowMarketplaceInfoAction(enabled: boolean): IDontShowMarketplaceInfoAction{ return { type: "DONT_SHOW_MARKETPLACE_INFO_ACTION", payload: enabled, }; } export function setAutoExpandLevelAction(part: "DOM" | "content" | "diff",level: number): ISetAutoExpandLevelAction{ return { type: "SET_AUTOEXPAND_LEVEL", payload: { level, part, }, }; } export function setRecordRawAction(value: boolean): ISetRecordRawAction{ return { type: "SET_RECORD_RAW", payload: value, }; } export function setMaximumItems(value: string):ISetMaximumItemsAction { return { type: "SET_MAXIMUM_ITEMS", payload: value, }; } export function setColumnSizeAction(px: number): ISetColumnSizeAction{ return { type: "SET_COLUMN_SIZE_ACTION", payload: px, }; } export function setInspectorViewAction(inspectorType:"content" | "diff" | "code", viewType:TGenericViewType|TCodeViewType): ISetInspectorViewAction{ return { type: "SET_INSPECTOR_VIEW_ACTION", payload: { inspectorType, viewType, }, }; } export function setDescriptorOptionsAction(uuids:string[]|"default",options: Partial<IDescriptorSettings>): ISetDescriptorOptionsAction{ return { type: "SET_DESCRIPTOR_OPTIONS", payload: { uuids, options, }, }; } export function setRenameModeAction(uuid:string,on:boolean):ISetRenameModeAction{ return { type: "SET_RENAME_MODE", payload: { on, uuid, }, }; } export function renameDescriptorAction(uuid:string,name:string):IRenameDescriptorAction{ return { type: "RENAME_DESCRIPTOR", payload: { name, uuid, }, }; } export function setDispatcherValueAction(value:string): ISetDispatcherValueAction{ return { type: "SET_DISPATCHER_VALUE", payload:value, }; } export function replaceWholeStateAction(state: IInspectorState):IReplaceWholeState { return { type: "REPLACE_WHOLE_STATE", payload: state, }; } export function setListenerAction(enabled:boolean):IListenerAction{ return{ type:"SET_LISTENER", payload:enabled, }; } export function setAutoInspectorAction(enabled:boolean):IAutoInspectorAction{ return{ type:"SET_AUTO_INSPECTOR", payload:enabled, }; } export function setExpandedPathAction(type: ITreeDataTabs,path: TPath, expand: boolean, recursive: boolean,data:any): ISetExpandedPathAction{ return { type: "SET_EXPANDED_PATH", payload: { type,path, expand, recursive,data, }, }; } export function setInspectorPathDomAction(path:string[],mode:"replace"|"add"):ISetInspectorPathDOMAction{ return { type: "SET_INSPECTOR_PATH_DOM", payload: { path, mode, }, }; } export function setInspectorPathDiffAction(path:TPath,mode:"replace"|"add"):ISetInspectorPathDiffAction{ return { type: "SET_INSPECTOR_PATH_DIFF", payload: { path, mode, }, }; } export function setInspectorPathContentAction(path:string[],mode:"replace"|"add"):ISetInspectorPathContentAction{ return { type: "SET_INSPECTOR_PATH_CONTENT", payload: { path, mode, }, }; } export function setFilterStateAction(type: TTargetReference,subType: TSubTypes|"main",state: TState): ISetFilterStateAction { return { type: "SET_FILTER_STATE", payload: { type, subType, state, }, }; } export function setMainTabAction(id:TActiveSection):ISetMainTab{ return { type: "SET_MAIN_TAB", payload: id, }; } export function setModeTabAction(id:TActiveInspectorTab):ISetModeTab{ return { type: "SET_MODE_TAB", payload: id, }; } export function setTargetReferenceAction(arg:ITargetReference):ISetTargetReference{ return { type: "SET_TARGET_REFERENCE", payload: arg, }; } export function addDescriptorAction(arg:IDescriptor, replace:boolean):IAddDescriptorAction{ return { type: "ADD_DESCRIPTOR", payload: { arg, replace, }, }; } export function selectDescriptorAction(operation: TSelectDescriptorOperation, uuid?: string,crc?:number): ISelectDescriptor { return { type: "SELECT_DESCRIPTOR", payload: {operation,uuid,crc}, }; } export function setSelectedReferenceTypeAction(type: TTargetReference): ISetSelectedReferenceTypeAction { return { type: "SET_SELECTED_REFERENCE_TYPE_ACTION", payload: type, }; } export function clearViewAction(keep:boolean):IClearViewAction{ return{ type: "CLEAR_VIEW", payload: {keep}, }; } export function clearAction():IClearAction{ return{ type: "CLEAR", payload: null, }; } export function clearNonExistentAction():IClearNonExistentAction{ return{ type: "CLEAR_NON_EXISTENT", payload: null, }; } export function lockDescAction(lock:boolean,uuids:string[]):ILockDescAction{ return{ type: "LOCK_DESC", payload: { uuids, lock, }, }; } export function pinDescAction(pin:boolean,uuids:string[]):IPinDescAction{ return{ type: "PIN_DESC", payload: { uuids, pin, }, }; } export function removeDescAction(uuids:string[]):IRemoveDescAction{ return{ type: "REMOVE_DESC", payload: uuids, }; } export function importStateAction(state:IRootState):IImportStateAction{ return{ type: "IMPORT_STATE", payload: state, }; } export function importItemsAction(items:IDescriptor[],kind:TImportItems):IImportItemsAction{ return{ type: "IMPORT_ITEMS", payload: {items,kind}, }; } export function importReplaceAction():IImportReplaceAction{ return{ type: "IMPORT_REPLACE", payload: null, }; } export function exportSelectedDescAction():IExportSelectedDescAction{ return{ type: "EXPORT_SELECTED_DESC", payload: null, }; } export function exportAllDescAction():IExportAllDescAction{ return{ type: "EXPORT_ALL_DESC", payload: null, }; } export function exportStateAction():IExportStateAction{ return{ type: "EXPORT_STATE", payload: null, }; } ///////////////// export function setSearchTermAction(str:string|null):ISetSearchTermAction{ return{ type: "SET_SEARCH_TERM_ACTION", payload: str, }; } export function setFilterTypeAction(filterType:TFilterEvents): ISetFilterType{ return { type: "SET_FILTER_TYPE", payload:filterType, }; } export function setIncludeAction(arr:string[]):ISetIncludeAction{ return{ type: "SET_INCLUDE_ACTION", payload:arr, }; } export function setExcludeAction(arr:string[]):ISetExcludeAction{ return{ type: "SET_EXCLUDE_ACTION", payload:arr, }; } /* export function groupSameAction(enabled: boolean):IGroupSameAction { return { type: "GROUP_SAME_ACTION", payload: enabled, }; }*/ export function filterEventNameAction(eventName:string, kind:"include"|"exclude", operation: "add"|"remove"):IFilterEventNameAction { return { type: "FILTER_EVENT_NAME_ACTION", payload: { eventName,kind,operation, }, }; } export type TActions = ISetMainTab | ISetInspectorPathDOMAction | ISetModeTab | ISetTargetReference | IAddDescriptorAction | ISelectDescriptor | ISetSelectedReferenceTypeAction | IClearViewAction | IClearAction | IClearNonExistentAction | ILockDescAction | IPinDescAction | IRemoveDescAction | IImportStateAction | IImportItemsAction | IExportSelectedDescAction | IExportAllDescAction | IExportStateAction | ISetFilterStateAction | ISetInspectorPathDiffAction | ISetInspectorPathContentAction | ISetExpandedPathAction | IListenerAction | IAutoInspectorAction | ISetSearchTermAction | ISetFilterType | ISetIncludeAction | ISetExcludeAction | //IGroupSameAction | IFilterEventNameAction | IReplaceWholeState | ISetDispatcherValueAction | ISetRenameModeAction | IRenameDescriptorAction | ISetDescriptorOptionsAction | ISetInspectorViewAction | ISetColumnSizeAction | ISetRecordRawAction | ISetAutoExpandLevelAction | ISetMaximumItemsAction | IDontShowMarketplaceInfoAction | ISetConverterInfoAction | ISetFontSizeAction | ISetNeverRecordActionNamesAction | IToggleDescriptorsGroupingAction | ISetSettingsAction
the_stack
import PropTypes from 'prop-types'; import expr from 'property-expr'; import React, { useEffect, useImperativeHandle, useMemo, useRef, SyntheticEvent, Fragment, } from 'react'; import shallowequal from 'shallowequal'; import { BindingContext } from 'topeka'; import { useUncontrolledProp } from 'uncontrollable'; import warning from 'warning'; import { reach, isSchema, AnyObjectSchema, AnySchema, InferType } from 'yup'; import useEventCallback from '@restart/hooks/useEventCallback'; import useMergeState from '@restart/hooks/useMergeState'; import useMounted from '@restart/hooks/useMounted'; import useTimeout from '@restart/hooks/useTimeout'; import { FormActionsContext, FormErrorContext, FormSubmitsContext, FormTouchedContext, } from './Contexts'; import createErrorManager, { isValidationError, ValidationPathSpec, } from './errorManager'; import { BeforeSubmitData, Errors, Touched, ValidateData } from './types'; import * as ErrorUtils from './Errors'; import errToJSON from './utils/errToJSON'; import notify from './utils/notify'; export interface FormProps< TSchema extends AnyObjectSchema, TValue = Record<string, any> > { as?: React.ElementType | null | false; className?: string; children?: React.ReactNode; schema?: TSchema; value?: TValue; defaultValue?: Partial<TValue>; errors?: Errors; defaultErrors?: Errors; touched?: Touched; defaultTouched?: Touched; noValidate?: boolean; onChange?: (input: TValue, changedPaths: string[]) => void; onError?: (errors: Errors) => void; onTouch?: (touched: Touched, changedPaths: string[]) => void; onValidate?: (data: ValidateData) => void; onBeforeSubmit?: (data: BeforeSubmitData) => void; onSubmit?: (validatedValue: InferType<TSchema>) => void; onInvalidSubmit?: (errors: Errors) => void; onSubmitFinished?: (error?: Error) => void; submitForm?: (input: TValue) => Promise<any> | any; getter?: (path: string, value: TValue) => any; setter?: (path: string, value: TValue, fieldValue: any) => TValue; context?: Record<string, unknown>; delay?: number; stripUnknown?: boolean; /** * Controls how errors are dealt with for field level validation. When * set, the first validation error a field throws is returned instead of waiting * for all validations to finish */ abortEarly?: boolean; strict?: boolean; /** Adds some additional runtime console warnings */ debug?: boolean; [other: string]: any; } let done = (e: Error) => setTimeout(() => { throw e; }); const formGetter = (path: string, model: any) => path ? expr.getter(path, true)(model || {}) : model; const formSetter = BindingContext.defaultProps.setter; function useErrorContext(errors?: Errors) { const ref = useRef<Errors | null>(null); if (!ref.current) { return (ref.current = errors ?? null); } if (!shallowequal(ref.current.errors, errors)) { ref.current = errors ?? null; } return ref.current; } const isEvent = (e): e is SyntheticEvent => typeof e == 'object' && e != null && 'target' in e; type Setter = ( path: string, formData: unknown, fieldValue: any, setter: any, ) => unknown; const createFormSetter = ( setter: Setter, schema?: AnySchema, context?: any, ) => { function parseValueFromEvent( target: HTMLInputElement & HTMLSelectElement, fieldValue: any, fieldSchema?: any, ) { const { type, value, checked, options, multiple, files } = target; if (type === 'file') return multiple ? files : files && files[0]; if (multiple) { // @ts-ignore const innerType = fieldSchema?._subType?._type; return Array.from(options) .filter((opt) => opt.selected) .map(({ value: option }) => innerType == 'number' ? parseFloat(option) : option, ); } if (/number|range/.test(type)) { let parsed = parseFloat(value); return isNaN(parsed) ? null : parsed; } if (type === 'checkbox') { const isArray = Array.isArray(fieldValue); const isBool = !isArray && (fieldSchema as any)?._type === 'boolean'; if (isBool) return checked; const nextValue = isArray ? [...fieldValue] : []; const idx = nextValue.indexOf(value); if (checked) { if (idx === -1) nextValue.push(value); } else nextValue.splice(idx, 1); return nextValue; } return value; } return ( path: string, formData: any, fieldValue: any, defaultSetter: any, ): any => { if (isEvent(fieldValue)) fieldValue = parseValueFromEvent( fieldValue.target as any, formGetter(path, formData), schema && path && reach(schema, path, formData, context), ); return setter(path, formData, fieldValue, defaultSetter); }; }; function validatePath( { path }: ValidationPathSpec, { value, schema, ...rest }, ): Promise<Error | void> { return schema .validateAt(path, value, rest) .then(() => null) .catch((err) => err); } const EMPTY_TOUCHED = {}; export interface FormHandle { submit: () => Promise<false | void>; validate(fields: string[]): void; } export declare interface Form { <T extends AnyObjectSchema, TValue = Record<string, any>>( props: FormProps<T, TValue> & React.RefAttributes<FormHandle>, ): React.ReactElement | null; displayName?: string; propTypes?: any; // getter: typeof formGetter // setter: typeof formSetter } /** @alias Form */ const _Form: Form = React.forwardRef( <T extends AnyObjectSchema>( { children, defaultValue, value: propValue, onChange: propOnChange, errors: propErrors, onError: propOnError, defaultErrors = ErrorUtils.EMPTY_ERRORS, defaultTouched = EMPTY_TOUCHED, touched: propTouched, onTouch: propOnTouch, schema, submitForm, getter = formGetter, setter = formSetter, delay = 300, debug, noValidate, onValidate, onBeforeSubmit, onSubmit, onSubmitFinished, onInvalidSubmit, context, stripUnknown, abortEarly, strict = false, as: Element = 'form', ...elementProps }: FormProps<T>, ref: React.Ref<FormHandle>, ) => { const [value, onChange] = useUncontrolledProp( propValue, defaultValue, propOnChange, ); const [errors, onError] = useUncontrolledProp( propErrors, defaultErrors, propOnError, ); const [touched, onTouch] = useUncontrolledProp( propTouched, defaultTouched, propOnTouch, ); const shouldValidate = !!schema && !noValidate; const flushTimeout = useTimeout(); const submitTimeout = useTimeout(); const isMounted = useMounted(); const queueRef = useRef<string[]>([]); const errorManager = useMemo(() => createErrorManager(validatePath), []); const updateFormValue = useMemo( () => createFormSetter(setter, schema, context), [context, schema, setter], ); const yupOptions = { strict, context, stripUnknown, abortEarly: abortEarly == null ? false : abortEarly, }; const isSubmittingRef = useRef(false); const [submits, setSubmitState] = useMergeState(() => ({ submitCount: 0, submitAttempts: 0, submitting: false, })); function setSubmitting(submitting) { if (!isMounted()) return; isSubmittingRef.current = submitting; setSubmitState({ submitting }); } const errorContext = useErrorContext(errors); const isUpdateRef = useRef(false); useEffect(() => { // don't do this on mount if (!isUpdateRef.current) { isUpdateRef.current = true; return; } if (errors) { enqueue(Object.keys(errors)); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [schema]); const flush = () => { flushTimeout.set(() => { let fields = queueRef.current; if (!fields.length) return; queueRef.current = []; errorManager .collect(fields, errors, { schema, value, ...yupOptions, }) .then((nextErrors) => { if (nextErrors !== errors) { maybeWarn(debug, errors, 'field validation'); notify(onError, [nextErrors]); } }) .catch(done); }, delay); }; useEffect(() => { flush(); }); function enqueue(fields: string[]) { queueRef.current.push(...fields); } const getSchemaForPath = (path: string): AnySchema | undefined => { if (schema && path) return reach(schema, path, value, context); }; const handleChange = useEventCallback((model, paths) => { let nextTouched = touched; onChange(model, paths); paths.forEach((path) => { if (touched && touched[path]) return; if (nextTouched === touched) nextTouched = { ...touched, [path]: true }; else nextTouched[path] = true; }); if (nextTouched !== touched) onTouch(nextTouched!, paths); }); const handleValidationRequest = ( fields: string[], type: string, args?: any[], ) => { if (!shouldValidate) return; notify(onValidate, [{ type, fields, args }]); enqueue(fields); if (type !== 'onChange') flush(); }; const handleFieldError = (name: string, fieldErrors: Errors) => { handleError(Object.assign(ErrorUtils.remove(errors, name), fieldErrors)); }; const handleError = (nextErrors: Errors) => { notify(onError, [nextErrors]); }; const handleSubmitSuccess = (validatedValue: InferType<T>) => { notify(onError, [] as any); notify(onSubmit, [validatedValue]); return Promise.resolve(submitForm && submitForm(validatedValue)).then( () => { setSubmitting(false); setSubmitState((s) => ({ submitCount: s.submitCount + 1, submitAttempts: s.submitAttempts + 1, })); notify(onSubmitFinished); }, (err) => { setSubmitting(false); notify(onSubmitFinished, [err]); throw err; }, ); }; const handleSubmitError = (err: any) => { if (!isValidationError(err)) throw err; const nextErrors = errToJSON(err); maybeWarn(debug, nextErrors, 'onSubmit'); setSubmitState((s) => ({ submitAttempts: s.submitAttempts + 1, })); notify(onError, [nextErrors]); notify(onInvalidSubmit, [nextErrors]); setSubmitting(false); notify(onSubmitFinished, [err]); }; const clearPendingValidations = () => { flushTimeout.clear(); queueRef.current.length = 0; }; const handleSubmit = (e?: React.SyntheticEvent) => { if (e && e.preventDefault && e.stopPropagation) { e.preventDefault(); e.stopPropagation(); } clearPendingValidations(); submitTimeout.set(() => submit().catch(done)); }; const submit = (): Promise<false | void> => { if (isSubmittingRef.current) { return Promise.resolve(false); } clearPendingValidations(); notify(onBeforeSubmit, [ { value, errors, }, ]); setSubmitting(true); return ( (!shouldValidate ? Promise.resolve(value as any) : schema!.validate(value, { ...yupOptions, abortEarly: false, strict: false, }) ) // no catch, we aren't interested in errors from onSubmit handlers .then(handleSubmitSuccess, handleSubmitError) ); }; useImperativeHandle(ref, () => ({ submit, validate(fields) { errorManager.collect(fields, errors, { schema, value, ...yupOptions }); }, })); const formActions = Object.assign(useRef({}).current, { getSchemaForPath, yupContext: context, onSubmit: handleSubmit, onValidate: handleValidationRequest, onFieldError: handleFieldError, formHasValidation: () => shouldValidate, }); if (Element === 'form') { elementProps.noValidate = true; // disable html5 validation } elementProps.onSubmit = handleSubmit; let useChildren = Element == null || Element === false; // if it's a fragment no props if ( Element === Fragment || (useChildren && React.Children.only(children as React.ReactElement).type === Fragment) ) { elementProps = {}; } return ( <BindingContext value={value} getter={getter} setter={updateFormValue} onChange={handleChange} > <FormActionsContext.Provider value={formActions}> <FormTouchedContext.Provider value={touched}> <FormSubmitsContext.Provider value={submits}> <FormErrorContext.Provider value={errorContext!}> {Element == null || Element === false ? ( React.cloneElement( React.Children.only(children as React.ReactElement), elementProps, ) ) : ( <Element {...elementProps}>{children}</Element> )} </FormErrorContext.Provider> </FormSubmitsContext.Provider> </FormTouchedContext.Provider> </FormActionsContext.Provider> </BindingContext> ); }, ); function maybeWarn(debug, errors, target) { if (!debug) return; if (process.env.NODE_ENV !== 'production') { let keys = Object.keys(errors); warning( !keys.length, `[react-formal] (${target}) invalid fields: ${keys.join(', ')}`, ); } } _Form.propTypes = { /** * Form value object, can be left [uncontrolled](/controllables); * use the `defaultValue` prop to initialize an uncontrolled form. */ value: PropTypes.object, /** * Callback that is called when the `value` prop changes. * * ```ts static * function ( * value: any, * updatedPaths: string[] * ) * ``` */ onChange: PropTypes.func, /** * An object hash of field errors for the form. The object should be keyed with paths * with the values being an array of errors or message objects. Errors can be * left [uncontrolled](/controllables) (use `defaultErrors` to set an initial value) * or managed along with the `onError` callback. You can use any object shape you'd like for * errors, as long as you provide the Form.Message component an `extract` prop that * understands how to pull out the strings message. By default it understands strings and objects * with a `'message'` property. * * ```jsx static * <Form errors={{ * "name.first": [ * 'First names are required', * { * message: "Names must be at least 2 characters long", * type: 'min' * } * ], * }}/> * ``` */ errors: PropTypes.object, /** * Callback that is called when a validation error occurs. It is called with an `errors` object * * ```jsx renderAsComponent * import Form from '@docs/components/FormWithResult'; * import * as yup from 'yup' * * const schema = yup.object({ * name: yup.string().required().min(15) * }) * * const [errors, setErrors] = useState({}); * * <Form * schema={schema} * errors={errors} * onError={errors => { * if (errors.name) { * errors.name = 'hijacked!' * } * * setErrors(errors) * }}> * <label> * Name * <Form.Field name='name'/> * </label> * <Form.Message for='name' className="error" /> * * <Form.Submit type='submit'>Submit</Form.Submit> * </Form> * ``` */ onError: PropTypes.func, /** An object hash of field paths and whether they have been "touched" yet */ touched: PropTypes.object, /** * Callback that is called when a field is touched. It is called with an `touched` object */ onTouch: PropTypes.func, /** * Callback that is called whenever a validation is triggered. * It is called _before_ the validation is actually run. * * ```js static * function onValidate(event) { * let { type, fields, args } = event * } * ``` */ onValidate: PropTypes.func, /** * Callback that is fired in response to a submit, _before_ validation runs. * * ```js static * function onSubmit(formValue) { * // do something with valid value * } * ``` */ onBeforeSubmit: PropTypes.func, /** * Callback that is fired in response to a submit, after validation runs for the entire form. * * ```js static * function onSubmit(formValue) { * // do something with valid value * } * ``` */ onSubmit: PropTypes.func, onSubmitFinished: PropTypes.func, /* */ submitForm: PropTypes.func, /** * Callback that is fired when the native onSubmit event is triggered. Only relevant when * the `component` prop renders a `<form/>` tag. onInvalidSubmit will trigger only if the form is invalid. * * ```js static * function onInvalidSubmit(errors){ * // do something with errors * } * ``` */ onInvalidSubmit: PropTypes.func, /** * A value getter function. `getter` is called with `path` and `value` and * should return the plain **javascript** value at the path. * * ```ts static * function( * path: string, * value: any, * ): Object * ``` */ getter: PropTypes.func, /** * A value setter function. `setter` is called with `path`, the form `value` and the path `value`. * The `setter` must return updated form `value`, which allows you to leave the original value unmutated. * * The default implementation uses the [react immutability helpers](http://facebook.github.io/react/docs/update.html), * letting you treat the form `value` as immutable. * * ```ts static * function( * path: string, * formValue: any, * pathValue: any * ): Object * ``` */ setter: PropTypes.func, /** * Time in milliseconds that validations should be debounced. Reduces the amount of validation calls * made at the expense of a slight delay. Helpful for performance. */ delay: PropTypes.number, /** * Validations will be strict, making no attempt to coarce input values to the appropriate type. */ strict: PropTypes.bool, /** * Turns off input validation for the Form, value updates will continue to work. */ noValidate: PropTypes.bool, /** * A tag name or Component class the Form should render. * * If `null` are `false` the form will simply render it's child. In * this instance there must only be one child. */ as: PropTypes.oneOfType([ PropTypes.elementType, PropTypes.oneOf([null, false]), ]), /** * A Yup schema that validates the Form `value` prop. Used to validate the form input values * For more information about the yup api check out: https://github.com/jquense/yup/blob/master/README.md * @type {Schema} */ schema(props, name, componentName) { let err: null | Error = null; if (props[name]) { if (!isSchema(props[name])) err = new Error( '`schema` must be a proper yup schema: (' + componentName + ')', ); } return err; }, /** * yup schema context */ context: PropTypes.object, /** * toggle debug mode, which `console.warn`s validation errors */ debug: PropTypes.bool, }; _Form.displayName = 'Form'; export default _Form; export { formGetter as getter, formSetter as setter };
the_stack
import { DialogConnectionFactory } from "../common.speech/DialogConnectorFactory"; import { DialogServiceAdapter, IAgentConfig, IAuthentication, IConnectionFactory, RecognitionMode, RecognizerConfig, ServiceRecognizerBase, SpeechServiceConfig, } from "../common.speech/Exports"; import { Deferred, marshalPromiseToCallbacks } from "../common/Exports"; import { ActivityReceivedEventArgs } from "./ActivityReceivedEventArgs"; import { AudioConfigImpl } from "./Audio/AudioConfig"; import { AudioOutputFormatImpl } from "./Audio/AudioOutputFormat"; import { Contracts } from "./Contracts"; import { DialogServiceConfig, DialogServiceConfigImpl } from "./DialogServiceConfig"; import { AudioConfig, PropertyCollection, Recognizer, SpeechRecognitionCanceledEventArgs, SpeechRecognitionEventArgs, SpeechRecognitionResult } from "./Exports"; import { PropertyId } from "./PropertyId"; import { TurnStatusReceivedEventArgs } from "./TurnStatusReceivedEventArgs"; /** * Dialog Service Connector * @class DialogServiceConnector */ export class DialogServiceConnector extends Recognizer { private privIsDisposed: boolean; private isTurnComplete: boolean; /** * Initializes an instance of the DialogServiceConnector. * @constructor * @param {DialogServiceConfig} dialogConfig - Set of properties to configure this recognizer. * @param {AudioConfig} audioConfig - An optional audio config associated with the recognizer */ public constructor(dialogConfig: DialogServiceConfig, audioConfig?: AudioConfig) { const dialogServiceConfigImpl = dialogConfig as DialogServiceConfigImpl; Contracts.throwIfNull(dialogConfig, "dialogConfig"); super(audioConfig, dialogServiceConfigImpl.properties, new DialogConnectionFactory()); this.isTurnComplete = true; this.privIsDisposed = false; this.privProperties = dialogServiceConfigImpl.properties.clone(); const agentConfig = this.buildAgentConfig(); this.privReco.agentConfig.set(agentConfig); } /** * The event recognizing signals that an intermediate recognition result is received. * @member DialogServiceConnector.prototype.recognizing * @function * @public */ public recognizing: (sender: DialogServiceConnector, event: SpeechRecognitionEventArgs) => void; /** * The event recognized signals that a final recognition result is received. * @member DialogServiceConfig.prototype.recognized * @function * @public */ public recognized: (sender: DialogServiceConnector, event: SpeechRecognitionEventArgs) => void; /** * The event canceled signals that an error occurred during recognition. * @member DialogServiceConnector.prototype.canceled * @function * @public */ public canceled: (sender: DialogServiceConnector, event: SpeechRecognitionCanceledEventArgs) => void; /** * The event activityReceived signals that an activity has been received. * @member DialogServiceConnector.prototype.activityReceived * @function * @public */ public activityReceived: (sender: DialogServiceConnector, event: ActivityReceivedEventArgs) => void; /** * The event turnStatusReceived signals that a turn status message has been received. These messages are * associated with both an interaction and a conversation. They are used to notify the client in the event * of an interaction failure with the dialog backend, e.g. in the event of a network issue, timeout, crash, * or other problem. * @member DialogServiceConnector.prototype.turnStatusReceived * @function * @public */ public turnStatusReceived: (sender: DialogServiceConnector, event: TurnStatusReceivedEventArgs) => void; /** * Starts a connection to the service. * Users can optionally call connect() to manually set up a connection in advance, before starting interactions. * * Note: On return, the connection might not be ready yet. Please subscribe to the Connected event to * be notified when the connection is established. * @member DialogServiceConnector.prototype.connect * @function * @public */ public connect(cb?: () => void, err?: (error: string) => void): void { marshalPromiseToCallbacks(this.privReco.connect(), cb, err); } /** * Closes the connection the service. * Users can optionally call disconnect() to manually shutdown the connection of the associated DialogServiceConnector. * * If disconnect() is called during a recognition, recognition will fail and cancel with an error. */ public disconnect(cb?: () => void, err?: (error: string) => void): void { marshalPromiseToCallbacks(this.privReco.disconnect(), cb, err); } /** * Gets the authorization token used to communicate with the service. * @member DialogServiceConnector.prototype.authorizationToken * @function * @public * @returns {string} Authorization token. */ public get authorizationToken(): string { return this.properties.getProperty(PropertyId.SpeechServiceAuthorization_Token); } /** * Sets the authorization token used to communicate with the service. * @member DialogServiceConnector.prototype.authorizationToken * @function * @public * @param {string} token - Authorization token. */ public set authorizationToken(token: string) { Contracts.throwIfNullOrWhitespace(token, "token"); this.properties.setProperty(PropertyId.SpeechServiceAuthorization_Token, token); } /** * The collection of properties and their values defined for this DialogServiceConnector. * @member DialogServiceConnector.prototype.properties * @function * @public * @returns {PropertyCollection} The collection of properties and their values defined for this DialogServiceConnector. */ public get properties(): PropertyCollection { return this.privProperties; } /** Gets the template for the activity generated by service from speech. * Properties from the template will be stamped on the generated activity. * It can be empty */ public get speechActivityTemplate(): string { return this.properties.getProperty(PropertyId.Conversation_Speech_Activity_Template); } /** Sets the template for the activity generated by service from speech. * Properties from the template will be stamped on the generated activity. * It can be null or empty. * Note: it has to be a valid Json object. */ public set speechActivityTemplate(speechActivityTemplate: string) { this.properties.setProperty(PropertyId.Conversation_Speech_Activity_Template, speechActivityTemplate); } /** * Starts recognition and stops after the first utterance is recognized. * @member DialogServiceConnector.prototype.listenOnceAsync * @function * @public * @param cb - Callback that received the result when the reco has completed. * @param err - Callback invoked in case of an error. */ public listenOnceAsync(cb?: (e: SpeechRecognitionResult) => void, err?: (e: string) => void): void { if (this.isTurnComplete) { Contracts.throwIfDisposed(this.privIsDisposed); const callbackHolder = async (): Promise<SpeechRecognitionResult> => { await this.privReco.connect(); await this.implRecognizerStop(); this.isTurnComplete = false; const ret: Deferred<SpeechRecognitionResult> = new Deferred<SpeechRecognitionResult>(); await this.privReco.recognize(RecognitionMode.Conversation, ret.resolve, ret.reject); const e: SpeechRecognitionResult = await ret.promise; await this.implRecognizerStop(); return e; }; const retPromise: Promise<SpeechRecognitionResult> = callbackHolder(); retPromise.catch(() => { // Destroy the recognizer. /* tslint:disable:no-empty */ // We've done all we can here. this.dispose(true).catch(() => { }); }); marshalPromiseToCallbacks(retPromise.finally((): void => { this.isTurnComplete = true; }), cb, err); } } public sendActivityAsync(activity: string, cb?: () => void, errCb?: (error: string) => void): void { marshalPromiseToCallbacks((this.privReco as DialogServiceAdapter).sendMessage(activity), cb, errCb); } /** * closes all external resources held by an instance of this class. * @member DialogServiceConnector.prototype.close * @function * @public */ public close(cb?: () => void, err?: (error: string) => void): void { Contracts.throwIfDisposed(this.privIsDisposed); marshalPromiseToCallbacks(this.dispose(true), cb, err); } protected async dispose(disposing: boolean): Promise<void> { if (this.privIsDisposed) { return; } if (disposing) { this.privIsDisposed = true; await this.implRecognizerStop(); await super.dispose(disposing); } } protected createRecognizerConfig(speechConfig: SpeechServiceConfig): RecognizerConfig { return new RecognizerConfig(speechConfig, this.privProperties); } protected createServiceRecognizer( authentication: IAuthentication, connectionFactory: IConnectionFactory, audioConfig: AudioConfig, recognizerConfig: RecognizerConfig): ServiceRecognizerBase { const audioSource: AudioConfigImpl = audioConfig as AudioConfigImpl; return new DialogServiceAdapter(authentication, connectionFactory, audioSource, recognizerConfig, this); } private buildAgentConfig(): IAgentConfig { const communicationType = this.properties.getProperty("Conversation_Communication_Type", "Default"); return { botInfo: { commType: communicationType, commandsCulture: undefined, connectionId: this.properties.getProperty(PropertyId.Conversation_Agent_Connection_Id), conversationId: this.properties.getProperty(PropertyId.Conversation_Conversation_Id, undefined), fromId: this.properties.getProperty(PropertyId.Conversation_From_Id, undefined), ttsAudioFormat: this.properties.getProperty(PropertyId.SpeechServiceConnection_SynthOutputFormat, undefined) }, version: 0.2 }; } }
the_stack
import * as core from "@actions/core"; import * as github from "@actions/github"; import * as im from "@actions/exec/lib/interfaces"; // eslint-disable-line no-unused-vars import * as tr from "@actions/exec/lib/toolrunner"; import * as io from "@actions/io"; import * as os from "os"; import * as path from "path"; import * as url from "url"; import fs from "fs"; import retry from "async-retry"; import * as dep from "./dependencies"; const validROS1Distros: string[] = ["kinetic", "lunar", "melodic", "noetic"]; const validROS2Distros: string[] = [ "dashing", "eloquent", "foxy", "galactic", "rolling", ]; const targetROS1DistroInput: string = "target-ros1-distro"; const targetROS2DistroInput: string = "target-ros2-distro"; const isLinux: boolean = process.platform == "linux"; const isWindows: boolean = process.platform == "win32"; /** * Join string array using a single space and make sure to filter out empty elements. * * @param values the string values array * @returns the joined string */ export function filterNonEmptyJoin(values: string[]): string { return values.filter((v) => v.length > 0).join(" "); } /** * Check if a string is a valid JSON string. * * @param str the string to validate * @returns `true` if valid, `false` otherwise */ function isValidJson(str: string): boolean { try { JSON.parse(str); } catch (e) { return false; } return true; } /** * Convert local paths to URLs. * * The user can pass the VCS repo file either as a URL or a path. * If it is a path, this function will convert it into a URL (file://...). * If the file is already passed as an URL, this function does nothing. * * @param vcsRepoFileUrl path or URL to the repo file * @returns URL to the repo file */ function resolveVcsRepoFileUrl(vcsRepoFileUrl: string): string { if (fs.existsSync(vcsRepoFileUrl)) { return url.pathToFileURL(path.resolve(vcsRepoFileUrl)).href; } else { return vcsRepoFileUrl; } } /** * Execute a command in bash and wrap the output in a log group. * * @param commandLine command to execute (can include additional args). Must be correctly escaped. * @param commandPrefix optional string used to prefix the command to be executed. * @param options optional exec options. See ExecOptions * @param log_message log group title. * @returns Promise<number> exit code */ export async function execBashCommand( commandLine: string, commandPrefix?: string, options?: im.ExecOptions, log_message?: string ): Promise<number> { commandPrefix = commandPrefix || ""; const bashScript = `${commandPrefix}${commandLine}`; const message = log_message || `Invoking: bash -c '${bashScript}'`; let toolRunnerCommandLine = ""; let toolRunnerCommandLineArgs: string[] = []; if (isWindows) { toolRunnerCommandLine = "C:\\Windows\\system32\\cmd.exe"; // This passes the same flags to cmd.exe that "run:" in a workflow. // https://help.github.com/en/actions/automating-your-workflow-with-github-actions/workflow-syntax-for-github-actions#using-a-specific-shell // Except for /D, which disables the AutoRun functionality from command prompt // and it blocks Python virtual environment activation if one configures it in // the previous steps. toolRunnerCommandLineArgs = [ "/E:ON", "/V:OFF", "/S", "/C", "call", "%programfiles(x86)%\\Microsoft Visual Studio\\2019\\Enterprise\\VC\\Auxiliary\\Build\\vcvarsall.bat", "amd64", "&", "C:\\Program Files\\Git\\bin\\bash.exe", "-c", bashScript, ]; } else { toolRunnerCommandLine = "bash"; toolRunnerCommandLineArgs = ["-c", bashScript]; } const runner: tr.ToolRunner = new tr.ToolRunner( toolRunnerCommandLine, toolRunnerCommandLineArgs, options ); if (options && options.silent) { return runner.exec(); } return core.group(message, () => { return runner.exec(); }); } //Determine whether all inputs name supported ROS distributions. export function validateDistros( ros1Distro: string, ros2Distro: string ): boolean { if (!ros1Distro && !ros2Distro) { core.setFailed( `Neither '${targetROS1DistroInput}' or '${targetROS2DistroInput}' inputs were set, at least one is required.` ); return false; } if (ros1Distro && validROS1Distros.indexOf(ros1Distro) <= -1) { core.setFailed( `Input ${ros1Distro} was not a valid ROS 1 distribution for '${targetROS1DistroInput}'. Valid values: ${validROS1Distros}` ); return false; } if (ros2Distro && validROS2Distros.indexOf(ros2Distro) <= -1) { core.setFailed( `Input ${ros2Distro} was not a valid ROS 2 distribution for '${targetROS2DistroInput}'. Valid values: ${validROS2Distros}` ); return false; } return true; } /** * Install ROS dependencies for given packages in the workspace, for all ROS distros being used. */ async function installRosdeps( packageSelection: string, workspaceDir: string, options: im.ExecOptions, ros1Distro?: string, ros2Distro?: string ): Promise<number> { const scriptName = "install_rosdeps.sh"; const scriptPath = path.join(workspaceDir, scriptName); const scriptContent = `#!/bin/bash set -euxo pipefail if [ $# != 1 ]; then echo "Specify rosdistro name as single argument to this script" exit 1 fi DISTRO=$1 package_paths=$(colcon list --paths-only ${packageSelection}) # suppress errors from unresolved install keys to preserve backwards compatibility # due to difficulty reading names of some non-catkin dependencies in the ros2 core # see https://index.ros.org/doc/ros2/Installation/Foxy/Linux-Development-Setup/#install-dependencies-using-rosdep rosdep install -r --from-paths $package_paths --ignore-src --skip-keys rti-connext-dds-5.3.1 --rosdistro $DISTRO -y || true`; fs.writeFileSync(scriptPath, scriptContent, { mode: 0o766 }); let exitCode = 0; if (ros1Distro) { exitCode += await execBashCommand( `./${scriptName} ${ros1Distro}`, "", options ); } if (ros2Distro) { exitCode += await execBashCommand( `./${scriptName} ${ros2Distro}`, "", options ); } return exitCode; } /** * Run tests and process & aggregate coverage results. * * @param colconCommandPrefix the prefix to use before colcon commands * @param options the exec options * @param testPackageSelection the package selection option string * @param extra_options the extra options for 'colcon test' * @param coverageIgnorePattern the coverage filter pattern to use for lcov, or an empty string */ async function runTests( colconCommandPrefix: string, options: im.ExecOptions, testPackageSelection: string, extra_options: string[], coverageIgnorePattern: string ): Promise<void> { // ignoreReturnCode is set to true to avoid having a lack of coverage // data fail the build. const colconLcovInitialCmd = "colcon lcov-result --initial"; await execBashCommand(colconLcovInitialCmd, colconCommandPrefix, { ...options, ignoreReturnCode: true, }); const colconTestCmd = filterNonEmptyJoin([ `colcon test`, `--event-handlers console_cohesion+`, `--return-code-on-test-failure`, testPackageSelection, `${extra_options.join(" ")}`, ]); await execBashCommand(colconTestCmd, colconCommandPrefix, options); // ignoreReturnCode, check comment above in --initial const colconLcovResultCmd = filterNonEmptyJoin([ `colcon lcov-result`, coverageIgnorePattern !== "" ? `--filter ${coverageIgnorePattern}` : "", testPackageSelection, `--verbose`, ]); await execBashCommand(colconLcovResultCmd, colconCommandPrefix, { ...options, ignoreReturnCode: true, }); const colconCoveragepyResultCmd = filterNonEmptyJoin([ `colcon coveragepy-result`, testPackageSelection, `--verbose`, `--coverage-report-args -m`, ]); await execBashCommand( colconCoveragepyResultCmd, colconCommandPrefix, options ); } async function run_throw(): Promise<void> { const repo = github.context.repo; const workspace = process.env.GITHUB_WORKSPACE as string; const colconDefaults = core.getInput("colcon-defaults"); const colconMixinRepo = core.getInput("colcon-mixin-repository"); const extraCmakeArgs = core.getInput("extra-cmake-args"); const colconExtraArgs = core.getInput("colcon-extra-args"); const importToken = core.getInput("import-token"); const packageNameInput = core.getInput("package-name"); const packageNames = packageNameInput ? filterNonEmptyJoin(packageNameInput.split(RegExp("\\s"))) : undefined; const buildPackageSelection = packageNames ? `--packages-up-to ${packageNames}` : ""; const testPackageSelection = packageNames ? `--packages-select ${packageNames}` : ""; const rosWorkspaceName = "ros_ws"; core.setOutput("ros-workspace-directory-name", rosWorkspaceName); const rosWorkspaceDir = path.join(workspace, rosWorkspaceName); const targetRos1Distro = core.getInput(targetROS1DistroInput); const targetRos2Distro = core.getInput(targetROS2DistroInput); const vcsRepoFileUrlListAsString = core.getInput("vcs-repo-file-url") || ""; let vcsRepoFileUrlList = vcsRepoFileUrlListAsString.split(RegExp("\\s")); const skipTests = core.getInput("skip-tests") === "true"; // Check if PR overrides/adds supplemental repos files const vcsReposOverride = dep.getReposFilesOverride(github.context.payload); const vcsReposSupplemental = dep.getReposFilesSupplemental( github.context.payload ); await core.group( "Repos files: override" + (vcsReposOverride.length === 0 ? " - none" : ""), () => { for (const vcsRepos of vcsReposOverride) { core.info("\t" + vcsRepos); } return Promise.resolve(); } ); if (vcsReposOverride.length > 0) { vcsRepoFileUrlList = vcsReposOverride; } await core.group( "Repos files: supplemental" + (vcsReposSupplemental.length === 0 ? " - none" : ""), () => { for (const vcsRepos of vcsReposSupplemental) { core.info("\t" + vcsRepos); } return Promise.resolve(); } ); vcsRepoFileUrlList = vcsRepoFileUrlList.concat(vcsReposSupplemental); const vcsRepoFileUrlListNonEmpty = vcsRepoFileUrlList.filter((x) => x != ""); const coverageIgnorePattern = core.getInput("coverage-ignore-pattern"); if (!validateDistros(targetRos1Distro, targetRos2Distro)) { return; } // rosdep does not reliably work on Windows, see // ros-infrastructure/rosdep#610 for instance. So, we do not run it. if (!isWindows) { await retry( async () => { await execBashCommand("rosdep update --include-eol-distros"); }, { retries: 3, } ); } // Reset colcon configuration and create defaults file if one was provided. await io.rmRF(path.join(os.homedir(), ".colcon")); let colconDefaultsFile = ""; if (colconDefaults.length > 0) { if (!isValidJson(colconDefaults)) { core.setFailed( `colcon-defaults value is not a valid JSON string:\n${colconDefaults}` ); return; } colconDefaultsFile = path.join( fs.mkdtempSync(path.join(os.tmpdir(), "colcon-defaults-")), "defaults.yaml" ); fs.writeFileSync(colconDefaultsFile, colconDefaults); } // Wipe out the workspace directory to ensure the workspace is always // identical. await io.rmRF(rosWorkspaceDir); // Checkout ROS 2 from source and install ROS 2 system dependencies await io.mkdirP(rosWorkspaceDir + "/src"); const options: im.ExecOptions = { cwd: rosWorkspaceDir, env: { ...process.env, ROS_VERSION: targetRos2Distro ? "2" : "1", ROS_PYTHON_VERSION: targetRos2Distro || (targetRos1Distro && targetRos1Distro == "noetic") ? "3" : "2", }, }; if (colconDefaultsFile !== "") { options.env = { ...options.env, COLCON_DEFAULTS_FILE: colconDefaultsFile, }; } if (isLinux) { options.env = { ...options.env, DEBIAN_FRONTEND: "noninteractive", }; } if (importToken !== "") { // Unset all local extraheader config entries possibly set by actions/checkout, // because local settings take precedence and the default token used by // actions/checkout might not have the right permissions for any/all repos await execBashCommand( `/usr/bin/git config --local --unset-all http.https://github.com/.extraheader || true`, undefined, options ); await execBashCommand( String.raw`/usr/bin/git submodule foreach --recursive git config --local --name-only --get-regexp 'http\.https\:\/\/github\.com\/\.extraheader'` + ` && git config --local --unset-all 'http.https://github.com/.extraheader' || true`, undefined, options ); // Use a global insteadof entry because local configs aren't observed by git clone await execBashCommand( `/usr/bin/git config --global url.https://x-access-token:${importToken}@github.com.insteadof 'https://github.com'`, undefined, options ); if (core.isDebug()) { await execBashCommand( `/usr/bin/git config --list --show-origin || true`, undefined, options ); } } // Make sure to delete root .colcon directory if it exists // This is because, for some reason, using Docker, commands might get run as root await execBashCommand( `rm -rf ${path.join(path.sep, "root", ".colcon")} || true`, undefined, { ...options, silent: true } ); for (const vcsRepoFileUrl of vcsRepoFileUrlListNonEmpty) { const resolvedUrl = resolveVcsRepoFileUrl(vcsRepoFileUrl); await execBashCommand( `vcs import --force --recursive src/ --input ${resolvedUrl}`, undefined, options ); } // If the package under tests is part of ros.repos, remove it first. // We do not want to allow the "default" head state of the package to // to be present in the workspace, and colcon will fail stating it found twice // a package with an identical name. let posixPathScriptPath = ""; if (isWindows) { // vcs might output paths with a mix of forward slashes and backslashes on Windows posixPathScriptPath = path.join(rosWorkspaceDir, "slash_converter.sh"); const scriptContent = String.raw`#!/bin/bash while IFS= read -r line; do echo "$line" | sed 's/\\/\//g' done`; fs.writeFileSync(posixPathScriptPath, scriptContent, { mode: 0o766, }); posixPathScriptPath = posixPathScriptPath.replace(/\\/g, "/"); } const posixRosWorkspaceDir = isWindows ? rosWorkspaceDir.replace(/\\/g, "/") : rosWorkspaceDir; await execBashCommand( `vcs diff -s --repos ${posixRosWorkspaceDir} | cut -d ' ' -f 1 | grep "${repo["repo"]}$"` + (isWindows ? ` | ${posixPathScriptPath}` : "") + ` | xargs rm -rf` ); // The repo file for the repository needs to be generated on-the-fly to // incorporate the custom repository URL and branch name, when a PR is // being built. let repoFullName = process.env.GITHUB_REPOSITORY as string; if (github.context.payload.pull_request) { repoFullName = github.context.payload.pull_request.head.repo.full_name; } const headRef = process.env.GITHUB_HEAD_REF as string; const commitRef = headRef || github.context.sha; const repoFilePath = path.join(rosWorkspaceDir, "package.repo"); // Add a random string prefix to avoid naming collisions when checking out the test repository const randomStringPrefix = Math.random().toString(36).substring(2, 15); const repoFileContent = `repositories: ${randomStringPrefix}/${repo["repo"]}: type: git url: 'https://github.com/${repoFullName}.git' version: '${commitRef}'`; fs.writeFileSync(repoFilePath, repoFileContent); await execBashCommand( "vcs import --force --recursive src/ < package.repo", undefined, options ); // Print HEAD commits of all repos await execBashCommand("vcs log -l1 src/", undefined, options); if (isLinux) { // Always update APT before installing packages on Ubuntu await execBashCommand("sudo apt-get update"); } await installRosdeps( buildPackageSelection, rosWorkspaceDir, options, targetRos1Distro, targetRos2Distro ); if (colconDefaults.includes(`"mixin"`) && colconMixinRepo !== "") { await execBashCommand( `colcon mixin add default '${colconMixinRepo}'`, undefined, options ); await execBashCommand("colcon mixin update default", undefined, options); } let extra_options: string[] = []; if (colconExtraArgs !== "") { extra_options = extra_options.concat(colconExtraArgs); } // Add the future install bin directory to PATH. // This enables cmake find_package to find packages installed in the // colcon install directory, even if local_setup.sh has not been sourced. // // From the find_package doc: // https://cmake.org/cmake/help/latest/command/find_package.html // 5. Search the standard system environment variables. // Path entries ending in /bin or /sbin are automatically converted to // their parent directories: // PATH // // ament_cmake should handle this automatically, but we are seeing cases // where this does not happen. See issue #26 for relevant CI logs. core.addPath(path.join(rosWorkspaceDir, "install", "bin")); // Source any installed ROS distributions if they are present let colconCommandPrefix = ""; if (isLinux) { if (targetRos1Distro) { const ros1SetupPath = `/opt/ros/${targetRos1Distro}/setup.sh`; if (fs.existsSync(ros1SetupPath)) { colconCommandPrefix += `source ${ros1SetupPath} && `; } } if (targetRos2Distro) { const ros2SetupPath = `/opt/ros/${targetRos2Distro}/setup.sh`; if (fs.existsSync(ros2SetupPath)) { colconCommandPrefix += `source ${ros2SetupPath} && `; } } } else if (isWindows) { // Windows only supports ROS2 if (targetRos2Distro) { const ros2SetupPath = `c:/dev/${targetRos2Distro}/ros2-windows/setup.bat`; if (fs.existsSync(ros2SetupPath)) { colconCommandPrefix += `${ros2SetupPath} && `; } } } let colconBuildCmd = filterNonEmptyJoin([ `colcon build`, `--event-handlers console_cohesion+`, buildPackageSelection, `${extra_options.join(" ")}`, extraCmakeArgs !== "" ? `--cmake-args ${extraCmakeArgs}` : "", ]); if (!isWindows) { colconBuildCmd = colconBuildCmd.concat(" --symlink-install"); } await execBashCommand(colconBuildCmd, colconCommandPrefix, options); if (!skipTests) { await runTests( colconCommandPrefix, options, testPackageSelection, extra_options, coverageIgnorePattern ); } else { core.info("Skipping tests"); } if (importToken !== "") { // Unset config so that it doesn't leak to other actions await execBashCommand( `/usr/bin/git config --global --unset-all url.https://x-access-token:${importToken}@github.com.insteadof`, undefined, options ); } } async function run(): Promise<void> { try { await run_throw(); } catch (error) { core.setFailed(error.message); } } run();
the_stack
import React, { RefObject, createRef, Fragment } from "react"; import { Comment, Form, Button, Header, RatingProps, Rating, Popup, Divider, Container } from "semantic-ui-react"; import connectAllProps from "../../../shared/connect"; import User from "../../../models/User"; import CommentClass from "../../../models/Comment"; import UserAvatar from "../user/UserAvatar"; import { FormattedMessage, MessageDescriptor } from "react-intl"; import { PrimitiveType } from "intl-messageformat"; import PostType from "../../../models/PostType"; import { byCommentedAtLatestFirst, byCommentedAtOldestFirst } from "../../../shared/date"; import { ADD_COMMENT_START, ADD_COMMENT_SUCCESS } from "../../../actions/comment"; import WarningModal from "../shared/WarningModal"; import { getNameListString, getMentionedUserId, getAllNames } from "../../../shared/string"; import moment from "moment"; import { CONTAINER_STYLE } from "../../../shared/styles"; import Loading from "./Loading"; import { ComponentProps } from "../../../shared/ComponentProps"; import "../../css/text-complete.css"; import { registerAutoComplete } from "../autocomplete"; interface Props extends ComponentProps { targetId: string; target: PostType; maxThreadStackDepth: number; commentsOrder: "latest" | "oldest"; replyFormPosition: "top" | "bottom"; threaded: boolean; divided?: boolean; withHeader?: boolean; } interface States { showReplyFormForCommentId: string; commentEditing: boolean; replyCommentEditing: boolean; openDeleteWarning: boolean; } class CommentSection extends React.Component<Props, States> { private commentFormRef: RefObject<any>; private replyCommentFormRef: RefObject<any>; private toDeleteId: string = ""; private userNamesCache: string[]; componentDidMount() { this.registerAutoCompleteForForms(); if (this.props.state.userState.currentUser) { this.props.actions.getComments(this.props.target, this.props.targetId); } } componentDidUpdate(prevProps: Props, prevState: States) { if (prevProps.state.commentState.updating === ADD_COMMENT_START && this.props.state.commentState.updating === ADD_COMMENT_SUCCESS) { // Reset this.commentFormRef.current && (this.commentFormRef.current.value = ""); this.replyCommentFormRef.current && (this.replyCommentFormRef.current.value = ""); this.setState({ showReplyFormForCommentId: this.props.targetId, commentEditing: false, replyCommentEditing: false }); } if (!prevProps.state.userState.currentUser && this.props.state.userState.currentUser) { this.props.actions.getComments(this.props.target, this.props.targetId); } if (prevProps.state.commentState.loading && !this.props.state.commentState.loading && window.location.hash) { const commentElement: HTMLElement | null = document.getElementById(window.location.hash.substr(1)); if (commentElement) { commentElement.scrollIntoView({ behavior: "smooth", block: "center" }); commentElement.animate([ {backgroundColor: "white"}, {backgroundColor: "white"}, {backgroundColor: "#FDFF47"}, {backgroundColor: "white"} ], 2000); } } if (prevState.showReplyFormForCommentId !== this.state.showReplyFormForCommentId) { this.registerAutoCompleteForForms(); } } constructor(props: Props) { super(props); this.commentFormRef = createRef(); this.replyCommentFormRef = createRef(); this.userNamesCache = getAllNames(this.props.state.userDictionary); this.state = { showReplyFormForCommentId: this.props.targetId, commentEditing: false, replyCommentEditing: false, openDeleteWarning: false }; } render(): React.ReactElement<any> { const getString: (descriptor: MessageDescriptor, values?: Record<string, PrimitiveType>) => string = this.props.intl.formatMessage; return <Comment.Group threaded={this.props.threaded}> { this.props.withHeader ? <Header as="h3" dividing> <FormattedMessage id={"component.comment.title"} /> {"("} { this.props.state.userState.currentUser ? this.props.state.commentState.data.length : <FormattedMessage id={"component.comment.private"} /> } {")"} </Header> : undefined } { this.props.replyFormPosition === "top" ? this.renderPrimaryReplyForm() : undefined } { this.props.state.commentState.loading ? <Container text style={CONTAINER_STYLE}> <Loading/> </Container> : this.props.state.commentState.data .filter((value: CommentClass, index: number) => !value.parent) .sort(this.props.commentsOrder === "latest" ? byCommentedAtLatestFirst : byCommentedAtOldestFirst) .map((value: CommentClass) => this.renderComment(value)) } <WarningModal descriptionIcon="delete" open={this.state.openDeleteWarning} descriptionText={getString({id: "component.comment.delete_title"})} warningText={getString({id: "component.comment.delete_confirmation"})} onConfirm={() => { this.props.actions.removeComment(this.props.target, this.toDeleteId); this.setState({openDeleteWarning: false}); }} onCancel={() => { this.setState({openDeleteWarning: false}); }}/> { this.props.replyFormPosition === "bottom" ? this.renderPrimaryReplyForm() : undefined } </Comment.Group>; } private renderPrimaryReplyForm = (): React.ReactElement<any> | undefined => { if (this.props.targetId === this.state.showReplyFormForCommentId) { return this.renderReplyForm(this.state.commentEditing, this.props.targetId, this.commentFormRef); } else { return undefined; } } private renderReplyForm = (editing: boolean, id: string, ref: RefObject<any>): React.ReactElement<any> | undefined => { if (!this.props.state.userState.currentUser) { return undefined; } if (id !== this.props.targetId && id !== this.state.showReplyFormForCommentId) { return undefined; } const getString: (descriptor: MessageDescriptor, values?: Record<string, PrimitiveType>) => string = this.props.intl.formatMessage; const user: User = this.props.state.userState.currentUser; return <div style={{display: "flex", flexDirection: "row", alignItems: "flex-start"}}> <UserAvatar user={user} /> <Form reply style={{flex: 1, marginLeft: 10, marginTop: 0}}> <textarea ref={ref} rows={3} style={{marginBottom: 4}} onChange={(event: any) => { this.onTextChange(event, ref); }} placeholder={ getString({id: "component.comment.placeholder"}) } /> <Button disabled={!editing} loading={this.props.state.commentState.updating === ADD_COMMENT_START} content={ getString({id: "component.comment.submit"}) } icon="edit" primary onClick={() => { this.onSubmitComment(id, ref); }} /> </Form> </div>; }; private onTextChange = (event: any, ref: RefObject<any>): void => { if (ref === this.commentFormRef && ref.current) { if (this.state.commentEditing && !ref.current.value) { this.setState({commentEditing: false}); } else if (!this.state.commentEditing && ref.current.value) { this.setState({commentEditing: true}); } } else if (ref === this.replyCommentFormRef && ref.current) { if (this.state.replyCommentEditing && !ref.current.value) { this.setState({replyCommentEditing: false}); } else if (!this.state.replyCommentEditing && ref.current.value) { this.setState({replyCommentEditing: true}); } } } private onSubmitComment = (id: string, ref: RefObject<any>): void => { if (ref.current && ref.current.value) { const content: string = ref.current.value; this.props.actions.addComment( this.props.target, this.props.targetId, id === this.props.targetId ? "" : id, content, getMentionedUserId(content, this.props.state.userDictionary) ); } }; private renderComment = (comment: CommentClass, stackDepth: number = 0): React.ReactElement<any> => { const createDate: Date = comment.createdAt ? new Date(comment.createdAt) : new Date(0); const author: User = this.props.state.userDictionary[comment.author]; return <Comment key={comment._id} id={comment._id}> { this.props.divided ? <Divider /> : undefined } <div /> <Comment.Avatar src={author.avatarUrl ? author.avatarUrl : "/images/avatar.png"} /> <Comment.Content> {/* There is a bug of style for <Comment /> in semantic-ui-react. Here we explicitly set the style */} <div style={{display: "flex", flexDirection: "row", alignItems: "flex-end"}}> <Comment.Author> {author.name} </Comment.Author> <Comment.Metadata> {moment(createDate).fromNow()} </Comment.Metadata> </div> <Comment.Text> {comment.content} </Comment.Text> {this.renderActions(comment, stackDepth)} </Comment.Content> <Comment.Group threaded={this.props.threaded}> { this.props.replyFormPosition === "top" ? this.renderReplyForm(this.state.replyCommentEditing, comment._id, this.replyCommentFormRef) : undefined } {/* Recursively render the children */ this.props.state.commentState.data .filter((value: CommentClass, index: number) => (value.parent === comment._id)) .sort(this.props.commentsOrder === "latest" ? byCommentedAtLatestFirst : byCommentedAtOldestFirst) .map((value: CommentClass) => this.renderComment(value, stackDepth + 1)) } { this.props.replyFormPosition === "bottom" ? this.renderReplyForm(this.state.replyCommentEditing, comment._id, this.replyCommentFormRef) : undefined } </Comment.Group> </Comment>; }; private renderActions = (comment: CommentClass, stackDepth: number): any => { const likersPopUpContent: string = getNameListString(comment.likes, this.props.state.userDictionary); return <Comment.Actions> {/* There is a bug for <Comment.Action />. It will automatically call onClick. */} { this.props.state.userState.currentUser && stackDepth < this.props.maxThreadStackDepth ? /* eslint-disable-next-line */ <Comment.Action onClick={() => {this.onToggleReplyForm(comment._id); }}> <FormattedMessage id="component.comment.reply"/> </Comment.Action> : undefined } { this.props.state.userState.currentUser && this.props.state.userState.currentUser._id === comment.author ? /* eslint-disable-next-line */ <Fragment> <Comment.Action onClick={() => { this.deleteComment(comment._id); }}> <FormattedMessage id="component.comment.delete"/> </Comment.Action> </Fragment> : undefined } <Popup trigger={this.renderRating(comment)} disabled={!likersPopUpContent} content={likersPopUpContent} position="bottom center" /> </Comment.Actions>; }; private onToggleReplyForm = (id: string): void => { console.log("onToggleReplyForm: " + id); if (this.state.showReplyFormForCommentId === id) { this.setState({ showReplyFormForCommentId: this.props.targetId }); } else { this.setState({ showReplyFormForCommentId: id }); } }; private deleteComment = (id: string): void => { this.setState({openDeleteWarning: true }); this.toDeleteId = id; } private renderRating = (comment: CommentClass): any => { const user: User | undefined = this.props.state.userState.currentUser; const hasRated: boolean = !!user && comment.likes && (comment.likes.findIndex((value: string) => user._id === value) >= 0); return <label style={{color: "grey"}}> <Rating size="small" icon="heart" defaultRating={hasRated ? 1 : 0} maxRating={1} disabled={!user || comment.author === user._id} onRate={ (event: React.MouseEvent<HTMLDivElement>, data: RatingProps): void => { if (!this.props.state.userState.currentUser) { return; } this.props.actions.rateComment( data.rating as number, comment._id, user && user._id); }}/> { comment.likes ? comment.likes.length : 0 } </label>; } private registerAutoCompleteForForms = (): void => { if (this.replyCommentFormRef.current) { registerAutoComplete(this.replyCommentFormRef.current, this.userNamesCache); } if (this.commentFormRef.current) { registerAutoComplete(this.commentFormRef.current, this.userNamesCache); } } } export default connectAllProps(CommentSection);
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/billingSubscriptionsMappers"; import * as Parameters from "../models/parameters"; import { BillingManagementClientContext } from "../billingManagementClientContext"; /** Class representing a BillingSubscriptions. */ export class BillingSubscriptions { private readonly client: BillingManagementClientContext; /** * Create a BillingSubscriptions. * @param {BillingManagementClientContext} client Reference to the service client. */ constructor(client: BillingManagementClientContext) { this.client = client; } /** * Lists the subscriptions for a customer. The operation is supported only for billing accounts * with agreement type Microsoft Partner Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsListByCustomerResponse> */ listByCustomer(billingAccountName: string, customerName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsListByCustomerResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param callback The callback */ listByCustomer(billingAccountName: string, customerName: string, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param customerName The ID that uniquely identifies a customer. * @param options The optional parameters * @param callback The callback */ listByCustomer(billingAccountName: string, customerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; listByCustomer(billingAccountName: string, customerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscriptionsListResult>, callback?: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): Promise<Models.BillingSubscriptionsListByCustomerResponse> { return this.client.sendOperationRequest( { billingAccountName, customerName, options }, listByCustomerOperationSpec, callback) as Promise<Models.BillingSubscriptionsListByCustomerResponse>; } /** * Lists the subscriptions for a billing account. The operation is supported for billing accounts * with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsListByBillingAccountResponse> */ listByBillingAccount(billingAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsListByBillingAccountResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param callback The callback */ listByBillingAccount(billingAccountName: string, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param options The optional parameters * @param callback The callback */ listByBillingAccount(billingAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; listByBillingAccount(billingAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscriptionsListResult>, callback?: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): Promise<Models.BillingSubscriptionsListByBillingAccountResponse> { return this.client.sendOperationRequest( { billingAccountName, options }, listByBillingAccountOperationSpec, callback) as Promise<Models.BillingSubscriptionsListByBillingAccountResponse>; } /** * Lists the subscriptions that are billed to a billing profile. The operation is supported for * billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner * Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsListByBillingProfileResponse> */ listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsListByBillingProfileResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param callback The callback */ listByBillingProfile(billingAccountName: string, billingProfileName: string, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param options The optional parameters * @param callback The callback */ listByBillingProfile(billingAccountName: string, billingProfileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; listByBillingProfile(billingAccountName: string, billingProfileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscriptionsListResult>, callback?: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): Promise<Models.BillingSubscriptionsListByBillingProfileResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, options }, listByBillingProfileOperationSpec, callback) as Promise<Models.BillingSubscriptionsListByBillingProfileResponse>; } /** * Lists the subscriptions that are billed to an invoice section. The operation is supported only * for billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsListByInvoiceSectionResponse> */ listByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsListByInvoiceSectionResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param callback The callback */ listByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param billingProfileName The ID that uniquely identifies a billing profile. * @param invoiceSectionName The ID that uniquely identifies an invoice section. * @param options The optional parameters * @param callback The callback */ listByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; listByInvoiceSection(billingAccountName: string, billingProfileName: string, invoiceSectionName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscriptionsListResult>, callback?: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): Promise<Models.BillingSubscriptionsListByInvoiceSectionResponse> { return this.client.sendOperationRequest( { billingAccountName, billingProfileName, invoiceSectionName, options }, listByInvoiceSectionOperationSpec, callback) as Promise<Models.BillingSubscriptionsListByInvoiceSectionResponse>; } /** * Gets a subscription by its ID. The operation is supported for billing accounts with agreement * type Microsoft Customer Agreement and Microsoft Partner Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsGetResponse> */ get(billingAccountName: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsGetResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param callback The callback */ get(billingAccountName: string, callback: msRest.ServiceCallback<Models.BillingSubscription>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param options The optional parameters * @param callback The callback */ get(billingAccountName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscription>): void; get(billingAccountName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscription>, callback?: msRest.ServiceCallback<Models.BillingSubscription>): Promise<Models.BillingSubscriptionsGetResponse> { return this.client.sendOperationRequest( { billingAccountName, options }, getOperationSpec, callback) as Promise<Models.BillingSubscriptionsGetResponse>; } /** * Updates the properties of a billing subscription. Currently, cost center can be updated. The * operation is supported only for billing accounts with agreement type Microsoft Customer * Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param parameters Request parameters that are provided to the update billing subscription * operation. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsUpdateResponse> */ update(billingAccountName: string, parameters: Models.BillingSubscription, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsUpdateResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param parameters Request parameters that are provided to the update billing subscription * operation. * @param callback The callback */ update(billingAccountName: string, parameters: Models.BillingSubscription, callback: msRest.ServiceCallback<Models.BillingSubscription>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param parameters Request parameters that are provided to the update billing subscription * operation. * @param options The optional parameters * @param callback The callback */ update(billingAccountName: string, parameters: Models.BillingSubscription, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscription>): void; update(billingAccountName: string, parameters: Models.BillingSubscription, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscription>, callback?: msRest.ServiceCallback<Models.BillingSubscription>): Promise<Models.BillingSubscriptionsUpdateResponse> { return this.client.sendOperationRequest( { billingAccountName, parameters, options }, updateOperationSpec, callback) as Promise<Models.BillingSubscriptionsUpdateResponse>; } /** * Moves a subscription's charges to a new invoice section. The new invoice section must belong to * the same billing profile as the existing invoice section. This operation is supported for * billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param destinationInvoiceSectionId The destination invoice section id. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsMoveResponse> */ move(billingAccountName: string, destinationInvoiceSectionId: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsMoveResponse> { return this.beginMove(billingAccountName,destinationInvoiceSectionId,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.BillingSubscriptionsMoveResponse>; } /** * Validates if a subscription's charges can be moved to a new invoice section. This operation is * supported for billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param destinationInvoiceSectionId The destination invoice section id. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsValidateMoveResponse> */ validateMove(billingAccountName: string, destinationInvoiceSectionId: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsValidateMoveResponse>; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param destinationInvoiceSectionId The destination invoice section id. * @param callback The callback */ validateMove(billingAccountName: string, destinationInvoiceSectionId: string, callback: msRest.ServiceCallback<Models.ValidateSubscriptionTransferEligibilityResult>): void; /** * @param billingAccountName The ID that uniquely identifies a billing account. * @param destinationInvoiceSectionId The destination invoice section id. * @param options The optional parameters * @param callback The callback */ validateMove(billingAccountName: string, destinationInvoiceSectionId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ValidateSubscriptionTransferEligibilityResult>): void; validateMove(billingAccountName: string, destinationInvoiceSectionId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ValidateSubscriptionTransferEligibilityResult>, callback?: msRest.ServiceCallback<Models.ValidateSubscriptionTransferEligibilityResult>): Promise<Models.BillingSubscriptionsValidateMoveResponse> { return this.client.sendOperationRequest( { billingAccountName, destinationInvoiceSectionId, options }, validateMoveOperationSpec, callback) as Promise<Models.BillingSubscriptionsValidateMoveResponse>; } /** * Moves a subscription's charges to a new invoice section. The new invoice section must belong to * the same billing profile as the existing invoice section. This operation is supported for * billing accounts with agreement type Microsoft Customer Agreement. * @param billingAccountName The ID that uniquely identifies a billing account. * @param destinationInvoiceSectionId The destination invoice section id. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginMove(billingAccountName: string, destinationInvoiceSectionId: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { billingAccountName, destinationInvoiceSectionId, options }, beginMoveOperationSpec, options); } /** * Lists the subscriptions for a customer. The operation is supported only for billing accounts * with agreement type Microsoft Partner Agreement. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsListByCustomerNextResponse> */ listByCustomerNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsListByCustomerNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByCustomerNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByCustomerNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; listByCustomerNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscriptionsListResult>, callback?: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): Promise<Models.BillingSubscriptionsListByCustomerNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByCustomerNextOperationSpec, callback) as Promise<Models.BillingSubscriptionsListByCustomerNextResponse>; } /** * Lists the subscriptions for a billing account. The operation is supported for billing accounts * with agreement type Microsoft Customer Agreement or Microsoft Partner Agreement. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsListByBillingAccountNextResponse> */ listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsListByBillingAccountNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByBillingAccountNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByBillingAccountNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; listByBillingAccountNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscriptionsListResult>, callback?: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): Promise<Models.BillingSubscriptionsListByBillingAccountNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByBillingAccountNextOperationSpec, callback) as Promise<Models.BillingSubscriptionsListByBillingAccountNextResponse>; } /** * Lists the subscriptions that are billed to a billing profile. The operation is supported for * billing accounts with agreement type Microsoft Customer Agreement or Microsoft Partner * Agreement. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsListByBillingProfileNextResponse> */ listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsListByBillingProfileNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByBillingProfileNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByBillingProfileNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; listByBillingProfileNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscriptionsListResult>, callback?: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): Promise<Models.BillingSubscriptionsListByBillingProfileNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByBillingProfileNextOperationSpec, callback) as Promise<Models.BillingSubscriptionsListByBillingProfileNextResponse>; } /** * Lists the subscriptions that are billed to an invoice section. The operation is supported only * for billing accounts with agreement type Microsoft Customer Agreement. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.BillingSubscriptionsListByInvoiceSectionNextResponse> */ listByInvoiceSectionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.BillingSubscriptionsListByInvoiceSectionNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listByInvoiceSectionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listByInvoiceSectionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): void; listByInvoiceSectionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingSubscriptionsListResult>, callback?: msRest.ServiceCallback<Models.BillingSubscriptionsListResult>): Promise<Models.BillingSubscriptionsListByInvoiceSectionNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listByInvoiceSectionNextOperationSpec, callback) as Promise<Models.BillingSubscriptionsListByInvoiceSectionNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByCustomerOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/customers/{customerName}/billingSubscriptions", urlParameters: [ Parameters.billingAccountName, Parameters.customerName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscriptionsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByBillingAccountOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions", urlParameters: [ Parameters.billingAccountName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscriptionsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByBillingProfileOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/billingSubscriptions", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscriptionsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByInvoiceSectionOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingProfiles/{billingProfileName}/invoiceSections/{invoiceSectionName}/billingSubscriptions", urlParameters: [ Parameters.billingAccountName, Parameters.billingProfileName, Parameters.invoiceSectionName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscriptionsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}", urlParameters: [ Parameters.billingAccountName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscription }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}", urlParameters: [ Parameters.billingAccountName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.BillingSubscription, required: true } }, responses: { 200: { bodyMapper: Mappers.BillingSubscription }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const validateMoveOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/validateMoveEligibility", urlParameters: [ Parameters.billingAccountName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { destinationInvoiceSectionId: "destinationInvoiceSectionId" }, mapper: { ...Mappers.TransferBillingSubscriptionRequestProperties, required: true } }, responses: { 200: { bodyMapper: Mappers.ValidateSubscriptionTransferEligibilityResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const beginMoveOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "providers/Microsoft.Billing/billingAccounts/{billingAccountName}/billingSubscriptions/{subscriptionId}/move", urlParameters: [ Parameters.billingAccountName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: { destinationInvoiceSectionId: "destinationInvoiceSectionId" }, mapper: { ...Mappers.TransferBillingSubscriptionRequestProperties, required: true } }, responses: { 200: { bodyMapper: Mappers.BillingSubscription, headersMapper: Mappers.BillingSubscriptionsMoveHeaders }, 202: { headersMapper: Mappers.BillingSubscriptionsMoveHeaders }, default: { bodyMapper: Mappers.ErrorResponse, headersMapper: Mappers.BillingSubscriptionsMoveHeaders } }, serializer }; const listByCustomerNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscriptionsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByBillingAccountNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscriptionsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByBillingProfileNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscriptionsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer }; const listByInvoiceSectionNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BillingSubscriptionsListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, serializer };
the_stack
var Cetab: {[id: number]: string} = { 0x0000: 'BEEP', 0x0001: 'OPEN', 0x0002: 'OPEN.LINKS', 0x0003: 'CLOSE.ALL', 0x0004: 'SAVE', 0x0005: 'SAVE.AS', 0x0006: 'FILE.DELETE', 0x0007: 'PAGE.SETUP', 0x0008: 'PRINT', 0x0009: 'PRINTER.SETUP', 0x000A: 'QUIT', 0x000B: 'NEW.WINDOW', 0x000C: 'ARRANGE.ALL', 0x000D: 'WINDOW.SIZE', 0x000E: 'WINDOW.MOVE', 0x000F: 'FULL', 0x0010: 'CLOSE', 0x0011: 'RUN', 0x0016: 'SET.PRINT.AREA', 0x0017: 'SET.PRINT.TITLES', 0x0018: 'SET.PAGE.BREAK', 0x0019: 'REMOVE.PAGE.BREAK', 0x001A: 'FONT', 0x001B: 'DISPLAY', 0x001C: 'PROTECT.DOCUMENT', 0x001D: 'PRECISION', 0x001E: 'A1.R1C1', 0x001F: 'CALCULATE.NOW', 0x0020: 'CALCULATION', 0x0022: 'DATA.FIND', 0x0023: 'EXTRACT', 0x0024: 'DATA.DELETE', 0x0025: 'SET.DATABASE', 0x0026: 'SET.CRITERIA', 0x0027: 'SORT', 0x0028: 'DATA.SERIES', 0x0029: 'TABLE', 0x002A: 'FORMAT.NUMBER', 0x002B: 'ALIGNMENT', 0x002C: 'STYLE', 0x002D: 'BORDER', 0x002E: 'CELL.PROTECTION', 0x002F: 'COLUMN.WIDTH', 0x0030: 'UNDO', 0x0031: 'CUT', 0x0032: 'COPY', 0x0033: 'PASTE', 0x0034: 'CLEAR', 0x0035: 'PASTE.SPECIAL', 0x0036: 'EDIT.DELETE', 0x0037: 'INSERT', 0x0038: 'FILL.RIGHT', 0x0039: 'FILL.DOWN', 0x003D: 'DEFINE.NAME', 0x003E: 'CREATE.NAMES', 0x003F: 'FORMULA.GOTO', 0x0040: 'FORMULA.FIND', 0x0041: 'SELECT.LAST.CELL', 0x0042: 'SHOW.ACTIVE.CELL', 0x0043: 'GALLERY.AREA', 0x0044: 'GALLERY.BAR', 0x0045: 'GALLERY.COLUMN', 0x0046: 'GALLERY.LINE', 0x0047: 'GALLERY.PIE', 0x0048: 'GALLERY.SCATTER', 0x0049: 'COMBINATION', 0x004A: 'PREFERRED', 0x004B: 'ADD.OVERLAY', 0x004C: 'GRIDLINES', 0x004D: 'SET.PREFERRED', 0x004E: 'AXES', 0x004F: 'LEGEND', 0x0050: 'ATTACH.TEXT', 0x0051: 'ADD.ARROW', 0x0052: 'SELECT.CHART', 0x0053: 'SELECT.PLOT.AREA', 0x0054: 'PATTERNS', 0x0055: 'MAIN.CHART', 0x0056: 'OVERLAY', 0x0057: 'SCALE', 0x0058: 'FORMAT.LEGEND', 0x0059: 'FORMAT.TEXT', 0x005A: 'EDIT.REPEAT', 0x005B: 'PARSE', 0x005C: 'JUSTIFY', 0x005D: 'HIDE', 0x005E: 'UNHIDE', 0x005F: 'WORKSPACE', 0x0060: 'FORMULA', 0x0061: 'FORMULA.FILL', 0x0062: 'FORMULA.ARRAY', 0x0063: 'DATA.FIND.NEXT', 0x0064: 'DATA.FIND.PREV', 0x0065: 'FORMULA.FIND.NEXT', 0x0066: 'FORMULA.FIND.PREV', 0x0067: 'ACTIVATE', 0x0068: 'ACTIVATE.NEXT', 0x0069: 'ACTIVATE.PREV', 0x006A: 'UNLOCKED.NEXT', 0x006B: 'UNLOCKED.PREV', 0x006C: 'COPY.PICTURE', 0x006D: 'SELECT', 0x006E: 'DELETE.NAME', 0x006F: 'DELETE.FORMAT', 0x0070: 'VLINE', 0x0071: 'HLINE', 0x0072: 'VPAGE', 0x0073: 'HPAGE', 0x0074: 'VSCROLL', 0x0075: 'HSCROLL', 0x0076: 'ALERT', 0x0077: 'NEW', 0x0078: 'CANCEL.COPY', 0x0079: 'SHOW.CLIPBOARD', 0x007A: 'MESSAGE', 0x007C: 'PASTE.LINK', 0x007D: 'APP.ACTIVATE', 0x007E: 'DELETE.ARROW', 0x007F: 'ROW.HEIGHT', 0x0080: 'FORMAT.MOVE', 0x0081: 'FORMAT.SIZE', 0x0082: 'FORMULA.REPLACE', 0x0083: 'SEND.KEYS', 0x0084: 'SELECT.SPECIAL', 0x0085: 'APPLY.NAMES', 0x0086: 'REPLACE.FONT', 0x0087: 'FREEZE.PANES', 0x0088: 'SHOW.INFO', 0x0089: 'SPLIT', 0x008A: 'ON.WINDOW', 0x008B: 'ON.DATA', 0x008C: 'DISABLE.INPUT', 0x008E: 'OUTLINE', 0x008F: 'LIST.NAMES', 0x0090: 'FILE.CLOSE', 0x0091: 'SAVE.WORKBOOK', 0x0092: 'DATA.FORM', 0x0093: 'COPY.CHART', 0x0094: 'ON.TIME', 0x0095: 'WAIT', 0x0096: 'FORMAT.FONT', 0x0097: 'FILL.UP', 0x0098: 'FILL.LEFT', 0x0099: 'DELETE.OVERLAY', 0x009B: 'SHORT.MENUS', 0x009F: 'SET.UPDATE.STATUS', 0x00A1: 'COLOR.PALETTE', 0x00A2: 'DELETE.STYLE', 0x00A3: 'WINDOW.RESTORE', 0x00A4: 'WINDOW.MAXIMIZE', 0x00A6: 'CHANGE.LINK', 0x00A7: 'CALCULATE.DOCUMENT', 0x00A8: 'ON.KEY', 0x00A9: 'APP.RESTORE', 0x00AA: 'APP.MOVE', 0x00AB: 'APP.SIZE', 0x00AC: 'APP.MINIMIZE', 0x00AD: 'APP.MAXIMIZE', 0x00AE: 'BRING.TO.FRONT', 0x00AF: 'SEND.TO.BACK', 0x00B9: 'MAIN.CHART.TYPE', 0x00BA: 'OVERLAY.CHART.TYPE', 0x00BB: 'SELECT.END', 0x00BC: 'OPEN.MAIL', 0x00BD: 'SEND.MAIL', 0x00BE: 'STANDARD.FONT', 0x00BF: 'CONSOLIDATE', 0x00C0: 'SORT.SPECIAL', 0x00C1: 'GALLERY.3D.AREA', 0x00C2: 'GALLERY.3D.COLUMN', 0x00C3: 'GALLERY.3D.LINE', 0x00C4: 'GALLERY.3D.PIE', 0x00C5: 'VIEW.3D', 0x00C6: 'GOAL.SEEK', 0x00C7: 'WORKGROUP', 0x00C8: 'FILL.GROUP', 0x00C9: 'UPDATE.LINK', 0x00CA: 'PROMOTE', 0x00CB: 'DEMOTE', 0x00CC: 'SHOW.DETAIL', 0x00CE: 'UNGROUP', 0x00CF: 'OBJECT.PROPERTIES', 0x00D0: 'SAVE.NEW.OBJECT', 0x00D1: 'SHARE', 0x00D2: 'SHARE.NAME', 0x00D3: 'DUPLICATE', 0x00D4: 'APPLY.STYLE', 0x00D5: 'ASSIGN.TO.OBJECT', 0x00D6: 'OBJECT.PROTECTION', 0x00D7: 'HIDE.OBJECT', 0x00D8: 'SET.EXTRACT', 0x00D9: 'CREATE.PUBLISHER', 0x00DA: 'SUBSCRIBE.TO', 0x00DB: 'ATTRIBUTES', 0x00DC: 'SHOW.TOOLBAR', 0x00DE: 'PRINT.PREVIEW', 0x00DF: 'EDIT.COLOR', 0x00E0: 'SHOW.LEVELS', 0x00E1: 'FORMAT.MAIN', 0x00E2: 'FORMAT.OVERLAY', 0x00E3: 'ON.RECALC', 0x00E4: 'EDIT.SERIES', 0x00E5: 'DEFINE.STYLE', 0x00F0: 'LINE.PRINT', 0x00F3: 'ENTER.DATA', 0x00F9: 'GALLERY.RADAR', 0x00FA: 'MERGE.STYLES', 0x00FB: 'EDITION.OPTIONS', 0x00FC: 'PASTE.PICTURE', 0x00FD: 'PASTE.PICTURE.LINK', 0x00FE: 'SPELLING', 0x0100: 'ZOOM', 0x0103: 'INSERT.OBJECT', 0x0104: 'WINDOW.MINIMIZE', 0x0109: 'SOUND.NOTE', 0x010A: 'SOUND.PLAY', 0x010B: 'FORMAT.SHAPE', 0x010C: 'EXTEND.POLYGON', 0x010D: 'FORMAT.AUTO', 0x0110: 'GALLERY.3D.BAR', 0x0111: 'GALLERY.3D.SURFACE', 0x0112: 'FILL.AUTO', 0x0114: 'CUSTOMIZE.TOOLBAR', 0x0115: 'ADD.TOOL', 0x0116: 'EDIT.OBJECT', 0x0117: 'ON.DOUBLECLICK', 0x0118: 'ON.ENTRY', 0x0119: 'WORKBOOK.ADD', 0x011A: 'WORKBOOK.MOVE', 0x011B: 'WORKBOOK.COPY', 0x011C: 'WORKBOOK.OPTIONS', 0x011D: 'SAVE.WORKSPACE', 0x0120: 'CHART.WIZARD', 0x0121: 'DELETE.TOOL', 0x0122: 'MOVE.TOOL', 0x0123: 'WORKBOOK.SELECT', 0x0124: 'WORKBOOK.ACTIVATE', 0x0125: 'ASSIGN.TO.TOOL', 0x0127: 'COPY.TOOL', 0x0128: 'RESET.TOOL', 0x0129: 'CONSTRAIN.NUMERIC', 0x012A: 'PASTE.TOOL', 0x012E: 'WORKBOOK.NEW', 0x0131: 'SCENARIO.CELLS', 0x0132: 'SCENARIO.DELETE', 0x0133: 'SCENARIO.ADD', 0x0134: 'SCENARIO.EDIT', 0x0135: 'SCENARIO.SHOW', 0x0136: 'SCENARIO.SHOW.NEXT', 0x0137: 'SCENARIO.SUMMARY', 0x0138: 'PIVOT.TABLE.WIZARD', 0x0139: 'PIVOT.FIELD.PROPERTIES', 0x013A: 'PIVOT.FIELD', 0x013B: 'PIVOT.ITEM', 0x013C: 'PIVOT.ADD.FIELDS', 0x013E: 'OPTIONS.CALCULATION', 0x013F: 'OPTIONS.EDIT', 0x0140: 'OPTIONS.VIEW', 0x0141: 'ADDIN.MANAGER', 0x0142: 'MENU.EDITOR', 0x0143: 'ATTACH.TOOLBARS', 0x0144: 'VBAActivate', 0x0145: 'OPTIONS.CHART', 0x0148: 'VBA.INSERT.FILE', 0x014A: 'VBA.PROCEDURE.DEFINITION', 0x0150: 'ROUTING.SLIP', 0x0152: 'ROUTE.DOCUMENT', 0x0153: 'MAIL.LOGON', 0x0156: 'INSERT.PICTURE', 0x0157: 'EDIT.TOOL', 0x0158: 'GALLERY.DOUGHNUT', 0x015E: 'CHART.TREND', 0x0160: 'PIVOT.ITEM.PROPERTIES', 0x0162: 'WORKBOOK.INSERT', 0x0163: 'OPTIONS.TRANSITION', 0x0164: 'OPTIONS.GENERAL', 0x0172: 'FILTER.ADVANCED', 0x0175: 'MAIL.ADD.MAILER', 0x0176: 'MAIL.DELETE.MAILER', 0x0177: 'MAIL.REPLY', 0x0178: 'MAIL.REPLY.ALL', 0x0179: 'MAIL.FORWARD', 0x017A: 'MAIL.NEXT.LETTER', 0x017B: 'DATA.LABEL', 0x017C: 'INSERT.TITLE', 0x017D: 'FONT.PROPERTIES', 0x017E: 'MACRO.OPTIONS', 0x017F: 'WORKBOOK.HIDE', 0x0180: 'WORKBOOK.UNHIDE', 0x0181: 'WORKBOOK.DELETE', 0x0182: 'WORKBOOK.NAME', 0x0184: 'GALLERY.CUSTOM', 0x0186: 'ADD.CHART.AUTOFORMAT', 0x0187: 'DELETE.CHART.AUTOFORMAT', 0x0188: 'CHART.ADD.DATA', 0x0189: 'AUTO.OUTLINE', 0x018A: 'TAB.ORDER', 0x018B: 'SHOW.DIALOG', 0x018C: 'SELECT.ALL', 0x018D: 'UNGROUP.SHEETS', 0x018E: 'SUBTOTAL.CREATE', 0x018F: 'SUBTOTAL.REMOVE', 0x0190: 'RENAME.OBJECT', 0x019C: 'WORKBOOK.SCROLL', 0x019D: 'WORKBOOK.NEXT', 0x019E: 'WORKBOOK.PREV', 0x019F: 'WORKBOOK.TAB.SPLIT', 0x01A0: 'FULL.SCREEN', 0x01A1: 'WORKBOOK.PROTECT', 0x01A4: 'SCROLLBAR.PROPERTIES', 0x01A5: 'PIVOT.SHOW.PAGES', 0x01A6: 'TEXT.TO.COLUMNS', 0x01A7: 'FORMAT.CHARTTYPE', 0x01A8: 'LINK.FORMAT', 0x01A9: 'TRACER.DISPLAY', 0x01AE: 'TRACER.NAVIGATE', 0x01AF: 'TRACER.CLEAR', 0x01B0: 'TRACER.ERROR', 0x01B1: 'PIVOT.FIELD.GROUP', 0x01B2: 'PIVOT.FIELD.UNGROUP', 0x01B3: 'CHECKBOX.PROPERTIES', 0x01B4: 'LABEL.PROPERTIES', 0x01B5: 'LISTBOX.PROPERTIES', 0x01B6: 'EDITBOX.PROPERTIES', 0x01B7: 'PIVOT.REFRESH', 0x01B8: 'LINK.COMBO', 0x01B9: 'OPEN.TEXT', 0x01BA: 'HIDE.DIALOG', 0x01BB: 'SET.DIALOG.FOCUS', 0x01BC: 'ENABLE.OBJECT', 0x01BD: 'PUSHBUTTON.PROPERTIES', 0x01BE: 'SET.DIALOG.DEFAULT', 0x01BF: 'FILTER', 0x01C0: 'FILTER.SHOW.ALL', 0x01C1: 'CLEAR.OUTLINE', 0x01C2: 'FUNCTION.WIZARD', 0x01C3: 'ADD.LIST.ITEM', 0x01C4: 'SET.LIST.ITEM', 0x01C5: 'REMOVE.LIST.ITEM', 0x01C6: 'SELECT.LIST.ITEM', 0x01C7: 'SET.CONTROL.VALUE', 0x01C8: 'SAVE.COPY.AS', 0x01CA: 'OPTIONS.LISTS.ADD', 0x01CB: 'OPTIONS.LISTS.DELETE', 0x01CC: 'SERIES.AXES', 0x01CD: 'SERIES.X', 0x01CE: 'SERIES.Y', 0x01CF: 'ERRORBAR.X', 0x01D0: 'ERRORBAR.Y', 0x01D1: 'FORMAT.CHART', 0x01D2: 'SERIES.ORDER', 0x01D3: 'MAIL.LOGOFF', 0x01D4: 'CLEAR.ROUTING.SLIP', 0x01D5: 'APP.ACTIVATE.MICROSOFT', 0x01D6: 'MAIL.EDIT.MAILER', 0x01D7: 'ON.SHEET', 0x01D8: 'STANDARD.WIDTH', 0x01D9: 'SCENARIO.MERGE', 0x01DA: 'SUMMARY.INFO', 0x01DB: 'FIND.FILE', 0x01DC: 'ACTIVE.CELL.FONT', 0x01DD: 'ENABLE.TIPWIZARD', 0x01DE: 'VBA.MAKE.ADDIN', 0x01E0: 'INSERTDATATABLE', 0x01E1: 'WORKGROUP.OPTIONS', 0x01E2: 'MAIL.SEND.MAILER', 0x01E5: 'AUTOCORRECT', 0x01E9: 'POST.DOCUMENT', 0x01EB: 'PICKLIST', 0x01ED: 'VIEW.SHOW', 0x01EE: 'VIEW.DEFINE', 0x01EF: 'VIEW.DELETE', 0x01FD: 'SHEET.BACKGROUND', 0x01FE: 'INSERT.MAP.OBJECT', 0x01FF: 'OPTIONS.MENONO', 0x0205: 'MSOCHECKS', 0x0206: 'NORMAL', 0x0207: 'LAYOUT', 0x0208: 'RM.PRINT.AREA', 0x0209: 'CLEAR.PRINT.AREA', 0x020A: 'ADD.PRINT.AREA', 0x020B: 'MOVE.BRK', 0x0221: 'HIDECURR.NOTE', 0x0222: 'HIDEALL.NOTES', 0x0223: 'DELETE.NOTE', 0x0224: 'TRAVERSE.NOTES', 0x0225: 'ACTIVATE.NOTES', 0x026C: 'PROTECT.REVISIONS', 0x026D: 'UNPROTECT.REVISIONS', 0x0287: 'OPTIONS.ME', 0x028D: 'WEB.PUBLISH', 0x029B: 'NEWWEBQUERY', 0x02A1: 'PIVOT.TABLE.CHART', 0x02F1: 'OPTIONS.SAVE', 0x02F3: 'OPTIONS.SPELL', 0x0328: 'HIDEALL.INKANNOTS' }; /* [MS-XLS] 2.5.198.17 */ /* [MS-XLSB] 2.5.97.10 */ var Ftab: {[id: number]: string} = { 0x0000: 'COUNT', 0x0001: 'IF', 0x0002: 'ISNA', 0x0003: 'ISERROR', 0x0004: 'SUM', 0x0005: 'AVERAGE', 0x0006: 'MIN', 0x0007: 'MAX', 0x0008: 'ROW', 0x0009: 'COLUMN', 0x000A: 'NA', 0x000B: 'NPV', 0x000C: 'STDEV', 0x000D: 'DOLLAR', 0x000E: 'FIXED', 0x000F: 'SIN', 0x0010: 'COS', 0x0011: 'TAN', 0x0012: 'ATAN', 0x0013: 'PI', 0x0014: 'SQRT', 0x0015: 'EXP', 0x0016: 'LN', 0x0017: 'LOG10', 0x0018: 'ABS', 0x0019: 'INT', 0x001A: 'SIGN', 0x001B: 'ROUND', 0x001C: 'LOOKUP', 0x001D: 'INDEX', 0x001E: 'REPT', 0x001F: 'MID', 0x0020: 'LEN', 0x0021: 'VALUE', 0x0022: 'TRUE', 0x0023: 'FALSE', 0x0024: 'AND', 0x0025: 'OR', 0x0026: 'NOT', 0x0027: 'MOD', 0x0028: 'DCOUNT', 0x0029: 'DSUM', 0x002A: 'DAVERAGE', 0x002B: 'DMIN', 0x002C: 'DMAX', 0x002D: 'DSTDEV', 0x002E: 'VAR', 0x002F: 'DVAR', 0x0030: 'TEXT', 0x0031: 'LINEST', 0x0032: 'TREND', 0x0033: 'LOGEST', 0x0034: 'GROWTH', 0x0035: 'GOTO', 0x0036: 'HALT', 0x0037: 'RETURN', 0x0038: 'PV', 0x0039: 'FV', 0x003A: 'NPER', 0x003B: 'PMT', 0x003C: 'RATE', 0x003D: 'MIRR', 0x003E: 'IRR', 0x003F: 'RAND', 0x0040: 'MATCH', 0x0041: 'DATE', 0x0042: 'TIME', 0x0043: 'DAY', 0x0044: 'MONTH', 0x0045: 'YEAR', 0x0046: 'WEEKDAY', 0x0047: 'HOUR', 0x0048: 'MINUTE', 0x0049: 'SECOND', 0x004A: 'NOW', 0x004B: 'AREAS', 0x004C: 'ROWS', 0x004D: 'COLUMNS', 0x004E: 'OFFSET', 0x004F: 'ABSREF', 0x0050: 'RELREF', 0x0051: 'ARGUMENT', 0x0052: 'SEARCH', 0x0053: 'TRANSPOSE', 0x0054: 'ERROR', 0x0055: 'STEP', 0x0056: 'TYPE', 0x0057: 'ECHO', 0x0058: 'SET.NAME', 0x0059: 'CALLER', 0x005A: 'DEREF', 0x005B: 'WINDOWS', 0x005C: 'SERIES', 0x005D: 'DOCUMENTS', 0x005E: 'ACTIVE.CELL', 0x005F: 'SELECTION', 0x0060: 'RESULT', 0x0061: 'ATAN2', 0x0062: 'ASIN', 0x0063: 'ACOS', 0x0064: 'CHOOSE', 0x0065: 'HLOOKUP', 0x0066: 'VLOOKUP', 0x0067: 'LINKS', 0x0068: 'INPUT', 0x0069: 'ISREF', 0x006A: 'GET.FORMULA', 0x006B: 'GET.NAME', 0x006C: 'SET.VALUE', 0x006D: 'LOG', 0x006E: 'EXEC', 0x006F: 'CHAR', 0x0070: 'LOWER', 0x0071: 'UPPER', 0x0072: 'PROPER', 0x0073: 'LEFT', 0x0074: 'RIGHT', 0x0075: 'EXACT', 0x0076: 'TRIM', 0x0077: 'REPLACE', 0x0078: 'SUBSTITUTE', 0x0079: 'CODE', 0x007A: 'NAMES', 0x007B: 'DIRECTORY', 0x007C: 'FIND', 0x007D: 'CELL', 0x007E: 'ISERR', 0x007F: 'ISTEXT', 0x0080: 'ISNUMBER', 0x0081: 'ISBLANK', 0x0082: 'T', 0x0083: 'N', 0x0084: 'FOPEN', 0x0085: 'FCLOSE', 0x0086: 'FSIZE', 0x0087: 'FREADLN', 0x0088: 'FREAD', 0x0089: 'FWRITELN', 0x008A: 'FWRITE', 0x008B: 'FPOS', 0x008C: 'DATEVALUE', 0x008D: 'TIMEVALUE', 0x008E: 'SLN', 0x008F: 'SYD', 0x0090: 'DDB', 0x0091: 'GET.DEF', 0x0092: 'REFTEXT', 0x0093: 'TEXTREF', 0x0094: 'INDIRECT', 0x0095: 'REGISTER', 0x0096: 'CALL', 0x0097: 'ADD.BAR', 0x0098: 'ADD.MENU', 0x0099: 'ADD.COMMAND', 0x009A: 'ENABLE.COMMAND', 0x009B: 'CHECK.COMMAND', 0x009C: 'RENAME.COMMAND', 0x009D: 'SHOW.BAR', 0x009E: 'DELETE.MENU', 0x009F: 'DELETE.COMMAND', 0x00A0: 'GET.CHART.ITEM', 0x00A1: 'DIALOG.BOX', 0x00A2: 'CLEAN', 0x00A3: 'MDETERM', 0x00A4: 'MINVERSE', 0x00A5: 'MMULT', 0x00A6: 'FILES', 0x00A7: 'IPMT', 0x00A8: 'PPMT', 0x00A9: 'COUNTA', 0x00AA: 'CANCEL.KEY', 0x00AB: 'FOR', 0x00AC: 'WHILE', 0x00AD: 'BREAK', 0x00AE: 'NEXT', 0x00AF: 'INITIATE', 0x00B0: 'REQUEST', 0x00B1: 'POKE', 0x00B2: 'EXECUTE', 0x00B3: 'TERMINATE', 0x00B4: 'RESTART', 0x00B5: 'HELP', 0x00B6: 'GET.BAR', 0x00B7: 'PRODUCT', 0x00B8: 'FACT', 0x00B9: 'GET.CELL', 0x00BA: 'GET.WORKSPACE', 0x00BB: 'GET.WINDOW', 0x00BC: 'GET.DOCUMENT', 0x00BD: 'DPRODUCT', 0x00BE: 'ISNONTEXT', 0x00BF: 'GET.NOTE', 0x00C0: 'NOTE', 0x00C1: 'STDEVP', 0x00C2: 'VARP', 0x00C3: 'DSTDEVP', 0x00C4: 'DVARP', 0x00C5: 'TRUNC', 0x00C6: 'ISLOGICAL', 0x00C7: 'DCOUNTA', 0x00C8: 'DELETE.BAR', 0x00C9: 'UNREGISTER', 0x00CC: 'USDOLLAR', 0x00CD: 'FINDB', 0x00CE: 'SEARCHB', 0x00CF: 'REPLACEB', 0x00D0: 'LEFTB', 0x00D1: 'RIGHTB', 0x00D2: 'MIDB', 0x00D3: 'LENB', 0x00D4: 'ROUNDUP', 0x00D5: 'ROUNDDOWN', 0x00D6: 'ASC', 0x00D7: 'DBCS', 0x00D8: 'RANK', 0x00DB: 'ADDRESS', 0x00DC: 'DAYS360', 0x00DD: 'TODAY', 0x00DE: 'VDB', 0x00DF: 'ELSE', 0x00E0: 'ELSE.IF', 0x00E1: 'END.IF', 0x00E2: 'FOR.CELL', 0x00E3: 'MEDIAN', 0x00E4: 'SUMPRODUCT', 0x00E5: 'SINH', 0x00E6: 'COSH', 0x00E7: 'TANH', 0x00E8: 'ASINH', 0x00E9: 'ACOSH', 0x00EA: 'ATANH', 0x00EB: 'DGET', 0x00EC: 'CREATE.OBJECT', 0x00ED: 'VOLATILE', 0x00EE: 'LAST.ERROR', 0x00EF: 'CUSTOM.UNDO', 0x00F0: 'CUSTOM.REPEAT', 0x00F1: 'FORMULA.CONVERT', 0x00F2: 'GET.LINK.INFO', 0x00F3: 'TEXT.BOX', 0x00F4: 'INFO', 0x00F5: 'GROUP', 0x00F6: 'GET.OBJECT', 0x00F7: 'DB', 0x00F8: 'PAUSE', 0x00FB: 'RESUME', 0x00FC: 'FREQUENCY', 0x00FD: 'ADD.TOOLBAR', 0x00FE: 'DELETE.TOOLBAR', 0x00FF: 'User', 0x0100: 'RESET.TOOLBAR', 0x0101: 'EVALUATE', 0x0102: 'GET.TOOLBAR', 0x0103: 'GET.TOOL', 0x0104: 'SPELLING.CHECK', 0x0105: 'ERROR.TYPE', 0x0106: 'APP.TITLE', 0x0107: 'WINDOW.TITLE', 0x0108: 'SAVE.TOOLBAR', 0x0109: 'ENABLE.TOOL', 0x010A: 'PRESS.TOOL', 0x010B: 'REGISTER.ID', 0x010C: 'GET.WORKBOOK', 0x010D: 'AVEDEV', 0x010E: 'BETADIST', 0x010F: 'GAMMALN', 0x0110: 'BETAINV', 0x0111: 'BINOMDIST', 0x0112: 'CHIDIST', 0x0113: 'CHIINV', 0x0114: 'COMBIN', 0x0115: 'CONFIDENCE', 0x0116: 'CRITBINOM', 0x0117: 'EVEN', 0x0118: 'EXPONDIST', 0x0119: 'FDIST', 0x011A: 'FINV', 0x011B: 'FISHER', 0x011C: 'FISHERINV', 0x011D: 'FLOOR', 0x011E: 'GAMMADIST', 0x011F: 'GAMMAINV', 0x0120: 'CEILING', 0x0121: 'HYPGEOMDIST', 0x0122: 'LOGNORMDIST', 0x0123: 'LOGINV', 0x0124: 'NEGBINOMDIST', 0x0125: 'NORMDIST', 0x0126: 'NORMSDIST', 0x0127: 'NORMINV', 0x0128: 'NORMSINV', 0x0129: 'STANDARDIZE', 0x012A: 'ODD', 0x012B: 'PERMUT', 0x012C: 'POISSON', 0x012D: 'TDIST', 0x012E: 'WEIBULL', 0x012F: 'SUMXMY2', 0x0130: 'SUMX2MY2', 0x0131: 'SUMX2PY2', 0x0132: 'CHITEST', 0x0133: 'CORREL', 0x0134: 'COVAR', 0x0135: 'FORECAST', 0x0136: 'FTEST', 0x0137: 'INTERCEPT', 0x0138: 'PEARSON', 0x0139: 'RSQ', 0x013A: 'STEYX', 0x013B: 'SLOPE', 0x013C: 'TTEST', 0x013D: 'PROB', 0x013E: 'DEVSQ', 0x013F: 'GEOMEAN', 0x0140: 'HARMEAN', 0x0141: 'SUMSQ', 0x0142: 'KURT', 0x0143: 'SKEW', 0x0144: 'ZTEST', 0x0145: 'LARGE', 0x0146: 'SMALL', 0x0147: 'QUARTILE', 0x0148: 'PERCENTILE', 0x0149: 'PERCENTRANK', 0x014A: 'MODE', 0x014B: 'TRIMMEAN', 0x014C: 'TINV', 0x014E: 'MOVIE.COMMAND', 0x014F: 'GET.MOVIE', 0x0150: 'CONCATENATE', 0x0151: 'POWER', 0x0152: 'PIVOT.ADD.DATA', 0x0153: 'GET.PIVOT.TABLE', 0x0154: 'GET.PIVOT.FIELD', 0x0155: 'GET.PIVOT.ITEM', 0x0156: 'RADIANS', 0x0157: 'DEGREES', 0x0158: 'SUBTOTAL', 0x0159: 'SUMIF', 0x015A: 'COUNTIF', 0x015B: 'COUNTBLANK', 0x015C: 'SCENARIO.GET', 0x015D: 'OPTIONS.LISTS.GET', 0x015E: 'ISPMT', 0x015F: 'DATEDIF', 0x0160: 'DATESTRING', 0x0161: 'NUMBERSTRING', 0x0162: 'ROMAN', 0x0163: 'OPEN.DIALOG', 0x0164: 'SAVE.DIALOG', 0x0165: 'VIEW.GET', 0x0166: 'GETPIVOTDATA', 0x0167: 'HYPERLINK', 0x0168: 'PHONETIC', 0x0169: 'AVERAGEA', 0x016A: 'MAXA', 0x016B: 'MINA', 0x016C: 'STDEVPA', 0x016D: 'VARPA', 0x016E: 'STDEVA', 0x016F: 'VARA', 0x0170: 'BAHTTEXT', 0x0171: 'THAIDAYOFWEEK', 0x0172: 'THAIDIGIT', 0x0173: 'THAIMONTHOFYEAR', 0x0174: 'THAINUMSOUND', 0x0175: 'THAINUMSTRING', 0x0176: 'THAISTRINGLENGTH', 0x0177: 'ISTHAIDIGIT', 0x0178: 'ROUNDBAHTDOWN', 0x0179: 'ROUNDBAHTUP', 0x017A: 'THAIYEAR', 0x017B: 'RTD', 0x017C: 'CUBEVALUE', 0x017D: 'CUBEMEMBER', 0x017E: 'CUBEMEMBERPROPERTY', 0x017F: 'CUBERANKEDMEMBER', 0x0180: 'HEX2BIN', 0x0181: 'HEX2DEC', 0x0182: 'HEX2OCT', 0x0183: 'DEC2BIN', 0x0184: 'DEC2HEX', 0x0185: 'DEC2OCT', 0x0186: 'OCT2BIN', 0x0187: 'OCT2HEX', 0x0188: 'OCT2DEC', 0x0189: 'BIN2DEC', 0x018A: 'BIN2OCT', 0x018B: 'BIN2HEX', 0x018C: 'IMSUB', 0x018D: 'IMDIV', 0x018E: 'IMPOWER', 0x018F: 'IMABS', 0x0190: 'IMSQRT', 0x0191: 'IMLN', 0x0192: 'IMLOG2', 0x0193: 'IMLOG10', 0x0194: 'IMSIN', 0x0195: 'IMCOS', 0x0196: 'IMEXP', 0x0197: 'IMARGUMENT', 0x0198: 'IMCONJUGATE', 0x0199: 'IMAGINARY', 0x019A: 'IMREAL', 0x019B: 'COMPLEX', 0x019C: 'IMSUM', 0x019D: 'IMPRODUCT', 0x019E: 'SERIESSUM', 0x019F: 'FACTDOUBLE', 0x01A0: 'SQRTPI', 0x01A1: 'QUOTIENT', 0x01A2: 'DELTA', 0x01A3: 'GESTEP', 0x01A4: 'ISEVEN', 0x01A5: 'ISODD', 0x01A6: 'MROUND', 0x01A7: 'ERF', 0x01A8: 'ERFC', 0x01A9: 'BESSELJ', 0x01AA: 'BESSELK', 0x01AB: 'BESSELY', 0x01AC: 'BESSELI', 0x01AD: 'XIRR', 0x01AE: 'XNPV', 0x01AF: 'PRICEMAT', 0x01B0: 'YIELDMAT', 0x01B1: 'INTRATE', 0x01B2: 'RECEIVED', 0x01B3: 'DISC', 0x01B4: 'PRICEDISC', 0x01B5: 'YIELDDISC', 0x01B6: 'TBILLEQ', 0x01B7: 'TBILLPRICE', 0x01B8: 'TBILLYIELD', 0x01B9: 'PRICE', 0x01BA: 'YIELD', 0x01BB: 'DOLLARDE', 0x01BC: 'DOLLARFR', 0x01BD: 'NOMINAL', 0x01BE: 'EFFECT', 0x01BF: 'CUMPRINC', 0x01C0: 'CUMIPMT', 0x01C1: 'EDATE', 0x01C2: 'EOMONTH', 0x01C3: 'YEARFRAC', 0x01C4: 'COUPDAYBS', 0x01C5: 'COUPDAYS', 0x01C6: 'COUPDAYSNC', 0x01C7: 'COUPNCD', 0x01C8: 'COUPNUM', 0x01C9: 'COUPPCD', 0x01CA: 'DURATION', 0x01CB: 'MDURATION', 0x01CC: 'ODDLPRICE', 0x01CD: 'ODDLYIELD', 0x01CE: 'ODDFPRICE', 0x01CF: 'ODDFYIELD', 0x01D0: 'RANDBETWEEN', 0x01D1: 'WEEKNUM', 0x01D2: 'AMORDEGRC', 0x01D3: 'AMORLINC', 0x01D4: 'CONVERT', 0x02D4: 'SHEETJS', 0x01D5: 'ACCRINT', 0x01D6: 'ACCRINTM', 0x01D7: 'WORKDAY', 0x01D8: 'NETWORKDAYS', 0x01D9: 'GCD', 0x01DA: 'MULTINOMIAL', 0x01DB: 'LCM', 0x01DC: 'FVSCHEDULE', 0x01DD: 'CUBEKPIMEMBER', 0x01DE: 'CUBESET', 0x01DF: 'CUBESETCOUNT', 0x01E0: 'IFERROR', 0x01E1: 'COUNTIFS', 0x01E2: 'SUMIFS', 0x01E3: 'AVERAGEIF', 0x01E4: 'AVERAGEIFS' }; var FtabArgc: {[id: number]: number} = { 0x0002: 1, /* ISNA */ 0x0003: 1, /* ISERROR */ 0x000A: 0, /* NA */ 0x000F: 1, /* SIN */ 0x0010: 1, /* COS */ 0x0011: 1, /* TAN */ 0x0012: 1, /* ATAN */ 0x0013: 0, /* PI */ 0x0014: 1, /* SQRT */ 0x0015: 1, /* EXP */ 0x0016: 1, /* LN */ 0x0017: 1, /* LOG10 */ 0x0018: 1, /* ABS */ 0x0019: 1, /* INT */ 0x001A: 1, /* SIGN */ 0x001B: 2, /* ROUND */ 0x001E: 2, /* REPT */ 0x001F: 3, /* MID */ 0x0020: 1, /* LEN */ 0x0021: 1, /* VALUE */ 0x0022: 0, /* TRUE */ 0x0023: 0, /* FALSE */ 0x0026: 1, /* NOT */ 0x0027: 2, /* MOD */ 0x0028: 3, /* DCOUNT */ 0x0029: 3, /* DSUM */ 0x002A: 3, /* DAVERAGE */ 0x002B: 3, /* DMIN */ 0x002C: 3, /* DMAX */ 0x002D: 3, /* DSTDEV */ 0x002F: 3, /* DVAR */ 0x0030: 2, /* TEXT */ 0x0035: 1, /* GOTO */ 0x003D: 3, /* MIRR */ 0x003F: 0, /* RAND */ 0x0041: 3, /* DATE */ 0x0042: 3, /* TIME */ 0x0043: 1, /* DAY */ 0x0044: 1, /* MONTH */ 0x0045: 1, /* YEAR */ 0x0046: 1, /* WEEKDAY */ 0x0047: 1, /* HOUR */ 0x0048: 1, /* MINUTE */ 0x0049: 1, /* SECOND */ 0x004A: 0, /* NOW */ 0x004B: 1, /* AREAS */ 0x004C: 1, /* ROWS */ 0x004D: 1, /* COLUMNS */ 0x004F: 2, /* ABSREF */ 0x0050: 2, /* RELREF */ 0x0053: 1, /* TRANSPOSE */ 0x0055: 0, /* STEP */ 0x0056: 1, /* TYPE */ 0x0059: 0, /* CALLER */ 0x005A: 1, /* DEREF */ 0x005E: 0, /* ACTIVE.CELL */ 0x005F: 0, /* SELECTION */ 0x0061: 2, /* ATAN2 */ 0x0062: 1, /* ASIN */ 0x0063: 1, /* ACOS */ 0x0065: 3, /* HLOOKUP */ 0x0066: 3, /* VLOOKUP */ 0x0069: 1, /* ISREF */ 0x006A: 1, /* GET.FORMULA */ 0x006C: 2, /* SET.VALUE */ 0x006F: 1, /* CHAR */ 0x0070: 1, /* LOWER */ 0x0071: 1, /* UPPER */ 0x0072: 1, /* PROPER */ 0x0075: 2, /* EXACT */ 0x0076: 1, /* TRIM */ 0x0077: 4, /* REPLACE */ 0x0079: 1, /* CODE */ 0x007E: 1, /* ISERR */ 0x007F: 1, /* ISTEXT */ 0x0080: 1, /* ISNUMBER */ 0x0081: 1, /* ISBLANK */ 0x0082: 1, /* T */ 0x0083: 1, /* N */ 0x0085: 1, /* FCLOSE */ 0x0086: 1, /* FSIZE */ 0x0087: 1, /* FREADLN */ 0x0088: 2, /* FREAD */ 0x0089: 2, /* FWRITELN */ 0x008A: 2, /* FWRITE */ 0x008C: 1, /* DATEVALUE */ 0x008D: 1, /* TIMEVALUE */ 0x008E: 3, /* SLN */ 0x008F: 4, /* SYD */ 0x0090: 4, /* DDB */ 0x00A1: 1, /* DIALOG.BOX */ 0x00A2: 1, /* CLEAN */ 0x00A3: 1, /* MDETERM */ 0x00A4: 1, /* MINVERSE */ 0x00A5: 2, /* MMULT */ 0x00AC: 1, /* WHILE */ 0x00AF: 2, /* INITIATE */ 0x00B0: 2, /* REQUEST */ 0x00B1: 3, /* POKE */ 0x00B2: 2, /* EXECUTE */ 0x00B3: 1, /* TERMINATE */ 0x00B8: 1, /* FACT */ 0x00BA: 1, /* GET.WORKSPACE */ 0x00BD: 3, /* DPRODUCT */ 0x00BE: 1, /* ISNONTEXT */ 0x00C3: 3, /* DSTDEVP */ 0x00C4: 3, /* DVARP */ 0x00C5: 1, /* TRUNC */ 0x00C6: 1, /* ISLOGICAL */ 0x00C7: 3, /* DCOUNTA */ 0x00C9: 1, /* UNREGISTER */ 0x00CF: 4, /* REPLACEB */ 0x00D2: 3, /* MIDB */ 0x00D3: 1, /* LENB */ 0x00D4: 2, /* ROUNDUP */ 0x00D5: 2, /* ROUNDDOWN */ 0x00D6: 1, /* ASC */ 0x00D7: 1, /* DBCS */ 0x00E1: 0, /* END.IF */ 0x00E5: 1, /* SINH */ 0x00E6: 1, /* COSH */ 0x00E7: 1, /* TANH */ 0x00E8: 1, /* ASINH */ 0x00E9: 1, /* ACOSH */ 0x00EA: 1, /* ATANH */ 0x00EB: 3, /* DGET */ 0x00F4: 1, /* INFO */ 0x00F7: 4, /* DB */ 0x00FC: 2, /* FREQUENCY */ 0x0101: 1, /* EVALUATE */ 0x0105: 1, /* ERROR.TYPE */ 0x010F: 1, /* GAMMALN */ 0x0111: 4, /* BINOMDIST */ 0x0112: 2, /* CHIDIST */ 0x0113: 2, /* CHIINV */ 0x0114: 2, /* COMBIN */ 0x0115: 3, /* CONFIDENCE */ 0x0116: 3, /* CRITBINOM */ 0x0117: 1, /* EVEN */ 0x0118: 3, /* EXPONDIST */ 0x0119: 3, /* FDIST */ 0x011A: 3, /* FINV */ 0x011B: 1, /* FISHER */ 0x011C: 1, /* FISHERINV */ 0x011D: 2, /* FLOOR */ 0x011E: 4, /* GAMMADIST */ 0x011F: 3, /* GAMMAINV */ 0x0120: 2, /* CEILING */ 0x0121: 4, /* HYPGEOMDIST */ 0x0122: 3, /* LOGNORMDIST */ 0x0123: 3, /* LOGINV */ 0x0124: 3, /* NEGBINOMDIST */ 0x0125: 4, /* NORMDIST */ 0x0126: 1, /* NORMSDIST */ 0x0127: 3, /* NORMINV */ 0x0128: 1, /* NORMSINV */ 0x0129: 3, /* STANDARDIZE */ 0x012A: 1, /* ODD */ 0x012B: 2, /* PERMUT */ 0x012C: 3, /* POISSON */ 0x012D: 3, /* TDIST */ 0x012E: 4, /* WEIBULL */ 0x012F: 2, /* SUMXMY2 */ 0x0130: 2, /* SUMX2MY2 */ 0x0131: 2, /* SUMX2PY2 */ 0x0132: 2, /* CHITEST */ 0x0133: 2, /* CORREL */ 0x0134: 2, /* COVAR */ 0x0135: 3, /* FORECAST */ 0x0136: 2, /* FTEST */ 0x0137: 2, /* INTERCEPT */ 0x0138: 2, /* PEARSON */ 0x0139: 2, /* RSQ */ 0x013A: 2, /* STEYX */ 0x013B: 2, /* SLOPE */ 0x013C: 4, /* TTEST */ 0x0145: 2, /* LARGE */ 0x0146: 2, /* SMALL */ 0x0147: 2, /* QUARTILE */ 0x0148: 2, /* PERCENTILE */ 0x014B: 2, /* TRIMMEAN */ 0x014C: 2, /* TINV */ 0x0151: 2, /* POWER */ 0x0156: 1, /* RADIANS */ 0x0157: 1, /* DEGREES */ 0x015A: 2, /* COUNTIF */ 0x015B: 1, /* COUNTBLANK */ 0x015E: 4, /* ISPMT */ 0x015F: 3, /* DATEDIF */ 0x0160: 1, /* DATESTRING */ 0x0161: 2, /* NUMBERSTRING */ 0x0168: 1, /* PHONETIC */ 0x0170: 1, /* BAHTTEXT */ 0x0171: 1, /* THAIDAYOFWEEK */ 0x0172: 1, /* THAIDIGIT */ 0x0173: 1, /* THAIMONTHOFYEAR */ 0x0174: 1, /* THAINUMSOUND */ 0x0175: 1, /* THAINUMSTRING */ 0x0176: 1, /* THAISTRINGLENGTH */ 0x0177: 1, /* ISTHAIDIGIT */ 0x0178: 1, /* ROUNDBAHTDOWN */ 0x0179: 1, /* ROUNDBAHTUP */ 0x017A: 1, /* THAIYEAR */ 0x017E: 3, /* CUBEMEMBERPROPERTY */ 0x0181: 1, /* HEX2DEC */ 0x0188: 1, /* OCT2DEC */ 0x0189: 1, /* BIN2DEC */ 0x018C: 2, /* IMSUB */ 0x018D: 2, /* IMDIV */ 0x018E: 2, /* IMPOWER */ 0x018F: 1, /* IMABS */ 0x0190: 1, /* IMSQRT */ 0x0191: 1, /* IMLN */ 0x0192: 1, /* IMLOG2 */ 0x0193: 1, /* IMLOG10 */ 0x0194: 1, /* IMSIN */ 0x0195: 1, /* IMCOS */ 0x0196: 1, /* IMEXP */ 0x0197: 1, /* IMARGUMENT */ 0x0198: 1, /* IMCONJUGATE */ 0x0199: 1, /* IMAGINARY */ 0x019A: 1, /* IMREAL */ 0x019E: 4, /* SERIESSUM */ 0x019F: 1, /* FACTDOUBLE */ 0x01A0: 1, /* SQRTPI */ 0x01A1: 2, /* QUOTIENT */ 0x01A4: 1, /* ISEVEN */ 0x01A5: 1, /* ISODD */ 0x01A6: 2, /* MROUND */ 0x01A8: 1, /* ERFC */ 0x01A9: 2, /* BESSELJ */ 0x01AA: 2, /* BESSELK */ 0x01AB: 2, /* BESSELY */ 0x01AC: 2, /* BESSELI */ 0x01AE: 3, /* XNPV */ 0x01B6: 3, /* TBILLEQ */ 0x01B7: 3, /* TBILLPRICE */ 0x01B8: 3, /* TBILLYIELD */ 0x01BB: 2, /* DOLLARDE */ 0x01BC: 2, /* DOLLARFR */ 0x01BD: 2, /* NOMINAL */ 0x01BE: 2, /* EFFECT */ 0x01BF: 6, /* CUMPRINC */ 0x01C0: 6, /* CUMIPMT */ 0x01C1: 2, /* EDATE */ 0x01C2: 2, /* EOMONTH */ 0x01D0: 2, /* RANDBETWEEN */ 0x01D4: 3, /* CONVERT */ 0x01DC: 2, /* FVSCHEDULE */ 0x01DF: 1, /* CUBESETCOUNT */ 0x01E0: 2, /* IFERROR */ 0xFFFF: 0 };
the_stack
import React, { useCallback } from 'react'; import { actions, ActionType, CellProps, CellRendererProps, Column, Row, TableInstance, TableState, } from 'react-table'; import { Checkbox, Code, InputGroup, Table, Leading, tableFilters, TableFilterValue, TableProps, Tooltip, DefaultCell, EditableCell, TablePaginator, TablePaginatorRendererProps, } from '../../src/core'; import { Story, Meta } from '@storybook/react'; import { useMemo, useState } from '@storybook/addons'; import { action } from '@storybook/addon-actions'; import { CreeveyMeta, CreeveyStoryParams } from 'creevey'; export default { title: 'Core/Table', component: Table, args: { data: [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], emptyTableContent: 'No data.', density: 'default', emptyFilteredTableContent: 'No results found. Clear or try another filter.', }, argTypes: { columns: { control: { disable: true } }, isSelectable: { control: { disable: true } }, style: { control: { disable: true } }, className: { control: { disable: true } }, id: { control: { disable: true } }, initialState: { table: { disable: true } }, stateReducer: { table: { disable: true } }, useControlledState: { table: { disable: true } }, defaultColumn: { table: { disable: true } }, getSubRows: { table: { disable: true } }, getRowId: { table: { disable: true } }, manualRowSelectedKey: { table: { disable: true } }, autoResetSelectedRows: { table: { disable: true } }, selectSubRows: { table: { disable: true } }, manualSortBy: { table: { disable: true } }, defaultCanSort: { table: { disable: true } }, disableMultiSort: { table: { disable: true } }, isMultiSortEvent: { table: { disable: true } }, maxMultiSortColCount: { table: { disable: true } }, disableSortRemove: { table: { disable: true } }, disabledMultiRemove: { table: { disable: true } }, orderByFn: { table: { disable: true } }, sortTypes: { table: { disable: true } }, autoResetSortBy: { table: { disable: true } }, autoResetHiddenColumns: { table: { disable: true } }, autoResetFilters: { table: { disable: true } }, filterTypes: { table: { disable: true } }, defaultCanFilter: { table: { disable: true } }, manualFilters: { table: { disable: true } }, paginateExpandedRows: { table: { disable: true } }, expandSubRows: { table: { disable: true } }, autoResetExpanded: { table: { disable: true } }, manualExpandedKey: { table: { disable: true } }, }, parameters: { creevey: { skip: { stories: ['Lazy Loading', 'Row In Viewport'] } }, }, } as Meta<TableProps> & CreeveyMeta; export const Basic: Story<Partial<TableProps>> = (args) => { const onClickHandler = ( props: CellProps<{ name: string; description: string }>, ) => action(props.row.original.name)(); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, }, { id: 'click-me', Header: 'Click', width: 100, Cell: (props: CellProps<{ name: string; description: string }>) => { const onClick = () => onClickHandler(props); return ( <a className='iui-anchor' onClick={onClick}> Click me! </a> ); }, }, ], }, ], [], ); const data = useMemo( () => [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], [], ); return ( <Table columns={columns} data={data} emptyTableContent='No data.' {...args} /> ); }; export const Selectable: Story<Partial<TableProps>> = (args) => { const onSelect = useCallback( (rows, state) => action( `Selected rows: ${JSON.stringify(rows)}, Table state: ${JSON.stringify( state, )}`, )(), [], ); const onRowClick = useCallback( (event: React.MouseEvent, row: Row) => action(`Row clicked: ${JSON.stringify(row.original)}`)(), [], ); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, }, { id: 'click-me', Header: 'Click', width: 100, Cell: (props: CellProps<{ name: string; description: string }>) => { return ( <a className='iui-anchor' onClick={(e) => { e.stopPropagation(); // prevent row selection when clicking on link action(props.row.original.name)(); }} > Click me! </a> ); }, }, ], }, ], [], ); const data = useMemo( () => [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], [], ); return ( <Table columns={columns} data={data} emptyTableContent='No data.' isSelectable={true} onSelect={onSelect} onRowClick={onRowClick} {...args} /> ); }; Selectable.args = { isSelectable: true }; export const Sortable: Story<Partial<TableProps>> = (args) => { const onClickHandler = ( props: CellProps<{ name: string; description: string }>, ) => action(props.row.original.name)(); const onSort = useCallback( (state) => action(`Sort changed. Table state: ${JSON.stringify(state)}`)(), [], ); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description Not Sortable', accessor: 'description', maxWidth: 200, disableSortBy: true, }, { id: 'click-me', Header: 'Click', width: 100, Cell: (props: CellProps<{ name: string; description: string }>) => { const onClick = () => onClickHandler(props); return ( <a className='iui-anchor' onClick={onClick}> Click me! </a> ); }, }, ], }, ], [], ); const data = useMemo( () => [ { name: 'Name1', description: 'Description1' }, { name: 'Name3', description: 'Description3' }, { name: 'Name2', description: 'Description2' }, ], [], ); return ( <Table columns={columns} data={data} emptyTableContent='No data.' isSortable onSort={onSort} {...args} /> ); }; Sortable.args = { data: [ { name: 'Name1', description: 'Description1' }, { name: 'Name3', description: 'Description3' }, { name: 'Name2', description: 'Description2' }, ], isSortable: true, }; export const Filters: Story<Partial<TableProps>> = (args) => { type TableStoryDataType = { index: number; name: string; description: string; ids: number[]; startDate: Date; endDate: string; }; const translatedLabels = useMemo( () => ({ filter: 'Filter', clear: 'Clear', from: 'From', to: 'To', }), [], ); const formatter = useMemo( () => new Intl.DateTimeFormat('en-us', { month: 'short', day: 'numeric', year: 'numeric', }), [], ); const formatDate = useCallback( (date: Date) => { return formatter.format(date); }, [formatter], ); const columns = useMemo( (): Column<TableStoryDataType>[] => [ { Header: 'Table', columns: [ { id: 'index', Header: '#', accessor: 'index', width: 80, fieldType: 'number', Filter: tableFilters.NumberRangeFilter(translatedLabels), filter: 'between', }, { id: 'name', Header: 'Name', accessor: 'name', fieldType: 'text', Filter: tableFilters.TextFilter(translatedLabels), }, { id: 'description', Header: 'Description', accessor: 'description', fieldType: 'text', Filter: tableFilters.TextFilter(translatedLabels), maxWidth: 200, }, { id: 'ids', Header: 'IDs (enter one of the IDs in the filter)', accessor: 'ids', Cell: (props: CellProps<TableStoryDataType>) => { return props.row.original.ids.join(', '); }, Filter: tableFilters.TextFilter(translatedLabels), filter: 'includes', }, { id: 'startDate', Header: 'Start date', accessor: 'startDate', Cell: (props: CellProps<TableStoryDataType>) => { return formatDate(props.row.original.startDate); }, Filter: tableFilters.DateRangeFilter({ translatedLabels, }), filter: 'betweenDate', }, { id: 'endDate', Header: 'End date', // Converting string to Date for filtering accessor: (rowData) => new Date(rowData.endDate), Cell: (props: CellProps<TableStoryDataType>) => { return formatDate(new Date(props.row.original.endDate)); }, Filter: tableFilters.DateRangeFilter({ translatedLabels, }), filter: 'betweenDate', }, ], }, ], [formatDate, translatedLabels], ); const data = useMemo( () => [ { index: 1, name: 'Name1', description: 'Description1', ids: ['1'], startDate: new Date('May 1, 2021'), endDate: '2021-05-31T21:00:00.000Z', }, { index: 2, name: 'Name2', description: 'Description2', ids: ['2', '3', '4'], startDate: new Date('May 2, 2021'), endDate: '2021-06-01T21:00:00.000Z', }, { index: 3, name: 'Name3', description: 'Description3', ids: ['3', '4'], startDate: new Date('May 3, 2021'), endDate: '2021-06-02T21:00:00.000Z', }, ], [], ); const onFilter = React.useCallback( (filters: TableFilterValue<TableStoryDataType>[], state: TableState) => { action( `Filter changed. Filters: ${JSON.stringify( filters, )}, State: ${JSON.stringify(state)}`, )(); }, [], ); return ( <Table columns={columns} data={data} emptyTableContent='No data.' onFilter={onFilter} {...args} /> ); }; Filters.args = { data: [ { index: 1, name: 'Name1', description: 'Description1', ids: ['1'], startDate: new Date('May 1, 2021'), endDate: '2021-05-31T21:00:00.000Z', }, { index: 2, name: 'Name2', description: 'Description2', ids: ['2', '3', '4'], startDate: new Date('May 2, 2021'), endDate: '2021-06-01T21:00:00.000Z', }, { index: 3, name: 'Name3', description: 'Description3', ids: ['3', '4'], startDate: new Date('May 3, 2021'), endDate: '2021-06-02T21:00:00.000Z', }, ], }; Filters.parameters = { creevey: { tests: { async open() { const filter = ( await this.browser.findElements({ css: '.iui-filter-button', }) )[1]; await this.browser.actions().move({ origin: filter }).click().perform(); await this.expect( await this.browser .findElement({ css: '.iui-table' }) .takeScreenshot(), ).to.matchImage('opened'); }, }, } as CreeveyStoryParams, }; export const Expandable: Story<Partial<TableProps>> = (args) => { const onExpand = useCallback( (rows, state) => action( `Expanded rows: ${JSON.stringify(rows)}. Table state: ${JSON.stringify( state, )}`, )(), [], ); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, }, ], }, ], [], ); const data = useMemo( () => [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], [], ); const expandedSubComponent = useCallback( (row: Row) => ( <div style={{ padding: 16 }}> <Leading>Extra information</Leading> <pre> <code>{JSON.stringify({ values: row.values }, null, 2)}</code> </pre> </div> ), [], ); return ( <Table columns={columns} data={data} emptyTableContent='No data.' subComponent={expandedSubComponent} onExpand={onExpand} {...args} /> ); }; Expandable.args = { isSelectable: true, }; Expandable.parameters = { creevey: { tests: { async open() { const closed = await this.takeScreenshot(); const table = await this.browser.findElement({ css: '.iui-table', }); const expanderButtons = await table.findElements({ css: '.iui-button', }); await expanderButtons[0].click(); await expanderButtons[2].click(); const expanded = await this.takeScreenshot(); await this.expect({ closed, expanded }).to.matchImages(); }, }, } as CreeveyStoryParams, }; export const ExpandableSubrows: Story<Partial<TableProps>> = (args) => { const onExpand = useCallback( (rows, state) => action( `Expanded rows: ${JSON.stringify(rows)}. Table state: ${JSON.stringify( state, )}`, )(), [], ); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', Filter: tableFilters.TextFilter(), }, { id: 'description', Header: 'Description', accessor: 'description', }, ], }, ], [], ); const data = [ { name: 'Row 1', description: 'Description 1', subRows: [ { name: 'Row 1.1', description: 'Description 1.1', subRows: [] }, { name: 'Row 1.2', description: 'Description 1.2', subRows: [ { name: 'Row 1.2.1', description: 'Description 1.2.1', subRows: [], }, { name: 'Row 1.2.2', description: 'Description 1.2.2', subRows: [], }, { name: 'Row 1.2.3', description: 'Description 1.2.3', subRows: [], }, { name: 'Row 1.2.4', description: 'Description 1.2.4', subRows: [], }, ], }, { name: 'Row 1.3', description: 'Description 1.3', subRows: [] }, { name: 'Row 1.4', description: 'Description 1.4', subRows: [] }, ], }, { name: 'Row 2', description: 'Description 2', subRows: [ { name: 'Row 2.1', description: 'Description 2.1', subRows: [] }, { name: 'Row 2.2', description: 'Description 2.2', subRows: [] }, { name: 'Row 2.3', description: 'Description 2.3', subRows: [] }, ], }, { name: 'Row 3', description: 'Description 3', subRows: [] }, ]; return ( <> <div> Each data entry should have <Code>subRows</Code> property. If{' '} <Code>subRows</Code> has any items, then expander will be shown for that row. </div> <br /> <Table emptyTableContent='No data.' isSelectable isSortable data={data} columns={columns} {...args} onExpand={onExpand} /> </> ); }; ExpandableSubrows.args = { data: [ { name: 'Row 1', description: 'Description 1', subRows: [ { name: 'Row 1.1', description: 'Description 1.1', subRows: [] }, { name: 'Row 1.2', description: 'Description 1.2', subRows: [ { name: 'Row 1.2.1', description: 'Description 1.2.1', subRows: [], }, { name: 'Row 1.2.2', description: 'Description 1.2.2', subRows: [], }, { name: 'Row 1.2.3', description: 'Description 1.2.3', subRows: [], }, { name: 'Row 1.2.4', description: 'Description 1.2.4', subRows: [], }, ], }, { name: 'Row 1.3', description: 'Description 1.3', subRows: [] }, { name: 'Row 1.4', description: 'Description 1.4', subRows: [] }, ], }, { name: 'Row 2', description: 'Description 2', subRows: [ { name: 'Row 2.1', description: 'Description 2.1', subRows: [] }, { name: 'Row 2.2', description: 'Description 2.2', subRows: [] }, { name: 'Row 2.3', description: 'Description 2.3', subRows: [] }, ], }, { name: 'Row 3', description: 'Description 3', subRows: [] }, ], }; ExpandableSubrows.parameters = { creevey: { tests: { async expand() { const closed = await this.browser .findElement({ css: '.iui-table' }) .takeScreenshot(); let expanders = await this.browser.findElements({ css: '.iui-row-expander', }); // Expand Row 1 await expanders[0].click(); expanders = await this.browser.findElements({ css: '.iui-row-expander', }); // Expand Row 1.2 await expanders[1].click(); const expanded = await this.browser .findElement({ css: '.iui-table' }) .takeScreenshot(); await this.expect({ closed, expanded }).to.matchImages(); }, }, } as CreeveyStoryParams, }; export const LazyLoading: Story<Partial<TableProps>> = (args) => { const onClickHandler = ( props: CellProps<{ name: string; description: string }>, ) => action(props.row.original.name)(); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, }, { id: 'click-me', Header: 'Click', width: 100, Cell: (props: CellProps<{ name: string; description: string }>) => { const onClick = () => onClickHandler(props); return ( <a className='iui-anchor' onClick={onClick}> Click me! </a> ); }, }, ], }, ], [], ); const generateData = (start: number, end: number) => { return Array(end - start) .fill(null) .map((_, index) => ({ name: `Name${start + index}`, description: `Description${start + index}`, })); }; const [data, setData] = useState(() => generateData(0, 100)); const [isLoading, setIsLoading] = useState(false); const onBottomReached = useCallback(() => { action('Bottom reached!')(); setIsLoading(true); // Simulating request setTimeout(() => { setData(() => [...data, ...generateData(data.length, data.length + 100)]); setIsLoading(false); }, 1000); }, [data]); return ( <Table columns={columns} emptyTableContent='No data.' onBottomReached={onBottomReached} isLoading={isLoading} {...args} data={data} /> ); }; LazyLoading.argTypes = { isLoading: { control: { disable: true } }, }; export const RowInViewport: Story<Partial<TableProps>> = (args) => { const onClickHandler = ( props: CellProps<{ name: string; description: string }>, ) => action(props.row.original.name)(); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, }, { id: 'click-me', Header: 'Click', width: 100, Cell: (props: CellProps<{ name: string; description: string }>) => { const onClick = () => onClickHandler(props); return ( <a className='iui-anchor' onClick={onClick}> Click me! </a> ); }, }, ], }, ], [], ); const data = useMemo( () => Array(100) .fill(null) .map((_, index) => ({ name: `Name${index}`, description: `Description${index}`, })), [], ); const onRowInViewport = useCallback((rowData) => { action(`Row in view: ${JSON.stringify(rowData)}`)(); }, []); return ( <> <div> Demo of <Code>IntersectionObserver</Code> hook that triggers{' '} <Code>onRowInViewport</Code> callback once the row is visible. </div> <div> Open{' '} <a className='iui-anchor' onClick={() => (parent.document.querySelector( '[id^="tabbutton-actions"]', ) as HTMLButtonElement)?.click() } > Actions </a>{' '} tab to see when callback is called and scroll the table. </div> <br /> <Table columns={columns} emptyTableContent='No data.' onRowInViewport={onRowInViewport} {...args} data={data} /> </> ); }; RowInViewport.argTypes = { data: { control: { disable: true } }, }; export const DisabledRows: Story<Partial<TableProps>> = (args) => { const onRowClick = useCallback( (event: React.MouseEvent, row: Row) => action(`Row clicked: ${JSON.stringify(row.original)}`)(), [], ); const isRowDisabled = useCallback( (rowData: { name: string; description: string }) => { return rowData.name === 'Name2'; }, [], ); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, }, ], }, { id: 'click-me', Header: 'Click', width: 100, // Manually handling disabled state in custom cells Cell: (props: CellProps<{ name: string; description: string }>) => ( <> {isRowDisabled(props.row.original) ? ( <>Click me!</> ) : ( <a className='iui-anchor' onClick={action(props.row.original.name)} > Click me! </a> )} </> ), }, ], [isRowDisabled], ); const data = useMemo( () => [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], [], ); const expandedSubComponent = useCallback( (row: Row) => ( <div style={{ padding: 16 }}> <Leading>Extra information</Leading> <pre> <code>{JSON.stringify({ values: row.values }, null, 2)}</code> </pre> </div> ), [], ); return ( <Table columns={columns} data={data} emptyTableContent='No data.' onRowClick={onRowClick} subComponent={expandedSubComponent} isRowDisabled={isRowDisabled} {...args} /> ); }; DisabledRows.args = { data: [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], isSelectable: true, }; export const Loading: Story<Partial<TableProps>> = (args) => { const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, }, ], }, ], [], ); return ( <Table columns={columns} data={[]} isLoading={true} emptyTableContent='No data.' {...args} /> ); }; Loading.args = { data: [], isLoading: true, }; export const NoData: Story<Partial<TableProps>> = (args) => { const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, }, ], }, ], [], ); return ( <Table columns={columns} data={[]} isLoading={false} emptyTableContent='No data.' {...args} /> ); }; NoData.args = { data: [], }; export const ControlledState: Story<Partial<TableProps>> = (args) => { const [selectedRows, setSelectedRows] = useState<Record<string, boolean>>({}); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', }, ], }, ], [], ); const data = useMemo( () => [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], [], ); const controlledState = useCallback( (state) => { return { ...state, selectedRowIds: { ...selectedRows }, }; }, [selectedRows], ); // When using `useControlledState` we are fully responsible for the state part we are modifying. // Therefore we want to keep our outside state (`selectedRows`) in sync with inside table state (`state.selectedRowIds`). const tableStateReducer = ( newState: TableState, action: ActionType, previousState: TableState, instance?: TableInstance, ): TableState => { switch (action.type) { case actions.toggleRowSelected: { const newSelectedRows = { ...selectedRows, }; if (action.value) { newSelectedRows[action.id] = true; } else { delete newSelectedRows[action.id]; } setSelectedRows(newSelectedRows); newState.selectedRowIds = newSelectedRows; break; } case actions.toggleAllRowsSelected: { if (!instance?.rowsById) { break; } const newSelectedRows = {} as Record<string, boolean>; if (action.value) { Object.keys(instance.rowsById).forEach( (id) => (newSelectedRows[id] = true), ); } setSelectedRows(newSelectedRows); newState.selectedRowIds = newSelectedRows; break; } default: break; } return newState; }; return ( <> <InputGroup label='Control selected rows' style={{ marginBottom: 11 }}> {data.map((data, index) => ( <Checkbox key={index} label={data.name} checked={selectedRows[index]} onChange={(e) => { setSelectedRows((rowIds) => { const selectedRowIds = { ...rowIds }; if (e.target.checked) { selectedRowIds[index] = true; } else { delete selectedRowIds[index]; } return selectedRowIds; }); }} /> ))} </InputGroup> <Table columns={columns} data={data} emptyTableContent='No data.' useControlledState={controlledState} stateReducer={tableStateReducer} isSelectable {...args} /> </> ); }; ControlledState.args = { isSelectable: true }; export const Full: Story<Partial<TableProps>> = (args) => { const [hoveredRowIndex, setHoveredRowIndex] = useState(0); const rowRefMap = React.useRef<Record<number, HTMLDivElement>>({}); const isRowDisabled = useCallback( (rowData: { name: string; description: string }) => { return rowData.name === 'Name2'; }, [], ); const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', Filter: tableFilters.TextFilter(), }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, Filter: tableFilters.TextFilter(), }, ], }, ], [], ); const data = useMemo( () => [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], [], ); const expandedSubComponent = useCallback( (row: Row) => ( <div style={{ padding: 16 }}> <Leading>Extra information</Leading> <pre> <code>{JSON.stringify({ values: row.values }, null, 2)}</code> </pre> </div> ), [], ); const rowProps = useCallback( (row: Row<{ name: string; description: string }>) => { return { onMouseEnter: () => { action(`Hovered over ${row.original.name}`)(); setHoveredRowIndex(row.index); }, ref: (el: HTMLDivElement | null) => { if (el) { rowRefMap.current[row.index] = el; } }, }; }, [], ); return ( <> <Table columns={columns} data={data} emptyTableContent='No data.' subComponent={expandedSubComponent} isRowDisabled={isRowDisabled} rowProps={rowProps} isSelectable isSortable isResizable {...args} /> <Tooltip reference={rowRefMap.current[hoveredRowIndex]} content={`Hovered over ${data[hoveredRowIndex].name}.`} placement='bottom' /> </> ); }; Full.args = { data: [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Description3' }, ], isSelectable: true, isSortable: true, isResizable: true, }; export const Condensed: Story<Partial<TableProps>> = Basic.bind({}); Condensed.args = { density: 'condensed' }; export const Editable: Story<Partial<TableProps>> = (args) => { type TableStoryDataType = { name: string; description: string; }; const [data, setData] = React.useState(() => [ { name: 'Name1', description: 'Description1' }, { name: 'Name2', description: 'Description2' }, { name: 'Name3', description: 'Fetching...' }, ]); const isRowDisabled = useCallback((rowData: TableStoryDataType) => { return rowData.name === 'Name2'; }, []); const onCellEdit = useCallback( (columnId: string, value: string, rowData: TableStoryDataType) => { action('onCellEdit')({ columnId, value, rowData }); setData((oldData) => { const newData = [...oldData]; const index = oldData.indexOf(rowData); const newObject = { ...newData[index] }; newObject[columnId as keyof TableStoryDataType] = value; newData[index] = newObject; return newData; }); }, [], ); const cellRenderer = useCallback( (props: CellRendererProps<TableStoryDataType>) => ( <> {!isRowDisabled(props.cellProps.row.original) && props.cellProps.value !== 'Fetching...' ? ( <EditableCell {...props} onCellEdit={onCellEdit} /> ) : ( <DefaultCell {...props} /> )} </> ), [isRowDisabled, onCellEdit], ); const columns = React.useMemo( (): Column<TableStoryDataType>[] => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', cellRenderer, Filter: tableFilters.TextFilter(), }, { id: 'description', Header: 'Description', accessor: 'description', cellRenderer, Filter: tableFilters.TextFilter(), }, ], }, ], [cellRenderer], ); return ( <Table emptyTableContent='No data.' {...args} columns={columns} data={data} isRowDisabled={isRowDisabled} isSortable isSelectable // These flags prevent filters and sorting from resetting autoResetFilters={false} autoResetSortBy={false} /> ); }; Editable.argTypes = { data: { control: { disable: true } }, }; Editable.parameters = { creevey: { tests: { async focusAndHover() { const editableCells = await this.browser.findElements({ css: '.iui-cell[contenteditable]', }); await this.browser .actions() .click(editableCells[0]) .sendKeys('test') .perform(); await this.browser .actions() .move({ origin: editableCells[2] }) .perform(); await this.expect( await this.browser .findElement({ css: '.iui-table' }) .takeScreenshot(), ).to.matchImage(); }, }, } as CreeveyStoryParams, }; export const WithPaginator: Story<Partial<TableProps>> = (args) => { const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', Filter: tableFilters.TextFilter(), }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, Filter: tableFilters.TextFilter(), }, ], }, ], [], ); type TableStoryDataType = { name: string; description: string; subRows: TableStoryDataType[]; }; const generateItem = useCallback( (index: number, parentRow = '', depth = 0): TableStoryDataType => { const keyValue = parentRow ? `${parentRow}.${index}` : `${index}`; return { name: `Name ${keyValue}`, description: `Description ${keyValue}`, subRows: depth < 2 ? Array(Math.round(index % 5)) .fill(null) .map((_, index) => generateItem(index, keyValue, depth + 1)) : [], }; }, [], ); const data = useMemo( () => Array(5005) .fill(null) .map((_, index) => generateItem(index)), [generateItem], ); const pageSizeList = useMemo(() => [10, 25, 50], []); const paginator = useCallback( (props: TablePaginatorRendererProps) => ( <TablePaginator {...props} pageSizeList={pageSizeList} /> ), [pageSizeList], ); return ( <> <Table emptyTableContent='No data.' isSelectable isSortable {...args} columns={columns} data={data} pageSize={25} paginatorRenderer={paginator} style={{ height: '100%' }} /> </> ); }; WithPaginator.args = { isSelectable: true, isSortable: true, }; WithPaginator.decorators = [ (Story) => ( <div style={{ height: '90vh' }}> <Story /> </div> ), ]; WithPaginator.argTypes = { data: { control: { disable: true } }, parameters: { docs: { source: { excludeDecorators: true } }, }, }; export const WithManualPaginator: Story<Partial<TableProps>> = (args) => { const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', Filter: tableFilters.TextFilter(), }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, Filter: tableFilters.TextFilter(), }, ], }, ], [], ); const generateData = (start: number, end: number) => { return Array(end - start) .fill(null) .map((_, index) => ({ name: `Name${start + index}`, description: `Description${start + index}`, })); }; const [data, setData] = useState(() => generateData(0, 25)); const [isLoading, setIsLoading] = useState(false); const [currentPage, setCurrentPage] = useState(0); const pageSizeList = useMemo(() => [10, 25, 50], []); const paginator = useCallback( (props: TablePaginatorRendererProps) => ( <TablePaginator {...props} onPageChange={(page) => { setIsLoading(true); setData([]); setCurrentPage(page); // Simulating a request setTimeout(() => { setIsLoading(false); setData( generateData(page * props.pageSize, (page + 1) * props.pageSize), ); }, 500); }} onPageSizeChange={(size) => { setData(generateData(currentPage * size, (currentPage + 1) * size)); props.onPageSizeChange(size); }} pageSizeList={pageSizeList} currentPage={currentPage} isLoading={false} // Imagining we know the total count of data items totalRowsCount={60000} /> ), [currentPage, pageSizeList], ); return ( <> <Table emptyTableContent='No data.' {...args} isLoading={isLoading} columns={columns} data={data} pageSize={25} paginatorRenderer={paginator} style={{ height: '100%' }} manualPagination /> </> ); }; WithManualPaginator.decorators = [ (Story) => ( <div style={{ height: '90vh' }}> <Story /> </div> ), ]; WithManualPaginator.argTypes = { data: { control: { disable: true } }, parameters: { docs: { source: { excludeDecorators: true } }, }, }; export const ResizableColumns: Story<Partial<TableProps>> = (args) => { type TableStoryDataType = { index: number; name: string; description: string; id: string; startDate: Date; endDate: Date; }; const columns = useMemo( (): Column<TableStoryDataType>[] => [ { Header: 'Table', columns: [ { id: 'index', Header: '#', accessor: 'index', width: 80, disableResizing: true, }, { id: 'name', Header: 'Name', accessor: 'name', }, { id: 'description', Header: 'Description', accessor: 'description', fieldType: 'text', minWidth: 100, }, { id: 'id', Header: 'ID', accessor: 'id', width: 100, disableResizing: true, }, { id: 'startDate', Header: 'Start date', accessor: 'startDate', Cell: (props: CellProps<TableStoryDataType>) => { return props.row.original.startDate.toLocaleDateString('en-US'); }, width: 100, disableResizing: true, }, { id: 'endDate', Header: 'End date', Cell: (props: CellProps<TableStoryDataType>) => { return props.row.original.endDate.toLocaleDateString('en-US'); }, maxWidth: 200, }, ], }, ], [], ); const data = useMemo( () => [ { index: 1, name: 'Name1', description: 'Description1', id: '111', startDate: new Date('May 1, 2021'), endDate: new Date('Jun 1, 2021'), }, { index: 2, name: 'Name2', description: 'Description2', id: '222', startDate: new Date('May 2, 2021'), endDate: new Date('Jun 2, 2021'), }, { index: 3, name: 'Name3', description: 'Description3', id: '333', startDate: new Date('May 3, 2021'), endDate: new Date('Jun 3, 2021'), }, ], [], ); return ( <Table columns={columns} data={data} emptyTableContent='No data.' isResizable isSortable {...args} /> ); }; ResizableColumns.args = { isResizable: true, data: [ { index: 1, name: 'Name1', description: 'Description1', id: '111', startDate: new Date('May 1, 2021'), endDate: new Date('Jun 1, 2021'), }, { index: 2, name: 'Name2', description: 'Description2', id: '222', startDate: new Date('May 2, 2021'), endDate: new Date('Jun 2, 2021'), }, { index: 3, name: 'Name3', description: 'Description3', id: '333', startDate: new Date('May 3, 2021'), endDate: new Date('Jun 3, 2021'), }, ], }; export const ZebraStripedRows: Story<Partial<TableProps>> = (args) => { const columns = useMemo( () => [ { Header: 'Table', columns: [ { id: 'name', Header: 'Name', accessor: 'name', Filter: tableFilters.TextFilter(), }, { id: 'description', Header: 'Description', accessor: 'description', maxWidth: 200, Filter: tableFilters.TextFilter(), }, ], }, ], [], ); type TableStoryDataType = { name: string; description: string; subRows: TableStoryDataType[]; }; const generateItem = useCallback( (index: number, parentRow = '', depth = 0): TableStoryDataType => { const keyValue = parentRow ? `${parentRow}.${index}` : `${index}`; return { name: `Name ${keyValue}`, description: `Description ${keyValue}`, subRows: depth < 2 ? Array(Math.round(index % 5)) .fill(null) .map((_, index) => generateItem(index, keyValue, depth + 1)) : [], }; }, [], ); const data = useMemo( () => Array(20) .fill(null) .map((_, index) => generateItem(index)), [generateItem], ); return ( <> <Table emptyTableContent='No data.' isSelectable isSortable styleType='zebra-rows' {...args} columns={columns} data={data} style={{ height: '100%' }} /> </> ); }; ZebraStripedRows.args = { isSelectable: true, isSortable: true, styleType: 'zebra-rows', }; export const HorizontalScroll: Story<Partial<TableProps>> = (args) => { const data = useMemo( () => [ { product: 'Product 1', price: 5, quantity: 500, rating: '4/5', deliveryTime: 5, }, { product: 'Product 2', price: 12, quantity: 1200, rating: '1/5', deliveryTime: 25, }, { product: 'Product 3', price: 2.99, quantity: 1500, rating: '3/5', deliveryTime: 7, }, { product: 'Product 4', price: 20, quantity: 50, rating: '4/5', deliveryTime: 2, }, { product: 'Product 5', price: 1.99, quantity: 700, rating: '5/5', deliveryTime: 1, }, { product: 'Product 6', price: 499, quantity: 30, rating: '5/5', deliveryTime: 20, }, { product: 'Product 7', price: 13.99, quantity: 130, rating: '1/5', deliveryTime: 30, }, { product: 'Product 8', price: 5.99, quantity: 500, rating: '4/5', deliveryTime: 5, }, { product: 'Product 9', price: 12, quantity: 1200, rating: '1/5', deliveryTime: 25, }, { product: 'Product 10', price: 2.99, quantity: 200, rating: '3/5', deliveryTime: 17, }, ], [], ); const columns = useMemo( (): Column[] => [ { Header: 'Table', columns: [ { id: 'product', Header: 'Product', accessor: 'product', minWidth: 400, }, { id: 'price', Header: 'Price', accessor: 'price', width: 400, Cell: (props: CellProps<typeof data[0]>) => { return `$${props.value}`; }, }, { id: 'quantity', Header: 'Quantity', accessor: 'quantity', width: 400, }, { id: 'rating', Header: 'Rating', accessor: 'rating', width: 400, }, { id: 'deliveryTime', Header: 'Delivery Time', accessor: 'deliveryTime', width: 400, Cell: (props: CellProps<typeof data[0]>) => { return `${props.value} day(s)`; }, }, ], }, ], [], ); return ( <Table columns={columns} data={data} emptyTableContent='No data.' style={{ height: '100%' }} {...args} /> ); }; HorizontalScroll.args = { data: [ { product: 'Product 1', price: 5, quantity: 500, rating: '4/5', deliveryTime: 5, }, { product: 'Product 2', price: 12, quantity: 1200, rating: '1/5', deliveryTime: 25, }, { product: 'Product 3', price: 2.99, quantity: 1500, rating: '3/5', deliveryTime: 7, }, { product: 'Product 4', price: 20, quantity: 50, rating: '4/5', deliveryTime: 2, }, { product: 'Product 5', price: 1.99, quantity: 700, rating: '5/5', deliveryTime: 1, }, { product: 'Product 6', price: 499, quantity: 30, rating: '5/5', deliveryTime: 20, }, { product: 'Product 7', price: 13.99, quantity: 130, rating: '1/5', deliveryTime: 30, }, { product: 'Product 8', price: 5.99, quantity: 500, rating: '4/5', deliveryTime: 5, }, { product: 'Product 9', price: 12, quantity: 1200, rating: '1/5', deliveryTime: 25, }, { product: 'Product 10', price: 2.99, quantity: 200, rating: '3/5', deliveryTime: 17, }, ], }; HorizontalScroll.decorators = [ (Story) => ( <div style={{ height: '375px', maxHeight: '90vh', maxWidth: '1000px', }} > <Story /> </div> ), ];
the_stack
import { Attribute, Entity, InvalidPrimaryKeyAttributesUpdateError, InvalidUniqueAttributeUpdateError, QUERY_ORDER, } from '@typedorm/common'; import {Customer} from '../../../../__mocks__/inherited-customer'; import {table} from '../../../../__mocks__/table'; import {User, UserGSI1} from '../../../../__mocks__/user'; import {createTestConnection, resetTestConnection} from '@typedorm/testing'; import {UserPrimaryKey} from '../../../../__mocks__/user'; import {DocumentClientRequestTransformer} from '../document-client-request-transformer'; import { UserUniqueEmail, UserUniqueEmailPrimaryKey, } from '../../../../__mocks__/user-unique-email'; import {CATEGORY, Photo, PhotoPrimaryKey} from '@typedorm/core/__mocks__/photo'; // eslint-disable-next-line node/no-extraneous-import import moment from 'moment'; jest.useFakeTimers('modern').setSystemTime(1622530750000); let transformer: DocumentClientRequestTransformer; beforeEach(async () => { const connection = createTestConnection({ entities: [User, Customer, UserUniqueEmail, Photo], }); transformer = new DocumentClientRequestTransformer(connection); }); afterEach(() => { resetTestConnection(); }); /** * @group toDynamoGetItem */ test('transforms get item requests', () => { const getItem = transformer.toDynamoGetItem<User, UserPrimaryKey>(User, { id: '1', }); expect(getItem).toEqual({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }); }); test('transforms get item requests with projection expression', () => { const getItem = transformer.toDynamoGetItem<User, UserPrimaryKey>( User, { id: '1', }, { select: ['name'], } ); expect(getItem).toEqual({ Key: { PK: 'USER#1', SK: 'USER#1', }, ExpressionAttributeNames: { '#PE_name': 'name', }, ProjectionExpression: '#PE_name', TableName: 'test-table', }); }); test('transforms get item requests for inherited class', () => { const getItem = transformer.toDynamoGetItem(Customer, { id: '1', email: 'user@example.com', }); expect(getItem).toEqual({ Key: { PK: 'CUS#1', SK: 'CUS#user@example.com', }, TableName: 'test-table', }); }); /** * @group toDynamoPutItem */ test('transforms put item requests', () => { const user = new User(); user.id = '1'; user.name = 'Tito'; user.status = 'active'; const putItem = transformer.toDynamoPutItem(user); expect(putItem).toEqual({ Item: { GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Tito', PK: 'USER#1', SK: 'USER#1', id: '1', name: 'Tito', __en: 'user', status: 'active', }, ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, TableName: 'test-table', }); }); test('transforms put item requests with condition', () => { const user = new User(); user.id = '1'; user.name = 'Tito'; user.status = 'active'; const putItem = transformer.toDynamoPutItem(user, { where: { status: { EQ: 'active', }, }, }); expect(putItem).toEqual({ Item: { GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Tito', PK: 'USER#1', SK: 'USER#1', id: '1', name: 'Tito', __en: 'user', status: 'active', }, ConditionExpression: '((attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))) AND (#CE_status = :CE_status)', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', '#CE_status': 'status', }, ExpressionAttributeValues: { ':CE_status': 'active', }, TableName: 'test-table', }); }); test('transforms put item request with unique attributes', () => { resetTestConnection(); @Entity({ table, name: 'user', primaryKey: { partitionKey: 'USER#{{id}}', sortKey: 'USER#{{id}}', }, }) class UserUniqueEmail { @Attribute() id: string; @Attribute({ unique: true, }) email: string; } const newConnection = createTestConnection({ entities: [UserUniqueEmail], }); const newTransformer = new DocumentClientRequestTransformer(newConnection); const user = new UserUniqueEmail(); user.id = '1'; user.email = 'user@example.com'; const putItem = newTransformer.toDynamoPutItem(user); expect(putItem).toEqual([ { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: {'#CE_PK': 'PK', '#CE_SK': 'SK'}, Item: { PK: 'USER#1', SK: 'USER#1', email: 'user@example.com', id: '1', __en: 'user', }, TableName: 'test-table', }, }, { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: {'#CE_PK': 'PK', '#CE_SK': 'SK'}, Item: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@example.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@example.com', }, TableName: 'test-table', }, }, ]); }); test('transforms put item request with unique attributes and condition options', () => { const user = new UserUniqueEmail(); user.id = '1'; user.email = 'user@example.com'; user.name = 'test user'; user.status = 'active'; const putItem = transformer.toDynamoPutItem(user, { where: { status: 'ATTRIBUTE_NOT_EXISTS', }, }); expect(putItem).toEqual([ { Put: { ConditionExpression: '((attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))) AND (attribute_not_exists(#CE_status))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', '#CE_status': 'status', }, Item: { PK: 'USER#1', SK: 'USER#1', email: 'user@example.com', id: '1', name: 'test user', status: 'active', __en: 'user-unique-email', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#test user', }, TableName: 'test-table', }, }, { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: {'#CE_PK': 'PK', '#CE_SK': 'SK'}, Item: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@example.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@example.com', }, TableName: 'test-table', }, }, ]); }); test('transforms put item request with default values ', () => { resetTestConnection(); @Entity({ table, name: 'product', primaryKey: { partitionKey: 'PRD#{{id}}', sortKey: 'PRD#{{id}}', }, }) class Product { @Attribute() id: string; @Attribute({ default: () => 'available', }) status: string; } const newConnection = createTestConnection({ entities: [Product], }); const newTransformer = new DocumentClientRequestTransformer(newConnection); const product = new Product(); product.id = '1'; const putItem = newTransformer.toDynamoPutItem(product); expect(putItem).toEqual({ ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, Item: { PK: 'PRD#1', SK: 'PRD#1', __en: 'product', id: '1', status: 'available', }, TableName: 'test-table', }); // when overriding item, this can product.status = 'unavailable'; const overriddenPutItem = newTransformer.toDynamoPutItem(product) as any; expect(overriddenPutItem.Item.status).toEqual('unavailable'); }); test('transforms put item request with dynamic default values ', () => { resetTestConnection(); @Entity({ table, name: 'person', primaryKey: { partitionKey: 'PER#{{id}}', sortKey: 'PER#{{id}}', }, }) class Person { @Attribute() id: string; @Attribute() firstName: string; @Attribute() lastName: string; @Attribute<Person>({ default: person => `${person.firstName} ${person.lastName}`, }) name: string; } const newConnection = createTestConnection({ entities: [Person], }); const newTransformer = new DocumentClientRequestTransformer(newConnection); const person = new Person(); person.id = '1'; person.firstName = 'Rushi'; person.lastName = 'Patel'; const putItem = newTransformer.toDynamoPutItem(person); expect(putItem).toEqual({ ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, Item: { PK: 'PER#1', SK: 'PER#1', __en: 'person', id: '1', name: 'Rushi Patel', firstName: 'Rushi', lastName: 'Patel', }, TableName: 'test-table', }); }); test('transforms put item request consisting unique attributes with provided primary key', () => { resetTestConnection(); @Entity({ table, name: 'user', primaryKey: { partitionKey: 'USER#{{id}}', sortKey: 'USER#{{id}}', }, }) class UserUniqueEmail { @Attribute() id: string; @Attribute({ unique: { partitionKey: 'CUSTOM#{{email}}', sortKey: 'CUSTOM#{{email}}', }, }) email: string; } const newConnection = createTestConnection({ entities: [UserUniqueEmail], }); const newTransformer = new DocumentClientRequestTransformer(newConnection); const user = new UserUniqueEmail(); user.id = '1'; user.email = 'user@example.com'; const putItem = newTransformer.toDynamoPutItem(user); expect(putItem).toEqual([ { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: {'#CE_PK': 'PK', '#CE_SK': 'SK'}, Item: { PK: 'USER#1', SK: 'USER#1', email: 'user@example.com', id: '1', __en: 'user', }, TableName: 'test-table', }, }, { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: {'#CE_PK': 'PK', '#CE_SK': 'SK'}, Item: { PK: 'CUSTOM#user@example.com', SK: 'CUSTOM#user@example.com', }, TableName: 'test-table', }, }, ]); }); /** * @group toDynamoUpdateItem */ test('transforms update item request', () => { const updatedItem = transformer.toDynamoUpdateItem<User, UserPrimaryKey>( User, { id: '1', }, { name: 'new name', } ); expect(updatedItem).toEqual({ ExpressionAttributeNames: { '#UE_name': 'name', '#UE_GSI1SK': 'GSI1SK', }, ExpressionAttributeValues: { ':UE_name': 'new name', ':UE_GSI1SK': 'USER#new name', }, Key: { PK: 'USER#1', SK: 'USER#1', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_name = :UE_name, #UE_GSI1SK = :UE_GSI1SK', }); }); // Issue: #154 test('transforms update item request with custom transformation', () => { const updatedItem = transformer.toDynamoUpdateItem( Photo, { id: '123', category: CATEGORY.KIDS, }, { createdAt: moment().subtract(2, 'days'), } ); expect(updatedItem).toEqual({ ExpressionAttributeNames: { '#UE_createdAt': 'createdAt', '#UE_updatedAt': 'updatedAt', }, ExpressionAttributeValues: { ':UE_createdAt': '2021-05-30', ':UE_updatedAt': '1622530750', }, Key: { PK: 'PHOTO#KIDS', SK: 'PHOTO#123', }, ReturnConsumedCapacity: undefined, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_createdAt = :UE_createdAt, #UE_updatedAt = :UE_updatedAt', }); }); test('transforms update item request respects custom transforms applied via class transformer', () => { const updatedItem = transformer.toDynamoUpdateItem( Photo, { id: 1, category: CATEGORY.KIDS, }, { category: { // even tho we try to update `category` attribute to `KIDS` final result will have `new-kids` // due to custom transformation defined on the Photo entity SET: { IF_NOT_EXISTS: CATEGORY.KIDS, }, }, } ); const writeItemList = (updatedItem as any).lazyLoadTransactionWriteItems({ id: 1, category: CATEGORY.PETS, PK: 'PHOTO#PETS', SK: 'PHOTO#1', GSI1PK: 'PHOTO#1', GSI1SK: 'PHOTO#PETS', }); expect(writeItemList).toEqual([ { Put: { Item: { GSI1SK: 'PHOTO#kids-new', GSI1PK: 'PHOTO#1', PK: 'PHOTO#kids-new', SK: 'PHOTO#1', category: 'kids-new', id: 1, updatedAt: '1622530750', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', }, }, { Delete: { Key: { PK: 'PHOTO#PETS', SK: 'PHOTO#1', }, TableName: 'test-table', }, }, ]); }); test('transforms update item record with unique attributes', () => { const updatedItem = transformer.toDynamoUpdateItem< UserUniqueEmail, UserPrimaryKey >( UserUniqueEmail, { id: '1', }, { name: 'new name', email: 'new@email.com', } ); const lazyWriteItemListLoader = (updatedItem as any) .lazyLoadTransactionWriteItems; expect(typeof lazyWriteItemListLoader).toEqual('function'); const writeItemList = lazyWriteItemListLoader({ name: 'new name', email: 'old@email.com', }); expect(writeItemList).toEqual([ { Update: { ExpressionAttributeNames: { '#UE_name': 'name', '#UE_email': 'email', '#UE_GSI1SK': 'GSI1SK', }, ExpressionAttributeValues: { ':UE_name': 'new name', ':UE_email': 'new@email.com', ':UE_GSI1SK': 'USER#new name', }, Key: {PK: 'USER#1', SK: 'USER#1'}, TableName: 'test-table', UpdateExpression: 'SET #UE_name = :UE_name, #UE_email = :UE_email, #UE_GSI1SK = :UE_GSI1SK', }, }, { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: {'#CE_PK': 'PK', '#CE_SK': 'SK'}, Item: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@email.com', }, TableName: 'test-table', }, }, { Delete: { Key: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', }, TableName: 'test-table', }, }, ]); }); test('transforms update item request with unique attributes and complex update value', () => { const updatedItem = transformer.toDynamoUpdateItem( UserUniqueEmail, { id: '1', }, { email: { SET: 'new@email.com', }, } ); const lazyWriteItemListLoader = (updatedItem as any) .lazyLoadTransactionWriteItems; expect(typeof lazyWriteItemListLoader).toEqual('function'); const writeItemList = lazyWriteItemListLoader({ email: 'old@email.com', }); expect(writeItemList).toEqual([ { Update: { ExpressionAttributeNames: { '#UE_email': 'email', }, ExpressionAttributeValues: { ':UE_email': 'new@email.com', }, Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', UpdateExpression: 'SET #UE_email = :UE_email', }, }, { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, Item: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@email.com', }, TableName: 'test-table', }, }, { Delete: { Key: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', }, TableName: 'test-table', }, }, ]); }); test('transforms update item request with condition input', () => { const updatedItem = transformer.toDynamoUpdateItem<User, UserPrimaryKey>( User, { id: '1', }, { name: 'new name', }, { where: { age: { BETWEEN: [3, 10], }, }, } ); expect(updatedItem).toEqual({ ExpressionAttributeNames: { '#UE_name': 'name', '#UE_GSI1SK': 'GSI1SK', '#CE_age': 'age', }, ExpressionAttributeValues: { ':UE_name': 'new name', ':UE_GSI1SK': 'USER#new name', ':CE_age_end': 10, ':CE_age_start': 3, }, Key: { PK: 'USER#1', SK: 'USER#1', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_name = :UE_name, #UE_GSI1SK = :UE_GSI1SK', ConditionExpression: '#CE_age BETWEEN :CE_age_start AND :CE_age_end', }); }); test('transforms update item record with unique attributes and condition options', () => { const updatedItem = transformer.toDynamoUpdateItem< UserUniqueEmail, UserPrimaryKey >( UserUniqueEmail, { id: '1', }, { name: 'new name', email: 'new@email.com', }, { where: { 'user.name': { NE: 'test user', }, }, } ); const lazyWriteItemListLoader = (updatedItem as any) .lazyLoadTransactionWriteItems; expect(typeof lazyWriteItemListLoader).toEqual('function'); const writeItemList = lazyWriteItemListLoader({ name: 'new name', email: 'old@email.com', }); expect(writeItemList).toEqual([ { Update: { ExpressionAttributeNames: { '#UE_name': 'name', '#UE_email': 'email', '#UE_GSI1SK': 'GSI1SK', '#CE_user': 'user', '#CE_user_name': 'name', }, ExpressionAttributeValues: { ':UE_name': 'new name', ':UE_email': 'new@email.com', ':UE_GSI1SK': 'USER#new name', ':CE_user_name': 'test user', }, Key: {PK: 'USER#1', SK: 'USER#1'}, TableName: 'test-table', UpdateExpression: 'SET #UE_name = :UE_name, #UE_email = :UE_email, #UE_GSI1SK = :UE_GSI1SK', ConditionExpression: '#CE_user.#CE_user_name <> :CE_user_name', }, }, { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: {'#CE_PK': 'PK', '#CE_SK': 'SK'}, Item: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@email.com', }, TableName: 'test-table', }, }, { Delete: { Key: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', }, TableName: 'test-table', }, }, ]); }); test('transforms update item with primary key changes', () => { const updateItem = transformer.toDynamoUpdateItem< UserUniqueEmail, UserPrimaryKey >( UserUniqueEmail, { id: '1', }, { id: '1a', } ); const lazyWriteItemListLoader = (updateItem as any) .lazyLoadTransactionWriteItems; expect(typeof lazyWriteItemListLoader).toEqual('function'); // with following existing item const writeItemList = lazyWriteItemListLoader({ id: '1', PK: 'USER#1', SK: 'USER#1', name: 'new name', email: 'user@email.com', __en: 'user', }); expect(writeItemList).toEqual([ { Put: { Item: { email: 'user@email.com', id: '1a', name: 'new name', PK: 'USER#1a', SK: 'USER#1a', __en: 'user', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', }, }, { Delete: { Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }, }, ]); }); test('transforms update item with attributes that reference primary key and indexes', () => { const updateItem = transformer.toDynamoUpdateItem<Photo, PhotoPrimaryKey>( Photo, { category: CATEGORY.PETS, id: 1, }, { id: 2, } ); const lazyWriteItemListLoader = (updateItem as any) .lazyLoadTransactionWriteItems; expect(typeof lazyWriteItemListLoader).toEqual('function'); // with following existing item const writeItemList = lazyWriteItemListLoader({ id: 1, PK: 'PHOTO#PETS', SK: 'PHOTO#1', category: 'PETS', GSI1PK: 'PHOTO#1', GSI1SK: 'PHOTO#PETS', __en: 'photo', }); expect(writeItemList).toEqual([ { Put: { Item: { GSI1PK: 'PHOTO#2', GSI1SK: 'PHOTO#PETS', PK: 'PHOTO#PETS', SK: 'PHOTO#2', __en: 'photo', category: 'PETS', id: 2, updatedAt: '1622530750', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', }, }, { Delete: { Key: { PK: 'PHOTO#PETS', SK: 'PHOTO#1', }, TableName: 'test-table', }, }, ]); }); test('throws when trying to update primary key attribute and unique attribute in the same request', () => { const updateItem = () => transformer.toDynamoUpdateItem<UserUniqueEmail, UserUniqueEmailPrimaryKey>( UserUniqueEmail, { id: 'OLD_ID', }, { id: 'NEW_ID', email: 'new@email.com', } ); expect(updateItem).toThrow(InvalidUniqueAttributeUpdateError); }); test('throws when trying to update primary key attribute and non key attribute in the same request', () => { const updateItem = () => transformer.toDynamoUpdateItem<Photo, PhotoPrimaryKey>( Photo, { category: CATEGORY.PETS, id: 1, }, { id: 2, createdAt: moment(), } ); expect(updateItem).toThrow(InvalidPrimaryKeyAttributesUpdateError); }); test('transforms update item request with complex condition input', () => { const updatedItem = transformer.toDynamoUpdateItem<User, UserPrimaryKey>( User, { id: '1', }, { name: 'new name', }, { where: { AND: { age: { GE: 3, }, status: { IN: ['active', 'standby'], }, }, }, } ); expect(updatedItem).toEqual({ ExpressionAttributeNames: { '#UE_name': 'name', '#UE_GSI1SK': 'GSI1SK', '#CE_age': 'age', '#CE_status': 'status', }, ExpressionAttributeValues: { ':UE_name': 'new name', ':UE_GSI1SK': 'USER#new name', ':CE_age': 3, ':CE_status_0': 'active', ':CE_status_1': 'standby', }, Key: { PK: 'USER#1', SK: 'USER#1', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_name = :UE_name, #UE_GSI1SK = :UE_GSI1SK', ConditionExpression: '(#CE_age >= :CE_age) AND (#CE_status IN (:CE_status_0, :CE_status_1))', }); }); /** * @group toDynamoDeleteItem */ test('transforms delete item request', () => { const deleteItemInput = transformer.toDynamoDeleteItem<User, UserPrimaryKey>( User, { id: '1', } ); expect(deleteItemInput).toEqual({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }); }); test('transforms delete item request with condition options', () => { const deleteItemInput = transformer.toDynamoDeleteItem<User, UserPrimaryKey>( User, { id: '1', }, { where: { age: { BETWEEN: [1, 9], }, }, } ); expect(deleteItemInput).toEqual({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', ConditionExpression: '#CE_age BETWEEN :CE_age_start AND :CE_age_end', ExpressionAttributeNames: { '#CE_age': 'age', }, ExpressionAttributeValues: { ':CE_age_end': 9, ':CE_age_start': 1, }, }); }); test('transforms delete item request with unique attributes', () => { const deleteItemInput = transformer.toDynamoDeleteItem< UserUniqueEmail, UserUniqueEmailPrimaryKey >(UserUniqueEmail, { id: '1', }); expect(deleteItemInput).toMatchObject({ entityClass: UserUniqueEmail, primaryKeyAttributes: { id: '1', }, }); const lazyWriteItemListLoader = (deleteItemInput as any) .lazyLoadTransactionWriteItems; expect(typeof lazyWriteItemListLoader).toEqual('function'); const deleteItemList = lazyWriteItemListLoader({ id: '1', name: 'new name', email: 'old@email.com', }); expect(deleteItemList).toEqual([ { Delete: { TableName: 'test-table', Key: { PK: 'USER#1', SK: 'USER#1', }, }, }, { Delete: { TableName: 'test-table', Key: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', }, }, }, ]); }); test('transforms delete item request with unique attributes and condition options', () => { const deleteItemInput = transformer.toDynamoDeleteItem< UserUniqueEmail, UserUniqueEmailPrimaryKey >( UserUniqueEmail, { id: '1', }, { where: { email: { NE: 'admin@user.com', }, }, } ); expect(deleteItemInput).toMatchObject({ entityClass: UserUniqueEmail, primaryKeyAttributes: { id: '1', }, }); const lazyWriteItemListLoader = (deleteItemInput as any) .lazyLoadTransactionWriteItems; expect(typeof lazyWriteItemListLoader).toEqual('function'); const deleteItemList = lazyWriteItemListLoader({ id: '1', name: 'new name', email: 'old@email.com', }); expect(deleteItemList).toEqual([ { Delete: { TableName: 'test-table', Key: { PK: 'USER#1', SK: 'USER#1', }, ConditionExpression: '#CE_email <> :CE_email', ExpressionAttributeNames: { '#CE_email': 'email', }, ExpressionAttributeValues: { ':CE_email': 'admin@user.com', }, }, }, { Delete: { TableName: 'test-table', Key: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', }, }, }, ]); }); /** * @group toDynamoQueryItem */ test('transforms simple query item request', () => { const queryItem = transformer.toDynamoQueryItem<User, UserPrimaryKey>(User, { id: '1', }); expect(queryItem).toEqual({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#1', }, KeyConditionExpression: '#KY_CE_PK = :KY_CE_PK', TableName: 'test-table', }); }); test('transforms simple query item request with projection expression', () => { const queryItem = transformer.toDynamoQueryItem<User, UserPrimaryKey>( User, { id: '1', }, { select: ['status', 'name'], } ); expect(queryItem).toEqual({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#PE_name': 'name', '#PE_status': 'status', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#1', }, ScanIndexForward: true, KeyConditionExpression: '#KY_CE_PK = :KY_CE_PK', TableName: 'test-table', ProjectionExpression: '#PE_status, #PE_name', }); }); test('transforms simple count query item request', () => { const queryItem = transformer.toDynamoQueryItem<User, UserPrimaryKey>( User, { id: '1', }, { onlyCount: true, } ); expect(queryItem).toEqual({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#1', }, ScanIndexForward: true, KeyConditionExpression: '#KY_CE_PK = :KY_CE_PK', TableName: 'test-table', Select: 'COUNT', }); }); test('transforms query item request with filter input', () => { const queryItem = transformer.toDynamoQueryItem<User, UserPrimaryKey>( User, { id: '1', }, { where: { name: { EQ: 'suzan', }, }, } ); expect(queryItem).toEqual({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#FE_name': 'name', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#1', ':FE_name': 'suzan', }, ScanIndexForward: true, KeyConditionExpression: '#KY_CE_PK = :KY_CE_PK', FilterExpression: '#FE_name = :FE_name', TableName: 'test-table', }); }); test('transforms complex query item request', () => { const queryItem = transformer.toDynamoQueryItem<User, UserPrimaryKey>( User, { id: '1', }, { keyCondition: { BEGINS_WITH: 'USER#', }, limit: 12, orderBy: QUERY_ORDER.DESC, } ); expect(queryItem).toEqual({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#1', ':KY_CE_SK': 'USER#', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', Limit: 12, ScanIndexForward: false, TableName: 'test-table', }); }); test('transforms index based query item request', () => { const queryItem = transformer.toDynamoQueryItem<User, UserGSI1>( User, { status: '13', }, { queryIndex: 'GSI1', keyCondition: { BETWEEN: ['jay', 'joe'], }, orderBy: QUERY_ORDER.ASC, } ); expect(queryItem).toEqual({ TableName: 'test-table', ExpressionAttributeNames: { '#KY_CE_GSI1PK': 'GSI1PK', '#KY_CE_GSI1SK': 'GSI1SK', }, ExpressionAttributeValues: { ':KY_CE_GSI1PK': 'USER#STATUS#13', ':KY_CE_GSI1SK_end': 'joe', ':KY_CE_GSI1SK_start': 'jay', }, IndexName: 'GSI1', KeyConditionExpression: '(#KY_CE_GSI1PK = :KY_CE_GSI1PK) AND (#KY_CE_GSI1SK BETWEEN :KY_CE_GSI1SK_start AND :KY_CE_GSI1SK_end)', ScanIndexForward: true, }); }); test('errors when querying unknown index', () => { expect(() => transformer.toDynamoQueryItem( User, { status: '13', }, { queryIndex: 'LSI1', keyCondition: { EQ: 'joe', }, } ) ).toThrowError( 'Requested to query items from index "LSI1", but no such index exists on entity.' ); });
the_stack
import { List, Range } from 'immutable' import { GameType } from '../../../common/games/configuration' import { canAddObservers, canRemoveObservers, getLobbySlots, getLobbySlotsWithIndexes, getObserverTeam, hasObservers, humanSlotCount, isInObserverTeam, isTeamType, isUms, Lobby, MAX_OBSERVERS, openSlotCount, slotCount, takenSlotCount, Team, teamTakenSlotCount, } from '../../../common/lobbies' import { createClosed, createComputer, createControlledClosed, createControlledOpen, createHuman, createOpen, createUmsComputer, Slot, SlotType, } from '../../../common/lobbies/slot' import { MapForce, MapInfo } from '../../../common/maps' import { RaceChar } from '../../../common/races' import { SbUserId } from '../../../common/users/user-info' export function hasControlledOpens(gameType: GameType) { return gameType === GameType.TeamMelee || gameType === GameType.TeamFreeForAll } export function hasDynamicObsSlots(gameType: GameType) { return gameType === GameType.Melee } export function isTeamEmpty(team: Team) { // Team is deemed empty if it's only consisted of open and/or closed type of slots return team.slots.every(slot => slot.type === SlotType.Open || slot.type === SlotType.Closed) } export function getSlotsPerControlledTeam(gameSubType: number) { switch (gameSubType) { case 2: return [4, 4] case 3: return [3, 3, 2] case 4: return [2, 2, 2, 2] default: throw new Error('Unknown game sub-type: ' + gameSubType) } } export function getSlotsPerTeam( gameType: GameType, gameSubType: number, numSlots: number, umsForces: MapForce[], ) { switch (gameType) { case 'melee': case 'ffa': case 'oneVOne': return [numSlots] case 'topVBottom': return [gameSubType, numSlots - gameSubType] case 'teamMelee': case 'teamFfa': return getSlotsPerControlledTeam(gameSubType) case 'ums': return umsForces.map(f => f.players.length) default: throw new Error('Unknown game type: ' + gameType) } } export function numTeams(gameType: GameType, gameSubType: number, umsForces: MapForce[]) { switch (gameType) { case 'melee': case 'ffa': case 'oneVOne': return 1 case 'topVBottom': return 2 case 'teamMelee': case 'teamFfa': return gameSubType case 'ums': return umsForces.length default: throw new Error('Unknown game type: ' + gameType) } } export function getTeamNames(gameType: GameType, gameSubType: number, umsForces: MapForce[]) { switch (gameType) { case 'melee': case 'ffa': case 'oneVOne': return [] case 'topVBottom': return ['Top', 'Bottom'] case 'teamMelee': case 'teamFfa': const teamNames = [] for (let i = 1; i <= numTeams(gameType, gameSubType, umsForces); i++) { teamNames.push('Team ' + i) } return teamNames case 'ums': return umsForces.map(f => f.name) default: throw new Error('Invalid game type: ' + gameType) } } /** * Serializes a lobby to a summary-form in JSON, suitable for e.g. displaying a list of all the open * lobbies. */ export function toSummaryJson(lobby: Lobby) { return { name: lobby.name, map: lobby.map, gameType: lobby.gameType, gameSubType: lobby.gameSubType, host: { name: lobby.host.name, id: lobby.host.id }, openSlotCount: openSlotCount(lobby), } } /** * Finds the next available slot in the lobby (ie. `open` or `controlledOpen` slot type). * * @returns the `[teamIndex, slotIndex, slot]` tuple of the available slot if found. If there are no * available slots, it returns a [-1, -1, undefined] tuple. */ export function findAvailableSlot( lobby: Lobby, ): [teamIndex: number, slotIndex: number, slot: Slot | undefined] { const slotsCount = slotCount(lobby) const takenCount = takenSlotCount(lobby) if (slotsCount <= takenCount) { // There are no available slots in the regular teams. Check if there is an observer team and see // if there is available space there. if (hasObservers(lobby)) { const [teamIndex, observerTeam] = getObserverTeam(lobby) // Find the first available slot in the observer team const slotIndex = observerTeam!.slots.findIndex(slot => slot.type === SlotType.Open) return slotIndex !== -1 ? [teamIndex!, slotIndex, observerTeam!.slots.get(slotIndex)] : [-1, -1, undefined] } else { // There is no available slot in the lobby return [-1, -1, undefined] } } // To choose the team of the empty slot, first filter out any teams that are full, then sort the // remaining teams such that first team in the resulting list is the one with the least number of // players (ie. the highest number of available slots). Note that we're excluding the observer // team from this algorithm, because we've handled the observer team above. const availableTeam = lobby.teams .filterNot(team => team.isObserver) .map<[index: number, team: Team]>((team, teamIndex) => [teamIndex, team]) .filter(([, team]) => teamTakenSlotCount(team) < team.slots.size) .sort(([, a], [, b]) => { const availableCountA = a.slots.size - teamTakenSlotCount(a) const availableCountB = b.slots.size - teamTakenSlotCount(b) if (availableCountA > availableCountB) return -1 else if (availableCountA < availableCountB) return 1 else return 0 }) .first()! const [teamIndex, team] = availableTeam // After finding the available team, find the first available slot in that team and return its // team index, slot index, and slot const slotIndex = team.slots.findIndex( slot => slot.type === SlotType.Open || slot.type === SlotType.ControlledOpen, ) return [teamIndex, slotIndex, team.slots.get(slotIndex)] } function createInitialTeams( map: MapInfo, gameType: GameType, gameSubType: number, numSlots: number, ) { // When creating a lobby, we first create all the individual slots for the lobby, and then we // distribute each of the slots into their respective teams. This distribution of slots shouldn't // change at all during the lifetime of a lobby, except when creating/deleting observer slots, // which will be handled separately const slotsPerTeam = getSlotsPerTeam(gameType, gameSubType, numSlots, map.mapData.umsForces) let slots: List<Slot> if (!isUms(gameType)) { slots = Range(0, numSlots) .map(() => createOpen()) .toList() } else { slots = List( map.mapData.umsForces.flatMap(force => force.players.map(player => { const playerId = player.id const playerRace = player.race const race = playerRace !== 'any' ? playerRace : 'r' const hasForcedRace = playerRace !== 'any' return player.computer ? createUmsComputer(race, playerId, player.typeId) : createOpen(race, hasForcedRace, playerId) }), ), ) } const teamNames = getTeamNames(gameType, gameSubType, map.mapData.umsForces) let slotIndex = 0 return Range(0, numTeams(gameType, gameSubType, map.mapData.umsForces)) .map(teamIndex => { let teamSlots = slots.slice(slotIndex, slotIndex + slotsPerTeam[teamIndex]) let hiddenSlots slotIndex += slotsPerTeam[teamIndex] const teamName = teamNames[teamIndex] let teamId if (isUms(gameType)) { // Player type 5 means regular computer and 6 means human const isHiddenSlot = (player: Slot) => player.typeId !== 5 && player.typeId !== 6 teamId = map.mapData.umsForces[teamIndex].teamId hiddenSlots = teamSlots.filter(isHiddenSlot) teamSlots = teamSlots.filterNot(isHiddenSlot) } else { hiddenSlots = List<Slot>() teamId = isTeamType(gameType) ? teamIndex + 1 : teamIndex } return new Team({ name: teamName, teamId, slots: teamSlots, originalSize: teamSlots.size, hiddenSlots, }) }) .toList() } // TODO(tec27): This should be refactored to have less params but I'm not doing that while this // isn't in TS code /** Creates a new lobby, and an initial host player in the first slot. */ // eslint-disable-next-line max-params export function createLobby( name: string, map: MapInfo, gameType: GameType, gameSubType = 0, numSlots: number, hostName: string, hostUserId: SbUserId, hostRace: RaceChar = 'r', allowObservers: boolean, ) { let teams = createInitialTeams(map, gameType, gameSubType, numSlots) if (gameType === 'melee' && allowObservers) { const observerCount = Math.min( 8 - teams.reduce((sum, team) => sum + team.slots.size, 0), MAX_OBSERVERS, ) const observerSlots = Range(0, observerCount) .map(() => createClosed()) .toList() const observerTeam = new Team({ name: 'Observers', isObserver: true, slots: observerSlots, }) teams = teams.concat(List.of(observerTeam)) } const lobby = new Lobby({ name, map, gameType, gameSubType: +gameSubType, teams, host: new Slot(), }) let host const [hostTeamIndex, hostSlotIndex, hostSlot] = getLobbySlotsWithIndexes(lobby) .filter(([teamIndex, slotIndex, slot]) => slot.type === SlotType.Open) .min()! if (!isUms(gameType)) { host = createHuman(hostName, hostUserId, hostRace) } else { host = createHuman( hostName, hostUserId, hostSlot.race, hostSlot.hasForcedRace, hostSlot.playerId, ) } return addPlayer(lobby, hostTeamIndex, hostSlotIndex, host).set('host', host) } /** * A helper function that is used when a player joins an empty team in team melee/ffa game types. * Join can be triggered by player joining the lobby, adding a computer to the empty controlled team * or moving to the slot of an empty controlled team. Returns the updated lobby. */ function addPlayerAndControlledSlots( lobby: Lobby, teamIndex: number, slotIndex: number, player: Slot, ): Lobby { // The team which the new player is joining is empty (ie. it has only open and/or closed slots); // fill the whole team with either computer slots or controlled slots (leaving the slot of the new // player as is) const team = lobby.teams.get(teamIndex)! const slots = team.slots.map((currentSlot, currentSlotIndex) => { if (currentSlotIndex === slotIndex) return player if (player.type === SlotType.Computer) { return createComputer(player.race) } else { // If the human player is joining empty controlled team, check if the currentSlot is `closed`, // in which case create a `controlledClosed` type of slot in its place. This type of slot is // used in team melee/ffa game types where a closed slot still have its race set, which // affects race composition in the game, but no one can join that slot. return currentSlot.type === SlotType.Closed ? // TODO(2Pac): Set the races of these slots to 'r' instead? createControlledClosed(player.race, player.id) : createControlledOpen(player.race, player.id) } }) return lobby.setIn(['teams', teamIndex, 'slots'], slots) } export function addPlayer(lobby: Lobby, teamIndex: number, slotIndex: number, player: Slot): Lobby { const team = lobby.teams.get(teamIndex)! return hasControlledOpens(lobby.gameType) && isTeamEmpty(team) ? addPlayerAndControlledSlots(lobby, teamIndex, slotIndex, player) : lobby.setIn(['teams', teamIndex, 'slots', slotIndex], player) } /** Updates the race of a particular player, returning the updated lobby. */ export function setRace( lobby: Lobby, teamIndex: number, slotIndex: number, newRace: RaceChar, ): Lobby { const team = lobby.teams.get(teamIndex)! if ( hasControlledOpens(lobby.gameType) && team.slots.count(slot => slot.type === SlotType.Computer) > 0 ) { // BW doesn't support computer teams in team melee having different races. Change all races // of a computer team at once. // The exact limitation is with some but not all slots being random, we could allow multiple // non-random races but the AI won't be able to take advantage of it anyway. const slots = team.slots.map(slot => slot.set('race', newRace)) return lobby.setIn(['teams', teamIndex, 'slots'], slots) } else { return lobby.setIn(['teams', teamIndex, 'slots', slotIndex, 'race'], newRace) } } /** * A helper function that is used when a player leaves a team in team melee/ffa game types. Leave * can be triggered by player leaving the lobby, being kicked/banned, moving the slot etc. Returns * the updated lobby. */ function removePlayerAndControlledSlots(lobby: Lobby, teamIndex: number, playerIndex: number) { const team = lobby.teams.get(teamIndex)! const id = team.slots.get(playerIndex)!.id if ( team.slots.count(slot => slot.type === SlotType.Human) === 1 || team.slots.count(slot => slot.type === SlotType.Computer) > 0 ) { // The player that is leaving is alone in this team, so to remove them we replace the whole team // with either opened or closed slots. Same goes if we're removing a computer in team melee/ffa // lobby. const slots = team.slots.map(currentSlot => { return currentSlot.type === SlotType.ControlledClosed ? createClosed() : createOpen() }) return lobby.setIn(['teams', teamIndex, 'slots'], slots) } else { // The team which the player is leaving has other human players in it; find the new oldest human // player in the team and: // 1) create a new controlled open with controlledBy set to their ID // 2) update any controlled slots with controlledBy set to the leaver's ID to that ID const oldestInTeam = team.slots .filter(slot => slot.type === SlotType.Human && slot.id !== id) .sortBy(p => p.joinedAt) .first()! return lobby.updateIn(['teams', teamIndex, 'slots'], slotsUntyped => { const slots = slotsUntyped as List<Slot> return slots.map(slot => { if (slot.id === id) { return createControlledOpen(slot.race, oldestInTeam.id) } else if (slot.controlledBy === id) { return slot.set('controlledBy', oldestInTeam.id) } else { return slot } }) }) } } /** * Removes the player at the specified `teamIndex` and `slotIndex` from a lobby, returning the * updated lobby. If the lobby is closed (e.g. because it no longer has any human players), * `undefined` will be returned. Note that if the host is being removed, a new, suitable host will * be chosen. */ export function removePlayer( lobby: Lobby, teamIndex: number, slotIndex: number, toRemove: Slot, ): Lobby | undefined { if (!toRemove) { // nothing removed, e.g. player wasn't in the lobby return lobby } const openSlot = isUms(lobby.gameType) ? createOpen(toRemove.race, toRemove.hasForcedRace, toRemove.playerId) : createOpen() let updated = hasControlledOpens(lobby.gameType) ? removePlayerAndControlledSlots(lobby, teamIndex, slotIndex) : lobby.setIn(['teams', teamIndex, 'slots', slotIndex], openSlot) if (humanSlotCount(updated) < 1) { return undefined } if (lobby.host.id === toRemove.id) { // The player we removed was the host, find a new host (the "oldest" player in lobby) const newHost = getLobbySlots(updated) .filter(slot => slot.type === SlotType.Human || slot.type === SlotType.Observer) .sortBy(p => p.joinedAt) .first()! updated = updated.set('host', newHost) } return updated } /** * "Moves" one slot to another. For now it's only possible to move a `human` type slot to `open` or * `controlledOpen` type slot. Once the player is moved, there can be multiple side-effects: * * 1) in melee/ffa/tvb lobby, there are no side-effects * 2) in ums lobby, dest slot might have forced race, while the source slot did not or is different * 3) in team melee/ffa lobby * 3.1) the source and dest slots are in the same team, no side-effects * 3.2) the source and dest slots are in different teams * 3.2.1) the team of source slot will become empty after move * 3.2.2) the team of source slot will have remaining players * 3.2.2.1) the slot that moved was the "controller" of that team * 3.2.2.2) the slot that moved was not the "controller" of that team * 3.2.3) the team of dest slot was empty before the move * 3.2.4) the team of dest slot was not empty before the move */ export function movePlayerToSlot( lobby: Lobby, sourceTeamIndex: number, sourceSlotIndex: number, destTeamIndex: number, destSlotIndex: number, ): Lobby { let sourceSlot = lobby.teams.get(sourceTeamIndex)!.slots.get(sourceSlotIndex)! const destSlot = lobby.teams.get(destTeamIndex)!.slots.get(destSlotIndex)! if (!hasControlledOpens(lobby.gameType)) { let openSlot: Slot let updated = lobby if (!isUms(lobby.gameType)) { // 1) case - move the source slot to the destination slot and create an `open` slot at the // source slot openSlot = createOpen() } else { // 2) case - in UMS games, when player moves to a different slot, it's possible that the // destination slot has a forced race, while the source slot didn't. Also, `playerId` of the // moving player needs to change to the value of the destination slot. const orig = sourceSlot sourceSlot = sourceSlot.set('playerId', destSlot.playerId) sourceSlot = destSlot.hasForcedRace ? sourceSlot.set('race', destSlot.race).set('hasForcedRace', true) : sourceSlot.set('hasForcedRace', false) openSlot = createOpen(orig.race, orig.hasForcedRace, orig.playerId) if (orig === lobby.host) { // It was the host who moved to a different slot; update the lobby host record because it // now has a different `playerId` and potentially a different `race` updated = updated.set('host', sourceSlot) } } const hasObs = hasObservers(updated) if (hasObs && isInObserverTeam(updated, destSlot) && sourceSlot.type !== SlotType.Observer) { // If the destination slot is in the observer team, and the source slot is not already an // observer, update the player to an `observer` type slot sourceSlot = sourceSlot.set('type', SlotType.Observer) } if (hasObs && isInObserverTeam(updated, sourceSlot) && !isInObserverTeam(updated, destSlot)) { // If the source slot is in the observer team and the destination slot is not, change the // observer to a `human` type slot sourceSlot = sourceSlot.set('type', SlotType.Human) } return updated .setIn(['teams', destTeamIndex, 'slots', destSlotIndex], sourceSlot) .setIn(['teams', sourceTeamIndex, 'slots', sourceSlotIndex], openSlot) } else { // 3) case - in team melee/ffa lobbies, there can be quite a few side-effects; handle them below if (sourceTeamIndex === destTeamIndex) { // 3.1) case - move the source slot to the destination slot and create a `controlledOpen` slot // at the source return lobby .setIn(['teams', destTeamIndex, 'slots', destSlotIndex], sourceSlot) .setIn( ['teams', sourceTeamIndex, 'slots', sourceSlotIndex], createControlledOpen('r', destSlot.controlledBy!), ) } else { let updated: Lobby if (isTeamEmpty(lobby.teams.get(destTeamIndex)!)) { // 3.2.3) case - move the source slot (player) to the destination team and fill out the rest // of its slots properly updated = addPlayerAndControlledSlots(lobby, destTeamIndex, destSlotIndex, sourceSlot) } else { // 3.2.4) case - move the source slot to the destination slot updated = lobby.setIn(['teams', destTeamIndex, 'slots', destSlotIndex], sourceSlot) } // 3.2.1) and 3.2.2) case - clean up the controlled team which the player is leaving return removePlayerAndControlledSlots(updated, sourceTeamIndex, sourceSlotIndex) } } } /** * "Opens" a particular slot. This function is only possible to use to open a `closed` and * `controlledClosed` slot types. If you want to open a player slot, use the `removePlayer` function * instead, as that operation has side-effects, unlike this one. */ export function openSlot(lobby: Lobby, teamIndex: number, slotIndex: number): Lobby { const slotToOpen = lobby.teams.get(teamIndex)!.slots.get(slotIndex)! const openSlot = isUms(lobby.gameType) ? createOpen(slotToOpen.race, slotToOpen.hasForcedRace, slotToOpen.playerId) : createOpen() if (slotToOpen.type === SlotType.Closed) { return lobby.setIn(['teams', teamIndex, 'slots', slotIndex], openSlot) } else if (slotToOpen.type === SlotType.ControlledClosed) { return lobby.setIn( ['teams', teamIndex, 'slots', slotIndex], createControlledOpen(slotToOpen.race, slotToOpen.controlledBy!), ) } else { throw new Error('trying to open an invalid slot type: ' + slotToOpen.type) } } /** * "Closes" a particular slot. This function is only possible to use to close an `open` and * `controlledOpen` slot types. If you want to close a player slot, make sure to first remove the * player from the slot and then close their slot with this function. */ export function closeSlot(lobby: Lobby, teamIndex: number, slotIndex: number) { const slotToClose = lobby.teams.get(teamIndex)!.slots.get(slotIndex)! const closedSlot = isUms(lobby.gameType) ? createClosed(slotToClose.race, slotToClose.hasForcedRace, slotToClose.playerId) : createClosed() if (slotToClose.type === SlotType.Open) { return lobby.setIn(['teams', teamIndex, 'slots', slotIndex], closedSlot) } else if (slotToClose.type === SlotType.ControlledOpen) { return lobby.setIn( ['teams', teamIndex, 'slots', slotIndex], createControlledClosed(slotToClose.race, slotToClose.controlledBy!), ) } else { throw new Error('trying to close an invalid slot type: ' + slotToClose.type) } } /** Moves a regular slot to the observer team. */ export function makeObserver(lobby: Lobby, teamIndex: number, slotIndex: number): Lobby { if (!hasDynamicObsSlots(lobby.gameType)) { throw new Error('Lobby type not supported') } if (!canAddObservers(lobby)) { throw new Error('Cannot add more observers') } const team = lobby.teams.get(teamIndex)! if (team.isObserver) { throw new Error("Trying to make an observer from obs team's slot") } if (team.slots.size <= 1) { throw new Error('Cannot make observer from the last slot in team') } const slot = team.slots.get(slotIndex)! if ( slot.type !== SlotType.Open && slot.type !== SlotType.Closed && slot.type !== SlotType.Human ) { throw new Error('Trying to make observer from an invalid slot type: ' + slot.type) } const [obsTeamIndex, obsTeam] = getObserverTeam(lobby) // We create a new slot in obs team and move human to it, or just replicate the slot there, // and then delete the original slot. if (slot.type === SlotType.Human) { const newSlot = createOpen() lobby = lobby.setIn(['teams', obsTeamIndex, 'slots'], obsTeam!.slots.push(newSlot)) lobby = movePlayerToSlot(lobby, teamIndex, slotIndex, obsTeamIndex!, obsTeam!.slots.size) } else { const newSlot = slot.type === SlotType.Open ? createOpen() : createClosed() lobby = lobby.setIn(['teams', obsTeamIndex, 'slots'], obsTeam!.slots.push(newSlot)) } return lobby.deleteIn(['teams', teamIndex, 'slots', slotIndex]) } /** * Moves a slot from the observer team to players. The team that the slot gets moved to is the * smallest one with space for players. */ export function removeObserver(lobby: Lobby, slotIndex: number): Lobby { if (!hasDynamicObsSlots(lobby.gameType)) { throw new Error('Lobby type not supported') } if (!canRemoveObservers(lobby)) { throw new Error('Cannot remove more observers') } const [obsTeamIndex, obsTeam] = getObserverTeam(lobby) const slot = obsTeam!.slots.get(slotIndex)! const [newTeam, newTeamIndex] = lobby.teams .filter(team => !team.isObserver && team.slots.size !== team.originalSize) .map<[team: Team, index: number]>((team, index) => [team, index]) .minBy(([team]) => team.slots.size)! // We create a new slot in the team and move human to it, or just replicate the slot there, // and then delete the original slot. if (slot.type === SlotType.Observer) { const newSlot = createOpen() lobby = lobby.setIn(['teams', newTeamIndex, 'slots'], newTeam.slots.push(newSlot)) lobby = movePlayerToSlot(lobby, obsTeamIndex!, slotIndex, newTeamIndex, newTeam.slots.size) } else { const newSlot = slot.type === SlotType.Open ? createOpen() : createClosed() lobby = lobby.setIn(['teams', newTeamIndex, 'slots'], newTeam.slots.push(newSlot)) } return lobby.deleteIn(['teams', obsTeamIndex, 'slots', slotIndex]) }
the_stack
import set from 'lodash/set'; import cloneDeep from 'lodash/cloneDeep'; import '../../fixtures/window'; import { Project } from '../../../src/project/project'; import { Node } from '../../../src/document/node/node'; import { Designer } from '../../../src/designer/designer'; import formSchema from '../../fixtures/schema/form'; import { getIdsFromSchema, getNodeFromSchemaById } from '../../utils'; const mockCreateSettingEntry = jest.fn(); jest.mock('../../../src/designer/designer', () => { return { Designer: jest.fn().mockImplementation(() => { return { getComponentMeta() { return { getMetadata() { return { configure: { advanced: null } }; }, }; }, transformProps(props) { return props; }, createSettingEntry: mockCreateSettingEntry, postEvent() {}, }; }), }; }); let designer = null; beforeAll(() => { designer = new Designer({}); }); describe('schema 生成节点模型测试', () => { describe('block ❌ | component ❌ | slot ❌', () => { let project: Project; beforeEach(() => { project = new Project(designer, { componentsTree: [ formSchema, ], }); project.open(); }); it('读取普通属性,string | number | object', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); const expectedNodeCnt = ids.length; const formNode = currentDocument?.getNode('form'); /* props: { size: 'medium', labelAlign: 'top', autoValidate: true, scrollToFirstError: true, autoUnmount: true, behavior: 'NORMAL', dataSource: { type: 'variable', variable: 'state.formData', }, obj: { a: 1, b: false, c: 'string', }, __style__: {}, fieldId: 'form', fieldOptions: {}, }, id: 'form', condition: true, */ const sizeProp = formNode?.getProp('size'); const sizeProp2 = formNode?.getProps().getProp('size'); expect(sizeProp).toBe(sizeProp2); expect(sizeProp?.getAsString()).toBe('medium'); expect(sizeProp?.getValue()).toBe('medium'); const autoValidateProp = formNode?.getProp('autoValidate'); expect(autoValidateProp?.getValue()).toBe(true); const objProp = formNode?.getProp('obj'); expect(objProp?.getValue()).toEqual({ a: 1, b: false, c: 'string', }); const objAProp = formNode?.getProp('obj.a'); const objBProp = formNode?.getProp('obj.b'); const objCProp = formNode?.getProp('obj.c'); expect(objAProp?.getValue()).toBe(1); expect(objBProp?.getValue()).toBe(false); expect(objCProp?.getValue()).toBe('string'); const idProp = formNode?.getExtraProp('extraPropA'); expect(idProp?.getValue()).toBe('extraPropA'); }); it('修改普通属性,string | number | object,使用 Node 实例接口', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); const expectedNodeCnt = ids.length; const formNode = currentDocument?.getNode('form'); /* props: { size: 'medium', labelAlign: 'top', autoValidate: true, scrollToFirstError: true, autoUnmount: true, behavior: 'NORMAL', dataSource: { type: 'variable', variable: 'state.formData', }, obj: { a: 1, b: false, c: 'string', }, __style__: {}, fieldId: 'form', fieldOptions: {}, }, id: 'form', condition: true, */ formNode?.setPropValue('size', 'large'); const sizeProp = formNode?.getProp('size'); expect(sizeProp?.getAsString()).toBe('large'); expect(sizeProp?.getValue()).toBe('large'); formNode?.setPropValue('autoValidate', false); const autoValidateProp = formNode?.getProp('autoValidate'); expect(autoValidateProp?.getValue()).toBe(false); formNode?.setPropValue('obj', { a: 2, b: true, c: 'another string', }); const objProp = formNode?.getProp('obj'); expect(objProp?.getValue()).toEqual({ a: 2, b: true, c: 'another string', }); formNode?.setPropValue('obj.a', 3); formNode?.setPropValue('obj.b', false); formNode?.setPropValue('obj.c', 'string'); const objAProp = formNode?.getProp('obj.a'); const objBProp = formNode?.getProp('obj.b'); const objCProp = formNode?.getProp('obj.c'); expect(objAProp?.getValue()).toBe(3); expect(objBProp?.getValue()).toBe(false); expect(objCProp?.getValue()).toBe('string'); expect(objProp?.getValue()).toEqual({ a: 3, b: false, c: 'string', }); }); it('修改普通属性,string | number | object,使用 Props 实例接口', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); const expectedNodeCnt = ids.length; const formNode = currentDocument?.getNode('form'); /* props: { size: 'medium', labelAlign: 'top', autoValidate: true, scrollToFirstError: true, autoUnmount: true, behavior: 'NORMAL', dataSource: { type: 'variable', variable: 'state.formData', }, obj: { a: 1, b: false, c: 'string', }, __style__: {}, fieldId: 'form', fieldOptions: {}, }, id: 'form', condition: true, */ const props = formNode?.getProps(); props?.setPropValue('size', 'large'); const sizeProp = formNode?.getProp('size'); expect(sizeProp?.getAsString()).toBe('large'); expect(sizeProp?.getValue()).toBe('large'); props?.setPropValue('autoValidate', false); const autoValidateProp = formNode?.getProp('autoValidate'); expect(autoValidateProp?.getValue()).toBe(false); props?.setPropValue('obj', { a: 2, b: true, c: 'another string', }); const objProp = formNode?.getProp('obj'); expect(objProp?.getValue()).toEqual({ a: 2, b: true, c: 'another string', }); props?.setPropValue('obj.a', 3); props?.setPropValue('obj.b', false); props?.setPropValue('obj.c', 'string'); const objAProp = formNode?.getProp('obj.a'); const objBProp = formNode?.getProp('obj.b'); const objCProp = formNode?.getProp('obj.c'); expect(objAProp?.getValue()).toBe(3); expect(objBProp?.getValue()).toBe(false); expect(objCProp?.getValue()).toBe('string'); expect(objProp?.getValue()).toEqual({ a: 3, b: false, c: 'string', }); }); it('修改普通属性,string | number | object,使用 Prop 实例接口', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); const expectedNodeCnt = ids.length; const formNode = currentDocument?.getNode('form'); /* props: { size: 'medium', labelAlign: 'top', autoValidate: true, scrollToFirstError: true, autoUnmount: true, behavior: 'NORMAL', dataSource: { type: 'variable', variable: 'state.formData', }, obj: { a: 1, b: false, c: 'string', }, __style__: {}, fieldId: 'form', fieldOptions: {}, }, id: 'form', condition: true, */ const sizeProp = formNode?.getProp('size'); sizeProp?.setValue('large'); expect(sizeProp?.getAsString()).toBe('large'); expect(sizeProp?.getValue()).toBe('large'); const autoValidateProp = formNode?.getProp('autoValidate'); autoValidateProp?.setValue(false); expect(autoValidateProp?.getValue()).toBe(false); const objProp = formNode?.getProp('obj'); objProp?.setValue({ a: 2, b: true, c: 'another string', }); expect(objProp?.getValue()).toEqual({ a: 2, b: true, c: 'another string', }); const objAProp = formNode?.getProp('obj.a'); const objBProp = formNode?.getProp('obj.b'); const objCProp = formNode?.getProp('obj.c'); objAProp?.setValue(3); objBProp?.setValue(false); objCProp?.setValue('string'); expect(objAProp?.getValue()).toBe(3); expect(objBProp?.getValue()).toBe(false); expect(objCProp?.getValue()).toBe('string'); expect(objProp?.getValue()).toEqual({ a: 3, b: false, c: 'string', }); }); }); describe('block ❌ | component ❌ | slot ✅', () => { let project: Project; beforeEach(() => { project = new Project(designer, { componentsTree: [ formSchema, ], }); project.open(); }); it('修改 slot 属性,初始存在 slot 属性名,正常生成节点模型', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); const expectedNodeCnt = ids.length; const formNode = currentDocument?.getNode('form'); formNode?.setPropValue('slotA', { type: 'JSSlot', value: [{ componentName: 'TextInput1', props: { txt: 'haha', num: 1, bool: true, }, }, { componentName: 'TextInput2', props: { txt: 'heihei', num: 2, bool: false, }, }], }); expect(nodesMap.size).toBe(ids.length + 3); expect(formNode?.slots).toHaveLength(1); expect(formNode?.slots[0].children).toHaveLength(2); const firstChildNode = formNode?.slots[0].children?.get(0); const secondChildNode = formNode?.slots[0].children?.get(1); expect(firstChildNode?.componentName).toBe('TextInput1'); expect(firstChildNode?.getPropValue('txt')).toBe('haha'); expect(firstChildNode?.getPropValue('num')).toBe(1); expect(firstChildNode?.getPropValue('bool')).toBe(true); expect(secondChildNode?.componentName).toBe('TextInput2'); expect(secondChildNode?.getPropValue('txt')).toBe('heihei'); expect(secondChildNode?.getPropValue('num')).toBe(2); expect(secondChildNode?.getPropValue('bool')).toBe(false); }); it('修改 slot 属性,初始存在 slot 属性名,关闭 slot', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); const expectedNodeCnt = ids.length; const formNode = currentDocument?.getNode('form'); formNode?.setPropValue('slotA', { type: 'JSSlot', value: [{ componentName: 'TextInput1', props: { txt: 'haha', num: 1, bool: true, }, }, { componentName: 'TextInput2', props: { txt: 'heihei', num: 2, bool: false, }, }], }); expect(nodesMap.size).toBe(ids.length + 3); expect(formNode?.slots).toHaveLength(1); formNode?.setPropValue('slotA', ''); expect(nodesMap.size).toBe(ids.length); expect(formNode?.slots).toHaveLength(0); }); it('修改 slot 属性,初始存在 slot 属性名,同名覆盖 slot', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); const expectedNodeCnt = ids.length; const formNode = currentDocument?.getNode('form'); formNode?.setPropValue('slotA', { type: 'JSSlot', name: 'slotA', value: [{ componentName: 'TextInput1', props: { txt: 'haha', num: 1, bool: true, }, }, { componentName: 'TextInput2', props: { txt: 'heihei', num: 2, bool: false, }, }], }); expect(nodesMap.size).toBe(ids.length + 3); expect(formNode?.slots).toHaveLength(1); expect(formNode?.slots[0].children).toHaveLength(2); let firstChildNode = formNode?.slots[0].children?.get(0); expect(firstChildNode?.componentName).toBe('TextInput1'); expect(firstChildNode?.getPropValue('txt')).toBe('haha'); expect(firstChildNode?.getPropValue('num')).toBe(1); expect(firstChildNode?.getPropValue('bool')).toBe(true); formNode?.setPropValue('slotA', { type: 'JSSlot', name: 'slotA', value: [{ componentName: 'TextInput3', props: { txt: 'xixi', num: 3, bool: false, }, }], }); expect(nodesMap.size).toBe(ids.length + 2); expect(formNode?.slots).toHaveLength(1); expect(formNode?.slots[0].children).toHaveLength(1); firstChildNode = formNode?.slots[0].children?.get(0); expect(firstChildNode?.componentName).toBe('TextInput3'); expect(firstChildNode?.getPropValue('txt')).toBe('xixi'); expect(firstChildNode?.getPropValue('num')).toBe(3); expect(firstChildNode?.getPropValue('bool')).toBe(false); }); }); });
the_stack
const path = require('path') const fs = require('fs') const recast = require('recast') /** * Re-using few private methods of react-docgen to avoid code duplication */ const isRequiredPropType = require('react-docgen/dist/utils/isRequiredPropType') .default const setPropDescription = require('react-docgen/dist/utils/setPropDescription') .default let babylon: any try { const buildParser = require('react-docgen/dist/babelParser').default babylon = buildParser() } catch (e) { /** DOCZ: special error message as people often encounter errors here because they misconfigure or lack a babel plugin */ console.error('Error while initializing babel in docz: ', e) /** DOCZ: disabling this require because it no longer exists */ throw new Error(e) // babylon = require('react-docgen/dist/babylon').default } const utils = require('react-docgen').utils const types = recast.types.namedTypes const HOP = Object.prototype.hasOwnProperty const createObject = Object.create function isPropTypesExpression(path: string) { const moduleName = utils.resolveToModule(path) if (moduleName) { return ( utils.isReactModuleName(moduleName) || moduleName === 'ReactPropTypes' ) } return false } /** * Amends the documentation object with propTypes information. * @method amendPropTypes * @param {Object} documentation documentation object * @param {Object} path node path reference of propTypes property */ function amendPropTypes(documentation: any, path: any) { if (!types.ObjectExpression.check(path.node)) { return } path.get('properties').each((propertyPath: any) => { let propDescriptor, valuePath, type, resolvedValuePath const nodeType = propertyPath.node.type if (nodeType === types.Property.name) { propDescriptor = documentation.getPropDescriptor( utils.getPropertyName(propertyPath) ) valuePath = propertyPath.get('value') type = isPropTypesExpression(valuePath) ? utils.getPropType(valuePath) : { name: 'custom', raw: utils.printValue(valuePath), } if (type) { propDescriptor.type = type propDescriptor.required = type.name !== 'custom' && isRequiredPropType(valuePath) } } else if (nodeType === types.SpreadProperty.name) { resolvedValuePath = utils.resolveToValue(propertyPath.get('argument')) // normal object literal if (resolvedValuePath.node.type === types.ObjectExpression.name) { amendPropTypes(documentation, resolvedValuePath) } } if (types.Property.check(propertyPath.node)) { setPropDescription(documentation, propertyPath) } }) } /** * Accepts absolute path of a source file and returns the file source as string. * @method getSrc * @param {String} filePath File path of the component * @return {String} Source code of the given file if file exist else returns empty */ function getSrc(filePath: string) { let src if (fs.existsSync(filePath)) { src = fs.readFileSync(filePath, 'utf-8') } return src } function getAST(src: string) { return recast.parse(src, { source: 'module', esprima: babylon, }) } /** * Resolves propTypes source file path relative to current component, * which resolves only file extension of type .js or .jsx * * @method resolveFilePath * @param {String} componentPath Relative file path of the component * @param {String} importedFilePath Relative file path of a dependent component * @return {String} Resolved file path if file exist else null */ function resolveFilePath(componentPath: string, importedFilePath: string) { const regEx = /\.(js|jsx)$/ let srcPath = path.resolve(path.dirname(componentPath), importedFilePath) if (regEx.exec(srcPath)) { return srcPath } else { srcPath += fs.existsSync(`${srcPath}.js`) ? '.js' : '.jsx' return srcPath } } /** * Method which returns actual values from the AST node of type specifiers. * * @method getSpecifiersOfNode */ function getSpecifiersOfNode(specifiers: any) { const specifier: string[] = [] specifiers.forEach((node: any) => { specifier.push(node.local.name) }) return specifier } /** * Filters the list of identifier node values or node paths from a given AST. * * @method getIdentifiers * @param {Object} ast Root AST node of a component * @return {Object} Which holds identifier relative file path as `key` and identifier name as `value` */ function getIdentifiers(ast: any) { const identifiers = createObject(null) recast.visit(ast, { visitVariableDeclarator(path: any) { const node = path.node const nodeType = node.init.type if (nodeType === types.Identifier.name) { if (identifiers[node.init.name]) { identifiers[node.init.name].push(node.init.name) } else { identifiers[node.init.name] = [node.init.name] } } else if (nodeType === types.Literal.name) { if (identifiers[node.id.name]) { identifiers[node.id.name].push(node.init.value) } else { identifiers[node.id.name] = [node.init.value] } } else if (nodeType === types.ArrayExpression.name) { if (identifiers[node.id.name]) { identifiers[node.id.name].push(node.init.elements) } else { identifiers[node.id.name] = node.init.elements } } else if (nodeType === types.ObjectExpression.name) { if (identifiers[node.id.name]) { identifiers[node.id.name].push({ path, value: node.init.properties, }) } else { identifiers[node.id.name] = { path, value: node.init.properties, } } } this.traverse(path) }, }) return identifiers } /** * Traverse through given AST and filters named and default export declarations. * * @method getExports * @param {Object} ast Root AST node of a component * @return {Array} which holds list of named identifiers */ function getExports(ast: any) { const exports: any = [] recast.visit(ast, { visitExportNamedDeclaration(path: any) { const node = path.node const specifiers = getSpecifiersOfNode(node.specifiers) const declarations = Object.keys(getIdentifiers(ast)) exports.push(...new Set(specifiers.concat(declarations))) this.traverse(path) }, visitExportDefaultDeclaration(path: any) { const node = path.node if (node.declaration.type === types.Identifier.name) { exports.push(node.declaration.name) } /* Commenting it for now, this might needed for further enhancements. else if (nodeType === types.Literal.name) { varDeclarators.push(node.init.value); } else if (nodeType === types.ArrayExpression.name) { computedPropNodes[node.id.name] = node.init.elements; }*/ this.traverse(path) }, }) return exports } /** * Method to list all specifiers of es6 `import` of a given file(AST) * * @method getImports * @param {Object} ast Root AST node of a component * @return {Object/Boolean} if Object: Holds import module name or file path as `key` * and identifier as `value`, else return false */ function getImports(ast: any) { const specifiers = createObject(null) recast.visit(ast, { visitImportDeclaration: (path: any) => { const name = path.node.source.value const specifier = getSpecifiersOfNode(path.node.specifiers) if (!specifiers[name]) { specifiers[name] = specifier } else { specifiers[name].push(...specifier) } return false }, }) return specifiers } /** * Method to resolve all dependent values(computed values, which are from external files). * * @method resolveImportedDependencies * @param {Object} ast Root AST node of the component * @param {Object} srcFilePath Absolute path of a dependent file * @return {Object} Holds export identifier as `key` and respective AST node path as value */ function resolveImportedDependencies(ast: any, srcFilePath: any) { const filteredItems = createObject(null) const importSpecifiers = getImports(ast) let identifiers, resolvedNodes if (importSpecifiers && Object.keys(importSpecifiers).length) { resolvedNodes = resolveDependencies(importSpecifiers, srcFilePath) } const exportSpecifiers = getExports(ast) if (exportSpecifiers && exportSpecifiers.length) { identifiers = getIdentifiers(ast) } if (resolvedNodes) { Object.assign(identifiers, ...resolvedNodes) } for (const identifier in identifiers) { if ( HOP.call(identifiers, identifier) && exportSpecifiers.indexOf(identifier) > -1 ) { filteredItems[identifier] = identifiers[identifier] } } return filteredItems } /** * Method to resolve all the external dependencies of the component propTypes * * @method resolveDependencies * @param {Array} filePaths List of files to resolve * @param {String} componentPath Absolute path of the component in case `propTypes` are declared in a component file or * absolute path to the file where `propTypes` is declared. */ function resolveDependencies(filePaths: string[], componentPath: string) { const importedNodes = [] for (const importedFilePath in filePaths) { if (HOP.call(filePaths, importedFilePath)) { const srcPath = resolveFilePath(componentPath, importedFilePath) if (!srcPath) { return } const src = getSrc(srcPath) if (src) { const ast = getAST(src) importedNodes.push(resolveImportedDependencies(ast, srcPath)) } } } return importedNodes } /** * Method to filter computed props(which are declared out side of the component and used in propTypes object). * * @method filterSpecifiers * @param {Object} specifiers List which holds all the values of external dependencies * @return {Object} computedPropNames List which holds all the computed values from `propTypes` property */ function filterSpecifiers(specifiers: any, computedPropNames: any) { const filteredSpecifiers = createObject(null) for (const cp in computedPropNames) { if (HOP.call(computedPropNames, cp)) { for (const sp in specifiers) { if (HOP.call(specifiers, sp) && specifiers[sp].indexOf(cp) > -1) { if (filteredSpecifiers[sp]) { filteredSpecifiers[sp].push(cp) } else { filteredSpecifiers[sp] = [cp] } } } } } return filteredSpecifiers } /** * Method to parse and get computed nodes from a document object * * @method getComputedPropValuesFromDoc * @param {Object} doc react-docgen document object * @return {Object/Boolean} Object with computed property identifer as `key` and AST node path as `value`, * If document object have any computed properties else return false. */ function getComputedPropValuesFromDoc(doc: any) { let flag const computedProps = createObject(null) const props = doc.toObject().props flag = false if (props) { for (const prop in props) { if (HOP.call(props, prop)) { const o = props[prop] if (o.type && o.type.name === 'enum' && o.type.computed) { flag = true computedProps[o.type.value] = o } } } return flag ? computedProps : false } else { return false } } /** * Method to update the document object computed values with actual values to generate doc for external dependent values. * * @method amendDocs * @param {Object} doc react-docgen document object * @param {Object} path AST node path of component `propTypes` * @param {Object} props list of actual values of computed properties */ function amendDocs(doc: any, path: any, props: any) { const propsToPatch = path.get('properties') function getComputedPropVal(name: string) { for (let i = 0; i < props.length; i++) { if (props[i][name]) { return props[i][name] } } } propsToPatch.each((propertyPath: string) => { const propDescriptor = doc.getPropDescriptor( utils.getPropertyName(propertyPath) ) if (propDescriptor.type.name === 'enum' && propDescriptor.type.computed) { const oldVal = propDescriptor.type.value const newVal = getComputedPropVal(propDescriptor.type.value) || oldVal propDescriptor.type.value = newVal propDescriptor.type.computed = false } }) } /** * Initializer of react-docgen custom handler. * * @method externalProptypesHandler * @param {String} componentPath Absolute path of the react component */ function externalProptypesHandler(componentPath: string) { return (doc: any, path: any) => { const root = path.scope.getGlobalScope().node let propTypesPath, propTypesFilePath, propTypesAST propTypesPath = utils.getMemberValuePath(path, 'propTypes') propTypesAST = root propTypesFilePath = componentPath if (!propTypesPath) { return } const propsNameIdentifier = propTypesPath.node.name propTypesPath = utils.resolveToValue(propTypesPath) if (!propTypesPath) { return } if (!types.ObjectExpression.check(propTypesPath.node)) { //First resolve dependencies against component path propTypesFilePath = resolveFilePath( componentPath, propTypesPath.node.source.value ) const propTypesSrc = getSrc(propTypesFilePath) propTypesAST = getAST(propTypesSrc) const importedPropTypes = getIdentifiers(propTypesAST)[ propsNameIdentifier ] if (!importedPropTypes) { return } propTypesPath = utils.resolveToValue(importedPropTypes.path) //updating doc object with external props amendPropTypes(doc, propTypesPath) } const computedPropNames = getComputedPropValuesFromDoc(doc) if (!computedPropNames) { return } const importSpecifiers = getImports(propTypesAST) if (!importSpecifiers) { return } const filteredProps = filterSpecifiers(importSpecifiers, computedPropNames) if (!Object.keys(filteredProps).length) { return } const resolvedImports = resolveDependencies( filteredProps, propTypesFilePath ) if (resolvedImports && !resolvedImports.length) { return } amendDocs(doc, propTypesPath, resolvedImports) } } export default externalProptypesHandler
the_stack
import {each, map, isFunction, createHashMap, noop, HashMap, assert} from 'zrender/src/core/util'; import { createTask, Task, TaskContext, TaskProgressCallback, TaskProgressParams, TaskPlanCallbackReturn, PerformArgs } from './task'; import {getUID} from '../util/component'; import GlobalModel from '../model/Global'; import ExtensionAPI from './ExtensionAPI'; import {normalizeToArray} from '../util/model'; import { StageHandlerInternal, StageHandlerOverallReset, StageHandler, Payload, StageHandlerReset, StageHandlerPlan, StageHandlerProgressExecutor, SeriesLargeOptionMixin, SeriesOption } from '../util/types'; import { EChartsType } from './echarts'; import SeriesModel from '../model/Series'; import ChartView from '../view/Chart'; import SeriesData from '../data/SeriesData'; export type GeneralTask = Task<TaskContext>; export type SeriesTask = Task<SeriesTaskContext>; export type OverallTask = Task<OverallTaskContext> & { agentStubMap?: HashMap<StubTask> }; export type StubTask = Task<StubTaskContext> & { agent?: OverallTask; }; export type Pipeline = { id: string head: GeneralTask, tail: GeneralTask, threshold: number, progressiveEnabled: boolean, blockIndex: number, step: number, count: number, currentTask?: GeneralTask, context?: PipelineContext }; export type PipelineContext = { progressiveRender: boolean, modDataCount: number, large: boolean }; type TaskRecord = { // key: seriesUID seriesTaskMap?: HashMap<SeriesTask>, overallTask?: OverallTask }; type PerformStageTaskOpt = { block?: boolean, setDirty?: boolean, visualType?: StageHandlerInternal['visualType'], dirtyMap?: HashMap<any> }; export interface SeriesTaskContext extends TaskContext { model?: SeriesModel; data?: SeriesData; view?: ChartView; ecModel?: GlobalModel; api?: ExtensionAPI; useClearVisual?: boolean; plan?: StageHandlerPlan; reset?: StageHandlerReset; scheduler?: Scheduler; payload?: Payload; resetDefines?: StageHandlerProgressExecutor[] } interface OverallTaskContext extends TaskContext { ecModel: GlobalModel; api: ExtensionAPI; overallReset: StageHandlerOverallReset; scheduler: Scheduler; payload?: Payload; } interface StubTaskContext extends TaskContext { model: SeriesModel; overallProgress: boolean; }; class Scheduler { readonly ecInstance: EChartsType; readonly api: ExtensionAPI; // Shared with echarts.js, should only be modified by // this file and echarts.js unfinished: boolean; private _dataProcessorHandlers: StageHandlerInternal[]; private _visualHandlers: StageHandlerInternal[]; private _allHandlers: StageHandlerInternal[]; // key: handlerUID private _stageTaskMap: HashMap<TaskRecord> = createHashMap<TaskRecord>(); // key: pipelineId private _pipelineMap: HashMap<Pipeline>; constructor( ecInstance: EChartsType, api: ExtensionAPI, dataProcessorHandlers: StageHandlerInternal[], visualHandlers: StageHandlerInternal[] ) { this.ecInstance = ecInstance; this.api = api; // Fix current processors in case that in some rear cases that // processors might be registered after echarts instance created. // Register processors incrementally for a echarts instance is // not supported by this stream architecture. dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice(); visualHandlers = this._visualHandlers = visualHandlers.slice(); this._allHandlers = dataProcessorHandlers.concat(visualHandlers); } restoreData(ecModel: GlobalModel, payload: Payload): void { // TODO: Only restore needed series and components, but not all components. // Currently `restoreData` of all of the series and component will be called. // But some independent components like `title`, `legend`, `graphic`, `toolbox`, // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`, // and some components like coordinate system, axes, dataZoom, visualMap only // need their target series refresh. // (1) If we are implementing this feature some day, we should consider these cases: // if a data processor depends on a component (e.g., dataZoomProcessor depends // on the settings of `dataZoom`), it should be re-performed if the component // is modified by `setOption`. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`, // it should be re-performed when the result array of `getTargetSeries` changed. // We use `dependencies` to cover these issues. // (3) How to update target series when coordinate system related components modified. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty, // and this case all of the tasks will be set as dirty. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also // depends on all of the series. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure // that the overall task is set as dirty and to be performed, otherwise it probably cause // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it // probably cause state chaos (consider `dataZoomProcessor`). this._stageTaskMap.each(function (taskRecord) { const overallTask = taskRecord.overallTask; overallTask && overallTask.dirty(); }); } // If seriesModel provided, incremental threshold is check by series data. getPerformArgs(task: GeneralTask, isBlock?: boolean): { step: number, modBy: number, modDataCount: number } { // For overall task if (!task.__pipeline) { return; } const pipeline = this._pipelineMap.get(task.__pipeline.id); const pCtx = pipeline.context; const incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex; const step = incremental ? pipeline.step : null; const modDataCount = pCtx && pCtx.modDataCount; const modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null; return {step: step, modBy: modBy, modDataCount: modDataCount}; } getPipeline(pipelineId: string) { return this._pipelineMap.get(pipelineId); } /** * Current, progressive rendering starts from visual and layout. * Always detect render mode in the same stage, avoiding that incorrect * detection caused by data filtering. * Caution: * `updateStreamModes` use `seriesModel.getData()`. */ updateStreamModes(seriesModel: SeriesModel<SeriesOption & SeriesLargeOptionMixin>, view: ChartView): void { const pipeline = this._pipelineMap.get(seriesModel.uid); const data = seriesModel.getData(); const dataLen = data.count(); // `progressiveRender` means that can render progressively in each // animation frame. Note that some types of series do not provide // `view.incrementalPrepareRender` but support `chart.appendData`. We // use the term `incremental` but not `progressive` to describe the // case that `chart.appendData`. const progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold; const large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint. // see `test/candlestick-large3.html` const modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null; seriesModel.pipelineContext = pipeline.context = { progressiveRender: progressiveRender, modDataCount: modDataCount, large: large }; } restorePipelines(ecModel: GlobalModel): void { const scheduler = this; const pipelineMap = scheduler._pipelineMap = createHashMap(); ecModel.eachSeries(function (seriesModel) { const progressive = seriesModel.getProgressive(); const pipelineId = seriesModel.uid; pipelineMap.set(pipelineId, { id: pipelineId, head: null, tail: null, threshold: seriesModel.getProgressiveThreshold(), progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()), blockIndex: -1, step: Math.round(progressive || 700), count: 0 }); scheduler._pipe(seriesModel, seriesModel.dataTask); }); } prepareStageTasks(): void { const stageTaskMap = this._stageTaskMap; const ecModel = this.api.getModel(); const api = this.api; each(this._allHandlers, function (handler) { const record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, {}); let errMsg = ''; if (__DEV__) { // Currently do not need to support to sepecify them both. errMsg = '"reset" and "overallReset" must not be both specified.'; } assert(!(handler.reset && handler.overallReset), errMsg); handler.reset && this._createSeriesStageTask(handler, record, ecModel, api); handler.overallReset && this._createOverallStageTask(handler, record, ecModel, api); }, this); } prepareView(view: ChartView, model: SeriesModel, ecModel: GlobalModel, api: ExtensionAPI): void { const renderTask = view.renderTask; const context = renderTask.context; context.model = model; context.ecModel = ecModel; context.api = api; renderTask.__block = !view.incrementalPrepareRender; this._pipe(model, renderTask); } performDataProcessorTasks(ecModel: GlobalModel, payload?: Payload): void { // If we do not use `block` here, it should be considered when to update modes. this._performStageTasks(this._dataProcessorHandlers, ecModel, payload, {block: true}); } performVisualTasks( ecModel: GlobalModel, payload?: Payload, opt?: PerformStageTaskOpt ): void { this._performStageTasks(this._visualHandlers, ecModel, payload, opt); } private _performStageTasks( stageHandlers: StageHandlerInternal[], ecModel: GlobalModel, payload: Payload, opt?: PerformStageTaskOpt ): void { opt = opt || {}; let unfinished: boolean = false; const scheduler = this; each(stageHandlers, function (stageHandler, idx) { if (opt.visualType && opt.visualType !== stageHandler.visualType) { return; } const stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid); const seriesTaskMap = stageHandlerRecord.seriesTaskMap; const overallTask = stageHandlerRecord.overallTask; if (overallTask) { let overallNeedDirty; const agentStubMap = overallTask.agentStubMap; agentStubMap.each(function (stub) { if (needSetDirty(opt, stub)) { stub.dirty(); overallNeedDirty = true; } }); overallNeedDirty && overallTask.dirty(); scheduler.updatePayload(overallTask, payload); const performArgs = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty, // then execute the overall task. And stub will call seriesModel.setData, // which ensures that in the overallTask seriesModel.getData() will not // return incorrect data. agentStubMap.each(function (stub) { stub.perform(performArgs); }); if (overallTask.perform(performArgs)) { unfinished = true; } } else if (seriesTaskMap) { seriesTaskMap.each(function (task, pipelineId) { if (needSetDirty(opt, task)) { task.dirty(); } const performArgs: PerformArgs = scheduler.getPerformArgs(task, opt.block); // FIXME // if intending to decalare `performRawSeries` in handlers, only // stream-independent (specifically, data item independent) operations can be // performed. Because is a series is filtered, most of the tasks will not // be performed. A stream-dependent operation probably cause wrong biz logic. // Perhaps we should not provide a separate callback for this case instead // of providing the config `performRawSeries`. The stream-dependent operaions // and stream-independent operations should better not be mixed. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model); scheduler.updatePayload(task, payload); if (task.perform(performArgs)) { unfinished = true; } }); } }); function needSetDirty(opt: PerformStageTaskOpt, task: GeneralTask): boolean { return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id)); } this.unfinished = unfinished || this.unfinished; } performSeriesTasks(ecModel: GlobalModel): void { let unfinished: boolean; ecModel.eachSeries(function (seriesModel) { // Progress to the end for dataInit and dataRestore. unfinished = seriesModel.dataTask.perform() || unfinished; }); this.unfinished = unfinished || this.unfinished; } plan(): void { // Travel pipelines, check block. this._pipelineMap.each(function (pipeline) { let task = pipeline.tail; do { if (task.__block) { pipeline.blockIndex = task.__idxInPipeline; break; } task = task.getUpstream(); } while (task); }); } updatePayload( task: Task<SeriesTaskContext | OverallTaskContext>, payload: Payload | 'remain' ): void { payload !== 'remain' && (task.context.payload = payload); } private _createSeriesStageTask( stageHandler: StageHandlerInternal, stageHandlerRecord: TaskRecord, ecModel: GlobalModel, api: ExtensionAPI ): void { const scheduler = this; const oldSeriesTaskMap = stageHandlerRecord.seriesTaskMap; // The count of stages are totally about only several dozen, so // do not need to reuse the map. const newSeriesTaskMap = stageHandlerRecord.seriesTaskMap = createHashMap(); const seriesType = stageHandler.seriesType; const getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily, // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`, // it works but it may cause other irrelevant charts blocked. if (stageHandler.createOnAllSeries) { ecModel.eachRawSeries(create); } else if (seriesType) { ecModel.eachRawSeriesByType(seriesType, create); } else if (getTargetSeries) { getTargetSeries(ecModel, api).each(create); } function create(seriesModel: SeriesModel): void { const pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once. // Reuse original task instance. const task = newSeriesTaskMap.set( pipelineId, oldSeriesTaskMap && oldSeriesTaskMap.get(pipelineId) || createTask<SeriesTaskContext>({ plan: seriesTaskPlan, reset: seriesTaskReset, count: seriesTaskCount }) ); task.context = { model: seriesModel, ecModel: ecModel, api: api, // PENDING: `useClearVisual` not used? useClearVisual: stageHandler.isVisual && !stageHandler.isLayout, plan: stageHandler.plan, reset: stageHandler.reset, scheduler: scheduler }; scheduler._pipe(seriesModel, task); } } private _createOverallStageTask( stageHandler: StageHandlerInternal, stageHandlerRecord: TaskRecord, ecModel: GlobalModel, api: ExtensionAPI ): void { const scheduler = this; const overallTask: OverallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage. || createTask<OverallTaskContext>({reset: overallTaskReset}); overallTask.context = { ecModel: ecModel, api: api, overallReset: stageHandler.overallReset, scheduler: scheduler }; const oldAgentStubMap = overallTask.agentStubMap; // The count of stages are totally about only several dozen, so // do not need to reuse the map. const newAgentStubMap = overallTask.agentStubMap = createHashMap<StubTask>(); const seriesType = stageHandler.seriesType; const getTargetSeries = stageHandler.getTargetSeries; let overallProgress = true; let shouldOverallTaskDirty = false; // FIXME:TS never used, so comment it // let modifyOutputEnd = stageHandler.modifyOutputEnd; // An overall task with seriesType detected or has `getTargetSeries`, we add // stub in each pipelines, it will set the overall task dirty when the pipeline // progress. Moreover, to avoid call the overall task each frame (too frequent), // we set the pipeline block. let errMsg = ''; if (__DEV__) { errMsg = '"createOnAllSeries" do not supported for "overallReset", ' + 'becuase it will block all streams.'; } assert(!stageHandler.createOnAllSeries, errMsg); if (seriesType) { ecModel.eachRawSeriesByType(seriesType, createStub); } else if (getTargetSeries) { getTargetSeries(ecModel, api).each(createStub); } // Otherwise, (usually it is legancy case), the overall task will only be // executed when upstream dirty. Otherwise the progressive rendering of all // pipelines will be disabled unexpectedly. But it still needs stubs to receive // dirty info from upsteam. else { overallProgress = false; each(ecModel.getSeries(), createStub); } function createStub(seriesModel: SeriesModel): void { const pipelineId = seriesModel.uid; const stub = newAgentStubMap.set( pipelineId, oldAgentStubMap && oldAgentStubMap.get(pipelineId) || ( // When the result of `getTargetSeries` changed, the overallTask // should be set as dirty and re-performed. shouldOverallTaskDirty = true, createTask<StubTaskContext>( {reset: stubReset, onDirty: stubOnDirty} ) ) ); stub.context = { model: seriesModel, overallProgress: overallProgress // FIXME:TS never used, so comment it // modifyOutputEnd: modifyOutputEnd }; stub.agent = overallTask; stub.__block = overallProgress; scheduler._pipe(seriesModel, stub); } if (shouldOverallTaskDirty) { overallTask.dirty(); } } private _pipe(seriesModel: SeriesModel, task: GeneralTask) { const pipelineId = seriesModel.uid; const pipeline = this._pipelineMap.get(pipelineId); !pipeline.head && (pipeline.head = task); pipeline.tail && pipeline.tail.pipe(task); pipeline.tail = task; task.__idxInPipeline = pipeline.count++; task.__pipeline = pipeline; } static wrapStageHandler( stageHandler: StageHandler | StageHandlerOverallReset, visualType: StageHandlerInternal['visualType'] ): StageHandlerInternal { if (isFunction(stageHandler)) { stageHandler = { overallReset: stageHandler, seriesType: detectSeriseType(stageHandler) } as StageHandlerInternal; } (stageHandler as StageHandlerInternal).uid = getUID('stageHandler'); visualType && ((stageHandler as StageHandlerInternal).visualType = visualType); return stageHandler as StageHandlerInternal; }; } function overallTaskReset(context: OverallTaskContext): void { context.overallReset( context.ecModel, context.api, context.payload ); } function stubReset(context: StubTaskContext): TaskProgressCallback<StubTaskContext> { return context.overallProgress && stubProgress; } function stubProgress(this: StubTask): void { this.agent.dirty(); this.getDownstream().dirty(); } function stubOnDirty(this: StubTask): void { this.agent && this.agent.dirty(); } function seriesTaskPlan(context: SeriesTaskContext): TaskPlanCallbackReturn { return context.plan ? context.plan( context.model, context.ecModel, context.api, context.payload ) : null; } function seriesTaskReset( context: SeriesTaskContext ): TaskProgressCallback<SeriesTaskContext> | TaskProgressCallback<SeriesTaskContext>[] { if (context.useClearVisual) { context.data.clearAllVisual(); } const resetDefines = context.resetDefines = normalizeToArray( context.reset(context.model, context.ecModel, context.api, context.payload) ) as StageHandlerProgressExecutor[]; return resetDefines.length > 1 ? map(resetDefines, function (v, idx) { return makeSeriesTaskProgress(idx); }) : singleSeriesTaskProgress; } const singleSeriesTaskProgress = makeSeriesTaskProgress(0); function makeSeriesTaskProgress(resetDefineIdx: number): TaskProgressCallback<SeriesTaskContext> { return function (params: TaskProgressParams, context: SeriesTaskContext): void { const data = context.data; const resetDefine = context.resetDefines[resetDefineIdx]; if (resetDefine && resetDefine.dataEach) { for (let i = params.start; i < params.end; i++) { resetDefine.dataEach(data, i); } } else if (resetDefine && resetDefine.progress) { resetDefine.progress(params, data); } }; } function seriesTaskCount(context: SeriesTaskContext): number { return context.data.count(); } /** * Only some legacy stage handlers (usually in echarts extensions) are pure function. * To ensure that they can work normally, they should work in block mode, that is, * they should not be started util the previous tasks finished. So they cause the * progressive rendering disabled. We try to detect the series type, to narrow down * the block range to only the series type they concern, but not all series. */ function detectSeriseType(legacyFunc: StageHandlerOverallReset): string { seriesType = null; try { // Assume there is no async when calling `eachSeriesByType`. legacyFunc(ecModelMock, apiMock); } catch (e) { } return seriesType; } const ecModelMock: GlobalModel = {} as GlobalModel; const apiMock: ExtensionAPI = {} as ExtensionAPI; let seriesType; mockMethods(ecModelMock, GlobalModel); mockMethods(apiMock, ExtensionAPI); ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) { seriesType = type; }; ecModelMock.eachComponent = function (cond: any): void { if (cond.mainType === 'series' && cond.subType) { seriesType = cond.subType; } }; function mockMethods(target: any, Clz: any): void { /* eslint-disable */ for (let name in Clz.prototype) { // Do not use hasOwnProperty target[name] = noop; } /* eslint-enable */ } export default Scheduler;
the_stack
import Component, { types } from "@ff/graph/Component"; import { ITweenState } from "@ff/graph/components/CTweenMachine"; import { IPulseContext } from "@ff/graph/components/CPulse"; import { ITour, ITours, ITourStep } from "client/schema/setup"; import { ELanguageType, DEFAULT_LANGUAGE } from "client/schema/common"; import CVSnapshots, { EEasingCurve } from "./CVSnapshots"; import CVAnalytics from "./CVAnalytics"; import CVLanguageManager from "./CVLanguageManager"; //////////////////////////////////////////////////////////////////////////////// export default class CVTours extends Component { static readonly typeName: string = "CVTours"; static readonly sceneSnapshotId = "scene-default"; protected static readonly ins = { enabled: types.Boolean("Tours.Enabled"), tourIndex: types.Integer("Tours.Index", -1), stepIndex: types.Integer("Step.Index"), next: types.Event("Step.Next"), previous: types.Event("Step.Previous"), first: types.Event("Step.First"), }; protected static readonly outs = { count: types.Integer("Tours.Count"), tourIndex: types.Integer("Tour.Index", -1), tourTitle: types.String("Tour.Title"), tourLead: types.String("Tour.Lead"), stepCount: types.Integer("Tour.Steps"), stepIndex: types.Integer("Step.Index"), stepTitle: types.String("Step.Title"), }; ins = this.addInputs(CVTours.ins); outs = this.addOutputs(CVTours.outs); private _tours: ITour[] = []; protected get analytics() { return this.getMainComponent(CVAnalytics); } protected get language() { return this.getGraphComponent(CVLanguageManager); } get snapshots() { return this.getComponent(CVSnapshots); } get tours() { return this._tours; } get activeSteps() { const tour = this.activeTour; return tour ? tour.steps : null; } get activeTour() { return this._tours[this.outs.tourIndex.value]; } get activeStep() { const tour = this.activeTour; return tour ? tour.steps[this.outs.stepIndex.value] : null; } get title() { const tour = this.activeTour; // TODO: Temporary - remove when single string properties are phased out if(Object.keys(tour.titles).length === 0) { tour.titles[DEFAULT_LANGUAGE] = tour.title; } return tour.titles[ELanguageType[this.language.outs.language.value]] || "undefined"; } set title(inTitle: string) { const tour = this.activeTour; tour.titles[ELanguageType[this.language.outs.language.value]] = inTitle; } get lead() { const tour = this.activeTour; // TODO: Temporary - remove when single string properties are phased out if(Object.keys(tour.leads).length === 0) { tour.leads[DEFAULT_LANGUAGE] = tour.lead; } return tour.leads[ELanguageType[this.language.outs.language.value]] || ""; } set lead(inLead: string) { const tour = this.activeTour; tour.leads[ELanguageType[this.language.outs.language.value]] = inLead; } get taglist() { const tour = this.activeTour; // TODO: Temporary - remove when single string properties are phased out if(Object.keys(tour.taglist).length === 0) { if(tour.tags.length > 0) { tour.taglist[DEFAULT_LANGUAGE] = tour.tags; } } return tour.taglist[ELanguageType[this.language.outs.language.value]] || []; } set taglist(inTags: string[]) { const tour = this.activeTour; tour.taglist[ELanguageType[this.language.outs.language.value]] = inTags; } get stepTitle() { const step = this.activeStep; if(step) { // TODO: Temporary - remove when single string properties are phased out if(Object.keys(step.titles).length === 0) { step.titles[DEFAULT_LANGUAGE] = step.title; } return step.titles[ELanguageType[this.language.outs.language.value]] || "undefined"; } else { return null; } } set stepTitle(inTitle: string) { const step = this.activeStep; if(step) { step.titles[ELanguageType[this.language.outs.language.value]] = inTitle; } } create() { super.create(); this.language.outs.language.on("value", this.update, this); } dispose() { this.language.outs.language.off("value", this.update, this); super.dispose(); } update(context: IPulseContext) { const { ins, outs } = this; const tours = this._tours; const machine = this.snapshots; if (ins.enabled.changed) { if (ins.enabled.value) { // store pre-tour scene state const state: ITweenState = { id: CVTours.sceneSnapshotId, curve: EEasingCurve.EaseOutQuad, duration: 1, threshold: 0, values: machine.getCurrentValues(), }; machine.setState(state); } else { outs.tourIndex.set(); // recall pre-tour scene state machine.tweenTo(CVTours.sceneSnapshotId, context.secondsElapsed); machine.deleteState(CVTours.sceneSnapshotId); return true; } } const tourIndex = Math.min(tours.length - 1, Math.max(-1, ins.tourIndex.value)); const tour = tours[tourIndex]; const stepCount = tour ? tour.steps.length : 0; outs.stepCount.setValue(stepCount); let nextStepIndex = -1; if (ins.tourIndex.changed || ins.enabled.changed) { if (tourIndex !== outs.tourIndex.value) { nextStepIndex = 0; } outs.tourIndex.setValue(tourIndex); outs.tourTitle.setValue(tour ? this.title : ""); outs.tourLead.setValue(tour ? this.lead : ""); } if (stepCount === 0) { outs.stepIndex.setValue(-1); outs.stepTitle.setValue(""); return true; } let tween = true; if (ins.enabled.changed) { nextStepIndex = outs.stepIndex.value; } if (ins.stepIndex.changed) { nextStepIndex = Math.min(tour.steps.length - 1, Math.max(0, ins.stepIndex.value)); tween = false; } if (ins.first.changed) { nextStepIndex = 0; } if (ins.next.changed) { nextStepIndex = outs.stepIndex.value + 1; // after last step, show tour menu if (nextStepIndex >= stepCount) { outs.tourIndex.setValue(-1); outs.tourTitle.setValue(""); outs.tourLead.setValue(""); outs.stepIndex.set(); nextStepIndex = -1; } } if (ins.previous.changed) { // previous step, wrap around when reaching first step nextStepIndex = (outs.stepIndex.value + stepCount - 1) % stepCount; } if (nextStepIndex >= 0) { // tween to the next step const step = tour.steps[nextStepIndex]; outs.stepIndex.setValue(nextStepIndex); outs.stepTitle.setValue(this.stepTitle || "undefined"); machine.ins.id.setValue(step.id); tween ? machine.ins.tween.set() : machine.ins.recall.set(); } return true; } fromData(data: ITours) { this._tours = data.map(tour => ({ title: tour.title, titles: tour.titles || {}, steps: tour.steps.map(step => ({ title: step.title, titles: step.titles || {}, id: step.id, })), lead: tour.lead || "", leads: tour.leads || {}, tags: tour.tags || [], taglist: tour.taglist || {} })); // update langauges used in tours this._tours.forEach( tour => { Object.keys(tour.titles).forEach( key => { this.language.addLanguage(ELanguageType[key]); }); // TODO: Delete when single string properties are phased out tour.steps.forEach( step => { if(Object.keys(step.titles).length == 0) { step.titles[DEFAULT_LANGUAGE] = step.title || null; } }); }); this.ins.tourIndex.setValue(-1); this.outs.count.setValue(this._tours.length); } toData(): ITours | null { if (this._tours.length === 0) { return null; } return this._tours.map(tour => { const data: Partial<ITour> = { steps: tour.steps.map(step => { const tourstep: Partial<ITourStep> = {}; tourstep.id = step.id; if (Object.keys(step.titles).length > 0) { tourstep.titles = step.titles; } else if (step.title) { tourstep.title = step.title; } return tourstep as ITourStep; }), }; if (Object.keys(tour.titles).length > 0) { data.titles = tour.titles; } else if (tour.title) { data.title = tour.title; } if (Object.keys(tour.leads).length > 0) { data.leads = tour.leads; } else if (tour.lead) { data.lead = tour.lead; } if (Object.keys(tour.taglist).length > 0) { data.taglist = tour.taglist; } else if (tour.tags.length > 0) { data.tags = tour.tags; } return data as ITour; }); } }
the_stack
const sys_op_test = 1 // sys_opcode op const sys_op_exit = 2 // int status_code const sys_op_openat = 3 // const char* path, usize flags, isize mode const sys_op_close = 4 // sys_fd fd const sys_op_read = 5 // sys_fd fd, void* data, usize size const sys_op_write = 6 // sys_fd fd, const void* data, usize size const sys_op_sleep = 7 // usize seconds, usize nanoseconds // enum sys_err const sys_err_none = 0 const sys_err_badfd = 1 const sys_err_invalid = 2 // invalid data or argument const sys_err_sys_op = 3 // invalid syscall op or syscall op data const sys_err_bad_name = 4 const sys_err_not_found = 5 const sys_err_name_too_long = 6 const sys_err_canceled = 7 const sys_err_not_supported = 8 const sys_err_exists = 9 const sys_err_end = 10 const sys_err_access = 11 // enum sys_open_flags const sys_open_ronly = 0 const sys_open_wonly = 1 const sys_open_rw = 2 const sys_open_append = 1 << 2 const sys_open_create = 1 << 3 const sys_open_trunc = 1 << 4 const sys_open_excl = 1 << 5 function assert(cond) { if (!cond) throw new Error(`assertion failed`) } function sys_syscall(proc, op, arg1, arg2, arg3, arg4, arg5) { // -> sys_ret // console.log("sys_syscall", {proc, op, arg1, arg2, arg3, arg4, arg5}) if (proc.suspended) return proc.resumeFinalize() switch (op) { case sys_op_test: return sys_syscall_test(proc, arg1); case sys_op_exit: return sys_syscall_exit(proc, arg1); case sys_op_openat: return sys_syscall_openat(proc, arg1, arg2, arg3, arg4); case sys_op_close: return sys_syscall_close(proc, arg1); case sys_op_read: return sys_syscall_read(proc, arg1, arg2, arg3); case sys_op_write: return sys_syscall_write(proc, arg1, arg2, arg3); case sys_op_sleep: return sys_syscall_sleep(proc, arg1, arg2); } console.error("invalid sys_syscall op", {proc, op, arg1, arg2, arg3, arg4, arg5}) return -sys_err_sys_op; } function sys_syscall_test(proc, supports_op) { if (supports_op > sys_op_write) return -sys_err_not_supported return 0 } function sys_syscall_exit(proc, status) { const err = new Error("exit " + status) err.name = "WasmExit" err.status = status throw err // only way to interrupt wasm in a JS runtime return 0 } async function open_web_fs(proc, pathptr, flags, mode) { // see https://web.dev/file-system-access/ // see https://developer.mozilla.org/en-US/docs/Web/API/window/showSaveFilePicker if (window.showSaveFilePicker === undefined) return -sys_err_not_supported const handle = await ( (flags & sys_open_create) ? showSaveFilePicker() : showOpenFilePicker().then(v => v[0]) ) let rstream = null let wstream = null if ((flags & 3) != sys_open_wonly) { const file = await handle.getFile() rstream = file.stream().getReader() } if ((flags & 3) != sys_open_ronly) { wstream = await handle.createWritable() if (flags & sys_open_trunc) await wstream.write({ type: "truncate", size: 0 }) } const fd = proc.allocFd() proc.files[fd] = new WebFSFile(proc, fd, flags, handle, rstream, wstream) return fd } function sys_syscall_openat(proc, basefd, pathptr, flags, mode) { const path = proc.cstr(pathptr) if (path.length == 0) return -sys_err_invalid let fent = fake_fs.findEntry(path) if (fent) { if (flags & sys_open_excl) return -sys_err_exists const fd = proc.allocFd() const file = new MemoryFile(proc, fd, flags, fent) proc.files[fd] = file if (flags & sys_open_trunc) { const r = file.truncate(0) if (r < 0) { proc.freeFd(fd) return r } } if (flags & sys_open_append) { const r = file.seek(0, sys_seek_end) if (r < 0) { proc.freeFd(fd) return r } } return fd } proc.suspend() open_web_fs(proc, pathptr, flags, mode).then(fd => { proc.resume(fd) }).catch(err => { // console.error("open_web_fs failed:", err, {err}) const code = (err.name == "AbortError") ? sys_err_canceled : sys_err_invalid proc.resume(-code) }) } function sys_syscall_close(proc, fd) { const file = proc.files[fd] if (!file) return -sys_err_badfd proc.freeFd(fd) return file.close() } function sys_syscall_read(proc, fd, dataptr, datalen) { const file = proc.files[fd] if (!file) return -sys_err_badfd if (!file.isReadable()) return -sys_err_invalid // not writable const result = file.read(dataptr, datalen) if (!(result instanceof Promise)) return result proc.suspend() result .then(result => proc.resume(result)) .catch(err => { // console.error("sys_syscall_read caught async exception:", err, {err}) proc.resume(-sys_err_canceled) }) } function sys_syscall_write(proc, fd, dataptr, datalen) { const file = proc.files[fd] if (!file) return -sys_err_badfd if (!file.isWritable()) return -sys_err_invalid // not writable return file.write(dataptr, datalen) } function sys_syscall_sleep(proc, seconds, nanoseconds) { proc.suspend() const milliseconds = seconds*1000 + nanoseconds/1000000 setTimeout(() => { proc.resume(0) }, milliseconds); } // ------------------------------------------------------------------------- // note: nodejs has require("util").TextEncoder & .TextDecoder const txt_enc = new TextEncoder("utf-8") const txt_dec = new TextDecoder("utf-8") class FileBase { constructor(proc, fd, flags) { this.proc = proc this.fd = fd this.flags = flags } isReadable() { return (this.flags & 3) != sys_open_wonly } isWritable() { return (this.flags & 3) != sys_open_ronly } read(dstptr, cap) { return -sys_err_invalid } write(srcptr, len) { return -sys_err_invalid } seek(offset, whence) { return -sys_err_invalid } truncate(size) { return -sys_err_invalid } flush(){ return -sys_err_invalid } close() { return 0 } size() { return -1 } } class SeekableFile extends FileBase { constructor(proc, fd, flags) { super(proc, fd, flags) this.pos = 0 } seek(offset, whence) { const sys_seek_set = 1 const sys_seek_current = 1 const sys_seek_end = 1 switch (whence) { case sys_seek_set: this.pos = offset; break case sys_seek_current: this.pos += offset; break case sys_seek_end: this.pos = this.size(); break } if (this.pos < 0) { this.pos = 0 return -sys_err_invalid } if (this.pos > this.size()) { this.pos = this.size() return -sys_err_invalid } return 0 } } class WebFSFile extends SeekableFile { constructor(proc, fd, flags, handle, rstream, wstream) { super(proc, fd, flags) this.handle = handle // FileSystemFileHandle this.rstream = rstream // ReadableStreamDefaultReader | null this.wstream = wstream // FileSystemWritableFileStream | null this.rbuf = null // queued UInt8Array } async read(dstptr, len) { let wptr = dstptr const write = (buf) => { const rlen = wptr - dstptr // bytes read so far const n = len - rlen // remaining number of bytes to read let remainder = null if (buf.length > n) { remainder = buf.subarray(n) buf = buf.subarray(0, n) } this.proc.mem_u8.set(buf, wptr) wptr += buf.length return remainder } if (this.rbuf) this.rbuf = write(this.rbuf) while (wptr - dstptr < len) { const { done, value } = await this.rstream.read() // value is a UInt8Array if (done) break this.rbuf = write(value) } return wptr - dstptr } async write(srcptr, len) { const data = this.proc.mem_u8.subarray(srcptr, srcptr + len) try { await this.wstream.write({ type: "write", data }) return len } catch (err) { if (err.name == "NotAllowedError") return -sys_err_access // Permission is not granted. return -sys_err_canceled } } async close() { if (this.rstream) { this.rstream.cancel("file closed") this.rstream.releaseLock() } if (this.wstream) await this.wstream.close() } } class MemoryFile extends SeekableFile { constructor(proc, fd, flags, fent) { super(proc, fd, flags) this.fent = fent } size() { return this.fent.size } write(srcptr, len) { // -> sys_ret nbytes_written if (this.pos + len > this.fent.buf.length) { const prevbuf = this.fent.buf this.fent.buf = new Uint8Array(align2(prevbuf.length + len, 4096)) this.fent.buf.set(prevbuf.subarray(0, this.pos)) } this.fent.buf.set(this.proc.mem_u8.subarray(srcptr, srcptr + len), this.pos) this.pos += len this.fent.size = Math.max(this.fent.size, this.pos) return len } read(dstptr, cap) { if (this.pos >= this.fent.size) return -sys_err_end const len = Math.min(this.fent.size - this.pos, cap) const src = this.fent.buf.subarray(this.pos, this.pos + len) this.proc.mem_u8.set(src, dstptr) this.pos += len return len } } class LineWriterFile extends FileBase { constructor(proc, fd, flags, onLine) { super(proc, fd, flags) this.buf = "" this.onLine = onLine } write(ptr, len) { // -> sys_ret nbytes_written this.buf += this.proc.str(ptr, len) const nl = this.buf.lastIndexOf("\n") if (nl != -1) { this.onLine(this.buf.substr(0, nl)) this.buf = this.buf.substr(nl + 1) } return len } flush() { const len = this.buf.length if (len > 0) { this.onLine(this.buf) this.buf = "" } return len } } // fake file system class FakeFSEntry {} class FakeFS { constructor() { this.entries = Object.create(null) const uname = `web-${navigator.appName} 1\n` this.createEntry("/sys/uname", 0o444, txt_enc.encode(uname)) } findEntry(path) { return this.entries[path] } createEntry(path, mode, buf) { const entry = { path, mode, size: buf ? buf.length : 0, mtime: Date.now()/1000, buf: buf || new Uint8Array(4096), } this.entries[path] = entry return entry } deleteEntry(path) { if (!this.entries[entry]) return false delete this.entries[entry] return true } } var fake_fs = new FakeFS() class Process { constructor(memory) { this.memory = memory this.mem_u8 = new Uint8Array(memory.buffer) this.mem_i32 = new Int32Array(memory.buffer) this.mem_u32 = new Uint32Array(memory.buffer) this.instance = null this.mainfun = null this.main_resolve = null this.main_reject = null this.cwd = "/" this.free_fds = [] this.max_fd = 2 this.suspended = false this.suspend_data_addr = 16 // where the unwind/rewind data will live this.suspend_stack_size = 1024 this.suspend_result = null // resumed return value this.main_args_addr = this.suspend_data_addr + this.suspend_stack_size this.onStdoutLine = console.log.bind(console) this.onStderrLine = console.error.bind(console) this.files = { // open file handles, indexed by fd 0: /*stdin*/ new FileBase(this, 0, 0), // invalid 1: /*stdout*/ new LineWriterFile(this, 1, sys_open_wonly, s => this.onStdoutLine(s)), 2: /*stderr*/ new LineWriterFile(this, 2, sys_open_wonly, s => this.onStderrLine(s)), } } run(main_args) { return new Promise((resolve, reject) => { //console.log("wasm exports:\n " + Object.keys(instance.exports).sort().join("\n ")) this.mainfun = this.instance.exports.main || this.instance.exports.__main_argc_argv this.main_resolve = resolve this.main_reject = reject const argc = 0 const argv = 0 // TODO: main args // const argc = main_args.length // const argv = this.main_args_addr // start address of argv // let argvp = argv // for (let arg of main_args) { // let srcbuf = txt_enc.encode(String(arg)) // this.mem_u8.set(srcbuf, argvp) // argvp += // } this.callMain(argc, argv) }) } callMain(argc, argv) { try { const retval = this.mainfun(argc, argv) const sstate = this.suspendState() if (sstate == 0) { assert(this.suspendState() == 0) this.finalize() this.main_resolve(retval) } else { assert(sstate == 1) this.instance.exports.asyncify_stop_unwind() } } catch (err) { this.suspended = false // TODO: figure out if we need to clean up asyncify state: // const sstate = this.suspendState() // if (sstate == 1) { // this.instance.exports.asyncify_stop_unwind() // } else if (sstate == 2) { // this.instance.exports.asyncify_stop_rewind() // } this.finalize() if (err.name == "WasmExit") { this.main_resolve(err.status) } else { this.main_reject(err) } } } finalize() { for (let fd in this.files) { const file = this.files[fd] if (file.isWritable()) file.flush() } } allocFd() { if (this.free_fds.length) return this.free_fds.pop() this.max_fd++ return this.max_fd } freeFd(fd) { delete this.files[fd] this.free_fds.push(fd) } u8(ptr) { return this.mem_u8[ptr] } i32(ptr) { return this.mem_i32[ptr >>> 2] } u32(ptr) { return this.mem_u32[ptr >>> 2] >>> 0 } setI32(ptr, v) { this.mem_u32[ptr >>> 2] = v } setU32(ptr, v) { this.mem_u32[ptr >>> 2] = (v >>> 0) } // u64(ptr) { // BigInt ... // } isize(ptr) { return this.mem_i32[ptr >>> 2] } usize(ptr) { return this.mem_u32[ptr >>> 2] >>> 0 } str(ptr, len) { return txt_dec.decode(new DataView(this.memory.buffer, ptr, len)) } cstr(ptr) { const len = this.mem_u8.indexOf(0, ptr) - ptr return txt_dec.decode(new DataView(this.memory.buffer, ptr, len)) } setStr(ptr, cap, jsstr) { let srcbuf = txt_enc.encode(String(jsstr)) if (srcbuf.length > cap) srcbuf = srcbuf.subarray(0, cap) this.mem_u8.set(srcbuf, ptr) return srcbuf.length } // Process suspension via Binaryen asyncify // Usage synopsis: // function foo(arg) { // if (proc.suspended) // woke up from resume() // return proc.resumeFinalize() // // Your function may complete immediately if it wants // if (done_imm) // return 123 // // Or suspend execution for a while // proc.suspend() // setTimeout(() => { // let result = 123 // proc.resume(result) // },100) // } // // See https://kripken.github.io/blog/wasm/2019/07/16/asyncify.html // See https://yingtongli.me/blog/2021/07/28/asyncify-vanilla.html // suspend() { assert(this.suspendState() == 0) // must not be suspended // Fill in the data structure. The first value has the stack location, // which for simplicity we can start right after the data structure itself this.mem_i32[this.suspend_data_addr >> 2] = this.suspend_data_addr + 8 this.mem_i32[this.suspend_data_addr + 4 >> 2] = this.suspend_stack_size // end of stack this.instance.exports.asyncify_start_unwind(this.suspend_data_addr) this.suspended = true } resume(result) { assert(this.suspendState() != 2) // must not be rewinding this.suspend_result = result this.instance.exports.asyncify_start_rewind(this.suspend_data_addr) // The code is now ready to rewind; to start the process, enter the // first function that should be on the call stack. this.callMain() } resumeFinalize() { assert(this.suspendState() == 2) // must be rewinding this.instance.exports.asyncify_stop_rewind() this.suspended = false return this.suspend_result } // 0 = normal, 1 = unwinding, 2 = rewinding suspendState() { return this.instance.exports.asyncify_get_state() } mkasync(f) { const proc = this return function() { if (!proc.suspended) { proc.suspend() f.call(proc, proc.resume.bind(proc), ...arguments) } else { return proc.resumeFinalize() } } } } const wasm_instantiate = ( WebAssembly.instantiateStreaming || ((res, import_obj) => res.then(r => r.arrayBuffer()).then(buf => WebAssembly.instantiate(buf, import_obj))) ) export async function wasm_load(url) { const fetch_promise = url instanceof Promise ? url : fetch(url) const memory = new WebAssembly.Memory({ initial: 32 /*pages*/ }) const proc = new Process(memory) const import_obj = { env: { memory, sys_syscall: sys_syscall.bind(null, proc), }, } const { instance } = await wasm_instantiate(fetch_promise, import_obj) proc.instance = instance return proc } // align2 rounds up unsigned integer u to closest a where a must be a power of two. // E.g. // align(0, 4) => 0 // align(1, 4) => 4 // align(2, 4) => 4 // align(3, 4) => 4 // align(4, 4) => 4 // align(5, 4) => 8 // ... function align2(u,a) { a = (a >>> 0) - 1 return (((u >>> 0) + a) & ~a) >>> 0 } // function TODO_open_web_fs() { // // see https://web.dev/file-system-access/ // // see https://developer.mozilla.org/en-US/docs/Web/API/window/showSaveFilePicker // if (window.showSaveFilePicker === undefined) // return -sys_err_not_supported // // allocate new file // file = new HostFile(proc, proc.files.length, flags) // file.promise = ( // flags & sys_open_create ? showSaveFilePicker() : // showOpenFilePicker() // ).catch(err => { // console.error("syscall open", err.message, {path,mode,flags}) // }) // }
the_stack
import { EventEmitter } from 'events'; import { LasConfig, TimeRange } from '../types/core'; import { MP4Segment } from '../types/remux'; import { Log } from '../utils/log'; import { ErrorDetails, ErrorTypes } from './errors'; import LasEvents from './events'; // append关闭时queue允许缓存的长度上限 const QUEUE_SIZE_LIMIT = 200 * 1024 * 1024; const MAX_CLEANUP_DURATION = 10; const MIN_CLEANUP_DURATION = 5; const MAX_BUFFERED = 30; /** * 处理MediaSource * https://developer.mozilla.org/zh-CN/docs/Web/API/MediaSource */ export default class MSE extends EventEmitter { private tag: string = 'MSE'; private _config: LasConfig; public video?: HTMLVideoElement; public _sourceBuffer: { [index: string]: SourceBuffer }; private _mediaSource: MediaSource | null = null; private _mimeCodec: { [index: string]: string }; private _cleanUpTask: { [index: string]: TimeRange[] }; private _appendQueue: { [index: string]: MP4Segment[] }; private _hasVideo: boolean; private _hasAudio: boolean; private _endOfData: boolean = false; private _appendEnabled: boolean; private _duration: number | null = null; private _appendError: number = 0; private _appendBufferError: boolean = false; private _sbHandler: { [index: string]: { updateend: (e: Event) => any; error: (e: Event) => any } } = {}; /** * 传入配置参数,初始化MSE * @param config LasConfig */ constructor(config: LasConfig) { super(); this._config = config; this._hasVideo = false; this._hasAudio = false; this._appendQueue = { video: [], audio: [], audiovideo: [] }; this._sourceBuffer = {}; this._cleanUpTask = { video: [], audio: [], audiovideo: [] }; this._mimeCodec = {}; this._appendEnabled = true; } /** * 绑定HTMLVideoElement * @param video HTMLVideoElement */ public attach(video: HTMLVideoElement): void { this.video = video; const MediaSourceDef = (window as any).MediaSource || (window as any).WebKitMediaSource; if (MediaSourceDef) { const ms = (this._mediaSource = new MediaSourceDef()); this.video.src = URL.createObjectURL(ms); this.video.load(); ms.addEventListener('sourceopen', this._onSourceOpen); ms.addEventListener('sourceended', this._onSourceEnded); ms.addEventListener('sourceclose', this._onSourceClose); } else { setTimeout(() => { this.emit(LasEvents.ERROR, { type: ErrorTypes.MSE_ERROR, details: ErrorDetails.MEDIASOURCE_ERROR, fatal: true, info: { reason: 'MediaSource is not support' } }); }, 0); } } /** * 传入视频头信息 * @param mediaInfo */ public mediaInit(mediaInfo: any): void { if ((this._hasAudio !== mediaInfo.hasAudio || this._hasVideo !== mediaInfo.hasVideo || !!mediaInfo.audiovideo !== !!this._mimeCodec.audiovideo) && this.video && this.hasSourceBuffer()) { // 音视频轨数量发生变化时需要重建mse Log.i(this.tag, 'trackInfo rebuild mse'); for (const type in this._sourceBuffer) { if (this._sourceBuffer[type] && this._sbHandler[type]) { this._sourceBuffer[type].removeEventListener('error', this._sbHandler[type].error); this._sourceBuffer[type].removeEventListener('updateend', this._sbHandler[type].updateend); } } this._sourceBuffer = {}; if (this._mediaSource) { this._mediaSource.removeEventListener('sourceopen', this._onSourceOpen); this._mediaSource.removeEventListener('sourceended', this._onSourceEnded); this._mediaSource.removeEventListener('sourceclose', this._onSourceClose); } this._mimeCodec = {}; this.attach(this.video); } if (!mediaInfo.audiovideo) { if (mediaInfo.hasAudio && mediaInfo.audioCodec) { this._mimeCodec.audio = `audio/mp4; codecs="${mediaInfo.audioCodec}"`; } if (mediaInfo.hasVideo && mediaInfo.videoCodec) { this._mimeCodec.video = `video/mp4; codecs="${mediaInfo.videoCodec}"`; } } else { this._mimeCodec.audiovideo = `video/mp4; codecs="${mediaInfo.codec}"`; } this._hasAudio = this._hasAudio || mediaInfo.hasAudio; this._hasVideo = this._hasVideo || mediaInfo.hasVideo; this._checkSourceBuffer(); } /** * 刷新MSE,计算一次清理任务,尝试重启填充buffer任务 */ public refresh() { for (const type in this._sourceBuffer) { this._update(type); } } /** * 转封装后fmp4数据 * @param segments segments */ public mediaSegment(segments: MP4Segment[]): void { segments.forEach(segment => { let type = segment.type; this._appendQueue[type].push(segment); if (this._sourceBuffer[type]) { this._update(type); } }) } /** * mse buffer范围,秒 * @param type video|audio|audiovideo */ public bufferedByType(type: string): { start: number; end: number } { const sb = this._sourceBuffer[type]; if (sb && sb.buffered.length > 0) { return { start: sb.buffered.start(0), end: sb.buffered.end(sb.buffered.length - 1) }; } return { start: 0, end: 0 }; } /** * mse buffer结束时间点,秒 * @param type video|audio|audiovideo */ public bufferedEndByType(type: string): number { const sb = this._sourceBuffer[type]; if (sb && sb.buffered.length > 0) { return sb.buffered.end(sb.buffered.length - 1); } return 0; } /** * mse buffer的分段数量,正常情况不大于1 * @param type video|audio|audiovideo */ public bufferSliceNumByType(type: string): number { const sb = this._sourceBuffer[type]; if (sb) { return sb.buffered.length; } return 0; } /** * 待填充buffer长度 * @param type video|audio|audiovideo */ public pendingSecByType(type: string): number { const buffer = this._appendQueue[type]; if (buffer) { return buffer.reduce((prev, current) => { return prev + current.endDTS - current.startDTS; }, 0); } return 0; } /** * 待填充buffer数量 */ public pendingNum(): number { let num = 0; for (let type in this._appendQueue) { num += this._appendQueue[type].length; } return num; } /** * 检查track是否已获取codec */ private _checkSourceBuffer(): void { let expected = (this._hasAudio ? 1 : 0) + (this._hasVideo ? 1 : 0); let codecs = (this._mimeCodec.audio ? 1 : 0) + (this._mimeCodec.video ? 1 : 0); if (this._mimeCodec.audiovideo) { expected = 1; codecs = 1; } Log.v(this.tag, 'checkSourceBuffer', expected, codecs, this._mimeCodec); if (this._mediaSource && this._mediaSource.readyState === 'open' && expected > 0 && codecs >= expected) { for (const type in this._mimeCodec) { if (this._mimeCodec[type]) { this._addSourceBuffer(type); } } } } /** * MediaSource的sourceopen事件处理 */ private _onSourceOpen = () => { Log.i(this.tag, 'MediaSource onSourceOpen'); if (this._mediaSource) { this._mediaSource.removeEventListener('sourceopen', this._onSourceOpen); this._checkSourceBuffer(); this.refresh(); this.emit('source_open'); } }; /** * 向mediaSource添加sourceBuffer * @param type video|audio */ private _addSourceBuffer(type: string): void { if (this._sourceBuffer[type]) { return; } try { if (this._mediaSource) { this._sourceBuffer[type] = this._mediaSource.addSourceBuffer(this._mimeCodec[type]); } } catch (e) { Log.e(this.tag, e); this.emit(LasEvents.ERROR, { type: ErrorTypes.MSE_ERROR, details: ErrorDetails.ADDSOURCEBUFFER_ERROR, fatal: true, info: { reason: e.message } }); return; } const sb = this._sourceBuffer[type]; this._sbHandler[type] = { updateend: () => { this._onSourceBufferUpdateEnd(type); }, error: (e: Event) => { this._onSourceBufferError(e); } }; sb.addEventListener('error', this._sbHandler[type].error); sb.addEventListener('updateend', this._sbHandler[type].updateend); if (this._duration && this._mediaSource) { this._mediaSource.duration = this._duration; } } /** * 是否有待处理的数据 */ private _hasPendingData(): boolean { return !!( this._appendQueue && ((this._appendQueue.video && this._appendQueue.video.length) || (this._appendQueue.audio && this._appendQueue.audio.length)) ); } /** * 向sourcebuffer中填入数据 * @param type video|audio */ private _doAppend(type: string): void { if (this._hasPendingData()) { if (!this._appendEnabled) { const size = this._getBufferQueueSize(); if (size > QUEUE_SIZE_LIMIT && !this._appendBufferError) { this._appendBufferError = true; this.emit(LasEvents.ERROR, { type: ErrorTypes.MSE_ERROR, details: ErrorDetails.APPENDBUFFER_ERROR, fatal: true, info: { reason: 'bufferfull' } }); } return; } if ( this._appendQueue[type].length > 0 && this._sourceBuffer[type] && !this._sourceBuffer[type].updating && !this._appendBufferError ) { const data = this._appendQueue[type].shift(); this._appendBuffer(data); } } } /** * 根据填充策略计算需要缓存清理的范围 * @param type video|audio|audiovideo */ private _calculateRemoveRange(type: string): void { const video = this.video; if (!video || video.seeking) { return; } const time = video.currentTime; if (this._sourceBuffer[type]) { const task = this._cleanUpTask[type]; const buffered = this._sourceBuffer[type].buffered; if (buffered.length >= 1 && time - buffered.start(0) >= MAX_CLEANUP_DURATION) { const end = time - MIN_CLEANUP_DURATION; if (task.length) { if (task[task.length - 1].start === 0 && task[task.length - 1].end === end) { return; } } task.push({ start: 0, end }); } } } /** * 尝试清理sourcebufer缓存 * @param sb 需要清理的sourceBuffer * @param range 需要清理的范围 */ private _cleanUpRange(type: string, range: TimeRange): boolean { const sb = this._sourceBuffer[type]; if (sb) { if (!sb.updating) { try { for (let i = 0; i < sb.buffered.length; i++) { const bufStart = 0; const bufEnd = sb.buffered.end(i); const removeStart = Math.max(bufStart, range.start); const removeEnd = Math.min(bufEnd, range.end); /** * remove不一定准确按照指定值进行,remove长度小于500ms,可能无效 */ if (removeEnd > removeStart) { sb.remove(removeStart, removeEnd); this.emit('remove'); // 多段buffer时可能需要多次清理 if (i < sb.buffered.length - 1) { return false; } } } } catch (error) { } } else { return false; } } return true; } /** * 向sourcebuffer中填充数据 * @param data data * @param type type */ private _appendBuffer(data?: MP4Segment): void { if (!data || !this._sourceBuffer[data.type] || !this.video || this.video.error) { return; } try { this._sourceBuffer[data.type].appendBuffer(data.payload.buffer); } catch (e) { Log.w(this.tag, e.code, e); if (e.code !== 22) { if (this._appendError) { this._appendError++; } else { this._appendError = 1; } if (this._appendError > this._config.appendErrorMaxRetry) { this._appendBufferError = true; this.emit(LasEvents.ERROR, { type: ErrorTypes.MSE_ERROR, details: ErrorDetails.APPENDBUFFER_ERROR, fatal: true, info: { reason: e.message } }); } else { this._appendQueue[data.type].unshift(data); } } else { // buffer满无法填充 let v = this.video, conf = this._config; this._appendEnabled = false; this._appendQueue[data.type].unshift(data); let buffered = v.buffered.end(v.buffered.length - 1) - v.currentTime; let useless = v.currentTime - v.buffered.start(0); // 未使用buffer小于阈值,尝试清理已使用buffer if (buffered < MAX_BUFFERED) { this._calculateRemoveRange(data.type); if (this.hasCleanUpTask(data.type)) { this._cleanUp(data.type); } // 已使用buffer小于清理阈值时,抛错 } else if (useless < MAX_CLEANUP_DURATION) { this.emit(LasEvents.ERROR, { type: ErrorTypes.MSE_ERROR, details: ErrorDetails.APPENDBUFFER_ERROR, fatal: true, info: { reason: 'buffer full, append error' } }); } Log.i(this.tag, 'mse bufferfull') this.emit('bufferFull'); } } } /** * sourcebuffer end */ private _onSourceEnded = () => { Log.i(this.tag, 'MediaSource onSourceEnded'); }; /** * sourcebuffer close */ private _onSourceClose = () => { Log.i(this.tag, 'MediaSource onSourceClose'); if (this._mediaSource) { this._mediaSource.removeEventListener('sourceopen', this._onSourceOpen); this._mediaSource.removeEventListener('sourceended', this._onSourceEnded); this._mediaSource.removeEventListener('sourceclose', this._onSourceClose); } }; private _onSourceBufferUpdateEnd = (type: string) => { this._update(type); if (this._endOfData) { this._endOfStream(); } this.emit('updateend'); }; /** * sourcebuffer error * @param {Object} e 事件 */ private _onSourceBufferError = (e: Event) => { Log.e(this.tag, `SourceBuffer Error: ${e}`); this.emit(LasEvents.ERROR, { type: ErrorTypes.MSE_ERROR, details: ErrorDetails.SOURCEBUFFER_ERROR, fatal: true, info: { reason: 'source buffer error' } }); }; /** * 清理mse sourcebuffer缓存 * @param startSec 开始时间点,未指从0点开始 * @param endSec 结束时间点,未指定时结束点为正无穷大 * @param flushType 类型,未指定时清理所有sourcebuffe */ public flush(startSec?: number, endSec?: number, flushType?: string): void { let start = 0, end = Number.POSITIVE_INFINITY; this._endOfData = false; // 计算清理范围 for (const type in this._sourceBuffer) { if (flushType && flushType !== type) { continue; } const sb = this._sourceBuffer[type]; if (!sb) { continue; } // 清理未填充数据 if (startSec) { start = Math.max(start, startSec); for (let i = this._appendQueue[type].length - 1; i >= 0; i--) { if (!this._appendQueue[type][i].startPTS || this._appendQueue[type][i].startPTS >= startSec) { this._appendQueue[type].pop(); } else { break; } } } else { this._appendQueue[type] = []; } if (endSec) { end = Math.min(end, endSec); } this._cleanUpTask[type].push({ start, end }); this._cleanUp(type); } this._appendEnabled = true; } /** * 是否开启buffer填充 * @param value 开关 */ public setAppendEnabled(value: boolean): void { if (!this._appendEnabled && value) { this._appendEnabled = value; this.refresh(); } else { this._appendEnabled = value; } } public getAppendEnabled(): boolean { return this._appendEnabled; } /** * 数据结束 */ public endOfData(): void { this._endOfData = true; if (!this._hasPendingData()) { this._endOfStream(); } } public ended(): boolean { return this._endOfData; } private _endOfStream(): void { const ms = this._mediaSource; if (!ms || ms.readyState !== 'open') { return; } for (const type in this._sourceBuffer) { const sb = this._sourceBuffer[type]; if (sb && sb.updating) { return; } } try { ms.endOfStream(); } catch (error) { Log.e(this.tag, error); this.emit(LasEvents.ERROR, { type: ErrorTypes.MSE_ERROR, details: ErrorDetails.ENDOFSTREAM_ERROR, fatal: true, info: { reason: error.message } }); } } /** * 销毁 */ public destroy(): void { if (this._mediaSource) { const ms = this._mediaSource; // pending segments should be discard // remove all sourcebuffers this._endOfStream(); if (ms.readyState !== 'closed') { for (const type in this._sourceBuffer) { if (this._sourceBuffer[type] && this._sbHandler[type]) { this._sourceBuffer[type].removeEventListener('error', this._sbHandler[type].error); this._sourceBuffer[type].removeEventListener('updateend', this._sbHandler[type].updateend); ms.removeSourceBuffer(this._sourceBuffer[type]); } } } ms.removeEventListener('sourceopen', this._onSourceOpen); ms.removeEventListener('sourceended', this._onSourceEnded); ms.removeEventListener('sourceclose', this._onSourceClose); this._mediaSource = null; } this.removeAllListeners(); this._appendQueue = {}; this._mimeCodec = {}; this._cleanUpTask = {}; this._sourceBuffer = {}; this._sbHandler = {}; } /** * 是否有未完成的清理任务 * @param type video|audio|audiovideo */ public hasCleanUpTask(type?: string): boolean { let num = 0; if (typeof type === 'undefined') { for (let type in this._cleanUpTask) { num += this._cleanUpTask[type].length; } } else { if (this._cleanUpTask[type]) { num = this._cleanUpTask[type].length; } } return num > 0; } /** * 是否已添加了sourceBuffer */ public hasSourceBuffer(): boolean { return !!Object.keys(this._sourceBuffer).length; } /** * 计算待填充数据队列中数据总大小 */ private _getBufferQueueSize(): number { let num = 0; for (const type in this._appendQueue) { num += this._appendQueue[type].reduce((prev, current) => { if (current.payload && current.payload.byteLength) { return prev + current.payload.byteLength; } return prev; }, 0); } return num; } /** * 待填充队列中的数据时长 * @param type video|audio|audiovideo,为空时返回video|audio最大值 * @returns 时长(秒) */ public getBufferQueueSec(type?: string): number { if (!this._appendQueue) { return 0; } let keys; if (type) { keys = [type]; } else { keys = Object.keys(this._appendQueue); } return keys.reduce((prev, current) => { if (this._appendQueue[current] && this._appendQueue[current].length > 0 && (Object.keys(this._sourceBuffer).length === 0 || this._sourceBuffer[current])) { return Math.max( prev, this._appendQueue[current].reduce((prevDuration, currentSegment) => { let duration = currentSegment.endDTS - currentSegment.startDTS; if (duration) { return prevDuration + duration; } return prevDuration; }, 0) ); } return prev; }, 0); } /** * 获取MSE当前状态,mse.readyState */ public get readyState(): ReadyState { if (this._mediaSource) { return this._mediaSource.readyState; } return 'closed'; } /** * 更新souceBuffer,清理或填充 */ private _update(type: string): void { if (this.hasCleanUpTask(type)) { this._cleanUp(type); } this._doAppend(type); } /** * 执行清理任务 * @param type video|audio|audiovideo */ private _cleanUp(type: string): void { let range = this._cleanUpTask[type]; while (range && range.length) { const item = range[0]; if (this._cleanUpRange(type, item)) { range.shift(); } else { return; } } this.refresh(); } }
the_stack
import '@polymer/iron-icon/iron-icon'; import '../gr-avatar/gr-avatar'; import '../gr-hovercard-account/gr-hovercard-account'; import {getAppContext} from '../../../services/app-context'; import {getDisplayName} from '../../../utils/display-name-util'; import {isSelf, isServiceUser} from '../../../utils/account-util'; import {ChangeInfo, AccountInfo, ServerInfo} from '../../../types/common'; import {hasOwnProperty} from '../../../utils/common-util'; import {fireEvent} from '../../../utils/event-util'; import {isInvolved} from '../../../utils/change-util'; import {ShowAlertEventDetail} from '../../../types/events'; import {LitElement, css, html} from 'lit'; import {customElement, property, state} from 'lit/decorators'; import {classMap} from 'lit/directives/class-map'; import {modifierPressed} from '../../../utils/dom-util'; import {getRemovedByIconClickReason} from '../../../utils/attention-set-util'; @customElement('gr-account-label') export class GrAccountLabel extends LitElement { @property({type: Object}) account?: AccountInfo; @property({type: Object}) _selfAccount?: AccountInfo; /** * Optional ChangeInfo object, typically comes from the change page or * from a row in a list of search results. This is needed for some change * related features like adding the user as a reviewer. */ @property({type: Object}) change?: ChangeInfo; @property({type: String}) voteableText?: string; /** * Should this user be considered to be in the attention set, regardless * of the current state of the change object? */ @property({type: Boolean}) forceAttention = false; /** * Only show the first name in the account label. */ @property({type: Boolean}) firstName = false; /** * Should attention set related features be shown in the component? Note * that the information whether the user is in the attention set or not is * part of the ChangeInfo object in the change property. */ @property({type: Boolean}) highlightAttention = false; @property({type: Boolean}) hideHovercard = false; @property({type: Boolean}) hideAvatar = false; @property({ type: Boolean, reflect: true, }) cancelLeftPadding = false; @property({type: Boolean}) hideStatus = false; @state() _config?: ServerInfo; @property({type: Boolean, reflect: true}) selectionChipStyle = false; @property({ type: Boolean, reflect: true, }) selected = false; @property({type: Boolean, reflect: true}) deselected = false; readonly reporting = getAppContext().reportingService; private readonly restApiService = getAppContext().restApiService; static override get styles() { return [ css` :host { display: inline-block; vertical-align: top; position: relative; border-radius: var(--label-border-radius); box-sizing: border-box; white-space: nowrap; padding: 0 var(--account-label-padding-horizontal, 0); } /* If the first element is the avatar, then we cancel the left padding, so we can fit nicely into the gr-account-chip rounding. The obvious alternative of 'chip has padding' and 'avatar gets negative margin' does not work, because we need 'overflow:hidden' on the label. */ :host([cancelLeftPadding]) { padding-left: 0; } :host::after { content: var(--account-label-suffix); } :host([deselected][selectionChipStyle]) { background-color: var(--background-color-primary); border: 1px solid var(--comment-separator-color); border-radius: 8px; color: var(--deemphasized-text-color); } :host([selected][selectionChipStyle]) { background-color: var(--chip-selected-background-color); border: 1px solid var(--chip-selected-background-color); border-radius: 8px; color: var(--chip-selected-text-color); } :host([selected]) iron-icon.attention { color: var(--chip-selected-text-color); } gr-avatar { height: calc(var(--line-height-normal) - 2px); width: calc(var(--line-height-normal) - 2px); vertical-align: top; position: relative; top: 1px; } #attentionButton { /* This negates the 4px horizontal padding, which we appreciate as a larger click target, but which we don't want to consume space. :-) */ margin: 0 -4px 0 -4px; vertical-align: top; } iron-icon.attention { color: var(--deemphasized-text-color); width: 12px; height: 12px; vertical-align: top; } iron-icon.status { color: var(--deemphasized-text-color); width: 14px; height: 14px; vertical-align: top; position: relative; top: 2px; } .name { display: inline-block; text-decoration: inherit; vertical-align: top; overflow: hidden; text-overflow: ellipsis; max-width: var(--account-max-length, 180px); } .hasAttention .name { font-weight: var(--font-weight-bold); } `, ]; } override render() { const {account, change, highlightAttention, forceAttention, _config} = this; if (!account) return; const hasAttention = forceAttention || this._hasUnforcedAttention(highlightAttention, account, change); this.deselected = !this.selected; const hasAvatars = !!_config?.plugin?.has_avatars; this.cancelLeftPadding = !this.hideAvatar && !hasAttention && hasAvatars; return html`<span> ${!this.hideHovercard ? html`<gr-hovercard-account for="hovercardTarget" .account=${account} .change=${change} .highlightAttention=${highlightAttention} .voteableText=${this.voteableText} ></gr-hovercard-account>` : ''} ${hasAttention ? html` <gr-tooltip-content ?has-tooltip=${this._computeAttentionButtonEnabled( highlightAttention, account, change, false, this._selfAccount )} title="${this._computeAttentionIconTitle( highlightAttention, account, change, forceAttention, this.selected, this._selfAccount )}" > <gr-button id="attentionButton" link="" aria-label="Remove user from attention set" @click=${this._handleRemoveAttentionClick} ?disabled=${!this._computeAttentionButtonEnabled( highlightAttention, account, change, this.selected, this._selfAccount )} ><iron-icon class="attention" icon="gr-icons:attention" ></iron-icon> </gr-button> </gr-tooltip-content>` : ''} </span> <span id="hovercardTarget" tabindex="0" @keydown="${(e: KeyboardEvent) => this.handleKeyDown(e)}" class="${classMap({ hasAttention: !!hasAttention, })}" > ${!this.hideAvatar ? html`<gr-avatar .account="${account}" imageSize="32"></gr-avatar>` : ''} <span class="text" part="gr-account-label-text"> <span class="name" >${this._computeName(account, this.firstName, this._config)}</span > ${!this.hideStatus && account.status ? html`<iron-icon class="status" icon="gr-icons:unavailable" ></iron-icon>` : ''} </span> </span>`; } constructor() { super(); this.restApiService.getConfig().then(config => { this._config = config; }); this.restApiService.getAccount().then(account => { this._selfAccount = account; }); this.addEventListener('attention-set-updated', () => { // For re-evaluation of everything that depends on 'change'. if (this.change) this.change = {...this.change}; }); } handleKeyDown(e: KeyboardEvent) { if (modifierPressed(e)) return; // Only react to `return` and `space`. if (e.keyCode !== 13 && e.keyCode !== 32) return; e.preventDefault(); e.stopPropagation(); this.dispatchEvent(new Event('click')); } _isAttentionSetEnabled( highlight: boolean, account: AccountInfo, change?: ChangeInfo ) { return highlight && !!change && !!account && !isServiceUser(account); } _hasUnforcedAttention( highlight: boolean, account: AccountInfo, change?: ChangeInfo ) { return ( this._isAttentionSetEnabled(highlight, account, change) && change && change.attention_set && !!account._account_id && hasOwnProperty(change.attention_set, account._account_id) ); } _computeName( account?: AccountInfo, firstName?: boolean, config?: ServerInfo ) { return getDisplayName(config, account, firstName); } _handleRemoveAttentionClick(e: MouseEvent) { if (!this.account || !this.change) return; if (this.selected) return; e.preventDefault(); e.stopPropagation(); if (!this.account._account_id) return; this.dispatchEvent( new CustomEvent<ShowAlertEventDetail>('show-alert', { detail: { message: 'Saving attention set update ...', dismissOnNavigation: true, }, composed: true, bubbles: true, }) ); // We are deliberately updating the UI before making the API call. It is a // risk that we are taking to achieve a better UX for 99.9% of the cases. const reason = getRemovedByIconClickReason(this._selfAccount, this._config); if (this.change.attention_set) delete this.change.attention_set[this.account._account_id]; // For re-evaluation of everything that depends on 'change'. this.change = {...this.change}; this.reporting.reportInteraction( 'attention-icon-remove', this._reportingDetails() ); this.restApiService .removeFromAttentionSet( this.change._number, this.account._account_id, reason ) .then(() => { fireEvent(this, 'hide-alert'); }); } _reportingDetails() { if (!this.account) return; const targetId = this.account._account_id; const ownerId = (this.change && this.change.owner && this.change.owner._account_id) || -1; const selfId = this._selfAccount?._account_id || -1; const reviewers = this.change && this.change.reviewers && this.change.reviewers.REVIEWER ? [...this.change.reviewers.REVIEWER] : []; const reviewerIds = reviewers .map(r => r._account_id) .filter(rId => rId !== ownerId); return { actionByOwner: selfId === ownerId, actionByReviewer: selfId !== -1 && reviewerIds.includes(selfId), targetIsOwner: targetId === ownerId, targetIsReviewer: reviewerIds.includes(targetId), targetIsSelf: targetId === selfId, }; } _computeAttentionButtonEnabled( highlight: boolean, account: AccountInfo, change: ChangeInfo | undefined, selected: boolean, selfAccount?: AccountInfo ) { if (selected) return true; return ( !!this._hasUnforcedAttention(highlight, account, change) && (isInvolved(change, selfAccount) || isSelf(account, selfAccount)) ); } _computeAttentionIconTitle( highlight: boolean, account: AccountInfo, change: ChangeInfo | undefined, force: boolean, selected: boolean, selfAccount?: AccountInfo ) { const enabled = this._computeAttentionButtonEnabled( highlight, account, change, selected, selfAccount ); return enabled ? 'Click to remove the user from the attention set' : force ? 'Disabled. Use "Modify" to make changes.' : 'Disabled. Only involved users can change.'; } } declare global { interface HTMLElementTagNameMap { 'gr-account-label': GrAccountLabel; } }
the_stack
'use strict' import { NightwatchBrowser } from 'nightwatch' import init from '../helpers/init' module.exports = { before: function (browser: NightwatchBrowser, done: VoidFunction) { init(browser, done, 'http://127.0.0.1:8080', true) }, 'Should zoom in editor #group1': function (browser: NightwatchBrowser) { browser.waitForElementVisible('div[data-id="mainPanelPluginsContainer"]') .clickLaunchIcon('filePanel') .waitForElementVisible('div[data-id="filePanelFileExplorerTree"]') .openFile('contracts') .openFile('contracts/1_Storage.sol') .waitForElementVisible('#editorView') .checkElementStyle('.view-lines', 'font-size', '14px') .click('*[data-id="tabProxyZoomIn"]') .click('*[data-id="tabProxyZoomIn"]') .checkElementStyle('.view-lines', 'font-size', '16px') }, 'Should zoom out editor #group1': function (browser: NightwatchBrowser) { browser.waitForElementVisible('#editorView') .checkElementStyle('.view-lines', 'font-size', '16px') .click('*[data-id="tabProxyZoomOut"]') .click('*[data-id="tabProxyZoomOut"]') .checkElementStyle('.view-lines', 'font-size', '14px') }, 'Should display compile error in editor #group1': function (browser: NightwatchBrowser) { browser.waitForElementVisible('#editorView') .setEditorValue(storageContractWithError + 'error') .pause(2000) .waitForElementVisible('.margin-view-overlays .fa-exclamation-square', 120000) .checkAnnotations('fa-exclamation-square', 29) // error .clickLaunchIcon('udapp') .checkAnnotationsNotPresent('fa-exclamation-square') // error .clickLaunchIcon('solidity') .checkAnnotations('fa-exclamation-square', 29) // error }, 'Should minimize and maximize codeblock in editor #group1': '' + function (browser: NightwatchBrowser) { browser.waitForElementVisible('#editorView') .waitForElementVisible('.ace_open') .click('.ace_start:nth-of-type(1)') .waitForElementVisible('.ace_closed') .click('.ace_start:nth-of-type(1)') .waitForElementVisible('.ace_open') }, 'Should add breakpoint to editor #group1': function (browser: NightwatchBrowser) { browser.waitForElementVisible('#editorView') .waitForElementNotPresent('.margin-view-overlays .fa-circle') .execute(() => { (window as any).addRemixBreakpoint(1) }, [], () => {}) .waitForElementVisible('.margin-view-overlays .fa-circle') }, 'Should load syntax highlighter for ace light theme #group1': '' + function (browser: NightwatchBrowser) { browser.waitForElementVisible('#editorView') .checkElementStyle('.ace_keyword', 'color', aceThemes.light.keyword) .checkElementStyle('.ace_comment.ace_doc', 'color', aceThemes.light.comment) .checkElementStyle('.ace_function', 'color', aceThemes.light.function) .checkElementStyle('.ace_variable', 'color', aceThemes.light.variable) }, 'Should load syntax highlighter for ace dark theme #group1': '' + function (browser: NightwatchBrowser) { browser.waitForElementVisible('*[data-id="verticalIconsKindsettings"]') .click('*[data-id="verticalIconsKindsettings"]') .waitForElementVisible('*[data-id="settingsTabThemeLabelDark"]') .click('*[data-id="settingsTabThemeLabelDark"]') .pause(2000) .waitForElementVisible('#editorView') /* @todo(#2863) ch for class and not colors .checkElementStyle('.ace_keyword', 'color', aceThemes.dark.keyword) .checkElementStyle('.ace_comment.ace_doc', 'color', aceThemes.dark.comment) .checkElementStyle('.ace_function', 'color', aceThemes.dark.function) .checkElementStyle('.ace_variable', 'color', aceThemes.dark.variable) */ }, 'Should highlight source code #group1': function (browser: NightwatchBrowser) { // include all files here because switching between plugins in side-panel removes highlight browser .addFile('sourcehighlight.js', sourcehighlightScript) .addFile('removeAllSourcehighlightScript.js', removeAllSourcehighlightScript) .openFile('sourcehighlight.js') .executeScript('remix.exeCurrent()') .scrollToLine(32) .waitForElementPresent('.highlightLine33', 60000) .checkElementStyle('.highlightLine33', 'background-color', 'rgb(52, 152, 219)') .scrollToLine(40) .waitForElementPresent('.highlightLine41', 60000) .checkElementStyle('.highlightLine41', 'background-color', 'rgb(52, 152, 219)') .scrollToLine(50) .waitForElementPresent('.highlightLine51', 60000) .checkElementStyle('.highlightLine51', 'background-color', 'rgb(52, 152, 219)') }, 'Should remove 1 highlight from source code #group1': '' + function (browser: NightwatchBrowser) { browser.waitForElementVisible('li[data-id="treeViewLitreeViewItemremoveSourcehighlightScript.js"]') .click('li[data-id="treeViewLitreeViewItemremoveSourcehighlightScript.js"]') .pause(2000) .executeScript('remix.exeCurrent()') .waitForElementVisible('li[data-id="treeViewLitreeViewItemcontracts"]') .click('li[data-id="treeViewLitreeViewItemcontracts"]') .waitForElementVisible('li[data-id="treeViewLitreeViewItemcontracts/3_Ballot.sol"]') .click('li[data-id="treeViewLitreeViewItemcontracts/3_Ballot.sol"]') .waitForElementNotPresent('.highlightLine33', 60000) .checkElementStyle('.highlightLine41', 'background-color', 'rgb(52, 152, 219)') .checkElementStyle('.highlightLine51', 'background-color', 'rgb(52, 152, 219)') }, 'Should remove all highlights from source code #group1': function (browser: NightwatchBrowser) { browser.waitForElementVisible('li[data-id="treeViewLitreeViewItemremoveAllSourcehighlightScript.js"]') .click('li[data-id="treeViewLitreeViewItemremoveAllSourcehighlightScript.js"]') .pause(2000) .executeScript('remix.exeCurrent()') .waitForElementVisible('li[data-id="treeViewLitreeViewItemcontracts/3_Ballot.sol"]') .click('li[data-id="treeViewLitreeViewItemcontracts/3_Ballot.sol"]') .pause(2000) .waitForElementNotPresent('.highlightLine33', 60000) .waitForElementNotPresent('.highlightLine41', 60000) .waitForElementNotPresent('.highlightLine51', 60000) }, 'Should display the context view #group2': function (browser: NightwatchBrowser) { browser .openFile('contracts') .openFile('contracts/1_Storage.sol') .waitForElementVisible('#editorView') .setEditorValue(storageContractWithError) .pause(2000) .execute(() => { (document.getElementById('editorView') as any).gotoLine(17, 16) }, [], () => {}) .waitForElementVisible('.contextview') .waitForElementContainsText('.contextview .type', 'FunctionDefinition') .waitForElementContainsText('.contextview .name', 'store') .execute(() => { (document.getElementById('editorView') as any).gotoLine(18, 12) }, [], () => {}) .waitForElementContainsText('.contextview .type', 'uint256') .waitForElementContainsText('.contextview .name', 'number') .click('.contextview [data-action="previous"]') // declaration .execute(() => { return (document.getElementById('editorView') as any).getCursorPosition() }, [], (result) => { console.log('result', result) browser.assert.equal(result.value, '180') }) .click('.contextview [data-action="next"]') // back to the initial state .execute(() => { return (document.getElementById('editorView') as any).getCursorPosition() }, [], (result) => { console.log('result', result) browser.assert.equal(result.value, '323') }) .click('.contextview [data-action="next"]') // next reference .execute(() => { return (document.getElementById('editorView') as any).getCursorPosition() }, [], (result) => { console.log('result', result) browser.assert.equal(result.value, '489') }) .click('.contextview [data-action="gotoref"]') // back to the declaration .execute(() => { return (document.getElementById('editorView') as any).getCursorPosition() }, [], (result) => { console.log('result', result) browser.assert.equal(result.value, '180') }) .end() } } const aceThemes = { light: { keyword: 'rgb(147, 15, 128)', comment: 'rgb(35, 110, 36)', function: 'rgb(0, 0, 162)', variable: 'rgb(253, 151, 31)' }, dark: { keyword: 'rgb(0, 105, 143)', comment: 'rgb(85, 85, 85)', function: 'rgb(0, 174, 239)', variable: 'rgb(153, 119, 68)' } } const sourcehighlightScript = { content: ` (async () => { try { await remix.call('fileManager', 'open', 'contracts/3_Ballot.sol') const pos = { start: { line: 32, column: 3 }, end: { line: 32, column: 20 } } await remix.call('editor', 'highlight', pos, 'contracts/3_Ballot.sol') const pos2 = { start: { line: 40, column: 3 }, end: { line: 40, column: 20 } } await remix.call('editor', 'highlight', pos2, 'contracts/3_Ballot.sol') const pos3 = { start: { line: 50, column: 3 }, end: { line: 50, column: 20 } } await remix.call('editor', 'highlight', pos3, 'contracts/3_Ballot.sol') } catch (e) { console.log(e.message) } })() ` } const removeAllSourcehighlightScript = { content: ` (async () => { try { await remix.call('editor', 'discardHighlight') } catch (e) { console.log(e.message) } })() ` } const storageContractWithError = ` // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; /** * @title Storage * @dev Store & retrieve value in a variable */ contract Storage { uint256 number; /** * @dev Store value in variable * @param num value to store */ function store(uint256 num) public { number = num; } /** * @dev Return value * @return value of 'number' */ function retrieve() public view returns (uint256){ return number; } }`
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type OrderHistoryRowTestsQueryVariables = {}; export type OrderHistoryRowTestsQueryResponse = { readonly commerceOrder: { readonly " $fragmentRefs": FragmentRefs<"OrderHistoryRow_order">; } | null; }; export type OrderHistoryRowTestsQuery = { readonly response: OrderHistoryRowTestsQueryResponse; readonly variables: OrderHistoryRowTestsQueryVariables; }; /* query OrderHistoryRowTestsQuery { commerceOrder(id: "some-id") { __typename ...OrderHistoryRow_order id } } fragment OrderHistoryRow_order on CommerceOrder { __isCommerceOrder: __typename internalID state mode buyerTotal(precision: 2) createdAt itemsTotal lineItems(first: 1) { edges { node { shipment { status trackingUrl trackingNumber id } artwork { image { resized(width: 55) { url } } partner { name id } title artistNames id } fulfillments(first: 1) { edges { node { trackingId id } } } id } } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "some-id" } ], v1 = [ { "kind": "Literal", "name": "first", "value": 1 } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v3 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v4 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v5 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "OrderHistoryRowTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "commerceOrder", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "OrderHistoryRow_order" } ], "storageKey": "commerceOrder(id:\"some-id\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "OrderHistoryRowTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "commerceOrder", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, { "kind": "TypeDiscriminator", "abstractKey": "__isCommerceOrder" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "state", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "mode", "storageKey": null }, { "alias": null, "args": [ { "kind": "Literal", "name": "precision", "value": 2 } ], "kind": "ScalarField", "name": "buyerTotal", "storageKey": "buyerTotal(precision:2)" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "createdAt", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "itemsTotal", "storageKey": null }, { "alias": null, "args": (v1/*: any*/), "concreteType": "CommerceLineItemConnection", "kind": "LinkedField", "name": "lineItems", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItemEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItem", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceShipment", "kind": "LinkedField", "name": "shipment", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "status", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingUrl", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingNumber", "storageKey": null }, (v2/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "width", "value": 55 } ], "concreteType": "ResizedImageUrl", "kind": "LinkedField", "name": "resized", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "url", "storageKey": null } ], "storageKey": "resized(width:55)" } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, (v2/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, (v2/*: any*/) ], "storageKey": null }, { "alias": null, "args": (v1/*: any*/), "concreteType": "CommerceFulfillmentConnection", "kind": "LinkedField", "name": "fulfillments", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceFulfillmentEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceFulfillment", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingId", "storageKey": null }, (v2/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "fulfillments(first:1)" }, (v2/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "lineItems(first:1)" }, (v2/*: any*/) ], "storageKey": "commerceOrder(id:\"some-id\")" } ] }, "params": { "id": "6960e567aafda7be0d3650d8f26990ed", "metadata": { "relayTestingSelectionTypeInfo": { "commerceOrder": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceOrder" }, "commerceOrder.__isCommerceOrder": (v3/*: any*/), "commerceOrder.__typename": (v3/*: any*/), "commerceOrder.buyerTotal": (v4/*: any*/), "commerceOrder.createdAt": (v3/*: any*/), "commerceOrder.id": (v5/*: any*/), "commerceOrder.internalID": (v5/*: any*/), "commerceOrder.itemsTotal": (v4/*: any*/), "commerceOrder.lineItems": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceLineItemConnection" }, "commerceOrder.lineItems.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "CommerceLineItemEdge" }, "commerceOrder.lineItems.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceLineItem" }, "commerceOrder.lineItems.edges.node.artwork": { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, "commerceOrder.lineItems.edges.node.artwork.artistNames": (v4/*: any*/), "commerceOrder.lineItems.edges.node.artwork.id": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.image": { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, "commerceOrder.lineItems.edges.node.artwork.image.resized": { "enumValues": null, "nullable": true, "plural": false, "type": "ResizedImageUrl" }, "commerceOrder.lineItems.edges.node.artwork.image.resized.url": (v3/*: any*/), "commerceOrder.lineItems.edges.node.artwork.partner": { "enumValues": null, "nullable": true, "plural": false, "type": "Partner" }, "commerceOrder.lineItems.edges.node.artwork.partner.id": (v5/*: any*/), "commerceOrder.lineItems.edges.node.artwork.partner.name": (v4/*: any*/), "commerceOrder.lineItems.edges.node.artwork.title": (v4/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceFulfillmentConnection" }, "commerceOrder.lineItems.edges.node.fulfillments.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "CommerceFulfillmentEdge" }, "commerceOrder.lineItems.edges.node.fulfillments.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceFulfillment" }, "commerceOrder.lineItems.edges.node.fulfillments.edges.node.id": (v5/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments.edges.node.trackingId": (v4/*: any*/), "commerceOrder.lineItems.edges.node.id": (v5/*: any*/), "commerceOrder.lineItems.edges.node.shipment": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceShipment" }, "commerceOrder.lineItems.edges.node.shipment.id": (v5/*: any*/), "commerceOrder.lineItems.edges.node.shipment.status": (v4/*: any*/), "commerceOrder.lineItems.edges.node.shipment.trackingNumber": (v4/*: any*/), "commerceOrder.lineItems.edges.node.shipment.trackingUrl": (v4/*: any*/), "commerceOrder.mode": { "enumValues": [ "BUY", "OFFER" ], "nullable": true, "plural": false, "type": "CommerceOrderModeEnum" }, "commerceOrder.state": { "enumValues": [ "ABANDONED", "APPROVED", "CANCELED", "FULFILLED", "PENDING", "REFUNDED", "SUBMITTED" ], "nullable": false, "plural": false, "type": "CommerceOrderStateEnum" } } }, "name": "OrderHistoryRowTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '7f6e21bc814b72455b346f818a1d8954'; export default node;
the_stack
import * as Config from '@oclif/config' import {expect, fancy} from 'fancy-test' import Base, {flags} from '../src' import {TestHelpClassConfig} from './helpers/test-help-in-src/src/test-help-plugin' import * as PluginHelp from '@oclif/plugin-help' const originalgetHelpClass = PluginHelp.getHelpClass // const pjson = require('../package.json') class Command extends Base { static description = 'test command' async run() { this.parse() this.log('foo') } } class CodeError extends Error { constructor(private readonly code: string) { super(code) } } describe('command', () => { fancy .stdout() .do(() => Command.run([])) .do(output => expect(output.stdout).to.equal('foo\n')) .it('logs to stdout') fancy .do(async () => { class Command extends Base { static description = 'test command' async run() { return 101 } } expect(await Command.run([])).to.equal(101) }) .it('returns value') fancy .do(() => { class Command extends Base { async run() { throw new Error('new x error') } } return Command.run([]) }) .catch(/new x error/) .it('errors out') fancy .stdout() .do(() => { class Command extends Base { async run() { this.exit(0) } } return Command.run([]) }) .catch(/EEXIT: 0/) .it('exits with 0') describe('convertToCached', () => { fancy // .skip() // .do(async () => { // class C extends Command { // static title = 'cmd title' // static type = 'mytype' // static usage = ['$ usage'] // static description = 'test command' // static aliases = ['alias1', 'alias2'] // static hidden = true // static flags = { // flaga: flags.boolean(), // flagb: flags.string({ // char: 'b', // hidden: true, // required: false, // description: 'flagb desc', // options: ['a', 'b'], // default: () => 'mydefault', // }), // } // static args = [ // { // name: 'arg1', // description: 'arg1 desc', // required: true, // hidden: false, // options: ['af', 'b'], // default: () => 'myadefault', // } // ] // } // const c = Config.Command.toCached(C) // expect(await c.load()).to.have.property('run') // delete c.load // expect(c).to.deep.equal({ // _base: `@oclif/command@${pjson.version}`, // id: 'foo:bar', // type: 'mytype', // hidden: true, // pluginName: undefined, // description: 'test command', // aliases: ['alias1', 'alias2'], // title: 'cmd title', // usage: ['$ usage'], // flags: { // flaga: { // char: undefined, // description: undefined, // name: 'flaga', // hidden: undefined, // required: undefined, // type: 'boolean', // }, // flagb: { // char: 'b', // description: 'flagb desc', // name: 'flagb', // hidden: true, // required: false, // type: 'option', // helpValue: undefined, // default: 'mydefault', // options: ['a', 'b'], // } // }, // args: [ // { // description: 'arg1 desc', // name: 'arg1', // hidden: false, // required: true, // options: ['af', 'b'], // default: 'myadefault', // } // ], // }) // }) .it('converts to cached with everything set') fancy // .skip() .do(async () => { // const c = class extends Command { // }.convertToCached() // expect(await c.load()).to.have.property('run') // delete c.load // expect(c).to.deep.equal({ // _base: `@oclif/command@${pjson.version}`, // id: undefined, // type: undefined, // hidden: undefined, // pluginName: undefined, // description: 'test command', // aliases: [], // title: undefined, // usage: undefined, // flags: {}, // args: [], // }) }) .it('adds plugin name') fancy // .skip() // .do(async () => { // const c = class extends Command { // }.convertToCached({pluginName: 'myplugin'}) // expect(await c.load()).to.have.property('run') // delete c.load // expect(c).to.deep.equal({ // _base: `@oclif/command@${pjson.version}`, // type: undefined, // id: undefined, // hidden: undefined, // pluginName: 'myplugin', // description: 'test command', // aliases: [], // title: undefined, // usage: undefined, // flags: {}, // args: [], // }) // }) .it('converts to cached with nothing set') }) describe('parse', () => { fancy .stdout() .it('has a flag', async ctx => { class CMD extends Base { static flags = { foo: flags.string(), } async run() { const {flags} = this.parse(CMD) this.log(flags.foo) } } await CMD.run(['--foo=bar']) expect(ctx.stdout).to.equal('bar\n') }) }) describe('version', () => { fancy .stdout() .add('config', () => Config.load()) .do(async () => { await Command.run(['--version']) }) .catch(/EEXIT: 0/) .it('shows version', ctx => { expect(ctx.stdout).to.equal(`${ctx.config.userAgent}\n`) }) }) describe('help', () => { fancy .stdout() .do(() => { class CMD extends Command { static flags = {help: flags.help()} } return CMD.run(['--help']) }) .catch(/EEXIT: 0/) .it('--help', ctx => { expect(ctx.stdout).to.equal(`test command USAGE $ @oclif/command OPTIONS --help show CLI help `) }) fancy .stdout() .do(async () => { class CMD extends Command {} await CMD.run(['-h']) }) .catch(/EEXIT: 0/) .it('-h', ctx => { // expect(process.exitCode).to.equal(0) expect(ctx.stdout).to.equal(`test command USAGE $ @oclif/command `) }) fancy .stdout() .add('config', async () => { const config: TestHelpClassConfig = await Config.load() config.pjson.oclif.helpClass = 'help-class-does-not-exist' return config }) .do(async ({config}) => { class CMD extends Command { config = config } await CMD.run(['-h']) }) .catch((error: Error) => expect(error.message).to.contain('Unable to load configured help class "help-class-does-not-exist", failed with message:\n')) .it('shows useful error message when configured help class cannot be loaded') fancy .stdout() .stub(PluginHelp, 'getHelpClass', function (config: any) { return originalgetHelpClass(config, '') }) .add('config', async () => { const config: TestHelpClassConfig = await Config.load() config.pjson.oclif.helpClass = undefined return config }) .do(async ({config}) => { class CMD extends Command { config = config } await CMD.run(['-h']) }) .catch((error: Error) => expect(error.message).to.contain('Could not load a help class, consider installing the @oclif/plugin-help package, failed with message:\n')) .it('shows useful error message when no help class has been configured and the default cannot be loaded') describe('from a help class', () => { fancy .stdout() .stub(PluginHelp, 'getHelpClass', function (config: Config.IConfig) { const patchedConfig = { ...config, root: `${__dirname}/helpers/test-help-in-lib/`, } return originalgetHelpClass(patchedConfig) }) .add('config', async () => { const config: TestHelpClassConfig = await Config.load() config.pjson.oclif.helpClass = './lib/test-help-plugin' return config }) .do(async ({config}) => { class CMD extends Command { static id = 'test-command-for-help-plugin' config = config } await CMD.run(['-h']) }) .catch(/EEXIT: 0/) .it('-h via a plugin in lib dir (compiled to js)', ctx => { expect(ctx.stdout).to.equal('hello from test-help-plugin #showCommandHelp in the lib folder and in compiled javascript\n') expect(ctx.config.showCommandHelpSpy!.getCalls().length).to.equal(1) expect(ctx.config.showHelpSpy!.getCalls().length).to.equal(0) const [Command, Topics] = ctx.config.showCommandHelpSpy!.firstCall.args expect(Command.id).to.deep.equal('test-command-for-help-plugin') expect(Topics).to.be.an('array') }) fancy .stdout() .stub(PluginHelp, 'getHelpClass', function (config: Config.IConfig) { const patchedConfig = { ...config, root: `${__dirname}/helpers/test-help-in-src/`, } return originalgetHelpClass(patchedConfig) }) .add('config', async () => { const config: TestHelpClassConfig = await Config.load() config.pjson.oclif.helpClass = './lib/test-help-plugin' return config }) .do(async ({config}) => { class CMD extends Command { static id = 'test-command-for-help-plugin' config = config } await CMD.run(['-h']) }) .catch(/EEXIT: 0/) .it('-h via a plugin in src dir (source in ts)', ctx => { expect(ctx.stdout).to.equal('hello from test-help-plugin #showCommandHelp\n') expect(ctx.config.showCommandHelpSpy!.getCalls().length).to.equal(1) expect(ctx.config.showHelpSpy!.getCalls().length).to.equal(0) const [Command, Topics] = ctx.config.showCommandHelpSpy!.firstCall.args expect(Command.id).to.deep.equal('test-command-for-help-plugin') expect(Topics).to.be.an('array') }) fancy .stdout() .stub(PluginHelp, 'getHelpClass', function (config: Config.IConfig) { const patchedConfig = { ...config, root: `${__dirname}/helpers/test-help-in-src/`, } return originalgetHelpClass(patchedConfig) }) .add('config', async () => { const config: TestHelpClassConfig = await Config.load() config.pjson.oclif.helpClass = './lib/test-help-plugin' return config }) .do(async ({config}) => { class CMD extends Command { static id = 'test-command-for-help-plugin' config = config static flags = {help: flags.help()} } return CMD.run(['--help']) }) .catch(/EEXIT: 0/) .it('--help via a plugin in src dir (source in ts)', ctx => { expect(ctx.stdout).to.equal('hello from test-help-plugin #showCommandHelp\n') expect(ctx.config.showCommandHelpSpy!.getCalls().length).to.equal(1) expect(ctx.config.showHelpSpy!.getCalls().length).to.equal(0) const [Command, Topics] = ctx.config.showCommandHelpSpy!.firstCall.args expect(Command.id).to.deep.equal('test-command-for-help-plugin') expect(Topics).to.be.an('array') }) }) }) describe('.log()', () => { fancy .stdout() .do(async () => { class CMD extends Command { async run() { this.log('json output: %j', {a: 'foobar'}) } } await CMD.run([]) }) .do(ctx => expect(ctx.stdout).to.equal('json output: {"a":"foobar"}\n')) .it('uses util.format()') }) describe('stdout err', () => { fancy .stdout() .do(async () => { class CMD extends Command { async run() { process.stdout.emit('error', new CodeError('dd')) } } await CMD.run([]) }) .catch(/dd/) .it('test stdout error throws') fancy .stdout() .do(async () => { class CMD extends Command { async run() { process.stdout.emit('error', new CodeError('EPIPE')) this.log('json output: %j', {a: 'foobar'}) } } await CMD.run([]) }) .do(ctx => expect(ctx.stdout).to.equal('json output: {"a":"foobar"}\n')) .it('test stdout EPIPE swallowed') }) })
the_stack
import * as events from 'events'; /** * A standard node.js callback after an asynchronous call with no return value. * @param error - This parameter will be undefined if the call was successful, or an error if not. */ export declare type AsyncCallback = (error: Error | undefined) => void; /** * A standard node.js callback after an asynchronous call with a return value. * @param error - This parameter will be undefined if the call was successful, or an error if not. * @param value - This parameter will be undefined if the call was not successful, or the return value if it was successful. */ export declare type AsyncValueCallback<T = any> = (error: Error | undefined, value: T | undefined) => void; /** * The events that can be raised by the Connection class and the event listener types. */ export declare interface ConnectionEvents { /** * Raised when the connection is closed. * @param hadError - Whether or not it was closed due to an error. */ close: (hadError: boolean) => void; /** * Raised when the connection is ended. */ end: () => void; /** * Raised when an error is encountered. * @param error - The error encountered. */ error: (error: Error) => void; /** * Raised when the connection times out. */ timeout: () => void; /** * Raised by KDB as an update. Includes the table name and typically one more piece of data indicating the updates (though optionally more than one). */ upd: (tableName: string, ...data: any[]) => void; } /** * Class representing the KDB connection. */ export declare class Connection extends events.EventEmitter { /** * A private constructor is used to prevent inheritance. */ private constructor(); /** * Adds an event listener for events of the specified type. * @param type The event type. * @param listener The event listener to add. */ addListener<T extends keyof ConnectionEvents>(type: T, listener: ConnectionEvents[T]): this; /** * Closes this connection. * @param callback Optional callback to be invoked when the close operation has finished. */ close(callback?: () => void): void; /** * Listen to a handle. * @param callback The callback to be invoked when the results are available or an error is to be reported. */ k(callback: AsyncValueCallback): void; /** * Execute a statement synchronously against KDB and return the result when available via the callback. * @param statement The statement to execute against KDB. * @param callback The callback to be invoked when the results are available or an error is to be reported. */ k(statement: string, callback: AsyncValueCallback): void; /** * Execute a statement synchronously against KDB that takes a single parameter and return the result when available via the callback. * @param statement The statement to execute against KDB. * @param parameter The parameter to pass to KDB. * @param callback The callback to be invoked when the results are available or an error is to be reported. */ k(statement: string, parameter: any, callback: AsyncValueCallback): void; /** * Execute a statement synchronously against KDB that takes an arbitrary number of parameters. The last element in the rest array must be an AsyncValueCallback. * @param statement The statement to execute against KDB. * @param parametersEndingInCallback The parameters to pass to KDB, with the last element being the callback to be invoked when the results are available or an error is to be reported. */ k(statement: string, ...parametersEndingInCallback: any[]): void; /** * Execute a statement asynchronously against KDB with no return value, and return a callback indicating the message was received by KDB successfuly. * @param statement The statement to execute against KDB. * @param callback The callback to be invoked when the statement is received by KDB or an error is to be reported. */ ks(statement: string, callback: AsyncCallback): void; /** * Execute a statement asynchronously against KDB with a single parameter and no return value, and return a callback indicating the message was received by KDB successfuly. * @param statement The statement to execute against KDB. * @param callback The callback to be invoked when the statement is received by KDB or an error is to be reported. */ ks(statement: string, parameter: any, callback: AsyncCallback): void; /** * Execute a statement asynchronously against KDB that takes an arbitrary number of parameters and has no return value. The last element in the rest array must be an AsyncCallback. * @param statement The statement to execute against KDB. * @param parametersEndingInCallback The parameters to pass to KDB, with the last element being the callback to be invoked when the statement is received by KDB or an error is to be reported. */ ks(statement: string, ...parametersEndingInCallback: any[]): void; /** * Gets the number of listeners for the specified event type. * @param type The event type. */ listenerCount(type: keyof ConnectionEvents): number; /** * Gets the collection of listeners for the specified event type. * @param type The event type. */ listeners<T extends keyof ConnectionEvents>(type: T): ConnectionEvents[T][]; /** * Adds an event listener for events of the specified type. * @param type The event type. * @param listener The event listener to add. */ on<T extends keyof ConnectionEvents>(type: T, listener: ConnectionEvents[T]): this; /** * Adds an event listener for only the next time an event of the specified type is invoked. * @param type The event type. * @param listener The event listener to add. */ once<T extends keyof ConnectionEvents>(type: T, listener: ConnectionEvents[T]): this; /** * Adds an event listener for events of the specified type, but add it at the beginning of the collection of listeners for the event type. * @param type The event type. * @param listener The event listener to add. */ prependListener<T extends keyof ConnectionEvents>(type: T, listener: ConnectionEvents[T]): this; /** * Adds an event listener for only the next time events of the specified type are raised, but add it at the beginning of the collection of listeners for the event type. * @param type The event type. * @param listener The event listener to add. */ prependOnceListener<T extends keyof ConnectionEvents>(type: T, listener: ConnectionEvents[T]): this; /** * Removes all listeners from all events. */ removeAllListeners(): this; /** * Removes all listeners from the specified event type. * @param type The event type. */ removeAllListeners(type: keyof ConnectionEvents): this; /** * Removes the specified listener from the collection of listeners associated with the type. * @param type The event type. * @param listener The listener to remove. */ removeListener<T extends keyof ConnectionEvents>(type: T, listener: ConnectionEvents[T]): this; } /** * Connection parameters. */ export declare interface ConnectionParameters { /** * The KDB host to connect to. */ host?: string; /** * The port on the KDB host to connect to. */ port?: number; /** * Optional - The user to authenticate as to KDB. */ user?: string; /** * Optional - The password to use to authenticate to KDB. */ password?: string; /** * Set the socket to no-delay. See https://nodejs.org/api/net.html#net_socket_setnodelay_nodelay */ socketNoDelay?: boolean; /** * Sets the socket to timeout after the number of milliseconds of inactivity. See https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback */ socketTimeout?: number; /** * Should this connection convert KDB nanoseconds to JavaScript Date objects (defaults to true). */ nanos2date?: boolean; /** * Should this connection flip tables (defaults to true). */ flipTables?: boolean; /** * Should this connection convert empty char fields to null (defaults to true). */ emptyChar2null?: boolean; /** * Should this connection convert KDB longs to JavaScript Number types (defaults to true). * Specifying false will cause KDB longs to be returned using long.js. */ long2number?: boolean; /** * Connect with Unix Domain Sockets rather than TCP */ unixSocket?: string; } /** * Attempt to connect to KDB using the specified connection parameters, and return the connection when it is established. * @param parameters The connection parameters. * @param callback Callback to be invoked when the connection is (or fails to be) established. */ export declare function connect(parameters: ConnectionParameters, callback: AsyncValueCallback<Connection>): void; /** * Attempt to connect to an unauthenticated KDB instance using the specified host and port, and return the connection when it is established. * @param host The KDB host to connect to. * @param port The port on the host to connect to. * @param callback Callback to be invoked when the connection is (or fails to be) established. */ export declare function connect(host: string, port: number, callback: AsyncValueCallback<Connection>): void; /** * Attempt to connect to a KDB instance using the specified host, port, username and password, and return the connection when it is established. * @param host The KDB host to connect to. * @param port The port on the host to connect to. * @param user The user to authenticate to KDB with. * @param password The password to use to authenticate to KDB. * @param callback Callback to be invoked when the connection is (or fails to be) established. */ export declare function connect(host: string, port: number, user: string, password: string, callback: AsyncValueCallback<Connection>): void; /** * Attempt to connect to KDB using Unix Domain Sockets, and return the connection when it is established. * @param unixSocket Path to KDB Unix Domain Socket (Doesn't support abstract namespace sockets: KDB3.5+ on Linux) * @param callback Callback to be invoked when the connection is (or fails to be) established. */ export declare function connect(unixSocket: string, callback: AsyncValueCallback<Connection>): void; /** * Brings in the Typed wrapper APIs. */ export * from './lib/typed';
the_stack
import {InfluxDB} from '@influxdata/influxdb-client' import {APIBase, RequestOptions} from '../APIBase' import { AddResourceMemberRequestBody, LabelMapping, LabelResponse, LabelsResponse, Logs, ResourceMember, ResourceMembers, ResourceOwner, ResourceOwners, Run, RunManually, Runs, Task, TaskCreateRequest, TaskUpdateRequest, Tasks, } from './types' export interface GetTasksIDRequest { /** The task ID. */ taskID: string } export interface PatchTasksIDRequest { /** The task ID. */ taskID: string /** Task update to apply */ body: TaskUpdateRequest } export interface DeleteTasksIDRequest { /** The ID of the task to delete. */ taskID: string } export interface GetTasksIDRunsRequest { /** The ID of the task to get runs for. */ taskID: string /** Returns runs after a specific ID. */ after?: string /** The number of runs to return */ limit?: number /** Filter runs to those scheduled after this time, RFC3339 */ afterTime?: string /** Filter runs to those scheduled before this time, RFC3339 */ beforeTime?: string } export interface PostTasksIDRunsRequest { taskID: string /** entity body */ body: RunManually } export interface GetTasksIDRunsIDRequest { /** The task ID. */ taskID: string /** The run ID. */ runID: string } export interface DeleteTasksIDRunsIDRequest { /** The task ID. */ taskID: string /** The run ID. */ runID: string } export interface PostTasksIDRunsIDRetryRequest { /** The task ID. */ taskID: string /** The run ID. */ runID: string /** entity body */ body: any } export interface GetTasksIDLogsRequest { /** The task ID. */ taskID: string } export interface GetTasksIDRunsIDLogsRequest { /** ID of task to get logs for. */ taskID: string /** ID of run to get logs for. */ runID: string } export interface GetTasksIDLabelsRequest { /** The task ID. */ taskID: string } export interface PostTasksIDLabelsRequest { /** The task ID. */ taskID: string /** Label to add */ body: LabelMapping } export interface DeleteTasksIDLabelsIDRequest { /** The task ID. */ taskID: string /** The label ID. */ labelID: string } export interface GetTasksIDMembersRequest { /** The task ID. */ taskID: string } export interface PostTasksIDMembersRequest { /** The task ID. */ taskID: string /** User to add as member */ body: AddResourceMemberRequestBody } export interface DeleteTasksIDMembersIDRequest { /** The ID of the member to remove. */ userID: string /** The task ID. */ taskID: string } export interface GetTasksIDOwnersRequest { /** The task ID. */ taskID: string } export interface PostTasksIDOwnersRequest { /** The task ID. */ taskID: string /** User to add as owner */ body: AddResourceMemberRequestBody } export interface DeleteTasksIDOwnersIDRequest { /** The ID of the owner to remove. */ userID: string /** The task ID. */ taskID: string } export interface GetTasksRequest { /** Returns task with a specific name. */ name?: string /** Return tasks after a specified ID. */ after?: string /** Filter tasks to a specific user ID. */ user?: string /** Filter tasks to a specific organization name. */ org?: string /** Filter tasks to a specific organization ID. */ orgID?: string /** Filter tasks by a status--"inactive" or "active". */ status?: string /** The number of tasks to return */ limit?: number /** Type of task, unset by default. */ type?: string } export interface PostTasksRequest { /** Task to create */ body: TaskCreateRequest } /** * Tasks API */ export class TasksAPI { // internal private base: APIBase /** * Creates TasksAPI * @param influxDB - an instance that knows how to communicate with InfluxDB server */ constructor(influxDB: InfluxDB) { this.base = new APIBase(influxDB) } /** * Retrieve a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasksID } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasksID( request: GetTasksIDRequest, requestOptions?: RequestOptions ): Promise<Task> { return this.base.request( 'GET', `/api/v2/tasks/${request.taskID}`, request, requestOptions ) } /** * Update a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/PatchTasksID } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ patchTasksID( request: PatchTasksIDRequest, requestOptions?: RequestOptions ): Promise<Task> { return this.base.request( 'PATCH', `/api/v2/tasks/${request.taskID}`, request, requestOptions, 'application/json' ) } /** * Delete a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/DeleteTasksID } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ deleteTasksID( request: DeleteTasksIDRequest, requestOptions?: RequestOptions ): Promise<void> { return this.base.request( 'DELETE', `/api/v2/tasks/${request.taskID}`, request, requestOptions ) } /** * List runs for a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasksIDRuns } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasksIDRuns( request: GetTasksIDRunsRequest, requestOptions?: RequestOptions ): Promise<Runs> { return this.base.request( 'GET', `/api/v2/tasks/${request.taskID}/runs${this.base.queryString(request, [ 'after', 'limit', 'afterTime', 'beforeTime', ])}`, request, requestOptions ) } /** * Manually start a task run, overriding the current schedule. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/PostTasksIDRuns } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ postTasksIDRuns( request: PostTasksIDRunsRequest, requestOptions?: RequestOptions ): Promise<Run> { return this.base.request( 'POST', `/api/v2/tasks/${request.taskID}/runs`, request, requestOptions, 'application/json' ) } /** * Retrieve a single run for a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasksIDRunsID } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasksIDRunsID( request: GetTasksIDRunsIDRequest, requestOptions?: RequestOptions ): Promise<Run> { return this.base.request( 'GET', `/api/v2/tasks/${request.taskID}/runs/${request.runID}`, request, requestOptions ) } /** * Cancel a running task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/DeleteTasksIDRunsID } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ deleteTasksIDRunsID( request: DeleteTasksIDRunsIDRequest, requestOptions?: RequestOptions ): Promise<void> { return this.base.request( 'DELETE', `/api/v2/tasks/${request.taskID}/runs/${request.runID}`, request, requestOptions ) } /** * Retry a task run. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/PostTasksIDRunsIDRetry } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ postTasksIDRunsIDRetry( request: PostTasksIDRunsIDRetryRequest, requestOptions?: RequestOptions ): Promise<Run> { return this.base.request( 'POST', `/api/v2/tasks/${request.taskID}/runs/${request.runID}/retry`, request, requestOptions, 'application/json; charset=utf-8' ) } /** * Retrieve all logs for a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasksIDLogs } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasksIDLogs( request: GetTasksIDLogsRequest, requestOptions?: RequestOptions ): Promise<Logs> { return this.base.request( 'GET', `/api/v2/tasks/${request.taskID}/logs`, request, requestOptions ) } /** * Retrieve all logs for a run. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasksIDRunsIDLogs } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasksIDRunsIDLogs( request: GetTasksIDRunsIDLogsRequest, requestOptions?: RequestOptions ): Promise<Logs> { return this.base.request( 'GET', `/api/v2/tasks/${request.taskID}/runs/${request.runID}/logs`, request, requestOptions ) } /** * List all labels for a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasksIDLabels } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasksIDLabels( request: GetTasksIDLabelsRequest, requestOptions?: RequestOptions ): Promise<LabelsResponse> { return this.base.request( 'GET', `/api/v2/tasks/${request.taskID}/labels`, request, requestOptions ) } /** * Add a label to a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/PostTasksIDLabels } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ postTasksIDLabels( request: PostTasksIDLabelsRequest, requestOptions?: RequestOptions ): Promise<LabelResponse> { return this.base.request( 'POST', `/api/v2/tasks/${request.taskID}/labels`, request, requestOptions, 'application/json' ) } /** * Delete a label from a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/DeleteTasksIDLabelsID } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ deleteTasksIDLabelsID( request: DeleteTasksIDLabelsIDRequest, requestOptions?: RequestOptions ): Promise<void> { return this.base.request( 'DELETE', `/api/v2/tasks/${request.taskID}/labels/${request.labelID}`, request, requestOptions ) } /** * List all task members. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasksIDMembers } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasksIDMembers( request: GetTasksIDMembersRequest, requestOptions?: RequestOptions ): Promise<ResourceMembers> { return this.base.request( 'GET', `/api/v2/tasks/${request.taskID}/members`, request, requestOptions ) } /** * Add a member to a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/PostTasksIDMembers } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ postTasksIDMembers( request: PostTasksIDMembersRequest, requestOptions?: RequestOptions ): Promise<ResourceMember> { return this.base.request( 'POST', `/api/v2/tasks/${request.taskID}/members`, request, requestOptions, 'application/json' ) } /** * Remove a member from a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/DeleteTasksIDMembersID } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ deleteTasksIDMembersID( request: DeleteTasksIDMembersIDRequest, requestOptions?: RequestOptions ): Promise<void> { return this.base.request( 'DELETE', `/api/v2/tasks/${request.taskID}/members/${request.userID}`, request, requestOptions ) } /** * List all owners of a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasksIDOwners } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasksIDOwners( request: GetTasksIDOwnersRequest, requestOptions?: RequestOptions ): Promise<ResourceOwners> { return this.base.request( 'GET', `/api/v2/tasks/${request.taskID}/owners`, request, requestOptions ) } /** * Add an owner to a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/PostTasksIDOwners } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ postTasksIDOwners( request: PostTasksIDOwnersRequest, requestOptions?: RequestOptions ): Promise<ResourceOwner> { return this.base.request( 'POST', `/api/v2/tasks/${request.taskID}/owners`, request, requestOptions, 'application/json' ) } /** * Remove an owner from a task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/DeleteTasksIDOwnersID } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ deleteTasksIDOwnersID( request: DeleteTasksIDOwnersIDRequest, requestOptions?: RequestOptions ): Promise<void> { return this.base.request( 'DELETE', `/api/v2/tasks/${request.taskID}/owners/${request.userID}`, request, requestOptions ) } /** * List all tasks. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/GetTasks } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ getTasks( request?: GetTasksRequest, requestOptions?: RequestOptions ): Promise<Tasks> { return this.base.request( 'GET', `/api/v2/tasks${this.base.queryString(request, [ 'name', 'after', 'user', 'org', 'orgID', 'status', 'limit', 'type', ])}`, request, requestOptions ) } /** * Create a new task. * See {@link https://v2.docs.influxdata.com/v2.0/api/#operation/PostTasks } * @param request - request parameters and body (if supported) * @param requestOptions - optional transport options * @returns promise of response */ postTasks( request: PostTasksRequest, requestOptions?: RequestOptions ): Promise<Task> { return this.base.request( 'POST', `/api/v2/tasks`, request, requestOptions, 'application/json' ) } }
the_stack
import WxmlParser from '../../parser/wxml-parser' const testCases = [ { name: 'plain text', input: 'This is the plain text', expected: [{ type: 'text', content: 'This is the plain text' }], }, { name: 'simple tag', input: '<view></view>', expected: [{ type: 'view', attributes: {}, children: [] }], }, { name: 'simple comment', input: '<!-- comment -->', expected: [], }, { name: 'text before tag', input: 'before<view>hello</view>', expected: [{ type: 'text', content: 'before' }, { type: 'view', attributes: {}, children: [{ type: 'text', content: 'hello' }]}], }, { name: 'text after tag', input: '<view>hello</view>after', expected: [{ type: 'view', attributes: {}, children: [{ type: 'text', content: 'hello' }]}, { type: 'text', content: 'after' }], }, { name: 'text inside tag', input: '<view>hello</view>', expected: [{ type: 'view', attributes: {}, children: [{ type: 'text', content: 'hello' }]}], }, { name: 'attribute with single quote', input: '<view class=\'test\'></view>', expected: [{ type: 'view', attributes: { class: 'test' }, children: []}], }, { name: 'attribute with double quote', input: '<view class="test"></view>', expected: [{ type: 'view', attributes: { class: 'test' }, children: []}], }, { name: 'attribute without value', input: '<view diabled></view>', expected: [{ type: 'view', attributes: { diabled: null }, children: []}], }, { name: 'tag with multiple attributes', input: '<view class="test" style="display: block;"></view>', expected: [{ type: 'view', attributes: { class: 'test', style: 'display: block;'}, children: []}], }, { name: 'tag with multiple attributes and text child node', input: '<view class="test" style="display: block;">{{ t(\'key\') }}</view>', expected: [{ type: 'view', attributes: { class: 'test', style: 'display: block;'}, children: [{ type: 'text', content: '{{ t(\'key\') }}' }]}], }, { name: 'tag with mixed attributes', input: '<view class=\'test\' style="display: block;"></view>', expected: [{ type: 'view', attributes: { class: 'test', style: 'display: block;'}, children: [] }], }, { name: 'self closing tag', input: '<input value="{{ value }}" bindfocus="onFocused" />', expected: [{ type: 'input', attributes: { value: '{{ value }}', bindfocus: 'onFocused' }, children: [] }], }, { name: 'nested self closing tag', input: '<view>name: <input value="{{ value }}" /></view>', expected: [{ type: 'view', attributes: { }, children: [{ type: 'text', content: 'name: ' }, { type: 'input', attributes: { value: '{{ value }}' }, children: [] }] }], }, { name: 'self closing tag with space', input: '<input />', expected: [{ type: 'input', attributes: {}, children: [] }], }, { name: 'self closing tag without space', input: '<input/>', expected: [{ type: 'input', attributes: {}, children: [] }], }, { name: 'self closing tag with more space', input: '<input />', expected: [{ type: 'input', attributes: {}, children: [] }], }, { name: 'attributes with spaces', input: '<view class = "test" style = "abc"></view>', expected: [{ type: 'view', attributes: { class: 'test', style: 'abc' }, children: [] }], }, { name: 'spaces in tag', input: '< view ></ view >', expected: [{ type: 'view', attributes: { }, children: [] }], }, { name: 'self closing tag with attributes', input: '<input class="test" />', expected: [{ type: 'input', attributes: { class: 'test' }, children: [] }], }, { name: 'nested tags', input: '<view><view class="a"><view class="b">{{ t("hello") }}</view></view></view>', expected: [{ type: 'view', attributes: { }, children: [ { type: 'view', attributes: { class: 'a' }, children: [ { type: 'view', attributes: { class: 'b' }, children: [{ type: 'text', content: '{{ t("hello") }}' }]}, ]}, ] }], }, { name: 'nested tags with text and child tags', input: '<view>{{ t("key") }}<view class="test">hello</view></view>', expected: [{ type: 'view', attributes: {}, children: [{ type: 'text', content: '{{ t("key") }}' }, { type: 'view', attributes: {class: 'test'}, children: [{ type: 'text', content: 'hello'}] }] }], }, { name: 'comments inside tag', input: '<view><!-- hello -->test<!--world-->abcd</view>', expected: [{ type: 'view', attributes: {}, children: [{ type: 'text', content: 'test' }, { type: 'text', content: 'abcd' }] }], }, { name: 'wxml inside comments', input: '<view>hello<!-- </view> --></view>', expected: [{ type: 'view', attributes: {}, children: [{ type: 'text', content: 'hello' }] }], }, { name: 'wxml inside attribute', input: '<view class="</view>"></view>', expected: [{ type: 'view', attributes: { class: '</view>' }, children: [] }], }, { name: 'tag name with -', input: '<custom-component></custom-component>', expected: [{ type: 'custom-component', attributes: { }, children: [] }], }, { name: 'tag name with _', input: '<custom_component></custom_component>', expected: [{ type: 'custom_component', attributes: { }, children: [] }], }, { name: 'unicode characters inside tag', input: '<view>你好</view>', expected: [{ type: 'view', attributes: { }, children: [{ type: 'text', content: '你好' }] }], }, { name: 'unicode characters inside attributes', input: '<view class="中文"></view>', expected: [{ type: 'view', attributes: { class: '中文' }, children: [] }], }, { name: 'should work with html entities', input: '<view class="a&gt;b">&gt;&notin;&#X41;</view>', expected: [{ type: 'view', attributes: { class: 'a&gt;b' }, children: [ { type: 'text', content: '&gt;&notin;&#X41;' }, ] }], }, { name: 'uppercase tag', input: '<VIEW>test</VIEW>', expected: [{ type: 'VIEW', attributes: {}, children: [{ type: 'text', content: 'test' }] }], }, { name: 'tag name with number', input: '<view2></view2>', expected: [{ type: 'view2', attributes: {}, children: [] }], }, { name: 'mixed case tag', input: '<View>test</View>', expected: [{ type: 'View', attributes: {}, children: [{ type: 'text', content: 'test' }] }], }, { name: 'uppercase attribute key', input: '<view CLASS="test"></view>', expected: [{ type: 'view', attributes: { CLASS: 'test' }, children: [] }], }, { name: 'uppercase attribute value', input: '<view class="TEST"></view>', expected: [{ type: 'view', attributes: { class: 'TEST' }, children: [] }], }, { name: 'attribute key with number', input: '<view class2="TEST"></view>', expected: [{ type: 'view', attributes: { class2: 'TEST' }, children: [] }], }, { name: 'attribute key with colon', input: '<view wx:if="{{true}}"></view>', expected: [{ type: 'view', attributes: { 'wx:if': '{{true}}' }, children: [] }], }, { name: 'multiple line tag', input: '<view \n class="test" \n>\nabc\ndef</view>', expected: [{ type: 'view', attributes: { class: 'test' }, children: [{ type: 'text', content: 'abc\ndef' }] }], }, { name: 'multiple line comments', input: '<view><!--\n\n comments \n\n-->abc</view>', expected: [{ type: 'view', attributes: { }, children: [{ type: 'text', content: 'abc' }] }], }, { name: 'wxs tag should be ignored', input: '<view></view>test</view>', expected: [{type: 'view', attributes: {}, children: []}, { type: 'text', content: 'test' }], }, { name: 'wxs tag should be ignored', input: "<wxs>var a = 1; var b = '</wxs>'</wxs>", expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var a = 1; var b = \'</wxs>\'' }] }], }, { name: 'wxs tag should be ignored 2', input: '<wxs>var s = "</wxs>"</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var s = "</wxs>"' }] }], }, { name: 'wxs tag should be ignored 3', input: '<wxs>var s = `<wxs></wxs>`</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var s = `<wxs></wxs>`' }] }], }, { name: 'wxs tag should be ignored even if there are <', input: '<wxs>var r = 1 < 5;</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var r = 1 < 5;' }] }], }, { name: 'wxs tag should be ignored even if there are <<', input: '<wxs>var r = 1 << 5;</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var r = 1 << 5;' }] }], }, { name: 'wxs tag should be ignored even if there are <=', input: '<wxs>var r = 1 <= 5;</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var r = 1 <= 5;' }] }], }, { name: 'wxs tag should be ignored even if there are >', input: '<wxs>var r = 1 > 5;</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var r = 1 > 5;' }] }], }, { name: 'wxs tag should be ignored even if there are >', input: '<wxs>var r = 1 >> 5;</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var r = 1 >> 5;' }] }], }, { name: 'wxs tag should be ignored even if there are >=', input: '<wxs>var r = 1 >= 5;</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var r = 1 >= 5;' }] }], }, { name: 'wxs tag should be ignored even if there are < in comments', input: '<wxs>//</wxs></wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: '//</wxs>' }] }], }, { name: 'wxs tag should be ignored even if there are < in multi-line comments', input: '<wxs>/*</wxs>*//* </wxs> */</wxs>', expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: '/*</wxs>*//* </wxs> */' }] }], }, { name: 'wxs tag should be ignored even if there are < in comments 2', input: ` <wxs> // </wxs> </wxs>`, expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: '// </wxs>\n' }] }], }, { name: 'interpolation block should be ignored in case there are < character', input: `<view>{{1 < 5 ? true : false}}</view>`, expected: [{ type: 'view', attributes: {}, children: [{ type: 'text', content: '{{1 < 5 ? true : false}}' }] }], }, { name: 'interpolation block should be ignored when there is ambiguous quoted string', input: `<view>{{"}}" < 1}}</view>`, expected: [{ type: 'view', attributes: {}, children: [{ type: 'text', content: '{{"}}" < 1}}' }] }], }, { name: 'bare interpolation block should be ignored in case there are < character', input: `{{1 < 5 ? true : "<test>"}}`, expected: [{ type: 'text', content: '{{1 < 5 ? true : "<test>"}}' }], }, // { // name: 'wxs tag should be ignored even if there are < in block comments', // input: '<wxs> /*</wxs>*/ </wxs>', // expected: [{ type: 'wxs', attributes: {}, children: [{ type: 'text', content: 'var r = 1 >= 5;' }] }], // }, { name: 'unfinished tag', input: '<view', expectThrows: true, }, { name: 'unfinished tag 2', input: '<view ', expectThrows: true, }, { name: 'unfinished tag 3', input: '<view $', expectThrows: true, }, { name: 'unfinished tag 4', input: '<<', expectThrows: true, }, { name: 'unfinished tag 5', input: '<test<', expectThrows: true, }, { name: 'unfinished tag with normal tag afterwards', input: '<view<view></view>', expectThrows: true, }, { name: 'unfinished attributes', input: '<view class="></view>', expectThrows: true, }, { name: 'unfinished attributes', input: '<view class=></view>', expectThrows: true, }, { name: 'invalid end tag', input: '<view></view 123>', expectThrows: true, }, ] testCases.forEach((testCase) => { test(`WXML parser: ${testCase.name}`, () => { const p = new WxmlParser(testCase.input) if (testCase.expectThrows) { expect(() => { const nodes = p.parse() }).toThrow() return } const nodes = p.parse() const dumpedNodes = nodes.map(node => node.dump()) expect(dumpedNodes).toEqual(testCase.expected) }) })
the_stack
import * as fs from 'fs'; import * as path from 'path'; import { PROJECT_CONFIG } from '../../project.config'; import { ObjectUtils } from '../object/ObjectUtils'; import { StringUtils } from '../string/StringUtils'; import { UriUtils } from '../view/uri-utils'; import { generateDependencyTreeSingle } from './errorStackLogging'; const errorStacks = [ `at logFoundAureliaProjects (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:313:33) at AureliaProjects.<anonymous> (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:111:33) at Generator.next (<anonymous>) at fulfilled (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:62:52) `, // region other logs // ` at (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:316:37 // at Array.forEach (<anonymous>) // at logFoundAureliaProjects (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:314:42) // at AureliaProjects.<anonymous> (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:111:33) // `, // ` at AureliaProjects.<anonymous> (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:143:40) // at Generator.next (<anonymous>) // at (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:79:135 // at new Promise (<anonymous>) // `, // ` at DiagnosticMessages.log (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/common/diagnosticMessages/DiagnosticMessages.js:20:37) // at (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/regions/ViewRegions.js:577:42 // at Array.forEach (<anonymous>) // at Function.parse5Start (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/regions/ViewRegions.js:572:58) // `, // ` at DiagnosticMessages.additionalLog (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/common/diagnosticMessages/DiagnosticMessages.js:24:37) // at (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/regions/ViewRegions.js:578:42 // at Array.forEach (<anonymous>) // at Function.parse5Start (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/regions/ViewRegions.js:572:58) // `, // ` at logComponentList (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/viewModel/AureliaComponents.js:264:34) // at AureliaComponents.init (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/viewModel/AureliaComponents.js:109:30) // at AureliaProgram.initAureliaComponents (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/viewModel/AureliaProgram.js:23:53) // at AureliaProjects.<anonymous> (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:230:57) // `, // ` at AureliaProjects.<anonymous> (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:151:41) // at Generator.next (<anonymous>) // at fulfilled (/home/hdn/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/server/src/core/AureliaProjects.js:62:52) // at processTicksAndRejections (node:internal/process/task_queues:96:5) // `, ]; // endregion other logs const wish = ` | File name | linenumber | Call site | AureliaProjects | 111 | AureliaProjects.<anonymous> | AureliaProjects | 313 | logFoundAureliaProjects | AureliaProjects | 111 | AureliaProjects.<anonymous> | AureliaProjects | 314 | logFoundAureliaProjects | initialization | 49 | - | AureliaProjects | 141 | AureliaProjects.hydrate | AureliaProjects | 143 | AureliaProjects.<anonymous> | | | Array.forEach | RegionParser | 82 | - | ViewRegions | 572 | Function.parse5Start | DiagnosticMesss | 20 | DiagnosticMessages.log | RegionParser | 82 | - | ViewRegions | 572 | Function.parse5Start | DiagnosticMesss | 24 | DiagnosticMessages.additionalLog | AureliaProjects | 230 | AureliaProjects.<anonymous> | AureliaProgram | 23 | AureliaProgram.initAureliaComponents | AureliaComponen | 109 | AureliaComponents.init | AureliaComponen | 264 | logComponentList | AureliaProjects | 151 | AureliaProjects.<anonymous> `; const errorStackTracker = {}; const TRACKER_SEPARATOR = ':'; const DONT_TRACK = [ 'node:internal/process', '(<anonymous>)', 'Promise', 'fulfilled', ]; function shouldNotTrack(source: string) { const shouldNot = DONT_TRACK.find((donts) => source.includes(donts)); return shouldNot; } export function prettifyCallstack(rawErrorSplit: string[]): { pickedStack: {}; rawToTrackerList: (string | undefined)[]; } { const errorSplit = rawErrorSplit.reverse(); // errorSplit; /*?*/ // TODO findIndex of Logger.log (stack always starts with 4 elements we are not interested in (Error\nfindLog\nLogmsseag...)) // - 1. Turn into tracker list const rawToTrackerList = turnIntoRawTrackerList(errorSplit); rawToTrackerList.forEach((rawTrackerEntry) => { if (rawTrackerEntry == null) return; const [fileName, lineNumber, caller] = rawTrackerEntry.split(TRACKER_SEPARATOR); const nameLineTracker = `${fileName}${TRACKER_SEPARATOR}${lineNumber}`; }); const result = generateDependencyTreeSingle( errorStackTracker, rawToTrackerList ); // - 2. Only get actual stack const pickedStack = {}; ObjectUtils.atPath(result, rawToTrackerList, pickedStack); // rawToTrackerList.forEach((trackerLine) => { // if (trackerLine == null) return; // // @ts-ignore // actualStack[trackerLine] = result[trackerLine]; // trackerLine; // }); // - 3. Put into actual tracker // ^ TODO // ... return { pickedStack, rawToTrackerList }; } /** * @example * new Error().stack * --> * [ * 'AureliaProjects.js:62:fulfilled', * 'AureliaProjects.js:111:AureliaProjects.<anonymous>', * 'AureliaProjects.js:313:logFoundAureliaProjects' * ] */ function turnIntoRawTrackerList(errorSplit: string[]) { return errorSplit .map((errorLine) => { // errorLine.trim(); /*?*/ const splitLine = errorLine.trim().split(' '); const cleanedLine = splitLine.filter((line) => line); if (cleanedLine.length === 0) return false; const [_at, _caller, ..._paths] = cleanedLine; let targetPath = _paths[0]; if (_paths.length >= 2) { targetPath = _paths.join(' '); } try { if (shouldNotTrack(targetPath)) return false; if (shouldNotTrack(_caller)) return false; const remapped = remapWallabyToNormalProject(targetPath); if (typeof remapped === 'string') return false; const jsPath = getJsPathMatch(targetPath)?.groups?.PATH; // const jsLine = getJsPathMatch(_path)?.groups?.LINE; const jsFileName = path.basename(jsPath ?? '').replace(/.js$/, '.ts'); const trackerKey = `${jsFileName}${TRACKER_SEPARATOR}${remapped.remappedLine}${TRACKER_SEPARATOR}${_caller}`; return trackerKey; } catch (_error) { return false; } }) .filter((line) => line); } export function remapWallabyToNormalProject(targetPath: string) { // - 1. Find in .js file // Before: (path/to/file.js:151:41) // Match: path/to/file.js const jsPathMatch = getJsPathMatch(targetPath); if (jsPathMatch == null) return '`findLogSource` File not found'; if (jsPathMatch.groups == null) return '`findLogSource` No Group'; const jsPath = jsPathMatch.groups.PATH; const targetJsLine = Number(jsPathMatch.groups.LINE) - 1; const jsFile = fs.readFileSync(jsPath, 'utf-8'); const jsLine = jsFile.split('\n')[targetJsLine]; // Before: $_$w(39, 106, $_$c), original.code(''); // Match: original.code(''); const jsCodeRegex = /(?:\$_\$w\(.*\), )(?<ORIGINAL>.*)/; const jsCodeMatch = jsCodeRegex.exec(jsLine); if (jsCodeMatch == null) return '`findLogSource` No line'; if (jsCodeMatch.groups == null) return '`findLogSource` No original group'; const originalCode = jsCodeMatch.groups.ORIGINAL; // - 2. Find in .ts file const tsPath = jsPath.replace('.js', '.ts'); const tsFile = fs.readFileSync(tsPath, 'utf-8'); const targetTsLines = tsFile .split('\n') .map((line, index) => { const normalizedLine = StringUtils.replaceAll(line, ' ', ''); const normalizedOriginalCode = StringUtils.replaceAll( originalCode, ' ', '' ); if (!normalizedLine.includes(normalizedOriginalCode)) return false; return [index + 1, line]; // + 1 Lines are shown 1-indexed }) .filter((line) => line != false); // - 3. Map back instrumented to project // Before: ~/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/your/code // Match: ~/.vscode/extensions/wallabyjs.wallaby-vscode-1.0.317/projects/832463c82f802eb4/instrumented/ const wallabyPathRegex = /(.*wallabyjs.wallaby.*instrumented)/; const wallabyPathMatch = wallabyPathRegex.exec(tsPath); if (wallabyPathMatch == null) return 'wallaby not found'; const wallabyPath = wallabyPathMatch[1]; const finalTsPath = tsPath.replace(wallabyPath, PROJECT_CONFIG.projectPath); const finalLinesNumberText = targetTsLines .map(([lineNumber, _code] = []) => lineNumber) .join(', '); const finalSourceName = `Loc: file://${finalTsPath} ${finalLinesNumberText}`; // const finalSourceName = finalLinesText; return { remappdeLocation: finalSourceName, remappedLine: finalLinesNumberText, }; } function getJsPathMatch(targetPath: string) { targetPath = UriUtils.toSysPath(targetPath); const jsPathRegexp = /(?:\(?)(?<PATH>.*)\:(?<LINE>\d+)\:\d+(?:\)?)$/; const jsPathMatch = jsPathRegexp.exec(targetPath); return jsPathMatch; }
the_stack
import { warn, info, error } from "../helper/Logger"; import { isFrame, downloadIconClass, version } from "../helper/Constants"; import { WaitUntil } from "../helper/Wait"; import { Downloader } from "../helper/Downloader"; import { Script } from "../helper/Script"; import { Config, UriType } from "../helper/ScriptConfig"; import * as qs from "../helper/QueryString"; import { BeginWith, Contains, EndWith, Shuffle } from "../helper/Extension"; import { ISiteRule } from "../SiteRule"; import { } from "../typings/Userscript.d"; import { } from "../typings/GM_Unsafe.d"; import { } from "../typings/globals/cryptojs/index.d"; const __MP3_BLANK = 'https://jixunmoe.github.io/cuwcl4c/blank.mp3'; var rule: IYellowEaseRule = { id: 'music.163', ssl: true, name: '黄易云音乐', host: 'music.163.com', includeSubHost: false, subModule: false, runInFrame: true, dl_icon: true, css: ` .m-pbar, .m-pbar .barbg { width: calc( 455px - 2.5em ); } .m-playbar .play { width: calc( 570px - 2.5em ); } .m-playbar .oper { width: initial; } .jx_dl:hover { color: white; } /* 底部单曲下载 */ .m-playbar .oper .jx_btn { text-indent: 0; font-size: 1.5em; margin: 13px 2px 0 0; float: left; color: #ccc; text-shadow: 1px 1px 2px black, 0 0 1em black, 0 0 0.2em #aaa; line-height: 1.6em; font-size: 1.2em; } .m-playbar .oper .jx_dl::before { padding-right: .25em; } .jx_btn:hover { color: white; } /* 播放列表下载 */ .m-playbar .listhdc .jx_dl.addall { left: 306px; line-height: 1em; /* 多一个 px, 对齐文字 */ top: 13px; } .m-playbar .listhdc .line.jx_dl_line { left: 385px; } `, instance: null, onStart: () => { rule.instance = new YellowEase(); }, onBody: () => { rule.instance.BodyEvent(); } }; export var Rules: ISiteRule[] = [rule]; interface IYellowEaseRule extends ISiteRule { instance: YellowEase } class YellowEase { _localProxy: boolean; _btnDownload: JQuery; _downloader: Downloader; _cdn: string; _cdns: string[]; _ips: string[]; constructor() { if (localStorage.__HIDE_BANNER) { rule.style.Hide('#index-banner'); } if (Config.bYellowEaseInternational) GenerateCdnList(this); this._downloader = new Downloader(); unsafeExec(() => { var fakePlatForm = navigator.platform + "--Fake-mac"; Object.defineProperty(navigator, "platform", { get: () => { return fakePlatForm; }, set: () => { } }); }); } public BodyEvent () { WaitUntil('nm.x', () => { // 两个版权提示, 一个权限提示. var fnBypassCr1 = this.Search(unsafeWindow.nej.e, 'nej.e', '.dataset;if'); var fnBypassCr2 = this.Search(unsafeWindow.nm.x, 'nm.x', '.copyrightId=='); var fnBypassCr3 = this.Search(unsafeWindow.nm.x, 'nm.x', '.privilege;if'); unsafeExec((fnBypassCr1: string, fnBypassCr2: string, fnBypassCr3: string) => { var _fnBypassCr1 = window.nej.e[fnBypassCr1]; window.nej.e[fnBypassCr1] = function (z: any, name: string) { if (name == 'copyright' || name == 'resCopyright') { return 1; } return _fnBypassCr1.apply(this, arguments); }; window.nm.x[fnBypassCr2]= () => { return false; }; window.nm.x[fnBypassCr3]= (song: CrStatus) => { song.status = 0; if (song.privilege) { song.privilege.pl = 320000; } return 0; }; }, fnBypassCr1, fnBypassCr2, fnBypassCr3); }); if (isFrame) { this.FramePage(); } else { this.PlayerPage(); } } public Search(base: Object, displayBase: string, keyword: string|RegExp, suppressLog: boolean = false): string { for(let itemName in base) { if (base.hasOwnProperty(itemName)) { let fn = (<any>base)[itemName]; if (fn && typeof fn == 'function') { let fnStr = String(fn); if (TestString(fnStr, keyword)) { if (!suppressLog) info(`定位查找 %c${keyword}%c 成功: %c${displayBase}.${itemName}`, 'color: darkviolet', 'reset', 'color: green'); return itemName; } } } } if (!suppressLog) error(`定位查找子函数 ${keyword} 于 ${displayBase} 失败, 请联系作者修复!`); return null; } private SearchSubPrototype(base: Object, displayBase: string, keyword: string|RegExp, suppressLog: boolean = false): string[] { for(let itemName in base) { if (base.hasOwnProperty(itemName)) { let newBase: Function = (<any>base)[itemName]; // 检查现在的这个是不是子类 if (newBase && newBase.prototype) { // info(`查找 %c${displayBase}.${itemName}.prototype%c ...`, 'color:lightgray', 'reset'); let r = this.Search(newBase.prototype, displayBase, keyword, true); if (r != null) { if (!suppressLog) info(`定位查找 %c${keyword}%c 成功: %c${displayBase}.${itemName}::${r}`, 'color: darkviolet', 'reset', 'color: green'); return [itemName, 'prototype', r]; } } } } if (!suppressLog) error(`定位查找子类函数 ${keyword} 于 ${displayBase} 失败, 请联系作者修复!`); return null; } _btnDownloadAll: JQuery; private PlayerPage() { this._btnDownload = $('<a>'); this._btnDownload .attr('title', '播放音乐,即刻解析。') .click((e) => e.stopPropagation()) .addClass(downloadIconClass) .addClass('jx_btn') .appendTo('.m-playbar .oper'); // TODO: 加入歌单下载按钮 this._btnDownloadAll = $('<a>'); this._btnDownloadAll .addClass('addall') .text('全部下载') .addClass(downloadIconClass) .click( () => this.DownloadAll () ); if (Config.dUriType == UriType.Aria) { this._downloader.CaptureAria(this._btnDownload); } else { // TODO: 隐藏歌单下载按钮 } if (location.pathname == '/demo/fm') { this.HookRadioPlayer(); } else { this.HookNormalPlayer(); } } private DownloadAll(): void { // TODO: 下载所有曲目 } _btnChangeCdn: JQuery; _ajaxBackup: YellowEaseAjax; private HookNormalPlayer() { WaitUntil(() => { return document.querySelector('.listhdc > .addall') != null; }, () => { var dlLine = $('<a>'); dlLine .addClass('line jx_dl_line') .hide(); this._btnDownloadAll .insertBefore('.m-playbar .listhdc .addall') .after(dlLine) .hide(); }, true, 500); function nextSong () { (document.querySelector('.nxt') as HTMLAnchorElement).click(); } WaitUntil('nej.j', () => { var fnAjax = this.Search(unsafeWindow.nej.j, "nej.j", '.replace("api","weapi'); var fnGetSongRaw = this.SearchSubPrototype( unsafeWindow.nm.w, 'nm.w', /return this\.\w+\[this\.\w+\]/ ); var clsPlayer = fnGetSongRaw[0]; var fnGetSong = fnGetSongRaw[2]; if (Config.bYellowEaseInternational) { this._btnChangeCdn = $('<a>'); this._btnChangeCdn .addClass('jx_btn jx_cdn') .click(() => this.NextCdn()) .insertAfter(this._btnDownload) .text('换'); var cdn = GM_getValue('_ws_cdn_media', null); if (!cdn) { this.NextCdn(); } else { this._cdn = cdn as string; } } ////// 安装修改后的 取得曲目信息 函数开始 var callEventFn = GenerateValidName(); exportFunction((song: string) => { var data = JSON.parse(song) as ISongInfoCache; this._song = { artists: data.artists.map((artist) => artist.name).join('、'), name: data.name, url: null }; info(`捕捉到音乐切换: ${this._song.name}`); }, unsafeWindow, { defineAs: callEventFn }); unsafeExec((callEventFn: string, clsPlayer: string, fnGetSong: string) => { var _getSongBackup: Function = window.nm.w[clsPlayer].prototype[fnGetSong]; window.nm.w[clsPlayer].prototype[fnGetSong] = function () { var r = _getSongBackup.call(this); if (r !== undefined) { window[callEventFn](JSON.stringify(r)); } return r; } }, callEventFn, clsPlayer, fnGetSong); ////// 安装修改后的 取得曲目信息 函数结束 ////// 安装修改后的 Ajax 函数开始 var ajaxPatchFn = GenerateValidName(); this._ajaxBackup = unsafeWindow.nej.j[fnAjax]; if (Config.bYellowEaseUseOldApi || Config.bYellowEaseInternational) { let hookedAjax = (Config.bYellowEaseUseOldApi ? this.AjaxPatchedOldApi : this.AjaxPatchedInternational); exportFunction(hookedAjax.bind(this), unsafeWindow, { defineAs: ajaxPatchFn }); unsafeExec((ajaxPatchFn: string, fnAjax: string) => { var ajaxPatched = (<any>window)[ajaxPatchFn] as YellowEaseAjax; var ajaxOriginal = window.nej.j[fnAjax] as YellowEaseAjax; window.nej.j[fnAjax] = CustomAjax as YellowEaseAjax; function CustomAjax(url: string, params: IXhrParam): void { // console.info(`url: ${url}`); if (url.indexOf('log/') != -1) { setTimeout(() => { params.onload({ code: 200 }); }, 100); return ; } if (!params.headers) params.headers = {}; var _onload = params.onload; // params._onload = params.onload; params.onload = (data) => { params.onload = _onload; if (params._onload) { params._onload(data, _onload); } else { params.onload(data); } }; ajaxPatched(url, params); } }, ajaxPatchFn, fnAjax); } ////// 安装修改后的 Ajax 函数结束 /// 挂钩下一首切换事件, 强制重新读取当前曲目地址。 var fnNextSong = this.Search(unsafeWindow.nm.w[clsPlayer].prototype, `nm.w.${clsPlayer}.prototype`, '(+1),"ui")'); unsafeExec((clsPlayer: string, fnNextSong: string) => { var oldNextSong: Function = window.nm.w[clsPlayer].prototype[fnNextSong]; var reloadSong: Function = eval('(' + oldNextSong.toString().replace('1', '0')+')'); window.nm.w[clsPlayer].prototype[fnNextSong] = function () { window.nm.w[clsPlayer].prototype[fnNextSong] = oldNextSong; return reloadSong.call(this); }; (document.querySelector('.nxt') as HTMLAnchorElement).click(); }, clsPlayer, fnNextSong); }); } private AjaxPatchedOldApi(url: string, params: IXhrParam): void { if (url != '/api/song/enhance/player/url') { this._ajaxBackup(url, params); return ; } url = '/api/v3/song/detail'; let query = params.query as ISongUrlQuery; if (query.br) delete query.br; var _ids = JSON.parse(query.ids); var requestIds: string[] = []; this.LoadCache(); var songs: ISongInfo[] = _ids.map((id: string) => { if (id in this._songCache) { return this._songCache[id]; } requestIds.push(id); return null; }).filter((song: ISongInfo) => { return song; }); if (requestIds.length === 0) { info(`从缓存读取曲目信息。`); let reply = SongsToUrlReply(songs); this.NotifyUrlChange(reply.data[0].url); params.onload(reply); return ; } info('请求服务器获取信息: %o', requestIds); params.query = { ids: requestIds }; params._onload = <IXhrOnloadCustom>exportFunction((data: IXhrSongDetailReply, _onload: IXhrOnload) => { this.LoadCache(false); data.songs.forEach((song) => { this._songCache[song.id] = song; }); this.SaveCache(); let reply = SongsToUrlReply(_ids.map((id: string) => this._songCache[id])); this.NotifyUrlChange(reply.data[0].url); _onload(reply); }, unsafeWindow); this._ajaxBackup(url, params); } _songCache: TrackCache; _reloadCache: boolean = true; private LoadCache(force: boolean = false) { if (force || this._reloadCache) { try { this._songCache = JSON.parse(localStorage.__track_queue_cache) as TrackCache; } catch (err) { this._songCache = {}; localStorage.__track_queue_cache = '{}'; } } this._reloadCache = false; } private SaveCache (): void { localStorage.__track_queue_cache = JSON.stringify(this._songCache); } _song: SongChangeEvent; private AjaxPatchedInternational(url: string, params: IXhrSongUrlParam, try_br?: number): void { if (url != '/api/song/enhance/player/url') { this._ajaxBackup(url, params); return ; } document.cookie = 'os=uwp'; let ip = this._ips.shift(); this._ips.push(ip); params.headers['X-Real-IP'] = ip; var id = JSON.parse(params.query.ids)[0]; params._onload = <IXhrOnloadCustom>exportFunction((data: IXhrSongUrlReply, _onload: IXhrOnload) => { if (data.data[0].url) { let url = this.InjectCdn(data.data[0].url); _onload(UrlToSongUrlReply(id, url)); this.NotifyUrlChange(url); } else if (Config.bYellowEaseUseThridOnFail && !try_br) { MusicSpy.Get(id, (err, url) => { if (err) { error(err); return ; } let cdn_url = this.InjectCdn(url); _onload(UrlToSongUrlReply(id, cdn_url)); this.NotifyUrlChange(cdn_url); }); }; }, unsafeWindow); this._ajaxBackup(url, params); } private NotifyUrlChange(url: string): void { this._song.url = url; this.OnSongChange(); } private OnSongChange(): void { this._btnDownload.attr({ href: this._downloader.GenerateUri(this._song.url, `${this._song.name} [${this._song.artists}].mp3`), title: `下载: ${this._song.name}` }); } private InjectCdn(url: string): string { var r = url.replace(/(m10\.music\.126\.net)/, `${this._cdn}/$1`); info(`播放音乐 (${r})`); return r; } private NextCdn() { if (!this._cdns) GenerateCdnList(this); var ip = this._cdns.shift(); this._cdns.push(ip); this.NotifyCdn(ip); } private NotifyCdn(ip: string) { if (this._btnChangeCdn) this._btnChangeCdn.attr('title', `更换 CDN [当前: ${ip}]`); info(`使用 CDN: ${ip}`); this._cdn = ip; localStorage.ws_cdn_media = ip; GM_setValue("_ws_cdn_media", ip); document.dispatchEvent(new CustomEvent(Script.Name + '-cdn', { detail: ip })); } private HookRadioPlayer() { } private FramePage() { switch(location.pathname.split('/')[1]) { case 'mv': // MV this.MoviePage(); break; case 'outchain': // 外链 this.OutchainPage(); break; case 'song': // 单曲 this.SinglePage(); break; case 'album': // 专辑 case 'artist': // 艺术家 case 'playlist': // 播放列表 case 'discover': // 首页 this.EnableItems(); break; } } private MoviePage () { var $flashBox = $('#flash_box'); if ($flashBox.length > 0) { var html = $flashBox.html(); var params: MvFlashParams = <MvFlashParams> qs.Parse(html.match(/flashvars="([\s\S]+?)"/)[1].replace(/&amp;/g, '&')); var qualities: IStringDictionary = { hurl: '高清', murl: '标清', lurl: '渣画质' }; var $dlHolder = $('<p>').css({ textAlign: 'right' }).text('MV 下载: ').insertAfter($flashBox); Object.keys(qualities).forEach((qualityId) => { if (params[qualityId]) { var $dl = $('<a>').attr({ href: this._downloader.GenerateUri(params[qualityId], `${params.trackName}[${qualities[qualityId]}].mp4`), title: `下载 ${params.trackName} 的 ${qualities[qualityId]} Mv` }).prop('download', true).text(qualities[qualityId]); // 修正 163 自己的跳转. this._downloader.CaptureAria($dl); $dlHolder.append($dl); $dlHolder.append(' | '); } }); $dlHolder.append(`提供: ${Script.Name} ${version}`); if (Config.bYellowEaseInternational) { $flashBox.html(html.replace(/restrict=true/g, 'restrict=')); // 自动关闭弹出的提示框 var timer = setInterval(function () { var el = document.getElementsByClassName('zcls'); if (el.length > 0) { el[0].dispatchEvent(new Event('mousedown')); clearInterval(timer); } }, 100); } } } private OutchainPage () { // TODO: 外链页面 } private SinglePage () { var timer = window.setInterval(() => { var playButton = document.getElementsByClassName('u-btni-addply'); if (playButton.length == 1) { window.clearInterval(timer); return; } // Otherwise it should be a disabled button. var playButtons = document.getElementsByClassName('u-btni-play-dis'); if (playButtons.length == 1) { window.clearInterval(timer); var songId = $('#content-operation').data('rid'); (<HTMLAnchorElement>playButtons[0]).outerHTML = ` <a data-res-action="play" data-res-id="${songId}" data-res-type="18" href="javascript:;" class="u-btn2 u-btn2-2 u-btni-addply f-fl" hidefocus="true" title="播放"> <i><em class="ply"></em>播放</i> </a> <a data-res-action="addto" data-res-id="${songId}" data-res-type="18" href="javascript:;" class="u-btni u-btni-add" hidefocus="true" title="添加到播放列表"> </a> `; } }, 1000); } private EnableItems () { var timer = window.setInterval(() => { var disbledItems = document.getElementsByClassName('js-dis'); if (disbledItems.length === 0){ window.clearInterval(timer); } for (var i = 0; i < disbledItems.length; ){ disbledItems[i].classList.remove('js-dis'); } }, 1000); } } function TestString(src:string, needle: string|RegExp) { if (typeof needle == 'string') { return Contains(src, needle as string); } else { return (needle as RegExp).test(src); } } function GenerateCdnList(ctx: YellowEase): void { var cdns: string[] = [ // 电信 "125.90.206.32", "222.186.132.103", "117.23.6.89", "119.145.207.17", "180.97.180.71", "116.55.236.93", "218.76.105.42", "125.64.232.15", "115.231.87.37", "58.221.78.68", "220.112.195.148", "218.64.94.67", "36.42.32.76", "61.136.211.16", "218.64.94.68", "219.138.21.71", "49.79.232.58", "122.228.24.30", "182.106.194.85", "218.59.186.98", "61.158.133.21", "117.27.241.20", "58.51.150.133", "218.29.49.132", "60.215.125.76", "183.61.22.17", "183.134.14.26", "58.220.6.142", "115.231.158.44", "61.164.241.105", "125.46.22.124", "222.28.152.139", "124.165.216.244", "218.60.106.115", "202.107.85.81", "61.179.107.116", "175.43.20.69", "220.194.203.86", "61.160.209.27", "120.209.141.79", "120.209.142.138", "219.138.21.72", "58.216.21.132", '14.215.228.10', '218.87.111.83', // 北京电信 '203.130.59.8', '203.130.59.10', '203.130.59.11', '203.130.59.12' ]; ctx._cdns = Shuffle<string>(cdns); var ips: string[] = [ '106.120.167.67', '111.206.61.131', '111.206.61.131', '111.13.66.226', '106.120.167.67', '125.88.190.56', '222.73.144.195', '220.181.57.232', '180.149.131.247', '180.149.133.167', '112.34.111.121', '61.135.185.24' ]; ctx._ips = Shuffle<string>(ips); } function GenerateValidName(): string { return `${Script.Name}__${Date.now()}${Math.random()}`; } function GetEnhancedData(id: number, url: string): IEnhancedData { return { id: id, url: url, br: 192000, size: 120000, md5: '00000000000000000000000000000000', code: 200, expi: 1200, type: 'mp3', gain: 0, fee: 0, uf: null, payed: 0, canExtend: false }; } function SongsToUrlReply(songs: ISongInfo[]): IXhrSongUrlReply { var reply: IXhrSongUrlReply = { code: 200, data: songs.map((song: ISongInfo) => { return GetEnhancedData(song.id, GenerateUrlFromSong(song)); }) }; return cloneInto<typeof reply>(reply, unsafeWindow, { cloneFunctions: false, wrapReflectors: true }); } function UrlToSongUrlReply(id: number, url: string): IXhrSongUrlReply { var reply: IXhrSongUrlReply = { code: 200, data: [GetEnhancedData(id, url)] }; return cloneInto<typeof reply>(reply, unsafeWindow, { cloneFunctions: false, wrapReflectors: true }); } function GenerateUrlFromSong(song:ISongInfo) { var dfsId: number; var q: IQualityInfo = <IQualityInfo>(song.h || song.m || song.l || song.a); if (!q) { error(`歌曲 ${song.name} 已经下架,获取地址失败!`); return __MP3_BLANK; } dfsId = q.fid; var randServer = ~~(Math.random() * 2) + 1; var ipPrefix: string = ''; if (Config.bYellowEaseInternational) { if (Config.bYellowEaseUseOldApi) { ipPrefix = '127.0.0.1:4003/'; } else { // TODO: 这些 Ip 有用嘛? ipPrefix = rule.instance._cdn; } } var dfsHash = DoDfsHash(dfsId); return `http://${ipPrefix}m${randServer}.music.126.net/${dfsHash}/${dfsId}.mp3`; } function strToKeyCodes (str: any): number[] { return String(str).split('').map((ch) => ch.charCodeAt(0)); } const keys = [ 51, 103, 111, 56, 38, 36, 56, 42, 51, 42, 51, 104, 48, 107, 40, 50, 41, 50 ]; function DoDfsHash(dfsid:number) { var fids = strToKeyCodes(dfsid).map(function(fid, i) { return (fid ^ keys[i % keys.length]) & 0xFF; }); return CryptoJS.MD5((CryptoJS.lib as any).ByteArray(fids)) .toString(CryptoJS.enc.Base64) .replace(/\//g, "_") .replace(/\+/g, "-"); } module MusicSpy { var _ready: boolean = false; var _reloadCache: boolean = true; var _cache: MusicSpyCache = {}; function Init(): void { _ready = true; Script.RegisterStorageEvent('_MUSIC_SPY', () => { _reloadCache = true; }); ReloadCache(); } function ReloadCache(force: boolean = false): void { if (force || _reloadCache) { try { _cache = JSON.parse(localStorage._MUSIC_SPY); } catch (ex) { _cache = {}; } } _reloadCache = false; } function ReadCache (id: string|number): MusicSpyCacheItem { if (_reloadCache) ReloadCache(); return _cache[id]; } function SaveCache(): void { localStorage._MUSIC_SPY = JSON.stringify(_cache); } export function Get(id: string|number, callback: MusicSpyCallback): void { if (!_ready) Init(); info(`第一步: 搜索曲目 (${id})`); var cacheSong = ReadCache(id); if (cacheSong) { info(`读自缓存, 请求解析真实地址。`); ParseRealAddress(cacheSong, callback); // callback(null, cacheSong.url); return ; } GM_xmlhttpRequest({ method: "GET", url: `http://api.itwusun.com/music/search/wy/1?format=json&sign=a5cc0a8797539d3a1a4f7aeca5b695b9&keyword=${id}`, onload: (response) => { var data: MusicSpyItem[]; try { data = JSON.parse(response.responseText); } catch (err) { callback(err); return ; } if (data.length === 0) { callback(new Error('无效的曲目搜索结果。')); return ; } var song = data .filter((song) => song.Type == 'wy' && song.SongId == id) .pop(); if (!song) { callback(new Error('找不到曲目信息。')); return ; } var url = song.SqUrl || song.HqUrl || song.LqUrl; var songObj: MusicSpyCacheItem = { time: Date.now(), url: url, real_time: 0, real_url: null }; _cache[id] = songObj; SaveCache(); info(`成功取得地址, 请求解析真实地址。`); ParseRealAddress(songObj, callback); // callback(null, url); }, onerror: () => { callback(new Error('网络错误 (搜索曲目)')); } }); } // 四小时后过期 // 1000 * 60 * 60 *4 == 14400000 function ParseRealAddress(cacheSong: MusicSpyCacheItem, callback: MusicSpyCallback) { info(`第二步: 解析真实地址 (${cacheSong.url})`); if (Date.now() - cacheSong.real_time < 14400000) { info (`读自缓存,结束读取。`); callback(null, cacheSong.real_url); return ; } GM_xmlhttpRequest({ method: "GET", url: cacheSong.url, headers: { Range: 'bytes=0-2' }, onload: (response) => { cacheSong.real_url = response.finalUrl; cacheSong.real_time = Date.now(); SaveCache(); info (`解析结束: ${cacheSong.real_url}`); callback(null, response.finalUrl); }, onerror: () => { callback(new Error('网络错误 (解析真实地址时)'), null); } }); } interface MusicSpyCache { [key: string]: MusicSpyCacheItem; } interface MusicSpyCacheItem { time: number; url: string; real_time: number; real_url: string; } interface MusicSpyCallback { (error: Error, url?: string): void; } interface MusicSpyItem { SongId: string; SongName: string; SubTitle: string; Artist: string; ArtistSubTitle: string; AlbumId: string; Album: string; AlbumSubTitle: string; AlbumArtist: string; CollectName: string; Length: string; Size: string; BitRate: string; FlacUrl: string; AacUrl: string; SqUrl: string; HqUrl: string; LqUrl: string; ListenUrl: string; CopyUrl: string; PicUrl: string; LrcUrl: string; KlokLrc: string; MvId: string; MvUrl: string; VideoUrl: string; Language: string; Company: string; Year: string; Disc: string; TrackNum: string; Type: string; } } declare var localStorage: YellowEaseStorage; declare var unsafeWindow: YellowEaseWindow; declare var window: YellowEaseWindow; interface YellowEaseStorage extends Storage { __HIDE_BANNER: string; __PLEASE_AUTO_SIGN: string; ws_cdn_media: string; __track_queue_cache: string; _MUSIC_SPY: string; } interface YellowEaseWindow extends Window { nej: any; nm: any; [key: string]: any; } interface IStringDictionary { [key: string]: string; } interface SongChangeEvent { artists: string; name: string; url: string; } interface CdnChangeEvent { } interface TrackCache { [key: string]: ISongInfo; } // 版权状态 interface CrStatus { privilege: IPrivilege; status: number; fee: number; } // Mv 参数 interface MvFlashParams extends IStringDictionary { trackName: string; } /** * 黄易的 Xhr 返回 */ interface IXhrReply { code: number; } interface IXhrData {} interface IXhrSongUrlReply extends IXhrReply { data: IEnhancedData[]; } interface IEnhancedData extends IXhrData { id: number; url: string; br: number; size: number; md5: string; code: number; expi: number; type: string; gain: number; fee: number; uf: void /* 未知类型 */; payed: number; canExtend: boolean; } // url: /api/v3/song/detail interface IXhrSongDetailReply extends IXhrReply { songs: ISongInfo[]; privileges: IPrivilege[]; } interface ISongInfo { id: number; name: string; rtUrls: void[]; ar: IArtist[]; al: IAlbum; st: number; a: void /* 未知类型 */; no: number; cd: string; fee: number; ftype: number; rtype: number; rurl: void /* 未知类型 */; t: number; v: number; crbt: void /* 未知类型 */; rtUrl: void /* 未知类型 */; pst: number; alia: void[]; pop: number; rt: string; mst: number; cp: number; mv: number; cf: string; dt: number; l: IQualityInfo; m: IQualityInfo; h: IQualityInfo; } interface IQualityInfo { br: number; fid: number; size: number; vd: number; } /** * 黄易的 Xhr 参数构造 */ interface IXhrParam { type: string; query: IQuery; headers?: IHttpHeader; onload: IXhrOnload; _onload: IXhrOnloadCustom; onerror: Function; } interface IXhrOnload { (data: IXhrReply): void } interface IXhrOnloadCustom extends IXhrOnload { (data: IXhrReply, _onload: IXhrOnload): void } interface IHttpHeader { "X-Real-IP"?: string; } interface IQuery { } interface ISongUrlQuery extends IQuery { ids: string; br: number; } interface IXhrSongUrlParam extends IXhrParam { query: ISongUrlQuery; } /** * 黄易的 Ajax 函数 */ interface YellowEaseAjax { (url: string, params: IXhrParam): void } /** * 黄易 */ interface ISongInfoCache { album: IAlbum; alias: void[]; artists: IArtist[]; commentThreadId: string; copyrightId: number; duration: number; id: number; mvid: number; name: string; cd: string; position: number; ringtone: string; rtUrl: void /* 未知类型 */; status: number; pstatus: number; fee: number; version: number; songType: number; mst: number; score: number; ftype: number; rtUrls: void[]; privilege: IPrivilege; source: void /* 未知类型 */; } interface IPrivilege { id: number; fee: number; payed: number; st: number; pl: number; dl: number; sp: number; cp: number; subp: number; cs: boolean; maxbr: number; fl: number; status: number; } interface IArtist { id: number; name: string; } interface IAlbum { id: number; name: string; picUrl: string; pic_str: string; pic: number; alia: string[]; }
the_stack
import { EventEmitter } from "events"; import { GraphQLError, GraphQLObjectType, GraphQLSchema, GraphQLString, } from "graphql"; import { createServer, Server } from "http"; import { AddressInfo } from "net"; import WebSocket from "ws"; import Benzene from "../../core/src/core"; import { Options } from "../../core/src/types"; import { makeHandler } from "../src/handler"; import { CompleteMessage, ConnectionAckMessage, ConnectionInitMessage, ErrorMessage, MessageType, NextMessage, SubscribeMessage, } from "../src/message"; import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from "../src/protocol"; import { HandlerOptions } from "../src/types"; const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); function emitterAsyncIterator( eventEmitter: EventEmitter, eventName: string ): AsyncIterableIterator<any> { const pullQueue = [] as any; const pushQueue = [] as any; let listening = true; eventEmitter.addListener(eventName, pushValue); function pushValue(event: any) { if (pullQueue.length !== 0) { pullQueue.shift()({ value: event, done: false }); } else { pushQueue.push(event); } } function pullValue() { return new Promise((resolve) => { if (pushQueue.length !== 0) { resolve({ value: pushQueue.shift(), done: false }); } else { pullQueue.push(resolve); } }); } function emptyQueue() { if (listening) { listening = false; eventEmitter.removeListener(eventName, pushValue); for (const resolve of pullQueue) { resolve({ value: undefined, done: true }); } pullQueue.length = 0; pushQueue.length = 0; } } return { // @ts-ignore async next() { return listening ? pullValue() : this.return?.(); }, return() { emptyQueue(); return Promise.resolve({ value: undefined, done: true }); }, throw(error) { emptyQueue(); return Promise.reject(error); }, [Symbol.asyncIterator]() { return this; }, }; } const Notification = new GraphQLObjectType({ name: "Notification", fields: { message: { type: GraphQLString, }, dummy: { type: GraphQLString, resolve: ({ message }) => message, }, DO_NOT_USE_THIS_FIELD: { type: GraphQLString, resolve: () => { throw new Error("I told you so"); }, }, user: { type: GraphQLString, resolve: (_, __, context) => context.user, }, }, }); let serverInit: { ws: WebSocket; server: Server }; const createSchema = (ee: EventEmitter) => new GraphQLSchema({ query: new GraphQLObjectType({ name: "Query", fields: { test: { type: GraphQLString, resolve: () => "test", }, }, }), subscription: new GraphQLObjectType({ name: "Subscription", fields: { notificationAdded: { type: Notification, subscribe: () => emitterAsyncIterator(ee, "NOTIFICATION_ADDED"), }, badAdded: { type: GraphQLString, subscribe: () => "nope", }, }, }), }); interface ServerUtil { ws: WebSocket; waitForMessage: ( test?: ( message: | ConnectionAckMessage | NextMessage | ErrorMessage | CompleteMessage ) => void, expire?: number ) => Promise<void>; waitForClose: ( test?: (code: number, reason: string) => void, expire?: number ) => Promise<void>; send: ( message: ConnectionInitMessage | SubscribeMessage | CompleteMessage ) => Promise<void>; doAck: () => Promise<void>; publish: (message?: string) => void; } async function startServer( handlerOptions?: Partial<HandlerOptions<any>>, options?: Partial<Options<any, any>>, wsOptions?: { protocols?: string }, extra?: any ): Promise<ServerUtil> { const ee = new EventEmitter(); const gql = new Benzene({ schema: createSchema(ee), ...options }); const server = createServer(); const wss = new WebSocket.Server({ server }); await new Promise<void>((resolve) => server.listen(0, resolve)); const port = (server.address() as AddressInfo).port; // We cross test different packages const graphqlWS = makeHandler(gql, handlerOptions); wss.on("connection", (socket) => { graphqlWS(socket, extra); }); // Inspired by https://github.com/enisdenjo/graphql-ws/tree/master/src/tests/utils/tclient.ts#L28 return new Promise((resolve) => { let closeEvent: WebSocket.CloseEvent; const queue: WebSocket.MessageEvent[] = []; const ws = new WebSocket( `ws://localhost:${port}`, wsOptions?.protocols || GRAPHQL_TRANSPORT_WS_PROTOCOL ); serverInit = { ws, server }; ws.onclose = (event) => (closeEvent = event); ws.onmessage = (message) => queue.push(message); ws.once("open", () => { resolve({ ws, send(message) { return new Promise((resolve, reject) => { ws.send(JSON.stringify(message), (err) => err ? reject(err) : resolve() ); }); }, async doAck(this: ServerUtil) { this.send({ type: MessageType.ConnectionInit, }); return this.waitForMessage((message) => { expect(message.type).toBe(MessageType.ConnectionAck); }); }, publish(message = "Hello World") { ee.emit("NOTIFICATION_ADDED", { notificationAdded: { message }, }); }, async waitForMessage(test, expire) { return new Promise((resolve, reject) => { const done = () => { const next = queue.shift()!; try { test?.(JSON.parse(String(next.data))); } catch (e) { reject(e); } resolve(); }; if (queue.length > 0) { return done(); } ws.once("message", done); if (expire) { setTimeout(() => { ws.removeListener("message", done); // expired resolve(); }, expire); } }); }, async waitForClose(test, expire) { return new Promise((resolve, reject) => { if (closeEvent) { test?.(closeEvent.code, closeEvent.reason); return resolve(); } ws.onclose = (event) => { closeEvent = event; try { test?.(closeEvent.code, closeEvent.reason); } catch (e) { reject(e); } resolve(); }; if (expire) { setTimeout(() => { // @ts-ignore: Can do ws.onclose = null; // expired resolve(); }, expire); } }); }, }); }); }); } const cleanupTest = () => { serverInit.ws.close(); serverInit.server.close(); }; afterEach(cleanupTest); test("closes connection if use protocol other than graphql-transport-ws", async () => { const utils = await startServer( {}, {}, { protocols: "graphql-subscriptions" } ); await utils.waitForClose((code) => { expect(code).toBe(1002); }); }); describe("closes connection if message is invalid", () => { it("when sending invalid JSON", async () => { const utils = await startServer(); utils.ws.send("'"); await utils.waitForClose((code, message) => { expect(code).toBe(4400); expect(message).toBe("Invalid message received"); }); }); it("when subscribing without id", async () => { const utils = await startServer(); await utils.doAck(); // @ts-expect-error utils.send({ payload: {}, type: MessageType.Subscribe, }); await utils.waitForClose((code, message) => { expect(code).toBe(4400); expect(message).toBe("Invalid message received"); }); }); }); test("replies with connection_ack", async () => { const utils = await startServer(); utils.send({ type: MessageType.ConnectionInit }); await utils.waitForMessage((message) => { expect(message.type).toBe(MessageType.ConnectionAck); }); }); test("replies with connection_ack if onConnect() == true", async () => { const utils = await startServer({ onConnect: () => true, }); utils.send({ type: MessageType.ConnectionInit }); await utils.waitForMessage((message) => { expect(message.type).toBe(MessageType.ConnectionAck); }); }); test("replies with connection_ack and payload if onConnect() == object", async () => { const utils = await startServer({ onConnect: () => ({ test: 1 }), }); utils.send({ type: MessageType.ConnectionInit }); await utils.waitForMessage((message) => { expect(message.type).toBe(MessageType.ConnectionAck); expect((message as ConnectionAckMessage).payload).toEqual({ test: 1 }); }); }); test("closes connection if onConnect() == false", async () => { const utils = await startServer({ onConnect: async () => false, }); utils.send({ type: MessageType.ConnectionInit }); await utils.waitForClose((code, reason) => { expect(code).toBe(4403); expect(reason).toBe("Forbidden"); }); }); test("receive connectionParams in onConnect", async () => { const utils = await startServer({ onConnect: async (ctx, connectionParams) => connectionParams, }); utils.send({ type: MessageType.ConnectionInit, payload: { test: "ok" } }); await utils.waitForMessage((message) => { expect(message.type).toBe(MessageType.ConnectionAck); expect((message as ConnectionAckMessage).payload).toEqual({ test: "ok" }); }); }); test("receive connection context and extra in onConnect", async () => { const utils = await startServer( { // see startServer - makeHandler(socket, request) request is extra onConnect: async (ctx) => ctx.extra === "foo", }, undefined, undefined, "foo" ); utils.send({ type: MessageType.ConnectionInit }); await utils.waitForMessage((message) => { expect(message.type).toBe(MessageType.ConnectionAck); }); }); test("closes connection if onConnect() throws", async () => { const utils = await startServer({ onConnect: async () => { throw new Error("bad"); }, }); utils.send({ type: MessageType.ConnectionInit }); await utils.waitForClose((code, reason) => { expect(code).toBe(4403); expect(reason).toBe("bad"); }); }); test("closes connection if too many initialisation requests", async () => { const utils = await startServer(); utils.send({ type: MessageType.ConnectionInit }); utils.send({ type: MessageType.ConnectionInit }); await utils.waitForClose((code, reason) => { expect(code).toBe(4429); expect(reason).toBe("Too many initialisation requests"); }); }); test("closes connection if subscribe before initialized", async () => { const utils = await startServer(); utils.send({ type: MessageType.Subscribe, id: "1", payload: {} }); await utils.waitForClose((code, reason) => { expect(code).toBe(4401); expect(reason).toBe("Unauthorized"); }); }); test("closes connection if subscriber id is already existed", async () => { const utils = await startServer(); await utils.doAck(); const query = `subscription { notificationAdded { message } }`; await utils.send({ type: MessageType.Subscribe, payload: { query }, id: "1", }); await wait(50); utils.send({ type: MessageType.Subscribe, payload: { query }, id: "1", }); await utils.waitForClose((code, reason) => { expect(code).toBe(4409); expect(reason).toBe("Subscriber for 1 already exists"); }); }); test("returns errors if no payload", async () => { const utils = await startServer(); await utils.doAck(); utils.send({ type: MessageType.Subscribe, // @ts-ignore payload: undefined, id: "1", }); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", type: MessageType.Error, payload: [{ message: "Must provide query string." }], }); }); }); test("returns errors on syntax error", async () => { const utils = await startServer(); await utils.doAck(); utils.send({ id: "1", payload: { query: ` subscription { NNotificationAdded { message } } `, }, type: MessageType.Subscribe, }); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", type: MessageType.Error, payload: [ { message: `Cannot query field "NNotificationAdded" on type "Subscription". Did you mean "notificationAdded"?`, locations: [{ line: 3, column: 9 }], }, ], }); }); }); test("formats errors using formatErrorFn", async () => { const utils = await startServer( {}, { formatErrorFn: () => { return new GraphQLError("Internal server error"); }, } ); await utils.doAck(); await utils.send({ id: "1", payload: { query: ` subscription { notificationAdded { message DO_NOT_USE_THIS_FIELD } } `, }, type: MessageType.Subscribe, }); await wait(50); await new Promise((resolve) => setTimeout(resolve, 50)); utils.publish(); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", type: MessageType.Next, payload: { data: { notificationAdded: { DO_NOT_USE_THIS_FIELD: null, message: "Hello World", }, }, // Override "I told you so" error errors: [{ message: "Internal server error" }], }, }); }); }); test("resolves subscriptions and send updates", async () => { const utils = await startServer(); await utils.doAck(); await utils.send({ id: "1", payload: { query: ` subscription { notificationAdded { message dummy } } `, }, type: MessageType.Subscribe, }); await wait(50); utils.publish(); await utils.waitForMessage((message) => { expect(message).toEqual({ type: MessageType.Next, id: "1", payload: { data: { notificationAdded: { message: "Hello World", dummy: "Hello World", }, }, }, }); }); }); test("returns errors when operation name is missing", async () => { const utils = await startServer(); await utils.doAck(); const query = ` subscription test { notificationAdded { message dummy } } subscription testt { notificationAdded { message dummy } } subscription testtt { notificationAdded { message dummy } } `; utils.send({ id: "1", payload: { query, }, type: MessageType.Subscribe, }); await utils.waitForMessage((message) => { expect(message).toEqual({ type: MessageType.Error, id: "1", payload: [ { message: "Must provide operation name if query contains multiple operations.", }, ], }); }); }); test("returns errors when operation name is invalid", async () => { const utils = await startServer(); await utils.doAck(); const query = ` subscription test { notificationAdded { message dummy } } subscription testt { notificationAdded { message dummy } } subscription testtt { notificationAdded { message dummy } } `; utils.send({ id: "1", payload: { query, operationName: "notest", }, type: MessageType.Subscribe, }); await utils.waitForMessage((message) => { expect(message).toEqual({ type: MessageType.Error, id: "1", payload: [ { message: 'Unknown operation named "notest".', }, ], }); }); }); test("resolves subscriptions with operation name and send updates", async () => { const utils = await startServer(); await utils.doAck(); const query = ` subscription test { notificationAdded { message dummy } } subscription testt { notificationAdded { message dummy } } subscription testtt { notificationAdded { message dummy } } `; await utils.send({ id: "1", payload: { query, operationName: "test", }, type: MessageType.Subscribe, }); await wait(50); utils.publish(); await utils.waitForMessage((message) => { expect(message).toEqual({ type: MessageType.Next, id: "1", payload: { data: { notificationAdded: { message: "Hello World", dummy: "Hello World", }, }, }, }); }); }); test("resolves queries and mutations", async () => { // We can also add a Query test just to be sure but Mutation one only should be sufficient const utils = await startServer(); await utils.doAck(); utils.send({ id: "1", payload: { query: `query test { test }`, }, type: MessageType.Subscribe, }); await utils.waitForMessage((message) => { expect(message).toEqual({ type: MessageType.Next, id: "1", payload: { data: { test: "test" } }, }); }); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", type: MessageType.Complete, }); }); }); test("resolves queries and mutations with operation name", async () => { // We can also add a Query test just to be sure but Mutation one only should be sufficient const utils = await startServer(); await utils.doAck(); const query = ` query test { test } query testt { test } query testtt { test } `; utils.send({ id: "1", payload: { query, operationName: "test", }, type: MessageType.Subscribe, }); await utils.waitForMessage((message) => { expect(message).toEqual({ type: MessageType.Next, id: "1", payload: { data: { test: "test" } }, }); }); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", type: MessageType.Complete, }); }); }); test("creates GraphQL context using Benzene#contextFn", async () => { const utils = await startServer(undefined, { contextFn: async () => ({ user: "Alexa" }), }); await utils.doAck(); await utils.send({ id: "1", payload: { query: ` subscription { notificationAdded { user } } `, }, type: MessageType.Subscribe, }); await wait(50); utils.publish(); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", payload: { data: { notificationAdded: { user: "Alexa", }, }, }, type: MessageType.Next, }); }); }); test("Receive extra in Benzene#contextFn", async () => { const utils = await startServer( undefined, { contextFn: async ({ extra }) => ({ user: extra === "foo", }), }, undefined, "foo" ); await utils.doAck(); await utils.send({ id: "1", payload: { query: ` subscription { notificationAdded { user } } `, }, type: MessageType.Subscribe, }); await wait(50); utils.publish(); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", payload: { data: { notificationAdded: { user: "true", }, }, }, type: MessageType.Next, }); }); }); test("Receive nullable extra in Benzene#contextFn", async () => { const utils = await startServer( undefined, { contextFn: async ({ extra }) => ({ user: extra === undefined, }), }, undefined ); await utils.doAck(); await utils.send({ id: "1", payload: { query: ` subscription { notificationAdded { user } } `, }, type: MessageType.Subscribe, }); await wait(50); utils.publish(); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", payload: { data: { notificationAdded: { user: "true", }, }, }, type: MessageType.Next, }); }); }); test("returns errors on subscribe() error", async () => { const utils = await startServer(); await utils.doAck(); utils.send({ id: "1", payload: { query: ` subscription { badAdded } `, }, type: MessageType.Subscribe, }); await utils.waitForMessage((message) => { expect(message).toEqual({ id: "1", type: MessageType.Error, payload: [ { message: 'Subscription field must return Async Iterable. Received: "nope".', }, ], }); }); }); test("stops subscription upon MessageType.GQL_STOP", async () => { const utils = await startServer(); await utils.doAck(); await utils.send({ id: "1", payload: { query: ` subscription { notificationAdded { message } } `, }, type: MessageType.Subscribe, }); await utils.send({ id: "1", type: MessageType.Complete, }); utils.publish(); await utils.waitForMessage(() => { throw new Error("Should have been unsubscribed"); }, 100); }); // TODO: Add test to test on close event cleanup
the_stack
import { AardvarkManifest, Av, AvActionState, AvInterfaceEventProcessor, AvNode, AvNodeTransform, AvNodeType, AvStartGadgetResult, EAction, EHand, EndpointAddr, endpointAddrToString, EndpointType, ENodeFlags, Envelope, InitialInterfaceLock, interfaceStringFromMsg, MessageType, MsgGadgetStarted, MsgGetInstalledGadgets, MsgGetInstalledGadgetsResponse, MsgInterfaceEnded, MsgInterfaceEvent, MsgInterfaceReceiveEvent, MsgInterfaceStarted, MsgInterfaceTransformUpdated, MsgNodeHaptic, MsgResourceLoadFailed, MsgSaveSettings, MsgUpdateActionState, MsgUpdateSceneGraph, stringToEndpointAddr, AvVector } from '@aardvarkxr/aardvark-shared'; import bind from 'bind-decorator'; import * as React from 'react'; import { IAvBaseNode } from './aardvark_base_node'; import { AsyncMessageHandler, MessageHandler } from './aardvark_endpoint'; import { RemoteGadgetComponent } from './component_remote_gadget'; import { CGadgetEndpoint } from './gadget_endpoint'; const equal = require( 'fast-deep-equal' ); export interface AvInterfaceEntityProcessor { started( startMsg: MsgInterfaceStarted ): void; ended( endMsg: MsgInterfaceEnded ): void; event( eventMsg: MsgInterfaceReceiveEvent ): void; transformUpdated( transformMsg: MsgInterfaceTransformUpdated ): void; } function parseURL(url: string) { var parser = document.createElement('a'), searchObject: {[ key: string ]: string } = {}, queries, split, i; // Let the browser do the work parser.href = url; // Convert query string to object queries = parser.search.replace(/^\?/, '').split('&'); for( i = 0; i < queries.length; i++ ) { split = queries[i].split('='); searchObject[split[0]] = split[1]; } return searchObject; } function getBooleanActionFromState( action: EAction, state: AvActionState): boolean { if( !state ) return false; switch( action ) { case EAction.A: return state.a; case EAction.B: return state.b; case EAction.Grab: return state.grab; case EAction.GrabShowRay: return state.grabShowRay; case EAction.Squeeze: return state.squeeze; case EAction.Detach: return state.detach; default: return false; } } interface ActionStateListener { hand: EHand; action: EAction; rising?: () => void; falling?: () => void; update?: ( newValue: [ number, number ] ) => void; } export function GetGadgetUrlFromWindow() { return window.location.origin + window.location.pathname.slice( 0, window.location.pathname.lastIndexOf( "/" ) ); } /** The singleton gadget object for the browser. */ export class AvGadget { private static s_instance:AvGadget = null; private m_onSettingsReceived:( settings: any ) => void = null; private m_nextNodeId = 1; private m_registeredNodes: {[nodeId:number]:IAvBaseNode } = {}; private m_nextFrameRequest: number = 0; private m_traversedNodes: {[nodeId:number]:IAvBaseNode } = {}; private m_endpoint: CGadgetEndpoint = null; private m_manifest: AardvarkManifest = null; private m_actualGadgetUri: string = null; private m_actionState: { [hand:number]: AvActionState } = {}; private m_epToNotify: EndpointAddr = null; private m_firstSceneGraph: boolean = true; private m_initialInterfaces: InitialInterfaceLock[] = []; private m_endpointOpened: boolean = false; private m_activeWaitForConnectReject: (reason: any) => void = null; private m_activeWaitForConnectResolve: () => void = null; private m_interfaceEventProcessors: {[nodeId: number]: AvInterfaceEventProcessor } = {} private m_interfaceEntityProcessors = new Map<number, AvInterfaceEntityProcessor>(); private m_startGadgetPromises: {[nodeId:number]: [ ( res: AvStartGadgetResult ) => void, ( reason: any ) => void ] } = {}; private m_actionStateListeners: { [listenerId: number] : ActionStateListener } = {}; constructor() { this.m_actualGadgetUri = GetGadgetUrlFromWindow(); let params = parseURL( window.location.href ); try { if( params[ "initialInterfaces" ] ) { this.m_initialInterfaces = JSON.parse( atob( params[ "initialInterfaces" ] ) ); console.log( "initialInterfaces", this.m_initialInterfaces ); } } catch( e ) { console.log( `failed to parse initial interfaces ${ e }` ); } if( params[ "epToNotify"] ) { this.m_epToNotify = stringToEndpointAddr( params[ "epToNotify"] ); console.log( "This gadget wants to notify " + endpointAddrToString(this.m_epToNotify ) ); } this.m_endpoint = new CGadgetEndpoint( this.m_actualGadgetUri, this.onEndpointOpen ); } /** Returns a promise that resolves when the initial endpoint handshake is complete * * @public */ @bind public waitForConnect() { if( this.m_activeWaitForConnectReject ) { this.m_activeWaitForConnectReject("Another caller registered a promise"); this.clearWaitForConnect(); } return new Promise<void>( (resolve, reject) => { if ( this.m_endpointOpened ) resolve(); this.m_activeWaitForConnectReject = reject this.m_activeWaitForConnectResolve = resolve }); } @bind private clearWaitForConnect() { this.m_activeWaitForConnectReject = null; this.m_activeWaitForConnectResolve = null; } @bind public onEndpointOpen( settings: any ) { this.m_endpoint.getGadgetManifest( this.m_actualGadgetUri ) .then( ( manifest: AardvarkManifest ) => { this.m_manifest = manifest; this.markDirty(); }); this.m_endpoint.registerHandler( MessageType.GadgetStarted, this.onGadgetStarted ); this.m_endpoint.registerHandler( MessageType.UpdateActionState, this.onUpdateActionState ); this.m_endpoint.registerHandler( MessageType.ResourceLoadFailed, this.onResourceLoadFailed ); this.m_endpoint.registerAsyncHandler( MessageType.InterfaceEvent, this.onInterfaceEvent ); this.m_endpoint.registerAsyncHandler( MessageType.InterfaceStarted, this.onInterfaceStarted ); this.m_endpoint.registerAsyncHandler( MessageType.InterfaceEnded, this.onInterfaceEnded ); this.m_endpoint.registerAsyncHandler( MessageType.InterfaceReceiveEvent, this.onInterfaceReceivedEvent ); this.m_endpoint.registerAsyncHandler( MessageType.InterfaceTransformUpdated, this.onInterfaceTransformUpdated ); if( this.m_onSettingsReceived ) { this.m_onSettingsReceived( settings ); } this.m_endpointOpened = true; if ( this.m_activeWaitForConnectResolve ) { this.m_activeWaitForConnectResolve(); this.clearWaitForConnect(); } } /** Returns the AvGadget singleton. * * @public */ public static instance() { if( !AvGadget.s_instance ) { AvGadget.s_instance = new AvGadget(); } return AvGadget.s_instance; } /** Returns the name of the gadget. * * @public */ public getName() { if( this.m_manifest ) { return this.m_manifest.name; } else { return this.m_actualGadgetUri; } } /** Returns the gadget's manifest */ public get manifest() { return this.m_manifest; } /** Returns the URL of the gadget. */ public get url() { return this.m_actualGadgetUri; } /** The initial parent requested by whomever started this gadget. */ public get initialInterfaces() { return this.m_initialInterfaces; } /** Returns a specific initial interface lock if it exists. */ public findInitialInterface( intefaceName: string ): InitialInterfaceLock { return this.m_initialInterfaces.find( ( lock )=> lock.iface == intefaceName ); } /** Loads a gadget manifest by gadget URI. * * @returns a promise that will resolve to the specified gadget's manifest * @public */ public loadManifest( gadgetUri: string ) : Promise<AardvarkManifest> { return this.m_endpoint.getGadgetManifest( gadgetUri ); } /** Returns a list of all the installed gadget's URIs. * * @public */ public getInstalledGadgets(): Promise< string[] > { console.log( "Requesting installed gadgets" ); return new Promise<string[]>( ( resolve, reject ) => { let m: MsgGetInstalledGadgets = {}; this.m_endpoint.sendMessageAndWaitForResponse<MsgGetInstalledGadgetsResponse>( MessageType.GetInstalledGadgets, m, MessageType.GetInstalledGadgetsResponse ) .then( ( [ resp, env ]: [ MsgGetInstalledGadgetsResponse, Envelope ]) => { resolve( resp.installedGadgets ); }); }); } public register( node: IAvBaseNode ) { //console.log( "assigning id", this.m_nextNodeId ); node.m_nodeId = this.m_nextNodeId++; this.m_registeredNodes[ node.m_nodeId ] = node; this.markDirty(); } public unregister( node: IAvBaseNode ) { if( node.m_nodeId ) { delete this.m_registeredNodes[ node.m_nodeId ]; node.m_nodeId = undefined; } this.markDirty(); } public getEndpointId() : number { return this.m_endpoint.getEndpointId(); } @bind onGadgetStarted( m: MsgGadgetStarted, env: Envelope ):void { let processor = this.m_startGadgetPromises[ env.target.nodeId ]; if( processor ) { processor[0]( { success: true, startedGadgetEndpointId: m.startedGadgetEndpointId, } ); delete this.m_startGadgetPromises[ env.target.nodeId ]; } } public setInterfaceEntityProcessor( nodeId: number, processor: AvInterfaceEntityProcessor ) { this.m_interfaceEntityProcessors.set( nodeId, processor ); this.markDirty(); } public clearInterfaceEntityProcessor( nodeId: number ) { this.m_interfaceEntityProcessors.delete( nodeId ); this.markDirty(); } private getInterfaceEntityProcessor( epa: EndpointAddr ): AvInterfaceEntityProcessor { if( epa.endpointId != this.m_endpoint.getEndpointId() ) { return null; } return this.m_interfaceEntityProcessors.get( epa.nodeId ); } @bind private async onInterfaceStarted( m: MsgInterfaceStarted, env: Envelope ) { console.log( `Received interface start for ${ interfaceStringFromMsg( m ) }` ); let processor = this.getInterfaceEntityProcessor( env.target ); if( processor ) { processor.started( m ); } if( !processor ) { console.log( `Received interface start for ${ interfaceStringFromMsg( m ) },` + ` which doesn't have a processor` ); } } @bind private async onInterfaceEnded( m: MsgInterfaceEnded, env: Envelope ) { let processor = this.getInterfaceEntityProcessor( env.target ); if( processor ) { processor.ended( m ); } if( !processor ) { console.log( `Received interface start for ${ interfaceStringFromMsg( m ) },` + ` which doesn't have a processor` ); } } @bind private async onInterfaceReceivedEvent( m: MsgInterfaceReceiveEvent, env: Envelope ) { let processor = this.getInterfaceEntityProcessor( m.destination ); if( processor ) { processor.event( m ); } if( !processor ) { console.log( `Received interface event for ${ endpointAddrToString( m.destination ) },` + ` which doesn't have a processor` ); } } @bind private async onInterfaceTransformUpdated( m: MsgInterfaceTransformUpdated, env: Envelope ) { let processor = this.getInterfaceEntityProcessor( m.destination ); if( processor ) { processor.transformUpdated( m ); } if( !processor ) { console.log( `Received interface transformUpdated for ${ endpointAddrToString( m.destination ) },` + ` which doesn't have a processor` ); } } public setInterfaceEventProcessor( nodeId: number, processor: AvInterfaceEventProcessor ) { this.m_interfaceEventProcessors[ nodeId ] = processor; this.markDirty(); } public sendInterfaceEvent( nodeId: number, destination: EndpointAddr, iface: string, data: object ) { let m: MsgInterfaceEvent = { destination, interface: iface, data, }; if( destination.endpointId == this.m_endpoint.getEndpointId() ) { let env: Envelope = { type: MessageType.InterfaceEvent, sender: { type: EndpointType.Node, endpointId: this.m_endpoint.getEndpointId(), nodeId }, sequenceNumber: -1, } // if this is a local send, just bounce it back to our own node // Does this need to be async? this.onInterfaceEvent( m, env ); } else { this.sendMessage( MessageType.InterfaceEvent, m ); } } @bind private async onInterfaceEvent( m: MsgInterfaceEvent, env: Envelope ) { let processor = this.m_interfaceEventProcessors[ m.destination.nodeId ]; if( !processor ) { console.log( `Received interface event for ${ m.destination.nodeId }, which doesn't have a processor`) } else { processor( m.interface, env.sender, m.data ); } } @bind private onResourceLoadFailed( m: MsgResourceLoadFailed ) { console.error( `Resource load failed for ${ endpointAddrToString( m.nodeId ) }.` + ` uri=${ m.resourceUri } error=${ m.error }` ); } public listenForActionState( action: EAction, hand: EHand, rising: () => void, falling: () =>void ): number { if( action == EAction.GrabMove ) { throw new Error( `listenForActionState for ${ EAction[ action ] } which is vector2` ); } let handle = this.m_nextNodeId++; this.m_actionStateListeners[ handle ] = { hand, action, rising, falling, }; return handle; } public listenForVector2ActionState( action: EAction, hand: EHand, update: ( value: [ number, number ] ) => void ): number { if( action != EAction.GrabMove ) { throw new Error( `listenForVector2ActionState for ${ EAction[ action ] } which is boolean` ); } let handle = this.m_nextNodeId++; this.m_actionStateListeners[ handle ] = { hand, action, update, }; return handle; } public listenForActionStateWithComponent( hand: EHand, action: EAction, comp: React.Component ): number { let fn = () => { comp.forceUpdate(); }; return this.listenForActionState( action, hand, fn, fn ); } public unlistenForActionState( handle: number ) { delete this.m_actionStateListeners[ handle ]; } @bind private onUpdateActionState( m: MsgUpdateActionState, env: Envelope ) { let oldState = this.m_actionState[ m.hand ]; let newState = m.actionState; if( !equal( newState, oldState ) ) { // Set the state first in case any of the listeners read it this.m_actionState[m.hand] = m.actionState; for( let handle in this.m_actionStateListeners ) { let listener = this.m_actionStateListeners[ handle ]; if( listener.hand == m.hand || listener.hand == EHand.Invalid ) { if( listener.action == EAction.GrabMove ) { listener.update?.( newState.grabMove ); } else { let oldAction = getBooleanActionFromState( listener.action, oldState ); let newAction = getBooleanActionFromState( listener.action, newState ); if( !oldAction && newAction && listener.rising ) { listener.rising(); } else if( oldAction && !newAction && listener.falling ) { listener.falling(); } } } } } } /** Returns true if the gadget is in edit mode for the * specified hand. * * @public */ public getActionStateForHand( hand: EHand, action: EAction ) { if( hand == undefined || hand == EHand.Invalid ) { return getBooleanActionFromState( action, this.m_actionState[ EHand.Left] ) || getBooleanActionFromState( action, this.m_actionState[ EHand.Right] ); } else { return getBooleanActionFromState( action, this.m_actionState[ hand ] ) } } private traverseNode( domNode: HTMLElement ): AvNode[] { let lowerName = domNode.nodeName.toLowerCase(); let node:AvNode = null; switch( lowerName ) { case "av-node": let attr = domNode.getAttribute( "nodeId" ); if( attr ) { let nodeId = parseInt( attr ); let reactNode = this.m_registeredNodes[ nodeId ]; if( reactNode ) { node = reactNode.createNodeForNode(); this.m_traversedNodes[nodeId] = reactNode; } } break; } let children: AvNode[] = []; for( let n = 0; n < domNode.children.length; n++ ) { let childDomNode = domNode.children.item( n ); if( childDomNode instanceof HTMLElement ) { let descencents = this.traverseNode( childDomNode as HTMLElement ); if( descencents && descencents.length > 0 ) { children = children.concat( descencents ); } } } // figure out what to return if( node ) { // if we got a node from the DOM, return that if( children.length > 0 ) { node.children = children; } return [ node ]; } else if( children.length > 0 ) { // If we have children but no node, just return // the children. This node is a no-op. return children; } else { // otherwise, we've got nothing return null; } } @bind public updateSceneGraph() { if( !this.m_manifest ) { console.log( "Updating scene graph before manifest was loaded" ); return; } this.m_traversedNodes = {}; let rootNodes = this.traverseNode( document.body ); let msg: MsgUpdateSceneGraph = {}; if( rootNodes && rootNodes.length > 0 ) { if( rootNodes.length > 1 ) { msg.root = { type: AvNodeType.Container, id: 0, flags: ENodeFlags.Visible, children: rootNodes, }; } else { msg.root = rootNodes[0]; } } this.m_endpoint.sendMessage( MessageType.UpdateSceneGraph, msg ); if( this.m_firstSceneGraph ) { this.m_firstSceneGraph = false; if( this.m_epToNotify ) { let msgStarted: MsgGadgetStarted = { epToNotify: this.m_epToNotify, startedGadgetEndpointId: this.m_endpoint.getEndpointId(), } this.m_endpoint.sendMessage( MessageType.GadgetStarted, msgStarted ); } } this.m_nextFrameRequest = 0; } public markDirty() { if( !this.m_manifest ) { // If we don't have our manifest yet, we can't update the scene graph. // We'll update automatically once that comes in. return; } if( this.m_nextFrameRequest == 0 ) { this.m_nextFrameRequest = window.setTimeout( this.updateSceneGraph, 1 ); } } public sendHapticEvent( nodeId: EndpointAddr, amplitude: number, frequency: number, duration: number ): void { let msg: MsgNodeHaptic = { nodeId, amplitude, frequency, duration, } this.m_endpoint.sendMessage( MessageType.NodeHaptic, msg ); } public startGadget( uri: string, initialInterfaces: InitialInterfaceLock[] ) : Promise<AvStartGadgetResult> { return new Promise( ( resolve, reject ) => { let notifyNodeId = this.m_nextNodeId++; this.m_startGadgetPromises[ notifyNodeId ] = [ resolve, reject ]; let initialInterfacesEncoded = btoa( JSON.stringify( initialInterfaces ) ); let epToNotify: EndpointAddr = { type: EndpointType.Node, endpointId: this.m_endpoint.getEndpointId(), nodeId: notifyNodeId, } Av().startGadget( { uri, initialInterfaces: initialInterfacesEncoded, epToNotify, } ); window.setTimeout( () => { if( this.m_startGadgetPromises[ notifyNodeId ] ) { // it's been 30 seconds. If the gadget hasn't started by now, // tell the caller it's never going to start resolve( { success: false, error: "Timed out" } ); delete this.m_startGadgetPromises[ notifyNodeId ]; } }, 30000 ); } ); } public get isRemote() : boolean { return !!this.findInitialInterface( RemoteGadgetComponent.interfaceName ); } /** Persists the gadget's settings. These weill be passed to the gadget * via the callback registered with registerForSettings whenever the * gadget is reloaded. * @public */ public saveSettings( settings: any ) { let msg: MsgSaveSettings = { settings, } this.m_endpoint.sendMessage( MessageType.SaveSettings, msg ); } /** The callback registered with this function will be invoked when * the gadget's settings are reloaded from the server. * @public */ public registerForSettings( callback: ( settings: any ) => void ) { this.m_onSettingsReceived = callback; } /** Returns the endpoint address for a DOM node Id, or null if there * isn't a matching Aardvark node with that Id. */ public getEndpointAddressForId( id: string ): EndpointAddr { let element = document.getElementById( id ); if( !element ) { console.log( "failed to find id " + id ); return null; } if( element.nodeName.toLowerCase() != "av-node" ) { console.log( "element was not an av-node " + id ); return null; } let attr = element.getAttribute( "nodeId" ); if( !attr ) { console.log( "element didn't have nodeId set " + id ); return null; } let nodeId = parseInt( attr ); return { type: EndpointType.Node, endpointId: this.getEndpointId(), nodeId: nodeId, } } /** Adds a handler for a raw Aardvark message. You probably don't need this. */ public registerMessageHandler( type: MessageType, handler: MessageHandler ) { this.m_endpoint.registerHandler( type, handler ); } /** Adds an asynchronous handler for a raw Aardvark message. You probably don't need this. */ public registerAsyncMessageHandler( type: MessageType, handler: AsyncMessageHandler ) { this.m_endpoint.registerAsyncHandler( type, handler ); } /** Sends a message to the server. You probably don't need this either. */ public sendMessage( type: MessageType, message: object, sendingNode?: number ) { this.m_endpoint.sendMessage( type, message, sendingNode ); } /** Sends a message and returns a promise that resolves when the response to that message * arrives. */ public sendMessageAndWaitForResponse<T>( type: MessageType, msg: any, responseType: MessageType ): Promise< [ T, Envelope ] > { return this.m_endpoint.sendMessageAndWaitForResponse<T>( type, msg, responseType ); } }
the_stack
import { Duration } from "chronoshift"; import { $, Expression, ExpressionJS, RefExpression } from "plywood"; import { DEFAULT_LATEST_PERIOD_DURATIONS, DEFAULT_TIME_SHIFT_DURATIONS } from "../../../client/components/filter-menu/time-filter-menu/presets"; import { DEFAULT_LIMITS } from "../../limit/limit"; import { makeTitle, verifyUrlSafeName } from "../../utils/general/general"; import { GranularityJS } from "../granularity/granularity"; import { Bucket } from "../split/split"; import { TimeShift, TimeShiftJS } from "../time-shift/time-shift"; const DEFAULT_TIME_SHIFTS = DEFAULT_TIME_SHIFT_DURATIONS.map(TimeShift.fromJS); const DEFAULT_LATEST_PERIODS = DEFAULT_LATEST_PERIOD_DURATIONS.map(Duration.fromJS); export type DimensionKind = "string" | "boolean" | "time" | "number"; interface BaseDimension { kind: DimensionKind; name: string; title: string; description?: string; expression: Expression; limits: number[]; url?: string; sortStrategy?: string; } export interface StringDimension extends BaseDimension { kind: "string"; multiValue: boolean; } export interface BooleanDimension extends BaseDimension { kind: "boolean"; } export interface TimeDimension extends BaseDimension { kind: "time"; granularities?: Duration[]; bucketedBy?: Duration; bucketingStrategy?: BucketingStrategy; timeShiftDurations: TimeShift[]; latestPeriodDurations: Duration[]; } export interface NumberDimension extends BaseDimension { kind: "number"; granularities?: number[]; bucketedBy?: number; bucketingStrategy?: BucketingStrategy; } export type Dimension = StringDimension | BooleanDimension | TimeDimension | NumberDimension; function readKind(kind: string): DimensionKind { if (kind === "string" || kind === "boolean" || kind === "time" || kind === "number") return kind; throw new Error(`Unrecognized kind: ${kind}`); } function typeToKind(type: string): DimensionKind { if (!type) return "string"; return readKind(type.toLowerCase().replace(/_/g, "-").replace(/-range$/, "")); } export enum BucketingStrategy { defaultBucket = "defaultBucket", defaultNoBucket = "defaultNoBucket" } export const bucketingStrategies: { [strategy in BucketingStrategy]: BucketingStrategy } = { defaultBucket: BucketingStrategy.defaultBucket, defaultNoBucket: BucketingStrategy.defaultNoBucket }; export interface DimensionJS { name: string; title?: string; description?: string; formula?: string; kind?: string; multiValue?: boolean; url?: string; granularities?: GranularityJS[]; timeShiftDurations?: string[]; latestPeriodDurations?: string[]; limits?: number[]; bucketedBy?: GranularityJS; bucketingStrategy?: BucketingStrategy; sortStrategy?: string; } interface LegacyDimension { expression?: any; type?: string; } function readExpression(config: DimensionJS & LegacyDimension): Expression { if (config.formula) return Expression.parse(config.formula); if (config.expression) return Expression.parse(config.expression); return $(config.name); } export function fromConfig(config: DimensionJS & LegacyDimension): Dimension { const { kind: rawKind, description, name, title: rawTitle, url, sortStrategy } = config; verifyUrlSafeName(name); const kind = rawKind ? readKind(rawKind) : typeToKind(config.type); const expression = readExpression(config); const title = rawTitle || makeTitle(name); const limits = readLimits(config); switch (kind) { case "string": { const { multiValue } = config; return { description, url, name, title, expression, limits, multiValue: Boolean(multiValue), sortStrategy, kind }; } case "boolean": return { description, url, name, title, expression, limits, sortStrategy, kind }; case "time": { const { bucketedBy, bucketingStrategy } = config; return { kind, name, sortStrategy, title, url, description, expression, limits, bucketedBy: bucketedBy && Duration.fromJS(bucketedBy as string), bucketingStrategy: bucketingStrategy && bucketingStrategies[bucketingStrategy], granularities: readGranularities(config, "time"), latestPeriodDurations: readLatestPeriodDurations(config), timeShiftDurations: readTimeShiftDurations(config) }; } case "number": { const { bucketedBy, bucketingStrategy } = config; return { kind, name, sortStrategy, title, url, description, expression, limits, bucketedBy: bucketedBy && Number(bucketedBy), bucketingStrategy: bucketingStrategy && bucketingStrategies[bucketingStrategy], granularities: readGranularities(config, "number") }; } } } function readLimits({ name, limits }: DimensionJS): number[] { if (!limits) return DEFAULT_LIMITS; if (!Array.isArray(limits)) { throw new Error(`must have list of valid limits in dimension '${name}'`); } return limits; } function readLatestPeriodDurations({ name, latestPeriodDurations }: DimensionJS): Duration[] { if (!latestPeriodDurations) return DEFAULT_LATEST_PERIODS; if (!Array.isArray(latestPeriodDurations) || latestPeriodDurations.length !== 5) { throw new Error(`must have list of 5 latestPeriodDurations in dimension '${name}'`); } return latestPeriodDurations.map(Duration.fromJS); } function readTimeShiftDurations({ name, timeShiftDurations }: DimensionJS): TimeShift[] { if (!timeShiftDurations) return DEFAULT_TIME_SHIFTS; if (!Array.isArray(timeShiftDurations) || timeShiftDurations.length !== 4) { throw new Error(`must have list of 4 timeShiftDurations in dimension '${name}'`); } return timeShiftDurations.map(TimeShift.fromJS); } function readGranularities(config: DimensionJS, kind: "time"): Duration[] | undefined; function readGranularities(config: DimensionJS, kind: "number"): number[] | undefined; function readGranularities(config: DimensionJS, kind: "number" | "time"): Bucket[] | undefined { const { granularities } = config; if (!granularities) return undefined; if (!Array.isArray(granularities) || granularities.length !== 5) { throw new Error(`must have list of 5 granularities in dimension '${config.name}'`); } switch (kind) { case "number": return granularities.map(g => Number(g)); case "time": return granularities.map(g => Duration.fromJS(g as string)); } } interface SerializedStringDimension { kind: "string"; name: string; title: string; description?: string; expression: ExpressionJS; limits: number[]; url?: string; sortStrategy?: string; multiValue: boolean; } interface SerializedBooleanDimension { kind: "boolean"; name: string; title: string; description?: string; expression: ExpressionJS; limits: number[]; url?: string; sortStrategy?: string; } interface SerializedNumberDimension { kind: "number"; name: string; title: string; description?: string; expression: ExpressionJS; limits: number[]; url?: string; sortStrategy?: string; granularities?: number[]; bucketedBy?: number; bucketingStrategy?: BucketingStrategy; } interface SerializedTimeDimension { kind: "time"; name: string; title: string; description?: string; expression: ExpressionJS; limits: number[]; url?: string; sortStrategy?: string; granularities?: string[]; bucketedBy?: string; bucketingStrategy?: BucketingStrategy; timeShiftDurations: TimeShiftJS[]; latestPeriodDurations: string[]; } export type SerializedDimension = SerializedStringDimension | SerializedBooleanDimension | SerializedNumberDimension | SerializedTimeDimension; export function serialize(dimension: Dimension): SerializedDimension { const { name, description, expression, title, sortStrategy, url, limits } = dimension; // NOTE: If we move kind to destructuring above, typescript would not infer proper Dimension variant switch (dimension.kind) { case "string": { const { multiValue } = dimension; return { description, url, name, title, expression: expression.toJS(), limits, multiValue, sortStrategy, kind: dimension.kind }; } case "boolean": return { description, url, name, title, expression: expression.toJS(), limits, sortStrategy, kind: dimension.kind }; case "time": { const { granularities, bucketedBy, bucketingStrategy, latestPeriodDurations, timeShiftDurations } = dimension; return { description, url, name, title, expression: expression.toJS(), limits, sortStrategy, bucketingStrategy, bucketedBy: bucketedBy && bucketedBy.toJS(), granularities: granularities && granularities.map(g => g.toJS()), latestPeriodDurations: latestPeriodDurations.map(p => p.toJS()), timeShiftDurations: timeShiftDurations.map(ts => ts.toJS()), kind: dimension.kind }; } case "number": { const { granularities, bucketedBy, bucketingStrategy } = dimension; return { description, url, name, title, expression: expression.toJS(), limits, sortStrategy, bucketingStrategy, bucketedBy, granularities, kind: dimension.kind }; } } } export type ClientDimension = Dimension; export function canBucketByDefault(dimension: ClientDimension): boolean { return isContinuous(dimension) && dimension.bucketingStrategy !== BucketingStrategy.defaultNoBucket; } export function isContinuous(dimension: ClientDimension): dimension is TimeDimension | NumberDimension { const { kind } = dimension; return kind === "time" || kind === "number"; } export function createDimension(kind: DimensionKind, name: string, expression: Expression, multiValue?: boolean): Dimension { switch (kind) { case "string": return { kind, name, title: makeTitle(name), expression, limits: DEFAULT_LIMITS, multiValue: Boolean(multiValue) }; case "boolean": return { kind, name, title: makeTitle(name), limits: DEFAULT_LIMITS, expression }; case "time": return { latestPeriodDurations: DEFAULT_LATEST_PERIODS, timeShiftDurations: DEFAULT_TIME_SHIFTS, kind, name, limits: DEFAULT_LIMITS, title: makeTitle(name), expression }; case "number": return { kind, name, limits: DEFAULT_LIMITS, title: makeTitle(name), expression }; } } export function timeDimension(timeAttribute: RefExpression): Dimension { return createDimension("time", "time", timeAttribute); }
the_stack
import * as assert from 'assert'; import * as vscode from 'vscode-languageserver'; import * as scopes from '../src/sentence-model/Scopes'; import {QualId, ScopeFlags, Symbol, SymbolKind} from '../src/sentence-model/Scopes'; class MockSentence { constructor( public prev: MockSentence|null, public next: MockSentence|null, public scope: (scopes.ScopeDeclaration<MockSentence> & IScopeDeclaration)|null) {} public getScope() { return this.scope; } } class ScopeDeclaration extends scopes.ScopeDeclaration<MockSentence> { } type SymbolInformation = scopes.SymbolInformation<MockSentence>; export interface IScopeDeclaration { privateSymbols : Symbol[]; localSymbols : Symbol[]; exportSymbols : Symbol[]; addExportSymbol(s: Symbol) : void; isBegin(name?: string) : this is ScopeDeclaration&{node: {kind:"begin",name:string,exports:boolean}} isEnd(name?: string) : this is ScopeDeclaration&{node: {kind:"end",name:string}}; lookup(id: QualId, flags: ScopeFlags) : SymbolInformation[]; lookupSymbolInList(id: QualId, symbols: Symbol[]) : SymbolInformation|null; lookupHere(id: QualId, flags: ScopeFlags) : SymbolInformation|null; getPreviousSentence() : ScopeDeclaration|null; getNextSentence() : ScopeDeclaration|null; getParentScope() : ScopeDeclaration|null; getPrefixes() : QualId[]; resolveSymbol(s: SymbolInformation|null) : SymbolInformation|null; resolveId(id: QualId, flags: ScopeFlags) : SymbolInformation|null; } describe("Scopes", function() { let currentPos : vscode.Position; beforeEach(function () { currentPos = vscode.Position.create(0,0); }) function nextPos(p?: vscode.Position) { if(!p) p = currentPos; const x = Math.floor(Math.random() * 10); const y = Math.floor(Math.random() * 10); currentPos = vscode.Position.create(p.line+x,p.character+y); return currentPos; } function nextRange(r?: vscode.Range|vscode.Position) { if(!r) r = currentPos; const s = nextPos(vscode.Range.is(r) ? r.end : r); const e = nextPos(s); return vscode.Range.create(s,e); } // before("check if coqtop exists", function() { // if(!fs.existsSync(path.join(COQBIN_8_6, '/coqtop')) && (os.platform()!=='win32' || !fs.existsSync(path.join(COQBIN_8_6, '/coqtop.exe')))) { // console.warn("Cannot find coqtop: " + path.join(COQBIN_8_6, '/coqtop')); // console.warn("Please make sure you have set env-var COQBIN_8_6 to point to the binaries directory of Coq 8.6."); // this.skip(); // } // }) describe('helpers', function() { it('resolveQualId', function() { assert.deepStrictEqual(scopes.resolveQualId([],[]), []); assert.deepStrictEqual(scopes.resolveQualId([],['a']), null); assert.deepStrictEqual(scopes.resolveQualId(['a'],['a']), ['a']); assert.deepStrictEqual(scopes.resolveQualId(['a'],['b','a']), null); assert.deepStrictEqual(scopes.resolveQualId(['a2'],[]), ['a2']); assert.deepStrictEqual(scopes.resolveQualId(['a2','b'],[]), ['a2','b']); assert.deepStrictEqual(scopes.resolveQualId(['b','a'],['a']), ['b','a']); assert.deepStrictEqual(scopes.resolveQualId(['a','b'],['a','b']), ['a','b']); assert.deepStrictEqual(scopes.resolveQualId(['a','b'],['a','c']), null); assert.deepStrictEqual(scopes.resolveQualId(['a','b'],['c']), null); }) it('matchQualId', function() { assert.deepStrictEqual(scopes.matchQualId([],[]), {which: 0, prefix: [], id: []}); assert.deepStrictEqual(scopes.matchQualId([],['a']), {which: 0, prefix: ['a'], id: []}); assert.deepStrictEqual(scopes.matchQualId(['a'],['a']), {which: 0, prefix: [], id: ['a']}); assert.deepStrictEqual(scopes.matchQualId(['a'],['b','a']), {which: 0, prefix: ['b'], id: ['a']}); assert.deepStrictEqual(scopes.matchQualId(['a'],[]), {which: 1, prefix: ['a'], id: []}); assert.deepStrictEqual(scopes.matchQualId(['b','a'],['a']), {which: 1, prefix: ['b'], id: ['a']}); assert.deepStrictEqual(scopes.matchQualId(['c','b','a'],['a']), {which: 1, prefix: ['c','b'], id: ['a']}); assert.deepStrictEqual(scopes.matchQualId(['c','b','a'],['b','a']), {which: 1, prefix: ['c'], id: ['b','a']}); assert.deepStrictEqual(scopes.matchQualId(['a','b'],['a','b']), {which: 0, prefix: [], id: ['a','b']}); assert.deepStrictEqual(scopes.matchQualId(['a','b'],['a','c']), null); assert.deepStrictEqual(scopes.matchQualId(['a','b'],['c','b']), null); assert.deepStrictEqual(scopes.matchQualId(['a','b'],['c']), null); }) it('ScopeFlags', function() { assert.equal(ScopeFlags.All & ScopeFlags.Local, ScopeFlags.Local); assert.equal(ScopeFlags.All & ScopeFlags.Private, ScopeFlags.Private); assert.equal(ScopeFlags.All & ScopeFlags.Export, ScopeFlags.Export); assert.equal(ScopeFlags.Local & ScopeFlags.Private, false); assert.equal(ScopeFlags.Local & ScopeFlags.Export, false); assert.equal(ScopeFlags.Private & ScopeFlags.Export, false); }) }) describe.skip('single-scope', function() { let s : MockSentence; let symb; beforeEach(function () { symb = { foo: {identifier: 'foo', range: nextRange(), kind: SymbolKind.Definition}, bar: {identifier: 'bar', range: nextRange(), kind: SymbolKind.Definition}, aaa: {identifier: 'aaa', range: nextRange(), kind: SymbolKind.Definition}, bbb: {identifier: 'bbb', range: nextRange(), kind: SymbolKind.Definition}, ccc: {identifier: 'ccc', range: nextRange(), kind: SymbolKind.Definition}, } s = new MockSentence(null,null,null); }) it("constructor1", function() { s.scope = new ScopeDeclaration(s,[], null) as any; const sc = s.scope as any as IScopeDeclaration; assert.equal(sc.lookup([],ScopeFlags.All),null); assert.equal(sc.lookup(['foo'],ScopeFlags.All),null); assert.equal(sc.lookup(['M','foo'],ScopeFlags.All),null); assert.equal(sc.isBegin(), false); assert.equal(sc.isEnd(), false); assert.deepStrictEqual(sc.getPrefixes(), []); assert.deepStrictEqual(sc.getNextSentence(), null); assert.deepStrictEqual(sc.getPreviousSentence(), null); assert.deepStrictEqual(sc.getParentScope(), null); }) it("constructor2", function() { s.scope = new ScopeDeclaration(s,['M'], null) as any; const sc = s.scope as any as IScopeDeclaration; assert.equal(sc.lookup([],ScopeFlags.All),null); assert.equal(sc.lookup(['foo'],ScopeFlags.All),null); assert.equal(sc.lookup(['M','foo'],ScopeFlags.All),null); assert.equal(sc.isBegin(), false); assert.equal(sc.isEnd(), false); assert.deepStrictEqual(sc.getPrefixes(), []); }) it("isBegin", function() { s.scope = new ScopeDeclaration(s,['M'], {kind: "begin", name: "MOO", exports:true}) as any; const sc = s.scope as any as IScopeDeclaration; assert.equal(sc.isBegin('M'), false); assert.equal(sc.isBegin('MOO'), true); assert.equal(sc.isEnd('MOO'), false); assert.equal(sc.isEnd('M'), false); assert.equal(sc.isEnd(), false); }) it("isEnd", function() { s.scope = new ScopeDeclaration(s,['M'], {kind: "end", name: "MOO"}) as any; const sc = s.scope as any as IScopeDeclaration; assert.equal(sc.isBegin('M'), false); assert.equal(sc.isBegin('MOO'), false); assert.equal(sc.isEnd('MOO'), true); assert.equal(sc.isEnd('M'), false); assert.equal(sc.isEnd(), true); }) function assertSymbolLookup(si: SymbolInformation[]|null, sy: Symbol[], p: QualId) { assert.notEqual(si, null); si.forEach((si,idx) => assert.equal(si.symbol,sy[idx])); si.forEach((si,idx) => assert.deepStrictEqual(si.source,s)); si.forEach((si, idx) => assert.deepStrictEqual(si.id,[...p,sy[idx].identifier])); si.forEach((si,idx) => assert.deepStrictEqual(si.assumedPrefix,[])); } it("lookupSymbolInList", function() { s.scope = new ScopeDeclaration(s,['M'], null) as any; const sc = s.scope as any as IScopeDeclaration; assertSymbolLookup([sc.lookupSymbolInList(['foo'],[symb.foo])], [symb.foo], []); assertSymbolLookup([sc.lookupSymbolInList(['bar'],[symb.foo, symb.bar, symb.aaa])], [symb.bar], []); assert.deepStrictEqual(sc.lookupSymbolInList(['bar'],[]), null); }) it("lookupHere", function() { s.scope = new ScopeDeclaration(s,['M'], null) as any; const sc = s.scope as any as IScopeDeclaration; sc.addExportSymbol(symb.foo); assert.equal(sc.lookupHere(['bar'],ScopeFlags.All), null); assert.equal(sc.lookupHere(['foo'],ScopeFlags.Local), null); assert.equal(sc.lookupHere(['foo'],ScopeFlags.Private), null); assertSymbolLookup([sc.lookupHere(['foo'],ScopeFlags.All)], [symb.foo], []); assertSymbolLookup([sc.lookupHere(['foo'],ScopeFlags.Export)], [symb.foo], []); }) it("resolveSymbol", function() { s.scope = new ScopeDeclaration(s,['M'], null) as any; const sc = s.scope as any as IScopeDeclaration; assert.equal(sc.resolveSymbol(null), null); sc.addExportSymbol(symb.foo); assert.equal(sc.resolveSymbol(null), null); const si1 : SymbolInformation = { assumedPrefix: [], id: ['foo'], source: s, symbol: symb.foo, } assert.notEqual(sc.resolveSymbol(si1), null); assert.deepStrictEqual(sc.resolveSymbol(si1).assumedPrefix, []); assert.deepStrictEqual(sc.resolveSymbol(si1).id, ['foo']); assert.equal(sc.resolveSymbol(si1).source, s); assert.equal(sc.resolveSymbol(si1).symbol, symb.foo); const si2 : SymbolInformation = {assumedPrefix: ['M0'], id: ['foo'], source: s, symbol: symb.foo} assert.deepStrictEqual(sc.resolveSymbol(si2), null); const si3 : SymbolInformation = {assumedPrefix: ['M2'], id: ['foo'], source: s, symbol: symb.foo} assert.deepStrictEqual(sc.resolveSymbol(si3), null); sc.getPrefixes = function() { return [['M1','M2']] } assert.deepStrictEqual(sc.resolveSymbol(si1).assumedPrefix, []); assert.deepStrictEqual(sc.resolveSymbol(si1).id, ['M1','M2','foo']); assert.deepStrictEqual(sc.resolveSymbol(si2), null); assert.notEqual(sc.resolveSymbol(si3), null); assert.deepStrictEqual(sc.resolveSymbol(si3).id, ['M1','M2','foo']); assert.deepStrictEqual(sc.resolveSymbol(si3).assumedPrefix, []); }) it("lookup", function() { s.scope = new ScopeDeclaration(s,['M'], null) as any; const sc = s.scope as any as IScopeDeclaration; sc.addExportSymbol(symb.foo); assertSymbolLookup(sc.lookup(['foo'],ScopeFlags.All), symb.foo, []); assert.equal(sc.lookup(['bar'],ScopeFlags.All), null); }) }) describe('multi-scope', function() { let s : MockSentence[]; function addScope(create: (s: MockSentence, ...args: any[]) => ScopeDeclaration, ...args: any[]) { const i = s.push(new MockSentence(null,null,null)) - 1; s[i].scope = create(s[i], ...args) as any; if(i > 0) { s[i-1].next = s[i]; s[i].prev = s[i-1]; } } beforeEach(function () { s = []; addScope(ScopeDeclaration.createDefinition,'foo',nextRange()) as any; addScope(ScopeDeclaration.createSection,'A',nextRange()) as any; addScope(ScopeDeclaration.createDefinition,'bar',nextRange()) as any; addScope(ScopeDeclaration.createEnd,'A') as any; addScope(ScopeDeclaration.createModule,'M',nextRange()) as any; addScope(ScopeDeclaration.createDefinition,'foo',nextRange()) as any; addScope(ScopeDeclaration.createDefinition,'bar',nextRange()) as any; addScope(ScopeDeclaration.createEnd,'M') as any; addScope(ScopeDeclaration.createDefinition,'bar',nextRange()) as any; }) it("getPreviousSentence", function() { const sc0 = s[0].scope as any as IScopeDeclaration; assert.deepStrictEqual(sc0.getPreviousSentence(), null); for(let idx = 1; idx < s.length; ++idx) { const sc = s[idx].scope as any as IScopeDeclaration; assert.deepStrictEqual(sc.getPreviousSentence(), s[idx-1].scope); } }) it("getNextSentence", function() { for(let idx = 0; idx < s.length-1; ++idx) { const sc = s[idx].scope as any as IScopeDeclaration; assert.deepStrictEqual(sc.getNextSentence(), s[idx+1].scope); } const sc1 = s[s.length-1].scope as any as IScopeDeclaration; assert.deepStrictEqual(sc1.getNextSentence(), null); }) it("getParentScope", function() { function testGetParentScope(tests: [number,number][]) { tests.forEach(([idx,expected]) => assert.deepStrictEqual((s[idx].scope as IScopeDeclaration).getParentScope(), expected===null ? null : s[expected].scope, `s[${idx}].getParent() === ${expected===null ? 'null' : `s[${expected.toString()}].scope`}`)); } testGetParentScope([ [0, null ], [1, null ], [2, 1 ], [3, 1 ], [4, null ], [5, 4 ], [6, 4 ], [7, 4 ], [8, null ], ]); }) it.skip("getPrefix", function() { function testGetPrefix(tests: [number,QualId][]) { tests.forEach(([idx,expected]) => { const sc = s[idx].scope as any as IScopeDeclaration; assert.deepStrictEqual(sc.getPrefixes(), expected, `s[${idx}].prefix === ${expected.toString()}`) }); } testGetPrefix([ [ 0, [] ], [ 1, [] ], [ 2, [] ], [ 3, [] ], [ 4, [] ], [ 5, ['M'] ], [ 6, ['M'] ], [ 7, ['M'] ], [ 8, [] ], ]); }) it.skip("lookup", function() { function testLookup(tests: [number,QualId,ScopeFlags,number[],QualId[]][]) { tests.forEach(([idx,id,f,expectedSource,expectedId]) => { const sc = s[idx].scope as any as IScopeDeclaration; const x = sc.lookup(id,f); x.forEach((x, idx) => { assert.deepStrictEqual(x.source, s[expectedSource[idx]], `s[${idx}].lookup(${id.toString()}).source === s[${expectedSource[idx].toString()}]`); assert.deepStrictEqual(x.id, expectedId[idx], `s[${idx}].lookup(${id.toString()}).id === ${expectedId[idx].toString()}`); }); }); } testLookup([ [0, ['foo'], ScopeFlags.All, [0], [['foo']] ], [8, ['bar'], ScopeFlags.All, [8], [['bar']] ], [8, ['foo'], ScopeFlags.All, [5], [['M','foo']] ], // bug; should fail [8, ['M','foo'], ScopeFlags.All, [5], [['M','foo']] ], [8, ['foo'], ScopeFlags.All, [0], [['foo']] ], // bug; should succeed ]); }) }) });
the_stack
import { workspace as Workspace, languages as Languages, TextDocument, TextDocumentChangeEvent, TextDocumentWillSaveEvent, TextEdit as VTextEdit, DocumentSelector as VDocumentSelector, Event, EventEmitter, Disposable } from 'vscode'; import { ClientCapabilities, DidChangeTextDocumentNotification, DidChangeTextDocumentParams, DidCloseTextDocumentNotification, DidCloseTextDocumentParams, DidOpenTextDocumentNotification, DidOpenTextDocumentParams, DidSaveTextDocumentNotification, DidSaveTextDocumentParams, DocumentSelector, ProtocolNotificationType, RegistrationType, SaveOptions, ServerCapabilities, TextDocumentChangeRegistrationOptions, TextDocumentRegistrationOptions, TextDocumentSaveRegistrationOptions, TextDocumentSyncKind, TextDocumentSyncOptions, WillSaveTextDocumentNotification, WillSaveTextDocumentParams, WillSaveTextDocumentWaitUntilRequest } from 'vscode-languageserver-protocol'; import { FeatureClient, TextDocumentEventFeature, DynamicFeature, NextSignature, TextDocumentSendFeature, NotifyingFeature, ensure, RegistrationData, DynamicDocumentFeature, NotificationSendEvent } from './features'; import { Delayer } from './utils/async'; import * as UUID from './utils/uuid'; export interface TextDocumentSynchronizationMiddleware { didOpen?: NextSignature<TextDocument, Promise<void>>; didChange?: NextSignature<TextDocumentChangeEvent, Promise<void>>; willSave?: NextSignature<TextDocumentWillSaveEvent, Promise<void>>; willSaveWaitUntil?: NextSignature<TextDocumentWillSaveEvent, Thenable<VTextEdit[]>>; didSave?: NextSignature<TextDocument, Promise<void>>; didClose?: NextSignature<TextDocument, Promise<void>>; } export interface DidOpenTextDocumentFeatureShape extends DynamicFeature<TextDocumentRegistrationOptions>, TextDocumentSendFeature<(textDocument: TextDocument) => Promise<void>>, NotifyingFeature<TextDocument, DidOpenTextDocumentParams> { openDocuments: Iterable<TextDocument>; } export type ResolvedTextDocumentSyncCapabilities = { resolvedTextDocumentSync?: TextDocumentSyncOptions; }; export class DidOpenTextDocumentFeature extends TextDocumentEventFeature<DidOpenTextDocumentParams, TextDocument, TextDocumentSynchronizationMiddleware> implements DidOpenTextDocumentFeatureShape { private readonly _syncedDocuments: Map<string, TextDocument>; constructor(client: FeatureClient<TextDocumentSynchronizationMiddleware>, syncedDocuments: Map<string, TextDocument>) { super( client, Workspace.onDidOpenTextDocument, DidOpenTextDocumentNotification.type, () => client.middleware.didOpen, (textDocument) => client.code2ProtocolConverter.asOpenTextDocumentParams(textDocument), (data) => data, TextDocumentEventFeature.textDocumentFilter ); this._syncedDocuments = syncedDocuments; } public get openDocuments(): IterableIterator<TextDocument> { return this._syncedDocuments.values(); } public fillClientCapabilities(capabilities: ClientCapabilities): void { ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.dynamicRegistration = true; } public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { const textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } public get registrationType(): RegistrationType<TextDocumentRegistrationOptions> { return DidOpenTextDocumentNotification.type; } public register(data: RegistrationData<TextDocumentRegistrationOptions>): void { super.register(data); if (!data.registerOptions.documentSelector) { return; } const documentSelector = this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector); Workspace.textDocuments.forEach((textDocument) => { const uri: string = textDocument.uri.toString(); if (this._syncedDocuments.has(uri)) { return; } if (Languages.match(documentSelector, textDocument) > 0 && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) { const middleware = this._client.middleware; const didOpen = (textDocument: TextDocument): Promise<void> => { return this._client.sendNotification(this._type, this._createParams(textDocument)); }; (middleware.didOpen ? middleware.didOpen(textDocument, didOpen) : didOpen(textDocument)).catch((error) => { this._client.error(`Sending document notification ${this._type.method} failed`, error); }); this._syncedDocuments.set(uri, textDocument); } }); } protected notificationSent(textDocument: TextDocument, type: ProtocolNotificationType<DidOpenTextDocumentParams, TextDocumentRegistrationOptions>, params: DidOpenTextDocumentParams): void { super.notificationSent(textDocument, type, params); this._syncedDocuments.set(textDocument.uri.toString(), textDocument); } } export interface DidCloseTextDocumentFeatureShape extends DynamicFeature<TextDocumentRegistrationOptions>, TextDocumentSendFeature<(textDocument: TextDocument) => Promise<void>>, NotifyingFeature<TextDocument, DidCloseTextDocumentParams> { } export class DidCloseTextDocumentFeature extends TextDocumentEventFeature<DidCloseTextDocumentParams, TextDocument, TextDocumentSynchronizationMiddleware> implements DidCloseTextDocumentFeatureShape { private readonly _syncedDocuments: Map<string, TextDocument>; constructor(client: FeatureClient<TextDocumentSynchronizationMiddleware>, syncedDocuments: Map<string, TextDocument>) { super( client, Workspace.onDidCloseTextDocument, DidCloseTextDocumentNotification.type, () => client.middleware.didClose, (textDocument) => client.code2ProtocolConverter.asCloseTextDocumentParams(textDocument), (data) => data, TextDocumentEventFeature.textDocumentFilter ); this._syncedDocuments = syncedDocuments; } public get registrationType(): RegistrationType<TextDocumentRegistrationOptions> { return DidCloseTextDocumentNotification.type; } public fillClientCapabilities(capabilities: ClientCapabilities): void { ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.dynamicRegistration = true; } public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.openClose) { this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } protected notificationSent(textDocument: TextDocument, type: ProtocolNotificationType<DidCloseTextDocumentParams, TextDocumentRegistrationOptions>, params: DidCloseTextDocumentParams): void { super.notificationSent(textDocument, type, params); this._syncedDocuments.delete(textDocument.uri.toString()); } public unregister(id: string): void { const selector = this._selectors.get(id)!; // The super call removed the selector from the map // of selectors. super.unregister(id); const selectors = this._selectors.values(); this._syncedDocuments.forEach((textDocument) => { if (Languages.match(selector, textDocument) > 0 && !this._selectorFilter!(selectors, textDocument) && !this._client.hasDedicatedTextSynchronizationFeature(textDocument)) { let middleware = this._client.middleware; let didClose = (textDocument: TextDocument): Promise<void> => { return this._client.sendNotification(this._type, this._createParams(textDocument)); }; this._syncedDocuments.delete(textDocument.uri.toString()); (middleware.didClose ? middleware.didClose(textDocument, didClose) :didClose(textDocument)).catch((error) => { this._client.error(`Sending document notification ${this._type.method} failed`, error); }); } }); } } interface DidChangeTextDocumentData { syncKind: 0 | 1 | 2; documentSelector: VDocumentSelector; } export interface DidChangeTextDocumentFeatureShape extends DynamicFeature<TextDocumentChangeRegistrationOptions>, TextDocumentSendFeature<(event: TextDocumentChangeEvent) => Promise<void>>, NotifyingFeature<TextDocumentChangeEvent, DidChangeTextDocumentParams> { } export class DidChangeTextDocumentFeature extends DynamicDocumentFeature<TextDocumentChangeRegistrationOptions, TextDocumentSynchronizationMiddleware> implements DidChangeTextDocumentFeatureShape { private _listener: Disposable | undefined; private readonly _changeData: Map<string, DidChangeTextDocumentData>; private _forcingDelivery: boolean = false; private _changeDelayer: { uri: string; delayer: Delayer<Promise<void>> } | undefined; private readonly _onNotificationSent: EventEmitter<NotificationSendEvent<TextDocumentChangeEvent, DidChangeTextDocumentParams>>; constructor(client: FeatureClient<TextDocumentSynchronizationMiddleware>) { super(client); this._changeData = new Map<string, DidChangeTextDocumentData>(); this._onNotificationSent = new EventEmitter(); } public get registrationType(): RegistrationType<TextDocumentChangeRegistrationOptions> { return DidChangeTextDocumentNotification.type; } public fillClientCapabilities(capabilities: ClientCapabilities): void { ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.dynamicRegistration = true; } public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.change !== undefined && textDocumentSyncOptions.change !== TextDocumentSyncKind.None) { this.register({ id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, { syncKind: textDocumentSyncOptions.change }) }); } } public register(data: RegistrationData<TextDocumentChangeRegistrationOptions>): void { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = Workspace.onDidChangeTextDocument(this.callback, this); } this._changeData.set( data.id, { syncKind: data.registerOptions.syncKind, documentSelector: this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector), } ); } public *getDocumentSelectors(): IterableIterator<VDocumentSelector> { for (const data of this._changeData.values()) { yield data.documentSelector; } } private async callback(event: TextDocumentChangeEvent): Promise<void> { // Text document changes are send for dirty changes as well. We don't // have dirty / un-dirty events in the LSP so we ignore content changes // with length zero. if (event.contentChanges.length === 0) { return; } const promises: Promise<void>[] = []; for (const changeData of this._changeData.values()) { if (Languages.match(changeData.documentSelector, event.document) > 0 && !this._client.hasDedicatedTextSynchronizationFeature(event.document)) { const middleware = this._client.middleware; if (changeData.syncKind === TextDocumentSyncKind.Incremental) { const didChange = async (event: TextDocumentChangeEvent): Promise<void> => { const params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event); await this._client.sendNotification(DidChangeTextDocumentNotification.type, params); this.notificationSent(event, DidChangeTextDocumentNotification.type, params); }; promises.push(middleware.didChange ? middleware.didChange(event, event => didChange(event)) : didChange(event)); } else if (changeData.syncKind === TextDocumentSyncKind.Full) { const didChange = async (event: TextDocumentChangeEvent): Promise<void> => { const doSend = async (event: TextDocumentChangeEvent): Promise<void> => { const params = this._client.code2ProtocolConverter.asChangeTextDocumentParams(event.document); await this._client.sendNotification(DidChangeTextDocumentNotification.type, params); this.notificationSent(event, DidChangeTextDocumentNotification.type, params); }; if (this._changeDelayer) { if (this._changeDelayer.uri !== event.document.uri.toString()) { // Use this force delivery to track boolean state. Otherwise we might call two times. await this.forceDelivery(); this._changeDelayer.uri = event.document.uri.toString(); } // Usually we return the promise that signals that the data has been // handed of to the network. With delayed change notification we can't // do that since it would make the sendNotification call wait until the // change delayer resolves and would therefore defeat the purpose. We // instead return the change delayer and ensure via forceDocumentSync // that before sending other notification / request the document sync // has actually happened. return this._changeDelayer.delayer.trigger(() => doSend(event)); } else { this._changeDelayer = { uri: event.document.uri.toString(), delayer: new Delayer<Promise<void>>(200) }; // See comment above. return this._changeDelayer.delayer.trigger(() => doSend(event), -1); } }; promises.push(middleware.didChange ? middleware.didChange(event, event => didChange(event)) : didChange(event)); } } } return Promise.all(promises).then(undefined, (error) => { this._client.error(`Sending document notification ${DidChangeTextDocumentNotification.type.method} failed`, error); throw error; }); } public get onNotificationSent(): Event<NotificationSendEvent<TextDocumentChangeEvent, DidChangeTextDocumentParams>> { return this._onNotificationSent.event; } private notificationSent(changeEvent: TextDocumentChangeEvent, type: ProtocolNotificationType<DidChangeTextDocumentParams, TextDocumentRegistrationOptions>, params: DidChangeTextDocumentParams): void { this._onNotificationSent.fire({ original: changeEvent, type, params }); } public unregister(id: string): void { this._changeData.delete(id); if (this._changeData.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } public dispose(): void { if (this._changeDelayer !== undefined) { this._changeDelayer.delayer.cancel(); } this._changeDelayer = undefined; this._forcingDelivery = false; this._changeData.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } public async forceDelivery(): Promise<void> { if (this._forcingDelivery || !this._changeDelayer) { return; } try { this._forcingDelivery = true; return this._changeDelayer.delayer.forceDelivery(); } finally { this._forcingDelivery = false; } } public getProvider(document: TextDocument): { send: (event: TextDocumentChangeEvent) => Promise<void> } | undefined { for (const changeData of this._changeData.values()) { if (Languages.match(changeData.documentSelector, document) > 0) { return { send: (event: TextDocumentChangeEvent): Promise<void> => { return this.callback(event); } }; } } return undefined; } } export class WillSaveFeature extends TextDocumentEventFeature<WillSaveTextDocumentParams, TextDocumentWillSaveEvent, TextDocumentSynchronizationMiddleware> { constructor(client: FeatureClient<TextDocumentSynchronizationMiddleware>) { super( client, Workspace.onWillSaveTextDocument, WillSaveTextDocumentNotification.type, () => client.middleware.willSave, (willSaveEvent) => client.code2ProtocolConverter.asWillSaveTextDocumentParams(willSaveEvent), (event) => event.document, (selectors, willSaveEvent) => TextDocumentEventFeature.textDocumentFilter(selectors, willSaveEvent.document) ); } public get registrationType(): RegistrationType<TextDocumentRegistrationOptions> { return WillSaveTextDocumentNotification.type; } public fillClientCapabilities(capabilities: ClientCapabilities): void { let value = ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!; value.willSave = true; } public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSave) { this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } } export class WillSaveWaitUntilFeature extends DynamicDocumentFeature<TextDocumentRegistrationOptions, TextDocumentSynchronizationMiddleware> { private _listener: Disposable | undefined; private readonly _selectors: Map<string, VDocumentSelector>; constructor(client: FeatureClient<TextDocumentSynchronizationMiddleware>) { super(client); this._selectors = new Map<string, VDocumentSelector>(); } protected getDocumentSelectors(): IterableIterator<VDocumentSelector> { return this._selectors.values(); } public get registrationType(): RegistrationType<TextDocumentRegistrationOptions> { return WillSaveTextDocumentWaitUntilRequest.type; } public fillClientCapabilities(capabilities: ClientCapabilities): void { let value = ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!; value.willSaveWaitUntil = true; } public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { let textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.willSaveWaitUntil) { this.register({ id: UUID.generateUuid(), registerOptions: { documentSelector: documentSelector } }); } } public register(data: RegistrationData<TextDocumentRegistrationOptions>): void { if (!data.registerOptions.documentSelector) { return; } if (!this._listener) { this._listener = Workspace.onWillSaveTextDocument(this.callback, this); } this._selectors.set(data.id, this._client.protocol2CodeConverter.asDocumentSelector(data.registerOptions.documentSelector)); } private callback(event: TextDocumentWillSaveEvent): void { if (TextDocumentEventFeature.textDocumentFilter(this._selectors.values(), event.document) && !this._client.hasDedicatedTextSynchronizationFeature(event.document)) { let middleware = this._client.middleware; let willSaveWaitUntil = (event: TextDocumentWillSaveEvent): Thenable<VTextEdit[]> => { return this._client.sendRequest(WillSaveTextDocumentWaitUntilRequest.type, this._client.code2ProtocolConverter.asWillSaveTextDocumentParams(event)).then(async (edits) => { let vEdits = await this._client.protocol2CodeConverter.asTextEdits(edits); return vEdits === undefined ? [] : vEdits; }); }; event.waitUntil( middleware.willSaveWaitUntil ? middleware.willSaveWaitUntil(event, willSaveWaitUntil) : willSaveWaitUntil(event) ); } } public unregister(id: string): void { this._selectors.delete(id); if (this._selectors.size === 0 && this._listener) { this._listener.dispose(); this._listener = undefined; } } public dispose(): void { this._selectors.clear(); if (this._listener) { this._listener.dispose(); this._listener = undefined; } } } export interface DidSaveTextDocumentFeatureShape extends DynamicFeature<TextDocumentRegistrationOptions>, TextDocumentSendFeature<(textDocument: TextDocument) => Promise<void>>, NotifyingFeature<TextDocument, DidSaveTextDocumentParams> { } export class DidSaveTextDocumentFeature extends TextDocumentEventFeature<DidSaveTextDocumentParams, TextDocument, TextDocumentSynchronizationMiddleware> implements DidSaveTextDocumentFeatureShape { private _includeText: boolean; constructor(client: FeatureClient<TextDocumentSynchronizationMiddleware>) { super( client, Workspace.onDidSaveTextDocument, DidSaveTextDocumentNotification.type, () => client.middleware.didSave, (textDocument) => client.code2ProtocolConverter.asSaveTextDocumentParams(textDocument, this._includeText), (data) => data, TextDocumentEventFeature.textDocumentFilter ); this._includeText = false; } public get registrationType(): RegistrationType<TextDocumentSaveRegistrationOptions> { return DidSaveTextDocumentNotification.type; } public fillClientCapabilities(capabilities: ClientCapabilities): void { ensure(ensure(capabilities, 'textDocument')!, 'synchronization')!.didSave = true; } public initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector): void { const textDocumentSyncOptions = (capabilities as ResolvedTextDocumentSyncCapabilities).resolvedTextDocumentSync; if (documentSelector && textDocumentSyncOptions && textDocumentSyncOptions.save) { const saveOptions: SaveOptions = typeof textDocumentSyncOptions.save === 'boolean' ? { includeText: false } : { includeText: !!textDocumentSyncOptions.save.includeText }; this.register({ id: UUID.generateUuid(), registerOptions: Object.assign({}, { documentSelector: documentSelector }, saveOptions) }); } } public register(data: RegistrationData<TextDocumentSaveRegistrationOptions>): void { this._includeText = !!data.registerOptions.includeText; super.register(data); } }
the_stack
export function createElement(name: string, props: Props, ...children: Node[]): Element; /** * Creates a new JSX fragment. * * A fragment is just an element without a name, but when inserted somewhere in the element tree, it disappears. * @example * const fragment = * <> * <div>Element 1</div> * <div>Element 2</div> * </> * const app = * <div> * some text * {fragment} * some more text * </div> * // equivalent to * const app = * <div> * some text * <div>Element 1</div> * <div>Element 2</div> * some more text * </div> * @param children The elements in the fragment. * @returns The newly created fragment. */ export function createElement(name: Fragment, props: Props, ...children: Node[]): Element; /** * Calls the generator function with the corresponding data and returns the generated element. * @example * const Block = ({ props, children }) => ( * <div class="block" {...props}> * <div class="blockHeader">{props.title}</div> * <div>{children}</div> * </div> // or className * ); * const myBlock = <Block title="A block"> * <a href="">Link</a> * </Block>; * @param generator Element generator function. * @param props The properties/attributes assigned to the element. * @param children Children passed to the element generator. * @returns The created element. */ export function createElement<T extends Props>(generator: ElementGenerator<T>, props: T, ...children: Node[]): Element; /** * Implementation. */ export function createElement(nameOrGenerator: any, props: any, ...children: Node[]): any { if (typeof nameOrGenerator == "function") { return nameOrGenerator(props ?? {}, children); } else if (nameOrGenerator == Fragment) { return new Element(Fragment, {}, children); } else { return new Element(nameOrGenerator, props ?? {}, children); } } /** * Readonly data container for JSX elements. */ export class Element { public children: Node[]; /** * Creates a new element data container. * @param name The name of the element. (Like `div`, `a`, etc.) * @param props The properties/attributes assigned to the element. * @param children Children of the element. */ constructor(public name: string | Fragment | typeof HTML | typeof CASE | typeof DEFAULT | typeof HEAD, public props: Props, children: Node[]) { this.children = flatten(children); } } function flatten(children: Node[]) { const result: Node[] = []; children.forEach(c => { if (c instanceof Array) result.push(...flatten(c)); else if (c instanceof Element && c.name == Fragment) result.push(...flatten(c.children)); else result.push(c); }); return result; } /** * Renders the JSX elements to a string. This function provides the core functionallity. * @param top The first (top) element that should be rendered. * @param options Options to use for rendering. * @param indentation The starting indentation level. Only used when options.indent is set to `true`. */ export function render(top: Element, options: RenderOptions = {}, indentation: number = 0) { options = { indent: false, indentString: "", indentSize: 4, useSelfCloseTags: true, ...options }; return renderInternal(top, options, indentation); } /** * Options for the rendering. */ export interface RenderOptions { /** * This option specifies if the resulting code should be formated and indented. If it is set to `false`, the whole output will be in one line. */ indent?: boolean; /** * Sets the amount of whitespaces used for indenting. Only used when `options.indent` is true. */ indentString?: string; /** * If you don't want to use whitespaces, if you want to use tabs for example, you can set this to your indentation string. If both `options.indentString` and `options.indentSize` are set, this one (`options.indentString`) will be prefered. */ indentSize?: number; /** * When you don't have children in an element, it will be outputed like `<div />`. If this is set to false, it will normally output both tags. If you even specify a list of strings, the self-closing will only be rendered for tags in that list. This is very useful when rendering web pages with `img` or `input` elements inside. */ useSelfCloseTags?: boolean | string[]; } function renderInternal(node: Node, options: RenderOptions, indentation: number): string { if (typeof node == "string") { return createIndent(options, indentation) + node; } else if (node instanceof Array) { return node.map(n => renderInternal(n, options, indentation)).join(options.indent ? "\n" : ""); } else if (node.name == Fragment) { return node.children.map(n => renderInternal(n, options, indentation)).join(options.indent ? "\n" : ""); } else if (node.name == HTML) { const indentString = createIndent(options, indentation); const children = [...node.children]; let index = children.findIndex(n => n instanceof Element && n.name == HEAD); let head: Node[]; if (index == -1) head = []; else { head = (children[index] as Element).children; children.splice(index, 1); } let result = `${indentString}<!DOCTYPE html>${options.indent ? "\n" : ""}`; result += `${indentString}<html>${options.indent ? "\n" : ""}`; result += `${indentString}<head>${options.indent ? "\n" : ""}`; result += renderInternal(head, options, indentation + 1) + (options.indent && head.length > 0 ? "\n" : ""); result += `${indentString}</head>${options.indent ? "\n" : ""}`; result += `${indentString}<body>${options.indent ? "\n" : ""}`; result += children.map(n => renderInternal(n, options, indentation + 1)).join(options.indent ? "\n" : ""); if (children.length > 0 && options.indent) result += "\n"; result += `${indentString}</body>${options.indent ? "\n" : ""}`; result += `${indentString}</html>`; return result; } else if (node.name == HEAD) { return ""; } else if (node.name == CASE || node.name == DEFAULT) { return renderInternal(node.children, options, indentation); } else { const selfClose = node.children.length == 0 && (options.useSelfCloseTags == true || (options.useSelfCloseTags instanceof Array && options.useSelfCloseTags.includes(node.name as string))); if (node.props.className && !node.props.class) node.props.class = node.props.className; const props = { ...node.props }; if (props.className && !props.class) props.class = props.className; delete props.className; const attrs = createAttrs(node.props); const indentString = createIndent(options, indentation); let result = `${indentString}<${node.name as string}${attrs}${selfClose ? " /" : ""}>`; if (!selfClose) { if (node.children.length > 0 && options.indent) result += "\n"; result += node.children.map(n => renderInternal(n, options, indentation + 1)).join(options.indent ? "\n" : ""); if (node.children.length > 0 && options.indent) result += `\n${indentString}`; result += `</${node.name as string}>`; } return result; } } function createIndent(options: RenderOptions, indentation: number): string { if (!options.indent) return ""; if (options.indentString != "") return options.indentString.repeat(indentation); if (options.indentSize != 0) return " ".repeat(indentation * options.indentSize); return ""; } function createAttrs(props: Props) { const attrKeys = Object.keys(props); const attrs: string[] = []; attrKeys.forEach(k => { attrs.push(" " + k + (props[k] === true ? "" : `="${props[k]}"`)); }); return attrs.join(""); } export function create(options: RenderOptions = {}): ExpressRenderer { if (options.useSelfCloseTags == null) options.useSelfCloseTags = [ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "input", "link", "meta", "param", "source", "track", "wbr" ]; let renderer: ExpressRenderer = Object.assign( function (top: Element) { if (top.name != HTML) top = new Element(HTML, {}, [top]); return render(top, options); }, { createHandler(component: ElementGenerator<{ req: ExpressRequest, res: ExpressResponse }>, status?: number) { return (req: ExpressRequest, res: ExpressResponse) => { let element = createElement(component, { req, res }); if (element.name != HTML) element = new Element(HTML, {}, [element]); let actualStatus; if (status != null) { actualStatus = status; } else if (typeof element.props.status == "number") { actualStatus = element.props.status; } else { actualStatus = 200; } res.status(actualStatus).send(renderer(element)); }; } } ); return renderer; } /** * Symbol indicating that the element is a fragment. */ export const Fragment = Symbol("Fragment"); /** * Element for an HTML page (including DOCTYPE, head and body). */ export const HtmlPage: ElementGenerator<{ [key: string]: any, status?: number }> = (props, children) => { return new Element(HTML, props, children); } const HTML = Symbol("HTML"); /** * Helper component for conditional elements. */ export const If: ElementGenerator<{ cond: boolean }> = ({ cond }, children) => { if (cond) return new Element(Fragment, {}, children); else return new Element(Fragment, {}, []); } /** * Helper component for multiple case szenarios. */ export const Switch: ElementGenerator<{ expr: any }> = ({ expr }, children) => { const found = children.find(c => c instanceof Element && c.name == CASE && c.props.c == expr) as Element; if (found) return new Element(Fragment, {}, found.children); const def = children.find(c => c instanceof Element && c.name == DEFAULT) as Element; if (def) return new Element(Fragment, {}, def.children); return new Element(Fragment, {}, []); }; export const Case: ElementGenerator<{ c: any }> = ({ c }, children) => { return new Element(CASE, { c }, children); } export const Default: ElementGenerator<{}> = (_, children) => { return new Element(DEFAULT, {}, children); } const CASE = Symbol("Case"); const DEFAULT = Symbol("Default"); export const Head: ElementGenerator = (props, children) => { return new Element(HEAD, props, children); } const HEAD = Symbol("Head"); /** * Element attributes/properties type. */ export type Props = { [key: string]: any }; /** * Type for an element fragment. */ export type Fragment = typeof Fragment; /** * Node (JSX element like text, elements, and arrays) type. */ export type Node = Element | string | Node[]; /** * Function for generating elements. */ export type ElementGenerator<T extends Props = {}> = (props: T, children: Node[]) => Element; /** * Return type for the `jsxt.create` function. */ export interface ExpressRenderer { (top: Element): string; createHandler(component: ElementGenerator<{ req: ExpressRequest, res: ExpressResponse }>, status?: number): (req: ExpressRequest, res: ExpressResponse) => void; } import type { Request as ExpressRequest, Response as ExpressResponse } from "express"; declare global { export namespace JSX { interface IntrinsicElements { [key: string]: any; } } } export default { createElement, Element, render, Fragment, HtmlPage, create, }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Cost Management Export for a Subscription. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleSubscription = azure.core.getSubscription({}); * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleAccount = new azure.storage.Account("exampleAccount", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * accountTier: "Standard", * accountReplicationType: "LRS", * }); * const exampleContainer = new azure.storage.Container("exampleContainer", {storageAccountName: azurerm_storage_account.test.name}); * const exampleSubscriptionCostManagementExport = new azure.core.SubscriptionCostManagementExport("exampleSubscriptionCostManagementExport", { * subscriptionId: azurerm_subscription.example.id, * recurrenceType: "Monthly", * recurrencePeriodStartDate: "2020-08-18T00:00:00Z", * recurrencePeriodEndDate: "2020-09-18T00:00:00Z", * exportDataStorageLocation: { * containerId: exampleContainer.resourceManagerId, * rootFolderPath: "/root/updated", * }, * exportDataOptions: { * type: "Usage", * timeFrame: "WeekToDate", * }, * }); * ``` * * ## Import * * Subscription Cost Management Exports can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:core/subscriptionCostManagementExport:SubscriptionCostManagementExport example /subscriptions/12345678-1234-9876-4563-123456789012/providers/Microsoft.CostManagement/exports/export1 * ``` */ export class SubscriptionCostManagementExport extends pulumi.CustomResource { /** * Get an existing SubscriptionCostManagementExport resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: SubscriptionCostManagementExportState, opts?: pulumi.CustomResourceOptions): SubscriptionCostManagementExport { return new SubscriptionCostManagementExport(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:core/subscriptionCostManagementExport:SubscriptionCostManagementExport'; /** * Returns true if the given object is an instance of SubscriptionCostManagementExport. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is SubscriptionCostManagementExport { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === SubscriptionCostManagementExport.__pulumiType; } /** * Is the cost management export active? Default is `true`. */ public readonly active!: pulumi.Output<boolean | undefined>; /** * A `exportDataOptions` block as defined below. */ public readonly exportDataOptions!: pulumi.Output<outputs.core.SubscriptionCostManagementExportExportDataOptions>; /** * A `exportDataStorageLocation` block as defined below. */ public readonly exportDataStorageLocation!: pulumi.Output<outputs.core.SubscriptionCostManagementExportExportDataStorageLocation>; /** * Specifies the name of the Cost Management Export. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; public readonly recurrencePeriodEndDate!: pulumi.Output<string>; /** * The date the export will start capturing information. */ public readonly recurrencePeriodStartDate!: pulumi.Output<string>; /** * How often the requested information will be exported. Valid values include `Annually`, `Daily`, `Monthly`, `Weekly`. */ public readonly recurrenceType!: pulumi.Output<string>; /** * The id of the subscription on which to create an export. */ public readonly subscriptionId!: pulumi.Output<string>; /** * Create a SubscriptionCostManagementExport resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: SubscriptionCostManagementExportArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: SubscriptionCostManagementExportArgs | SubscriptionCostManagementExportState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as SubscriptionCostManagementExportState | undefined; inputs["active"] = state ? state.active : undefined; inputs["exportDataOptions"] = state ? state.exportDataOptions : undefined; inputs["exportDataStorageLocation"] = state ? state.exportDataStorageLocation : undefined; inputs["name"] = state ? state.name : undefined; inputs["recurrencePeriodEndDate"] = state ? state.recurrencePeriodEndDate : undefined; inputs["recurrencePeriodStartDate"] = state ? state.recurrencePeriodStartDate : undefined; inputs["recurrenceType"] = state ? state.recurrenceType : undefined; inputs["subscriptionId"] = state ? state.subscriptionId : undefined; } else { const args = argsOrState as SubscriptionCostManagementExportArgs | undefined; if ((!args || args.exportDataOptions === undefined) && !opts.urn) { throw new Error("Missing required property 'exportDataOptions'"); } if ((!args || args.exportDataStorageLocation === undefined) && !opts.urn) { throw new Error("Missing required property 'exportDataStorageLocation'"); } if ((!args || args.recurrencePeriodEndDate === undefined) && !opts.urn) { throw new Error("Missing required property 'recurrencePeriodEndDate'"); } if ((!args || args.recurrencePeriodStartDate === undefined) && !opts.urn) { throw new Error("Missing required property 'recurrencePeriodStartDate'"); } if ((!args || args.recurrenceType === undefined) && !opts.urn) { throw new Error("Missing required property 'recurrenceType'"); } if ((!args || args.subscriptionId === undefined) && !opts.urn) { throw new Error("Missing required property 'subscriptionId'"); } inputs["active"] = args ? args.active : undefined; inputs["exportDataOptions"] = args ? args.exportDataOptions : undefined; inputs["exportDataStorageLocation"] = args ? args.exportDataStorageLocation : undefined; inputs["name"] = args ? args.name : undefined; inputs["recurrencePeriodEndDate"] = args ? args.recurrencePeriodEndDate : undefined; inputs["recurrencePeriodStartDate"] = args ? args.recurrencePeriodStartDate : undefined; inputs["recurrenceType"] = args ? args.recurrenceType : undefined; inputs["subscriptionId"] = args ? args.subscriptionId : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(SubscriptionCostManagementExport.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering SubscriptionCostManagementExport resources. */ export interface SubscriptionCostManagementExportState { /** * Is the cost management export active? Default is `true`. */ active?: pulumi.Input<boolean>; /** * A `exportDataOptions` block as defined below. */ exportDataOptions?: pulumi.Input<inputs.core.SubscriptionCostManagementExportExportDataOptions>; /** * A `exportDataStorageLocation` block as defined below. */ exportDataStorageLocation?: pulumi.Input<inputs.core.SubscriptionCostManagementExportExportDataStorageLocation>; /** * Specifies the name of the Cost Management Export. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; recurrencePeriodEndDate?: pulumi.Input<string>; /** * The date the export will start capturing information. */ recurrencePeriodStartDate?: pulumi.Input<string>; /** * How often the requested information will be exported. Valid values include `Annually`, `Daily`, `Monthly`, `Weekly`. */ recurrenceType?: pulumi.Input<string>; /** * The id of the subscription on which to create an export. */ subscriptionId?: pulumi.Input<string>; } /** * The set of arguments for constructing a SubscriptionCostManagementExport resource. */ export interface SubscriptionCostManagementExportArgs { /** * Is the cost management export active? Default is `true`. */ active?: pulumi.Input<boolean>; /** * A `exportDataOptions` block as defined below. */ exportDataOptions: pulumi.Input<inputs.core.SubscriptionCostManagementExportExportDataOptions>; /** * A `exportDataStorageLocation` block as defined below. */ exportDataStorageLocation: pulumi.Input<inputs.core.SubscriptionCostManagementExportExportDataStorageLocation>; /** * Specifies the name of the Cost Management Export. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; recurrencePeriodEndDate: pulumi.Input<string>; /** * The date the export will start capturing information. */ recurrencePeriodStartDate: pulumi.Input<string>; /** * How often the requested information will be exported. Valid values include `Annually`, `Daily`, `Monthly`, `Weekly`. */ recurrenceType: pulumi.Input<string>; /** * The id of the subscription on which to create an export. */ subscriptionId: pulumi.Input<string>; }
the_stack
import { IComponent } from "../types"; import { Vnode, TAttributes, isRepeatNode, isTextNode, isDirective, isEventDirective, isPropOrNvDirective, isTagName } from "../vnode"; import { cloneVnode, copyRepeatData, isFromVM, buildProps, argumentsIsReady, getVMFunctionArguments, getValueByValue, getVMVal, getVMFunction, setVMVal, valueIsReady } from './utils'; import { utils } from '../utils'; import { CompileRepeatUtil } from './compile-repeat-util'; import { ChangeDetectionStrategy } from '../component'; import { buildPipeScope } from "./compiler-utils"; /** * compile util for Compiler * * @export * @class CompileUtil */ export class CompileUtil { [index: string]: any; public fragment?: Vnode[]; /** * Creates an instance of CompileUtil. * * @param {Vnode[]} [fragment] * @memberof CompileUtil */ constructor(fragment?: Vnode[]) { this.fragment = fragment; } /** * get value by repeat value * * @param {*} vm * @param {string} exp * @returns {void} * @memberof CompileUtil */ public _getVMRepeatVal(vm: any, exp: string): void { const _vlList = exp.split(' in ')[1]; if (!_vlList) throw new Error(`directive nv-repeat 's expression ${exp} is wrong!`); const vlList = _vlList.replace(/\s*/g, ''); const value = getVMVal(vm, vlList); return value; } /** * bind handler for nv irective * * if node is repeat node and it will break compile and into CompileRepeatUtil * * @param {Vnode} vnode * @param {*} vm * @param {string} exp * @param {string} dir * @memberof CompileUtil */ public bind(vnode: Vnode, vm: IComponent, exp: string, dir: string): void { const isRepeatNodeBoolean = isRepeatNode(vnode); if (isRepeatNodeBoolean) { // compile repeatNode's attributes switch (dir) { case 'repeat': this.repeatUpdater(vnode, this._getVMRepeatVal(vm, exp), exp, vm); break; } } else { let value = null; // 拆分管道pipe const needCompileStringList = exp.split('|').map(v => v.trim()); const needCompileValue = needCompileStringList[0]; // for Function(arg) if (/^.*\(.*\)$/.test(needCompileValue)) { if (dir === 'model') throw new Error(`directive: nv-model can't use ${needCompileValue} as prop`); // if Function need function return value const fn = getVMFunction(vm, needCompileValue); const argsList = getVMFunctionArguments(vm, needCompileValue, vnode); value = this.pipeHandler(exp, fn.apply(vm, argsList), needCompileStringList, vm, vnode); // normal value } else if (isFromVM(vm, needCompileValue)) value = this.pipeHandler(exp, getVMVal(vm, needCompileValue), needCompileStringList, vm, vnode); else if (/^\'.*\'$/.test(needCompileValue)) value = this.pipeHandler(exp, needCompileValue.match(/^\'(.*)\'$/)[1], needCompileStringList, vm, vnode); else if (/^\".*\"$/.test(needCompileValue)) value = this.pipeHandler(exp, needCompileValue.match(/^\"(.*)\"$/)[1], needCompileStringList, vm, vnode); else if (!/^\'.*\'$/.test(needCompileValue) && !/^\".*\"$/.test(needCompileValue) && /(^[-,+]?\d+$)|(^[-, +]?\d+\.\d+$)/g.test(needCompileValue)) value = this.pipeHandler(exp, Number(needCompileValue), needCompileStringList, vm, vnode); else if (needCompileValue === 'true' || needCompileValue === 'false') value = this.pipeHandler(exp, (needCompileValue === 'true'), needCompileStringList, vm, vnode); else if (needCompileValue === 'null') value = this.pipeHandler(exp, null, needCompileStringList, vm, vnode); else if (needCompileValue === 'undefined') value = this.pipeHandler(exp, undefined, needCompileStringList, vm, vnode); else if (vnode.repeatData) { Object.keys(vnode.repeatData).forEach(data => { if (needCompileValue === data || needCompileValue.indexOf(`${data}.`) === 0) value = this.pipeHandler(exp, getValueByValue(vnode.repeatData[data], needCompileValue, data), needCompileStringList, vm, vnode); }); } else throw new Error(`directive: nv-${dir} can't use recognize this value ${needCompileValue} as prop`); // compile unrepeatNode's attributes switch (dir) { case 'model': { this.modelUpdater(vnode, value, needCompileValue, vm); break; } case 'text': { this.textUpdater(vnode, value); break; } case 'if': { this.ifUpdater(vnode, value); break; } case 'if-not': { this.ifNotUpdater(vnode, value); break; } case 'class': { this.classUpdater(vnode, value); break; } case 'key': { this.keyUpdater(vnode, value); break; } case 'value': { this.valueUpdater(vnode, value); break; } default: this.commonUpdater(vnode, value, dir); } } } /** * update text for {{}} * * @param Vnode node * @param {*} vm * @param {string} exp * @memberof CompileUtil */ public templateUpdater(vnode: Vnode, vm: any, exp: string): void { const _exp = exp.replace('{{', '').replace('}}', ''); // 拆分管道pipe const needCompileStringList = _exp.split('|').map(v => v.trim()); const needCompileValue = needCompileStringList[0]; if (/^.*\(.*\)$/.test(needCompileValue) && argumentsIsReady(needCompileValue, vnode, vm)) { const fn = getVMFunction(vm, needCompileValue); const argsList = getVMFunctionArguments(vm, needCompileValue, vnode); const fromVmValue = this.pipeHandler(exp, fn.apply(vm, argsList), needCompileStringList, vm, vnode); vnode.nodeValue = vnode.nodeValue.replace(exp, fromVmValue); } else if (isFromVM(vm, needCompileValue)) { const fromVmValue = this.pipeHandler(exp, getVMVal(vm, needCompileValue), needCompileStringList, vm, vnode); vnode.nodeValue = vnode.nodeValue.replace(exp, fromVmValue); } else if (vnode.repeatData) { Object.keys(vnode.repeatData).forEach(data => { if (exp === data || exp.indexOf(`${data}.`) === 0) { const fromVmValue = this.pipeHandler(exp, getValueByValue(vnode.repeatData[data], exp, data), needCompileStringList, vm, vnode); vnode.nodeValue = vnode.nodeValue.replace(exp, fromVmValue); } }); } else throw new Error(`directive: ${exp} can't use recognize this value`); } /** * update value of input for nv-model * * @param {Vnode} vnode * @param {*} value * @param {string} exp * @param {*} vm * @memberof CompileUtil */ public modelUpdater(vnode: Vnode, value: any, exp: string, vm: any): void { vnode.value = typeof value === 'undefined' ? '' : value; const findAttribute = vnode.attributes.find(attr => attr.name === 'nv-model'); findAttribute.nvValue = (typeof value === 'undefined' ? '' : value); const func = (event: Event) => { event.preventDefault(); if (!utils.hasWindowAndDocument()) return; if (isFromVM(vm, exp)) setVMVal(vm, exp, (event.target as HTMLInputElement).value); // OnPush 模式要允许触发更新 if ((vm as IComponent).$nvChangeDetection === ChangeDetectionStrategy.OnPush) { if ((vm as IComponent).nvDoCheck) (vm as IComponent).nvDoCheck(); (vm as IComponent).render(); } }; const sameEventType = vnode.eventTypes.find(_eventType => _eventType.type === 'input'); if (sameEventType) sameEventType.handler = func; if (!sameEventType) vnode.eventTypes.push({ type: 'input', handler: func, token: value, }); } /** * update text for nv-text * * @param {Vnode} vnode * @param {*} value * @returns {void} * @memberof CompileUtil */ public textUpdater(vnode: Vnode, value: any): void { const findAttribute = vnode.attributes.find(attr => attr.name === 'nv-text'); findAttribute.nvValue = (typeof value === 'undefined' ? '' : value); vnode.nodeValue = typeof value === 'undefined' ? '' : value; if (!vnode.childNodes || (vnode.childNodes && vnode.childNodes.length > 0)) vnode.childNodes = []; vnode.childNodes.push(new Vnode({ type: 'text', nodeValue: typeof value === 'undefined' ? '' : value, parentVnode: vnode, template: typeof value === 'undefined' ? '' : value, voidElement: true, })); vnode.voidElement = true; } /** * remove or show for nv-if * * @param {Vnode} vnode * @param {*} value * @memberof CompileUtil */ public ifUpdater(vnode: Vnode, value: any): void { const valueOfBoolean = Boolean(value); if (!valueOfBoolean && vnode.parentVnode.childNodes.indexOf(vnode) !== -1) vnode.parentVnode.childNodes.splice(vnode.parentVnode.childNodes.indexOf(vnode), 1); if (valueOfBoolean) { const findAttribute = vnode.attributes.find(attr => attr.name === 'nv-if'); findAttribute.nvValue = valueOfBoolean; } } /** * remove or show for nv-if-not * * @param {Vnode} vnode * @param {*} value * @memberof CompileUtil */ public ifNotUpdater(vnode: Vnode, value: any): void { const valueOfBoolean = !Boolean(value); if (!valueOfBoolean && vnode.parentVnode.childNodes.indexOf(vnode) !== -1) vnode.parentVnode.childNodes.splice(vnode.parentVnode.childNodes.indexOf(vnode), 1); if (valueOfBoolean) { const findAttribute = vnode.attributes.find(attr => attr.name === 'nv-if-not'); findAttribute.nvValue = valueOfBoolean; } } /** * update class for nv-class * * @param {Vnode} vnode * @param {*} value * @returns {void} * @memberof CompileUtil */ public classUpdater(vnode: Vnode, value: any): void { const findAttribute = vnode.attributes.find(attr => attr.name === 'nv-class'); findAttribute.nvValue = value; } /** * update value of repeat node for nv-key * * @param {Vnode} vnode * @param {*} value * @memberof CompileRepeatUtil */ public keyUpdater(vnode: Vnode, value: any): void { const findAttribute = vnode.attributes.find(attr => attr.name === 'nv-key'); findAttribute.nvValue = value; vnode.key = value; } /** * update value of node for nv-value * * @param {Vnode} vnode * @param {*} value * @memberof CompileRepeatUtil */ public valueUpdater(vnode: Vnode, value: any): void { const findAttribute = vnode.attributes.find(attr => attr.name === 'nv-value'); findAttribute.nvValue = value; vnode.value = value; } /** * commonUpdater for nv directive except repeat model text if class * * @param {Vnode} vnode * @param {*} value * @param {string} dir * @memberof CompileUtil */ public commonUpdater(vnode: Vnode, value: any, dir: string): void { const findAttribute = vnode.attributes.find(attr => attr.name === `nv-${dir}`); findAttribute.nvValue = value; } /** * update repeat Vnode for nv-repeat * * if it has child and it will into repeatChildrenUpdater * * @param {Vnode} vnode * @param {*} value * @param {string} expFather * @param {*} vm * @memberof CompileUtil */ public repeatUpdater(vnode: Vnode, value: any, expFather: string, vm: any): void { if (!value) return; if (!Array.isArray(value)) throw new Error('compile error: nv-repeat need an Array!'); const _key = expFather.split(' in ')[0]; if (!_key) throw new Error(`directive nv-repeat 's expression ${expFather} is wrong!`); const key = _key.replace(/\s*/g, ''); value.forEach((val: any, index: number) => { const repeatData: { [key: string]: any } = { ...vnode.repeatData }; repeatData[key] = val; repeatData.$index = index; const newVnode = cloneVnode(vnode, repeatData); newVnode.index = index; const nodeAttrs = newVnode.attributes; const text = newVnode.template; const reg = /\{\{(.*)\}\}/g; const compileUtilForRepeat = new CompileRepeatUtil(); this.fragment.splice(this.fragment.indexOf(vnode), 0, newVnode); if (isTextNode(newVnode) && reg.test(text)) compileUtilForRepeat.templateUpdater(newVnode, val, key, vm); if (nodeAttrs) { nodeAttrs.forEach(attr => { const attrName = attr.name; const dir = attrName.substring(3); const exp = attr.value; if (isDirective(attr.type) && attrName !== 'nv-repeat' && valueIsReady(exp, newVnode, vm) && argumentsIsReady(exp, newVnode, vm)) compileUtilForRepeat.bind(newVnode, key, dir, exp, index, vm, value, val); if (isEventDirective(attr.type) && attrName !== 'nv-repeat' && valueIsReady(exp, newVnode, vm) && argumentsIsReady(exp, newVnode, vm)) compileUtilForRepeat.eventHandler(newVnode, vm, exp, dir, key, val); if (isPropOrNvDirective(attr.type)) { const _exp = /^\{(.+)\}$/.exec(exp)[1]; if (valueIsReady(_exp, newVnode, vm) && argumentsIsReady(_exp, newVnode, vm)) compileUtilForRepeat.propHandler(newVnode, vm, attr); } }); } if (newVnode.childNodes && newVnode.childNodes.length > 0 && this.fragment.indexOf(newVnode) !== -1) { // 先根据此次循环的key编译一遍 this.repeatChildrenUpdaterByKey(newVnode, val, expFather, index, vm, value); // 然后再编译子节点 this.repeatChildrenUpdater(newVnode, vm); } }); } /** * update all child value by repeat key * * @param {Vnode} vnode * @param {*} value * @param {string} expFather * @param {number} index * @param {*} vm * @param {*} watchValue * @memberof CompileUtil */ public repeatChildrenUpdaterByKey(vnode: Vnode, value: any, expFather: string, index: number, vm: any, watchValue: any): void { const _key = expFather.split(' in ')[0]; if (!_key) throw new Error(`directive nv-repeat 's expression ${expFather} is wrong!`); const key = _key.replace(/\s*/g, ''); const compileUtilForRepeat = new CompileRepeatUtil(vnode.childNodes); vnode.childNodes.forEach(child => { const repeatData = { ...vnode.repeatData, ...child.repeatData }; repeatData[key] = value; repeatData.$index = index; child.repeatData = repeatData; copyRepeatData(child, repeatData); // 转移到 <nv-content>到组件视图上 const isNvContentVNode = isTagName(child, 'nv-content'); if (isNvContentVNode) child.childNodes = vm.$nvContent.map((content: Vnode) => cloneVnode(content, null, child)); const nodeAttrs = child.attributes; const text = child.template; const reg = /\{\{(.*)\}\}/g; if (isTextNode(child) && reg.test(text)) compileUtilForRepeat.templateUpdater(child, value, key, vm); if (nodeAttrs) { nodeAttrs.forEach(attr => { const attrName = attr.name; const exp = attr.value; const dir = attrName.substring(3); if (isDirective(attr.type) && attrName !== 'nv-repeat' && valueIsReady(exp, vnode, vm) && argumentsIsReady(exp, child, vm)) compileUtilForRepeat.bind(child, key, dir, exp, index, vm, watchValue, value); if (isEventDirective(attr.type) && attrName !== 'nv-repeat' && valueIsReady(exp, vnode, vm) && argumentsIsReady(exp, child, vm)) compileUtilForRepeat.eventHandler(child, vm, exp, dir, key, value); if (isPropOrNvDirective(attr.type)) { const _exp = /^\{(.+)\}$/.exec(exp)[1]; if (valueIsReady(_exp, vnode, vm) && argumentsIsReady(_exp, child, vm)) compileUtilForRepeat.propHandler(child, vm, attr); } }); } // 如果该组件是 <nv-content></nv-content> 则不会参与子组件的更新 if (!isNvContentVNode && child.childNodes && child.childNodes.length > 0) this.repeatChildrenUpdaterByKey(child, value, expFather, index, vm, watchValue); }); } /** * update child if child has nv-repeat directive * * @param {Vnode} vnode * @param {*} vm * @memberof CompileUtil */ public repeatChildrenUpdater(vnode: Vnode, vm: any): void { const _fragmentList: { originChild: Vnode, container: Vnode, }[] = []; vnode.childNodes.forEach(child => { const restRepeat = child.attributes.find(attr => isDirective(attr.type) && attr.name === 'nv-repeat'); if (restRepeat) { // if is repeat vnode, we do this const _value = restRepeat.value.split(' in ')[1]; if (!_value) throw new Error(`directive nv-repeat 's expression ${restRepeat.value} is wrong!`); const newWatchData = _value.replace(/\s*/g, ''); // 创建一个同级于vnode的容器存放新的子元素的容器,最后再统一放入vnode中 const _newContainerFragment = new Vnode(vnode); // 因为确定了是不允许递归的循环node所以子节点要清空 _newContainerFragment.childNodes = []; _newContainerFragment.childNodes.push(child); _fragmentList.push({ originChild: child, container: _newContainerFragment, }); const compileUtil = new CompileUtil(_newContainerFragment.childNodes); if (isFromVM(vm, newWatchData)) compileUtil.repeatUpdater(child, this._getVMRepeatVal(vm, restRepeat.value), restRepeat.value, vm); else if (child.repeatData) { let findData: any; Object.keys(child.repeatData).forEach(dataKey => { if (newWatchData === dataKey || newWatchData.indexOf(`${dataKey}.`) === 0) findData = getValueByValue(child.repeatData[dataKey], newWatchData, dataKey); }); if (findData) compileUtil.repeatUpdater(child, findData, restRepeat.value, vm); } else throw new Error(`dirctive nv-repeat can't use ${newWatchData}`); // remove child from _newContainerFragment.childNodes if (_newContainerFragment.childNodes.indexOf(child) !== -1) _newContainerFragment.childNodes.splice(_newContainerFragment.childNodes.indexOf(child), 1); } else { // if isn't repeat vnode, we repeat it's children this.repeatChildrenUpdater(child, vm); } }); // push repeat child into vnode.childNodes _fragmentList.forEach(_fragmentObject => { if (vnode.childNodes.indexOf(_fragmentObject.originChild) !== -1) vnode.childNodes.splice(vnode.childNodes.indexOf(_fragmentObject.originChild), 0, ..._fragmentObject.container.childNodes); }); // remove child from vnode.childNodes _fragmentList.forEach(_fragmentObject => { if (vnode.childNodes.indexOf(_fragmentObject.originChild) !== -1) vnode.childNodes.splice(vnode.childNodes.indexOf(_fragmentObject.originChild), 1); }); } /** * compile event and build eventType in Vnode * * @param {Vnode} vnode * @param {*} vm * @param {string} exp * @param {string} eventName * @memberof Compile */ public eventHandler(vnode: Vnode, vm: any, exp: string, eventName: string): void { const eventType = eventName.split(':')[1]; const fn = getVMFunction(vm, exp); const args = exp.match(/\((.*)\)/)[1].replace(/\s+/g, '').split(','); const func = function (event: Event): void { const argsList: any[] = []; args.forEach(arg => { if (arg === '') return false; if (arg === '$event') return argsList.push(event); if (arg === '$element' && event.target) return argsList.push(event.target); if (arg === 'true' || arg === 'false') return argsList.push(arg === 'true'); if (arg === 'null') return argsList.push(null); if (arg === 'undefined') return argsList.push(undefined); if (isFromVM(vm, arg)) return argsList.push(getVMVal(vm, arg)); if (/^\'.*\'$/.test(arg)) return argsList.push(arg.match(/^\'(.*)\'$/)[1]); if (/^\".*\"$/.test(arg)) return argsList.push(arg.match(/^\"(.*)\"$/)[1]); if (!/^\'.*\'$/.test(arg) && !/^\".*\"$/.test(arg) && /(^[-,+]?\d+$)|(^[-, +]?\d+\.\d+$)/.test(arg)) return argsList.push(Number(arg)); }); const saveWatchStatus = (vm as IComponent).$watchStatus; if (saveWatchStatus === 'available') (vm as IComponent).$watchStatus = 'pending'; fn.apply(vm, argsList); if (saveWatchStatus === 'available') { (vm as IComponent).$watchStatus = 'available'; if ((vm as IComponent).$isWaitingRender && (vm as IComponent).nvDoCheck) (vm as IComponent).nvDoCheck(); if ((vm as IComponent).$isWaitingRender) { (vm as IComponent).render(); (vm as IComponent).$isWaitingRender = false; } } }; if (eventType && fn) { const sameEventType = vnode.eventTypes.find(_eventType => _eventType.type === eventType); if (sameEventType) { sameEventType.handler = func; sameEventType.token = fn; } if (!sameEventType) vnode.eventTypes.push({ type: eventType, handler: func, token: fn, }); } } /** * handler props * * @param {Vnode} vnode * @param {*} vm * @param {TAttributes} attr * @param {string} prop * @memberof CompileUtil */ public propHandler(vnode: Vnode, vm: any, attr: TAttributes): void { const prop = /^\{(.+)\}$/.exec(attr.value); if (prop) { const propValue = prop[1]; let _prop = null; if (/^.*\(.*\)$/.test(propValue)) { const fn = getVMFunction(vm, propValue); const args = propValue.match(/\((.*)\)/)[1].replace(/\s+/g, '').split(','); const argsList: any[] = []; args.forEach(arg => { if (arg === '') return false; if (arg === '$element') return argsList.push(vnode.nativeElement); if (arg === 'true' || arg === 'false') return argsList.push(arg === 'true'); if (arg === 'null') return argsList.push(null); if (arg === 'undefined') return argsList.push(undefined); if (isFromVM(vm, arg)) return argsList.push(getVMVal(vm, arg)); if (/^\'.*\'$/.test(arg)) return argsList.push(arg.match(/^\'(.*)\'$/)[1]); if (/^\".*\"$/.test(arg)) return argsList.push(arg.match(/^\"(.*)\"$/)[1]); if (!/^\'.*\'$/.test(arg) && !/^\".*\"$/.test(arg) && /(^[-,+]?\d+$)|(^[-, +]?\d+\.\d+$)/g.test(arg)) return argsList.push(Number(arg)); if (vnode.repeatData) { // $index in this Object.keys(vnode.repeatData).forEach(data => { if (arg === data || arg.indexOf(`${data}.`) === 0) return argsList.push(getValueByValue(vnode.repeatData[data], arg, data)); }); } }); const value = fn.apply(vm, argsList); attr.nvValue = value; return; } const valueList = propValue.split('.'); const key = valueList[0]; if (isFromVM(vm, propValue)) { _prop = getVMVal(vm, propValue); attr.nvValue = buildProps(_prop, vm); return; } if (vnode.repeatData && vnode.repeatData.hasOwnProperty(key)) { _prop = getValueByValue(vnode.repeatData[key], propValue, key); attr.nvValue = buildProps(_prop, vm); return; } if (/^\'.*\'$/.test(propValue)) { attr.nvValue = propValue.match(/^\'(.*)\'$/)[1]; return; } if (/^\".*\"$/.test(propValue)) { attr.nvValue = propValue.match(/^\"(.*)\"$/)[1]; return; } if (!/^\'.*\'$/.test(propValue) && !/^\".*\"$/.test(propValue) && /(^[-,+]?\d+$)|(^[-, +]?\d+\.\d+$)/.test(propValue)) { attr.nvValue = Number(propValue); return; } if (propValue === 'true' || propValue === 'false') { attr.nvValue = (propValue === 'true'); return; } if (propValue === 'null') { attr.nvValue = null; return; } if (propValue === 'undefined') { attr.nvValue = undefined; return; } } } public pipeHandler(oldExp: string, value: any, needCompileStringList: string[], vm: any, vnode: Vnode): any { let canCompileFlag = true; let fromVmValue = value; if (needCompileStringList.length > 1) { needCompileStringList.forEach((need, index) => { if (index !== 0) { const pipeArgusList: string[] = []; let pipeName = ''; // need: test-pipe: 1:2 分离管道名和参数 need.split(':').forEach((v, i) => { if (i === 0) pipeName = v.trim(); else pipeArgusList.push(v.trim()); }); const argList: any[] = []; pipeArgusList.forEach(pipeArgu => { // 参数没准备好,不允许编译 if (!valueIsReady(pipeArgu, vnode, vm)) { canCompileFlag = false; return; } let pipeArguValue = null; if (isFromVM(vm, pipeArgu)) pipeArguValue = getVMVal(vm, pipeArgu); else if (/^\'.*\'$/.test(pipeArgu)) pipeArguValue = pipeArgu.match(/^\'(.*)\'$/)[1]; else if (/^\".*\"$/.test(pipeArgu)) pipeArguValue = pipeArgu.match(/^\"(.*)\"$/)[1]; else if (!/^\'.*\'$/.test(pipeArgu) && !/^\".*\"$/.test(pipeArgu) && /(^[-,+]?\d+$)|(^[-, +]?\d+\.\d+$)/g.test(pipeArgu)) pipeArguValue = Number(pipeArgu); else if (pipeArgu === 'true' || pipeArgu === 'false') pipeArguValue = (pipeArgu === 'true'); else if (pipeArgu === 'null') pipeArguValue = null; else if (pipeArgu === 'undefined') pipeArguValue = undefined; else if (vnode.repeatData) { Object.keys(vnode.repeatData).forEach(data => { if (pipeArgu === data || pipeArgu.indexOf(`${data}.`) === 0) pipeArguValue = getValueByValue(vnode.repeatData[data], pipeArgu, data); }); } argList.push(pipeArguValue); }); // 如果管道参数可以渲染则获取管道结果 if (canCompileFlag) { // 通过组件中的$declarationMap获取管道实例 const PipeClass = vm.$declarationMap.get(pipeName); // 获取管道实例 const pipeInstance = buildPipeScope(PipeClass, vm.$nativeElement, vm); // 调用管道的transform方法 if (!pipeInstance.transform) throw Error(`Pipe ${pipeName} don't implement the method 'transform'`); fromVmValue = pipeInstance.transform(value, ...argList); } } }); } if (canCompileFlag) return fromVmValue; else return oldExp; } }
the_stack
import moment from 'moment'; import React from 'react'; import { Chart as ChartJS, ArcElement, LineElement, BarElement, PointElement, BarController, BubbleController, DoughnutController, LineController, PieController, PolarAreaController, RadarController, ScatterController, CategoryScale, LinearScale, LogarithmicScale, RadialLinearScale, TimeScale, TimeSeriesScale, Decimation, Filler, Legend, Title, Tooltip, SubTitle } from 'chart.js'; import { Line } from 'react-chartjs-2'; ChartJS.register( ArcElement, LineElement, BarElement, PointElement, BarController, BubbleController, DoughnutController, LineController, PieController, PolarAreaController, RadarController, ScatterController, CategoryScale, LinearScale, LogarithmicScale, RadialLinearScale, TimeScale, TimeSeriesScale, Decimation, Filler, Legend, Title, Tooltip, SubTitle ); type Props = { chartData: {x: string, y: string}[]; timePeriod: string; }; const Chart = ({ chartData, timePeriod }: Props) => { const options: Object = { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: true, position: top, title: "Lambda Invocations", }, title: { display: true, text: 'Lambda Activity', align: 'center', }, }, scales: { x: { display: true, grid: { display: false, }, title: { display: true } }, y: { display: true, grid: { display: false, }, title: { display: true } }, } }; let labels: string[] = [] let testData: {date: any, calls: any }[] = []; let testDatapoints: number[] = []; //MONTH if (timePeriod === '30d' && chartData){ testData = []; labels = []; const popArray = () => { for (let i = 0; i < 31; i++){ let date = moment(); labels.push(date.subtract(i, 'day').format('MM-DD')) } labels.reverse() } popArray(); const popData = () => { //FORMAT DATA FROM AWS for (let i = 0; i < chartData.length; i++){ if (chartData[i - 1] && chartData[i - 1].x.slice(5, 10) === chartData[i].x.slice(5, 10)){ if (testData[testData.length - 1]){ testData[testData.length - 1].calls += chartData[i].y } } else { testData.push({"date": chartData[i].x.slice(5, 10), "calls": chartData[i].y}) } } //CREATE DATAPOINTS ARRAY testDatapoints = []; for (let i = 0; i < labels.length; i++){ if (testData[0] && labels[i] === testData[0].date){ testDatapoints.push(testData[0].calls) testData.shift(); } else { testDatapoints.push(0) } } } popData(); } //TWO WEEKS if (timePeriod === '14d' && chartData){ labels = []; testData = []; const popArray = () => { for (let i = 0; i < 15; i++){ let date = moment(); labels.push(date.subtract(i, 'day').format('MM-DD')) } labels.reverse() } popArray(); const popData = () => { //FORMAT DATA FROM AWS for (let i = 0; i < chartData.length; i++){ if (chartData[i - 1] && chartData[i - 1].x.slice(5, 10) === chartData[i].x.slice(5, 10)){ if (testData[testData.length - 1]){ testData[testData.length - 1].calls += chartData[i].y } } else { testData.push({"date": chartData[i].x.slice(5, 10), "calls": chartData[i].y}) } } //CREATE DATAPOINTS ARRAY testDatapoints = []; for (let i = 0; i < labels.length; i++){ if (testData[0] && labels[i] === testData[0].date){ testDatapoints.push(testData[0].calls) testData.shift(); } else { testDatapoints.push(0) } } } popData(); } //ONE WEEK if (timePeriod === '7d' && chartData){ labels = []; testData = []; const popArray = () => { for (let i = 0; i < 8; i++){ let date = moment(); labels.push(date.subtract(i, 'day').format('MM-DD')) } labels.reverse() } popArray(); const popData = () => { //FORMAT DATA FROM AWS for (let i = 0; i < chartData.length; i++){ if (chartData[i - 1] && chartData[i - 1].x.slice(5, 10) === chartData[i].x.slice(5, 10)){ if (testData[testData.length - 1]){ testData[testData.length - 1].calls += chartData[i].y } } else { testData.push({"date": chartData[i].x.slice(5, 10), "calls": chartData[i].y}) } } //CREATE DATAPOINTS ARRAY testDatapoints = []; for (let i = 0; i < labels.length; i++){ if (testData[0] && labels[i] === testData[0].date){ testDatapoints.push(testData[0].calls) testData.shift(); } else { testDatapoints.push(0) } } } popData(); } //24 HOURS if (timePeriod === '24hr' && chartData){ labels = []; testData = []; const popArray = () => { let testPM = moment().format('hA') if (testPM.includes("PM")){ let now: any = moment().format('h') let start = now - 12 let parsedNow = parseInt(now) + 12 for (let i = start; i < parsedNow; i++){ labels.push(moment().hour(i).format('hA')) } } else { let now: any = moment().format('h') let start = now - 23 for (let i = start; i < now; i++){ labels.push(moment().hour(i).format('hA')) } } } popArray(); const popData = () => { //FORMAT DATA FROM AWS for (let i = 0; i < chartData.length; i++){ if (chartData[i - 1] && chartData[i - 1].x.slice(11, 13) === chartData[i].x.slice(11, 13)){ if (testData[testData.length - 1]){ testData[testData.length - 1].calls += chartData[i].y } } else { testData.push({"date": chartData[i].x.slice(11, 13), "calls": chartData[i].y}) } } //FORMAT RESPONSE FOR h:A FROM MOMENT for (let i = 0; i < testData.length; i++){ testData[i].date = parseInt(testData[i].date) testData[i].date -= 5; if (testData[i].date > 12){ testData[i].date -= 12 JSON.stringify(testData[i].date); testData[i].date += "PM" } else{ JSON.stringify(testData[i].date); testData[i].date += "AM" } } //CREATE DATAPOINTS ARRAY testDatapoints = []; for (let i = 0; i < labels.length; i++){ if (testData[0] && labels[i] === testData[0].date){ testDatapoints.push(testData[0].calls) testData.shift(); } else { testDatapoints.push(0) } } } popData(); } //1 HOUR if (timePeriod === '1hr' && chartData){ labels = []; testData = []; const popArray = () => { for (let i = 0; i < 60; i = i + 5){ let date = moment(); labels.push(date.subtract(i, 'minutes').format('h:mmA')) //labels.push(moment().minute(i).format('h:mmA')) } labels.reverse(); } popArray(); const popData = () => { //FORMAT DATA FROM AWS testData = []; for (let i = 0; i < chartData.length; i++){ testData.push({"date": chartData[i].x.slice(14, 16), "calls": chartData[i].y}) } //FORMAT RESPONSE FOR h:A FROM MOMENT //CREATE DATAPOINTS ARRAY testDatapoints = []; for (let i = 0; i < labels.length; i++){ let min; let max; if (labels[i].length > 6 && labels[i+1]) { min = labels[i].slice(3,5) max = labels[i + 1].slice(3,5) } if (labels[i].length < 6 && labels[i+1]) { min = labels[i].slice(2, 4) if (labels[i + 1].length && labels[i + 1].length > 6){ max = labels[i + 1].slice(3, 5) } else max = labels[i + 1].slice(2, 4) } if (!labels[i + 1]){ max = labels[i]; min = labels[i - 1]; } if (testData[0] && parseInt(max) > testData[0].date && parseInt(min) <= testData[0].date){ testDatapoints.push(testData[0].calls) testData.shift(); } else { testDatapoints.push(0) } } } popData(); } //INITIALIZE GRAPH GRAPH let datapoints = testDatapoints const data = { labels, datasets: [ { label: 'Lambda Invocations', data: datapoints, borderColor: '#7c4dff', backgroundColor: '#7c4dff', fontColor: '#FFFFFF', fill: false, tension: 0.4, } ], }; return ( <React.Fragment> <Line options={options} data={data} style={{minHeight: '100%', minWidth: '100%', padding: '1%',}} /> </React.Fragment> ); }; export default Chart;
the_stack
import * as React from 'react'; import CustomTable, { Column, Row, CustomRendererProps } from '../components/CustomTable'; import RunUtils, { ExperimentInfo } from '../../src/lib/RunUtils'; import { Apis, JobSortKeys, ListRequest } from '../lib/Apis'; import { Link, RouteComponentProps } from 'react-router-dom'; import { RoutePage, RouteParams } from '../components/Router'; import { commonCss, color } from '../Css'; import { formatDateString, errorToMessage } from '../lib/Utils'; import Tooltip from '@material-ui/core/Tooltip'; import { ApiJob, ApiTrigger } from '../apis/job'; interface DisplayRecurringRun { experiment?: ExperimentInfo; job: ApiJob; error?: string; } // Both masks cannot be provided together. type MaskProps = Exclude< { experimentIdMask?: string; namespaceMask?: string }, { experimentIdMask: string; namespaceMask: string } >; export type RecurringRunListProps = MaskProps & RouteComponentProps & { disablePaging?: boolean; disableSelection?: boolean; disableSorting?: boolean; hideExperimentColumn?: boolean; noFilterBox?: boolean; onError: (message: string, error: Error) => void; onSelectionChange?: (selectedRunIds: string[]) => void; recurringRunIdListMask?: string[]; selectedIds?: string[]; refreshCount: number; }; interface RecurringRunListState { recurringRuns: DisplayRecurringRun[]; } class RecurringRunList extends React.PureComponent<RecurringRunListProps, RecurringRunListState> { private _tableRef = React.createRef<CustomTable>(); constructor(props: any) { super(props); this.state = { recurringRuns: [], }; } componentDidUpdate(prevProps: { refreshCount: number }) { if (prevProps.refreshCount === this.props.refreshCount) { return; } this.refresh(); } public render(): JSX.Element { const columns: Column[] = [ { customRenderer: this._nameCustomRenderer, flex: 1.5, label: 'Recurring Run Name', sortKey: JobSortKeys.NAME, }, { customRenderer: this._statusCustomRenderer, label: 'Status', flex: 0.5 }, { customRenderer: this._triggerCustomRenderer, label: 'Trigger', flex: 1 }, { label: 'Created at', flex: 1, sortKey: JobSortKeys.CREATED_AT }, ]; if (!this.props.hideExperimentColumn) { columns.splice(3, 0, { customRenderer: this._experimentCustomRenderer, flex: 1, label: 'Experiment', }); } const rows: Row[] = this.state.recurringRuns.map(j => { const row = { error: j.error, id: j.job.id!, otherFields: [ j.job!.name, j.job.status, j.job.trigger, formatDateString(j.job.created_at), ] as any, }; if (!this.props.hideExperimentColumn) { row.otherFields.splice(3, 0, j.experiment); } return row; }); return ( <div> <CustomTable columns={columns} rows={rows} selectedIds={this.props.selectedIds} initialSortColumn={JobSortKeys.CREATED_AT} ref={this._tableRef} filterLabel='Filter recurring runs' updateSelection={this.props.onSelectionChange} reload={this._loadRecurringRuns.bind(this)} disablePaging={this.props.disablePaging} disableSorting={this.props.disableSorting} disableSelection={this.props.disableSelection} noFilterBox={this.props.noFilterBox} emptyMessage={ `No available recurring runs found` + `${ this.props.experimentIdMask ? ' for this experiment' : this.props.namespaceMask ? ' for this namespace' : '' }.` } /> </div> ); } public async refresh(): Promise<void> { if (this._tableRef.current) { await this._tableRef.current.reload(); } } private _nameCustomRenderer: React.FC<CustomRendererProps<string>> = ( props: CustomRendererProps<string>, ) => { return ( <Tooltip title={props.value || ''} enterDelay={300} placement='top-start'> <Link className={commonCss.link} onClick={e => e.stopPropagation()} to={RoutePage.RECURRING_RUN_DETAILS.replace(':' + RouteParams.runId, props.id)} > {props.value} </Link> </Tooltip> ); }; private _experimentCustomRenderer: React.FC<CustomRendererProps<ExperimentInfo>> = ( props: CustomRendererProps<ExperimentInfo>, ) => { // If the getExperiment call failed or a run has no experiment, we display a placeholder. if (!props?.value?.id) { return <div>-</div>; } return ( <Link className={commonCss.link} onClick={e => e.stopPropagation()} to={RoutePage.EXPERIMENT_DETAILS.replace(':' + RouteParams.experimentId, props.value.id)} > {props.value.displayName} </Link> ); }; public _triggerCustomRenderer: React.FC<CustomRendererProps<ApiTrigger>> = ( props: CustomRendererProps<ApiTrigger>, ) => { if (props.value?.cron_schedule) { return <div>Cron: {props.value.cron_schedule.cron}</div>; } if (props.value?.periodic_schedule?.interval_second) { const interval_in_seconds = parseInt(props.value.periodic_schedule.interval_second, 10); if (interval_in_seconds % 86400 === 0) { // days return <div>Every {interval_in_seconds / 86400} days</div>; } if (interval_in_seconds % 3600 === 0) { // hours return <div>Every {interval_in_seconds / 3600} hours</div>; } if (interval_in_seconds % 60 === 0) { // minutes return <div>Every {interval_in_seconds / 60} minutes</div>; } return <div>Every {interval_in_seconds} seconds</div>; } return <div>-</div>; }; public _statusCustomRenderer: React.FC<CustomRendererProps<string>> = ( props: CustomRendererProps<string>, ) => { if (!props.value) { return <div>-</div>; } const textColor = props.value === 'Enabled' ? color.success : props.value === 'Disabled' ? color.inactive : color.errorText; return <div style={{ color: textColor }}>{props.value}</div>; }; protected async _loadRecurringRuns(request: ListRequest): Promise<string> { let displayRecurringRuns: DisplayRecurringRun[] = []; let nextPageToken = ''; if (Array.isArray(this.props.recurringRunIdListMask)) { displayRecurringRuns = this.props.recurringRunIdListMask.map(id => ({ job: { id } })); // listJobs doesn't currently support batching by IDs, so in this case we // retrieve each job individually. await this._getAndSetJobs(displayRecurringRuns); } else { try { let resourceReference: { keyType?: 'EXPERIMENT' | 'NAMESPACE'; keyId?: string; } = {}; if (this.props.experimentIdMask) { resourceReference = { keyType: 'EXPERIMENT', keyId: this.props.experimentIdMask, }; } else if (this.props.namespaceMask) { resourceReference = { keyType: 'NAMESPACE', keyId: this.props.namespaceMask, }; } const response = await Apis.jobServiceApi.listJobs( request.pageToken, request.pageSize, request.sortBy, resourceReference.keyType, resourceReference.keyId, request.filter, ); displayRecurringRuns = (response.jobs || []).map(j => ({ job: j })); nextPageToken = response.next_page_token || ''; } catch (err) { const error = new Error(await errorToMessage(err)); this.props.onError('Error: failed to fetch recurring runs.', error); // No point in continuing if we couldn't retrieve any jobs. return ''; } } await this._setColumns(displayRecurringRuns); this.setState({ recurringRuns: displayRecurringRuns, }); return nextPageToken; } private async _setColumns(displayJobs: DisplayRecurringRun[]): Promise<DisplayRecurringRun[]> { return Promise.all( displayJobs.map(async displayJob => { if (!this.props.hideExperimentColumn) { await this._getAndSetExperimentNames(displayJob); } return displayJob; }), ); } /** * For each job ID, fetch its corresponding job, and set it in DisplayJobs */ private _getAndSetJobs( displayRecurringRuns: DisplayRecurringRun[], ): Promise<DisplayRecurringRun[]> { return Promise.all( displayRecurringRuns.map(async displayRecurringRun => { let getJobResponse: ApiJob; try { getJobResponse = await Apis.jobServiceApi.getJob(displayRecurringRun.job!.id!); displayRecurringRun.job = getJobResponse!; } catch (err) { displayRecurringRun.error = await errorToMessage(err); } return displayRecurringRun; }), ); } /** * For the given DisplayRecurringRun, get its ApiJob and retrieve that ApiJob's Experiment ID if it has * one, then use that Experiment ID to fetch its associated Experiment and attach that * Experiment's name to the DisplayRecurringRun. If the ApiJob has no Experiment ID, then the corresponding * DisplayRecurringRun will show '-'. */ private async _getAndSetExperimentNames(displayRecurringRun: DisplayRecurringRun): Promise<void> { const experimentId = RunUtils.getFirstExperimentReferenceId(displayRecurringRun.job); if (experimentId) { let experimentName = RunUtils.getFirstExperimentReferenceName(displayRecurringRun.job); if (!experimentName) { try { const experiment = await Apis.experimentServiceApi.getExperiment(experimentId); experimentName = experiment.name || ''; } catch (err) { displayRecurringRun.error = 'Failed to get associated experiment: ' + (await errorToMessage(err)); return; } } displayRecurringRun.experiment = { displayName: experimentName, id: experimentId, }; } } } export default RecurringRunList;
the_stack
import { GenderEnum, EthnicityEnum, EyeColorEnum, HairColorEnum, BreastTypeEnum, DateAccuracyEnum, FingerprintAlgorithm } from "./globalTypes"; // ==================================================== // GraphQL fragment: EditDetailsFragment // ==================================================== export interface EditDetailsFragment_TagEdit { __typename: "TagEdit"; name: string | null; description: string | null; added_aliases: string[] | null; removed_aliases: string[] | null; category_id: string | null; } export interface EditDetailsFragment_PerformerEdit_added_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_PerformerEdit_removed_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_PerformerEdit_added_tattoos { __typename: "BodyModification"; location: string; description: string | null; } export interface EditDetailsFragment_PerformerEdit_removed_tattoos { __typename: "BodyModification"; location: string; description: string | null; } export interface EditDetailsFragment_PerformerEdit_added_piercings { __typename: "BodyModification"; location: string; description: string | null; } export interface EditDetailsFragment_PerformerEdit_removed_piercings { __typename: "BodyModification"; location: string; description: string | null; } export interface EditDetailsFragment_PerformerEdit_added_images { __typename: "Image"; id: string; url: string; width: number; height: number; } export interface EditDetailsFragment_PerformerEdit_removed_images { __typename: "Image"; id: string; url: string; width: number; height: number; } export interface EditDetailsFragment_PerformerEdit { __typename: "PerformerEdit"; name: string | null; disambiguation: string | null; added_aliases: string[] | null; removed_aliases: string[] | null; gender: GenderEnum | null; added_urls: EditDetailsFragment_PerformerEdit_added_urls[] | null; removed_urls: EditDetailsFragment_PerformerEdit_removed_urls[] | null; birthdate: string | null; birthdate_accuracy: string | null; ethnicity: EthnicityEnum | null; country: string | null; eye_color: EyeColorEnum | null; hair_color: HairColorEnum | null; /** * Height in cm */ height: number | null; cup_size: string | null; band_size: number | null; waist_size: number | null; hip_size: number | null; breast_type: BreastTypeEnum | null; career_start_year: number | null; career_end_year: number | null; added_tattoos: EditDetailsFragment_PerformerEdit_added_tattoos[] | null; removed_tattoos: EditDetailsFragment_PerformerEdit_removed_tattoos[] | null; added_piercings: EditDetailsFragment_PerformerEdit_added_piercings[] | null; removed_piercings: EditDetailsFragment_PerformerEdit_removed_piercings[] | null; added_images: (EditDetailsFragment_PerformerEdit_added_images | null)[] | null; removed_images: (EditDetailsFragment_PerformerEdit_removed_images | null)[] | null; } export interface EditDetailsFragment_StudioEdit_added_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_StudioEdit_removed_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_StudioEdit_parent_child_studios { __typename: "Studio"; id: string; name: string; } export interface EditDetailsFragment_StudioEdit_parent_parent { __typename: "Studio"; id: string; name: string; } export interface EditDetailsFragment_StudioEdit_parent_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_StudioEdit_parent_images { __typename: "Image"; id: string; url: string; height: number; width: number; } export interface EditDetailsFragment_StudioEdit_parent { __typename: "Studio"; id: string; name: string; child_studios: EditDetailsFragment_StudioEdit_parent_child_studios[]; parent: EditDetailsFragment_StudioEdit_parent_parent | null; urls: EditDetailsFragment_StudioEdit_parent_urls[]; images: EditDetailsFragment_StudioEdit_parent_images[]; deleted: boolean; } export interface EditDetailsFragment_StudioEdit_added_images { __typename: "Image"; id: string; url: string; width: number; height: number; } export interface EditDetailsFragment_StudioEdit_removed_images { __typename: "Image"; id: string; url: string; width: number; height: number; } export interface EditDetailsFragment_StudioEdit { __typename: "StudioEdit"; name: string | null; /** * Added and modified URLs */ added_urls: EditDetailsFragment_StudioEdit_added_urls[] | null; removed_urls: EditDetailsFragment_StudioEdit_removed_urls[] | null; parent: EditDetailsFragment_StudioEdit_parent | null; added_images: (EditDetailsFragment_StudioEdit_added_images | null)[] | null; removed_images: (EditDetailsFragment_StudioEdit_removed_images | null)[] | null; } export interface EditDetailsFragment_SceneEdit_added_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_SceneEdit_removed_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_SceneEdit_studio_child_studios { __typename: "Studio"; id: string; name: string; } export interface EditDetailsFragment_SceneEdit_studio_parent { __typename: "Studio"; id: string; name: string; } export interface EditDetailsFragment_SceneEdit_studio_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_SceneEdit_studio_images { __typename: "Image"; id: string; url: string; height: number; width: number; } export interface EditDetailsFragment_SceneEdit_studio { __typename: "Studio"; id: string; name: string; child_studios: EditDetailsFragment_SceneEdit_studio_child_studios[]; parent: EditDetailsFragment_SceneEdit_studio_parent | null; urls: EditDetailsFragment_SceneEdit_studio_urls[]; images: EditDetailsFragment_SceneEdit_studio_images[]; deleted: boolean; } export interface EditDetailsFragment_SceneEdit_added_performers_performer_birthdate { __typename: "FuzzyDate"; date: any; accuracy: DateAccuracyEnum; } export interface EditDetailsFragment_SceneEdit_added_performers_performer_measurements { __typename: "Measurements"; waist: number | null; hip: number | null; band_size: number | null; cup_size: string | null; } export interface EditDetailsFragment_SceneEdit_added_performers_performer_tattoos { __typename: "BodyModification"; location: string; description: string | null; } export interface EditDetailsFragment_SceneEdit_added_performers_performer_piercings { __typename: "BodyModification"; location: string; description: string | null; } export interface EditDetailsFragment_SceneEdit_added_performers_performer_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_SceneEdit_added_performers_performer_images { __typename: "Image"; id: string; url: string; width: number; height: number; } export interface EditDetailsFragment_SceneEdit_added_performers_performer { __typename: "Performer"; id: string; name: string; disambiguation: string | null; deleted: boolean; aliases: string[]; gender: GenderEnum | null; birthdate: EditDetailsFragment_SceneEdit_added_performers_performer_birthdate | null; age: number | null; /** * Height in cm */ height: number | null; hair_color: HairColorEnum | null; eye_color: EyeColorEnum | null; ethnicity: EthnicityEnum | null; country: string | null; career_end_year: number | null; career_start_year: number | null; breast_type: BreastTypeEnum | null; measurements: EditDetailsFragment_SceneEdit_added_performers_performer_measurements; tattoos: EditDetailsFragment_SceneEdit_added_performers_performer_tattoos[] | null; piercings: EditDetailsFragment_SceneEdit_added_performers_performer_piercings[] | null; urls: EditDetailsFragment_SceneEdit_added_performers_performer_urls[]; images: EditDetailsFragment_SceneEdit_added_performers_performer_images[]; } export interface EditDetailsFragment_SceneEdit_added_performers { __typename: "PerformerAppearance"; performer: EditDetailsFragment_SceneEdit_added_performers_performer; /** * Performing as alias */ as: string | null; } export interface EditDetailsFragment_SceneEdit_removed_performers_performer_birthdate { __typename: "FuzzyDate"; date: any; accuracy: DateAccuracyEnum; } export interface EditDetailsFragment_SceneEdit_removed_performers_performer_measurements { __typename: "Measurements"; waist: number | null; hip: number | null; band_size: number | null; cup_size: string | null; } export interface EditDetailsFragment_SceneEdit_removed_performers_performer_tattoos { __typename: "BodyModification"; location: string; description: string | null; } export interface EditDetailsFragment_SceneEdit_removed_performers_performer_piercings { __typename: "BodyModification"; location: string; description: string | null; } export interface EditDetailsFragment_SceneEdit_removed_performers_performer_urls { __typename: "URL"; url: string; type: string; } export interface EditDetailsFragment_SceneEdit_removed_performers_performer_images { __typename: "Image"; id: string; url: string; width: number; height: number; } export interface EditDetailsFragment_SceneEdit_removed_performers_performer { __typename: "Performer"; id: string; name: string; disambiguation: string | null; deleted: boolean; aliases: string[]; gender: GenderEnum | null; birthdate: EditDetailsFragment_SceneEdit_removed_performers_performer_birthdate | null; age: number | null; /** * Height in cm */ height: number | null; hair_color: HairColorEnum | null; eye_color: EyeColorEnum | null; ethnicity: EthnicityEnum | null; country: string | null; career_end_year: number | null; career_start_year: number | null; breast_type: BreastTypeEnum | null; measurements: EditDetailsFragment_SceneEdit_removed_performers_performer_measurements; tattoos: EditDetailsFragment_SceneEdit_removed_performers_performer_tattoos[] | null; piercings: EditDetailsFragment_SceneEdit_removed_performers_performer_piercings[] | null; urls: EditDetailsFragment_SceneEdit_removed_performers_performer_urls[]; images: EditDetailsFragment_SceneEdit_removed_performers_performer_images[]; } export interface EditDetailsFragment_SceneEdit_removed_performers { __typename: "PerformerAppearance"; performer: EditDetailsFragment_SceneEdit_removed_performers_performer; /** * Performing as alias */ as: string | null; } export interface EditDetailsFragment_SceneEdit_added_tags_category { __typename: "TagCategory"; id: string; name: string; } export interface EditDetailsFragment_SceneEdit_added_tags { __typename: "Tag"; id: string; name: string; description: string | null; deleted: boolean; category: EditDetailsFragment_SceneEdit_added_tags_category | null; } export interface EditDetailsFragment_SceneEdit_removed_tags_category { __typename: "TagCategory"; id: string; name: string; } export interface EditDetailsFragment_SceneEdit_removed_tags { __typename: "Tag"; id: string; name: string; description: string | null; deleted: boolean; category: EditDetailsFragment_SceneEdit_removed_tags_category | null; } export interface EditDetailsFragment_SceneEdit_added_images { __typename: "Image"; id: string; url: string; width: number; height: number; } export interface EditDetailsFragment_SceneEdit_removed_images { __typename: "Image"; id: string; url: string; width: number; height: number; } export interface EditDetailsFragment_SceneEdit_added_fingerprints { __typename: "Fingerprint"; hash: string; algorithm: FingerprintAlgorithm; duration: number; submissions: number; created: any; updated: any; } export interface EditDetailsFragment_SceneEdit_removed_fingerprints { __typename: "Fingerprint"; hash: string; algorithm: FingerprintAlgorithm; duration: number; submissions: number; created: any; updated: any; } export interface EditDetailsFragment_SceneEdit { __typename: "SceneEdit"; title: string | null; details: string | null; added_urls: EditDetailsFragment_SceneEdit_added_urls[] | null; removed_urls: EditDetailsFragment_SceneEdit_removed_urls[] | null; date: any | null; studio: EditDetailsFragment_SceneEdit_studio | null; /** * Added or modified performer appearance entries */ added_performers: EditDetailsFragment_SceneEdit_added_performers[] | null; removed_performers: EditDetailsFragment_SceneEdit_removed_performers[] | null; added_tags: EditDetailsFragment_SceneEdit_added_tags[] | null; removed_tags: EditDetailsFragment_SceneEdit_removed_tags[] | null; added_images: (EditDetailsFragment_SceneEdit_added_images | null)[] | null; removed_images: (EditDetailsFragment_SceneEdit_removed_images | null)[] | null; added_fingerprints: EditDetailsFragment_SceneEdit_added_fingerprints[] | null; removed_fingerprints: EditDetailsFragment_SceneEdit_removed_fingerprints[] | null; duration: number | null; director: string | null; } export type EditDetailsFragment = EditDetailsFragment_TagEdit | EditDetailsFragment_PerformerEdit | EditDetailsFragment_StudioEdit | EditDetailsFragment_SceneEdit;
the_stack
// module eui.sys { let STATE = "eui.State"; let ADD_ITEMS = "eui.AddItems"; let SET_PROPERTY = "eui.SetProperty"; let SET_STATEPROPERTY = "eui.SetStateProperty"; let BINDING_PROPERTIES = "eui.Binding.$bindProperties"; /** * @private * 代码生成工具基类 */ export class CodeBase { /** * @private * * @returns */ public toCode(): string { return ""; } /** * @private */ public indent: number = 0; /** * @private * 获取缩进字符串 */ public getIndent(indent?: number): string { if (indent === void 0) indent = this.indent; let str = ""; for (let i = 0; i < indent; i++) { str += " "; } return str; } } /** * @private */ export class EXClass extends CodeBase { /** * @private * 构造函数代码块 */ public constructCode: EXCodeBlock; /** * @private * 类名,不包括模块名 */ public className: string = ""; /** * @private * 全名包括模块名 */ public allName: string = ""; /** * @private * 父类类名,包括完整模块名 */ public superClass: string = ""; /** * @private * 内部类区块 */ private innerClassBlock: EXClass[] = []; /** * @private * 添加一个内部类 */ public addInnerClass(clazz: EXClass): void { if (this.innerClassBlock.indexOf(clazz) == -1) { this.innerClassBlock.push(clazz); } } /** * @private * 变量定义区块 */ private variableBlock: EXVariable[] = []; /** * @private * 添加变量 */ public addVariable(variableItem: EXVariable): void { if (this.variableBlock.indexOf(variableItem) == -1) { this.variableBlock.push(variableItem); } } /** * @private * 根据变量名获取变量定义 */ public getVariableByName(name: string): EXVariable { let list = this.variableBlock; let length = list.length; for (let i = 0; i < length; i++) { let item = list[i]; if (item.name == name) { return item; } } return null; } /** * @private * 函数定义区块 */ private functionBlock: EXFunction[] = []; /** * @private * 添加函数 */ public addFunction(functionItem: EXFunction): void { if (this.functionBlock.indexOf(functionItem) == -1) { this.functionBlock.push(functionItem); } } /** * @private * 根据函数名返回函数定义块 */ public getFuncByName(name: string): EXFunction { let list = this.functionBlock; let length = list.length; for (let i = 0; i < length; i++) { let item = list[i]; if (item.name == name) { return item; } } return null; } /** * @private * * @returns */ public toCode(isAssignWindow = false): string { let indent = this.indent; let indentStr = this.getIndent(indent); let indent1Str = this.getIndent(indent + 1); let indent2Str = this.getIndent(indent + 2); //打印类起始块 let returnStr = indentStr + "(function ("; if (this.superClass) { returnStr += "_super) {\n" + indent1Str + "__extends(" + this.className + ", _super);\n"; } else { returnStr += ") {\n"; } //打印内部类列表 let innerClasses = this.innerClassBlock; let length = innerClasses.length; for (let i = 0; i < length; i++) { let clazz = innerClasses[i]; clazz.indent = indent + 1; if (!isAssignWindow) returnStr += indent1Str + "var " + clazz.className + " = " + clazz.toCode() + "\n\n"; else { returnStr += indent1Str + "var " + clazz.className + " = " + clazz.toCode() + "\n"; returnStr += indent1Str + `window.${clazz.allName}=${clazz.className};\n`; } } returnStr += indent1Str + "function " + this.className + "() {\n"; if (this.superClass) { returnStr += indent2Str + "_super.call(this);\n"; } //打印变量列表 let variables = this.variableBlock; length = variables.length; for (let i = 0; i < length; i++) { let variable = variables[i]; if (variable.defaultValue) { returnStr += indent2Str + variable.toCode() + "\n"; } } //打印构造函数 if (this.constructCode) { let codes = this.constructCode.toCode().split("\n"); length = codes.length; for (let i = 0; i < length; i++) { let code = codes[i]; returnStr += indent2Str + code + "\n"; } } returnStr += indent1Str + "}\n"; returnStr += indent1Str + "var _proto = " + this.className + ".prototype;\n\n"; //打印函数列表 let functions = this.functionBlock; length = functions.length; for (let i = 0; i < length; i++) { let functionItem = functions[i]; functionItem.indent = indent + 1; returnStr += functionItem.toCode() + "\n"; } //打印类结尾 returnStr += indent1Str + "return " + this.className + ";\n" + indentStr; if (this.superClass) { returnStr += "})(" + this.superClass + ");"; } else { returnStr += "})();"; } return returnStr; } } /** * @private */ export class EXCodeBlock extends CodeBase { /** * @private * 添加变量声明语句 * @param name 变量名 * @param value 变量初始值 */ public addVar(name: string, value?: string): void { let valueStr = value ? " = " + value : ""; this.addCodeLine("var " + name + valueStr + ";"); } /** * @private * 添加赋值语句 * @param target 要赋值的目标 * @param value 值 * @param prop 目标的属性(用“.”访问),不填则是对目标赋值 */ public addAssignment(target: string, value: string, prop?: string): void { let propStr = prop ? "." + prop : ""; this.addCodeLine(target + propStr + " = " + value + ";"); } /** * @private * 添加返回值语句 */ public addReturn(data: string): void { this.addCodeLine("return " + data + ";"); } /** * @private * 添加一条空行 */ public addEmptyLine(): void { this.addCodeLine(""); } /** * @private * 开始添加if语句块,自动调用startBlock(); */ public startIf(expression: string): void { this.addCodeLine("if(" + expression + ")"); this.startBlock(); } /** * @private * 开始else语句块,自动调用startBlock(); */ public startElse(): void { this.addCodeLine("else"); this.startBlock(); } /** * @private * 开始else if语句块,自动调用startBlock(); */ public startElseIf(expression: string): void { this.addCodeLine("else if(" + expression + ")"); this.startBlock(); } /** * @private * 添加一个左大括号,开始新的语句块 */ public startBlock(): void { this.addCodeLine("{"); this.indent++; } /** * @private * 添加一个右大括号,结束当前的语句块 */ public endBlock(): void { this.indent--; this.addCodeLine("}"); } /** * @private * 添加执行函数语句块 * @param functionName 要执行的函数名称 * @param args 函数参数列表 */ public doFunction(functionName: string, args: string[]): void { let argsStr = args.join(","); this.addCodeLine(functionName + "(" + argsStr + ")"); } /** * @private */ private lines: string[] = []; /** * @private * 添加一行代码 */ public addCodeLine(code: string): void { this.lines.push(this.getIndent() + code); } /** * @private * 添加一行代码到指定行 */ public addCodeLineAt(code: string, index: number): void { this.lines.splice(index, 0, this.getIndent() + code); } /** * @private * 是否存在某行代码内容 */ public containsCodeLine(code: string): boolean { return this.lines.indexOf(code) != -1; } /** * @private * 在结尾追加另一个代码块的内容 */ public concat(cb: EXCodeBlock): void { this.lines = this.lines.concat(cb.lines); } /** * @private * * @returns */ public toCode(): string { return this.lines.join("\n"); } } /** * @private */ export class EXFunction extends CodeBase { /** * @private * 代码块 */ public codeBlock: EXCodeBlock = null; /** * @private */ public isGet: boolean = false; /** * @private * 函数名 */ public name: string = ""; /** * @private * * @returns */ public toCode(): string { let indentStr: string = this.getIndent(); let indent1Str: string = this.getIndent(this.indent + 1); let codeIndent: string; let returnStr = indentStr; if (this.isGet) { codeIndent = this.getIndent(this.indent + 2); returnStr += 'Object.defineProperty(_proto, "skinParts", {\n'; returnStr += indent1Str + "get: function () {\n"; } else { codeIndent = indent1Str; returnStr += "_proto." + this.name + " = function () {\n"; } if (this.codeBlock) { let lines = this.codeBlock.toCode().split("\n"); let length = lines.length; for (let i = 0; i < length; i++) { let line = lines[i]; returnStr += codeIndent + line + "\n"; } } if (this.isGet) { returnStr += indent1Str + "},\n" + indent1Str + "enumerable: true,\n" + indent1Str + "configurable: true\n" + indentStr + "});"; } else { returnStr += indentStr + "};"; } return returnStr; } } /** * @private */ export class EXVariable extends CodeBase { /** * @private */ public constructor(name: string, defaultValue?: string) { super(); this.indent = 2; this.name = name; this.defaultValue = defaultValue; } /** * @private * 变量名 */ public name: string; /** * @private * 默认值 */ public defaultValue: string; /** * @private * * @returns */ public toCode(): string { if (!this.defaultValue) { return ""; } return "this." + this.name + " = " + this.defaultValue + ";"; } } export class EXArray extends CodeBase { constructor(private array: string[]) { super(); } toCode() { return "[" + this.array.map(v => "\"" + v + "\"").join(",") + "]" } } /** * @private */ export class EXState extends CodeBase { /** * @private */ public constructor(name: string, stateGroups?: Array<any>) { super(); this.name = name; if (stateGroups) this.stateGroups = stateGroups; } /** * @private * 视图状态名称 */ public name: string = ""; /** * @private */ public stateGroups: Array<any> = []; /** * @private */ public addItems: Array<any> = []; /** * @private */ public setProperty: Array<any> = []; /** * @private * 添加一个覆盖 */ public addOverride(item: CodeBase): void { if (item instanceof EXAddItems) this.addItems.push(item); else this.setProperty.push(item); } /** * @private * * @returns */ public toCode(): string { let indentStr: string = this.getIndent(1); let returnStr: string = "new " + STATE + " (\"" + this.name + "\",\n" + indentStr + "[\n"; let index: number = 0; let isFirst: boolean = true; let overrides: Array<any> = this.addItems.concat(this.setProperty); while (index < overrides.length) { if (isFirst) isFirst = false; else returnStr += ",\n"; let item: CodeBase = overrides[index]; let codes: Array<any> = item.toCode().split("\n"); let length: number = codes.length; for (let i: number = 0; i < length; i++) { let code: string = codes[i]; codes[i] = indentStr + indentStr + code; } returnStr += codes.join("\n"); index++; } returnStr += "\n" + indentStr + "])"; return returnStr; } } /** * @private */ export class EXAddItems extends CodeBase { /** * @private */ public constructor(target: string, property: string, position: number, relativeTo: string) { super(); this.target = target; this.property = property; this.position = position; this.relativeTo = relativeTo; } /** * @private * 要添加的实例 */ public target: string; /** * @private * 要添加到的属性 */ public property: string; /** * @private * 添加的位置 */ public position: number; /** * @private * 相对的显示元素 */ public relativeTo: string; /** * @private * * @returns */ public toCode(): string { let returnStr: string = "new " + ADD_ITEMS + "(\"" + this.target + "\",\"" + this.property + "\"," + this.position + ",\"" + this.relativeTo + "\")"; return returnStr; } } /** * @private */ export class EXSetProperty extends CodeBase { /** * @private */ public constructor(target: string, name: string, value: string) { super(); this.target = target; this.name = name; this.value = value; } /** * @private * 要修改的属性名 */ public name: string; /** * @private * 目标实例名 */ public target: string; /** * @private * 属性值 */ public value: string; /** * @private * * @returns */ public toCode(): string { return "new " + SET_PROPERTY + "(\"" + this.target + "\",\"" + this.name + "\"," + this.value + ")"; } } /** * @private */ export class EXSetStateProperty extends CodeBase { /** * @private */ public constructor(target: string, property: string, templates: string[], chainIndex: number[]) { super(); if (target) { target = "this." + target; } else { target = "this"; } this.target = target; this.property = property; this.templates = templates; this.chainIndex = chainIndex; } /** * @private * 目标实例名 */ public target: string; /** * @private * 目标属性名 */ public property: string; /** * @private * 绑定的模板列表 */ public templates: string[]; /** * @private * chainIndex是一个索引列表,每个索引指向templates中的一个值,该值是代表属性链。 */ public chainIndex: number[]; /** * @private * * @returns */ public toCode(): string { let expression = this.templates.join(","); let chain = this.chainIndex.join(","); return "new " + SET_STATEPROPERTY + "(this, [" + expression + "]," + "[" + chain + "]," + this.target + ",\"" + this.property + "\")"; } } /** * @private */ export class EXBinding extends CodeBase { /** * @private */ public constructor(target: string, property: string, templates: string[], chainIndex: number[]) { super(); this.target = target; this.property = property; this.templates = templates; this.chainIndex = chainIndex; } /** * @private * 目标实例名 */ public target: string; /** * @private * 目标属性名 */ public property: string; /** * @private * 绑定的模板列表 */ public templates: string[]; /** * @private * chainIndex是一个索引列表,每个索引指向templates中的一个值,该值是代表属性链。 */ public chainIndex: number[]; /** * @private * * @returns */ public toCode(): string { let expression = this.templates.join(","); let chain = this.chainIndex.join(","); return BINDING_PROPERTIES + "(this, [" + expression + "]," + "[" + chain + "]," + this.target + ",\"" + this.property + "\");"; } } // }
the_stack
/// <reference types="node" /> import * as Stream from "stream"; import { Commit } from "conventional-commits-parser"; /** * Returns a transform stream. * * @param context Variables that will be interpolated to the template. This * object contains, but not limits to the following fields. * @param options */ // tslint:disable-next-line no-unnecessary-generics declare function conventionalChangelogWriter<TCommit extends Commit = Commit, TContext extends Context = Context>(context?: Partial<TContext>, options?: Options<TCommit, TContext>): Stream.Transform; declare namespace conventionalChangelogWriter { interface CommitGroup<T extends Commit = Commit> { title: string | false; commits: Array<TransformedCommit<T>>; } interface Context { /** * Version number of the up-coming release. If `version` is found in the last * commit before generating logs, it will be overwritten. */ version?: string | undefined; title?: string | undefined; /** * By default, this value is true if `version`'s patch is `0`. * * @default * semver.patch(context.version) !== 0 */ isPatch?: boolean | undefined; /** * The hosting website. Eg: `'https://github.com'` or `'https://bitbucket.org'`. */ host?: string | undefined; /** * The owner of the repository. Eg: `'stevemao'`. */ owner?: string | undefined; /** * The repository name on `host`. Eg: `'conventional-changelog-writer'`. */ repository?: string | undefined; /** * The whole repository url. Eg: `'https://github.com/conventional-changelog/conventional-changelog-writer'`. * The should be used as a fallback when `context.repository` doesn't exist. */ repoUrl?: string | undefined; /** * Should all references be linked? * * @defaults * `true` if (`context.repository` or `context.repoUrl`), `context.commit` and * `context.issue` are truthy. */ linkReferences?: boolean | undefined; /** * Commit keyword in the url if `context.linkReferences === true`. * * @default * 'commits' */ commit: string; /** * Issue or pull request keyword in the url if `context.linkReferences === true`. * * @default * 'issues' */ issue: string; /** * Default to formatted (`'yyyy-mm-dd'`) today's date. [dateformat](https://github.com/felixge/node-dateformat) * is used for formatting the date. If `version` is found in the last commit, * `committerDate` will overwrite this. * * @default * dateFormat(new Date(), 'yyyy-mm-dd', true) */ date: string; } type GeneratedContext<TCommit extends Commit = Commit, TContext extends Context = Context> = TContext & TransformedCommit<TCommit> & GeneratedContext.ExtraContext<TCommit>; namespace GeneratedContext { interface ExtraContext<T extends Commit = Commit> { /** * @default * [] */ commitGroups: Array<CommitGroup<T>>; /** * @default * [] */ noteGroups: NoteGroup[]; } } interface NoteGroup { title: string | false; commits: Commit.Note[]; } interface Options<TCommit extends Commit = Commit, TContext extends Context = Context> { /** * Replace with new values in each commit. * * If this is an object, the keys are paths to a nested object property. the * values can be a string (static) and a function (dynamic) with the old value * and path passed as arguments. This value is merged with your own transform * object. * * If this is a function, the commit chunk will be passed as the argument and * the returned value would be the new commit object. This is a handy function * if you can't provide a transform stream as an upstream of this one. If * returns a falsy value this commit is ignored. * * A `raw` object that is originally poured form upstream is attached to `commit`. */ transform?: Options.Transform<TCommit, TContext> | undefined; /** * How to group the commits. EG: based on the same type. If this value is falsy, * commits are not grouped. * * @default * 'type' */ groupBy?: string | false | undefined; /** * A compare function used to sort commit groups. If it's a string or array, it * sorts on the property(ies) by `localeCompare`. Will not sort if this is a * falsy value. * * The string can be a dot path to a nested object property. */ commitGroupsSort?: Options.Sort<CommitGroup<TCommit>> | undefined; /** * A compare function used to sort commits. If it's a string or array, it sorts * on the property(ies) by `localeCompare`. Will not sort if this is a falsy * value. * * The string can be a dot path to a nested object property. * * @default * 'header' */ commitsSort?: Options.Sort<TransformedCommit<TCommit>> | undefined; /** * A compare function used to sort note groups. If it's a string or array, it * sorts on the property(ies) by `localeCompare`. Will not sort if this is a * falsy value. * * The string can be a dot path to a nested object property. * * @default * 'title' */ noteGroupsSort?: Options.Sort<NoteGroup> | undefined; /** * A compare function used to sort note groups. If it's a string or array, it * sorts on the property(ies) by `localeCompare`. Will not sort if this is a * falsy value. * * The string can be a dot path to a nested object property. * * @default * 'text' */ notesSort?: Options.Sort<Commit.Note> | undefined; /** * When the upstream finishes pouring the commits it will generate a block of * logs if `doFlush` is `true`. However, you can generate more than one block * based on this criteria (usually a version) even if there are still commits * from the upstream. * * @remarks * It checks on the transformed commit chunk instead of the original one (you * can check on the original by access the `raw` object on the `commit`). * However, if the transformed commit is ignored it falls back to the original * commit. * * @remarks * If this value is a `string`, it checks the existence of the field. Set to * other type to disable it. * * @defaults * If `commit.version` is a valid semver. */ generateOn?: Options.GenerateOn<TContext, TCommit> | undefined; /** * Last chance to modify your context before generating a changelog. * * @defaults * Pass through. */ finalizeContext?: Options.FinalizeContext<TContext, TCommit> | undefined; /** * A function to get debug information. * * @default * function () {} */ debug?: ((message?: any) => void) | undefined; /** * The normal order means reverse chronological order. `reverse` order means * chronological order. Are the commits from upstream in the reverse order? You * should only worry about this when generating more than one blocks of logs * based on `generateOn`. If you find the last commit is in the wrong block * inverse this value. * * @default * false */ reverse?: boolean | undefined; /** * If this value is `true`, instead of emitting strings of changelog, it emits * objects containing the details the block. * * @remarks * The downstream must be in object mode if this is `true`. * * @default * false */ includeDetails?: boolean | undefined; /** * If `true`, reverted commits will be ignored. * * @default * true */ ignoreReverted?: boolean | undefined; /** * If `true`, the stream will flush out the last bit of commits (could be empty) * to changelog. * * @default * true */ doFlush?: boolean | undefined; /** * The main handlebars template. * * @defaults * [template.hbs](https://github.com/conventional-changelog/conventional-changelog/blob/master/packages/conventional-changelog-writer/templates/template.hbs) */ mainTemplate?: string | undefined; /** * @defaults * [header.hbs](https://github.com/conventional-changelog/conventional-changelog/blob/master/packages/conventional-changelog-writer/templates/header.hbs) */ headerPartial?: string | undefined; /** * @defaults * [commit.hbs](https://github.com/conventional-changelog/conventional-changelog/blob/master/packages/conventional-changelog-writer/templates/commit.hbs) */ commitPartial?: string | undefined; /** * @defaults * [footer.hbs](https://github.com/conventional-changelog/conventional-changelog/blob/master/packages/conventional-changelog-writer/templates/footer.hbs) */ footerPartial?: string | undefined; /** * Partials that used in the main template, if any. The key should be the * partial name and the value should be handlebars template strings. If you are * using handlebars template files, read files by yourself. */ partials?: Record<string, string> | undefined; } namespace Options { interface FinalizeContext<TContext extends Context = Context, TCommit extends Commit = Commit> { /** * @param context The generated context based on original input `context` and * `options`. * @param options Normalized options. * @param commits Filtered commits from your git metadata. * @param keyCommit The commit that triggers to generate the log. */ // tslint:disable-next-line max-line-length (context: GeneratedContext<TCommit, TContext>, options: Options<TCommit, TContext>, commits: Array<TransformedCommit<TCommit>>, keyCommit: TransformedCommit<TCommit>): GeneratedContext<TCommit, TContext>; } type GenerateOn<TContext extends Context = Context, TCommit extends Commit = Commit> = GenerateOn.Function<TContext, TCommit> | string | object; namespace GenerateOn { interface FunctionType<TContext extends Context = Context, TCommit extends Commit = Commit> { /** * @param commit Current commit. * @param commits Current collected commits. * @param context The generated context based on original input `context` and * `options`. * @param options Normalized options. */ (commit: TransformedCommit<TCommit>, commits: Array<TransformedCommit<TCommit>>, context: GeneratedContext<TCommit, TContext>, options: Options<TCommit, TContext>): boolean; } export { FunctionType as Function, }; } type Sort<T = any> = Sort.Function<T> | string | ReadonlyArray<string> | false; namespace Sort { type FunctionType<T = any> = (a: T, b: T) => number; export { FunctionType as Function, }; } type Transform<TCommit extends Commit = Commit, TContext extends Context = Context> = Transform.Object | Transform.Function<TCommit, TContext>; namespace Transform { interface FunctionType<TCommit extends Commit = Commit, TContext extends Context = Context> { (commit: Commit, context: TContext): TCommit | false; } type ObjectType = Record<string, object | ObjectType.Function>; namespace ObjectType { type FunctionType<T = any> = (value: T, path: string) => T; export { FunctionType as Function, }; } export { FunctionType as Function, ObjectType as Object, }; } } type TransformedCommit<T extends Commit = Commit> = Omit<T, "raw"> & { raw: T; }; } type Context = conventionalChangelogWriter.Context; type Options<TCommit extends Commit = Commit, TContext extends Context = Context> = conventionalChangelogWriter.Options<TCommit, TContext>; type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }; export = conventionalChangelogWriter;
the_stack
import * as assert from "assert"; import { AABB, EPSILON, Hit, Point, Sweep } from "../src/intersect"; function almostEqual(actual: number, expected: number, message?: string) { if (Math.abs(actual - expected) > 1e-8) { assert.equal(actual, expected, message); } } function assertNotNull<T>(value: T | null): T { if (value === null) { throw new Error("value is unexpectedly null"); } return value; } describe("AABB", () => { describe("intersectPoint", () => { test("should return null when not colliding", () => { const aabb = new AABB(new Point(0, 0), new Point(8, 8)); const points = [ new Point(-16, -16), new Point(0, -16), new Point(16, -16), new Point(16, 0), new Point(16, 16), new Point(0, 16), new Point(-16, 16), new Point(-16, 0) ]; points.forEach(point => { assert.equal(aabb.intersectPoint(point), null); }); }); test("should return hit when colliding", () => { const aabb = new AABB(new Point(0, 0), new Point(8, 8)); const point = new Point(4, 4); const hit = assertNotNull(aabb.intersectPoint(point)); assert.ok(hit instanceof Hit); }); test("should set hit pos and normal to nearest edge of box", () => { const aabb = new AABB(new Point(0, 0), new Point(8, 8)); let hit = assertNotNull(aabb.intersectPoint(new Point(-4, -2))); almostEqual(hit.pos.x, -8); almostEqual(hit.pos.y, -2); almostEqual(hit.delta.x, -4); almostEqual(hit.delta.y, 0); almostEqual(hit.normal.x, -1); almostEqual(hit.normal.y, 0); hit = assertNotNull(aabb.intersectPoint(new Point(4, -2))); almostEqual(hit.pos.x, 8); almostEqual(hit.pos.y, -2); almostEqual(hit.delta.x, 4); almostEqual(hit.delta.y, 0); almostEqual(hit.normal.x, 1); almostEqual(hit.normal.y, 0); hit = assertNotNull(aabb.intersectPoint(new Point(2, -4))); almostEqual(hit.pos.x, 2); almostEqual(hit.pos.y, -8); almostEqual(hit.delta.x, 0); almostEqual(hit.delta.y, -4); almostEqual(hit.normal.x, 0); almostEqual(hit.normal.y, -1); hit = assertNotNull(aabb.intersectPoint(new Point(2, 4))); almostEqual(hit.pos.x, 2); almostEqual(hit.pos.y, 8); almostEqual(hit.delta.x, 0); almostEqual(hit.delta.y, 4); almostEqual(hit.normal.x, 0); almostEqual(hit.normal.y, 1); }); }); describe("intersectSegment", () => { test("should return null when not colliding", () => { const aabb = new AABB(new Point(0, 0), new Point(8, 8)); assert.equal( aabb.intersectSegment(new Point(-16, -16), new Point(32, 0)), null ); }); test("should return hit when colliding", () => { const aabb = new AABB(new Point(0, 0), new Point(8, 8)); const point = new Point(-16, 4); const delta = new Point(32, 0); const hit = assertNotNull(aabb.intersectSegment(point, delta)); assert.ok(hit instanceof Hit); const time = 0.25; assert.equal(hit.collider, aabb); almostEqual(hit.time, time); almostEqual(hit.pos.x, point.x + delta.x * time); almostEqual(hit.pos.y, point.y + delta.y * time); almostEqual(hit.delta.x, (1.0 - time) * -delta.x); almostEqual(hit.delta.y, (1.0 - time) * -delta.y); almostEqual(hit.normal.x, -1); almostEqual(hit.normal.y, 0); }); test("should set hit.time to zero when segment starts inside box", () => { const aabb = new AABB(new Point(0, 0), new Point(8, 8)); const point = new Point(-4, 4); const delta = new Point(32, 0); const hit = assertNotNull(aabb.intersectSegment(point, delta)); almostEqual(hit.time, 0); almostEqual(hit.pos.x, -4); almostEqual(hit.pos.y, 4); almostEqual(hit.delta.x, -delta.x); almostEqual(hit.delta.y, -delta.y); almostEqual(hit.normal.x, -1); almostEqual(hit.normal.y, 0); }); test("should add padding to half size of box", () => { const aabb = new AABB(new Point(0, 0), new Point(8, 8)); const point = new Point(-16, 4); const delta = new Point(32, 0); const padding = 4; const hit = assertNotNull( aabb.intersectSegment(point, delta, padding, padding) ); const time = 0.125; assert.equal(hit.collider, aabb); almostEqual(hit.time, time); almostEqual(hit.pos.x, point.x + delta.x * time); almostEqual(hit.pos.y, point.y + delta.y * time); almostEqual(hit.delta.x, (1.0 - time) * -delta.x); almostEqual(hit.delta.y, (1.0 - time) * -delta.y); almostEqual(hit.normal.x, -1); almostEqual(hit.normal.y, 0); }); test("should have consistent results in both directions", () => { // If moving from far away to the near edge of the box doesn't cause a // collision, then moving away from the near edge shouldn't either. const aabb = new AABB(new Point(0, 0), new Point(32, 32)); const farPos = new Point(64, 0); const farToNearDelta = new Point(-32, 0); assert.equal(aabb.intersectSegment(farPos, farToNearDelta), null); const nearPos = new Point(32, 0); const nearToFarDelta = new Point(32, 0); assert.equal(aabb.intersectSegment(nearPos, nearToFarDelta), null); }); test("should work when segment is axis aligned", () => { // When the segment is axis aligned, it will cause the near and far values // to be Infinity and -Infinity. Make sure that this case works. const aabb = new AABB(new Point(0, 0), new Point(16, 16)); const pos = new Point(-32, 0); const delta = new Point(64, 0); const hit = assertNotNull(aabb.intersectSegment(pos, delta)); assert.equal(hit.time, 0.25); assert.equal(hit.normal.x, -1); assert.equal(hit.normal.y, 0); }); }); describe("intersectAABB", () => { test("should return null when not colliding", () => { const aabb1 = new AABB(new Point(0, 0), new Point(8, 8)); const aabb2 = new AABB(new Point(32, 0), new Point(8, 8)); assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(-32, 0); assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(0, 32); assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(0, -32); assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(0, -32); assert.equal(aabb1.intersectAABB(aabb2), null); }); test("should return null when edges are flush", () => { const aabb1 = new AABB(new Point(0, 0), new Point(8, 8)); const aabb2 = new AABB(new Point(16, 0), new Point(8, 8)); assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(-16, 0); assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(0, 16); assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(0, -16); assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(0, -16); assert.equal(aabb1.intersectAABB(aabb2), null); }); test("should return hit when colliding", () => { const aabb1 = new AABB(new Point(0, 0), new Point(8, 8)); const aabb2 = new AABB(new Point(8, 0), new Point(8, 8)); const hit = aabb1.intersectAABB(aabb2); assert.notEqual(hit, null); assert.ok(hit instanceof Hit); }); test("should set hit.pos and hit.normal to nearest edge of box 1", () => { const aabb1 = new AABB(new Point(0, 0), new Point(8, 8)); const aabb2 = new AABB(new Point(4, 0), new Point(8, 8)); let hit = assertNotNull(aabb1.intersectAABB(aabb2)); almostEqual(hit.pos.x, 8); almostEqual(hit.pos.y, 0); almostEqual(hit.normal.x, 1); almostEqual(hit.normal.y, 0); aabb2.pos = new Point(-4, 0); hit = assertNotNull(aabb1.intersectAABB(aabb2)); almostEqual(hit.pos.x, -8); almostEqual(hit.pos.y, 0); almostEqual(hit.normal.x, -1); almostEqual(hit.normal.y, 0); aabb2.pos = new Point(0, 4); hit = assertNotNull(aabb1.intersectAABB(aabb2)); almostEqual(hit.pos.x, 0); almostEqual(hit.pos.y, 8); almostEqual(hit.normal.x, 0); almostEqual(hit.normal.y, 1); aabb2.pos = new Point(0, -4); hit = assertNotNull(aabb1.intersectAABB(aabb2)); almostEqual(hit.pos.x, 0); almostEqual(hit.pos.y, -8); almostEqual(hit.normal.x, 0); almostEqual(hit.normal.y, -1); }); test("should set hit.delta to move box 2 out of collision", () => { const aabb1 = new AABB(new Point(0, 0), new Point(8, 8)); const aabb2 = new AABB(new Point(4, 0), new Point(8, 8)); let hit = assertNotNull(aabb1.intersectAABB(aabb2)); almostEqual(hit.delta.x, 12); almostEqual(hit.delta.y, 0); aabb2.pos.x += hit.delta.x; aabb2.pos.y += hit.delta.y; assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(-4, 0); hit = assertNotNull(aabb1.intersectAABB(aabb2)); almostEqual(hit.delta.x, -12); almostEqual(hit.delta.y, 0); aabb2.pos.x += hit.delta.x; aabb2.pos.y += hit.delta.y; assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(0, 4); hit = assertNotNull(aabb1.intersectAABB(aabb2)); almostEqual(hit.delta.x, 0); almostEqual(hit.delta.y, 12); aabb2.pos.x += hit.delta.x; aabb2.pos.y += hit.delta.y; assert.equal(aabb1.intersectAABB(aabb2), null); aabb2.pos = new Point(0, -4); hit = assertNotNull(aabb1.intersectAABB(aabb2)); almostEqual(hit.delta.x, 0); almostEqual(hit.delta.y, -12); aabb2.pos.x += hit.delta.x; aabb2.pos.y += hit.delta.y; assert.equal(aabb1.intersectAABB(aabb2), null); }); }); describe("sweepAABB", () => { test("should return sweep when not colliding", () => { const aabb1 = new AABB(new Point(0, 0), new Point(16, 16)); const aabb2 = new AABB(new Point(64, -64), new Point(8, 8)); const delta = new Point(0, 128); const sweep = aabb1.sweepAABB(aabb2, delta); assert.ok(sweep instanceof Sweep); assert.ok(sweep.pos instanceof Point); assert.equal(sweep.hit, null); almostEqual(sweep.pos.x, aabb2.pos.x + delta.x); almostEqual(sweep.pos.y, aabb2.pos.y + delta.y); }); test("should return sweep with sweep.hit when colliding", () => { const aabb1 = new AABB(new Point(0, 0), new Point(16, 16)); const aabb2 = new AABB(new Point(0, -64), new Point(8, 8)); const delta = new Point(0, 128); const sweep = aabb1.sweepAABB(aabb2, delta); assert.ok(sweep instanceof Sweep); assert.ok(sweep.hit instanceof Hit); assert.ok(sweep.pos instanceof Point); }); test("should place sweep.pos at a non-colliding point", () => { const aabb1 = new AABB(new Point(0, 0), new Point(16, 16)); const aabb2 = new AABB(new Point(0, -64), new Point(8, 8)); const delta = new Point(0, 128); const sweep = aabb1.sweepAABB(aabb2, delta); const time = 0.3125 - EPSILON; almostEqual(sweep.time, time); almostEqual(sweep.pos.x, aabb2.pos.x + delta.x * time); almostEqual(sweep.pos.y, aabb2.pos.y + delta.y * time); }); test("should place sweep.hit.pos on the edge of the box", () => { const aabb1 = new AABB(new Point(0, 0), new Point(16, 16)); const aabb2 = new AABB(new Point(0, -64), new Point(8, 8)); const delta = new Point(0, 128); const sweep = aabb1.sweepAABB(aabb2, delta); const time = 0.3125; const direction = delta.clone(); direction.normalize(); const hit = assertNotNull(sweep.hit); almostEqual(hit.time, time); almostEqual( hit.pos.x, aabb2.pos.x + delta.x * time + direction.x * aabb2.half.x ); almostEqual( hit.pos.y, aabb2.pos.y + delta.y * time + direction.y * aabb2.half.y ); almostEqual(hit.delta.x, (1.0 - time) * -delta.x); almostEqual(hit.delta.y, (1.0 - time) * -delta.y); }); test("should set sweep.hit.normal to normals of box 1", () => { const aabb1 = new AABB(new Point(0, 0), new Point(16, 16)); const aabb2 = new AABB(new Point(0, -64), new Point(8, 8)); const delta = new Point(0, 128); const sweep = aabb1.sweepAABB(aabb2, delta); const hit = assertNotNull(sweep.hit); almostEqual(hit.normal.x, 0); almostEqual(hit.normal.y, -1); }); test("should not move when the start position is colliding", () => { const aabb1 = new AABB(new Point(0, 0), new Point(16, 16)); const aabb2 = new AABB(new Point(0, -4), new Point(8, 8)); const delta = new Point(0, 128); const sweep = aabb1.sweepAABB(aabb2, delta); almostEqual(sweep.pos.x, 0); almostEqual(sweep.pos.y, -4); const hit = assertNotNull(sweep.hit); almostEqual(hit.time, 0); almostEqual(hit.delta.x, -delta.x); almostEqual(hit.delta.y, -delta.y); }); }); });
the_stack
import { HarnessLoader } from '@angular/cdk/testing'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { MatSortHarness } from '@angular/material/sort/testing'; import { MatTableModule } from '@angular/material/table'; import { MatSortModule } from '@angular/material/sort'; import { GioTableWrapperModule } from './gio-table-wrapper.module'; import { GioTableWrapperFilters } from './gio-table-wrapper.component'; import { GioTableWrapperHarness } from './gio-table-wrapper.harness'; describe('GioTableWrapperComponent', () => { describe('simple usage', () => { @Component({ template: ` <gio-table-wrapper [length]="length" [filters]="filters" (filtersChange)="filtersChange($event)"> <table mat-table [dataSource]="dataSource"> <!-- Name Column --> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef>Name</th> <td mat-cell *matCellDef="let element">{{ element.name }}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr> <tr class="mat-row" *matNoDataRow> <td class="mat-cell" [attr.colspan]="displayedColumns.length">No Data</td> </tr> </table> </gio-table-wrapper> `, }) class TestComponent { length = 0; dataSource = [{ name: '🦊' }, { name: '🐙' }, { name: '🐶' }]; displayedColumns = ['name']; filters: GioTableWrapperFilters; filtersChange = jest.fn(); } let component: TestComponent; let fixture: ComponentFixture<TestComponent>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ declarations: [TestComponent], imports: [NoopAnimationsModule, GioTableWrapperModule, MatTableModule, MatSortModule], }); fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; loader = TestbedHarnessEnvironment.loader(fixture); }); afterEach(() => { jest.clearAllMocks(); }); it('should emit default initial filtersChange', async () => { const tableWrapper = await loader.getHarness(GioTableWrapperHarness); expect(component.filtersChange).toHaveBeenCalledTimes(1); expect(component.filtersChange).toHaveBeenCalledWith({ pagination: { index: 1, size: 10, }, searchTerm: '', }); expect(await tableWrapper.getSearchValue()).toBe(''); }); it('should emit default initial filtersChange', async () => { component.filters = { pagination: { index: 2, size: 25, }, searchTerm: 'fox', }; component.length = 100; fixture.detectChanges(); const tableWrapper = await loader.getHarness(GioTableWrapperHarness); expect(component.filtersChange).toHaveBeenCalledTimes(1); expect(component.filtersChange).toHaveBeenCalledWith({ pagination: { index: 2, size: 25, }, searchTerm: 'fox', }); expect(await tableWrapper.getSearchValue()).toEqual('fox'); const paginator = await tableWrapper.getPaginator(); expect(await paginator.getRangeLabel()).toEqual('26 – 50 of 100'); }); it('should emit when search term change', async () => { fixture.detectChanges(); const tableWrapper = await loader.getHarness(GioTableWrapperHarness); // initial filtersChange expect(component.filtersChange).toHaveBeenCalledTimes(1); await tableWrapper.setSearchValue('Fox'); expect(component.filtersChange).toHaveBeenCalledTimes(3); expect(component.filtersChange).toHaveBeenNthCalledWith(2, { pagination: { index: 1, size: 10, }, searchTerm: '', }); expect(component.filtersChange).toHaveBeenNthCalledWith(3, { pagination: { index: 1, size: 10, }, searchTerm: 'Fox', }); }); it('should emit when pagination change', async () => { component.filters = { pagination: { index: 1, size: 25, }, searchTerm: '', }; component.length = 100; fixture.detectChanges(); const tableWrapper = await loader.getHarness(GioTableWrapperHarness); // initial filtersChange expect(component.filtersChange).toHaveBeenCalledTimes(1); const paginator = await tableWrapper.getPaginator(); await paginator.goToNextPage(); expect(component.filtersChange).toHaveBeenCalledTimes(2); expect(component.filtersChange).toHaveBeenNthCalledWith(2, { pagination: { index: 2, size: 25, }, searchTerm: '', }); await paginator.setPageSize(5); expect(component.filtersChange).toHaveBeenCalledTimes(3); expect(component.filtersChange).toHaveBeenNthCalledWith(3, { pagination: { index: 6, size: 5, }, searchTerm: '', }); }); it('should hide pagination when length < pagination size ', async () => { component.length = 0; component.filters = { pagination: { index: 1, size: 25, }, searchTerm: '', }; fixture.detectChanges(); const tableWrapper = await loader.getHarness(GioTableWrapperHarness); expect(await (await (await tableWrapper.getPaginator('footer')).host()).hasClass('hidden')).toBe(true); }); it('should emit and reset pagination when search term change', async () => { component.filters = { pagination: { index: 4, size: 10, }, searchTerm: 'fox', }; component.length = 100; fixture.detectChanges(); const tableWrapper = await loader.getHarness(GioTableWrapperHarness); const paginator = await tableWrapper.getPaginator(); // initial filtersChange expect(component.filtersChange).toHaveBeenCalledTimes(1); await tableWrapper.setSearchValue('Fox'); expect(component.filtersChange).toHaveBeenNthCalledWith(3, { pagination: { index: 1, size: 10, }, searchTerm: 'Fox', }); expect(await paginator.getRangeLabel()).toEqual('1 – 10 of 100'); }); }); describe('with sort usage', () => { @Component({ template: ` <gio-table-wrapper [length]="length" [filters]="filters" (filtersChange)="filtersChange($event)"> <table mat-table [dataSource]="dataSource" matSort> <!-- Name Column --> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th> <td mat-cell *matCellDef="let element">{{ element.name }}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr> <tr class="mat-row" *matNoDataRow> <td class="mat-cell" [attr.colspan]="displayedColumns.length">No Data</td> </tr> </table> </gio-table-wrapper> `, }) class TestComponentWithSort { length = 100; dataSource = [{ name: '🦊' }, { name: '🐙' }, { name: '🐶' }]; displayedColumns = ['name']; filters: GioTableWrapperFilters; filtersChange = jest.fn(); } let component: TestComponentWithSort; let fixture: ComponentFixture<TestComponentWithSort>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ declarations: [TestComponentWithSort], imports: [NoopAnimationsModule, GioTableWrapperModule, MatTableModule, MatSortModule, MatSortModule], }); fixture = TestBed.createComponent(TestComponentWithSort); component = fixture.componentInstance; loader = TestbedHarnessEnvironment.loader(fixture); }); afterEach(() => { jest.clearAllMocks(); }); it('should emit default initial filtersChange', async () => { const matSort = await loader.getHarness(MatSortHarness); const tableWrapper = await loader.getHarness(GioTableWrapperHarness); component.filters = { pagination: { index: 2, size: 25, }, searchTerm: 'fox', sort: { active: 'name', direction: 'asc', }, }; fixture.detectChanges(); expect(await (await matSort.getActiveHeader()).getLabel()).toEqual('Name'); expect(component.filtersChange).toHaveBeenNthCalledWith(2, { pagination: { index: 2, size: 25 }, searchTerm: 'fox', sort: { active: 'name', direction: 'asc', }, }); expect(await tableWrapper.getSearchValue()).toEqual('fox'); const paginator = await tableWrapper.getPaginator(); expect(await paginator.getRangeLabel()).toEqual('26 – 50 of 100'); expect(component.filtersChange).toHaveBeenCalledTimes(2); }); it('should emit when sort change', async () => { fixture.detectChanges(); const matSort = await loader.getHarness(MatSortHarness); const sortHeader = await matSort.getSortHeaders(); await sortHeader[0].click(); // initial filtersChange + sort change expect(component.filtersChange).toHaveBeenCalledTimes(2); expect(component.filtersChange).toHaveBeenNthCalledWith(2, { pagination: { index: 1, size: 10, }, searchTerm: '', sort: { active: 'name', direction: 'asc', }, }); await sortHeader[0].click(); expect(component.filtersChange).toHaveBeenNthCalledWith(3, { pagination: { index: 1, size: 10, }, searchTerm: '', sort: { active: 'name', direction: 'desc', }, }); }); }); });
the_stack
import { testSaga, TestApi, TestApiWithEffectsTesters, } from 'redux-saga-test-plan'; import { Platform, AppState } from 'react-native'; import NetInfo, { NetInfoState } from '@react-native-community/netinfo'; import networkSaga, { netInfoChangeSaga, connectionIntervalSaga, createNetInfoConnectionChangeChannel, connectionHandler, checkInternetAccessSaga, handleConnectivityChange, createIntervalChannel, intervalChannelFn, netInfoEventChannelFn, } from '../src/redux/sagas'; import { connectionChange } from '../src/redux/actionCreators'; import { networkSelector } from '../src/redux/createReducer'; import checkInternetAccess from '../src/utils/checkInternetAccess'; import { DEFAULT_ARGS } from '../src/utils/constants'; const args = DEFAULT_ARGS; describe('sagas', () => { describe('networkSaga', () => { it('forks netInfoChangeSaga with the right params', () => { const { pingInterval, ...params } = args; const { pingInBackground, pingOnlyIfOffline, ...rest } = params; testSaga(networkSaga, params) .next() .fork(netInfoChangeSaga, rest) .next() .isDone(); }); it(`forks netInfoChangeSaga AND sets an interval if pingInterval is higher than 0`, () => { const { pingInterval, ...params } = args; const { pingInBackground, pingOnlyIfOffline, shouldPing, ...rest } = params; testSaga(networkSaga, { ...args, pingInterval: 3000 }) .next() .fork(netInfoChangeSaga, { ...rest, shouldPing }) .next() .fork(connectionIntervalSaga, { ...rest, pingInterval: 3000, pingOnlyIfOffline, pingInBackground, }) .next() .isDone(); }); it('default parameters', () => { const { pingOnlyIfOffline, pingInterval, pingInBackground, ...params } = args; testSaga(networkSaga) .next() .fork(netInfoChangeSaga, { ...params }) .next() .isDone(); }); }); describe('netInfoChangeSaga', () => { const params = { pingTimeout: args.pingTimeout, pingServerUrl: args.pingServerUrl, shouldPing: args.shouldPing, httpMethod: args.httpMethod, customHeaders: args.customHeaders, }; function channelLoop(saga: TestApi) { return saga .next() .call(createNetInfoConnectionChangeChannel, netInfoEventChannelFn) .next('channel') .take('channel') .next(true) .fork(connectionHandler, { ...params, isConnected: true, }) .next() .take('channel'); } it('iOS', () => { Platform.OS = 'ios'; // @ts-ignore const saga = testSaga(netInfoChangeSaga, params); channelLoop(saga); }); it('Android', () => { Platform.OS = 'android'; // @ts-ignore const saga = testSaga(netInfoChangeSaga, params) .next() .call([NetInfo, NetInfo.fetch]) .next({ isConnected: false }) .fork(connectionHandler, { ...params, isConnected: false, }); channelLoop(saga); }); it('closes the channel when it ends emitting', () => { Platform.OS = 'ios'; const mockCloseFn = jest.fn(); const mockChannel = { close: mockCloseFn, }; const iterator = netInfoChangeSaga(params); iterator.next(); // This will make take(mockChannel) throw an error, since it's not a valid // channel or a valid pattern for take() inside the infinite loop, // hence executing the finally block. iterator.next((mockChannel as unknown) as NetInfoState); try { iterator.next({ isConnected: true } as NetInfoState); expect(mockCloseFn).toHaveBeenCalled(); // eslint-disable-next-line } catch (e) {} }); it('does NOT close the channel if redux-saga does NOT yield a cancelled effect', () => { Platform.OS = 'ios'; const mockCloseFn = jest.fn(); const mockChannel = { close: mockCloseFn, }; const iterator = netInfoChangeSaga(params); iterator.next(); // This will make take(mockChannel) throw an error, since it's not a valid // channel or a valid pattern for take() inside the infinite loop, // hence executing the finally block. iterator.next((mockChannel as unknown) as NetInfoState); try { iterator.next({ isConnected: false } as NetInfoState); expect(mockCloseFn).not.toHaveBeenCalled(); // eslint-disable-next-line } catch (e) {} }); }); describe('connectionHandler', () => { const params = { pingTimeout: args.pingTimeout, pingServerUrl: args.pingServerUrl, shouldPing: true, httpMethod: args.httpMethod, isConnected: true, customHeaders: args.customHeaders, }; it('forks checkInternetAccessSaga if shouldPing AND isConnected are true', () => { const saga = testSaga(connectionHandler, params); saga .next() .fork(checkInternetAccessSaga, { pingTimeout: args.pingTimeout, pingServerUrl: args.pingServerUrl, httpMethod: args.httpMethod, pingInBackground: args.pingInBackground, customHeaders: args.customHeaders, }) .next() .isDone(); }); it('forks handleConnectivityChange if shouldPing OR isConnected are NOT true', () => { params.isConnected = false; const saga = testSaga(connectionHandler, params); saga .next() .fork(handleConnectivityChange, false) .next() .isDone(); }); }); describe('connectionIntervalSaga', () => { const { shouldPing, ...params } = args; function takeChannelAndGetConnection(saga: TestApi, isConnected: boolean) { return saga .next() .call(createIntervalChannel, 3000, intervalChannelFn) .next('channel') .take('channel') .next() .select(networkSelector) .next({ isConnected }); } it(`forks checkInternetAccessSaga if it's NOT connected or it is, but pingOnlyIfOffline is false`, () => { // @ts-ignore let saga: TestApiWithEffectsTesters = testSaga(connectionIntervalSaga, { ...params, pingOnlyIfOffline: false, pingInterval: 3000, }); saga = takeChannelAndGetConnection(saga, true); saga .fork(checkInternetAccessSaga, { pingTimeout: params.pingTimeout, pingServerUrl: params.pingServerUrl, httpMethod: params.httpMethod, pingInBackground: params.pingInBackground, customHeaders: args.customHeaders, }) .next() .take('channel'); }); it(`does NOT fork checkInternetAccessSaga if it's connected AND pingOnlyIfOffline is true`, () => { // @ts-ignore let saga: TestApiWithEffectsTesters = testSaga(connectionIntervalSaga, { ...params, pingOnlyIfOffline: true, pingInterval: 3000, }); saga = takeChannelAndGetConnection(saga, true); saga.take('channel'); }); it('closes the channel when it ends emitting', () => { const mockCloseFn = jest.fn(); const mockChannel = { close: mockCloseFn, isConnected: false, actionQueue: [], isQueuePaused: false, }; const iterator = connectionIntervalSaga({ ...params, pingOnlyIfOffline: true, pingInterval: 3000, }); iterator.next(); // This will make take(mockChannel) throw an error, since it's not a valid // channel or a valid pattern for take() inside the infinite loop, // hence executing the finally block. iterator.next(mockChannel); try { // @ts-ignore iterator.next(true); expect(mockCloseFn).toHaveBeenCalled(); // eslint-disable-next-line } catch (e) {} }); it('does NOT close the channel if redux-saga does NOT yield a cancelled effect', () => { const mockCloseFn = jest.fn(); const mockChannel = { close: mockCloseFn, isConnected: false, actionQueue: [], isQueuePaused: false, }; const iterator = connectionIntervalSaga({ ...params, pingOnlyIfOffline: true, pingInterval: 3000, }); iterator.next(); // This will make take(mockChannel) throw an error, since it's not a valid // channel or a valid pattern for take() inside the infinite loop, // hence executing the finally block. iterator.next(mockChannel); try { // @ts-ignore iterator.next(false); expect(mockCloseFn).not.toHaveBeenCalled(); // eslint-disable-next-line } catch (e) {} }); }); describe('checkInternetAccessSaga', () => { const params = { pingServerUrl: args.pingServerUrl, pingTimeout: args.pingTimeout, httpMethod: args.httpMethod, pingInBackground: false, customHeaders: args.customHeaders, }; it('returns early if pingInBackground is false AND app state is NOT active', () => { AppState.currentState = 'inactive'; const saga = testSaga(checkInternetAccessSaga, params); saga.next().isDone(); }); it('calls checkInternetAccess AND handleConnectivityChange', () => { params.pingInBackground = true; const saga = testSaga(checkInternetAccessSaga, params); saga .next() .call(checkInternetAccess, { url: params.pingServerUrl, timeout: params.pingTimeout, method: params.httpMethod, customHeaders: params.customHeaders, }) .next(true) .call(handleConnectivityChange, true) .next() .isDone(); }); }); describe('handleConnectivityChange', () => { it('dispatches a CONNECTION_CHANGE action if the connection changed ', () => { const actionQueue = ['foo', 'bar']; // @ts-ignore const saga = testSaga(handleConnectivityChange, false); saga .next() .select(networkSelector) .next({ actionQueue, isConnected: true }) .put(connectionChange(false)) .next() .isDone(); }); it('does NOT dispatch if connection did NOT change and we are offline', () => { const actionQueue = ['foo', 'bar']; // @ts-ignore const saga = testSaga(handleConnectivityChange, false); saga .next() .select(networkSelector) .next({ actionQueue, isConnected: false }) .isDone(); }); }); });
the_stack
import { Observable } from 'rxjs/Observable'; import * as fromRouter from '@ngrx/router-store'; import { localStorageSync } from 'ngrx-store-localstorage'; import { Article } from './article/article.model'; import { Book } from './book/book.model'; import { Claim } from './claim/claim.model'; import { Comment } from './comment/comment.model'; import { Crisis } from './crisis/crisis.model'; import { ClaimRebuttal } from './claim-rebuttal/claim-rebuttal.model'; import { Contact } from './contact/contact.model'; import { Counter } from './counter/counter.model'; import { Hero } from './hero/hero.model'; import { Layout } from './layout/layout.model'; import { Note } from './note/note.model'; import { Profile } from './profile/profile.model'; import { Rebuttal } from './rebuttal/rebuttal.model'; import { Session } from './session/session.model'; import { User } from './user/user.model'; import { Tag } from './tag/tag.model'; import { BlogPageLayout } from '../../features/blog/blog.layout'; import { Talk } from './talk/talk.model'; import { actions } from './entity/entity.actions'; import { completeAssign } from './util'; import { ActionReducerMap, createSelector, createFeatureSelector, compose, ActionReducer, combineReducers, Action, ActionReducerFactory, MetaReducer } from '@ngrx/store'; /** * storeFreeze prevents state from being mutated. When mutation occurs, an * exception will be thrown. This is useful during development mode to * ensure that none of the reducers accidentally mutates the state. */ import { storeFreeze } from 'ngrx-store-freeze'; /** * Every reducer module's default export is the reducer function itself. In * addition, each module should export a type or interface that describes * the state of the reducer plus any selector functions. The `* as` * notation packages up all of the exports into a single object. */ import * as fromArticles from './article/article.reducer'; import * as fromBooks from './book/book.reducer'; import * as fromClaimRebuttals from './claim-rebuttal/claim-rebuttal.reducer'; import * as fromClaims from './claim/claim.reducer'; import * as fromCollection from './collection/collection.reducer'; import * as fromComments from './comment/comment.reducer'; import * as fromContacts from './contact/contact.reducer'; import * as fromCounter from './counter/counter.reducer'; import * as fromCrises from './crisis/crisis.reducer'; import * as fromGames from './game/game.reducer'; import * as fromHeroes from './hero/hero.reducer'; import * as fromLayout from './layout/layout.reducer'; import * as fromMessages from './message/message.reducer'; import * as fromNotes from './note/note.reducer'; import * as fromProfiles from './profile/profile.reducer'; import * as fromRebuttals from './rebuttal/rebuttal.reducer'; import * as fromSearch from './search/search.reducer'; import * as fromSession from './session/session.reducer'; import * as fromTags from './tag/tag.reducer'; import * as fromTalks from './talk/talk.reducer'; import { gameReducer, gamesReducer, p2pGameReducer } from './game/game.reducer'; import { Entities } from './entity/entity.model'; import { IDs } from './id/id.model'; /** * As mentioned, we treat each reducer like a table in a database. This means * our top level state interface is just a map of keys to inner state types. */ export interface RootState { book: Entities<Book>; article: Entities<Article>; claimRebuttal: Entities<ClaimRebuttal>; claim: Entities<Claim>; collection: IDs; comment: Entities<Comment>; contact: Entities<Contact>; counter: Counter; crisis: Entities<Crisis>; game; games; hero: Entities<Hero>; layout: Layout; message: any; note: Entities<Note>; p2pGame; profile: Entities<Profile>; rebuttal: Entities<Rebuttal>; router: fromRouter.RouterReducerState; search: IDs; session: Session; tag: Entities<Tag>; talk: Entities<Talk>; } export type RootStateKeys = keyof RootState; /** * Because metareducers take a reducer function and return a new reducer, * we can use our compose helper to chain them together. Here we are * using combineReducers to make our top level reducer, and then * wrapping that in storeLogger. Remember that compose applies * the result from right to left. */ export let reducers: ActionReducerMap<RootState> = { book: fromBooks.reducer, article: fromArticles.reducer, claim: fromClaims.reducer, claimRebuttal: fromClaimRebuttals.reducer, contact: fromContacts.reducer, collection: fromCollection.reducer, counter: fromCounter.reducer, crisis: fromCrises.reducer, game: fromGames.gameReducer, games: gamesReducer, hero: fromHeroes.reducer, layout: fromLayout.reducer, message: fromMessages.reducer, note: fromNotes.reducer, p2pGame: p2pGameReducer, profile: fromProfiles.reducer, rebuttal: fromRebuttals.reducer, router: fromRouter.routerReducer, search: fromSearch.reducer, comment: fromComments.reducer, talk: fromTalks.reducer, tag: fromTags.reducer, session: fromSession.reducer }; /** * By default, @ngrx/store uses combineReducers with the reducer map to compose * the root meta-reducer. To add more meta-reducers, provide an array of meta-reducers * that will be composed to form the root meta-reducer. */ // export const metaReducers: ActionReducer<any, any>[] = process.env.NODE_ENV === 'dev' // ? [logger] // : []; // export const metaReducers: MetaReducer<RootState>[] = (process.env.NODE_ENV === 'dev' // ? [logger] // : []).concat(loadingSetter) export const metaReducers: MetaReducer<RootState>[] = [logger, loadingSetter] // console.log all actions function logger(reducer: ActionReducer<RootState>) { return function (state: RootState, action: any) { console.log('state', state); console.log('action', action); return reducer(state, action); } } // set loading and loaded fields function loadingSetter(reducer: ActionReducer<RootState>) { return function (state: RootState, action: any) { let newState = state; if (action.verb) { newState = setLoading(state, action) } return reducer(newState, action); } } function setLoading(state, action) { const loading = isLoadingAction(action.verb); const loadSuccess = isLoadSuccessAction(action.verb); const loadFail = isLoadFailAction(action.verb); const newState = completeAssign({}, state); if (loading) { newState[action.slice].loading = true; } if (loadSuccess || loadFail) { newState[action.slice].loading = false; } if (loadSuccess) { newState[action.slice].loaded = true; } if (action.verb === actions.UNLOAD) { newState[action.slice].loaded = false; } if (action.verb === actions.ASYNC_SUCCESS) { if (typeof action.payload.totalItems !== 'undefined') { newState[action.slice].totalItems = action.payload.totalItems; } } return newState; } function isLoadingAction(verb: string) { switch (verb) { case actions.ADD: case actions.DELETE: case actions.LOAD: case actions.PATCH: case actions.UPDATE: case 'ADD_COMMENT': // TODO: create an ADD_CHILD action verb to handle this return true; default: return false; } } function isLoadSuccessAction(verb: string) { switch (verb) { case actions.ADD_SUCCESS: case actions.DELETE_SUCCESS: // case actions.ASYNC: case actions.ASYNC_SUCCESS: case actions.PATCH_SUCCESS: case actions.UPDATE_SUCCESS: return true; default: return false; } } function isLoadFailAction(verb: string) { switch (verb) { case actions.ADD_UPDATE_FAIL: case actions.DELETE_FAIL: case actions.LOAD_FAIL: case actions.PATCH_FAIL: return true; default: return false; } } const developmentReducer = compose( // reduxThunk, // Thunk middleware for Redux // reduxMulti, // Dispatch multiple actions // reduxPromiseMiddleware(), // storeFreeze, localStorageSync({ keys: ['session'] }), combineReducers)(reducers); const productionReducer = compose( // reduxThunk, // Thunk middleware for Redux // reduxMulti, // Dispatch multiple actions // reduxPromiseMiddleware(), localStorageSync({ keys: ['session'] }), combineReducers)(reducers); export function reducer(state: any, action: any) { if (process.env.NODE_ENV === 'prod') { return productionReducer(state, action); } else { return developmentReducer(state, action); } } /** * The compose function is one of our most handy tools. In basic terms, you give * it any number of functions and it returns a function. This new function * takes a value and chains it through every composed function, returning * the output. * * More: https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch5.html */ /** * combineReducers is another useful metareducer that takes a map of reducer * functions and creates a new reducer that gathers the values * of each reducer and stores them using the reducer's key. Think of it * almost like a database, where every reducer is a table in the db. * * More: https://egghead.io/lessons/javascript-redux-implementing-combinereducers-from-scratch */ /** * By default, @ngrx/store uses combineReducers with the reducer map to compose the root meta-reducer. * To add more meta-reducers, provide a custom reducer factory. */ export const developmentReducerFactory: ActionReducerFactory<RootState, Action> = compose(logger, combineReducers); /** * A selector function is a map function factory. We pass it parameters and it * returns a function that maps from the larger state tree into a smaller * piece of state. This selector simply selects the `books` state. * * Selectors are used with the `select` operator. * * ```ts * class MyComponent { * constructor(state$: Observable<State>) { * this.booksState$ = state$.select(getBooksState); * } * } * ``` */ /** * The createFeatureSelector function selects a piece of state from the root of the state object. * This is used for selecting feature states that are loaded eagerly or lazily. */ // const developmentReducer = compose( // // reduxThunk, // Thunk middleware for Redux // // reduxMulti, // Dispatch multiple actions // // reduxPromiseMiddleware(), // // storeFreeze, // localStorageSync({ keys: ['session'] }), // combineReducers)(reducers); // const productionReducer = compose( // // reduxThunk, // Thunk middleware for Redux // // reduxMulti, // Dispatch multiple actions // // reduxPromiseMiddleware(), // localStorageSync({ keys: ['session'] }), // combineReducers)(reducers); // export function reducer(state: any, action: any) { // if (process.env === 'prod') { // return productionReducer(state, action); // } else { // return developmentReducer(state, action); // } // } /** * A selector function is a map function factory. We pass it parameters and it * returns a function that maps from the larger state tree into a smaller * piece of state. This selector simply selects the `books` state. * * Selectors are used with the `select` operator. * * ```ts * class MyComponent { * constructor(state$: Observable<RootState>) { * this.booksState$ = state$.select(getBooksState); * } * } * * ``` * */ export const getBooksState = (state: RootState) => state.book; /** * Every reducer module exports selector functions, however child reducers * have no knowledge of the overall state tree. To make them useable, we * need to make new selectors that wrap them. * * Once again our createSelector function comes in handy. From right to left, we * first select the books state then we pass the state to the book * reducer's getBooks selector, finally returning an observable * of search results. * * Share memoizes the selector functions and published the result. This means * every time you call the selector, you will get back the same result * observable. Each subscription to the resultant observable * is shared across all subscribers. */ export const getBookEntities = createSelector(getBooksState, fromBooks.getEntities); export const getBookIds = createSelector(getBooksState, fromBooks.getIds); export const getSelectedBookId = createSelector(getBooksState, fromBooks.getSelectedId); export const getSelectedBook = createSelector(getBooksState, fromBooks.getSelected); /** * Just like with the books selectors, we also have to createSelector the search * reducer's and collection reducer's selectors. */ export const getSearchState = (state: RootState) => state.search; export const getSearchBookIds = createSelector(getSearchState, fromSearch.getIds); export const getSearchLoading = createSelector(getSearchState, fromSearch.getLoading); /** * Some selector functions create joins across parts of state. This selector * composes the search result IDs to return an array of books in the store. */ export const getSearchResults = createSelector(getBookEntities, getSearchBookIds, (books, searchIds) => { return searchIds.map((id) => books[id]); }); export const getCollectionState = (state: RootState) => state.collection; export const getCollectionLoaded = createSelector(getCollectionState, fromCollection.getLoaded); export const getCollectionLoading = createSelector(getCollectionState, fromCollection.getLoading); export const getCollectionBookIds = createSelector(getCollectionState, fromCollection.getIds); export const getBookCollection = createSelector(getBookEntities, getCollectionBookIds, (entities, ids) => { return ids.map((id) => entities[id]); }); export const isSelectedBookInCollection = createSelector(getCollectionBookIds, getSelectedBookId, (ids, selected) => { return ids.indexOf(selected) > -1; }); /** * Layout Selectors */ export const getLayoutState = (state: RootState) => state.layout; export const getMsg = createSelector(getLayoutState, fromLayout.getMsg); export const getBerniePageState = createSelector(getLayoutState, fromLayout.getBerniePageState); export const getHeroSearchTerm = createSelector(getLayoutState, fromLayout.getHeroSearchTerm); export const getSearchQuery = createSelector(getLayoutState, fromLayout.getBookSearchQuery); export const getBernieSearchTerm = createSelector(getLayoutState, fromLayout.getBernieSearchTerm); export const getBlogPageLayout = createSelector(getLayoutState, fromLayout.getBlogPageState); export const getTalksPageFilters = createSelector(getLayoutState, fromLayout.getTalksPageFilters); /** * Session Selectors */ export const getSessionState = (state: RootState) => state.session; export const hasError = createSelector(getSessionState, fromSession.hasError); export const isLoading = createSelector(getSessionState, fromSession.isLoading); export const loggedIn = createSelector(getSessionState, fromSession.loggedIn); export const loggedOut = createSelector(getSessionState, fromSession.loggedOut); export const getFirstName = createSelector(getSessionState, fromSession.getFirstName); export const getLastName = createSelector(getSessionState, fromSession.getLastName); export const getCurrentUser = createSelector(getSessionState, fromSession.getCurrentUser); /** * Profiles Selectors */ export const getProfilesState = (state: RootState): Entities<Profile> => state.profile; export const getProfileEntities = createSelector(getProfilesState, fromProfiles.getEntities); export const getProfileIds = createSelector(getProfilesState, fromProfiles.getIds); export const getProfiles = createSelector(getProfileEntities, getProfileIds, (entities, ids) => { return ids.map((id) => entities[id]); }); // TODO: Setting bio to '' is just wrong, but the author:user relationship is a real pain export const getCurrentProfile = createSelector(getCurrentUser, (user): Profile => { return { id: user.id, username: user.login, bio: '', image: user.imageUrl, following: false }; }); /** * Notes Selectors */ export const getNotesState = (state: RootState) => state.note; export const getNoteEntities = createSelector(getNotesState, fromNotes.getEntities); export const getNoteIds = createSelector(getNotesState, fromNotes.getIds); export const getNotes = createSelector(getNoteEntities, getNoteIds, (entities, ids) => { return ids.map((id) => entities[id]); }); /** * Claims Selectors */ export const getClaimsState = (state: RootState): Entities<Claim> => state.claim; export const getClaimEntities = createSelector(getClaimsState, fromClaims.getEntities); export const getClaimIds = createSelector(getClaimsState, fromClaims.getIds); export const getClaims = createSelector(getClaimEntities, getClaimIds, (entities, ids) => { return ids.map((id) => entities[id]); }); export const getSelectedClaimId = createSelector(getClaimsState, fromClaims.getSelectedId); export const getSelectedProfile = createSelector(getProfilesState, fromProfiles.getSelected); // export const getBerniePage = createSelector(getBerniePageState, getClaims, (berniePage, claims) => { // let _dirty = false; // claims.forEach((claim) => { // claim.rebuttals.forEach((rebuttal) => { // if (rebuttal && rebuttal.dirty) { // _dirty = true; // } // }); // }); // return Object.assign({}, berniePage, { dirty: _dirty }); // }); /** * Rebuttal Selectors */ export const getRebuttalsState = (state: RootState): Entities<Rebuttal> => state.rebuttal; export const getRebuttalEntities = createSelector(getRebuttalsState, fromRebuttals.getEntities); export const getRebuttalIds = createSelector(getRebuttalsState, fromRebuttals.getIds); export const getRebuttals = createSelector(getRebuttalEntities, getRebuttalIds, (entities, ids) => { return ids.map((id) => entities[id]); }); /** * ClaimRebuttal Selectors */ export const getClaimRebuttalsState = (state: RootState): Entities<ClaimRebuttal> => state.claimRebuttal; export const getClaimRebuttalEntities = createSelector(getClaimRebuttalsState, fromClaimRebuttals.getEntities); export const getClaimRebuttalIds = createSelector(getClaimRebuttalsState, fromClaimRebuttals.getIds); export const getClaimRebuttals = createSelector(getClaimRebuttalEntities, getClaimRebuttalIds, (entities, ids) => { return ids.map((id) => entities[id]); }); export const getDeepClaimRebuttals = createSelector(getClaimRebuttals, getRebuttals, (claimRebuttals, rebuttals) => { return claimRebuttals.map((cr) => { return { claimId: cr.claimId, sortOrder: cr.sortOrder, rebuttal: rebuttals.filter((rebuttal) => rebuttal.id === cr.rebuttalId)[0] } }) }); export const getDeepClaims = createSelector(getClaimsState, getDeepClaimRebuttals, getBernieSearchTerm, (state, deepClaimRebuttals, bernieSearchTerm) => { return { selectedClaimId: state.selectedEntityId, shallowClaims: state.entities, deepClaims: state.ids.map((id) => { return completeAssign({}, <Claim>state.entities[id], { rebuttals: deepClaimRebuttals .filter((dcr) => !!dcr.rebuttal && dcr.claimId === id) .sort((a, b) => a.sortOrder < b.sortOrder ? -1 : 1) .map((dcr) => dcr.rebuttal) }) } ) .filter((dc) => !bernieSearchTerm || (dc.name && dc.name.toLowerCase().indexOf(bernieSearchTerm.toLowerCase()) > -1)) .sort((a, b) => a.sortOrder < b.sortOrder ? -1 : 1) } }); /** * Counter Selectors */ export const getCounterState = (state: RootState) => state.counter; export const getCounterValue = createSelector(getCounterState, fromCounter.getValue); /** * Crises Selectors */ export const getCrisesState = (state: RootState): Entities<Crisis> => state.crisis; export const getCrisisEntities = createSelector(getCrisesState, fromCrises.getEntities); export const getCrisisIds = createSelector(getCrisesState, fromCrises.getIds); export const getSelectedCrisis = createSelector(getCrisesState, fromCrises.getSelected); export const getCrises = createSelector(getCrisisEntities, getCrisisIds, (entities, ids) => { return ids.map((id) => entities[id]); }); // A selector that takes a parameter (id) export const getCrisis = (id) => createSelector(getCrisesState, (crisisList) => { // return crisisList.filter(c => c.id === id); return crisisList.ids.map((crisisId) => crisisList.entities[crisisId]).filter((c) => c.id === id); }); /** * Contacts Selectors */ export const getContactsState = (state: RootState): Entities<Contact> => state.contact; export const getContactEntities = createSelector(getContactsState, fromContacts.getEntities); export const getContactIds = createSelector(getContactsState, fromContacts.getIds); export const getSelectedContact = createSelector(getContactsState, fromContacts.getSelected); export const getContacts = createSelector(getContactEntities, getContactIds, (entities, ids) => { return ids.map((id) => entities[id]); }); /** * Heroes Selectors */ export const getHeroesState = (state: RootState): Entities<Hero> => state.hero; export const getHeroEntities = createSelector(getHeroesState, fromHeroes.getEntities); export const getHeroIds = createSelector(getHeroesState, fromHeroes.getIds); export const getSelectedHero = createSelector(getHeroesState, fromHeroes.getSelected); export const getHeroes = createSelector(getHeroEntities, getHeroIds, (entities, ids) => { return ids.map((id) => entities[id]); }); export const getHeroesForSearchTerm = createSelector(getHeroes, getHeroSearchTerm, (heroes, searchTerm) => { return heroes.filter((hero) => hero.name.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1); }); /** * Messages Selectors */ export const getMessagesState = (state: RootState) => state.message; export const getMessageEntities = createSelector(getMessagesState, fromMessages.getEntities); export const getMessageIds = createSelector(getMessagesState, fromMessages.getIds); export const getSelectedMessage = createSelector(getMessagesState, fromMessages.getSelected); export const getMessages = createSelector(getMessageEntities, getMessageIds, (entities, ids) => { return ids.map((id) => entities[id]); }); export const getMessage = createSelector(getMessagesState, fromMessages.getSelected); /** * Comments Selectors */ export const getCommentsState = (state: RootState): Entities<Comment> => state.comment; export const getCommentEntities = createSelector(getCommentsState, fromComments.getEntities); export const getCommentIds = createSelector(getCommentsState, fromComments.getIds); export const getComments = createSelector(getCommentEntities, getCommentIds, (entities, ids) => { return ids.map((id) => entities[id]); }); export const getCleanTempComment = createSelector(getCommentsState, fromComments.getCleanTemp); /** * Tags Selectors */ export const getTagsState = (state: RootState): Entities<Tag> => state.tag; export const getTagEntities = createSelector(getTagsState, fromTags.getEntities); export const getTagIds = createSelector(getTagsState, fromTags.getIds); export const getTags = createSelector(getTagEntities, getTagIds, (entities, ids) => { return ids.map((id) => entities[id].name); }); /** * Articles Selectors */ export const getArticlesState = (state: RootState): Entities<Article> => state.article; export const getArticleEntities = createSelector(getArticlesState, fromArticles.getEntities); export const getArticleIds = createSelector(getArticlesState, fromArticles.getIds); export const getArticleLoaded = createSelector(getArticlesState, fromArticles.getLoading); export const getSelectedArticleId = createSelector(getArticlesState, fromArticles.getSelectedId); export const getSelectedArticle = createSelector(getArticlesState, (articles) => { return completeAssign({}, articles.entities[articles.selectedEntityId], { loading: articles.loading }); }); export const getTempArticle = createSelector(getArticlesState, fromArticles.getTemp); export const getArticles = createSelector(getArticleEntities, getArticleIds, (entities, ids) => { return ids.map((id) => entities[id]); }); export const getCommentsForSelectedArticle = createSelector(getComments, getSelectedArticleId, (comments, articleId) => { return comments.filter((comment) => comment && comment.articleId === articleId); }); /** * Talks Selectors */ export const getTalksState = (state: RootState) => state.talk; export const getTalkEntities = createSelector(getTalksState, fromTalks.getEntities); export const getSelectedTalkId = createSelector(getTalksState, fromTalks.getSelectedId); export const getSelectedTalk = createSelector(getTalksState, fromTalks.getSelected); export const getTalkIds = createSelector(getTalksState, fromTalks.getIds); export const getTalks = createSelector(getTalkEntities, getTalkIds, (entities, ids) => { return ids.map((id) => entities[id]); }); export const getEntityState = (slice: keyof RootState) => { return (state: RootState) => state[slice]; } export const getEntityLoaded = (slice: keyof RootState) => { return (state: RootState) => { return state[slice].loaded; } }
the_stack
import { Assertion, Orbit } from '@orbit/core'; import { buildQuery, buildTransform, DefaultRequestOptions, FullRequestOptions, FullResponse, OperationTerm, QueryOrExpressions, RequestOptions, TransformOrOperations } from '@orbit/data'; import { AsyncRecordQueryable, AsyncRecordUpdatable, InitializedRecord, RecordIdentity, RecordOperation, RecordOperationResult, RecordOperationTerm, RecordQuery, RecordQueryBuilder, RecordQueryExpression, RecordQueryResult, recordsReferencedByOperations, RecordTransform, RecordTransformBuilder, RecordTransformBuilderFunc, RecordTransformResult } from '@orbit/records'; import { deepGet, Dict, toArray } from '@orbit/utils'; import { AsyncOperationProcessor, AsyncOperationProcessorClass } from './async-operation-processor'; import { AsyncLiveQuery } from './live-query/async-live-query'; import { AsyncCacheIntegrityProcessor } from './operation-processors/async-cache-integrity-processor'; import { AsyncSchemaConsistencyProcessor } from './operation-processors/async-schema-consistency-processor'; import { AsyncSchemaValidationProcessor } from './operation-processors/async-schema-validation-processor'; import { AsyncInverseTransformOperator, AsyncInverseTransformOperators } from './operators/async-inverse-transform-operators'; import { AsyncQueryOperator, AsyncQueryOperators } from './operators/async-query-operators'; import { AsyncTransformOperator, AsyncTransformOperators } from './operators/async-transform-operators'; import { AsyncRecordAccessor, RecordChangeset, RecordRelationshipIdentity } from './record-accessor'; import { RecordCache, RecordCacheQueryOptions, RecordCacheSettings, RecordCacheTransformOptions } from './record-cache'; import { RecordTransformBuffer } from './record-transform-buffer'; import { PatchResult, RecordCacheUpdateDetails } from './response'; const { assert, deprecate } = Orbit; export interface AsyncRecordCacheSettings< QO extends RequestOptions = RecordCacheQueryOptions, TO extends RequestOptions = RecordCacheTransformOptions, QB = RecordQueryBuilder, TB = RecordTransformBuilder > extends RecordCacheSettings<QO, TO, QB, TB> { processors?: AsyncOperationProcessorClass[]; queryOperators?: Dict<AsyncQueryOperator>; transformOperators?: Dict<AsyncTransformOperator>; inverseTransformOperators?: Dict<AsyncInverseTransformOperator>; debounceLiveQueries?: boolean; transformBuffer?: RecordTransformBuffer; } export abstract class AsyncRecordCache< QO extends RequestOptions = RecordCacheQueryOptions, TO extends RequestOptions = RecordCacheTransformOptions, QB = RecordQueryBuilder, TB = RecordTransformBuilder, QueryResponseDetails = unknown, TransformResponseDetails extends RecordCacheUpdateDetails = RecordCacheUpdateDetails > extends RecordCache<QO, TO, QB, TB> implements AsyncRecordAccessor, AsyncRecordQueryable<QueryResponseDetails, QB, QO>, AsyncRecordUpdatable<TransformResponseDetails, TB, TO> { protected _processors: AsyncOperationProcessor[]; protected _queryOperators: Dict<AsyncQueryOperator>; protected _transformOperators: Dict<AsyncTransformOperator>; protected _inverseTransformOperators: Dict<AsyncInverseTransformOperator>; protected _debounceLiveQueries: boolean; protected _transformBuffer?: RecordTransformBuffer; constructor(settings: AsyncRecordCacheSettings<QO, TO, QB, TB>) { super(settings); this._queryOperators = settings.queryOperators ?? AsyncQueryOperators; this._transformOperators = settings.transformOperators ?? AsyncTransformOperators; this._inverseTransformOperators = settings.inverseTransformOperators ?? AsyncInverseTransformOperators; this._debounceLiveQueries = settings.debounceLiveQueries !== false; this._transformBuffer = settings.transformBuffer; const processors: AsyncOperationProcessorClass[] = settings.processors ? settings.processors : [AsyncSchemaConsistencyProcessor, AsyncCacheIntegrityProcessor]; if (Orbit.debug && settings.processors === undefined) { processors.push(AsyncSchemaValidationProcessor); } this._processors = processors.map((Processor) => { let processor = new Processor(this); assert( 'Each processor must extend AsyncOperationProcessor', processor instanceof AsyncOperationProcessor ); return processor; }); } get processors(): AsyncOperationProcessor[] { return this._processors; } getQueryOperator(op: string): AsyncQueryOperator { return this._queryOperators[op]; } getTransformOperator(op: string): AsyncTransformOperator { return this._transformOperators[op]; } getInverseTransformOperator(op: string): AsyncInverseTransformOperator { return this._inverseTransformOperators[op]; } // Abstract methods for getting records and relationships abstract getRecordAsync( recordIdentity: RecordIdentity ): Promise<InitializedRecord | undefined>; abstract getRecordsAsync( typeOrIdentities?: string | RecordIdentity[] ): Promise<InitializedRecord[]>; abstract getInverseRelationshipsAsync( recordIdentityOrIdentities: RecordIdentity | RecordIdentity[] ): Promise<RecordRelationshipIdentity[]>; // Abstract methods for setting records and relationships abstract setRecordAsync(record: InitializedRecord): Promise<void>; abstract setRecordsAsync(records: InitializedRecord[]): Promise<void>; abstract removeRecordAsync( recordIdentity: RecordIdentity ): Promise<InitializedRecord | undefined>; abstract removeRecordsAsync( recordIdentities: RecordIdentity[] ): Promise<InitializedRecord[]>; abstract addInverseRelationshipsAsync( relationships: RecordRelationshipIdentity[] ): Promise<void>; abstract removeInverseRelationshipsAsync( relationships: RecordRelationshipIdentity[] ): Promise<void>; async applyRecordChangesetAsync(changeset: RecordChangeset): Promise<void> { const { setRecords, removeRecords, addInverseRelationships, removeInverseRelationships } = changeset; const promises = []; if (setRecords && setRecords.length > 0) { promises.push(await this.setRecordsAsync(setRecords)); } if (removeRecords && removeRecords.length > 0) { promises.push(await this.removeRecordsAsync(removeRecords)); } if (addInverseRelationships && addInverseRelationships.length > 0) { promises.push( await this.addInverseRelationshipsAsync(addInverseRelationships) ); } if (removeInverseRelationships && removeInverseRelationships.length > 0) { promises.push( await this.removeInverseRelationshipsAsync(removeInverseRelationships) ); } await Promise.all(promises); } async getRelatedRecordAsync( identity: RecordIdentity, relationship: string ): Promise<RecordIdentity | null | undefined> { const record = await this.getRecordAsync(identity); if (record) { return deepGet(record, ['relationships', relationship, 'data']); } return undefined; } async getRelatedRecordsAsync( identity: RecordIdentity, relationship: string ): Promise<RecordIdentity[] | undefined> { const record = await this.getRecordAsync(identity); if (record) { return deepGet(record, ['relationships', relationship, 'data']); } return undefined; } /** * Queries the cache. */ query<RequestData extends RecordQueryResult = RecordQueryResult>( queryOrExpressions: QueryOrExpressions<RecordQueryExpression, QB>, options?: DefaultRequestOptions<QO>, id?: string ): Promise<RequestData>; query<RequestData extends RecordQueryResult = RecordQueryResult>( queryOrExpressions: QueryOrExpressions<RecordQueryExpression, QB>, options: FullRequestOptions<QO>, id?: string ): Promise<FullResponse<RequestData, QueryResponseDetails, RecordOperation>>; async query<RequestData extends RecordQueryResult = RecordQueryResult>( queryOrExpressions: QueryOrExpressions<RecordQueryExpression, QB>, options?: QO, id?: string ): Promise< | RequestData | FullResponse<RequestData, QueryResponseDetails, RecordOperation> > { const query = buildQuery( queryOrExpressions, options, id, this._queryBuilder ); const response = await this._query<RequestData>(query, options); if (options?.fullResponse) { return response; } else { return response.data as RequestData; } } /** * Updates the cache. */ update<RequestData extends RecordTransformResult = RecordTransformResult>( transformOrOperations: TransformOrOperations<RecordOperation, TB>, options?: DefaultRequestOptions<TO>, id?: string ): Promise<RequestData>; update<RequestData extends RecordTransformResult = RecordTransformResult>( transformOrOperations: TransformOrOperations<RecordOperation, TB>, options: FullRequestOptions<TO>, id?: string ): Promise< FullResponse<RequestData, TransformResponseDetails, RecordOperation> >; async update< RequestData extends RecordTransformResult = RecordTransformResult >( transformOrOperations: TransformOrOperations<RecordOperation, TB>, options?: TO, id?: string ): Promise< | RequestData | FullResponse<RequestData, TransformResponseDetails, RecordOperation> > { const transform = buildTransform( transformOrOperations, options, id, this._transformBuilder ); const response = await this._update<RequestData>(transform, options); if (options?.fullResponse) { return response; } else { return response.data as RequestData; } } /** * Patches the cache with an operation or operations. * * @deprecated since v0.17 */ async patch( operationOrOperations: | RecordOperation | RecordOperation[] | RecordOperationTerm | RecordOperationTerm[] | RecordTransformBuilderFunc ): Promise<PatchResult> { deprecate( 'AsyncRecordCache#patch has been deprecated. Use AsyncRecordCache#update instead.' ); // TODO - Why is this `this` cast necessary for TS to understand the correct // method overload? const { data, details } = await (this as any).update( operationOrOperations, { fullResponse: true } ); return { inverse: details?.inverseOperations || [], data: Array.isArray(data) ? data : [data] }; } liveQuery( queryOrExpressions: QueryOrExpressions<RecordQueryExpression, QB>, options?: DefaultRequestOptions<QO>, id?: string ): AsyncLiveQuery<QO, TO, QB, TB> { const query = buildQuery( queryOrExpressions, options, id, this.queryBuilder ); let debounce = options && (options as any).debounce; if (typeof debounce !== 'boolean') { debounce = this._debounceLiveQueries; } return new AsyncLiveQuery<QO, TO, QB, TB>({ debounce, cache: this, query }); } ///////////////////////////////////////////////////////////////////////////// // Protected methods ///////////////////////////////////////////////////////////////////////////// protected async _query< RequestData extends RecordQueryResult = RecordQueryResult >( query: RecordQuery, // eslint-disable-next-line @typescript-eslint/no-unused-vars options?: QO ): Promise<FullResponse<RequestData, QueryResponseDetails, RecordOperation>> { let data; if (Array.isArray(query.expressions)) { data = []; for (let expression of query.expressions) { const queryOperator = this.getQueryOperator(expression.op); if (!queryOperator) { throw new Error(`Unable to find query operator: ${expression.op}`); } data.push( await queryOperator( this, expression, this.getQueryOptions(query, expression) ) ); } } else { const expression = query.expressions as RecordQueryExpression; const queryOperator = this.getQueryOperator(expression.op); if (!queryOperator) { throw new Error(`Unable to find query operator: ${expression.op}`); } data = await queryOperator( this, expression, this.getQueryOptions(query, expression) ); } return { data: data as RequestData }; } protected async _update< RequestData extends RecordTransformResult = RecordTransformResult >( transform: RecordTransform, options?: TO ): Promise< FullResponse<RequestData, TransformResponseDetails, RecordOperation> > { if (this.getTransformOptions(transform)?.useBuffer) { const buffer = await this._initTransformBuffer(transform); buffer.startTrackingChanges(); const response = buffer.update(transform, { fullResponse: true }); const changes = buffer.stopTrackingChanges(); await this.applyRecordChangesetAsync(changes); const { appliedOperations, appliedOperationResults } = response.details as TransformResponseDetails; for (let i = 0, len = appliedOperations.length; i < len; i++) { this.emit('patch', appliedOperations[i], appliedOperationResults[i]); } return response as FullResponse< RequestData, TransformResponseDetails, RecordOperation >; } else { const response = { data: [] } as FullResponse< RecordOperationResult[], RecordCacheUpdateDetails, RecordOperation >; if (options?.fullResponse) { response.details = { appliedOperations: [], appliedOperationResults: [], inverseOperations: [] }; } let data: RecordTransformResult; if (Array.isArray(transform.operations)) { await this._applyTransformOperations( transform, transform.operations, response, true ); data = response.data; } else { await this._applyTransformOperation( transform, transform.operations, response, true ); if (Array.isArray(response.data)) { data = response.data[0]; } } if (options?.fullResponse) { response.details?.inverseOperations.reverse(); } return { ...response, data } as FullResponse<RequestData, TransformResponseDetails, RecordOperation>; } } protected _getTransformBuffer(): RecordTransformBuffer { if (this._transformBuffer === undefined) { throw new Assertion( 'transformBuffer must be provided to cache via constructor settings' ); } return this._transformBuffer; } protected async _initTransformBuffer( transform: RecordTransform ): Promise<RecordTransformBuffer> { const buffer = this._getTransformBuffer(); const records = recordsReferencedByOperations( toArray(transform.operations) ); const inverseRelationships = await this.getInverseRelationshipsAsync( records ); const relatedRecords = inverseRelationships.map((ir) => ir.record); Array.prototype.push.apply(records, relatedRecords); buffer.resetState(); buffer.setRecordsSync(await this.getRecordsAsync(records)); buffer.addInverseRelationshipsSync(inverseRelationships); return buffer; } protected async _applyTransformOperations( transform: RecordTransform, ops: RecordOperation[] | RecordOperationTerm[], response: FullResponse< RecordOperationResult[], RecordCacheUpdateDetails, RecordOperation >, primary = false ): Promise<void> { for (let op of ops) { await this._applyTransformOperation(transform, op, response, primary); } } protected async _applyTransformOperation( transform: RecordTransform, operation: RecordOperation | RecordOperationTerm, response: FullResponse< RecordOperationResult[], RecordCacheUpdateDetails, RecordOperation >, primary = false ): Promise<void> { if (operation instanceof OperationTerm) { operation = operation.toOperation() as RecordOperation; } for (let processor of this._processors) { await processor.validate(operation); } const inverseTransformOperator = this.getInverseTransformOperator( operation.op ); const inverseOp: | RecordOperation | undefined = await inverseTransformOperator( this, operation, this.getTransformOptions(transform, operation) ); if (inverseOp) { response.details?.inverseOperations?.push(inverseOp); // Query and perform related `before` operations for (let processor of this._processors) { await this._applyTransformOperations( transform, await processor.before(operation), response ); } // Query related `after` operations before performing // the requested operation. These will be applied on success. let preparedOps = []; for (let processor of this._processors) { preparedOps.push(await processor.after(operation)); } // Perform the requested operation let transformOperator = this.getTransformOperator(operation.op); let data = await transformOperator( this, operation, this.getTransformOptions(transform, operation) ); if (primary) { response.data?.push(data); } if (response.details) { response.details.appliedOperationResults.push(data); response.details.appliedOperations.push(operation); } // Query and perform related `immediate` operations for (let processor of this._processors) { await processor.immediate(operation); } // Emit event this.emit('patch', operation, data); // Perform prepared operations after performing the requested operation for (let ops of preparedOps) { await this._applyTransformOperations(transform, ops, response); } // Query and perform related `finally` operations for (let processor of this._processors) { await this._applyTransformOperations( transform, await processor.finally(operation), response ); } } else if (primary) { response.data?.push(undefined); } } }
the_stack
'use strict'; // tslint:disable no-unused-expression import * as vscode from 'vscode'; import { FabricGatewayConnection } from 'ibm-blockchain-platform-gateway-v1'; import { FabricRuntimeUtil, FabricGatewayRegistryEntry } from 'ibm-blockchain-platform-common'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import * as path from 'path'; import { TestUtil } from '../TestUtil'; import { FabricGatewayConnectionManager } from '../../extension/fabric/FabricGatewayConnectionManager'; import { UserInputUtil } from '../../extension/commands/UserInputUtil'; import { BlockchainTreeItem } from '../../extension/explorer/model/BlockchainTreeItem'; import { BlockchainGatewayExplorerProvider } from '../../extension/explorer/gatewayExplorer'; import { ChannelTreeItem } from '../../extension/explorer/model/ChannelTreeItem'; import { ExtensionCommands } from '../../ExtensionCommands'; import { InstantiatedContractTreeItem } from '../../extension/explorer/model/InstantiatedContractTreeItem'; import { ExtensionUtil } from '../../extension/util/ExtensionUtil'; import { InstantiatedTreeItem } from '../../extension/explorer/model/InstantiatedTreeItem'; import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter'; import { FabricGatewayHelper } from '../../extension/fabric/FabricGatewayHelper'; import { LogType } from 'ibm-blockchain-platform-common'; import { TransactionView } from '../../extension/webview/TransactionView'; import ITransaction from '../../extension/interfaces/ITransaction'; import IAssociatedTxData from '../../extension/interfaces/IAssociatedTxData'; import ISmartContract from '../../extension/interfaces/ISmartContract'; import ITxDataFile from '../../extension/interfaces/ITxDataFile'; import { ContractTreeItem } from '../../extension/explorer/model/ContractTreeItem'; chai.use(sinonChai); chai.should(); interface IAppState { gatewayName: string; smartContracts: ISmartContract[]; associatedTxdata: IAssociatedTxData; preselectedSmartContract: ISmartContract; preselectedTransaction: ITransaction; } const transactionOne: ITransaction = { name: 'transactionOne', parameters: [{ description: '', name: 'name', schema: {} }], returns: { type: '' }, tag: ['submit'] }; const transactionTwo: ITransaction = { name: 'transactionTwo', parameters: [], returns: { type: '' }, tag: ['submit'] }; const transactionsInFiles: ITxDataFile[] = [ { transactionName: transactionOne.name, transactionLabel: transactionOne.name, arguments: [], transientData: {}, txDataFile: 'file.txdata', }, { transactionName: transactionTwo.name, transactionLabel: transactionTwo.name, arguments: [], transientData: {}, txDataFile: 'file2.txdata', } ]; describe('OpenTransactionViewCommand', () => { let mySandBox: sinon.SinonSandbox = sinon.createSandbox(); let instantiatedSmartContract: InstantiatedContractTreeItem; let fabricClientConnectionMock: sinon.SinonStubbedInstance<FabricGatewayConnection>; let executeCommandStub: sinon.SinonStub; let getConnectionStub: sinon.SinonStub; let showInstantiatedSmartContractQuickPickStub: sinon.SinonStub; let showChannelFromGatewayQuickPickBoxStub: sinon.SinonStub; let fabricConnectionManager: FabricGatewayConnectionManager; let logSpy: sinon.SinonSpy; let gatewayRegistryEntry: FabricGatewayRegistryEntry; let getGatewayRegistryStub: sinon.SinonStub; let openViewStub: sinon.SinonStub; before(async () => { await TestUtil.setupTests(mySandBox); }); describe('OpenTransactionView', () => { beforeEach(async () => { mySandBox = sinon.createSandbox(); logSpy = mySandBox.spy(VSCodeBlockchainOutputAdapter.instance(), 'log'); executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand'); executeCommandStub.callThrough(); executeCommandStub.withArgs(ExtensionCommands.CONNECT_TO_GATEWAY).resolves(); fabricClientConnectionMock = mySandBox.createStubInstance(FabricGatewayConnection); fabricClientConnectionMock.connect.resolves(); const map: Map<string, Array<string>> = new Map<string, Array<string>>(); map.set('myChannel', ['peerOne']); map.set('otherChannel', ['otherPeer']); fabricClientConnectionMock.createChannelMap.resolves(map); fabricClientConnectionMock.getChannelCapabilityFromPeer.resolves([UserInputUtil.V2_0]); fabricConnectionManager = FabricGatewayConnectionManager.instance(); getConnectionStub = mySandBox.stub(fabricConnectionManager, 'getConnection').returns(fabricClientConnectionMock); gatewayRegistryEntry = new FabricGatewayRegistryEntry(); gatewayRegistryEntry.name = 'myGateway'; getGatewayRegistryStub = mySandBox.stub(fabricConnectionManager, 'getGatewayRegistryEntry'); getGatewayRegistryStub.resolves(gatewayRegistryEntry); mySandBox.stub(FabricGatewayHelper, 'getConnectionProfilePath').resolves(path.join('myPath', 'connection.json')); fabricClientConnectionMock.getAllPeerNames.returns(['peerOne']); fabricClientConnectionMock.getAllChannelsForPeer.withArgs('peerOne').resolves(['myChannel']); fabricClientConnectionMock.getChannelPeersInfo.resolves([{ name: 'peerOne', mspID: 'org1msp' }, { name: 'peerTwo', mspID: 'org1msp' }]); fabricClientConnectionMock.getInstantiatedChaincode.resolves([{ name: 'mySmartContract', version: '0.0.1' }]); fabricClientConnectionMock.getMetadata.resolves( { contracts: { 'my-contract': { name: 'my-contract', transactions: [ transactionOne, transactionTwo, ], }, 'org.hyperledger.fabric': { name: 'org.hyperledger.fabric', transactions: [ { name: 'GetMetadata' } ] } } } ); fabricClientConnectionMock.getMetadata.withArgs('MultiContract', sinon.match.any).resolves( { contracts: { 'my-contract': { name: 'my-contract', transactions: [ transactionOne, transactionTwo, ], }, 'my-contract-2': { name: 'my-contract-2', transactions: [ transactionOne, ], } } } ); showChannelFromGatewayQuickPickBoxStub = mySandBox.stub(UserInputUtil, 'showChannelFromGatewayQuickPickBox'); showChannelFromGatewayQuickPickBoxStub.resolves({label: 'myChannel'}); showInstantiatedSmartContractQuickPickStub = mySandBox.stub(UserInputUtil, 'showClientInstantiatedSmartContractsQuickPick'); showInstantiatedSmartContractQuickPickStub.resolves({ label: 'myContract', data: { name: 'myContract', channel: 'myChannel', version: '0.0.1' } }); openViewStub = mySandBox.stub(TransactionView.prototype, 'openView').resolves(); mySandBox.stub(TransactionView, 'readTxdataFiles').resolves(transactionsInFiles); }); afterEach(async () => { mySandBox.restore(); }); it('should open the transaction web view through the tree', async () => { const blockchainGatewayExplorerProvider: BlockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider(); const allChildren: BlockchainTreeItem[] = await blockchainGatewayExplorerProvider.getChildren(); const channels: Array<ChannelTreeItem> = await blockchainGatewayExplorerProvider.getChildren(allChildren[2]) as Array<ChannelTreeItem>; const contracts: Array<InstantiatedTreeItem> = await blockchainGatewayExplorerProvider.getChildren(channels[0]) as Array<InstantiatedTreeItem>; instantiatedSmartContract = contracts[0]; const appstate: IAppState = await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE, instantiatedSmartContract); const smartContract: ISmartContract = { channel: 'myChannel', label: 'mySmartContract@0.0.1', name: 'mySmartContract', namespace: 'my-contract', contractName: 'my-contract', peerNames: ['peerOne', 'peerTwo'], version: '0.0.1', transactions: [ transactionOne, transactionTwo, ], }; const want: IAppState = { associatedTxdata: {}, gatewayName: 'myGateway', smartContracts: [smartContract], preselectedSmartContract: smartContract, preselectedTransaction: undefined, }; appstate.should.deep.equal(want); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); openViewStub.should.have.been.calledOnce; }); it('should open the transaction web view through the tree and handle set the preselectedTransaction when passed in', async () => { const blockchainGatewayExplorerProvider: BlockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider(); const allChildren: BlockchainTreeItem[] = await blockchainGatewayExplorerProvider.getChildren(); const channels: Array<ChannelTreeItem> = await blockchainGatewayExplorerProvider.getChildren(allChildren[2]) as Array<ChannelTreeItem>; const contracts: Array<InstantiatedTreeItem> = await blockchainGatewayExplorerProvider.getChildren(channels[0]) as Array<InstantiatedTreeItem>; instantiatedSmartContract = contracts[0]; const appstate: IAppState = await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE, instantiatedSmartContract, 'transactionOne'); const smartContract: ISmartContract = { channel: 'myChannel', label: 'mySmartContract@0.0.1', name: 'mySmartContract', namespace: 'my-contract', contractName: 'my-contract', peerNames: ['peerOne', 'peerTwo'], version: '0.0.1', transactions: [ transactionOne, transactionTwo, ], }; const want: IAppState = { associatedTxdata: {}, gatewayName: 'myGateway', smartContracts: [smartContract], preselectedSmartContract: smartContract, preselectedTransaction: transactionOne, }; appstate.should.deep.equal(want); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); openViewStub.should.have.been.calledOnce; }); it('should open the transaction web view through the tree and handle when the preselectedTransaction does not exist', async () => { const blockchainGatewayExplorerProvider: BlockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider(); const allChildren: BlockchainTreeItem[] = await blockchainGatewayExplorerProvider.getChildren(); const channels: Array<ChannelTreeItem> = await blockchainGatewayExplorerProvider.getChildren(allChildren[2]) as Array<ChannelTreeItem>; const contracts: Array<InstantiatedTreeItem> = await blockchainGatewayExplorerProvider.getChildren(channels[0]) as Array<InstantiatedTreeItem>; instantiatedSmartContract = contracts[0]; const appstate: IAppState = await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE, instantiatedSmartContract, 'does not exist'); const smartContract: ISmartContract = { channel: 'myChannel', label: 'mySmartContract@0.0.1', name: 'mySmartContract', namespace: 'my-contract', contractName: 'my-contract', peerNames: ['peerOne', 'peerTwo'], version: '0.0.1', transactions: [ transactionOne, transactionTwo, ], }; const want: IAppState = { associatedTxdata: {}, gatewayName: 'myGateway', smartContracts: [smartContract], preselectedSmartContract: smartContract, preselectedTransaction: undefined, }; appstate.should.deep.equal(want); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); openViewStub.should.have.been.calledOnce; }); it('should open the transaction web view through the tree when the chaincode contains multiple contracts and make the correct transaction active', async () => { const blockchainGatewayExplorerProvider: BlockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider(); const allChildren: BlockchainTreeItem[] = await blockchainGatewayExplorerProvider.getChildren(); const channels: Array<ChannelTreeItem> = await blockchainGatewayExplorerProvider.getChildren(allChildren[2]) as Array<ChannelTreeItem>; fabricClientConnectionMock.getInstantiatedChaincode.resolves([{ name: 'MultiContract', version: '0.0.1' }]); const chainCodeElement: any = { channels, collapsibleState: 1, contextValue: 'blockchain-instantiated-multi-contract-item', contracts: ['my-contract', 'my-contract-2'], iconPath: {light: '', dark: ''}, label: 'MultiContract@0.0.1', name: 'MultiContract', provider: blockchainGatewayExplorerProvider, showIcon: true, tooltip: '', version: '0.0.1', }; const treeItem: any = new ContractTreeItem(blockchainGatewayExplorerProvider, 'my-contract-2', 1, chainCodeElement, [transactionOne.name, transactionTwo.name], chainCodeElement.channels[0].label); const appstate: IAppState = await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE, treeItem, transactionOne.name); const smartContract: ISmartContract = { channel: 'myChannel', label: 'MultiContract@0.0.1', name: 'MultiContract', namespace: 'my-contract', contractName: 'my-contract', peerNames: ['peerOne', 'peerTwo'], version: '0.0.1', transactions: [ transactionOne, transactionTwo, ], }; const smartContract2: ISmartContract = { ...smartContract, namespace: 'my-contract-2', contractName: 'my-contract-2', transactions: [ transactionOne, ] }; const want: IAppState = { associatedTxdata: {}, gatewayName: 'myGateway', smartContracts: [smartContract, smartContract2], preselectedSmartContract: smartContract2, preselectedTransaction: transactionOne, }; appstate.should.deep.equal(want); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); openViewStub.should.have.been.calledOnce; }); it('should open the transaction web view for a contract without metadata', async () => { const blockchainGatewayExplorerProvider: BlockchainGatewayExplorerProvider = ExtensionUtil.getBlockchainGatewayExplorerProvider(); const allChildren: BlockchainTreeItem[] = await blockchainGatewayExplorerProvider.getChildren(); const channels: Array<ChannelTreeItem> = await blockchainGatewayExplorerProvider.getChildren(allChildren[2]) as Array<ChannelTreeItem>; const contracts: Array<InstantiatedTreeItem> = await blockchainGatewayExplorerProvider.getChildren(channels[0]) as Array<InstantiatedTreeItem>; fabricClientConnectionMock.getInstantiatedChaincode.resolves([{ name: 'mySmartContract', version: '0.0.1' }, { name: 'mySmartContract2', version: '0.0.2' }]); instantiatedSmartContract = contracts[0]; fabricClientConnectionMock.getMetadata.rejects('Transaction function "org.hyperledger.fabric:GetMetadata" did not return any metadata'); const appstate: IAppState = await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE, instantiatedSmartContract); const smartContract: ISmartContract = { channel: 'myChannel', label: 'mySmartContract@0.0.1', name: 'mySmartContract', contractName: undefined, namespace: undefined, peerNames: ['peerOne', 'peerTwo'], version: '0.0.1', transactions: [] }; const want: IAppState = { associatedTxdata: {}, gatewayName: 'myGateway', smartContracts: [smartContract], preselectedSmartContract: smartContract, preselectedTransaction: undefined, }; appstate.should.deep.equal(want); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); openViewStub.should.have.been.calledOnce; }); it('should open the transaction web view through the command', async () => { const appstate: IAppState = await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE); const want: IAppState = { associatedTxdata: {}, gatewayName: 'myGateway', smartContracts: [], preselectedSmartContract: undefined, preselectedTransaction: undefined, }; appstate.should.deep.equal(want); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); showInstantiatedSmartContractQuickPickStub.should.have.been.calledOnce; openViewStub.should.have.been.calledOnce; }); it('should open the transaction web view through the command', async () => { const chaincode: { chaincodeName: string, channelName: string, transactionDataPath: string } = { chaincodeName: 'mySmartContract', channelName: 'myChannel', transactionDataPath: '/directory', }; showInstantiatedSmartContractQuickPickStub.resolves({ label: 'mySmartContract', data: { name: 'mySmartContract', channel: 'myChannel', version: '0.0.1' } }); getGatewayRegistryStub.resolves({ ...gatewayRegistryEntry, transactionDataDirectories: [chaincode], }); const appstate: IAppState = await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE); const associatedTxdata: IAssociatedTxData = { [chaincode.chaincodeName]: { channelName: chaincode.channelName, transactionDataPath: chaincode.transactionDataPath, transactions: transactionsInFiles, } }; const smartContract: ISmartContract = { channel: 'myChannel', label: 'mySmartContract@0.0.1', name: 'mySmartContract', namespace: 'my-contract', contractName: 'my-contract', peerNames: ['peerOne', 'peerTwo'], version: '0.0.1', transactions: [ transactionOne, transactionTwo, ], }; const want: IAppState = { associatedTxdata, gatewayName: 'myGateway', smartContracts: [smartContract], preselectedSmartContract: undefined, preselectedTransaction: undefined, }; appstate.should.deep.equal(want); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); showInstantiatedSmartContractQuickPickStub.should.have.been.calledOnce; openViewStub.should.have.been.calledOnce; }); it(`should correctly display the ${FabricRuntimeUtil.LOCAL_FABRIC} gateway name`, async () => { const localGatewayRegistryEntry: FabricGatewayRegistryEntry = new FabricGatewayRegistryEntry(); localGatewayRegistryEntry.name = `${FabricRuntimeUtil.LOCAL_FABRIC} - Org1`; localGatewayRegistryEntry.displayName = `Org1`; getGatewayRegistryStub.resolves(localGatewayRegistryEntry); await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); showInstantiatedSmartContractQuickPickStub.should.have.been.calledOnce; openViewStub.should.have.been.calledOnce; }); it('should open the transaction web view through the command when not connected', async () => { getConnectionStub.onCall(0).returns(null); await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_GATEWAY); showInstantiatedSmartContractQuickPickStub.should.have.been.calledOnce; openViewStub.should.have.been.calledOnce; }); it('should handle cancellation when connecting to a gateway', async () => { getConnectionStub.onCall(0).returns(null); getConnectionStub.onCall(1).returns(null); await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_GATEWAY); showInstantiatedSmartContractQuickPickStub.should.not.have.been.called; openViewStub.should.not.have.been.called; }); it('should handle cancellation when choosing a channel', async () => { showChannelFromGatewayQuickPickBoxStub.resolves(); await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); showChannelFromGatewayQuickPickBoxStub.should.have.been.calledOnce; showInstantiatedSmartContractQuickPickStub.should.have.not.been.called; openViewStub.should.not.have.been.called; }); it('should handle cancellation when choosing a smart contract', async () => { showInstantiatedSmartContractQuickPickStub.resolves(); await vscode.commands.executeCommand(ExtensionCommands.OPEN_TRANSACTION_PAGE); logSpy.should.have.been.calledWith(LogType.INFO, undefined, `Open Transaction View`); showInstantiatedSmartContractQuickPickStub.should.have.been.calledOnce; openViewStub.should.not.have.been.called; }); }); });
the_stack
import {Table, TableExpiresSettings, TableUpdateOptions, TableWaitForActiveSettings} from "."; import Internal from "../Internal"; const {internalProperties} = Internal.General; import * as DynamoDB from "@aws-sdk/client-dynamodb"; import ddb from "../aws/ddb/internal"; import utils from "../utils"; import CustomError from "../Error"; import {TableIndexChangeType} from "../utils/dynamoose/index_changes"; import {TableClass} from "./types"; // Utility functions export async function getTableDetails (table: Table, settings: {allowError?: boolean; forceRefresh?: boolean} = {}): Promise<DynamoDB.DescribeTableOutput> { const func = async (): Promise<void> => { const tableDetails: DynamoDB.DescribeTableOutput = await ddb(table.getInternalProperties(internalProperties).instance, "describeTable", {"TableName": table.getInternalProperties(internalProperties).name}); table.getInternalProperties(internalProperties).latestTableDetails = tableDetails; // eslint-disable-line require-atomic-updates }; if (settings.forceRefresh || !table.getInternalProperties(internalProperties).latestTableDetails) { if (settings.allowError) { try { await func(); } catch (e) {} // eslint-disable-line no-empty } else { await func(); } } return table.getInternalProperties(internalProperties).latestTableDetails; } function getExpectedTags (table: Table): DynamoDB.Tag[] | undefined { const tagEntries: [string, string][] = Object.entries(table.getInternalProperties(internalProperties).options.tags); if (tagEntries.length === 0) { return undefined; } else { return tagEntries.map(([Key, Value]) => ({ Key, Value })); } } export async function getTagDetails (table: Table): Promise<DynamoDB.ListTagsOfResourceOutput> { const tableDetails = await getTableDetails(table); const instance = table.getInternalProperties(internalProperties).instance; const tags: DynamoDB.ListTagsOfResourceOutput = await ddb(instance, "listTagsOfResource", { "ResourceArn": tableDetails.Table.TableArn }); while (tags.NextToken) { // TODO: The timeout below causes tests to fail, so we disable it for now. We should also probably only run a timeout if we get an error from AWS. // await timeout(100); // You can call ListTagsOfResource up to 10 times per second, per account. const nextTags = await ddb(instance, "listTagsOfResource", { "ResourceArn": tableDetails.Table.TableArn, "NextToken": tags.NextToken }); tags.NextToken = nextTags.NextToken; tags.Tags = [...tags.Tags, ...nextTags.Tags]; } return tags; } export async function createTableRequest (table: Table): Promise<DynamoDB.CreateTableInput> { const object: DynamoDB.CreateTableInput = { "TableName": table.getInternalProperties(internalProperties).name, ...utils.dynamoose.get_provisioned_throughput(table.getInternalProperties(internalProperties).options), ...await table.getInternalProperties(internalProperties).getCreateTableAttributeParams() }; if (table.getInternalProperties(internalProperties).options.tableClass === TableClass.infrequentAccess) { object.TableClass = DynamoDB.TableClass.STANDARD_INFREQUENT_ACCESS; } const tags = getExpectedTags(table); if (tags) { object.Tags = tags; } return object; } // Setting `force` to true will create the table even if the table is already believed to be active export function createTable (table: Table): Promise<void | (() => Promise<void>)>; export function createTable (table: Table, force: true): Promise<void>; export function createTable (table: Table, force: false): Promise<void | (() => Promise<void>)>; export async function createTable (table: Table, force = false): Promise<void | (() => Promise<void>)> { if (!force && ((await getTableDetails(table, {"allowError": true}) || {}).Table || {}).TableStatus === "ACTIVE") { table.getInternalProperties(internalProperties).alreadyCreated = true; return (): Promise<void> => Promise.resolve.bind(Promise)(); } await ddb(table.getInternalProperties(internalProperties).instance, "createTable", await createTableRequest(table)); } export async function updateTimeToLive (table: Table): Promise<void> { let ttlDetails; const instance = table.getInternalProperties(internalProperties).instance; async function updateDetails (): Promise<void> { ttlDetails = await ddb(instance, "describeTimeToLive", { "TableName": table.getInternalProperties(internalProperties).name }); } await updateDetails(); function updateTTL (): Promise<DynamoDB.UpdateTimeToLiveOutput> { return ddb(instance, "updateTimeToLive", { "TableName": table.getInternalProperties(internalProperties).name, "TimeToLiveSpecification": { "AttributeName": (table.getInternalProperties(internalProperties).options.expires as TableExpiresSettings).attribute, "Enabled": true } }); } switch (ttlDetails.TimeToLiveDescription.TimeToLiveStatus) { case "DISABLING": while (ttlDetails.TimeToLiveDescription.TimeToLiveStatus === "DISABLING") { await utils.timeout(1000); await updateDetails(); } // fallthrough case "DISABLED": await updateTTL(); break; /* istanbul ignore next */ default: break; } } export function waitForActive (table: Table, forceRefreshOnFirstAttempt = true) { return (): Promise<void> => new Promise((resolve, reject) => { const start = Date.now(); async function check (count: number): Promise<void> { if (typeof table.getInternalProperties(internalProperties).options.waitForActive !== "boolean") { try { // Normally we'd want to do `dynamodb.waitFor` here, but since it doesn't work with tables that are being updated we can't use it in this case const tableDetails = (await getTableDetails(table, {"forceRefresh": forceRefreshOnFirstAttempt === true ? forceRefreshOnFirstAttempt : count > 0})).Table; if (tableDetails.TableStatus === "ACTIVE" && (tableDetails.GlobalSecondaryIndexes ?? []).every((val) => val.IndexStatus === "ACTIVE")) { return resolve(); } } catch (e) { return reject(e); } if (count > 0) { (table.getInternalProperties(internalProperties).options.waitForActive as TableWaitForActiveSettings).check.frequency === 0 ? await utils.set_immediate_promise() : await utils.timeout((table.getInternalProperties(internalProperties).options.waitForActive as TableWaitForActiveSettings).check.frequency); } if (Date.now() - start >= (table.getInternalProperties(internalProperties).options.waitForActive as TableWaitForActiveSettings).check.timeout) { return reject(new CustomError.WaitForActiveTimeout(`Wait for active timed out after ${Date.now() - start} milliseconds.`)); } else { check(++count); } } } check(0); }); } export async function updateTable (table: Table): Promise<void> { const updateAll = typeof table.getInternalProperties(internalProperties).options.update === "boolean" && table.getInternalProperties(internalProperties).options.update; const instance = table.getInternalProperties(internalProperties).instance; // Throughput if (updateAll || (table.getInternalProperties(internalProperties).options.update as TableUpdateOptions[]).includes(TableUpdateOptions.throughput)) { const currentThroughput = (await getTableDetails(table)).Table; const expectedThroughput: any = utils.dynamoose.get_provisioned_throughput(table.getInternalProperties(internalProperties).options); const isThroughputUpToDate = expectedThroughput.BillingMode === (currentThroughput.BillingModeSummary || {}).BillingMode && expectedThroughput.BillingMode || (currentThroughput.ProvisionedThroughput || {}).ReadCapacityUnits === (expectedThroughput.ProvisionedThroughput || {}).ReadCapacityUnits && currentThroughput.ProvisionedThroughput.WriteCapacityUnits === expectedThroughput.ProvisionedThroughput.WriteCapacityUnits; if (!isThroughputUpToDate) { const object: DynamoDB.UpdateTableInput = { "TableName": table.getInternalProperties(internalProperties).name, ...expectedThroughput }; await ddb(instance, "updateTable", object); await waitForActive(table)(); } } // Indexes if (updateAll || (table.getInternalProperties(internalProperties).options.update as TableUpdateOptions[]).includes(TableUpdateOptions.indexes)) { const tableDetails = await getTableDetails(table); const existingIndexes = tableDetails.Table.GlobalSecondaryIndexes; const updateIndexes = await utils.dynamoose.index_changes(table, existingIndexes); await updateIndexes.reduce(async (existingFlow, index) => { await existingFlow; const params: DynamoDB.UpdateTableInput = { "TableName": table.getInternalProperties(internalProperties).name }; if (index.type === TableIndexChangeType.add) { params.AttributeDefinitions = (await table.getInternalProperties(internalProperties).getCreateTableAttributeParams()).AttributeDefinitions; params.GlobalSecondaryIndexUpdates = [{"Create": index.spec}]; } else { params.GlobalSecondaryIndexUpdates = [{"Delete": {"IndexName": index.name}}]; } await ddb(instance, "updateTable", params); await waitForActive(table)(); }, Promise.resolve()); } // Tags if (updateAll || (table.getInternalProperties(internalProperties).options.update as TableUpdateOptions[]).includes(TableUpdateOptions.tags)) { const currentTags = (await getTagDetails(table)).Tags; const expectedTags: {[key: string]: string} = table.getInternalProperties(internalProperties).options.tags; let tableDetails: DynamoDB.DescribeTableOutput; const tagsToDelete = currentTags.filter((tag) => expectedTags[tag.Key] !== tag.Value).map((tag) => tag.Key); if (tagsToDelete.length > 0) { tableDetails = await getTableDetails(table); await ddb(instance, "untagResource", { "ResourceArn": tableDetails.Table.TableArn, "TagKeys": tagsToDelete }); } const tagsToAdd = Object.keys(expectedTags).filter((key) => tagsToDelete.includes(key) || !currentTags.some((tag) => tag.Key === key)); if (tagsToAdd.length > 0) { tableDetails = tableDetails || await getTableDetails(table); await ddb(instance, "tagResource", { "ResourceArn": tableDetails.Table.TableArn, "Tags": tagsToAdd.map((key) => ({ "Key": key, "Value": expectedTags[key] })) }); } } // Table Class if (updateAll || (table.getInternalProperties(internalProperties).options.update as TableUpdateOptions[]).includes(TableUpdateOptions.tableClass)) { const tableDetails = (await getTableDetails(table)).Table; const expectedDynamoDBTableClass = table.getInternalProperties(internalProperties).options.tableClass === TableClass.infrequentAccess ? DynamoDB.TableClass.STANDARD_INFREQUENT_ACCESS : DynamoDB.TableClass.STANDARD; if (!tableDetails.TableClassSummary && expectedDynamoDBTableClass !== DynamoDB.TableClass.STANDARD || tableDetails.TableClassSummary && tableDetails.TableClassSummary.TableClass !== expectedDynamoDBTableClass) { const object: DynamoDB.UpdateTableInput = { "TableName": table.getInternalProperties(internalProperties).name, "TableClass": expectedDynamoDBTableClass }; await ddb(instance, "updateTable", object); await waitForActive(table)(); } } }
the_stack
import dayjs from 'dayjs'; import { AnyFactorType, ComputedParameter, ConstantParameter, Parameter, ParameterComputeType, ParameterExpression, ParameterExpressionOperator, ParameterInvalidReason, ParameterJoint, TopicFactorParameter, ValueType, ValueTypes } from './factor-calculator-types'; import { computeValidTypesByExpressionOperator, computeValidTypesForSubParameter, isComputeTypeValid, isFactorTypeCompatibleWith } from './factor-calculator-utils'; import {FactorType} from './factor-types'; import { isComputedParameter, isConstantParameter, isExpressionParameter, isJointParameter, isTopicFactorParameter, ParameterCalculatorDefsMap } from './parameter-utils'; import {Topic} from './topic-types'; export const isJointValid4DataSet = (options: { joint: ParameterJoint; topics: Array<Topic>; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {joint, topics, reasons} = options; const {jointType, filters} = joint; if (!jointType) { reasons(ParameterInvalidReason.JOINT_TYPE_NOT_DEFINED); return false; } if (!filters || filters.length === 0) { reasons(ParameterInvalidReason.JOINT_FILTERS_NOT_DEFINED); return false; } return !filters.some(filter => { if (isJointParameter(filter)) { return !isJointValid4DataSet({joint: filter, topics, reasons}); } else if (isExpressionParameter(filter)) { return !isExpressionValid4DataSet({expression: filter, topics, reasons}); } return true; }); }; export const isExpressionValid4DataSet = (options: { expression: ParameterExpression; topics: Array<Topic>; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {expression, topics, reasons} = options; const {left, operator, right} = expression; if (!operator) { reasons(ParameterInvalidReason.EXPRESSION_OPERATOR_NOT_DEFINED); return false; } const expectedTypes = computeValidTypesByExpressionOperator(operator); if (!left) { reasons(ParameterInvalidReason.EXPRESSION_LEFT_NOT_DEFINED); return false; } if (!isParameterValid4DataSet({parameter: left, topics, expectedTypes, array: false, reasons})) { return false; } if (operator !== ParameterExpressionOperator.NOT_EMPTY && operator !== ParameterExpressionOperator.EMPTY) { const array = operator === ParameterExpressionOperator.IN || operator === ParameterExpressionOperator.NOT_IN; if (!right) { reasons(ParameterInvalidReason.EXPRESSION_RIGHT_NOT_DEFINED); return false; } if (!isParameterValid4DataSet({parameter: right, topics, expectedTypes, array, reasons})) { return false; } } return true; }; export const isParameterValid4DataSet = (options: { parameter: Parameter; topics: Array<Topic>; expectedTypes: ValueTypes; array?: boolean; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {parameter, topics, expectedTypes, array = false, reasons} = options; if (!parameter) { reasons(ParameterInvalidReason.PARAMETER_NOT_DEFINED); return false; } if (isTopicFactorParameter(parameter)) { if (array) { reasons(ParameterInvalidReason.FACTOR_TYPE_NOT_MATCHED); return false; } else { return isTopicFactorParameterValid({parameter, topics, expectedTypes, reasons}); } } else if (isConstantParameter(parameter)) { return isConstantParameterValid({parameter, expectedTypes, array, reasons}); } else if (isComputedParameter(parameter)) { return isComputedParameterValid({parameter, topics, expectedTypes, array, reasons}); } else { return false; } }; const isValueValid = (value: string, type: ValueType): boolean => { switch (type) { // always matched case FactorType.TEXT: case FactorType.ADDRESS: case FactorType.DISTRICT: case FactorType.ROAD: case FactorType.COMMUNITY: case FactorType.EMAIL: case FactorType.PHONE: case FactorType.MOBILE: case FactorType.FAX: case FactorType.ID_NO: return true; // always mismatched case FactorType.OBJECT: case FactorType.ARRAY: case FactorType.SEQUENCE: // sequence factor never occurs in any expression/filter return false; // enum case FactorType.ENUM: case FactorType.CONTINENT: case FactorType.REGION: case FactorType.COUNTRY: case FactorType.PROVINCE: case FactorType.CITY: case FactorType.RESIDENCE_TYPE: return true; case FactorType.HALF_YEAR: case FactorType.HALF_MONTH: // eslint-disable-next-line return value == '1' || value == '2'; case FactorType.QUARTER: // eslint-disable-next-line return value == '1' || value == '2' || value == '3' || value == '4'; case FactorType.TEN_DAYS: // eslint-disable-next-line return value == '1' || value == '2' || value == '3'; case FactorType.WEEK_OF_YEAR: // eslint-disable-next-line return value == '1' || value == '2' || value == '3'; case FactorType.WEEK_OF_MONTH: // eslint-disable-next-line return value == '0' || value == '1' || value == '2' || value == '3' || value == '4' || value == '5'; case FactorType.HALF_WEEK: // eslint-disable-next-line return value == '1' || value == '2'; case FactorType.DAY_OF_WEEK: // eslint-disable-next-line return value == '1' || value == '2' || value == '3' || value == '4' || value == '5' || value == '6' || value == '7'; case FactorType.DAY_KIND: // eslint-disable-next-line return value == '1' || value == '2' || value == '3'; case FactorType.HOUR_KIND: // eslint-disable-next-line return value == '1' || value == '2' || value == '3'; case FactorType.AM_PM: // eslint-disable-next-line return value == '1' || value == '2'; case FactorType.GENDER: case FactorType.OCCUPATION: case FactorType.RELIGION: case FactorType.NATIONALITY: case FactorType.BIZ_TRADE: return true; // numeric case FactorType.NUMBER: case FactorType.FLOOR: return /^-?\d+(\.\d+)?$/.test(value); case FactorType.UNSIGNED: case FactorType.AGE: case FactorType.RESIDENTIAL_AREA: case FactorType.BIZ_SCALE: return /^\d+(\.\d+)?$/.test(value); case FactorType.YEAR: return /^\d{4}$/.test(value); case FactorType.MONTH: return /^(10|11|12|0?[1-9])$/.test(value); case FactorType.DAY_OF_MONTH: return /^([0-2]?[1-9]|10|20|30|31)$/.test(value); case FactorType.HOUR: return /^([0-1]?[1-9]|10|20|21|22|23)$/.test(value); case FactorType.MINUTE: case FactorType.SECOND: return /^[0-5]?[0-9]$/.test(value); case FactorType.MILLISECOND: return /^\d{1,3}$/.test(value); // datetime case FactorType.DATE: case FactorType.DATE_OF_BIRTH: return !!value && !!dayjs(value, ['YYYY/MM/DD', 'YYYY-MM-DD'], true); case FactorType.TIME: return !!value && !!dayjs(value, 'HH:mm:ss', true); case FactorType.DATETIME: return !!value && !!dayjs(value, ['YYYY/MM/DD HH:mm:ss', 'YYYY-MM-DD HH:mm:ss'], true); case FactorType.FULL_DATETIME: return !!value && !!dayjs(value, ['YYYY/MM/DD HH:mm:ss.SSS', 'YYYY-MM-DD HH:mm:ss.SSS'], true); // boolean case FactorType.BOOLEAN: return ['true', 'false'].includes(value.toLowerCase()); default: // never occurs return true; } }; /** * constant parameter in dataset-and-palette doesn't support {} syntax, just check value */ const isConstantParameterValid = (options: { parameter: ConstantParameter; expectedTypes: ValueTypes; array: boolean; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {parameter, expectedTypes, array, reasons} = options; const value = (parameter.value || '').trim(); if (/^.*{.+}.*$/.test(value)) { return true; } let check = (type: ValueType) => isValueValid(value, type); if (array) { const values = value.split(',').map(x => x.trim()); check = (type: ValueType) => values.every(value => isValueValid(value, type)); } const passed = expectedTypes.some(expectedType => expectedType === AnyFactorType.ANY || check(expectedType)); if (!passed) { reasons(ParameterInvalidReason.CONSTANT_TYPE_NOT_MATCHED); } return passed; }; const isTopicFactorParameterValid = (options: { parameter: TopicFactorParameter; topics: Array<Topic>; expectedTypes: ValueTypes; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {parameter, topics, expectedTypes, reasons} = options; if (!parameter.topicId) { // no topic, failure reasons(ParameterInvalidReason.TOPIC_NOT_DEFINED); return false; } if (!parameter.factorId) { // no factor, failure reasons(ParameterInvalidReason.FACTOR_NOT_DEFINED); return false; } // eslint-disable-next-line const topic = topics.find(topic => topic.topicId == parameter.topicId); if (!topic) { // topic not found, failure reasons(ParameterInvalidReason.TOPIC_NOT_FOUND); return false; } // eslint-disable-next-line const factor = topic.factors.find(factor => factor.factorId == parameter.factorId); if (!factor) { // factor not found, failure reasons(ParameterInvalidReason.FACTOR_NOT_FOUND); return false; } return isFactorTypeCompatibleWith({factorType: factor.type, expectedTypes, reasons}); }; const isComputedParameterValid = (options: { parameter: ComputedParameter; topics: Array<Topic>; expectedTypes: ValueTypes; array: boolean; reasons: (reason: ParameterInvalidReason) => void; }): boolean => { const {parameter, topics, expectedTypes, array, reasons} = options; const {type: computeType, parameters} = parameter; if (!computeType) { // type must exists return false; } const calculatorDef = ParameterCalculatorDefsMap[computeType]; // no calculator if (calculatorDef.parameterCount && parameters.length !== calculatorDef.parameterCount) { // parameters length mismatch reasons(ParameterInvalidReason.COMPUTE_PARAMETER_COUNT_NOT_MATCHED); return false; } if (calculatorDef.minParameterCount && parameters.length < calculatorDef.minParameterCount) { // parameters length mismatch reasons(ParameterInvalidReason.COMPUTE_PARAMETER_COUNT_NOT_MATCHED); return false; } if (calculatorDef.maxParameterCount && parameters.length > calculatorDef.maxParameterCount) { // parameters length mismatch reasons(ParameterInvalidReason.COMPUTE_PARAMETER_COUNT_NOT_MATCHED); return false; } const hasEmptyParameter = parameters.some(param => !param); if (hasEmptyParameter) { reasons(ParameterInvalidReason.COMPUTE_PARAMETER_HAS_NOT_DEFINED); return false; } if (array && computeType !== ParameterComputeType.CASE_THEN) { // only case-then can produce array result reasons(ParameterInvalidReason.COMPUTE_RETURN_TYPE_NOT_MATCHED); return false; } if (!isComputeTypeValid({computeType, expectedTypes, reasons})) { return false; } const subTypes = computeValidTypesForSubParameter(computeType, expectedTypes); return parameters.every(parameter => { return isParameterValid4DataSet({parameter, topics, expectedTypes: subTypes, array, reasons}); }); };
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace baremetalsolution_v2 { export interface Options extends GlobalOptions { version: 'v2'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * Bare Metal Solution API * * Provides ways to manage Bare Metal Solution hardware installed in a regional extension located near a Google Cloud data center. * * @example * ```js * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * ``` */ export class Baremetalsolution { context: APIRequestContext; projects: Resource$Projects; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.projects = new Resource$Projects(this.context); } } /** * Represents an 'access point' for the share. */ export interface Schema$AllowedClient { /** * Allow dev flag. Which controls whether to allow creation of devices. */ allowDev?: boolean | null; /** * The subnet of IP addresses permitted to access the share. */ allowedClientsCidr?: string | null; /** * Allow the setuid flag. */ allowSuid?: boolean | null; /** * Mount permissions. */ mountPermissions?: string | null; /** * The network the access point sits on. */ network?: string | null; /** * Disable root squashing, which is a feature of NFS. Root squash is a special mapping of the remote superuser (root) identity when using identity authentication. */ noRootSquash?: boolean | null; /** * The IP address of the share on this network. */ shareIp?: string | null; } /** * A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); \} */ export interface Schema$Empty {} /** * Response with all provisioning settings. */ export interface Schema$FetchInstanceProvisioningSettingsResponse { /** * The OS images available. */ images?: Schema$OSImage[]; } /** * A server. */ export interface Schema$Instance { /** * Output only. Create a time stamp. */ createTime?: string | null; /** * True if you enable hyperthreading for the server, otherwise false. The default value is false. */ hyperthreadingEnabled?: boolean | null; /** * An identifier for the `Instance`, generated by the backend. */ id?: string | null; /** * True if the interactive serial console feature is enabled for the instance, false otherwise. The default value is false. */ interactiveSerialConsoleEnabled?: boolean | null; /** * Labels as key value pairs. */ labels?: {[key: string]: string} | null; /** * List of LUNs associated with this server. */ luns?: Schema$Lun[]; /** * The server type. [Available server types](https://cloud.google.com/bare-metal/docs/bms-planning#server_configurations) */ machineType?: string | null; /** * Output only. The resource name of this `Instance`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/instances/{instance\}` */ name?: string | null; /** * List of networks associated with this server. */ networks?: Schema$Network[]; /** * The OS image currently installed on the server. */ osImage?: string | null; /** * The state of the server. */ state?: string | null; /** * Output only. Update a time stamp. */ updateTime?: string | null; } /** * Configuration parameters for a new instance. */ export interface Schema$InstanceConfig { /** * If true networks can be from different projects of the same vendor account. */ accountNetworksEnabled?: boolean | null; /** * Client network address. */ clientNetwork?: Schema$NetworkAddress; /** * Whether the instance should be provisioned with Hyperthreading enabled. */ hyperthreading?: boolean | null; /** * A transient unique identifier to idenfity an instance within an ProvisioningConfig request. */ id?: string | null; /** * Instance type. [Available types](https://cloud.google.com/bare-metal/docs/bms-planning#server_configurations) */ instanceType?: string | null; /** * Output only. The name of the instance config. */ name?: string | null; /** * OS image to initialize the instance. [Available images](https://cloud.google.com/bare-metal/docs/bms-planning#server_configurations) */ osImage?: string | null; /** * Private network address, if any. */ privateNetwork?: Schema$NetworkAddress; /** * User note field, it can be used by customers to add additional information for the BMS Ops team . */ userNote?: string | null; } /** * A resource budget. */ export interface Schema$InstanceQuota { /** * Number of machines than can be created for the given location and instance_type. */ availableMachineCount?: number | null; /** * Instance type. */ instanceType?: string | null; /** * Location where the quota applies. */ location?: string | null; /** * Output only. The name of the instance quota. */ name?: string | null; } /** * A GCP vlan attachment. */ export interface Schema$IntakeVlanAttachment { /** * Identifier of the VLAN attachment. */ id?: string | null; /** * Attachment pairing key. */ pairingKey?: string | null; } /** * Response message for the list of servers. */ export interface Schema$ListInstancesResponse { /** * The list of servers. */ instances?: Schema$Instance[]; /** * A token identifying a page of results from the server. */ nextPageToken?: string | null; /** * Locations that could not be reached. */ unreachable?: string[] | null; } /** * The response message for Locations.ListLocations. */ export interface Schema$ListLocationsResponse { /** * A list of locations that matches the specified filter in the request. */ locations?: Schema$Location[]; /** * The standard List next-page token. */ nextPageToken?: string | null; } /** * Response message containing the list of storage volume luns. */ export interface Schema$ListLunsResponse { /** * The list of luns. */ luns?: Schema$Lun[]; /** * A token identifying a page of results from the server. */ nextPageToken?: string | null; /** * Locations that could not be reached. */ unreachable?: string[] | null; } /** * Response message containing the list of networks. */ export interface Schema$ListNetworksResponse { /** * The list of networks. */ networks?: Schema$Network[]; /** * A token identifying a page of results from the server. */ nextPageToken?: string | null; /** * Locations that could not be reached. */ unreachable?: string[] | null; } /** * Response with Networks with IPs */ export interface Schema$ListNetworkUsageResponse { /** * Networks with IPs. */ networks?: Schema$NetworkUsage[]; } /** * Response message containing the list of NFS shares. */ export interface Schema$ListNfsSharesResponse { /** * A token identifying a page of results from the server. */ nextPageToken?: string | null; /** * The list of NFS shares. */ nfsShares?: Schema$NfsShare[]; /** * Locations that could not be reached. */ unreachable?: string[] | null; } /** * Response message for the list of provisioning quotas. */ export interface Schema$ListProvisioningQuotasResponse { /** * Token to retrieve the next page of results, or empty if there are no more results in the list. */ nextPageToken?: string | null; /** * The provisioning quotas registered in this project. */ provisioningQuotas?: Schema$ProvisioningQuota[]; } /** * Response message containing the list of snapshot schedule policies. */ export interface Schema$ListSnapshotSchedulePoliciesResponse { /** * Token to retrieve the next page of results, or empty if there are no more results in the list. */ nextPageToken?: string | null; /** * The snapshot schedule policies registered in this project. */ snapshotSchedulePolicies?: Schema$SnapshotSchedulePolicy[]; } /** * Response message containing the list of storage volume snapshots. */ export interface Schema$ListVolumeSnapshotsResponse { /** * A token identifying a page of results from the server. */ nextPageToken?: string | null; /** * Locations that could not be reached. */ unreachable?: string[] | null; /** * The list of storage volumes. */ volumeSnapshots?: Schema$VolumeSnapshot[]; } /** * Response message containing the list of storage volumes. */ export interface Schema$ListVolumesResponse { /** * A token identifying a page of results from the server. */ nextPageToken?: string | null; /** * Locations that could not be reached. */ unreachable?: string[] | null; /** * The list of storage volumes. */ volumes?: Schema$Volume[]; } /** * A resource that represents Google Cloud Platform location. */ export interface Schema$Location { /** * The friendly name for this location, typically a nearby city name. For example, "Tokyo". */ displayName?: string | null; /** * Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"\} */ labels?: {[key: string]: string} | null; /** * The canonical id for this location. For example: `"us-east1"`. */ locationId?: string | null; /** * Service-specific metadata. For example the available capacity at the given location. */ metadata?: {[key: string]: any} | null; /** * Resource name for the location, which may vary between implementations. For example: `"projects/example-project/locations/us-east1"` */ name?: string | null; } /** * Logical interface. */ export interface Schema$LogicalInterface { /** * Interface name. This is not a globally unique identifier. Name is unique only inside the ServerNetworkTemplate. */ name?: string | null; /** * If true, interface must have network connected. */ required?: boolean | null; /** * Interface type. */ type?: string | null; } /** * A storage volume logical unit number (LUN). */ export interface Schema$Lun { /** * Display if this LUN is a boot LUN. */ bootLun?: boolean | null; /** * An identifier for the LUN, generated by the backend. */ id?: string | null; /** * The LUN multiprotocol type ensures the characteristics of the LUN are optimized for each operating system. */ multiprotocolType?: string | null; /** * Output only. The name of the LUN. */ name?: string | null; /** * Display if this LUN can be shared between multiple physical servers. */ shareable?: boolean | null; /** * The size of this LUN, in gigabytes. */ sizeGb?: string | null; /** * The state of this storage volume. */ state?: string | null; /** * The storage type for this LUN. */ storageType?: string | null; /** * Display the storage volume for this LUN. */ storageVolume?: string | null; /** * The WWID for this LUN. */ wwid?: string | null; } /** * A LUN(Logical Unit Number) range. */ export interface Schema$LunRange { /** * Number of LUNs to create. */ quantity?: number | null; /** * The requested size of each LUN, in GB. */ sizeGb?: number | null; } /** * A Network. */ export interface Schema$Network { /** * The cidr of the Network. */ cidr?: string | null; /** * An identifier for the `Network`, generated by the backend. */ id?: string | null; /** * IP address configured. */ ipAddress?: string | null; /** * Labels as key value pairs. */ labels?: {[key: string]: string} | null; /** * List of physical interfaces. */ macAddress?: string[] | null; /** * Output only. The resource name of this `Network`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/networks/{network\}` */ name?: string | null; /** * IP range for reserved for services (e.g. NFS). */ servicesCidr?: string | null; /** * The Network state. */ state?: string | null; /** * The type of this network. */ type?: string | null; /** * The vlan id of the Network. */ vlanId?: string | null; /** * The vrf for the Network. */ vrf?: Schema$VRF; } /** * A network. */ export interface Schema$NetworkAddress { /** * IPv4 address to be assigned to the server. */ address?: string | null; /** * Name of the existing network to use. */ existingNetworkId?: string | null; /** * Id of the network to use, within the same ProvisioningConfig request. */ networkId?: string | null; } /** * Configuration parameters for a new network. */ export interface Schema$NetworkConfig { /** * Interconnect bandwidth. Set only when type is CLIENT. */ bandwidth?: string | null; /** * CIDR range of the network. */ cidr?: string | null; /** * The GCP service of the network. Available gcp_service are in https://cloud.google.com/bare-metal/docs/bms-planning. */ gcpService?: string | null; /** * A transient unique identifier to identify a volume within an ProvisioningConfig request. */ id?: string | null; /** * Output only. The name of the network config. */ name?: string | null; /** * Service CIDR, if any. */ serviceCidr?: string | null; /** * The type of this network, either Client or Private. */ type?: string | null; /** * User note field, it can be used by customers to add additional information for the BMS Ops team (b/194021617). */ userNote?: string | null; /** * List of VLAN attachments. As of now there are always 2 attachments, but it is going to change in the future (multi vlan). */ vlanAttachments?: Schema$IntakeVlanAttachment[]; /** * Whether the VLAN attachment pair is located in the same project. */ vlanSameProject?: boolean | null; } /** * Network with all used IP addresses. */ export interface Schema$NetworkUsage { /** * Network. */ network?: Schema$Network; /** * All used IP addresses in this network. */ usedIps?: string[] | null; } /** * A NFS export entry. */ export interface Schema$NfsExport { /** * Allow dev flag in NfsShare AllowedClientsRequest. */ allowDev?: boolean | null; /** * Allow the setuid flag. */ allowSuid?: boolean | null; /** * A CIDR range. */ cidr?: string | null; /** * Either a single machine, identified by an ID, or a comma-separated list of machine IDs. */ machineId?: string | null; /** * Network to use to publish the export. */ networkId?: string | null; /** * Disable root squashing, which is a feature of NFS. Root squash is a special mapping of the remote superuser (root) identity when using identity authentication. */ noRootSquash?: boolean | null; /** * Export permissions. */ permissions?: string | null; } /** * An NFS share. */ export interface Schema$NfsShare { /** * List of allowed access points. */ allowedClients?: Schema$AllowedClient[]; /** * Labels as key value pairs. */ labels?: {[key: string]: string} | null; /** * Output only. The name of the NFS share. */ name?: string | null; /** * Output only. An identifier for the NFS share, generated by the backend. */ nfsShareId?: string | null; /** * The state of the NFS share. */ state?: string | null; /** * The volume containing the share. */ volume?: string | null; } /** * This resource represents a long-running operation that is the result of a network API call. */ export interface Schema$Operation { /** * If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ done?: boolean | null; /** * The error result of the operation in case of failure or cancellation. */ error?: Schema$Status; /** * Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ metadata?: {[key: string]: any} | null; /** * The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id\}`. */ name?: string | null; /** * The normal response of the operation in case of success. If the original method returns no data on success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`. */ response?: {[key: string]: any} | null; } /** * Operation System image. */ export interface Schema$OSImage { /** * Instance types this image is applicable to. [Available types](https://cloud.google.com/bare-metal/docs/bms-planning#server_configurations) */ applicableInstanceTypes?: string[] | null; /** * OS Image code. */ code?: string | null; /** * OS Image description. */ description?: string | null; /** * Output only. OS Image's unique name. */ name?: string | null; /** * Network templates that can be used with this OS Image. */ supportedNetworkTemplates?: Schema$ServerNetworkTemplate[]; } /** * A provisioning configuration. */ export interface Schema$ProvisioningConfig { /** * Output only. URI to Cloud Console UI view of this provisioning config. */ cloudConsoleUri?: string | null; /** * Email provided to send a confirmation with provisioning config to. Deprecated in favour of email field in request messages. */ email?: string | null; /** * A service account to enable customers to access instance credentials upon handover. */ handoverServiceAccount?: string | null; /** * Instances to be created. */ instances?: Schema$InstanceConfig[]; /** * Optional. Location name of this ProvisioningConfig. It is optional only for Intake UI transition period. */ location?: string | null; /** * Output only. The name of the provisioning config. */ name?: string | null; /** * Networks to be created. */ networks?: Schema$NetworkConfig[]; /** * Output only. State of ProvisioningConfig. */ state?: string | null; /** * A generated buganizer id to track provisioning request. */ ticketId?: string | null; /** * Output only. Last update timestamp. */ updateTime?: string | null; /** * Volumes to be created. */ volumes?: Schema$VolumeConfig[]; } /** * A provisioning quota for a given project. */ export interface Schema$ProvisioningQuota { /** * The asset type of this provisioning quota. */ assetType?: string | null; /** * The available count of the provisioning quota. */ availableCount?: number | null; /** * The gcp service of the provisioning quota. */ gcpService?: string | null; /** * Instance quota. */ instanceQuota?: Schema$InstanceQuota; /** * The specific location of the provisioining quota. */ location?: string | null; /** * Output only. The name of the provisioning quota. */ name?: string | null; /** * Network bandwidth, Gbps */ networkBandwidth?: string | null; /** * Server count. */ serverCount?: string | null; /** * Storage size (GB). */ storageGib?: string | null; } /** * QOS policy parameters. */ export interface Schema$QosPolicy { /** * The bandwidth permitted by the QOS policy, in gbps. */ bandwidthGbps?: number | null; } /** * Message requesting to reset a server. */ export interface Schema$ResetInstanceRequest {} /** * Message for restoring a volume snapshot. */ export interface Schema$RestoreVolumeSnapshotRequest {} /** * A snapshot schedule. */ export interface Schema$Schedule { /** * A crontab-like specification that the schedule uses to take snapshots. */ crontabSpec?: string | null; /** * A list of snapshot names created in this schedule. */ prefix?: string | null; /** * The maximum number of snapshots to retain in this schedule. */ retentionCount?: number | null; } /** * Network template. */ export interface Schema$ServerNetworkTemplate { /** * Instance types this template is applicable to. */ applicableInstanceTypes?: string[] | null; /** * Logical interfaces. */ logicalInterfaces?: Schema$LogicalInterface[]; /** * Output only. Template's unique name. */ name?: string | null; } /** * Details about snapshot space reservation and usage on the storage volume. */ export interface Schema$SnapshotReservationDetail { /** * The space on this storage volume reserved for snapshots, shown in GiB. */ reservedSpaceGib?: string | null; /** * Percent of the total Volume size reserved for snapshot copies. Enabling snapshots requires reserving 20% or more of the storage volume space for snapshots. Maximum reserved space for snapshots is 40%. Setting this field will effectively set snapshot_enabled to true. */ reservedSpacePercent?: number | null; /** * The amount, in GiB, of available space in this storage volume's reserved snapshot space. */ reservedSpaceRemainingGib?: string | null; /** * The percent of snapshot space on this storage volume actually being used by the snapshot copies. This value might be higher than 100% if the snapshot copies have overflowed into the data portion of the storage volume. */ reservedSpaceUsedPercent?: number | null; } /** * A snapshot schedule policy. */ export interface Schema$SnapshotSchedulePolicy { /** * The description of the snapshot schedule policy. */ description?: string | null; /** * An identifier for the snapshot schedule policy, generated by the backend. */ id?: string | null; /** * Labels as key value pairs. */ labels?: {[key: string]: string} | null; /** * Output only. The name of the snapshot schedule policy. */ name?: string | null; /** * The snapshot schedules contained in this policy. You can specify a maximum of 5 schedules. */ schedules?: Schema$Schedule[]; /** * The state of the snapshot schedule policy. */ state?: string | null; } /** * Message requesting to start a server. */ export interface Schema$StartInstanceRequest {} /** * The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ export interface Schema$Status { /** * The status code, which should be an enum value of google.rpc.Code. */ code?: number | null; /** * A list of messages that carry the error details. There is a common set of message types for APIs to use. */ details?: Array<{[key: string]: any}> | null; /** * A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ message?: string | null; } /** * Message requesting to stop a server. */ export interface Schema$StopInstanceRequest {} /** * Request for SubmitProvisioningConfig. */ export interface Schema$SubmitProvisioningConfigRequest { /** * Optional. Email provided to send a confirmation with provisioning config to. */ email?: string | null; /** * Required. The ProvisioningConfig to create. */ provisioningConfig?: Schema$ProvisioningConfig; } /** * Response for SubmitProvisioningConfig. */ export interface Schema$SubmitProvisioningConfigResponse { /** * The submitted provisioning config. */ provisioningConfig?: Schema$ProvisioningConfig; } /** * VLAN attachment details. */ export interface Schema$VlanAttachment { /** * The peer IP of the attachment. */ peerIp?: string | null; /** * The peer vlan ID of the attachment. */ peerVlanId?: string | null; /** * The router IP of the attachment. */ routerIp?: string | null; } /** * A storage volume. */ export interface Schema$Volume { /** * The size, in GiB, that this storage volume has expanded as a result of an auto grow policy. In the absence of auto-grow, the value is 0. */ autoGrownSizeGib?: string | null; /** * The current size of this storage volume, in GiB, including space reserved for snapshots. This size might be different than the requested size if the storage volume has been configured with auto grow or auto shrink. */ currentSizeGib?: string | null; /** * Additional emergency size that was requested for this Volume, in GiB. current_size_gib includes this value. */ emergencySizeGib?: string | null; /** * An identifier for the `Volume`, generated by the backend. */ id?: string | null; /** * Labels as key value pairs. */ labels?: {[key: string]: string} | null; /** * Output only. The resource name of this `Volume`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/volumes/{volume\}` */ name?: string | null; /** * The space remaining in the storage volume for new LUNs, in GiB, excluding space reserved for snapshots. */ remainingSpaceGib?: string | null; /** * The requested size of this storage volume, in GiB. */ requestedSizeGib?: string | null; /** * The behavior to use when snapshot reserved space is full. */ snapshotAutoDeleteBehavior?: string | null; /** * Whether snapshots are enabled. */ snapshotEnabled?: boolean | null; /** * Details about snapshot space reservation and usage on the storage volume. */ snapshotReservationDetail?: Schema$SnapshotReservationDetail; /** * The name of the snapshot schedule policy in use for this volume, if any. */ snapshotSchedulePolicy?: string | null; /** * The state of this storage volume. */ state?: string | null; /** * The storage type for this volume. */ storageType?: string | null; } /** * Configuration parameters for a new volume. */ export interface Schema$VolumeConfig { /** * The GCP service of the storage volume. Available gcp_service are in https://cloud.google.com/bare-metal/docs/bms-planning. */ gcpService?: string | null; /** * A transient unique identifier to identify a volume within an ProvisioningConfig request. */ id?: string | null; /** * LUN ranges to be configured. Set only when protocol is PROTOCOL_FC. */ lunRanges?: Schema$LunRange[]; /** * Machine ids connected to this volume. Set only when protocol is PROTOCOL_FC. */ machineIds?: string[] | null; /** * Output only. The name of the volume config. */ name?: string | null; /** * NFS exports. Set only when protocol is PROTOCOL_NFS. */ nfsExports?: Schema$NfsExport[]; /** * Volume protocol. */ protocol?: string | null; /** * The requested size of this volume, in GB. */ sizeGb?: number | null; /** * Whether snapshots should be enabled. */ snapshotsEnabled?: boolean | null; /** * The type of this Volume. */ type?: string | null; /** * User note field, it can be used by customers to add additional information for the BMS Ops team (b/194021617). */ userNote?: string | null; } /** * Snapshot registered for a given storage volume. */ export interface Schema$VolumeSnapshot { /** * Output only. The creation time of the storage volume snapshot. */ createTime?: string | null; /** * The description of the storage volume snapshot. */ description?: string | null; /** * An identifier for the snapshot, generated by the backend. */ id?: string | null; /** * Output only. The name of the storage volume snapshot. */ name?: string | null; /** * The size of the storage volume snapshot, in bytes. */ sizeBytes?: string | null; /** * The storage volume this snapshot belongs to. */ storageVolume?: string | null; } /** * A network VRF. */ export interface Schema$VRF { /** * The name of the VRF. */ name?: string | null; /** * The QOS policy applied to this VRF. */ qosPolicy?: Schema$QosPolicy; /** * The possible state of VRF. */ state?: string | null; /** * The list of VLAN attachments for the VRF. */ vlanAttachments?: Schema$VlanAttachment[]; } export class Resource$Projects { context: APIRequestContext; locations: Resource$Projects$Locations; constructor(context: APIRequestContext) { this.context = context; this.locations = new Resource$Projects$Locations(this.context); } } export class Resource$Projects$Locations { context: APIRequestContext; instanceProvisioningSettings: Resource$Projects$Locations$Instanceprovisioningsettings; instances: Resource$Projects$Locations$Instances; networks: Resource$Projects$Locations$Networks; nfsShares: Resource$Projects$Locations$Nfsshares; provisioningConfigs: Resource$Projects$Locations$Provisioningconfigs; provisioningQuotas: Resource$Projects$Locations$Provisioningquotas; snapshotSchedulePolicies: Resource$Projects$Locations$Snapshotschedulepolicies; volumes: Resource$Projects$Locations$Volumes; constructor(context: APIRequestContext) { this.context = context; this.instanceProvisioningSettings = new Resource$Projects$Locations$Instanceprovisioningsettings( this.context ); this.instances = new Resource$Projects$Locations$Instances(this.context); this.networks = new Resource$Projects$Locations$Networks(this.context); this.nfsShares = new Resource$Projects$Locations$Nfsshares(this.context); this.provisioningConfigs = new Resource$Projects$Locations$Provisioningconfigs(this.context); this.provisioningQuotas = new Resource$Projects$Locations$Provisioningquotas(this.context); this.snapshotSchedulePolicies = new Resource$Projects$Locations$Snapshotschedulepolicies(this.context); this.volumes = new Resource$Projects$Locations$Volumes(this.context); } /** * Gets information about a location. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.get({ * // Resource name for the location. * name: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "displayName": "my_displayName", * // "labels": {}, * // "locationId": "my_locationId", * // "metadata": {}, * // "name": "my_name" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Get, options?: MethodOptions ): GaxiosPromise<Schema$Location>; get( params: Params$Resource$Projects$Locations$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Get, options: MethodOptions | BodyResponseCallback<Schema$Location>, callback: BodyResponseCallback<Schema$Location> ): void; get( params: Params$Resource$Projects$Locations$Get, callback: BodyResponseCallback<Schema$Location> ): void; get(callback: BodyResponseCallback<Schema$Location>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Get | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Location> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Location> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Location>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Location>(parameters); } } /** * Lists information about the supported locations for this service. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.list({ * // A filter to narrow down results to a preferred subset. The filtering language accepts strings like `"displayName=tokyo"`, and is documented in more detail in [AIP-160](https://google.aip.dev/160). * filter: 'placeholder-value', * // The resource that owns the locations collection, if applicable. * name: 'projects/my-project', * // The maximum number of results to return. If not set, the service selects a default. * pageSize: 'placeholder-value', * // A page token received from the `next_page_token` field in the response. Send that page token to receive the subsequent page. * pageToken: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "locations": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$List, options?: MethodOptions ): GaxiosPromise<Schema$ListLocationsResponse>; list( params: Params$Resource$Projects$Locations$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$List, options: | MethodOptions | BodyResponseCallback<Schema$ListLocationsResponse>, callback: BodyResponseCallback<Schema$ListLocationsResponse> ): void; list( params: Params$Resource$Projects$Locations$List, callback: BodyResponseCallback<Schema$ListLocationsResponse> ): void; list(callback: BodyResponseCallback<Schema$ListLocationsResponse>): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$List | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListLocationsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListLocationsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}/locations').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListLocationsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListLocationsResponse>(parameters); } } } export interface Params$Resource$Projects$Locations$Get extends StandardParameters { /** * Resource name for the location. */ name?: string; } export interface Params$Resource$Projects$Locations$List extends StandardParameters { /** * A filter to narrow down results to a preferred subset. The filtering language accepts strings like `"displayName=tokyo"`, and is documented in more detail in [AIP-160](https://google.aip.dev/160). */ filter?: string; /** * The resource that owns the locations collection, if applicable. */ name?: string; /** * The maximum number of results to return. If not set, the service selects a default. */ pageSize?: number; /** * A page token received from the `next_page_token` field in the response. Send that page token to receive the subsequent page. */ pageToken?: string; } export class Resource$Projects$Locations$Instanceprovisioningsettings { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Get instance provisioning settings for a given project. This is hidden method used by UI only. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.instanceProvisioningSettings.fetch( * { * // Required. The parent project and location containing the ProvisioningSettings. * location: 'projects/my-project/locations/my-location', * } * ); * console.log(res.data); * * // Example response * // { * // "images": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ fetch( params: Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch, options: StreamMethodOptions ): GaxiosPromise<Readable>; fetch( params?: Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch, options?: MethodOptions ): GaxiosPromise<Schema$FetchInstanceProvisioningSettingsResponse>; fetch( params: Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; fetch( params: Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch, options: | MethodOptions | BodyResponseCallback<Schema$FetchInstanceProvisioningSettingsResponse>, callback: BodyResponseCallback<Schema$FetchInstanceProvisioningSettingsResponse> ): void; fetch( params: Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch, callback: BodyResponseCallback<Schema$FetchInstanceProvisioningSettingsResponse> ): void; fetch( callback: BodyResponseCallback<Schema$FetchInstanceProvisioningSettingsResponse> ): void; fetch( paramsOrCallback?: | Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch | BodyResponseCallback<Schema$FetchInstanceProvisioningSettingsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$FetchInstanceProvisioningSettingsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$FetchInstanceProvisioningSettingsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$FetchInstanceProvisioningSettingsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v2/{+location}/instanceProvisioningSettings:fetch' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['location'], pathParams: ['location'], context: this.context, }; if (callback) { createAPIRequest<Schema$FetchInstanceProvisioningSettingsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$FetchInstanceProvisioningSettingsResponse>( parameters ); } } } export interface Params$Resource$Projects$Locations$Instanceprovisioningsettings$Fetch extends StandardParameters { /** * Required. The parent project and location containing the ProvisioningSettings. */ location?: string; } export class Resource$Projects$Locations$Instances { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Get details about a single server. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.instances.get({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/instances/my-instance', * }); * console.log(res.data); * * // Example response * // { * // "createTime": "my_createTime", * // "hyperthreadingEnabled": false, * // "id": "my_id", * // "interactiveSerialConsoleEnabled": false, * // "labels": {}, * // "luns": [], * // "machineType": "my_machineType", * // "name": "my_name", * // "networks": [], * // "osImage": "my_osImage", * // "state": "my_state", * // "updateTime": "my_updateTime" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Instances$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Instances$Get, options?: MethodOptions ): GaxiosPromise<Schema$Instance>; get( params: Params$Resource$Projects$Locations$Instances$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Instances$Get, options: MethodOptions | BodyResponseCallback<Schema$Instance>, callback: BodyResponseCallback<Schema$Instance> ): void; get( params: Params$Resource$Projects$Locations$Instances$Get, callback: BodyResponseCallback<Schema$Instance> ): void; get(callback: BodyResponseCallback<Schema$Instance>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Instances$Get | BodyResponseCallback<Schema$Instance> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Instance> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Instance> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Instance> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Instances$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Instances$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Instance>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Instance>(parameters); } } /** * List servers in a given project and location. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.instances.list({ * // List filter. * filter: 'placeholder-value', * // Requested page size. Server may return fewer items than requested. If unspecified, the server will pick an appropriate default. * pageSize: 'placeholder-value', * // A token identifying a page of results from the server. * pageToken: 'placeholder-value', * // Required. Parent value for ListInstancesRequest. * parent: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "instances": [], * // "nextPageToken": "my_nextPageToken", * // "unreachable": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Instances$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Instances$List, options?: MethodOptions ): GaxiosPromise<Schema$ListInstancesResponse>; list( params: Params$Resource$Projects$Locations$Instances$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Instances$List, options: | MethodOptions | BodyResponseCallback<Schema$ListInstancesResponse>, callback: BodyResponseCallback<Schema$ListInstancesResponse> ): void; list( params: Params$Resource$Projects$Locations$Instances$List, callback: BodyResponseCallback<Schema$ListInstancesResponse> ): void; list(callback: BodyResponseCallback<Schema$ListInstancesResponse>): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Instances$List | BodyResponseCallback<Schema$ListInstancesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListInstancesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListInstancesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListInstancesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Instances$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Instances$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/instances').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListInstancesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListInstancesResponse>(parameters); } } /** * Update details of a single server. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.instances.patch({ * // Output only. The resource name of this `Instance`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/instances/{instance\}` * name: 'projects/my-project/locations/my-location/instances/my-instance', * // The list of fields to update. The only currently supported fields are: `labels` `hyperthreading_enabled` * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "createTime": "my_createTime", * // "hyperthreadingEnabled": false, * // "id": "my_id", * // "interactiveSerialConsoleEnabled": false, * // "labels": {}, * // "luns": [], * // "machineType": "my_machineType", * // "name": "my_name", * // "networks": [], * // "osImage": "my_osImage", * // "state": "my_state", * // "updateTime": "my_updateTime" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Locations$Instances$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Locations$Instances$Patch, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; patch( params: Params$Resource$Projects$Locations$Instances$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Locations$Instances$Patch, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; patch( params: Params$Resource$Projects$Locations$Instances$Patch, callback: BodyResponseCallback<Schema$Operation> ): void; patch(callback: BodyResponseCallback<Schema$Operation>): void; patch( paramsOrCallback?: | Params$Resource$Projects$Locations$Instances$Patch | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Instances$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Instances$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } /** * Perform an ungraceful, hard reset on a server. Equivalent to shutting the power off and then turning it back on. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.instances.reset({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/instances/my-instance', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ reset( params: Params$Resource$Projects$Locations$Instances$Reset, options: StreamMethodOptions ): GaxiosPromise<Readable>; reset( params?: Params$Resource$Projects$Locations$Instances$Reset, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; reset( params: Params$Resource$Projects$Locations$Instances$Reset, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; reset( params: Params$Resource$Projects$Locations$Instances$Reset, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; reset( params: Params$Resource$Projects$Locations$Instances$Reset, callback: BodyResponseCallback<Schema$Operation> ): void; reset(callback: BodyResponseCallback<Schema$Operation>): void; reset( paramsOrCallback?: | Params$Resource$Projects$Locations$Instances$Reset | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Instances$Reset; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Instances$Reset; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}:reset').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } /** * Starts a server that was shutdown. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.instances.start({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/instances/my-instance', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ start( params: Params$Resource$Projects$Locations$Instances$Start, options: StreamMethodOptions ): GaxiosPromise<Readable>; start( params?: Params$Resource$Projects$Locations$Instances$Start, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; start( params: Params$Resource$Projects$Locations$Instances$Start, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; start( params: Params$Resource$Projects$Locations$Instances$Start, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; start( params: Params$Resource$Projects$Locations$Instances$Start, callback: BodyResponseCallback<Schema$Operation> ): void; start(callback: BodyResponseCallback<Schema$Operation>): void; start( paramsOrCallback?: | Params$Resource$Projects$Locations$Instances$Start | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Instances$Start; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Instances$Start; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}:start').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } /** * Stop a running server. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.instances.stop({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/instances/my-instance', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ stop( params: Params$Resource$Projects$Locations$Instances$Stop, options: StreamMethodOptions ): GaxiosPromise<Readable>; stop( params?: Params$Resource$Projects$Locations$Instances$Stop, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; stop( params: Params$Resource$Projects$Locations$Instances$Stop, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; stop( params: Params$Resource$Projects$Locations$Instances$Stop, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; stop( params: Params$Resource$Projects$Locations$Instances$Stop, callback: BodyResponseCallback<Schema$Operation> ): void; stop(callback: BodyResponseCallback<Schema$Operation>): void; stop( paramsOrCallback?: | Params$Resource$Projects$Locations$Instances$Stop | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Instances$Stop; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Instances$Stop; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}:stop').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } } export interface Params$Resource$Projects$Locations$Instances$Get extends StandardParameters { /** * Required. Name of the resource. */ name?: string; } export interface Params$Resource$Projects$Locations$Instances$List extends StandardParameters { /** * List filter. */ filter?: string; /** * Requested page size. Server may return fewer items than requested. If unspecified, the server will pick an appropriate default. */ pageSize?: number; /** * A token identifying a page of results from the server. */ pageToken?: string; /** * Required. Parent value for ListInstancesRequest. */ parent?: string; } export interface Params$Resource$Projects$Locations$Instances$Patch extends StandardParameters { /** * Output only. The resource name of this `Instance`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/instances/{instance\}` */ name?: string; /** * The list of fields to update. The only currently supported fields are: `labels` `hyperthreading_enabled` */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$Instance; } export interface Params$Resource$Projects$Locations$Instances$Reset extends StandardParameters { /** * Required. Name of the resource. */ name?: string; /** * Request body metadata */ requestBody?: Schema$ResetInstanceRequest; } export interface Params$Resource$Projects$Locations$Instances$Start extends StandardParameters { /** * Required. Name of the resource. */ name?: string; /** * Request body metadata */ requestBody?: Schema$StartInstanceRequest; } export interface Params$Resource$Projects$Locations$Instances$Stop extends StandardParameters { /** * Required. Name of the resource. */ name?: string; /** * Request body metadata */ requestBody?: Schema$StopInstanceRequest; } export class Resource$Projects$Locations$Networks { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Get details of a single network. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.networks.get({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/networks/my-network', * }); * console.log(res.data); * * // Example response * // { * // "cidr": "my_cidr", * // "id": "my_id", * // "ipAddress": "my_ipAddress", * // "labels": {}, * // "macAddress": [], * // "name": "my_name", * // "servicesCidr": "my_servicesCidr", * // "state": "my_state", * // "type": "my_type", * // "vlanId": "my_vlanId", * // "vrf": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Networks$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Networks$Get, options?: MethodOptions ): GaxiosPromise<Schema$Network>; get( params: Params$Resource$Projects$Locations$Networks$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Networks$Get, options: MethodOptions | BodyResponseCallback<Schema$Network>, callback: BodyResponseCallback<Schema$Network> ): void; get( params: Params$Resource$Projects$Locations$Networks$Get, callback: BodyResponseCallback<Schema$Network> ): void; get(callback: BodyResponseCallback<Schema$Network>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Networks$Get | BodyResponseCallback<Schema$Network> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Network> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Network> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Network> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Networks$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Networks$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Network>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Network>(parameters); } } /** * List network in a given project and location. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.networks.list({ * // List filter. * filter: 'placeholder-value', * // Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. * pageSize: 'placeholder-value', * // A token identifying a page of results from the server. * pageToken: 'placeholder-value', * // Required. Parent value for ListNetworksRequest. * parent: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "networks": [], * // "nextPageToken": "my_nextPageToken", * // "unreachable": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Networks$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Networks$List, options?: MethodOptions ): GaxiosPromise<Schema$ListNetworksResponse>; list( params: Params$Resource$Projects$Locations$Networks$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Networks$List, options: | MethodOptions | BodyResponseCallback<Schema$ListNetworksResponse>, callback: BodyResponseCallback<Schema$ListNetworksResponse> ): void; list( params: Params$Resource$Projects$Locations$Networks$List, callback: BodyResponseCallback<Schema$ListNetworksResponse> ): void; list(callback: BodyResponseCallback<Schema$ListNetworksResponse>): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Networks$List | BodyResponseCallback<Schema$ListNetworksResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListNetworksResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListNetworksResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListNetworksResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Networks$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Networks$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/networks').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListNetworksResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListNetworksResponse>(parameters); } } /** * List all Networks (and used IPs for each Network) in the vendor account associated with the specified project. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.networks.listNetworkUsage({ * // Required. Parent value (project and location). * location: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "networks": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ listNetworkUsage( params: Params$Resource$Projects$Locations$Networks$Listnetworkusage, options: StreamMethodOptions ): GaxiosPromise<Readable>; listNetworkUsage( params?: Params$Resource$Projects$Locations$Networks$Listnetworkusage, options?: MethodOptions ): GaxiosPromise<Schema$ListNetworkUsageResponse>; listNetworkUsage( params: Params$Resource$Projects$Locations$Networks$Listnetworkusage, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; listNetworkUsage( params: Params$Resource$Projects$Locations$Networks$Listnetworkusage, options: | MethodOptions | BodyResponseCallback<Schema$ListNetworkUsageResponse>, callback: BodyResponseCallback<Schema$ListNetworkUsageResponse> ): void; listNetworkUsage( params: Params$Resource$Projects$Locations$Networks$Listnetworkusage, callback: BodyResponseCallback<Schema$ListNetworkUsageResponse> ): void; listNetworkUsage( callback: BodyResponseCallback<Schema$ListNetworkUsageResponse> ): void; listNetworkUsage( paramsOrCallback?: | Params$Resource$Projects$Locations$Networks$Listnetworkusage | BodyResponseCallback<Schema$ListNetworkUsageResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListNetworkUsageResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListNetworkUsageResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListNetworkUsageResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Networks$Listnetworkusage; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Networks$Listnetworkusage; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v2/{+location}/networks:listNetworkUsage' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['location'], pathParams: ['location'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListNetworkUsageResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListNetworkUsageResponse>(parameters); } } /** * Update details of a single network. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.networks.patch({ * // Output only. The resource name of this `Network`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/networks/{network\}` * name: 'projects/my-project/locations/my-location/networks/my-network', * // The list of fields to update. The only currently supported fields are: `labels` * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "cidr": "my_cidr", * // "id": "my_id", * // "ipAddress": "my_ipAddress", * // "labels": {}, * // "macAddress": [], * // "name": "my_name", * // "servicesCidr": "my_servicesCidr", * // "state": "my_state", * // "type": "my_type", * // "vlanId": "my_vlanId", * // "vrf": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Locations$Networks$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Locations$Networks$Patch, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; patch( params: Params$Resource$Projects$Locations$Networks$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Locations$Networks$Patch, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; patch( params: Params$Resource$Projects$Locations$Networks$Patch, callback: BodyResponseCallback<Schema$Operation> ): void; patch(callback: BodyResponseCallback<Schema$Operation>): void; patch( paramsOrCallback?: | Params$Resource$Projects$Locations$Networks$Patch | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Networks$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Networks$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } } export interface Params$Resource$Projects$Locations$Networks$Get extends StandardParameters { /** * Required. Name of the resource. */ name?: string; } export interface Params$Resource$Projects$Locations$Networks$List extends StandardParameters { /** * List filter. */ filter?: string; /** * Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. */ pageSize?: number; /** * A token identifying a page of results from the server. */ pageToken?: string; /** * Required. Parent value for ListNetworksRequest. */ parent?: string; } export interface Params$Resource$Projects$Locations$Networks$Listnetworkusage extends StandardParameters { /** * Required. Parent value (project and location). */ location?: string; } export interface Params$Resource$Projects$Locations$Networks$Patch extends StandardParameters { /** * Output only. The resource name of this `Network`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/networks/{network\}` */ name?: string; /** * The list of fields to update. The only currently supported fields are: `labels` */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$Network; } export class Resource$Projects$Locations$Nfsshares { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Get details of a single NFS share. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.nfsShares.get({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/nfsShares/my-nfsShare', * }); * console.log(res.data); * * // Example response * // { * // "allowedClients": [], * // "labels": {}, * // "name": "my_name", * // "nfsShareId": "my_nfsShareId", * // "state": "my_state", * // "volume": "my_volume" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Nfsshares$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Nfsshares$Get, options?: MethodOptions ): GaxiosPromise<Schema$NfsShare>; get( params: Params$Resource$Projects$Locations$Nfsshares$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Nfsshares$Get, options: MethodOptions | BodyResponseCallback<Schema$NfsShare>, callback: BodyResponseCallback<Schema$NfsShare> ): void; get( params: Params$Resource$Projects$Locations$Nfsshares$Get, callback: BodyResponseCallback<Schema$NfsShare> ): void; get(callback: BodyResponseCallback<Schema$NfsShare>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Nfsshares$Get | BodyResponseCallback<Schema$NfsShare> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$NfsShare> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$NfsShare> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$NfsShare> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Nfsshares$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Nfsshares$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$NfsShare>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$NfsShare>(parameters); } } /** * List NFS shares. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.nfsShares.list({ * // List filter. * filter: 'placeholder-value', * // Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. * pageSize: 'placeholder-value', * // A token identifying a page of results from the server. * pageToken: 'placeholder-value', * // Required. Parent value for ListNfsSharesRequest. * parent: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "nfsShares": [], * // "unreachable": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Nfsshares$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Nfsshares$List, options?: MethodOptions ): GaxiosPromise<Schema$ListNfsSharesResponse>; list( params: Params$Resource$Projects$Locations$Nfsshares$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Nfsshares$List, options: | MethodOptions | BodyResponseCallback<Schema$ListNfsSharesResponse>, callback: BodyResponseCallback<Schema$ListNfsSharesResponse> ): void; list( params: Params$Resource$Projects$Locations$Nfsshares$List, callback: BodyResponseCallback<Schema$ListNfsSharesResponse> ): void; list(callback: BodyResponseCallback<Schema$ListNfsSharesResponse>): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Nfsshares$List | BodyResponseCallback<Schema$ListNfsSharesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListNfsSharesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListNfsSharesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListNfsSharesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Nfsshares$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Nfsshares$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/nfsShares').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListNfsSharesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListNfsSharesResponse>(parameters); } } /** * Update details of a single NFS share. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.nfsShares.patch({ * // Output only. The name of the NFS share. * name: 'projects/my-project/locations/my-location/nfsShares/my-nfsShare', * // The list of fields to update. The only currently supported fields are: `labels` * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "allowedClients": [], * // "labels": {}, * // "name": "my_name", * // "nfsShareId": "my_nfsShareId", * // "state": "my_state", * // "volume": "my_volume" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Locations$Nfsshares$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Locations$Nfsshares$Patch, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; patch( params: Params$Resource$Projects$Locations$Nfsshares$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Locations$Nfsshares$Patch, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; patch( params: Params$Resource$Projects$Locations$Nfsshares$Patch, callback: BodyResponseCallback<Schema$Operation> ): void; patch(callback: BodyResponseCallback<Schema$Operation>): void; patch( paramsOrCallback?: | Params$Resource$Projects$Locations$Nfsshares$Patch | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Nfsshares$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Nfsshares$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } } export interface Params$Resource$Projects$Locations$Nfsshares$Get extends StandardParameters { /** * Required. Name of the resource. */ name?: string; } export interface Params$Resource$Projects$Locations$Nfsshares$List extends StandardParameters { /** * List filter. */ filter?: string; /** * Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. */ pageSize?: number; /** * A token identifying a page of results from the server. */ pageToken?: string; /** * Required. Parent value for ListNfsSharesRequest. */ parent?: string; } export interface Params$Resource$Projects$Locations$Nfsshares$Patch extends StandardParameters { /** * Output only. The name of the NFS share. */ name?: string; /** * The list of fields to update. The only currently supported fields are: `labels` */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$NfsShare; } export class Resource$Projects$Locations$Provisioningconfigs { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Create new ProvisioningConfig. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.provisioningConfigs.create({ * // Optional. Email provided to send a confirmation with provisioning config to. * email: 'placeholder-value', * // Required. The parent project and location containing the ProvisioningConfig. * parent: 'projects/my-project/locations/my-location', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "cloudConsoleUri": "my_cloudConsoleUri", * // "email": "my_email", * // "handoverServiceAccount": "my_handoverServiceAccount", * // "instances": [], * // "location": "my_location", * // "name": "my_name", * // "networks": [], * // "state": "my_state", * // "ticketId": "my_ticketId", * // "updateTime": "my_updateTime", * // "volumes": [] * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "cloudConsoleUri": "my_cloudConsoleUri", * // "email": "my_email", * // "handoverServiceAccount": "my_handoverServiceAccount", * // "instances": [], * // "location": "my_location", * // "name": "my_name", * // "networks": [], * // "state": "my_state", * // "ticketId": "my_ticketId", * // "updateTime": "my_updateTime", * // "volumes": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Projects$Locations$Provisioningconfigs$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Projects$Locations$Provisioningconfigs$Create, options?: MethodOptions ): GaxiosPromise<Schema$ProvisioningConfig>; create( params: Params$Resource$Projects$Locations$Provisioningconfigs$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Projects$Locations$Provisioningconfigs$Create, options: MethodOptions | BodyResponseCallback<Schema$ProvisioningConfig>, callback: BodyResponseCallback<Schema$ProvisioningConfig> ): void; create( params: Params$Resource$Projects$Locations$Provisioningconfigs$Create, callback: BodyResponseCallback<Schema$ProvisioningConfig> ): void; create(callback: BodyResponseCallback<Schema$ProvisioningConfig>): void; create( paramsOrCallback?: | Params$Resource$Projects$Locations$Provisioningconfigs$Create | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ProvisioningConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Provisioningconfigs$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Provisioningconfigs$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/provisioningConfigs').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ProvisioningConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ProvisioningConfig>(parameters); } } /** * Get ProvisioningConfig by name. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.provisioningConfigs.get({ * // Required. Name of the ProvisioningConfig. * name: 'projects/my-project/locations/my-location/provisioningConfigs/my-provisioningConfig', * }); * console.log(res.data); * * // Example response * // { * // "cloudConsoleUri": "my_cloudConsoleUri", * // "email": "my_email", * // "handoverServiceAccount": "my_handoverServiceAccount", * // "instances": [], * // "location": "my_location", * // "name": "my_name", * // "networks": [], * // "state": "my_state", * // "ticketId": "my_ticketId", * // "updateTime": "my_updateTime", * // "volumes": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Provisioningconfigs$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Provisioningconfigs$Get, options?: MethodOptions ): GaxiosPromise<Schema$ProvisioningConfig>; get( params: Params$Resource$Projects$Locations$Provisioningconfigs$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Provisioningconfigs$Get, options: MethodOptions | BodyResponseCallback<Schema$ProvisioningConfig>, callback: BodyResponseCallback<Schema$ProvisioningConfig> ): void; get( params: Params$Resource$Projects$Locations$Provisioningconfigs$Get, callback: BodyResponseCallback<Schema$ProvisioningConfig> ): void; get(callback: BodyResponseCallback<Schema$ProvisioningConfig>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Provisioningconfigs$Get | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ProvisioningConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Provisioningconfigs$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Provisioningconfigs$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$ProvisioningConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ProvisioningConfig>(parameters); } } /** * Update existing ProvisioningConfig. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.provisioningConfigs.patch({ * // Optional. Email provided to send a confirmation with provisioning config to. * email: 'placeholder-value', * // Output only. The name of the provisioning config. * name: 'projects/my-project/locations/my-location/provisioningConfigs/my-provisioningConfig', * // Required. The list of fields to update. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "cloudConsoleUri": "my_cloudConsoleUri", * // "email": "my_email", * // "handoverServiceAccount": "my_handoverServiceAccount", * // "instances": [], * // "location": "my_location", * // "name": "my_name", * // "networks": [], * // "state": "my_state", * // "ticketId": "my_ticketId", * // "updateTime": "my_updateTime", * // "volumes": [] * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "cloudConsoleUri": "my_cloudConsoleUri", * // "email": "my_email", * // "handoverServiceAccount": "my_handoverServiceAccount", * // "instances": [], * // "location": "my_location", * // "name": "my_name", * // "networks": [], * // "state": "my_state", * // "ticketId": "my_ticketId", * // "updateTime": "my_updateTime", * // "volumes": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Locations$Provisioningconfigs$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Locations$Provisioningconfigs$Patch, options?: MethodOptions ): GaxiosPromise<Schema$ProvisioningConfig>; patch( params: Params$Resource$Projects$Locations$Provisioningconfigs$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Locations$Provisioningconfigs$Patch, options: MethodOptions | BodyResponseCallback<Schema$ProvisioningConfig>, callback: BodyResponseCallback<Schema$ProvisioningConfig> ): void; patch( params: Params$Resource$Projects$Locations$Provisioningconfigs$Patch, callback: BodyResponseCallback<Schema$ProvisioningConfig> ): void; patch(callback: BodyResponseCallback<Schema$ProvisioningConfig>): void; patch( paramsOrCallback?: | Params$Resource$Projects$Locations$Provisioningconfigs$Patch | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ProvisioningConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ProvisioningConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Provisioningconfigs$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Provisioningconfigs$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$ProvisioningConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ProvisioningConfig>(parameters); } } /** * Submit a provisiong configuration for a given project. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.provisioningConfigs.submit({ * // Required. The parent project and location containing the ProvisioningConfig. * parent: 'projects/my-project/locations/my-location', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "email": "my_email", * // "provisioningConfig": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "provisioningConfig": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ submit( params: Params$Resource$Projects$Locations$Provisioningconfigs$Submit, options: StreamMethodOptions ): GaxiosPromise<Readable>; submit( params?: Params$Resource$Projects$Locations$Provisioningconfigs$Submit, options?: MethodOptions ): GaxiosPromise<Schema$SubmitProvisioningConfigResponse>; submit( params: Params$Resource$Projects$Locations$Provisioningconfigs$Submit, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; submit( params: Params$Resource$Projects$Locations$Provisioningconfigs$Submit, options: | MethodOptions | BodyResponseCallback<Schema$SubmitProvisioningConfigResponse>, callback: BodyResponseCallback<Schema$SubmitProvisioningConfigResponse> ): void; submit( params: Params$Resource$Projects$Locations$Provisioningconfigs$Submit, callback: BodyResponseCallback<Schema$SubmitProvisioningConfigResponse> ): void; submit( callback: BodyResponseCallback<Schema$SubmitProvisioningConfigResponse> ): void; submit( paramsOrCallback?: | Params$Resource$Projects$Locations$Provisioningconfigs$Submit | BodyResponseCallback<Schema$SubmitProvisioningConfigResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$SubmitProvisioningConfigResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$SubmitProvisioningConfigResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$SubmitProvisioningConfigResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Provisioningconfigs$Submit; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Provisioningconfigs$Submit; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/provisioningConfigs:submit').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$SubmitProvisioningConfigResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$SubmitProvisioningConfigResponse>( parameters ); } } } export interface Params$Resource$Projects$Locations$Provisioningconfigs$Create extends StandardParameters { /** * Optional. Email provided to send a confirmation with provisioning config to. */ email?: string; /** * Required. The parent project and location containing the ProvisioningConfig. */ parent?: string; /** * Request body metadata */ requestBody?: Schema$ProvisioningConfig; } export interface Params$Resource$Projects$Locations$Provisioningconfigs$Get extends StandardParameters { /** * Required. Name of the ProvisioningConfig. */ name?: string; } export interface Params$Resource$Projects$Locations$Provisioningconfigs$Patch extends StandardParameters { /** * Optional. Email provided to send a confirmation with provisioning config to. */ email?: string; /** * Output only. The name of the provisioning config. */ name?: string; /** * Required. The list of fields to update. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$ProvisioningConfig; } export interface Params$Resource$Projects$Locations$Provisioningconfigs$Submit extends StandardParameters { /** * Required. The parent project and location containing the ProvisioningConfig. */ parent?: string; /** * Request body metadata */ requestBody?: Schema$SubmitProvisioningConfigRequest; } export class Resource$Projects$Locations$Provisioningquotas { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * List the budget details to provision resources on a given project. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.provisioningQuotas.list({ * // Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. Notice that page_size field is not supported and won't be respected in the API request for now, will be updated when pagination is supported. * pageSize: 'placeholder-value', * // A token identifying a page of results from the server. * pageToken: 'placeholder-value', * // Required. Parent value for ListProvisioningQuotasRequest. * parent: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "provisioningQuotas": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Provisioningquotas$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Provisioningquotas$List, options?: MethodOptions ): GaxiosPromise<Schema$ListProvisioningQuotasResponse>; list( params: Params$Resource$Projects$Locations$Provisioningquotas$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Provisioningquotas$List, options: | MethodOptions | BodyResponseCallback<Schema$ListProvisioningQuotasResponse>, callback: BodyResponseCallback<Schema$ListProvisioningQuotasResponse> ): void; list( params: Params$Resource$Projects$Locations$Provisioningquotas$List, callback: BodyResponseCallback<Schema$ListProvisioningQuotasResponse> ): void; list( callback: BodyResponseCallback<Schema$ListProvisioningQuotasResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Provisioningquotas$List | BodyResponseCallback<Schema$ListProvisioningQuotasResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListProvisioningQuotasResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListProvisioningQuotasResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListProvisioningQuotasResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Provisioningquotas$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Provisioningquotas$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/provisioningQuotas').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListProvisioningQuotasResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListProvisioningQuotasResponse>( parameters ); } } } export interface Params$Resource$Projects$Locations$Provisioningquotas$List extends StandardParameters { /** * Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. Notice that page_size field is not supported and won't be respected in the API request for now, will be updated when pagination is supported. */ pageSize?: number; /** * A token identifying a page of results from the server. */ pageToken?: string; /** * Required. Parent value for ListProvisioningQuotasRequest. */ parent?: string; } export class Resource$Projects$Locations$Snapshotschedulepolicies { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Create a snapshot schedule policy in the specified project. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.snapshotSchedulePolicies.create({ * // Required. The parent project and location containing the SnapshotSchedulePolicy. * parent: 'projects/my-project/locations/my-location', * // Required. Snapshot policy ID * snapshotSchedulePolicyId: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "description": "my_description", * // "id": "my_id", * // "labels": {}, * // "name": "my_name", * // "schedules": [], * // "state": "my_state" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "description": "my_description", * // "id": "my_id", * // "labels": {}, * // "name": "my_name", * // "schedules": [], * // "state": "my_state" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create, options?: MethodOptions ): GaxiosPromise<Schema$SnapshotSchedulePolicy>; create( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create, options: | MethodOptions | BodyResponseCallback<Schema$SnapshotSchedulePolicy>, callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy> ): void; create( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create, callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy> ): void; create(callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy>): void; create( paramsOrCallback?: | Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$SnapshotSchedulePolicy> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/snapshotSchedulePolicies').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$SnapshotSchedulePolicy>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$SnapshotSchedulePolicy>(parameters); } } /** * Delete a named snapshot schedule policy. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.snapshotSchedulePolicies.delete({ * // Required. The name of the snapshot schedule policy to delete. * name: 'projects/my-project/locations/my-location/snapshotSchedulePolicies/my-snapshotSchedulePolicie', * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete, options?: MethodOptions ): GaxiosPromise<Schema$Empty>; delete( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty> ): void; delete( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete, callback: BodyResponseCallback<Schema$Empty> ): void; delete(callback: BodyResponseCallback<Schema$Empty>): void; delete( paramsOrCallback?: | Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Empty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Empty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Empty>(parameters); } } /** * Get details of a single snapshot schedule policy. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.snapshotSchedulePolicies.get({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/snapshotSchedulePolicies/my-snapshotSchedulePolicie', * }); * console.log(res.data); * * // Example response * // { * // "description": "my_description", * // "id": "my_id", * // "labels": {}, * // "name": "my_name", * // "schedules": [], * // "state": "my_state" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get, options?: MethodOptions ): GaxiosPromise<Schema$SnapshotSchedulePolicy>; get( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get, options: | MethodOptions | BodyResponseCallback<Schema$SnapshotSchedulePolicy>, callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy> ): void; get( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get, callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy> ): void; get(callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$SnapshotSchedulePolicy> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$SnapshotSchedulePolicy>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$SnapshotSchedulePolicy>(parameters); } } /** * List snapshot schedule policies in a given project and location. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.snapshotSchedulePolicies.list({ * // List filter. * filter: 'placeholder-value', * // The maximum number of items to return. * pageSize: 'placeholder-value', * // The next_page_token value returned from a previous List request, if any. * pageToken: 'placeholder-value', * // Required. The parent project containing the Snapshot Schedule Policies. * parent: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "snapshotSchedulePolicies": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Snapshotschedulepolicies$List, options?: MethodOptions ): GaxiosPromise<Schema$ListSnapshotSchedulePoliciesResponse>; list( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$List, options: | MethodOptions | BodyResponseCallback<Schema$ListSnapshotSchedulePoliciesResponse>, callback: BodyResponseCallback<Schema$ListSnapshotSchedulePoliciesResponse> ): void; list( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$List, callback: BodyResponseCallback<Schema$ListSnapshotSchedulePoliciesResponse> ): void; list( callback: BodyResponseCallback<Schema$ListSnapshotSchedulePoliciesResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Snapshotschedulepolicies$List | BodyResponseCallback<Schema$ListSnapshotSchedulePoliciesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListSnapshotSchedulePoliciesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListSnapshotSchedulePoliciesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListSnapshotSchedulePoliciesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Snapshotschedulepolicies$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Snapshotschedulepolicies$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/snapshotSchedulePolicies').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListSnapshotSchedulePoliciesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListSnapshotSchedulePoliciesResponse>( parameters ); } } /** * Update a snapshot schedule policy in the specified project. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.snapshotSchedulePolicies.patch({ * // Output only. The name of the snapshot schedule policy. * name: 'projects/my-project/locations/my-location/snapshotSchedulePolicies/my-snapshotSchedulePolicie', * // Required. The list of fields to update. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "description": "my_description", * // "id": "my_id", * // "labels": {}, * // "name": "my_name", * // "schedules": [], * // "state": "my_state" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "description": "my_description", * // "id": "my_id", * // "labels": {}, * // "name": "my_name", * // "schedules": [], * // "state": "my_state" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch, options?: MethodOptions ): GaxiosPromise<Schema$SnapshotSchedulePolicy>; patch( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch, options: | MethodOptions | BodyResponseCallback<Schema$SnapshotSchedulePolicy>, callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy> ): void; patch( params: Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch, callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy> ): void; patch(callback: BodyResponseCallback<Schema$SnapshotSchedulePolicy>): void; patch( paramsOrCallback?: | Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$SnapshotSchedulePolicy> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$SnapshotSchedulePolicy> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$SnapshotSchedulePolicy>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$SnapshotSchedulePolicy>(parameters); } } } export interface Params$Resource$Projects$Locations$Snapshotschedulepolicies$Create extends StandardParameters { /** * Required. The parent project and location containing the SnapshotSchedulePolicy. */ parent?: string; /** * Required. Snapshot policy ID */ snapshotSchedulePolicyId?: string; /** * Request body metadata */ requestBody?: Schema$SnapshotSchedulePolicy; } export interface Params$Resource$Projects$Locations$Snapshotschedulepolicies$Delete extends StandardParameters { /** * Required. The name of the snapshot schedule policy to delete. */ name?: string; } export interface Params$Resource$Projects$Locations$Snapshotschedulepolicies$Get extends StandardParameters { /** * Required. Name of the resource. */ name?: string; } export interface Params$Resource$Projects$Locations$Snapshotschedulepolicies$List extends StandardParameters { /** * List filter. */ filter?: string; /** * The maximum number of items to return. */ pageSize?: number; /** * The next_page_token value returned from a previous List request, if any. */ pageToken?: string; /** * Required. The parent project containing the Snapshot Schedule Policies. */ parent?: string; } export interface Params$Resource$Projects$Locations$Snapshotschedulepolicies$Patch extends StandardParameters { /** * Output only. The name of the snapshot schedule policy. */ name?: string; /** * Required. The list of fields to update. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$SnapshotSchedulePolicy; } export class Resource$Projects$Locations$Volumes { context: APIRequestContext; luns: Resource$Projects$Locations$Volumes$Luns; snapshots: Resource$Projects$Locations$Volumes$Snapshots; constructor(context: APIRequestContext) { this.context = context; this.luns = new Resource$Projects$Locations$Volumes$Luns(this.context); this.snapshots = new Resource$Projects$Locations$Volumes$Snapshots( this.context ); } /** * Get details of a single storage volume. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.volumes.get({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/volumes/my-volume', * }); * console.log(res.data); * * // Example response * // { * // "autoGrownSizeGib": "my_autoGrownSizeGib", * // "currentSizeGib": "my_currentSizeGib", * // "emergencySizeGib": "my_emergencySizeGib", * // "id": "my_id", * // "labels": {}, * // "name": "my_name", * // "remainingSpaceGib": "my_remainingSpaceGib", * // "requestedSizeGib": "my_requestedSizeGib", * // "snapshotAutoDeleteBehavior": "my_snapshotAutoDeleteBehavior", * // "snapshotEnabled": false, * // "snapshotReservationDetail": {}, * // "snapshotSchedulePolicy": "my_snapshotSchedulePolicy", * // "state": "my_state", * // "storageType": "my_storageType" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Volumes$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Volumes$Get, options?: MethodOptions ): GaxiosPromise<Schema$Volume>; get( params: Params$Resource$Projects$Locations$Volumes$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Volumes$Get, options: MethodOptions | BodyResponseCallback<Schema$Volume>, callback: BodyResponseCallback<Schema$Volume> ): void; get( params: Params$Resource$Projects$Locations$Volumes$Get, callback: BodyResponseCallback<Schema$Volume> ): void; get(callback: BodyResponseCallback<Schema$Volume>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Get | BodyResponseCallback<Schema$Volume> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Volume> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Volume> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Volume> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Volume>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Volume>(parameters); } } /** * List storage volumes in a given project and location. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.volumes.list({ * // List filter. * filter: 'placeholder-value', * // Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. * pageSize: 'placeholder-value', * // A token identifying a page of results from the server. * pageToken: 'placeholder-value', * // Required. Parent value for ListVolumesRequest. * parent: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "unreachable": [], * // "volumes": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Volumes$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Volumes$List, options?: MethodOptions ): GaxiosPromise<Schema$ListVolumesResponse>; list( params: Params$Resource$Projects$Locations$Volumes$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Volumes$List, options: MethodOptions | BodyResponseCallback<Schema$ListVolumesResponse>, callback: BodyResponseCallback<Schema$ListVolumesResponse> ): void; list( params: Params$Resource$Projects$Locations$Volumes$List, callback: BodyResponseCallback<Schema$ListVolumesResponse> ): void; list(callback: BodyResponseCallback<Schema$ListVolumesResponse>): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$List | BodyResponseCallback<Schema$ListVolumesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListVolumesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListVolumesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListVolumesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/volumes').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListVolumesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListVolumesResponse>(parameters); } } /** * Update details of a single storage volume. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.volumes.patch({ * // Output only. The resource name of this `Volume`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/volumes/{volume\}` * name: 'projects/my-project/locations/my-location/volumes/my-volume', * // The list of fields to update. The only currently supported fields are: `snapshot_auto_delete_behavior` `snapshot_schedule_policy_name` 'labels' 'requested_size_gib' 'snapshot_enabled' 'snapshot_reservation_detail.reserved_space_percent' * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "autoGrownSizeGib": "my_autoGrownSizeGib", * // "currentSizeGib": "my_currentSizeGib", * // "emergencySizeGib": "my_emergencySizeGib", * // "id": "my_id", * // "labels": {}, * // "name": "my_name", * // "remainingSpaceGib": "my_remainingSpaceGib", * // "requestedSizeGib": "my_requestedSizeGib", * // "snapshotAutoDeleteBehavior": "my_snapshotAutoDeleteBehavior", * // "snapshotEnabled": false, * // "snapshotReservationDetail": {}, * // "snapshotSchedulePolicy": "my_snapshotSchedulePolicy", * // "state": "my_state", * // "storageType": "my_storageType" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Locations$Volumes$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Locations$Volumes$Patch, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; patch( params: Params$Resource$Projects$Locations$Volumes$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Locations$Volumes$Patch, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; patch( params: Params$Resource$Projects$Locations$Volumes$Patch, callback: BodyResponseCallback<Schema$Operation> ): void; patch(callback: BodyResponseCallback<Schema$Operation>): void; patch( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Patch | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } } export interface Params$Resource$Projects$Locations$Volumes$Get extends StandardParameters { /** * Required. Name of the resource. */ name?: string; } export interface Params$Resource$Projects$Locations$Volumes$List extends StandardParameters { /** * List filter. */ filter?: string; /** * Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. */ pageSize?: number; /** * A token identifying a page of results from the server. */ pageToken?: string; /** * Required. Parent value for ListVolumesRequest. */ parent?: string; } export interface Params$Resource$Projects$Locations$Volumes$Patch extends StandardParameters { /** * Output only. The resource name of this `Volume`. Resource names are schemeless URIs that follow the conventions in https://cloud.google.com/apis/design/resource_names. Format: `projects/{project\}/locations/{location\}/volumes/{volume\}` */ name?: string; /** * The list of fields to update. The only currently supported fields are: `snapshot_auto_delete_behavior` `snapshot_schedule_policy_name` 'labels' 'requested_size_gib' 'snapshot_enabled' 'snapshot_reservation_detail.reserved_space_percent' */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$Volume; } export class Resource$Projects$Locations$Volumes$Luns { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Get details of a single storage logical unit number(LUN). * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.volumes.luns.get({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/volumes/my-volume/luns/my-lun', * }); * console.log(res.data); * * // Example response * // { * // "bootLun": false, * // "id": "my_id", * // "multiprotocolType": "my_multiprotocolType", * // "name": "my_name", * // "shareable": false, * // "sizeGb": "my_sizeGb", * // "state": "my_state", * // "storageType": "my_storageType", * // "storageVolume": "my_storageVolume", * // "wwid": "my_wwid" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Volumes$Luns$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Volumes$Luns$Get, options?: MethodOptions ): GaxiosPromise<Schema$Lun>; get( params: Params$Resource$Projects$Locations$Volumes$Luns$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Volumes$Luns$Get, options: MethodOptions | BodyResponseCallback<Schema$Lun>, callback: BodyResponseCallback<Schema$Lun> ): void; get( params: Params$Resource$Projects$Locations$Volumes$Luns$Get, callback: BodyResponseCallback<Schema$Lun> ): void; get(callback: BodyResponseCallback<Schema$Lun>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Luns$Get | BodyResponseCallback<Schema$Lun> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Lun> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Lun> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Lun> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Luns$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Luns$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Lun>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Lun>(parameters); } } /** * List storage volume luns for given storage volume. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.volumes.luns.list({ * // Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. * pageSize: 'placeholder-value', * // A token identifying a page of results from the server. * pageToken: 'placeholder-value', * // Required. Parent value for ListLunsRequest. * parent: 'projects/my-project/locations/my-location/volumes/my-volume', * }); * console.log(res.data); * * // Example response * // { * // "luns": [], * // "nextPageToken": "my_nextPageToken", * // "unreachable": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Volumes$Luns$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Volumes$Luns$List, options?: MethodOptions ): GaxiosPromise<Schema$ListLunsResponse>; list( params: Params$Resource$Projects$Locations$Volumes$Luns$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Volumes$Luns$List, options: MethodOptions | BodyResponseCallback<Schema$ListLunsResponse>, callback: BodyResponseCallback<Schema$ListLunsResponse> ): void; list( params: Params$Resource$Projects$Locations$Volumes$Luns$List, callback: BodyResponseCallback<Schema$ListLunsResponse> ): void; list(callback: BodyResponseCallback<Schema$ListLunsResponse>): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Luns$List | BodyResponseCallback<Schema$ListLunsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListLunsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListLunsResponse> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$ListLunsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Luns$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Luns$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/luns').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListLunsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListLunsResponse>(parameters); } } } export interface Params$Resource$Projects$Locations$Volumes$Luns$Get extends StandardParameters { /** * Required. Name of the resource. */ name?: string; } export interface Params$Resource$Projects$Locations$Volumes$Luns$List extends StandardParameters { /** * Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. */ pageSize?: number; /** * A token identifying a page of results from the server. */ pageToken?: string; /** * Required. Parent value for ListLunsRequest. */ parent?: string; } export class Resource$Projects$Locations$Volumes$Snapshots { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Create a storage volume snapshot in a containing volume. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.volumes.snapshots.create({ * // Required. The volume to snapshot. * parent: 'projects/my-project/locations/my-location/volumes/my-volume', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "createTime": "my_createTime", * // "description": "my_description", * // "id": "my_id", * // "name": "my_name", * // "sizeBytes": "my_sizeBytes", * // "storageVolume": "my_storageVolume" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "createTime": "my_createTime", * // "description": "my_description", * // "id": "my_id", * // "name": "my_name", * // "sizeBytes": "my_sizeBytes", * // "storageVolume": "my_storageVolume" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Projects$Locations$Volumes$Snapshots$Create, options?: MethodOptions ): GaxiosPromise<Schema$VolumeSnapshot>; create( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Create, options: MethodOptions | BodyResponseCallback<Schema$VolumeSnapshot>, callback: BodyResponseCallback<Schema$VolumeSnapshot> ): void; create( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Create, callback: BodyResponseCallback<Schema$VolumeSnapshot> ): void; create(callback: BodyResponseCallback<Schema$VolumeSnapshot>): void; create( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Snapshots$Create | BodyResponseCallback<Schema$VolumeSnapshot> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$VolumeSnapshot> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$VolumeSnapshot> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$VolumeSnapshot> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Snapshots$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Snapshots$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/snapshots').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$VolumeSnapshot>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$VolumeSnapshot>(parameters); } } /** * Deletes a storage volume snapshot for a given volume. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.volumes.snapshots.delete({ * // Required. The name of the snapshot to delete. * name: 'projects/my-project/locations/my-location/volumes/my-volume/snapshots/my-snapshot', * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Projects$Locations$Volumes$Snapshots$Delete, options?: MethodOptions ): GaxiosPromise<Schema$Empty>; delete( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Delete, options: MethodOptions | BodyResponseCallback<Schema$Empty>, callback: BodyResponseCallback<Schema$Empty> ): void; delete( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Delete, callback: BodyResponseCallback<Schema$Empty> ): void; delete(callback: BodyResponseCallback<Schema$Empty>): void; delete( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Snapshots$Delete | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Empty> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Empty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Snapshots$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Snapshots$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$Empty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Empty>(parameters); } } /** * Get details of a single storage volume snapshot. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.volumes.snapshots.get({ * // Required. Name of the resource. * name: 'projects/my-project/locations/my-location/volumes/my-volume/snapshots/my-snapshot', * }); * console.log(res.data); * * // Example response * // { * // "createTime": "my_createTime", * // "description": "my_description", * // "id": "my_id", * // "name": "my_name", * // "sizeBytes": "my_sizeBytes", * // "storageVolume": "my_storageVolume" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Volumes$Snapshots$Get, options?: MethodOptions ): GaxiosPromise<Schema$VolumeSnapshot>; get( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Get, options: MethodOptions | BodyResponseCallback<Schema$VolumeSnapshot>, callback: BodyResponseCallback<Schema$VolumeSnapshot> ): void; get( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Get, callback: BodyResponseCallback<Schema$VolumeSnapshot> ): void; get(callback: BodyResponseCallback<Schema$VolumeSnapshot>): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Snapshots$Get | BodyResponseCallback<Schema$VolumeSnapshot> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$VolumeSnapshot> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$VolumeSnapshot> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$VolumeSnapshot> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Snapshots$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Snapshots$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$VolumeSnapshot>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$VolumeSnapshot>(parameters); } } /** * List storage volume snapshots for given storage volume. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await baremetalsolution.projects.locations.volumes.snapshots.list( * { * // Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. * pageSize: 'placeholder-value', * // A token identifying a page of results from the server. * pageToken: 'placeholder-value', * // Required. Parent value for ListVolumesRequest. * parent: 'projects/my-project/locations/my-location/volumes/my-volume', * } * ); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "unreachable": [], * // "volumeSnapshots": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Locations$Volumes$Snapshots$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Locations$Volumes$Snapshots$List, options?: MethodOptions ): GaxiosPromise<Schema$ListVolumeSnapshotsResponse>; list( params: Params$Resource$Projects$Locations$Volumes$Snapshots$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Locations$Volumes$Snapshots$List, options: | MethodOptions | BodyResponseCallback<Schema$ListVolumeSnapshotsResponse>, callback: BodyResponseCallback<Schema$ListVolumeSnapshotsResponse> ): void; list( params: Params$Resource$Projects$Locations$Volumes$Snapshots$List, callback: BodyResponseCallback<Schema$ListVolumeSnapshotsResponse> ): void; list( callback: BodyResponseCallback<Schema$ListVolumeSnapshotsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Snapshots$List | BodyResponseCallback<Schema$ListVolumeSnapshotsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$ListVolumeSnapshotsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$ListVolumeSnapshotsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$ListVolumeSnapshotsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Snapshots$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Snapshots$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v2/{+parent}/snapshots').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$ListVolumeSnapshotsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$ListVolumeSnapshotsResponse>(parameters); } } /** * Restore a storage volume snapshot to its containing volume. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/baremetalsolution.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const baremetalsolution = google.baremetalsolution('v2'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await baremetalsolution.projects.locations.volumes.snapshots.restoreVolumeSnapshot( * { * // Required. Name of the resource. * volumeSnapshot: * 'projects/my-project/locations/my-location/volumes/my-volume/snapshots/my-snapshot', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * } * ); * console.log(res.data); * * // Example response * // { * // "done": false, * // "error": {}, * // "metadata": {}, * // "name": "my_name", * // "response": {} * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ restoreVolumeSnapshot( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot, options: StreamMethodOptions ): GaxiosPromise<Readable>; restoreVolumeSnapshot( params?: Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot, options?: MethodOptions ): GaxiosPromise<Schema$Operation>; restoreVolumeSnapshot( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; restoreVolumeSnapshot( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot, options: MethodOptions | BodyResponseCallback<Schema$Operation>, callback: BodyResponseCallback<Schema$Operation> ): void; restoreVolumeSnapshot( params: Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot, callback: BodyResponseCallback<Schema$Operation> ): void; restoreVolumeSnapshot( callback: BodyResponseCallback<Schema$Operation> ): void; restoreVolumeSnapshot( paramsOrCallback?: | Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$Operation> | BodyResponseCallback<Readable> ): void | GaxiosPromise<Schema$Operation> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://baremetalsolution.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v2/{+volumeSnapshot}:restoreVolumeSnapshot' ).replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['volumeSnapshot'], pathParams: ['volumeSnapshot'], context: this.context, }; if (callback) { createAPIRequest<Schema$Operation>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$Operation>(parameters); } } } export interface Params$Resource$Projects$Locations$Volumes$Snapshots$Create extends StandardParameters { /** * Required. The volume to snapshot. */ parent?: string; /** * Request body metadata */ requestBody?: Schema$VolumeSnapshot; } export interface Params$Resource$Projects$Locations$Volumes$Snapshots$Delete extends StandardParameters { /** * Required. The name of the snapshot to delete. */ name?: string; } export interface Params$Resource$Projects$Locations$Volumes$Snapshots$Get extends StandardParameters { /** * Required. Name of the resource. */ name?: string; } export interface Params$Resource$Projects$Locations$Volumes$Snapshots$List extends StandardParameters { /** * Requested page size. The server might return fewer items than requested. If unspecified, server will pick an appropriate default. */ pageSize?: number; /** * A token identifying a page of results from the server. */ pageToken?: string; /** * Required. Parent value for ListVolumesRequest. */ parent?: string; } export interface Params$Resource$Projects$Locations$Volumes$Snapshots$Restorevolumesnapshot extends StandardParameters { /** * Required. Name of the resource. */ volumeSnapshot?: string; /** * Request body metadata */ requestBody?: Schema$RestoreVolumeSnapshotRequest; } }
the_stack
import { Component, OnInit } from "@angular/core"; import { PanelExtendMoveBackService } from "../panel-extend-move-back.service"; import { Subscription } from "rxjs"; import { PanelExtendService } from "../panel-extend.service"; import { PanelScopeEnchantmentService } from "../panel-scope-enchantment/panel-scope-enchantment.service"; import { PanelSoulService } from "../panel-soul/panel-soul.service"; import { PanelWidgetModel } from "../panel-widget/model"; import { cloneDeep } from "lodash"; import { debounceTime } from "rxjs/operators"; import { CombinationWidgetModel } from "../panel-scope-enchantment/model"; import { PanelAssistArborService } from "./panel-assist-arbor.service"; import { environment } from "environments/environment"; @Component({ selector: "app-panel-assist-arbor", templateUrl: "./panel-assist-arbor.component.html", styleUrls: ["./panel-assist-arbor.component.scss", "./dropdown.scss"], }) export class PanelAssistArborComponent implements OnInit { public environment = environment; // 订阅本地数据库DB发射过来的数据集 private indexedDBDataRX$: Subscription; // 订阅轮廓值的创建 private profileOuterSphereRX$: Subscription; // 订阅组合组件的轮廓值变化 private combinationValueChangeRX$: Subscription; // 订阅组合 private createComRX$: Subscription; // 订阅打散 private disperseComRX$: Subscription; // 是否允许前进 public get isMove(): boolean { return this.panelExtendMoveBackService.currentMoveBackInfoValue.isMove; } // 是否允许后退 public get isBack(): boolean { return this.panelExtendMoveBackService.currentMoveBackInfoValue.isBack; } // 是否允许设置组合,需要选中多个组件才能创建组合 public get isCombination(): boolean { return this.panelAssistArborService.isCombination; } // 是否允许设置打散,需要备选组件当中有组合元素组件 public get isDisperse(): boolean { return this.panelAssistArborService.isDisperse; } constructor( private readonly panelExtendMoveBackService: PanelExtendMoveBackService, private readonly panelScopeEnchantmentService: PanelScopeEnchantmentService, private readonly panelAssistArborService: PanelAssistArborService, private readonly panelSoulService: PanelSoulService, private readonly panelExtendService: PanelExtendService ) { this.profileOuterSphereRX$ = this.panelScopeEnchantmentService.scopeEnchantmentModel.profileOuterSphere$.subscribe( pro => { if (pro) { this.combinationValueChangeRX$ = pro.valueChange$.pipe(debounceTime(1)).subscribe(() => { const iW = this.panelScopeEnchantmentService.scopeEnchantmentModel.outerSphereInsetWidgetList$ .value; if (Array.isArray(iW)) { iW.forEach(w => { if (w.type == "combination" && Array.isArray(w.autoWidget.content)) { w.autoWidget.content.forEach(cw => { if (cw.profileModel.combinationWidgetData$) { this.handleCombinationAllChildWidgetProportion(cw); } }); } }); } }); } } ); this.createComRX$ = this.panelAssistArborService.launchCreateCombination$.subscribe(() => { this.createCombination(); }); this.disperseComRX$ = this.panelAssistArborService.launchDisperseCombination$.subscribe(() => { this.disperseCombination(); }); } ngOnInit() { this.indexedDBDataRX$ = this.panelExtendMoveBackService.launchDBDataValue$.subscribe(res => { const widgetList = JSON.parse(res.widgetList); if (Array.isArray(widgetList)) { this.panelScopeEnchantmentService.scopeEnchantmentModel.emptyAllProfile(); this.panelExtendService.nextWidgetList(this.panelExtendService.handleFreeItemToPanelWidget(widgetList)); } }); } ngOnDestroy() { if (this.indexedDBDataRX$) this.indexedDBDataRX$.unsubscribe(); if (this.combinationValueChangeRX$) this.combinationValueChangeRX$.unsubscribe(); if (this.profileOuterSphereRX$) this.profileOuterSphereRX$.unsubscribe(); if (this.createComRX$) this.createComRX$.unsubscribe(); if (this.disperseComRX$) this.disperseComRX$.unsubscribe(); } /** * 拉伸组合组件的时候保证其所有子集组件的四个方位比例不变 * 根据childFourProportionObj计算 */ public handleCombinationAllChildWidgetProportion(widget: PanelWidgetModel): void { const widgetCom = widget.profileModel.combinationWidgetData$.value; if (widgetCom && widgetCom.insetProOuterSphereFourProportion) { const fourProp = widgetCom.insetProOuterSphereFourProportion; const combinationPro = widgetCom.combinationRoom; widgetCom.left = fourProp.left * combinationPro.profileModel.width; widgetCom.top = fourProp.top * combinationPro.profileModel.height; widgetCom.width = fourProp.right * combinationPro.profileModel.width - widgetCom.left; widgetCom.height = fourProp.bottom * combinationPro.profileModel.height - widgetCom.top; widget.profileModel.setData({ width: widgetCom.width, height: widgetCom.height, }); widget.addStyleToUltimatelyStyle({ height: `${widget.profileModel.height}px`, width: `${widget.profileModel.width}px`, }); } } /** * 接收前进和后退的回调 */ public handleMoveBack(type: "move" | "back"): void { if (type == "back") { this.panelExtendMoveBackService.acquireBackDBData(); } else if (type == "move") { this.panelExtendMoveBackService.acquireMoveDBData(); } } /** * 根据组合组件的轮廓值变化来计算其所有子集widget组件的轮廓数据 */ public handleCombinationChildWidgetProfileData(combination: PanelWidgetModel): void { const childWidget: Array<PanelWidgetModel> = combination.autoWidget.content; const comPro = combination.profileModel; if (Array.isArray(childWidget)) { childWidget.forEach(w => { const wCom = w.profileModel.combinationWidgetData$.value; if (wCom) { w.profileModel.setData({ rotate: this.panelScopeEnchantmentService.conversionRotateOneCircle( w.profileModel.immobilizationData.rotate + comPro.rotate ), }); /** * 利用圆的公式计算在旋转的时候子集组件的中心点在其对应的椭圆边上 * (x ** 2 ) + (y ** 2) == r ** 2 * 先记录子集组件在以combination的中心点为坐标系圆点计算其对应的坐标 * 半径 radius */ const coordinatesX = wCom.left - comPro.width / 2 + w.profileModel.width / 2; const coordinatesY = comPro.height / 2 - wCom.top - w.profileModel.height / 2; // 根据坐标和角度返回对应的新的坐标 const offsetCoord = this.panelScopeEnchantmentService.conversionRotateNewCoordinates( [coordinatesX, coordinatesY], comPro.rotate ); if (offsetCoord) { w.profileModel.setData({ left: w.profileModel.left + offsetCoord.left, top: w.profileModel.top + offsetCoord.top, }); } wCom.removeInsetProOuterSphereFourProportion(); } }); } } /** * 创建组合 * 创建之前保存原数据到indexedDB */ public createCombination(): void { if (this.isCombination) { this.panelExtendService.launchSaveIndexedDB$.next(); let panelCombination = this.panelSoulService.fixedWidget$.value.find(e => e.type == "combination"); const insetW = this.panelScopeEnchantmentService.scopeEnchantmentModel.outerSphereInsetWidgetList$.value; const profile = this.panelScopeEnchantmentService.scopeEnchantmentModel.valueProfileOuterSphere; if (panelCombination && insetW.length > 1) { panelCombination = cloneDeep(panelCombination); let combinationWidget = new PanelWidgetModel(panelCombination); let awaitInjectWidgetUniqueId: Array<string | number> = []; // 待赋值的组合内组件列表 let awaitInjectWidget: Array<PanelWidgetModel> = this.handleDisperseWidgetList(); // 先赋予组合组件宽高和位置 combinationWidget.profileModel.setData({ left: profile.left, top: profile.top, width: profile.width, height: profile.height, }); insetW.forEach(w => { awaitInjectWidgetUniqueId.push(w.uniqueId); if (w.type != "combination") { awaitInjectWidget.push(w); } }); awaitInjectWidget.forEach(w => { const combinationData = new CombinationWidgetModel(combinationWidget); combinationData.setData({ left: w.profileModel.left - combinationWidget.profileModel.left, top: w.profileModel.top - combinationWidget.profileModel.top, width: w.profileModel.width, height: w.profileModel.height, rotate: w.profileModel.rotate, }); w.profileModel.combinationWidgetData$.next(combinationData); // 计算子集组件在组合组件里的位置比例 w.profileModel.combinationWidgetData$.value.recordInsetProOuterSphereFourProportion(); w.profileModel.recordImmobilizationData(); }); combinationWidget.autoWidget.content = awaitInjectWidget; // 先删除组合组件内的映射组件 this.panelExtendService.deletePanelWidget(awaitInjectWidgetUniqueId); // 再添加组合组件 this.panelExtendService.addPanelWidget([combinationWidget]); // 再选中该组合组件 this.panelScopeEnchantmentService.pushOuterSphereInsetWidget([combinationWidget]); } } } /** * 打散组合 * 同时需要根据角度的不同计算left和top值,使其能够还原到组合前的位置 * 打散之前保存原数据到indexedDB */ public disperseCombination(): void { if (this.isDisperse) { this.panelExtendService.launchSaveIndexedDB$.next(); // 从这些组合当中取出所有widget组件 const allContentWidget = this.handleDisperseWidgetList(); const insetWidget = this.panelScopeEnchantmentService.scopeEnchantmentModel.outerSphereInsetWidgetList$ .value; // 待删除的组合组件的唯一id列表 let comWidgetUniqueId = insetWidget.filter(e => e.type == "combination").map(e => e.uniqueId); // 先删除组合组件 this.panelExtendService.deletePanelWidget(comWidgetUniqueId); // 再添加allContentWidget this.panelExtendService.addPanelWidget(allContentWidget); // 再选中所传的组件列表 this.panelScopeEnchantmentService.pushOuterSphereInsetWidget(allContentWidget); } } /** * 执行打散操作但不选中其轮廓 * 返回所有打散处理完的widget组件 * isAddPro参数表示是否加上差值 */ public handleDisperseWidgetList(): Array<PanelWidgetModel> { const insetWidget = this.panelScopeEnchantmentService.scopeEnchantmentModel.outerSphereInsetWidgetList$.value; let allContentWidget = []; insetWidget.forEach(w => { if (w.type == "combination" && Array.isArray(w.autoWidget.content)) { this.handleCombinationChildWidgetProfileData(w); w.autoWidget.content.forEach((e: PanelWidgetModel) => { allContentWidget.push(e); }); } }); return allContentWidget; } }
the_stack
import { AnnotationMotivation, ExternalResourceType, } from "@iiif/vocabulary/dist-commonjs/"; import { Directory } from "./Directory"; import { dirname, extname } from "path"; import { IConfigJSON } from "./IConfigJSON"; import { join, basename } from "path"; import { promise as glob } from "glob-promise"; import { TypeFormat } from "./TypeFormat"; import chalk from "chalk"; import config from "./config.json"; import ffprobe from "ffprobe"; import ffprobeStatic from "ffprobe-static"; import fs from "fs"; import isurl from "is-url"; import jsonfile from "jsonfile"; import labelBoilerplate from "./boilerplate/label.json"; import thumbnailBoilerplate from "./boilerplate/thumbnail.json"; import urljoin from "url-join"; import yaml from "js-yaml"; const sharp = require("sharp"); const _config: IConfigJSON = config; export const compare = (a: string, b: string): number => { const collator: Intl.Collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base", }); return collator.compare(a, b); }; export const normaliseType = (type: string): string => { type = type.toLowerCase(); if (type.indexOf(":") !== -1) { const split: string[] = type.split(":"); return split[1]; } return type; }; export const getTypeByExtension = ( motivation: string, extension: string ): string | null => { motivation = normaliseType(motivation); const m: any = _config.annotation.motivations[motivation]; if (m) { if (m[extension] && m[extension].length) { return m[extension][0].type; } } return null; }; export const getFormatByExtension = ( motivation: string, extension: string ): string | null => { motivation = normaliseType(motivation); const m: any = _config.annotation.motivations[motivation]; if (m) { if (m[extension] && m[extension].length) { return m[extension][0].format; } } return null; }; export const getFormatByExtensionAndType = ( motivation: string, extension: string, type: string ): string | null => { motivation = normaliseType(motivation); const m: any = _config.annotation.motivations[motivation]; if (m) { if (m[extension] && m[extension].length) { const typeformats: TypeFormat[] = m[extension]; for (let i = 0; i < typeformats.length; i++) { const typeformat: TypeFormat = typeformats[i]; if (typeformat.type === type) { return typeformat.format; } } } } return null; }; export const getTypeByFormat = ( motivation: string, format: string ): string | null => { motivation = normaliseType(motivation); const m: any = _config.annotation.motivations[motivation]; if (m) { for (const extension in m) { const typeformats: TypeFormat[] = m[extension]; for (let i = 0; i < typeformats.length; i++) { const typeformat: TypeFormat = typeformats[i]; if (typeformat.format === format) { return typeformat.type; } } } } return null; }; export const getFormatByType = ( motivation: string, type: string ): string | null => { motivation = normaliseType(motivation); const m: any = _config.annotation.motivations[motivation]; // only able to categorically say there's a matching format // if there's a single extension with a single type if (m) { if (Object.keys(m).length === 1) { const typeformats: TypeFormat[] = m[Object.keys(m)[0]]; if (typeformats.length === 1) { return typeformats[0].format; } } } return null; }; export const timeout = (ms: number): Promise<void> => { return new Promise((resolve) => setTimeout(resolve, ms)); }; export const cloneJson = (json: any): any => { return JSON.parse(JSON.stringify(json)); }; export const formatMetadata = (metadata: any): any => { const formattedMetadata: any[] = []; for (let key in metadata) { if (metadata.hasOwnProperty(key)) { const value: string = metadata[key]; const item: any = {}; item.label = getLabel(key); item.value = getLabel(value); formattedMetadata.push(item); } } return formattedMetadata; }; // If filePath is: // C://Users/edsilv/github/edsilv/biiif-workshop/collection/_abyssinian/thumb.jpeg // and 'collection' has been replaced by the top-level virtual name 'virtualname' // it should return: // C://Users/edsilv/github/edsilv/biiif-workshop/virtualname/_abyssinian/thumb.jpeg // virtual names are needed when using dat or ipfs ids as the root directory. export const getVirtualFilePath = ( filePath: string, directory: Directory ): string => { // walk up directory parents building the realPath and virtualPath array as we go. // at the top level directory, use the real name for realPath and the virtual name for virtualPath. // reverse the arrays and join with a '/'. // replace the realPath section of filePath with virtualPath. let realPath: string[] = [basename(filePath)]; let virtualPath: string[] = [basename(filePath)]; while (directory) { const realName: string = basename(directory.directoryFilePath); const virtualName: string = directory.virtualName || realName; realPath.push(realName); virtualPath.push(virtualName); directory = directory.parentDirectory; } realPath = realPath.reverse(); virtualPath = virtualPath.reverse(); const realPathString: string = realPath.join("/"); const virtualPathString: string = virtualPath.join("/"); filePath = normaliseFilePath(filePath); filePath = filePath.replace(realPathString, virtualPathString); return filePath; }; export const isJsonFile = (path: string): boolean => { return extname(path) === ".json"; }; export const isDirectory = (path: string): boolean => { return fs.lstatSync(path).isDirectory(); }; export const getThumbnail = async ( json: any, directory: Directory, filePath?: string, ): Promise<void> => { let fp: string = filePath || directory.directoryFilePath; fp = normaliseFilePath(fp); const thumbnailPattern: string = fp + "/thumb.*"; const thumbnails: string[] = await glob(thumbnailPattern); if (thumbnails.length) { // there's alrady a thumbnail in the directory, add it to the canvas log(`found thumbnail for: ${fp}`); let thumbnail: string = thumbnails[0]; const thumbnailJson: any = cloneJson(thumbnailBoilerplate); const virtualFilePath = getVirtualFilePath(thumbnail, directory); thumbnailJson[0].id = mergePaths( directory.url, virtualFilePath, ); json.thumbnail = thumbnailJson; } else { // there isn't a thumbnail in the directory, so we'll need to generate it. // generate thumbnail if (json.items && json.items.length && json.items[0].items) { // find an annotation with a painting motivation of type image. const items: any[] = json.items[0].items; for (let i = 0; i < items.length; i++) { const item: any = items[i]; const body: any = item.body; if ( body && item.motivation === normaliseType(AnnotationMotivation.PAINTING) ) { // is it an image? (without an info.json) if ( body.type.toLowerCase() === ExternalResourceType.IMAGE && !isJsonFile(body.id) ) { let imageName: string = body.id.substr(body.id.lastIndexOf("/")); if (imageName.includes("#")) { imageName = imageName.substr(0, imageName.lastIndexOf("#")); } const imagePath: string = normaliseFilePath(join(fp, imageName)); let pathToThumb: string = normaliseFilePath( join(dirname(imagePath), "thumb.jpg") ); // todo: this currently assumes that the image to generate a thumb from is within the directory, // but it may be in an assets folder and painted by a custom annotation. // see canvas-with-dimensions-manifest.js if (await fileExists(imagePath)) { //const image: any = await Jimp.read(imagePath); //const thumb: any = image.clone(); // write image buffer to disk for testing // image.getBuffer(Jimp.AUTO, (err, buffer) => { // const arrBuffer = [...buffer]; // const pathToBuffer: string = imagePath.substr(0, imagePath.lastIndexOf('/')) + '/buffer.txt'; // fs.writeFile(pathToBuffer, arrBuffer); // }); //thumb.cover(_config.thumbnails.width, _config.thumbnails.height); //thumb.resize(_config.thumbnails.width, Jimp.AUTO); //pathToThumb += image.getExtension(); // a thumbnail may already exist at this path (when generating from a flat collection of images) const thumbExists: boolean = await fileExists(pathToThumb); if (!thumbExists) { try { await sharp(imagePath, { limitInputPixels: true, }) .resize({ width: _config.thumbnails.width, height: _config.thumbnails.height, fit: sharp.fit.cover, }) .toFormat("jpeg") .toFile(pathToThumb); // thumb.write(pathToThumb, () => { log(`generated thumbnail for: ${fp}`); } catch { warn(`unable to generate thumbnail for: ${fp}`); } } else { log(`found thumbnail for: ${fp}`); } } else { // placeholder img path pathToThumb += "jpg"; } const thumbnailJson: any = cloneJson(thumbnailBoilerplate); // const virtualPath: string = getVirtualFilePath( // pathToThumb, // directory // ); // const mergedPath: string = mergePaths(directory.url, virtualPath); // thumbnailJson[0].id = mergedPath; let path = getThumbnailUrl(directory); thumbnailJson[0].id = path; json.thumbnail = thumbnailJson; } } } } } }; const getThumbnailUrl = (directory: Directory) => { let path: string = ""; while (directory) { // if the directory is a manifest and doesn't have a parent collection if (directory.isManifest && (!directory.parentDirectory || !directory.parentDirectory.isCollection)) { break; } if (directory.isCollection && !directory.parentDirectory) { break; } const name = basename(directory.directoryFilePath); path = urljoin(path, name); directory = directory.parentDirectory; // todo: keep going unless you reach a manifest directory with no collection directory parent // if (directory.parentDirectory && directory.parentDirectory.isManifest) { // break; // } else { // } } return urljoin(directory.url.href, path, "thumb.jpg"); } export const getLabel = (value: string): any => { const labelJson: any = cloneJson(labelBoilerplate); labelJson["@none"].push(value); return labelJson; }; export const getFileDimensions = async ( type: string, file: string, canvasJson: any, annotationJson: any ): Promise<void> => { log(`getting file dimensions for: ${file}`); if (!isJsonFile(file)) { switch (type.toLowerCase()) { // if it's an image, get the width and height and add to the annotation body and canvas case ExternalResourceType.IMAGE: try { const image: any = await sharp(file, { limitInputPixels: true, }).metadata(); const width: number = image.width; const height: number = image.height; canvasJson.width = Math.max(canvasJson.width || 0, width); canvasJson.height = Math.max(canvasJson.height || 0, height); annotationJson.body.width = width; annotationJson.body.height = height; } catch (e) { warn(`getting file dimensions failed for: ${file}`); } break; // if it's a sound, get the duration and add to the canvas case ExternalResourceType.SOUND: case ExternalResourceType.VIDEO: try { const info: any = await ffprobe(file, { path: ffprobeStatic.path }); if (info && info.streams && info.streams.length) { const duration: number = Number(info.streams[0].duration); canvasJson.duration = duration; } } catch (error) { warn(`ffprobe couldn't load ${file}`); } break; } } }; export const generateImageTiles = async ( image: string, url: string, directoryName: string, directory: string, annotationJson: any ): Promise<void> => { try { log(`generating image tiles for: ${image}`); const id: string = urljoin(url, directoryName, "+tiles"); annotationJson.body.service = [ { "@id": id, "@type": "ImageService2", profile: "http://iiif.io/api/image/2/level2.json", }, ]; await sharp(image, { limitInputPixels: true, }) .tile({ layout: "iiif", id: urljoin(url, directoryName), }) .toFile(join(directory, "+tiles")); } catch { warn(`generating image tiles failed for: ${image}`); } }; /* merge these two example paths: url: http://test.com/collection/manifest filePath: c:/user/documents/collection/manifest/_canvas/thumb.png into: http://test.com/collection/manifest/_canvas/thumb.png */ export const mergePaths = (url: URL, filePath: string): string => { // split the url (minus origin) and filePath into arrays // ['collection', 'manifest'] // ['c:', 'user', 'documents', 'collection', 'manifest', '_canvas', 'thumb.jpg'] // walk backwards through the filePath array adding to the newPath array until the last item of the url array is found. // then while the next url item matches the next filePath item, add it to newPath. // the final path is the url origin plus a reversed newPath joined with a '/' let origin = url.origin; if (url.protocol === "dat:") { origin = "dat://"; } const urlParts = getUrlParts(url); filePath = normaliseFilePath(filePath); const fileParts: string[] = filePath.split("/"); let newPath: string[] = []; // if there's a single root folder and none of the file path matches if (urlParts.length === 1 && !fileParts.includes(urlParts[0])) { newPath.push(fileParts[fileParts.length - 1]); newPath.push(urlParts[0]); } else { for (let f = fileParts.length - 1; f >= 0; f--) { const filePart: string = fileParts[f]; newPath.push(filePart); if (filePart === urlParts[urlParts.length - 1]) { if (urlParts.length > 1) { for (let u = urlParts.length - 2; u >= 0; u--) { f--; if (fileParts[f] === urlParts[u]) { newPath.push(fileParts[f]); } else { newPath.push(urlParts[u]); } } } break; } } } let id: string = urljoin(origin, ...newPath.reverse()); return id; }; export const normaliseFilePath = (filePath: string): string => { return filePath.replace(/\\/g, "/").replace(/\/\//g, "/"); }; export const getUrlParts = (url: URL): string[] => { let origin: string = url.origin; let urlParts: string[]; let href: string = url.href; if (href.endsWith("/")) { href = href.slice(0, -1); } if (url.protocol === "dat:") { origin = "dat://"; urlParts = href.replace(origin, "").split("/"); } else { urlParts = href.replace(origin + "/", "").split("/"); } return urlParts; }; export const readJson = (path: string): Promise<string> => { return new Promise<string>((resolve, reject) => { jsonfile.readFile(path, (err, json) => { if (err) reject(err); else resolve(json); }); }); }; export const writeJson = (path: string, json: string): Promise<void> => { return new Promise<void>((resolve, reject) => { fs.writeFile(path, json, (err) => { if (err) reject(err); else resolve(); }); }); }; export const readYml = (path: string): Promise<string> => { return new Promise<string>((resolve, reject) => { try { const doc = yaml.load(fs.readFileSync(path, "utf8")); resolve(doc); } catch (e) { reject(e); } }); }; export const fileExists = (path: string): Promise<boolean> => { return new Promise<boolean>((resolve, reject) => { const exists: boolean = fs.existsSync(path); resolve(exists); }); }; export const hasManifestsYml = (path: string): Promise<boolean> => { return new Promise<boolean>((resolve, reject) => { const manifestsPath: string = join(path, "manifests.yml"); fileExists(manifestsPath).then((exists) => { resolve(exists); }); }); }; export const isURL = (path: string): boolean => { return isurl(path); }; export const log = (message: string): void => { console.log(chalk.green(message)); }; export const warn = (message: string): void => { console.warn(chalk.yellow(message)); }; export const error = (message: string): void => { console.warn(chalk.red(message)); };
the_stack
import * as _ from 'lodash'; import * as setProtocolUtils from 'set-protocol-utils'; import { Address } from 'set-protocol-utils'; import { CoreContract, CoreMockContract, CTokenExchangeIssuanceModuleContract, ExchangeIssuanceModuleContract, OracleWhiteListContract, RebalancingSetCTokenExchangeIssuanceModuleContract, RebalancingSetCTokenIssuanceModuleContract, RebalancingSetExchangeIssuanceModuleContract, RebalancingSetIssuanceModuleContract, RebalanceAuctionModuleContract, RebalanceAuctionModuleMockContract, RebalancingSetTokenContract, RebalancingSetTokenFactoryContract, RebalancingSetTokenV2FactoryContract, RebalancingSetTokenV3FactoryContract, SetTokenContract, SetTokenFactoryContract, TransferProxyContract, VaultContract, WethMockContract, WhiteListContract, } from '../contracts'; import { BigNumber } from 'bignumber.js'; import { DEFAULT_GAS, DEFAULT_REBALANCING_MINIMUM_NATURAL_UNIT, DEFAULT_REBALANCING_MAXIMUM_NATURAL_UNIT, ONE_DAY_IN_SECONDS, } from '../constants'; import { extractNewSetTokenAddressFromLogs } from '../contract_logs/core'; import { getWeb3, getContractInstance, importArtifactsFromSource, linkLibrariesToDeploy } from '../web3Helper'; const web3 = getWeb3(); const Bytes32Library = importArtifactsFromSource('Bytes32Library'); const CommonValidationsLibrary = importArtifactsFromSource('CommonValidationsLibrary'); const Core = importArtifactsFromSource('Core'); const CoreIssuanceLibrary = importArtifactsFromSource('CoreIssuanceLibrary'); const CoreMock = importArtifactsFromSource('CoreMock'); const CTokenExchangeIssuanceModule = importArtifactsFromSource('CTokenExchangeIssuanceModule'); const ERC20Wrapper = importArtifactsFromSource('ERC20Wrapper'); const ExchangeIssuanceModule = importArtifactsFromSource('ExchangeIssuanceModule'); const FactoryUtilsLibrary = importArtifactsFromSource('FactoryUtilsLibrary'); const OracleWhiteList = importArtifactsFromSource('OracleWhiteList'); const RebalancingSetCTokenExchangeIssuanceModule = importArtifactsFromSource( 'RebalancingSetCTokenExchangeIssuanceModule' ); const RebalancingSetCTokenIssuanceModule = importArtifactsFromSource('RebalancingSetCTokenIssuanceModule'); const RebalancingSetExchangeIssuanceModule = importArtifactsFromSource('RebalancingSetExchangeIssuanceModule'); const RebalancingSetIssuanceModule = importArtifactsFromSource('RebalancingSetIssuanceModule'); const RebalanceAuctionModule = importArtifactsFromSource('RebalanceAuctionModule'); const RebalanceAuctionModuleMock = importArtifactsFromSource('RebalanceAuctionModuleMock'); const RebalancingSetTokenFactory = importArtifactsFromSource('RebalancingSetTokenFactory'); const RebalancingSetTokenV2Factory = importArtifactsFromSource('RebalancingSetTokenV2Factory'); const RebalancingSetTokenV3Factory = importArtifactsFromSource('RebalancingSetTokenV3Factory'); const SetToken = importArtifactsFromSource('SetToken'); const SetTokenFactory = importArtifactsFromSource('SetTokenFactory'); const SetTokenLibrary = importArtifactsFromSource('SetTokenLibrary'); const FailAuctionLibrary = importArtifactsFromSource('FailAuctionLibrary'); const PlaceBidLibrary = importArtifactsFromSource('PlaceBidLibrary'); const ProposeLibrary = importArtifactsFromSource('ProposeLibrary'); const SettleRebalanceLibrary = importArtifactsFromSource('SettleRebalanceLibrary'); const StartRebalanceLibrary = importArtifactsFromSource('StartRebalanceLibrary'); const TransferProxy = importArtifactsFromSource('TransferProxy'); const Vault = importArtifactsFromSource('Vault'); const WhiteList = importArtifactsFromSource('WhiteList'); declare type CoreLikeContract = CoreMockContract | CoreContract; const { SetProtocolTestUtils: SetTestUtils, SetProtocolUtils: SetUtils } = setProtocolUtils; const setTestUtils = new SetTestUtils(web3); export class CoreHelper { private _tokenOwnerAddress: Address; private _contractOwnerAddress: Address; constructor(tokenOwnerAddress: Address, contractOwnerAddress: Address) { this._tokenOwnerAddress = tokenOwnerAddress; this._contractOwnerAddress = contractOwnerAddress; } /* ============ Deployment ============ */ public async deployTransferProxyAsync( from: Address = this._tokenOwnerAddress ): Promise<TransferProxyContract> { await linkLibrariesToDeploy(TransferProxy, [ERC20Wrapper], this._tokenOwnerAddress); const truffleTransferProxy = await TransferProxy.new( { from, gas: DEFAULT_GAS }, ); return new TransferProxyContract( getContractInstance(truffleTransferProxy), { from, gas: DEFAULT_GAS }, ); } public async deployVaultAsync( from: Address = this._tokenOwnerAddress ): Promise<VaultContract> { await linkLibrariesToDeploy(Vault, [ERC20Wrapper], this._tokenOwnerAddress); const truffleVault = await Vault.new( { from }, ); return new VaultContract( getContractInstance(truffleVault), { from, gas: DEFAULT_GAS }, ); } public async deploySetTokenFactoryAsync( coreAddress: Address, from: Address = this._tokenOwnerAddress ): Promise<SetTokenFactoryContract> { await linkLibrariesToDeploy(SetTokenFactory, [CommonValidationsLibrary, Bytes32Library], this._tokenOwnerAddress); const truffleSetTokenFactory = await SetTokenFactory.new( coreAddress, { from }, ); return new SetTokenFactoryContract( getContractInstance(truffleSetTokenFactory), { from, gas: DEFAULT_GAS }, ); } public async deployRebalancingSetTokenFactoryAsync( coreAddress: Address, componentWhitelistAddress: Address, minimumRebalanceInterval: BigNumber = ONE_DAY_IN_SECONDS, minimumProposalPeriod: BigNumber = ONE_DAY_IN_SECONDS, minimumTimeToPivot: BigNumber = ONE_DAY_IN_SECONDS.div(4), maximumTimeToPivot: BigNumber = ONE_DAY_IN_SECONDS.mul(3), minimumNaturalUnit: BigNumber = DEFAULT_REBALANCING_MINIMUM_NATURAL_UNIT, maximumNaturalUnit: BigNumber = DEFAULT_REBALANCING_MAXIMUM_NATURAL_UNIT, from: Address = this._tokenOwnerAddress ): Promise<RebalancingSetTokenFactoryContract> { await this.linkRebalancingLibrariesAsync(RebalancingSetTokenFactory); const truffleTokenFactory = await RebalancingSetTokenFactory.new( coreAddress, componentWhitelistAddress, minimumRebalanceInterval, minimumProposalPeriod, minimumTimeToPivot, maximumTimeToPivot, minimumNaturalUnit, maximumNaturalUnit, { from }, ); return new RebalancingSetTokenFactoryContract( getContractInstance(truffleTokenFactory), { from, gas: DEFAULT_GAS }, ); } public async deployRebalancingSetTokenV2FactoryAsync( coreAddress: Address, componentWhitelistAddress: Address, liquidatorWhitelistAddress: Address, feeCalculatorWhitelistAddress: Address, minimumRebalanceInterval: BigNumber = ONE_DAY_IN_SECONDS, minimumFailRebalancePeriod: BigNumber = ONE_DAY_IN_SECONDS, maximumFailRebalancePeriod: BigNumber = ONE_DAY_IN_SECONDS.mul(30), minimumNaturalUnit: BigNumber = DEFAULT_REBALANCING_MINIMUM_NATURAL_UNIT, maximumNaturalUnit: BigNumber = DEFAULT_REBALANCING_MAXIMUM_NATURAL_UNIT, from: Address = this._tokenOwnerAddress ): Promise<RebalancingSetTokenV2FactoryContract> { await this.linkRebalancingLibrariesAsync(RebalancingSetTokenV2Factory); const truffleTokenFactory = await RebalancingSetTokenV2Factory.new( coreAddress, componentWhitelistAddress, liquidatorWhitelistAddress, feeCalculatorWhitelistAddress, minimumRebalanceInterval, minimumFailRebalancePeriod, maximumFailRebalancePeriod, minimumNaturalUnit, maximumNaturalUnit, { from }, ); return new RebalancingSetTokenV2FactoryContract( getContractInstance(truffleTokenFactory), { from, gas: DEFAULT_GAS }, ); } public async deployRebalancingSetTokenV3FactoryAsync( coreAddress: Address, componentWhitelistAddress: Address, liquidatorWhitelistAddress: Address, feeCalculatorWhitelistAddress: Address, minimumRebalanceInterval: BigNumber = ONE_DAY_IN_SECONDS, minimumFailRebalancePeriod: BigNumber = ONE_DAY_IN_SECONDS, maximumFailRebalancePeriod: BigNumber = ONE_DAY_IN_SECONDS.mul(30), minimumNaturalUnit: BigNumber = DEFAULT_REBALANCING_MINIMUM_NATURAL_UNIT, maximumNaturalUnit: BigNumber = DEFAULT_REBALANCING_MAXIMUM_NATURAL_UNIT, from: Address = this._tokenOwnerAddress ): Promise<RebalancingSetTokenV3FactoryContract> { await linkLibrariesToDeploy( RebalancingSetTokenV3Factory, [FactoryUtilsLibrary, Bytes32Library], this._tokenOwnerAddress ); const truffleTokenFactory = await RebalancingSetTokenV3Factory.new( coreAddress, componentWhitelistAddress, liquidatorWhitelistAddress, feeCalculatorWhitelistAddress, minimumRebalanceInterval, minimumFailRebalancePeriod, maximumFailRebalancePeriod, minimumNaturalUnit, maximumNaturalUnit, { from }, ); return new RebalancingSetTokenV3FactoryContract( getContractInstance(truffleTokenFactory), { from, gas: DEFAULT_GAS }, ); } public async deploySetTokenAsync( factory: Address, componentAddresses: Address[], units: BigNumber[], naturalUnit: BigNumber, name: string = 'Set Token', symbol: string = 'SET', from: Address = this._tokenOwnerAddress ): Promise<SetTokenContract> { await linkLibrariesToDeploy(SetToken, [CommonValidationsLibrary], this._tokenOwnerAddress); // Creates but does not register the Set with Core as enabled const truffleSetToken = await SetToken.new( factory, componentAddresses, units, naturalUnit, name, symbol, { from, gas: DEFAULT_GAS }, ); const setToken = new SetTokenContract( getContractInstance(truffleSetToken), { from, gas: DEFAULT_GAS }, ); return setToken; } public async deployCoreAndDependenciesAsync( from: Address = this._tokenOwnerAddress ): Promise<CoreContract> { const transferProxy = await this.deployTransferProxyAsync(); const vault = await this.deployVaultAsync(); return this.deployCoreAsync(transferProxy, vault, from); } public async deployCoreAsync( transferProxy: TransferProxyContract, vault: VaultContract, from: Address = this._tokenOwnerAddress ): Promise<CoreContract> { const libraries = [CoreIssuanceLibrary, CommonValidationsLibrary, SetTokenLibrary]; await linkLibrariesToDeploy(Core, libraries, this._tokenOwnerAddress); const truffleCore = await Core.new( transferProxy.address, vault.address, { from }, ); return new CoreContract( getContractInstance(truffleCore), { from, gas: DEFAULT_GAS }, ); } public async deployCoreMockAsync( transferProxy: TransferProxyContract, vault: VaultContract, from: Address = this._tokenOwnerAddress ): Promise<CoreMockContract> { const libraries = [CoreIssuanceLibrary, CommonValidationsLibrary, SetTokenLibrary]; await linkLibrariesToDeploy(CoreMock, libraries, this._tokenOwnerAddress); const truffleCore = await CoreMock.new( transferProxy.address, vault.address, { from }, ); return new CoreMockContract( getContractInstance(truffleCore), { from, gas: DEFAULT_GAS }, ); } public async deployWhiteListAsync( initialAddresses: Address[] = [], from: Address = this._tokenOwnerAddress ): Promise<WhiteListContract> { const truffleWhiteList = await WhiteList.new( initialAddresses, { from }, ); return new WhiteListContract( getContractInstance(truffleWhiteList), { from, gas: DEFAULT_GAS }, ); } public async deployOracleWhiteListAsync( initialTokenAddresses: Address[] = [], initialOracleAddresses: Address[] = [], from: Address = this._tokenOwnerAddress ): Promise<OracleWhiteListContract> { const truffleWhiteList = await OracleWhiteList.new( initialTokenAddresses, initialOracleAddresses, { from }, ); return new OracleWhiteListContract( getContractInstance(truffleWhiteList), { from, gas: DEFAULT_GAS }, ); } public async deployRebalanceAuctionModuleAsync( core: CoreLikeContract, vault: VaultContract, from: Address = this._tokenOwnerAddress ): Promise<RebalanceAuctionModuleContract> { const truffleRebalanceAuctionModule = await RebalanceAuctionModule.new( core.address, vault.address, { from }, ); return new RebalanceAuctionModuleContract( getContractInstance(truffleRebalanceAuctionModule), { from, gas: DEFAULT_GAS }, ); } public async deployRebalanceAuctionModuleMockAsync( core: CoreLikeContract, vault: VaultContract, from: Address = this._tokenOwnerAddress ): Promise<RebalanceAuctionModuleMockContract> { const truffleRebalanceAuctionModuleMock = await RebalanceAuctionModuleMock.new( core.address, vault.address, { from }, ); return new RebalanceAuctionModuleMockContract( getContractInstance(truffleRebalanceAuctionModuleMock), { from, gas: DEFAULT_GAS }, ); } public async deployExchangeIssuanceModuleAsync( core: CoreLikeContract, vault: VaultContract, from: Address = this._tokenOwnerAddress ): Promise<ExchangeIssuanceModuleContract> { await linkLibrariesToDeploy(ExchangeIssuanceModule, [SetTokenLibrary], this._tokenOwnerAddress); const truffleExchangeIssuanceModule = await ExchangeIssuanceModule.new( core.address, vault.address, { from }, ); return new ExchangeIssuanceModuleContract( getContractInstance(truffleExchangeIssuanceModule), { from, gas: DEFAULT_GAS }, ); } public async deployCTokenExchangeIssuanceModuleAsync( core: Address, vault: Address, transferProxy: Address, cTokenWhiteList: Address, from: Address = this._tokenOwnerAddress ): Promise<CTokenExchangeIssuanceModuleContract> { await linkLibrariesToDeploy(CTokenExchangeIssuanceModule, [ERC20Wrapper, SetTokenLibrary], this._tokenOwnerAddress); const truffleCTokenExchangeIssuanceModule = await CTokenExchangeIssuanceModule.new( core, vault, transferProxy, cTokenWhiteList, { from }, ); return new CTokenExchangeIssuanceModuleContract( getContractInstance(truffleCTokenExchangeIssuanceModule), { from, gas: DEFAULT_GAS }, ); } public async deployRebalancingSetCTokenExchangeIssuanceModuleAsync( core: Address, transferProxy: Address, exchangeIssuanceModule: Address, wrappedEther: Address, vault: Address, cTokenWhiteList: Address, from: Address = this._tokenOwnerAddress ): Promise<RebalancingSetCTokenExchangeIssuanceModuleContract> { await linkLibrariesToDeploy(RebalancingSetCTokenExchangeIssuanceModule, [ERC20Wrapper], this._tokenOwnerAddress); const truffleModule = await RebalancingSetCTokenExchangeIssuanceModule.new( core, transferProxy, exchangeIssuanceModule, wrappedEther, vault, cTokenWhiteList, { from }, ); return new RebalancingSetCTokenExchangeIssuanceModuleContract( getContractInstance(truffleModule), { from, gas: DEFAULT_GAS }, ); } public async deployRebalancingSetCTokenIssuanceModuleAsync( core: Address, vault: Address, transferProxy: Address, weth: Address, cTokenWhiteList: Address, from: Address = this._tokenOwnerAddress ): Promise<RebalancingSetCTokenIssuanceModuleContract> { await linkLibrariesToDeploy(RebalancingSetCTokenIssuanceModule, [ERC20Wrapper], this._tokenOwnerAddress); const truffleModule = await RebalancingSetCTokenIssuanceModule.new( core, vault, transferProxy, weth, cTokenWhiteList, { from }, ); return new RebalancingSetCTokenIssuanceModuleContract( getContractInstance(truffleModule), { from, gas: DEFAULT_GAS }, ); } public async deployRebalancingSetExchangeIssuanceModuleAsync( core: Address, transferProxy: Address, exchangeIssuanceModule: Address, wrappedEther: Address, vault: Address, from: Address = this._contractOwnerAddress ): Promise<RebalancingSetExchangeIssuanceModuleContract> { await linkLibrariesToDeploy(RebalancingSetExchangeIssuanceModule, [ERC20Wrapper], this._tokenOwnerAddress); const payableExchangeIssuanceContract = await RebalancingSetExchangeIssuanceModule.new( core, transferProxy, exchangeIssuanceModule, wrappedEther, vault, { from }, ); return new RebalancingSetExchangeIssuanceModuleContract( getContractInstance(payableExchangeIssuanceContract), { from }, ); } public async deployRebalancingSetIssuanceModuleAsync( core: CoreLikeContract, vault: VaultContract, transferProxy: TransferProxyContract, weth: WethMockContract, from: Address = this._tokenOwnerAddress ): Promise<RebalancingSetIssuanceModuleContract> { await linkLibrariesToDeploy(RebalancingSetIssuanceModule, [ERC20Wrapper], this._tokenOwnerAddress); const truffleModule = await RebalancingSetIssuanceModule.new( core.address, vault.address, transferProxy.address, weth.address, { from }, ); return new RebalancingSetIssuanceModuleContract( getContractInstance(truffleModule), { from, gas: DEFAULT_GAS }, ); } public async linkRebalancingLibrariesAsync( contract: any, ): Promise<void> { const libraries = [ ProposeLibrary, StartRebalanceLibrary, PlaceBidLibrary, SettleRebalanceLibrary, FailAuctionLibrary, Bytes32Library, ]; await linkLibrariesToDeploy(contract, libraries, this._tokenOwnerAddress); } /* ============ CoreAdmin Extension ============ */ public async addFactoryAsync( core: CoreLikeContract, setTokenFactory: SetTokenFactoryContract | RebalancingSetTokenFactoryContract, from: Address = this._contractOwnerAddress, ) { await core.addFactory.sendTransactionAsync( setTokenFactory.address, { from } ); } public async addModuleAsync( core: CoreLikeContract, moduleAddress: Address, from: Address = this._contractOwnerAddress, ) { await core.addModule.sendTransactionAsync( moduleAddress, { from }, ); } /* ============ Authorizable ============ */ public async setDefaultStateAndAuthorizationsAsync( core: CoreLikeContract, vault: VaultContract, transferProxy: TransferProxyContract, setTokenFactory: SetTokenFactoryContract, from: Address = this._tokenOwnerAddress, ) { this.addAuthorizationAsync(vault, core.address); this.addAuthorizationAsync(transferProxy, core.address); await core.addFactory.sendTransactionAsync( setTokenFactory.address, { from }, ); } public async addAuthorizationAsync( contract: any, toAuthorize: Address, from: Address = this._contractOwnerAddress ) { await contract.addAuthorizedAddress.sendTransactionAsync( toAuthorize, { from }, ); } /* ============ Vault ============ */ public async incrementAccountBalanceAsync( vault: VaultContract, account: Address, token: Address, quantity: BigNumber, from: Address = this._contractOwnerAddress, ) { await vault.incrementTokenOwner.sendTransactionAsync( token, account, quantity, { from }, ); } public async getVaultBalancesForTokensForOwner( tokens: Address[], vault: VaultContract, owner: Address ): Promise<BigNumber[]> { const balancePromises = _.map(tokens, address => vault.balances.callAsync(address, owner)); let balances: BigNumber[]; await Promise.all(balancePromises).then(fetchedTokenBalances => { balances = fetchedTokenBalances; }); return balances; } /* ============ WhiteList ============ */ public async addTokensToWhiteList( tokenAddresses: Address[], whiteList: WhiteListContract, from: Address = this._contractOwnerAddress, ): Promise<void> { for (let i = 0; i < tokenAddresses.length; i++) { await this.addTokenToWhiteList(tokenAddresses[i], whiteList); } } public async addTokenToWhiteList( address: Address, whiteList: WhiteListContract, from: Address = this._contractOwnerAddress, ): Promise<void> { const isWhiteListed = await whiteList.whiteList.callAsync(address); if (!isWhiteListed) { await whiteList.addAddress.sendTransactionAsync( address, { from }, ); } } public async addAddressToWhiteList( address: Address, whiteList: WhiteListContract, from: Address = this._contractOwnerAddress, ): Promise<void> { await whiteList.addAddress.sendTransactionAsync( address, { from }, ); } /* ============ CoreFactory Extension ============ */ public async createSetTokenAsync( core: CoreLikeContract, factory: Address, componentAddresses: Address[], units: BigNumber[], naturalUnit: BigNumber, name: string = 'Set Token', symbol: string = 'SET', callData: string = '0x0', from: Address = this._tokenOwnerAddress, ): Promise<SetTokenContract> { const encodedName = SetUtils.stringToBytes(name); const encodedSymbol = SetUtils.stringToBytes(symbol); // Creates and registers the Set with Core as enabled const txHash = await core.createSet.sendTransactionAsync( factory, componentAddresses, units, naturalUnit, encodedName, encodedSymbol, callData, { from }, ); const logs = await setTestUtils.getLogsFromTxHash(txHash); const setAddress = extractNewSetTokenAddressFromLogs(logs); return await SetTokenContract.at( setAddress, web3, { from } ); } /* ============ CoreAccounting Extension ============ */ public async depositFromUser( core: CoreLikeContract, token: Address, quantity: BigNumber, from: Address = this._contractOwnerAddress, ) { await core.deposit.sendTransactionAsync( token, quantity, { from }, ); } public async depositTo( core: CoreLikeContract, to: Address, token: Address, quantity: BigNumber, from: Address = this._contractOwnerAddress, ) { await core.deposit.sendTransactionAsync( token, quantity, { from }, ); await core.internalTransfer.sendTransactionAsync( token, to, quantity, { from }, ); } /* ============ RebalancingToken Factory ============ */ public async getRebalancingInstanceFromAddress( rebalancingTokenAddress: Address, from: Address = this._contractOwnerAddress, ): Promise<RebalancingSetTokenContract> { return await RebalancingSetTokenContract.at( rebalancingTokenAddress, web3, { from }, ); } /* ============ CoreIssuance Extension ============ */ public async issueSetTokenAsync( core: CoreLikeContract, token: Address, quantity: BigNumber, from: Address = this._tokenOwnerAddress, ) { await core.issue.sendTransactionAsync( token, quantity, { from } ); } public maskForAllComponents( numComponents: number, ): BigNumber { const allIndices = _.range(numComponents); return this.maskForComponentsAtIndexes(allIndices); } public maskForComponentsAtIndexes( indexes: number[], ): BigNumber { return new BigNumber( _.sum( _.map( indexes, (_, idx) => Math.pow(2, indexes[idx])) ) ); } /* ============ CoreOperationState Extension ============ */ /** * OperationStates * 0 = Operational * 1 = Shut Down */ public async setOperationStateAsync( core: CoreLikeContract, operationState: BigNumber, from: Address = this._tokenOwnerAddress, ) { await core.setOperationState.sendTransactionAsync(operationState, { from }); } /* ============ CoreExchangeDispatcher Extension ============ */ public async addDefaultExchanges( core: CoreLikeContract, from: Address = this._contractOwnerAddress, ) { const approvePromises = _.map(_.values(SetUtils.EXCHANGES), exchangeId => this.addExchange(core, exchangeId, this._tokenOwnerAddress, from) ); await Promise.all(approvePromises); } public async addExchange( core: CoreLikeContract, exchangeId: number, exchangeAddress: Address, from: Address = this._contractOwnerAddress, ) { await core.addExchange.sendTransactionAsync( exchangeId, exchangeAddress, { from }, ); } /* ============ Set Token Convenience function ============ */ public async getSetInstance( setTokenAddress: Address, from: Address = this._contractOwnerAddress, ): Promise<SetTokenContract> { return new SetTokenContract(getContractInstance(SetToken, setTokenAddress), { from, gas: DEFAULT_GAS }); } }
the_stack
import 'zone.js/dist/zone.js'; import { tracing, Span, ATTRIBUTE_HTTP_STATUS_CODE, ATTRIBUTE_HTTP_METHOD, WindowWithOcwGlobals, LinkType, Link, } from '@opencensus/web-core'; import { InteractionTracker, RESET_TRACING_ZONE_DELAY, } from '../src/interaction-tracker'; import { doPatching, setXhrAttributeHasCalledSend, } from '../src/monkey-patching'; import { spanContextToTraceParent } from '@opencensus/web-propagation-tracecontext'; import { createFakePerfResourceEntry, spyPerfEntryByType } from './util'; describe('InteractionTracker', () => { doPatching(); InteractionTracker.startTracking(); let onEndSpanSpy: jasmine.Spy; const windowWithOcwGlobals = window as WindowWithOcwGlobals; // Set the traceparent to fake the initial load Span Context. Also, Sample // 100% of interactions for the testing. Necessary as this is supposed to be // done by the initial load page. const INITIAL_LOAD_TRACE_ID = '0af7651916cd43dd8448eb211c80319c'; const INITIAL_LOAD_SPAN_ID = 'b7ad6b7169203331'; windowWithOcwGlobals.traceparent = `00-${INITIAL_LOAD_TRACE_ID}-${INITIAL_LOAD_SPAN_ID}-01`; const EXPECTED_LINKS: Link[] = [ { traceId: INITIAL_LOAD_TRACE_ID, spanId: INITIAL_LOAD_SPAN_ID, type: LinkType.PARENT_LINKED_SPAN, attributes: {}, }, ]; // Use Buffer time as we expect that these interactions take // a little extra time to complete due to the setTimeout that // is needed for the final completion and runs in a different // tick. const TIME_BUFFER = 10; const XHR_TIME = 60; const SET_TIMEOUT_TIME = 60; const BUTTON_TAG_NAME = 'BUTTON'; tracing.registerExporter(tracing.exporter); beforeEach(() => { onEndSpanSpy = spyOn(tracing.exporter, 'onEndSpan'); }); it('should handle interactions with no async work', done => { fakeInteraction(noop); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); // As there is another setTimeOut that completes the interaction, the // span duraction is not precise, then only test if the interaction // duration finishes within a range. expect(rootSpan.duration).toBeLessThan(TIME_BUFFER); done(); }); }); it('should handle interactions with macroTask', done => { const onclick = () => { setTimeout(noop, SET_TIMEOUT_TIME); }; fakeInteraction(onclick); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(SET_TIMEOUT_TIME); expect(rootSpan.duration).toBeLessThanOrEqual( SET_TIMEOUT_TIME + TIME_BUFFER ); done(); }); }); it('should handle interactions with microTask', done => { const onclick = () => { const promise = getPromise(); promise.then(noop); }; fakeInteraction(onclick); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeLessThanOrEqual(TIME_BUFFER); done(); }); }); it('should handle interactions with canceled tasks', done => { const interactionTime = SET_TIMEOUT_TIME - 10; const canceledTask = () => { const timeoutId = setTimeout(noop, SET_TIMEOUT_TIME); setTimeout(() => { clearTimeout(timeoutId); }, interactionTime); }; fakeInteraction(canceledTask); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(interactionTime); //The duration has to be less than set to the canceled timeout. expect(rootSpan.duration).toBeLessThan(SET_TIMEOUT_TIME); done(); }); }); it('should ignore interactions on elements with disable', done => { const onclick = () => { setTimeout(noop, SET_TIMEOUT_TIME); }; const button = createButton('test interaction', true); fakeInteraction(onclick, button); const onclick2 = () => { setTimeout(noop, SET_TIMEOUT_TIME); }; button.removeAttribute('disabled'); fakeInteraction(onclick2, button); onEndSpanSpy.and.callFake((rootSpan: Span) => { // Make sure `onEndSpan` is called only once; expect(onEndSpanSpy.calls.count()).toBe(1); expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(SET_TIMEOUT_TIME); expect(rootSpan.duration).toBeLessThanOrEqual( SET_TIMEOUT_TIME + TIME_BUFFER ); done(); }); }); it('should handle interactions on elements without data-ocweb-id attribute', done => { const onclick = () => { setTimeout(noop, SET_TIMEOUT_TIME); }; const button = createButton(''); fakeInteraction(onclick, button); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('button#test_element click'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(SET_TIMEOUT_TIME); expect(rootSpan.duration).toBeLessThanOrEqual( SET_TIMEOUT_TIME + TIME_BUFFER ); done(); }); }); it('should ignore periodic tasks', done => { const onclick = () => { const interaval = setInterval(() => { clearInterval(interaval); }, SET_TIMEOUT_TIME); }; fakeInteraction(onclick); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeLessThanOrEqual(TIME_BUFFER); done(); }); }); it('should not start new interaction if second click handler occurs before 50 ms.', done => { const onclickInteraction1 = () => { setTimeout(noop, RESET_TRACING_ZONE_DELAY + 10); }; fakeInteraction(onclickInteraction1); const onclickInteraction2 = () => { setTimeout(noop, SET_TIMEOUT_TIME); }; // Schedule a second interactionto be run before `RESET_TRACING_ZONE_DELAY` setTimeout(() => { fakeInteraction(onclickInteraction2); }, RESET_TRACING_ZONE_DELAY - 10); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); // As this click is done at 'RESET_TRACING_ZONE_DELAY - 10' and this click has a // setTimeout, the minimum time taken by this click is the sum of these values. const timeInteraction2 = RESET_TRACING_ZONE_DELAY - 10 + SET_TIMEOUT_TIME; expect(rootSpan.duration).toBeGreaterThanOrEqual(timeInteraction2); expect(rootSpan.duration).toBeLessThanOrEqual( timeInteraction2 + TIME_BUFFER ); done(); }); }); it('should create a new interaction and track overlapping interactions.', done => { const timeInteraction1 = RESET_TRACING_ZONE_DELAY + 10; const onclickInteraction1 = () => { setTimeout(noop, timeInteraction1); }; fakeInteraction(onclickInteraction1); const onclickInteraction2 = () => { setTimeout(noop, RESET_TRACING_ZONE_DELAY); }; // Schedule a second interaction starting after `RESET_TRACING_ZONE_DELAY` ms setTimeout(() => { fakeInteraction(onclickInteraction2); }, RESET_TRACING_ZONE_DELAY + 1); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); // Test related to the first interaction if (onEndSpanSpy.calls.count() === 1) { expect(rootSpan.duration).toBeGreaterThanOrEqual(timeInteraction1); expect(rootSpan.duration).toBeLessThanOrEqual( timeInteraction1 + TIME_BUFFER ); } else { expect(rootSpan.duration).toBeGreaterThanOrEqual( RESET_TRACING_ZONE_DELAY ); expect(rootSpan.duration).toBeLessThanOrEqual( RESET_TRACING_ZONE_DELAY + TIME_BUFFER ); done(); } }); }); describe('Route transition', () => { afterEach(() => { // To allow the several tests to detect the route transition, go back to // the home page. history.back(); }); it('should handle route transition interaction and rename the interaction as Navigation', done => { const onclick = () => { setTimeout(() => { history.pushState({ test: 'testing' }, 'page 2', '/test_navigation'); }, SET_TIMEOUT_TIME); }; // Create a button without 'data-ocweb-id' attribute. const button = createButton(''); fakeInteraction(onclick, button); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('Navigation /test_navigation'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(SET_TIMEOUT_TIME); expect(rootSpan.duration).toBeLessThanOrEqual( SET_TIMEOUT_TIME + TIME_BUFFER ); done(); }); }); it('should not rename span as Navigation if it used data-ocweb-id', done => { const onclick = () => { setTimeout(() => { history.pushState({ test: 'testing' }, 'page 2', '/test_navigation'); }, SET_TIMEOUT_TIME); }; // Create a button with 'data-ocweb-id' attribute. const button = createButton('Test navigation'); fakeInteraction(onclick, button); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('Test navigation'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(SET_TIMEOUT_TIME); expect(rootSpan.duration).toBeLessThanOrEqual( SET_TIMEOUT_TIME + TIME_BUFFER ); done(); }); }); }); describe('Custom Spans', () => { it('Should handle the custom spans and add them to the current root span as child spans', done => { const onclick = () => { // Start a custom span for the setTimeout. const setTimeoutCustomSpan = tracing.tracer.startChildSpan({ name: 'setTimeout custom span', }); setTimeout(() => { setTimeoutCustomSpan.end(); }, SET_TIMEOUT_TIME); }; fakeInteraction(onclick); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.spans.length).toBe(1); const childSpan = rootSpan.spans[0]; expect(childSpan.name).toBe('setTimeout custom span'); expect(childSpan.duration).toBeGreaterThanOrEqual(SET_TIMEOUT_TIME); expect(childSpan.duration).toBeLessThanOrEqual( SET_TIMEOUT_TIME + TIME_BUFFER ); expect(rootSpan.duration).toBeGreaterThanOrEqual(SET_TIMEOUT_TIME); expect(rootSpan.duration).toBeLessThanOrEqual( SET_TIMEOUT_TIME + TIME_BUFFER ); done(); }); }); }); describe('HTTP requests', () => { // Value to be full when the XMLHttpRequest.send method is faked, // That way the perfornamce resource entries have a accurate timing. let perfResourceEntries: PerformanceResourceTiming[]; beforeEach(() => { perfResourceEntries = []; }); it('should handle HTTP requets and do not set Trace Context Header', done => { // Set a diferent ocTraceHeaderHostRegex to test that the trace context header is not // sent as the url request does not match the regex. windowWithOcwGlobals.ocTraceHeaderHostRegex = /"http:\/\/test-host".*/; const setRequestHeaderSpy = spyOn( XMLHttpRequest.prototype, 'setRequestHeader' ).and.callThrough(); const requestUrl = 'http://localhost:8000/test'; const onclick = () => { doHttpRequest(requestUrl); }; fakeInteraction(onclick); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(XHR_TIME); expect(rootSpan.duration).toBeLessThanOrEqual(XHR_TIME + TIME_BUFFER); expect(rootSpan.spans.length).toBe(1); const childSpan = rootSpan.spans[0]; // Check the `traceparent` header is not set as Trace Header Host does not match. expect(setRequestHeaderSpy).not.toHaveBeenCalled(); expect(childSpan.name).toBe('/test'); expect(childSpan.attributes[ATTRIBUTE_HTTP_STATUS_CODE]).toBe('200'); expect(childSpan.attributes[ATTRIBUTE_HTTP_METHOD]).toBe('GET'); expect(childSpan.ended).toBeTruthy(); const expectedAnnotations = [ { description: 'fetchStart', timestamp: perfResourceEntries[0].fetchStart, attributes: {}, }, { description: 'responseEnd', timestamp: perfResourceEntries[0].responseEnd, attributes: {}, }, ]; expect(childSpan.annotations).toEqual(expectedAnnotations); // Check the CORS span is not created as this XHR does not send CORS // pre-flight request. expect(childSpan.spans.length).toBe(0); expect(childSpan.duration).toBeGreaterThanOrEqual(XHR_TIME); expect(childSpan.duration).toBeLessThanOrEqual(XHR_TIME + TIME_BUFFER); done(); }); }); it('should handle HTTP requets and set Trace Context Header', done => { // Set the ocTraceHeaderHostRegex value so the `traceparent` context header is set. windowWithOcwGlobals.ocTraceHeaderHostRegex = /.*/; const setRequestHeaderSpy = spyOn( XMLHttpRequest.prototype, 'setRequestHeader' ).and.callThrough(); const requestUrl = 'http://localhost:8000/test'; const onclick = () => { doHttpRequest(requestUrl, true); }; fakeInteraction(onclick); onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(XHR_TIME); expect(rootSpan.duration).toBeLessThanOrEqual(XHR_TIME + TIME_BUFFER); expect(rootSpan.spans.length).toBe(1); const childSpan = rootSpan.spans[0]; expect(setRequestHeaderSpy).toHaveBeenCalledWith( 'traceparent', spanContextToTraceParent({ traceId: rootSpan.traceId, spanId: childSpan.id, options: 1, // Sampled trace }) ); expect(childSpan.name).toBe('/test'); expect(childSpan.attributes[ATTRIBUTE_HTTP_STATUS_CODE]).toBe('200'); expect(childSpan.attributes[ATTRIBUTE_HTTP_METHOD]).toBe('GET'); expect(childSpan.ended).toBeTruthy(); const mainRequestPerfTiming = perfResourceEntries[1]; const expectedChildSpanAnnotations = [ { description: 'fetchStart', timestamp: mainRequestPerfTiming.fetchStart, attributes: {}, }, { description: 'responseEnd', timestamp: mainRequestPerfTiming.responseEnd, attributes: {}, }, ]; expect(childSpan.annotations).toEqual(expectedChildSpanAnnotations); // Check the CORS span is created with the correct annotations. const corsPerfTiming = perfResourceEntries[0]; const expectedCorsSpanAnnotations = [ { description: 'fetchStart', timestamp: corsPerfTiming.fetchStart, attributes: {}, }, { description: 'responseEnd', timestamp: corsPerfTiming.responseEnd, attributes: {}, }, ]; expect(childSpan.spans.length).toBe(1); const corsSpan = childSpan.spans[0]; expect(corsSpan.name).toBe('CORS Preflight'); expect(corsSpan.annotations).toEqual(expectedCorsSpanAnnotations); expect(childSpan.duration).toBeGreaterThanOrEqual(XHR_TIME); expect(childSpan.duration).toBeLessThanOrEqual(XHR_TIME + TIME_BUFFER); done(); }); }); it('should handle cascading tasks', done => { const setRequestHeaderSpy = spyOn( XMLHttpRequest.prototype, 'setRequestHeader' ).and.callThrough(); const requestUrl = '/test'; const onclick = () => { const promise = getPromise(); promise.then(() => { setTimeout(() => { doHttpRequest(requestUrl, true); }, SET_TIMEOUT_TIME); }); }; fakeInteraction(onclick); const interactionTime = SET_TIMEOUT_TIME + XHR_TIME; onEndSpanSpy.and.callFake((rootSpan: Span) => { expect(rootSpan.name).toBe('test interaction'); expect(rootSpan.attributes['EventType']).toBe('click'); expect(rootSpan.attributes['TargetElement']).toBe(BUTTON_TAG_NAME); expect(rootSpan.attributes['initial_load_trace_id']).toBe( INITIAL_LOAD_TRACE_ID ); expect(rootSpan.links).toEqual(EXPECTED_LINKS); expect(rootSpan.ended).toBeTruthy(); expect(rootSpan.duration).toBeGreaterThanOrEqual(interactionTime); expect(rootSpan.duration).toBeLessThanOrEqual( interactionTime + TIME_BUFFER ); expect(rootSpan.spans.length).toBe(1); const childSpan = rootSpan.spans[0]; expect(setRequestHeaderSpy).toHaveBeenCalledWith( 'traceparent', spanContextToTraceParent({ traceId: rootSpan.traceId, spanId: childSpan.id, options: 1, // Sampled trace }) ); expect(childSpan.name).toBe('/test'); expect(childSpan.attributes[ATTRIBUTE_HTTP_STATUS_CODE]).toBe('200'); expect(childSpan.attributes[ATTRIBUTE_HTTP_METHOD]).toBe('GET'); expect(childSpan.ended).toBeTruthy(); const mainRequestPerfTiming = perfResourceEntries[1]; const expectedChildSpanAnnotations = [ { description: 'fetchStart', timestamp: mainRequestPerfTiming.fetchStart, attributes: {}, }, { description: 'responseEnd', timestamp: mainRequestPerfTiming.responseEnd, attributes: {}, }, ]; expect(childSpan.annotations).toEqual(expectedChildSpanAnnotations); // Check the CORS span is created with the correct annotations. const corsPerfTiming = perfResourceEntries[0]; const expectedCorsSpanAnnotations = [ { description: 'fetchStart', timestamp: corsPerfTiming.fetchStart, attributes: {}, }, { description: 'responseEnd', timestamp: corsPerfTiming.responseEnd, attributes: {}, }, ]; expect(childSpan.spans.length).toBe(1); const corsSpan = childSpan.spans[0]; expect(corsSpan.name).toBe('CORS Preflight'); expect(corsSpan.annotations).toEqual(expectedCorsSpanAnnotations); expect(childSpan.duration).toBeGreaterThanOrEqual(XHR_TIME); expect(childSpan.duration).toBeLessThanOrEqual(XHR_TIME + TIME_BUFFER); done(); }); }); function doHttpRequest(urlRequest = '/test', xhrHasCorsData = false) { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = noop; spyOn(xhr, 'send').and.callFake(() => { setXhrAttributeHasCalledSend(xhr); setTimeout(() => { spyOnProperty(xhr, 'status').and.returnValue(200); // Fake the readyState as DONE so the xhr interceptor knows when the // XHR finished. spyOnProperty(xhr, 'readyState').and.returnValue(XMLHttpRequest.DONE); const event = new Event('readystatechange'); xhr.dispatchEvent(event); }, XHR_TIME); // Create the performance entries at this point in order to have a // similar timing as span. createFakePerformanceEntries(urlRequest, xhrHasCorsData); spyPerfEntryByType(perfResourceEntries); spyOnProperty(xhr, 'responseURL').and.returnValue(urlRequest); }); xhr.open('GET', urlRequest); xhr.send(); } function createFakePerformanceEntries( urlRequest: string, xhrHasCorsData: boolean ) { const xhrPerfStart = performance.now(); let actualRequestStartTime = xhrPerfStart; if (xhrHasCorsData) { const corsEntry = createFakePerfResourceEntry( xhrPerfStart, xhrPerfStart + 1, urlRequest ); // Start the other request a bit after the CORS finished. actualRequestStartTime = xhrPerfStart + 1; perfResourceEntries.push(corsEntry); } const actualRequestEntry = createFakePerfResourceEntry( actualRequestStartTime + 1, actualRequestStartTime + XHR_TIME - 2, urlRequest ); perfResourceEntries.push(actualRequestEntry); } }); function fakeInteraction(callback: Function, elem?: HTMLElement) { let element: HTMLElement; if (elem) element = elem; else element = createButton('test interaction'); element.onclick = () => callback(); element.click(); } function createButton(dataOcwebId: string, disabled?: boolean): HTMLElement { const button = document.createElement('button'); button.setAttribute('data-ocweb-id', dataOcwebId); button.setAttribute('id', 'test_element'); if (disabled) { button.setAttribute('disabled', 'disabled'); } return button; } const noop = () => {}; function getPromise() { return new Promise(resolve => { resolve(); }); } });
the_stack
namespace SwiftSnapper { export module CameraManager { let video, mediaStream; var Capture = Windows.Media.Capture; var DeviceInformation = Windows.Devices.Enumeration.DeviceInformation; var DeviceClass = Windows.Devices.Enumeration.DeviceClass; var DisplayOrientations = Windows.Graphics.Display.DisplayOrientations; var FileProperties = Windows.Storage.FileProperties; var Media = Windows.Media; var SimpleOrientation = Windows.Devices.Sensors.SimpleOrientation; var SimpleOrientationSensor = Windows.Devices.Sensors.SimpleOrientationSensor; // Receive notifications about rotation of the device and UI and apply any necessary rotation to the preview stream and UI controls var oOrientationSensor = SimpleOrientationSensor.getDefault(), oDisplayInformation = Windows.Graphics.Display['DisplayInformation'].getForCurrentView(), oDeviceOrientation = SimpleOrientation.notRotated, oDisplayOrientation = DisplayOrientations.portrait; // Prevent the screen from sleeping while the camera is running var oDisplayRequest = new Windows.System.Display.DisplayRequest(); // For listening to media property changes //var oSystemMediaControls = Media.SystemMediaTransportControls.getForCurrentView(); // MediaCapture and its state variables var mediaCapture = null, isInitialized = false, isPreviewing = false, isRecording = false; // Information about the camera device var externalCamera = false, mirroringPreview = false; // Rotation metadata to apply to the preview stream and recorded videos (MF_MT_VIDEO_ROTATION) // Reference: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868174.aspx var RotationKey = "C380465D-2271-428C-9B83-ECEA3B4A85C1"; //document.getElementById("ShutterBtn").addEventListener("click", shutterButton_tapped); export function initialize(conf) { video = document.getElementById('CameraPreview'); var cameraPanelEnumerate = Windows.Devices.Enumeration.Panel.back; video.classList.remove('FrontFacing'); if (conf.frontFacing) { cameraPanelEnumerate = Windows.Devices.Enumeration.Panel.front; video.classList.add('FrontFacing'); } var Capture = Windows.Media.Capture; var mediaSettings = new Capture.MediaCaptureInitializationSettings(); var rotationValue = Capture.VideoRotation.none; //mediaSettings.audioDeviceId = ""; //mediaSettings.videoDeviceId = ""; //mediaSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.video;; //mediaSettings.photoCaptureSource = Capture.PhotoCaptureSource.photo; // Get available devices for capturing pictures findCameraDeviceByPanelAsync(cameraPanelEnumerate) .then(function (camera) { if (camera === null) { console.log("No camera device found!"); return; } // Figure out where the camera is located if (!camera.enclosureLocation || camera.enclosureLocation.panel === Windows.Devices.Enumeration.Panel.unknown) { // No information on the location of the camera, assume it's an external camera, not integrated on the device externalCamera = true; oDisplayOrientation = DisplayOrientations.landscape; } else { // Camera is fixed on the device externalCamera = false; // Only mirror the preview if the camera is on the front panel mirroringPreview = (camera.enclosureLocation.panel === Windows.Devices.Enumeration.Panel.front); } mediaCapture = new Capture.MediaCapture(); mediaSettings.videoDeviceId = camera.id; mediaSettings.streamingCaptureMode = Capture.StreamingCaptureMode.video; // Initialize media capture and start the preview isInitialized = false; mediaCapture.initializeAsync(mediaSettings).then(function () { // Prevent the device from sleeping while the preview is running oDisplayRequest.requestActive(); if (mirroringPreview) { video.style.transform = "scale(-1, 1)"; } else { video.style.transform = "scale(1, 1)"; } var previewUrl = URL.createObjectURL(mediaCapture); video.src = previewUrl; video.play(); video.addEventListener("playing", function () { isPreviewing = true; // Doing a catch loop because often the mediaCapture.setEncodingPropertiesAsync function was still in progress. // I don't know any better way to do this maybe a singleton design pattern? // TODO: get input on this. try { setPreviewRotationAsync(); } catch (Error) { console.log(Error.message); console.log("Error in setPreviewRotationAsync"); } /* setPreviewRotationAsync().then(function () { console.log("setPreviewRotationAsync completed correctly"); }, function () { console.log("Error in setPreviewEotationAsync"); }) */ }); }, function (error) { console.log("Error in mediaCapture.initializeAsync"); }) }, function (error) { console.log(error.message); } ) } export function getExportSettings() { var pngProperties = new Windows.Media.MediaProperties.ImageEncodingProperties(); pngProperties = Windows.Media.MediaProperties.ImageEncodingProperties.createPng(); return pngProperties } function shutterButton_tapped() { takePhotoAsync(); } /// <summary> /// Takes a photo to a StorageFile and adds rotation metadata to it /// </summary> /// <returns></returns> export function takePhotoAsync() { if (mediaCapture != null) { var Streams = Windows.Storage.Streams; var Imaging = Windows.Graphics.Imaging; var inputStream = new Streams.InMemoryRandomAccessStream(); var bitmapDecoder = null, bitmapEncoder = null, outputStream = null; // Take the picture console.log("Taking photo..."); mediaCapture.capturePhotoToStreamAsync(Windows.Media.MediaProperties.ImageEncodingProperties.createJpeg(), inputStream) console.log("Photo taken!"); var photoOrientation = convertOrientationToPhotoOrientation(getCameraOrientation()); return inputStream //return reencodeAndSavePhotoAsync(inputStream, photoOrientation); } return null; } /// <summary> /// Calculates the current camera orientation from the device orientation by taking into account whether the camera is external or facing the user /// </summary> /// <returns>The camera orientation in space, with an inverted rotation in the case the camera is mounted on the device and is facing the user</returns> function getCameraOrientation() { if (externalCamera) { // Cameras that are not attached to the device do not rotate along with it, so apply no rotation return SimpleOrientation.notRotated; } var result = oDeviceOrientation; // Account for the fact that, on portrait-first devices, the camera sensor is mounted at a 90 degree offset to the native orientation if (oDisplayInformation.nativeOrientation === DisplayOrientations.portrait) { switch (result) { case SimpleOrientation.rotated90DegreesCounterclockwise: result = SimpleOrientation.notRotated; break; case SimpleOrientation.rotated180DegreesCounterclockwise: result = SimpleOrientation.rotated90DegreesCounterclockwise; break; case SimpleOrientation.rotated270DegreesCounterclockwise: result = SimpleOrientation.rotated180DegreesCounterclockwise; break; case SimpleOrientation.notRotated: default: result = SimpleOrientation.rotated270DegreesCounterclockwise; break; } } // If the preview is being mirrored for a front-facing camera, then the rotation should be inverted if (mirroringPreview) { // This only affects the 90 and 270 degree cases, because rotating 0 and 180 degrees is the same clockwise and counter-clockwise switch (result) { case SimpleOrientation.rotated90DegreesCounterclockwise: return SimpleOrientation.rotated270DegreesCounterclockwise; case SimpleOrientation.rotated270DegreesCounterclockwise: return SimpleOrientation.rotated90DegreesCounterclockwise; } } return result; } /// <summary> /// Applies the given orientation to a photo stream and saves it as a StorageFile /// </summary> /// <param name="stream">The photo stream</param> /// <param name="photoOrientation">The orientation metadata to apply to the photo</param> /// <returns></returns> function reencodeAndSavePhotoAsync(inputStream, orientation) { var Imaging = Windows.Graphics.Imaging; var bitmapDecoder = null, bitmapEncoder = null, outputStream = null; return Imaging.BitmapDecoder.createAsync(inputStream) .then(function (decoder) { bitmapDecoder = decoder; return Windows.Storage.KnownFolders.picturesLibrary.createFileAsync("SimplePhoto.jpg", Windows.Storage.CreationCollisionOption.generateUniqueName); }).then(function (file) { return file.openAsync(Windows.Storage.FileAccessMode.readWrite); }).then(function (outStream) { outputStream = outStream; return Imaging.BitmapEncoder.createForTranscodingAsync(outputStream, bitmapDecoder); }).then(function (encoder) { bitmapEncoder = encoder; var properties = new Imaging.BitmapPropertySet(); properties.insert("System.Photo.Orientation", new Imaging.BitmapTypedValue(orientation, Windows.Foundation.PropertyType.uInt16)); return bitmapEncoder.bitmapProperties.setPropertiesAsync(properties) }).then(function () { return bitmapEncoder.flushAsync(); }).then(function () { inputStream.close(); outputStream.close(); }); } /// <summary> /// Attempts to find and return a device mounted on the panel specified, and on failure to find one it will return the first device listed /// </summary> /// <param name="panel">The desired panel on which the returned device should be mounted, if available</param> /// <returns></returns> function findCameraDeviceByPanelAsync(panel) { var deviceInfo = null; // Get available devices for capturing pictures return DeviceInformation.findAllAsync(DeviceClass.videoCapture) .then(function (devices) { devices.forEach(function (cameraDeviceInfo) { if (cameraDeviceInfo.enclosureLocation != null && cameraDeviceInfo.enclosureLocation.panel === panel) { deviceInfo = cameraDeviceInfo; return; } }); // Nothing matched, just return the first if (!deviceInfo && devices.length > 0) { deviceInfo = devices.getAt(0); } return deviceInfo; }); } /// <summary> /// Converts the given orientation of the app on the screen to the corresponding rotation in degrees /// </summary> /// <param name="orientation">The orientation of the app on the screen</param> /// <returns>An orientation in degrees</returns> function convertDisplayOrientationToDegrees(orientation) { switch (orientation) { case DisplayOrientations.portrait: return 90; case DisplayOrientations.landscapeFlipped: return 180; case DisplayOrientations.portraitFlipped: return 270; case DisplayOrientations.landscape: default: return 0; } } /// <summary> /// Gets the current orientation of the UI in relation to the device (when AutoRotationPreferences cannot be honored) and applies a corrective rotation to the preview /// </summary> /// <returns></returns> function setPreviewRotationAsync() { //Edge case for Windows on PCs if (!(navigator.userAgent.indexOf('Phone') > -1)) { return; } // Calculate which way and how far to rotate the preview var rotationDegrees = convertDisplayOrientationToDegrees(oDisplayOrientation); // The rotation direction needs to be inverted if the preview is being mirrored if (mirroringPreview) { rotationDegrees = (360 - rotationDegrees) % 360; } // Add rotation metadata to the preview stream to make sure the aspect ratio / dimensions match when rendering and getting preview frames var props = mediaCapture.videoDeviceController.getMediaStreamProperties(Capture.MediaStreamType.videoPreview); props.properties.insert(RotationKey, rotationDegrees); return mediaCapture.setEncodingPropertiesAsync(Capture.MediaStreamType.videoPreview, props, null); } /// <summary> /// Converts the given orientation of the device in space to the metadata that can be added to captured photos /// </summary> /// <param name="orientation">The orientation of the device in space</param> /// <returns></returns> function convertOrientationToPhotoOrientation(orientation) { switch (orientation) { case SimpleOrientation.rotated90DegreesCounterclockwise: return FileProperties.PhotoOrientation.rotate90; case SimpleOrientation.rotated180DegreesCounterclockwise: return FileProperties.PhotoOrientation.rotate180; case SimpleOrientation.rotated270DegreesCounterclockwise: return FileProperties.PhotoOrientation.rotate270; case SimpleOrientation.notRotated: default: return FileProperties.PhotoOrientation.normal; } } } }
the_stack
import EventEmitter from 'eventemitter3'; import { history } from 'prosemirror-history'; import { DOMParser, Node as ProsemirrorNode, Schema } from 'prosemirror-model'; import { EditorState, Plugin, Transaction } from 'prosemirror-state'; import { EditorView, NodeView } from 'prosemirror-view'; import { ISylApiAdapterOptions, SylApi } from './api'; import { BasicCtrlPlugin, BSControlKey, IBasicCtrlConfig } from './basic/basic-ctrl'; import { CtrlPlugin } from './basic/ctrl-plugin'; import { createCustomCtrlPlugin, CUSTOM_CTRL_ACCEPT, ICustomCtrlConfig } from './basic/custom-ctrl'; import { DecorationPlugin } from './basic/decoration'; import { basicKeymapPlugin, createCustomKeymapPlugins, defaultKeymapPlugin, TSylKeymap } from './basic/keymap'; import { createLifeCyclePlugin } from './basic/lifecycle/lifecycle-plugin'; import { ruleBuilder } from './basic/text-shortcut/rule-builder'; import { SHORTCUT_KEY } from './basic/text-shortcut/shortcut-plugin'; import { EventChannel } from './event'; import { handleDOMSpec, removeBrInEnd } from './formatter'; import { parseSylPluginConfig } from './libs/plugin-config-parse'; import { ISylPluginConfig, Types } from './libs/types'; import { LocaleStore } from './locale'; import { IModuleType, ModuleManager } from './module'; import { BaseCard, BaseCardView, basicSchema, IEventHandler, SchemaMeta, SylController, SylPlugin, TKeymapHandler, } from './schema'; import { createSchema, updateSchema } from './schema/normalize'; // extra configuration support, never related to editing interface IExtraConfig { spellCheck?: boolean; autoFocus?: boolean; onError?: (error: Error, args?: any) => any; onBlur?: () => void; onFocus?: () => void; } interface IBaseConfig { emitter?: EventChannel; locale?: Types.StringMap<any>; disable?: boolean; disableShortcut?: boolean; } interface IKeymapConfig { keymap?: Types.StringMap<TKeymapHandler>; } interface IConfiguration extends IBaseConfig, IBasicCtrlConfig, ICustomCtrlConfig, IExtraConfig, IKeymapConfig {} type TSylEventType = EventChannel['LocalEvent'] | string | symbol; const EDITOR_CHECK = ['autocomplete', 'autoCorrect', 'autoCapitalize']; const dispatchTransactionFactory = ({ view, emitter, onError, }: { view: EditorView; emitter: EventEmitter; onError: IExtraConfig['onError']; }): EditorView['dispatch'] => (tr: Transaction) => { try { if (!view || !view.docView || !emitter) return; const newState = view.state.apply(tr); view.updateState(newState); emitter.emit(EventChannel.LocalEvent.ON_CHANGE); } catch (err) { onError && onError(err); } }; // Format the property of `$NodeView` in `SylPlugin` as nodeViews` in `prosemirror-plugin-props, and inject `SylApi` const getNodeViewStringMap = (sylPlugins: SylPlugin<any>[], adapter: SylApi) => sylPlugins.reduce((nodeViewMap, sylPlugin) => { const NodeViewCtor = sylPlugin.$NodeView; const $schema = sylPlugin.$schema as BaseCard; if (!NodeViewCtor || !$schema) return nodeViewMap; const name = sylPlugin.name || sylPlugin.$controller!.name; if (nodeViewMap[name]) console.warn('multiple register', name); nodeViewMap[name] = (node, editorView, getPos) => { const nodeView = new NodeViewCtor(adapter, node, editorView, getPos); if (nodeView instanceof BaseCardView) { nodeView.mount({ ViewMap: $schema.ViewMap, layers: $schema.layers }); nodeView.afterMount(name); } return nodeView; }; return nodeViewMap; }, {} as Types.StringMap<(node: ProsemirrorNode, view: EditorView, getPos: boolean | (() => number)) => NodeView>); const setConfiguration = ( baseConfig: Types.StringMap<any>, configProps: Types.StringMap<any>, cb?: (key: string, val: any, oldVal: any) => void, ) => { Object.keys(baseConfig).forEach(key => { if (configProps[key] !== undefined && baseConfig[key] !== configProps[key]) { const preValue = baseConfig[key]; baseConfig[key] = configProps[key]; cb && cb(key, configProps[key], preValue); } }); }; class SylConfigurator { public mount: HTMLElement; public view: EditorView; public moduleManage?: ModuleManager; private adapter?: SylApi; private localStore?: LocaleStore; public domParser?: DOMParser; // configs of SylPlugin private sylPluginConfigs: Array<ISylPluginConfig> = []; // instances of SylPlugin private sylPluginInstances: Array<SylPlugin> = []; // relate to custom ctrl private customCtrlPlugin?: CtrlPlugin<ICustomCtrlConfig | ICustomCtrlConfig[]>; // relate to keymap private customKeyMapPlugin?: CtrlPlugin<TSylKeymap | TSylKeymap[]>; // configuration that pass to BasicCtrlPlugin public basicConfiguration: Required<IBasicCtrlConfig> = { keepLastLine: true, dropCursor: {}, placeholder: '', keepWhiteSpace: false, }; public extraConfiguration: Required<IExtraConfig> = { onError: err => { throw err; }, autoFocus: false, spellCheck: false, onBlur: () => {}, onFocus: () => {}, }; public baseConfiguration: Required<IBaseConfig> = { emitter: new EventChannel(), locale: {}, disable: false, disableShortcut: false, }; public customConfiguration: ICustomCtrlConfig = { eventHandler: {}, scrollThreshold: 5, scrollMargin: 0, }; public keymapConfiguration: TSylKeymap = {}; // prosemirror-plugin public plugins: Array<Plugin> = [history()]; // prosemirror-schema public schema: Schema = createSchema(basicSchema); get onError() { return this.extraConfiguration.onError; } get emitter() { return this.baseConfiguration.emitter; } constructor(mount: HTMLElement, sylPluginConfigs: Array<ISylPluginConfig> = [], config: IConfiguration = {}) { this.mount = mount; this.sylPluginConfigs = sylPluginConfigs; this.update(config); this.view = new EditorView(this.mount, { state: EditorState.create({ schema: this.schema, }), }); } public init(adapter: SylApi, module: Types.StringMap<IModuleType> = {}) { this.adapter = adapter; this.customCtrlPlugin = createCustomCtrlPlugin(adapter, [this.customConfiguration]); this.customKeyMapPlugin = createCustomKeymapPlugins(adapter, [this.keymapConfiguration]); this.installSylPlugins(adapter); this.installModule(adapter, module); this.constructParser(); } private constructParser() { const domParse = DOMParser.fromSchema(this.view.state.schema); const originParseSlice = domParse.parseSlice.bind(domParse); domParse.parseSlice = (dom: HTMLElement, _option) => { const { keepWhiteSpace } = this.basicConfiguration; let option = _option; if (!option) option = {}; if (keepWhiteSpace !== undefined) { option.preserveWhitespace = keepWhiteSpace; } handleDOMSpec(dom); const slice = originParseSlice(dom, option); removeBrInEnd(slice); return slice; }; this.domParser = domParse; } private installModule = (adapter: SylApi, module: Types.StringMap<IModuleType>) => { this.moduleManage = new ModuleManager(adapter, module); this.moduleManage.install(); }; private installSylPlugins = (adapter: SylApi) => { const { sylPlugins, nativePlugins } = parseSylPluginConfig(this.sylPluginConfigs, adapter); this.initNativePlugin(adapter, sylPlugins, nativePlugins); this.schema = createSchema( updateSchema(this.schema.spec, sylPlugins.map(p => p && p.$schemaMeta).filter(p => p) as SchemaMeta[]), ); const newProseState = EditorState.create({ schema: this.schema, plugins: this.plugins, }); this.view.setProps({ state: newProseState, nodeViews: getNodeViewStringMap(sylPlugins, adapter), dispatchTransaction: dispatchTransactionFactory({ view: this.view, emitter: this.baseConfiguration.emitter, onError: this.extraConfiguration.onError, }), }); this.sylPluginInstances = sylPlugins; this.extraConfiguration.autoFocus && this.view.focus(); }; private initNativePlugin( adapter: SylApi, sylPlugins: SylPlugin[], nativePlugins: { top: Plugin[]; bottom: Plugin[] }, ) { const textShortCutPlugin = ruleBuilder( sylPlugins.map(p => p && p.$schemaMeta!).filter(p => p), !this.baseConfiguration.disableShortcut, ); this.installController( adapter, sylPlugins.map(s => s.$controller!).filter(s => s), ); this.plugins.push( ...nativePlugins.top, textShortCutPlugin, this.customCtrlPlugin!, // decrease the priority of the `keymap`, because `handleKeyDown` can handle more things this.customKeyMapPlugin!, basicKeymapPlugin, defaultKeymapPlugin, DecorationPlugin(), BasicCtrlPlugin(this.basicConfiguration, !this.baseConfiguration.disable), ...nativePlugins.bottom, createLifeCyclePlugin(adapter), ); } private installController = (adapter: SylApi, sylControllers: SylController[]) => { this.collectCommands(adapter, sylControllers); this.customCtrlPlugin!.registerProps(sylControllers); this.customKeyMapPlugin!.registerProps(sylControllers.filter(c => c.keymap).map(c => c.keymap!)); }; private collectCommands = (adapter: SylApi, sylControllers: SylController[]) => { sylControllers.forEach((sylController: SylController) => { sylController?.command && adapter.addCommand(sylController.name, sylController.command); }); }; public registerController = ( name: string, Controller: typeof SylController, controllerProps?: Types.StringMap<any>, ) => { let plugin: SylPlugin | null = null; this.sylPluginInstances.some(instance => { if (instance.name === name) { plugin = instance; plugin.registerController(Controller, controllerProps); return true; } }); if (!plugin) { plugin = new SylPlugin(); plugin.name = name; plugin.Controller = Controller; plugin.init(this.adapter!, { controllerProps }); this.sylPluginInstances.push(plugin); } this.installController(this.adapter!, [plugin.$controller!]); this.emit(EventChannel.LocalEvent.CONFIG_PLUGIN_CHANGE); }; public unregisterController = (name: string) => { const isChange = this.sylPluginInstances.some(plugin => { if (plugin.name === name && plugin.$controller) { this.customCtrlPlugin?.unregisterProps(plugin.$controller); plugin.$controller.keymap && this.customKeyMapPlugin?.unregisterProps(plugin.$controller.keymap); if (plugin.$controller.command) delete this.adapter?.command[name]; plugin.unregisterController(); return true; } }); isChange && this.emit(EventChannel.LocalEvent.CONFIG_PLUGIN_CHANGE); }; private setExtraConfiguration = (config: IConfiguration) => setConfiguration(this.extraConfiguration, config, (key, val, oldVal) => { if (key === 'spellCheck') { EDITOR_CHECK.forEach(attr => this.view.dom.setAttribute(attr, val ? 'on' : 'off')); this.view.dom.setAttribute('spellcheck', val ? 'true' : 'false'); } else if (key === 'onBlur') { this.emitter.off(EventChannel.LocalEvent.ON_BLUR, oldVal); this.emitter.on(EventChannel.LocalEvent.ON_BLUR, val); } else if (key === 'onFocus') { this.emitter.off(EventChannel.LocalEvent.ON_FOCUS, oldVal); this.emitter.on(EventChannel.LocalEvent.ON_FOCUS, val); } }); private setBaseConfiguration = (config: IConfiguration) => setConfiguration(this.baseConfiguration, config, (key, val) => { if (key === 'locale') { this.localStore = new LocaleStore(val); } else if (key === 'disable' && this.view) { this.setEditable(val); } }); private setBasicCtrlConfiguration = (config: IConfiguration) => setConfiguration(this.basicConfiguration, config, key => { if (key === 'placeholder' && this.view) { this.view.updateState(this.view.state); } }); public update(config: IConfiguration & ISylApiAdapterOptions) { this.setBaseConfiguration(config); this.setExtraConfiguration(config); this.setBasicCtrlConfiguration(config); this.setCustomConfiguration(config); this.setKeymapConfiguration(config.keymap); config.module && this.moduleManage?.update(config.module); } private setCustomConfiguration = (props: ICustomCtrlConfig) => { (Object.keys(props) as Array<keyof ICustomCtrlConfig>).forEach(key => { if (CUSTOM_CTRL_ACCEPT[key]) { if (this.customConfiguration[key]) { this.customCtrlPlugin?.unregisterProps({ [key]: this.customConfiguration[key] }); } // @ts-ignore this.customConfiguration[key] = props[key]; } }); this.customCtrlPlugin?.registerProps(this.customConfiguration, true); }; public registerEventHandler = (eventHandler: IEventHandler) => { this.customCtrlPlugin?.registerProps({ eventHandler }); }; public unregisterEventHandler = (eventHandler: IEventHandler) => { this.customCtrlPlugin?.unregisterProps({ eventHandler }); }; private setKeymapConfiguration = (keymap?: TSylKeymap) => { if (this.keymapConfiguration !== keymap || !keymap) this.unregisterKeymap(this.keymapConfiguration); this.keymapConfiguration = keymap || {}; this.registerKeymap(this.keymapConfiguration); }; public registerKeymap = (keymap: TSylKeymap) => { this.customKeyMapPlugin && this.customKeyMapPlugin.registerProps(keymap); }; public unregisterKeymap = (keymap: Types.StringMap<TKeymapHandler>) => { this.customKeyMapPlugin && this.customKeyMapPlugin.unregisterProps(keymap); }; public on(event: TSylEventType, handler: (...args: any[]) => void) { return this.baseConfiguration.emitter.on(event, handler); } public off(event: TSylEventType, handler: (...args: Array<any>) => void) { return this.baseConfiguration.emitter.off(event, handler); } public emit(event: TSylEventType, ...args: any[]): boolean { return this.baseConfiguration.emitter.emit(event, ...args); } public getLocaleValue(name: string) { if (!this.localStore) return ''; return this.localStore._get(name); } public setEditable(editable: boolean) { const { state, dispatch } = this.view; dispatch(state.tr.setMeta(BSControlKey, { editable })); } public setShortcutAble(enable: boolean) { const { state, dispatch } = this.view; dispatch(state.tr.setMeta(SHORTCUT_KEY, enable)); } public setLocale(locale?: Types.StringMap<any>) { if (!locale) return; if (!this.localStore) this.localStore = new LocaleStore(this.baseConfiguration.locale); this.localStore._set(locale); return this.emit(EventChannel.LocalEvent.LOCALE_CHANGE); } public getSylPlugins(): SylPlugin<any>[] { return this.sylPluginInstances; } public uninstall() { this.emit(EventChannel.LocalEvent.EDITOR_WILL_UNMOUNT); this.view.destroy(); this.moduleManage && this.moduleManage.uninstall(); } } export { IConfiguration, SylConfigurator, TSylEventType };
the_stack
const HEX_CHARS = "0123456789abcdef".split(""); const EXTRA = Uint32Array.of(-2147483648, 8388608, 32768, 128); const SHIFT = Uint32Array.of(24, 16, 8, 0); const blocks = new Uint32Array(80); export class Sha1 { #blocks: Uint32Array; #block: number; #start: number; #bytes: number; #hBytes: number; #finalized: boolean; #hashed: boolean; #h0 = 0x67452301; #h1 = 0xefcdab89; #h2 = 0x98badcfe; #h3 = 0x10325476; #h4 = 0xc3d2e1f0; #lastByteIndex = 0; constructor(sharedMemory = false) { if (sharedMemory) { this.#blocks = blocks.fill(0, 0, 17); } else { this.#blocks = new Uint32Array(80); } this.#h0 = 0x67452301; this.#h1 = 0xefcdab89; this.#h2 = 0x98badcfe; this.#h3 = 0x10325476; this.#h4 = 0xc3d2e1f0; this.#block = this.#start = this.#bytes = this.#hBytes = 0; this.#finalized = this.#hashed = false; } update(data: string | ArrayBuffer | ArrayBufferView): Sha1 { if (this.#finalized) { return this; } let notString = true; let message; if (data instanceof ArrayBuffer) { message = new Uint8Array(data); } else if (ArrayBuffer.isView(data)) { message = new Uint8Array(data.buffer); } else { notString = false; message = String(data); } let code; let index = 0; let i; const start = this.#start; const length = message.length || 0; const blocks = this.#blocks; while (index < length) { if (this.#hashed) { this.#hashed = false; blocks[0] = this.#block; blocks.fill(0, 1, 17); } if (notString) { for (i = start; index < length && i < 64; ++index) { blocks[i >> 2] |= (message[index] as number) << SHIFT[i++ & 3]; } } else { for (i = start; index < length && i < 64; ++index) { code = (message as string).charCodeAt(index); if (code < 0x80) { blocks[i >> 2] |= code << SHIFT[i++ & 3]; } else if (code < 0x800) { blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else if (code < 0xd800 || code >= 0xe000) { blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } else { code = 0x10000 + (((code & 0x3ff) << 10) | ((message as string).charCodeAt(++index) & 0x3ff)); blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; } } } this.#lastByteIndex = i; this.#bytes += i - start; if (i >= 64) { this.#block = blocks[16]; this.#start = i - 64; this.hash(); this.#hashed = true; } else { this.#start = i; } } if (this.#bytes > 4294967295) { this.#hBytes += (this.#bytes / 4294967296) >>> 0; this.#bytes = this.#bytes >>> 0; } return this; } finalize(): void { if (this.#finalized) { return; } this.#finalized = true; const blocks = this.#blocks; const i = this.#lastByteIndex; blocks[16] = this.#block; blocks[i >> 2] |= EXTRA[i & 3]; this.#block = blocks[16]; if (i >= 56) { if (!this.#hashed) { this.hash(); } blocks[0] = this.#block; blocks.fill(0, 1, 17); } blocks[14] = (this.#hBytes << 3) | (this.#bytes >>> 29); blocks[15] = this.#bytes << 3; this.hash(); } hash(): void { let a = this.#h0; let b = this.#h1; let c = this.#h2; let d = this.#h3; let e = this.#h4; let f, j, t; const blocks = this.#blocks; for (j = 16; j < 80; ++j) { t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16]; blocks[j] = (t << 1) | (t >>> 31); } for (j = 0; j < 20; j += 5) { f = (b & c) | (~b & d); t = (a << 5) | (a >>> 27); e = (t + f + e + 1518500249 + blocks[j]) >>> 0; b = (b << 30) | (b >>> 2); f = (a & b) | (~a & c); t = (e << 5) | (e >>> 27); d = (t + f + d + 1518500249 + blocks[j + 1]) >>> 0; a = (a << 30) | (a >>> 2); f = (e & a) | (~e & b); t = (d << 5) | (d >>> 27); c = (t + f + c + 1518500249 + blocks[j + 2]) >>> 0; e = (e << 30) | (e >>> 2); f = (d & e) | (~d & a); t = (c << 5) | (c >>> 27); b = (t + f + b + 1518500249 + blocks[j + 3]) >>> 0; d = (d << 30) | (d >>> 2); f = (c & d) | (~c & e); t = (b << 5) | (b >>> 27); a = (t + f + a + 1518500249 + blocks[j + 4]) >>> 0; c = (c << 30) | (c >>> 2); } for (; j < 40; j += 5) { f = b ^ c ^ d; t = (a << 5) | (a >>> 27); e = (t + f + e + 1859775393 + blocks[j]) >>> 0; b = (b << 30) | (b >>> 2); f = a ^ b ^ c; t = (e << 5) | (e >>> 27); d = (t + f + d + 1859775393 + blocks[j + 1]) >>> 0; a = (a << 30) | (a >>> 2); f = e ^ a ^ b; t = (d << 5) | (d >>> 27); c = (t + f + c + 1859775393 + blocks[j + 2]) >>> 0; e = (e << 30) | (e >>> 2); f = d ^ e ^ a; t = (c << 5) | (c >>> 27); b = (t + f + b + 1859775393 + blocks[j + 3]) >>> 0; d = (d << 30) | (d >>> 2); f = c ^ d ^ e; t = (b << 5) | (b >>> 27); a = (t + f + a + 1859775393 + blocks[j + 4]) >>> 0; c = (c << 30) | (c >>> 2); } for (; j < 60; j += 5) { f = (b & c) | (b & d) | (c & d); t = (a << 5) | (a >>> 27); e = (t + f + e - 1894007588 + blocks[j]) >>> 0; b = (b << 30) | (b >>> 2); f = (a & b) | (a & c) | (b & c); t = (e << 5) | (e >>> 27); d = (t + f + d - 1894007588 + blocks[j + 1]) >>> 0; a = (a << 30) | (a >>> 2); f = (e & a) | (e & b) | (a & b); t = (d << 5) | (d >>> 27); c = (t + f + c - 1894007588 + blocks[j + 2]) >>> 0; e = (e << 30) | (e >>> 2); f = (d & e) | (d & a) | (e & a); t = (c << 5) | (c >>> 27); b = (t + f + b - 1894007588 + blocks[j + 3]) >>> 0; d = (d << 30) | (d >>> 2); f = (c & d) | (c & e) | (d & e); t = (b << 5) | (b >>> 27); a = (t + f + a - 1894007588 + blocks[j + 4]) >>> 0; c = (c << 30) | (c >>> 2); } for (; j < 80; j += 5) { f = b ^ c ^ d; t = (a << 5) | (a >>> 27); e = (t + f + e - 899497514 + blocks[j]) >>> 0; b = (b << 30) | (b >>> 2); f = a ^ b ^ c; t = (e << 5) | (e >>> 27); d = (t + f + d - 899497514 + blocks[j + 1]) >>> 0; a = (a << 30) | (a >>> 2); f = e ^ a ^ b; t = (d << 5) | (d >>> 27); c = (t + f + c - 899497514 + blocks[j + 2]) >>> 0; e = (e << 30) | (e >>> 2); f = d ^ e ^ a; t = (c << 5) | (c >>> 27); b = (t + f + b - 899497514 + blocks[j + 3]) >>> 0; d = (d << 30) | (d >>> 2); f = c ^ d ^ e; t = (b << 5) | (b >>> 27); a = (t + f + a - 899497514 + blocks[j + 4]) >>> 0; c = (c << 30) | (c >>> 2); } this.#h0 = (this.#h0 + a) >>> 0; this.#h1 = (this.#h1 + b) >>> 0; this.#h2 = (this.#h2 + c) >>> 0; this.#h3 = (this.#h3 + d) >>> 0; this.#h4 = (this.#h4 + e) >>> 0; } hex(): string { this.finalize(); const h0 = this.#h0; const h1 = this.#h1; const h2 = this.#h2; const h3 = this.#h3; const h4 = this.#h4; return ( HEX_CHARS[(h0 >> 28) & 0x0f] + HEX_CHARS[(h0 >> 24) & 0x0f] + HEX_CHARS[(h0 >> 20) & 0x0f] + HEX_CHARS[(h0 >> 16) & 0x0f] + HEX_CHARS[(h0 >> 12) & 0x0f] + HEX_CHARS[(h0 >> 8) & 0x0f] + HEX_CHARS[(h0 >> 4) & 0x0f] + HEX_CHARS[h0 & 0x0f] + HEX_CHARS[(h1 >> 28) & 0x0f] + HEX_CHARS[(h1 >> 24) & 0x0f] + HEX_CHARS[(h1 >> 20) & 0x0f] + HEX_CHARS[(h1 >> 16) & 0x0f] + HEX_CHARS[(h1 >> 12) & 0x0f] + HEX_CHARS[(h1 >> 8) & 0x0f] + HEX_CHARS[(h1 >> 4) & 0x0f] + HEX_CHARS[h1 & 0x0f] + HEX_CHARS[(h2 >> 28) & 0x0f] + HEX_CHARS[(h2 >> 24) & 0x0f] + HEX_CHARS[(h2 >> 20) & 0x0f] + HEX_CHARS[(h2 >> 16) & 0x0f] + HEX_CHARS[(h2 >> 12) & 0x0f] + HEX_CHARS[(h2 >> 8) & 0x0f] + HEX_CHARS[(h2 >> 4) & 0x0f] + HEX_CHARS[h2 & 0x0f] + HEX_CHARS[(h3 >> 28) & 0x0f] + HEX_CHARS[(h3 >> 24) & 0x0f] + HEX_CHARS[(h3 >> 20) & 0x0f] + HEX_CHARS[(h3 >> 16) & 0x0f] + HEX_CHARS[(h3 >> 12) & 0x0f] + HEX_CHARS[(h3 >> 8) & 0x0f] + HEX_CHARS[(h3 >> 4) & 0x0f] + HEX_CHARS[h3 & 0x0f] + HEX_CHARS[(h4 >> 28) & 0x0f] + HEX_CHARS[(h4 >> 24) & 0x0f] + HEX_CHARS[(h4 >> 20) & 0x0f] + HEX_CHARS[(h4 >> 16) & 0x0f] + HEX_CHARS[(h4 >> 12) & 0x0f] + HEX_CHARS[(h4 >> 8) & 0x0f] + HEX_CHARS[(h4 >> 4) & 0x0f] + HEX_CHARS[h4 & 0x0f] ); } toString(): string { return this.hex(); } digest(): number[] { this.finalize(); const h0 = this.#h0; const h1 = this.#h1; const h2 = this.#h2; const h3 = this.#h3; const h4 = this.#h4; return [ (h0 >> 24) & 0xff, (h0 >> 16) & 0xff, (h0 >> 8) & 0xff, h0 & 0xff, (h1 >> 24) & 0xff, (h1 >> 16) & 0xff, (h1 >> 8) & 0xff, h1 & 0xff, (h2 >> 24) & 0xff, (h2 >> 16) & 0xff, (h2 >> 8) & 0xff, h2 & 0xff, (h3 >> 24) & 0xff, (h3 >> 16) & 0xff, (h3 >> 8) & 0xff, h3 & 0xff, (h4 >> 24) & 0xff, (h4 >> 16) & 0xff, (h4 >> 8) & 0xff, h4 & 0xff, ]; } array(): number[] { return this.digest(); } arrayBuffer(): ArrayBuffer { this.finalize(); return Uint32Array.of(this.#h0, this.#h1, this.#h2, this.#h3, this.#h4) .buffer; } }
the_stack
// TODO: fix linter // tslint:disable import { Directionality } from '@angular/cdk/bidi'; import { OverlayContainer } from '@angular/cdk/overlay'; import { Platform } from '@angular/cdk/platform'; import { ScrollDispatcher } from '@angular/cdk/scrolling'; import { ChangeDetectionStrategy, Component, DebugElement, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core'; import { waitForAsync, ComponentFixture, fakeAsync, flush, inject, TestBed, tick } from '@angular/core/testing'; import { ControlValueAccessor, FormControl, FormGroup, FormGroupDirective, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule, Validators } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { DOWN_ARROW, END, ENTER, HOME, LEFT_ARROW, RIGHT_ARROW, SPACE, TAB, UP_ARROW, A, ESCAPE } from '@ptsecurity/cdk/keycodes'; import { createKeyboardEvent, dispatchEvent, dispatchFakeEvent, dispatchKeyboardEvent, wrappedErrorMessage } from '@ptsecurity/cdk/testing'; import { ErrorStateMatcher, McOption, McOptionSelectionChange, getMcSelectDynamicMultipleError, getMcSelectNonArrayValueError, getMcSelectNonFunctionValueError } from '@ptsecurity/mosaic/core'; import { McFormFieldModule } from '@ptsecurity/mosaic/form-field'; import { McInputModule } from '@ptsecurity/mosaic/input'; import { merge, Observable, of, Subject, Subscription } from 'rxjs'; import { map } from 'rxjs/operators'; import { McSelectModule } from './index'; import { McSelect } from './select.component'; /** The debounce interval when typing letters to select an option. */ const LETTER_KEY_DEBOUNCE_INTERVAL = 200; const OPTIONS = ['Abakan', 'Almetyevsk', 'Anadyr', 'Anapa', 'Arkhangelsk', 'Astrakhan', 'Barnaul', 'Belgorod', 'Beslan', 'Biysk', 'Birobidzhan', 'Blagoveshchensk', 'Bologoye', 'Bryansk', 'Veliky Novgorod', 'Veliky Ustyug', 'Vladivostok', 'Vladikavkaz', 'Vladimir', 'Volgograd', 'Vologda', 'Vorkuta', 'Voronezh', 'Gatchina', 'Gdov', 'Gelendzhik', 'Gorno-Altaysk', 'Grozny', 'Gudermes', 'Gus-Khrustalny', 'Dzerzhinsk', 'Dmitrov', 'Dubna', 'Yeysk', 'Yekaterinburg', 'Yelabuga', 'Yelets', 'Yessentuki', 'Zlatoust', 'Ivanovo', 'Izhevsk', 'Irkutsk', 'Yoshkar-Ola', 'Kazan', 'Kaliningrad', 'Kaluga', 'Kemerovo', 'Kislovodsk', 'Komsomolsk-on-Amur', 'Kotlas', 'Krasnodar', 'Krasnoyarsk', 'Kurgan', 'Kursk', 'Kyzyl', 'Leninogorsk', 'Lensk', 'Lipetsk', 'Luga', 'Lyuban', 'Lyubertsy', 'Magadan', 'Maykop', 'Makhachkala', 'Miass', 'Mineralnye Vody', 'Mirny', 'Moscow', 'Murmansk', 'Murom', 'Mytishchi', 'Naberezhnye Chelny', 'Nadym', 'Nalchik', 'Nazran', 'Naryan-Mar', 'Nakhodka', 'Nizhnevartovsk', 'Nizhnekamsk', 'Nizhny Novgorod', 'Nizhny Tagil', 'Novokuznetsk', 'Novosibirsk', 'Novy Urengoy', 'Norilsk', 'Obninsk', 'Oktyabrsky', 'Omsk', 'Orenburg', 'Orekhovo-Zuyevo', 'Oryol', 'Penza', 'Perm', 'Petrozavodsk', 'Petropavlovsk-Kamchatsky', 'Podolsk', 'Pskov', 'Pyatigorsk', 'Rostov-on-Don', 'Rybinsk', 'Ryazan', 'Salekhard', 'Samara', 'Saint Petersburg', 'Saransk', 'Saratov', 'Severodvinsk', 'Smolensk', 'Sol-Iletsk', 'Sochi', 'Stavropol', 'Surgut', 'Syktyvkar', 'Tambov', 'Tver', 'Tobolsk', 'Tolyatti', 'Tomsk', 'Tuapse', 'Tula', 'Tynda', 'Tyumen', 'Ulan-Ude', 'Ulyanovsk', 'Ufa', 'Khabarovsk', 'Khanty-Mansiysk', 'Chebarkul', 'Cheboksary', 'Chelyabinsk', 'Cherepovets', 'Cherkessk', 'Chistopol', 'Chita', 'Shadrinsk', 'Shatura', 'Shuya', 'Elista', 'Engels', 'Yuzhno-Sakhalinsk', 'Yakutsk', 'Yaroslavl']; @Component({ selector: 'basic-select', template: ` <div [style.height.px]="heightAbove"></div> <mc-form-field> <mc-select placeholder="Food" [formControl]="control" [required]="isRequired" [tabIndex]="tabIndexOverride" [panelClass]="panelClass"> <mc-option *ngFor="let food of foods" [value]="food.value" [disabled]="food.disabled"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> <div [style.height.px]="heightBelow"></div> ` }) class BasicSelect { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos', disabled: true }, { value: 'sandwich-3', viewValue: 'Sandwich' }, { value: 'chips-4', viewValue: 'Chips' }, { value: 'eggs-5', viewValue: 'Eggs' }, { value: 'pasta-6', viewValue: 'Pasta' }, { value: 'sushi-7', viewValue: 'Sushi' } ]; control = new FormControl(); isRequired: boolean; heightAbove = 0; heightBelow = 0; tabIndexOverride: number; panelClass = ['custom-one', 'custom-two']; @ViewChild(McSelect, { static: true }) select: McSelect; @ViewChildren(McOption) options: QueryList<McOption>; } @Component({ selector: 'basic-events', template: ` <mc-form-field> <mc-select (openedChange)="openedChangeListener($event)" (opened)="openedListener()" (closed)="closedListener()"> <mc-option *ngFor="let food of foods" [value]="food.value" [disabled]="food.disabled"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class BasicEvents { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos', disabled: true }, { value: 'sandwich-3', viewValue: 'Sandwich' }, { value: 'chips-4', viewValue: 'Chips' }, { value: 'eggs-5', viewValue: 'Eggs' }, { value: 'pasta-6', viewValue: 'Pasta' }, { value: 'sushi-7', viewValue: 'Sushi' } ]; @ViewChild(McSelect, { static: true }) select: McSelect; openedChangeListener = jasmine.createSpy('McSelect openedChange listener'); openedListener = jasmine.createSpy('McSelect opened listener'); closedListener = jasmine.createSpy('McSelect closed listener'); } @Component({ selector: 'ng-model-select', template: ` <mc-form-field> <mc-select placeholder="Food" ngModel [disabled]="isDisabled"> <mc-option *ngFor="let food of foods" [value]="food.value">{{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class NgModelSelect { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' } ]; isDisabled: boolean; @ViewChild(McSelect, {static: false}) select: McSelect; @ViewChildren(McOption) options: QueryList<McOption>; } @Component({ selector: 'many-selects', template: ` <mc-form-field> <mc-select placeholder="First"> <mc-option [value]="'one'">one</mc-option> <mc-option [value]="'two'">two</mc-option> </mc-select> </mc-form-field> <mc-form-field> <mc-select placeholder="Second"> <mc-option [value]="'three'">three</mc-option> <mc-option [value]="'four'">four</mc-option> </mc-select> </mc-form-field> ` }) class ManySelects { } @Component({ selector: 'ng-if-select', template: ` <div *ngIf="isShowing"> <mc-form-field> <mc-select placeholder="Food I want to eat right now" [formControl]="control"> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> </div> ` }) class NgIfSelect { isShowing = false; foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' } ]; control = new FormControl('pizza-1'); @ViewChild(McSelect, {static: false}) select: McSelect; } @Component({ selector: 'select-with-change-event', template: ` <mc-form-field> <mc-select (selectionChange)="changeListener($event)"> <mc-option *ngFor="let food of foods" [value]="food">{{ food }}</mc-option> </mc-select> </mc-form-field> ` }) class SelectWithChangeEvent { foods: string[] = [ 'steak-0', 'pizza-1', 'tacos-2', 'sandwich-3', 'chips-4', 'eggs-5', 'pasta-6', 'sushi-7' ]; changeListener = jasmine.createSpy('McSelect change listener'); } @Component({ selector: 'select-with-search', template: ` <mc-form-field> <mc-select #select [(value)]="singleSelectedWithSearch"> <mc-form-field mcSelectSearch> <input mcInput [formControl]="searchCtrl" type="text" /> </mc-form-field> <mc-option *ngFor="let option of options$ | async" [value]="option">{{ option }}</mc-option> </mc-select> </mc-form-field> ` }) class SelectWithSearch { @ViewChild(McSelect, {static: false}) select: McSelect; singleSelectedWithSearch = 'Moscow'; searchCtrl: FormControl = new FormControl(); options$: Observable<string[]>; private options: string[] = OPTIONS; ngOnInit(): void { this.options$ = merge( of(OPTIONS), this.searchCtrl.valueChanges .pipe(map((value) => this.getFilteredOptions(value))) ); } private getFilteredOptions(value): string[] { const searchFilter = (value && value.new) ? value.value : value; return searchFilter ? this.options.filter((option) => option.toLowerCase().includes((searchFilter.toLowerCase()))) : this.options; } } @Component({ selector: 'custom-select-accessor', template: ` <mc-form-field> <mc-select></mc-select> </mc-form-field>`, providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: CustomSelectAccessor, multi: true }] }) class CustomSelectAccessor implements ControlValueAccessor { @ViewChild(McSelect, {static: false}) select: McSelect; writeValue: (value?: any) => void = () => {}; registerOnChange: (changeFn?: (value: any) => void) => void = () => {}; registerOnTouched: (touchedFn?: () => void) => void = () => {}; } @Component({ selector: 'comp-with-custom-select', template: ` <custom-select-accessor [formControl]="ctrl"></custom-select-accessor>`, providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: CustomSelectAccessor, multi: true }] }) class CompWithCustomSelect { ctrl = new FormControl('initial value'); @ViewChild(CustomSelectAccessor, {static: true}) customAccessor: CustomSelectAccessor; } @Component({ selector: 'select-infinite-loop', template: ` <mc-form-field> <mc-select [(ngModel)]="value"></mc-select> </mc-form-field> <throws-error-on-init></throws-error-on-init> ` }) class SelectWithErrorSibling { value: string; } @Component({ selector: 'throws-error-on-init', template: '' }) class ThrowsErrorOnInit implements OnInit { ngOnInit() { throw Error('Oh no!'); } } @Component({ selector: 'basic-select-on-push', changeDetection: ChangeDetectionStrategy.OnPush, template: ` <mc-form-field> <mc-select placeholder="Food" [formControl]="control"> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class BasicSelectOnPush { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' } ]; control = new FormControl(); } @Component({ selector: 'basic-select-on-push-preselected', changeDetection: ChangeDetectionStrategy.OnPush, template: ` <mc-form-field> <mc-select placeholder="Food" [formControl]="control"> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class BasicSelectOnPushPreselected { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' } ]; control = new FormControl('pizza-1'); } @Component({ selector: 'multi-select', template: ` <mc-form-field> <mc-select multiple placeholder="Food" [formControl]="control" [sortComparator]="sortComparator"> <mc-option *ngFor="let food of foods" [value]="food.value">{{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class MultiSelect { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' }, { value: 'sandwich-3', viewValue: 'Sandwich' }, { value: 'chips-4', viewValue: 'Chips' }, { value: 'eggs-5', viewValue: 'Eggs' }, { value: 'pasta-6', viewValue: 'Pasta' }, { value: 'sushi-7', viewValue: 'Sushi' } ]; control = new FormControl(); @ViewChild(McSelect, {static: false}) select: McSelect; @ViewChildren(McOption) options: QueryList<McOption>; sortComparator: (a: McOption, b: McOption, options: McOption[]) => number; } @Component({ selector: 'select-with-plain-tabindex', template: ` <mc-form-field> <mc-select [tabIndex]="5"></mc-select> </mc-form-field>` }) class SelectWithPlainTabindex {} @Component({ selector: 'select-early-sibling-access', template: ` <mc-form-field> <mc-select #select="mcSelect"></mc-select> </mc-form-field> <div *ngIf="select.selected"></div> ` }) class SelectEarlyAccessSibling { } @Component({ selector: 'basic-select-initially-hidden', template: ` <mc-form-field> <mc-select [style.display]="isVisible ? 'block' : 'none'"> <mc-option [value]="'value'">There are no other options</mc-option> </mc-select> </mc-form-field> ` }) class BasicSelectInitiallyHidden { isVisible = false; } @Component({ selector: 'basic-select-no-placeholder', template: ` <mc-form-field> <mc-select> <mc-option [value]="'value'">There are no other options</mc-option> </mc-select> </mc-form-field> ` }) class BasicSelectNoPlaceholder { } @Component({ selector: 'basic-select-with-theming', template: ` <mc-form-field [color]="theme"> <mc-select placeholder="Food"> <mc-option [value]="'steak'-0">Steak</mc-option> <mc-option [value]="'pizza'-1">Pizza</mc-option> </mc-select> </mc-form-field> ` }) class BasicSelectWithTheming { @ViewChild(McSelect, {static: false}) select: McSelect; theme: string; } @Component({ selector: 'reset-values-select', template: ` <mc-form-field> <mc-select placeholder="Food" [formControl]="control"> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> <mc-option>None</mc-option> </mc-select> </mc-form-field> ` }) class ResetValuesSelect { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' }, { value: false, viewValue: 'Falsy' }, { viewValue: 'Undefined' }, { value: null, viewValue: 'Null' } ]; control = new FormControl(); @ViewChild(McSelect, {static: false}) select: McSelect; } @Component({ template: ` <mc-form-field> <mc-select [formControl]="control"> <mc-option *ngFor="let food of foods" [value]="food.value">{{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class FalsyValueSelect { foods: any[] = [ { value: 0, viewValue: 'Steak' }, { value: 1, viewValue: 'Pizza' } ]; control = new FormControl(); @ViewChildren(McOption) options: QueryList<McOption>; } @Component({ selector: 'select-with-groups', template: ` <mc-form-field> <mc-select placeholder="Pokemon" [formControl]="control"> <mc-optgroup *ngFor="let group of pokemonTypes" [label]="group.name" [disabled]="group.disabled"> <mc-option *ngFor="let pokemon of group.pokemon" [value]="pokemon.value"> {{ pokemon.viewValue }} </mc-option> </mc-optgroup> <mc-option [value]="'mime'-11">Mr. Mime</mc-option> </mc-select> </mc-form-field> ` }) class SelectWithGroups { control = new FormControl(); pokemonTypes = [ { name: 'Grass', pokemon: [ { value: 'bulbasaur-0', viewValue: 'Bulbasaur' }, { value: 'oddish-1', viewValue: 'Oddish' }, { value: 'bellsprout-2', viewValue: 'Bellsprout' } ] }, { name: 'Water', disabled: true, pokemon: [ { value: 'squirtle-3', viewValue: 'Squirtle' }, { value: 'psyduck-4', viewValue: 'Psyduck' }, { value: 'horsea-5', viewValue: 'Horsea' } ] }, { name: 'Fire', pokemon: [ { value: 'charmander-6', viewValue: 'Charmander' }, { value: 'vulpix-7', viewValue: 'Vulpix' }, { value: 'flareon-8', viewValue: 'Flareon' } ] }, { name: 'Psychic', pokemon: [ { value: 'mew-9', viewValue: 'Mew' }, { value: 'mewtwo-10', viewValue: 'Mewtwo' } ] } ]; @ViewChild(McSelect, {static: false}) select: McSelect; @ViewChildren(McOption) options: QueryList<McOption>; } @Component({ selector: 'select-with-groups', template: ` <mc-form-field> <mc-select placeholder="Pokemon" [formControl]="control"> <mc-optgroup *ngFor="let group of pokemonTypes" [label]="group.name" [disabled]="group.disabled"> <ng-container *ngFor="let pokemon of group.pokemon"> <mc-option [value]="pokemon.value">{{ pokemon.viewValue }}</mc-option> </ng-container> </mc-optgroup> </mc-select> </mc-form-field> ` }) class SelectWithGroupsAndNgContainer { control = new FormControl(); pokemonTypes = [{ name: 'Grass', pokemon: [{ value: 'bulbasaur-0', viewValue: 'Bulbasaur' }] }]; } @Component({ template: ` <form> <mc-form-field> <mc-select [(ngModel)]="value"></mc-select> </mc-form-field> </form> ` }) class InvalidSelectInForm { value: any; } @Component({ template: ` <form [formGroup]="formGroup"> <mc-form-field> <mc-select placeholder="Food" formControlName="food"> <mc-option [value]="'steak'-0">Steak</mc-option> <mc-option [value]="'pizza'-1">Pizza</mc-option> </mc-select> <!--<mc-error>This field is required</mc-error>--> </mc-form-field> </form> ` }) class SelectInsideFormGroup { @ViewChild(FormGroupDirective, {static: false}) formGroupDirective: FormGroupDirective; @ViewChild(McSelect, {static: false}) select: McSelect; formControl = new FormControl('', Validators.required); formGroup = new FormGroup({ food: this.formControl }); } @Component({ template: ` <mc-form-field> <mc-select placeholder="Food" [(value)]="selectedFood"> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class BasicSelectWithoutForms { selectedFood: string | null; foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'sandwich-2', viewValue: 'Sandwich' } ]; @ViewChild(McSelect, {static: false}) select: McSelect; } @Component({ template: ` <mc-form-field> <mc-select placeholder="Food" [(value)]="selectedFood"> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class BasicSelectWithoutFormsPreselected { selectedFood = 'pizza-1'; foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' } ]; @ViewChild(McSelect, {static: false}) select: McSelect; } @Component({ template: ` <mc-form-field> <mc-select placeholder="Food" [(value)]="selectedFoods" multiple> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class BasicSelectWithoutFormsMultiple { selectedFoods: string[]; foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'sandwich-2', viewValue: 'Sandwich' } ]; @ViewChild(McSelect, {static: false}) select: McSelect; } @Component({ selector: 'select-with-custom-trigger', template: ` <mc-form-field> <mc-select placeholder="Food" [formControl]="control" #select="mcSelect"> <mc-select__trigger> {{ select.selected?.viewValue.split('').reverse().join('') }} </mc-select__trigger> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class SelectWithCustomTrigger { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' } ]; control = new FormControl(); } @Component({ selector: 'ng-model-compare-with', template: ` <mc-form-field> <mc-select [ngModel]="selectedFood" (ngModelChange)="setFoodByCopy($event)" [compareWith]="comparator"> <mc-option *ngFor="let food of foods" [value]="food">{{ food.viewValue }}</mc-option> </mc-select> </mc-form-field> ` }) class NgModelCompareWithSelect { foods: ({ value: string; viewValue: string })[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' } ]; selectedFood: { value: string; viewValue: string } = { value: 'pizza-1', viewValue: 'Pizza' }; comparator: ((f1: any, f2: any) => boolean) | null = this.compareByValue; @ViewChild(McSelect, {static: false}) select: McSelect; @ViewChildren(McOption) options: QueryList<McOption>; useCompareByValue() { this.comparator = this.compareByValue; } useCompareByReference() { this.comparator = this.compareByReference; } useNullComparator() { this.comparator = null; } compareByValue(f1: any, f2: any) { return f1 && f2 && f1.value === f2.value; } compareByReference(f1: any, f2: any) { return f1 === f2; } setFoodByCopy(newValue: { value: string; viewValue: string }) { this.selectedFood = { ...{}, ...newValue }; } } @Component({ template: ` <mc-select placeholder="Food" [formControl]="control" [errorStateMatcher]="errorStateMatcher"> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> ` }) class CustomErrorBehaviorSelect { @ViewChild(McSelect, {static: false}) select: McSelect; control = new FormControl(); foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' } ]; errorStateMatcher: ErrorStateMatcher; } @Component({ template: ` <mc-form-field> <mc-select placeholder="Food" [(ngModel)]="selectedFoods"> <mc-option *ngFor="let food of foods" [value]="food.value">{{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class SingleSelectWithPreselectedArrayValues { foods: any[] = [ { value: ['steak-0', 'steak-1'], viewValue: 'Steak' }, { value: ['pizza-1', 'pizza-2'], viewValue: 'Pizza' }, { value: ['tacos-2', 'tacos-3'], viewValue: 'Tacos' } ]; selectedFoods = this.foods[1].value; @ViewChild(McSelect, {static: false}) select: McSelect; @ViewChildren(McOption) options: QueryList<McOption>; } @Component({ selector: 'select-without-option-centering', template: ` <mc-form-field> <mc-select placeholder="Food" [formControl]="control"> <mc-option *ngFor="let food of foods" [value]="food.value"> {{ food.viewValue }} </mc-option> </mc-select> </mc-form-field> ` }) class SelectWithoutOptionCentering { foods: any[] = [ { value: 'steak-0', viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: 'tacos-2', viewValue: 'Tacos' }, { value: 'sandwich-3', viewValue: 'Sandwich' }, { value: 'chips-4', viewValue: 'Chips' }, { value: 'eggs-5', viewValue: 'Eggs' }, { value: 'pasta-6', viewValue: 'Pasta' }, { value: 'sushi-7', viewValue: 'Sushi' } ]; control = new FormControl('pizza-1'); @ViewChild(McSelect, {static: false}) select: McSelect; @ViewChildren(McOption) options: QueryList<McOption>; } @Component({ template: ` <mc-form-field> <!--<mc-label>Select a thing</mc-label>--> <mc-select [placeholder]="placeholder"> <mc-option [value]="'thing'">A thing</mc-option> </mc-select> </mc-form-field> ` }) class SelectWithFormFieldLabel { placeholder: string; } describe('McSelect', () => { let overlayContainer: OverlayContainer; let overlayContainerElement: HTMLElement; let dir: { value: 'ltr' | 'rtl' }; const scrolledSubject: Subject<any> = new Subject(); let platform: Platform; /** * Configures the test module for McSelect with the given declarations. This is broken out so * that we're only compiling the necessary test components for each test in order to speed up * overall test time. * @param declarations Components to declare for this block */ function configureMcSelectTestingModule(declarations: any[]) { TestBed.configureTestingModule({ imports: [ McFormFieldModule, McSelectModule, McInputModule, ReactiveFormsModule, FormsModule, NoopAnimationsModule ], declarations, providers: [ { provide: Directionality, useFactory: () => dir = { value: 'ltr' } }, { provide: ScrollDispatcher, useFactory: () => ({ scrolled: () => scrolledSubject.asObservable() }) } ] }).compileComponents(); inject([OverlayContainer, Platform], (oc: OverlayContainer, p: Platform) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); platform = p; })(); } afterEach(() => { overlayContainer.ngOnDestroy(); }); describe('core', () => { beforeEach(waitForAsync(() => { configureMcSelectTestingModule([ BasicSelect, BasicEvents, MultiSelect, SelectWithGroups, SelectWithGroupsAndNgContainer, SelectWithFormFieldLabel, SelectWithChangeEvent ]); })); describe('accessibility', () => { describe('for select', () => { let fixture: ComponentFixture<BasicSelect>; let select: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicSelect); fixture.detectChanges(); select = fixture.debugElement.query(By.css('mc-select')).nativeElement; })); it('should set the tabindex of the select to 0 by default', fakeAsync(() => { expect(select.getAttribute('tabindex')).toEqual('0'); })); it('should be able to override the tabindex', fakeAsync(() => { fixture.componentInstance.tabIndexOverride = 3; fixture.detectChanges(); expect(select.getAttribute('tabindex')).toBe('3'); })); it('should set the tabindex of the select to -1 if disabled', fakeAsync(() => { fixture.componentInstance.control.disable(); fixture.detectChanges(); expect(select.getAttribute('tabindex')).toEqual('-1'); fixture.componentInstance.control.enable(); fixture.detectChanges(); expect(select.getAttribute('tabindex')).toEqual('0'); })); it('should select options via the UP/DOWN arrow keys on a closed select', fakeAsync(() => { const formControl = fixture.componentInstance.control; const options = fixture.componentInstance.options.toArray(); expect(formControl.value).toBeFalsy('Expected no initial value.'); dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); expect(options[0].selected).toBe(true, 'Expected first option to be selected.'); expect(formControl.value).toBe(options[0].value, 'Expected value from first option to have been set on the model.'); dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); // Note that the third option is skipped, because it is disabled. expect(options[3].selected).toBe(true, 'Expected fourth option to be selected.'); expect(formControl.value).toBe(options[3].value, 'Expected value from fourth option to have been set on the model.'); dispatchKeyboardEvent(select, 'keydown', UP_ARROW); expect(options[1].selected).toBe(true, 'Expected second option to be selected.'); expect(formControl.value).toBe(options[1].value, 'Expected value from second option to have been set on the model.'); })); it('should resume focus from selected item after selecting via click', fakeAsync(() => { const formControl = fixture.componentInstance.control; const options = fixture.componentInstance.options.toArray(); expect(formControl.value).toBeFalsy('Expected no initial value.'); fixture.componentInstance.select.open(); fixture.detectChanges(); flush(); (overlayContainerElement.querySelectorAll('mc-option')[3] as HTMLElement).click(); fixture.detectChanges(); flush(); expect(formControl.value).toBe(options[3].value); dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); fixture.detectChanges(); expect(formControl.value).toBe(options[4].value); })); it('should select options via LEFT/RIGHT arrow keys on a closed select', fakeAsync(() => { const formControl = fixture.componentInstance.control; const options = fixture.componentInstance.options.toArray(); expect(formControl.value).toBeFalsy('Expected no initial value.'); dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW); expect(options[0].selected).toBe(true, 'Expected first option to be selected.'); expect(formControl.value).toBe(options[0].value, 'Expected value from first option to have been set on the model.'); dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW); dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW); // Note that the third option is skipped, because it is disabled. expect(options[3].selected).toBe(true, 'Expected fourth option to be selected.'); expect(formControl.value).toBe(options[3].value, 'Expected value from fourth option to have been set on the model.'); dispatchKeyboardEvent(select, 'keydown', LEFT_ARROW); expect(options[1].selected).toBe(true, 'Expected second option to be selected.'); expect(formControl.value).toBe(options[1].value, 'Expected value from second option to have been set on the model.'); })); it('should open a single-selection select using ALT + DOWN_ARROW', fakeAsync(() => { const { control: formControl, select: selectInstance } = fixture.componentInstance; expect(selectInstance.panelOpen).toBe(false, 'Expected select to be closed.'); expect(formControl.value).toBeFalsy('Expected no initial value.'); const event = createKeyboardEvent('keydown', DOWN_ARROW); Object.defineProperty(event, 'altKey', { get: () => true }); dispatchEvent(select, event); expect(selectInstance.panelOpen).toBe(true, 'Expected select to be open.'); expect(formControl.value).toBeFalsy('Expected value not to have changed.'); })); it('should open a single-selection select using ALT + UP_ARROW', fakeAsync(() => { const { control: formControl, select: selectInstance } = fixture.componentInstance; expect(selectInstance.panelOpen).toBe(false, 'Expected select to be closed.'); expect(formControl.value).toBeFalsy('Expected no initial value.'); const event = createKeyboardEvent('keydown', UP_ARROW); Object.defineProperty(event, 'altKey', { get: () => true }); dispatchEvent(select, event); expect(selectInstance.panelOpen).toBe(true, 'Expected select to be open.'); expect(formControl.value).toBeFalsy('Expected value not to have changed.'); })); it('should should close when pressing ALT + DOWN_ARROW', fakeAsync(() => { const { select: selectInstance } = fixture.componentInstance; selectInstance.open(); expect(selectInstance.panelOpen).toBe(true, 'Expected select to be open.'); const event = createKeyboardEvent('keydown', DOWN_ARROW); Object.defineProperty(event, 'altKey', { get: () => true }); dispatchEvent(select, event); expect(selectInstance.panelOpen).toBe(false, 'Expected select to be closed.'); expect(event.defaultPrevented).toBe(true, 'Expected default action to be prevented.'); })); it('should should close when pressing ALT + UP_ARROW', fakeAsync(() => { const { select: selectInstance } = fixture.componentInstance; selectInstance.open(); expect(selectInstance.panelOpen).toBe(true, 'Expected select to be open.'); const event = createKeyboardEvent('keydown', UP_ARROW); Object.defineProperty(event, 'altKey', { get: () => true }); dispatchEvent(select, event); expect(selectInstance.panelOpen).toBe(false, 'Expected select to be closed.'); expect(event.defaultPrevented).toBe(true, 'Expected default action to be prevented.'); })); it('should be able to select options by typing on a closed select', fakeAsync(() => { const formControl = fixture.componentInstance.control; const options = fixture.componentInstance.options.toArray(); expect(formControl.value).toBeFalsy('Expected no initial value.'); dispatchEvent(select, createKeyboardEvent('keydown', 80, undefined, 'p')); tick(200); expect(options[1].selected).toBe(true, 'Expected second option to be selected.'); expect(formControl.value).toBe(options[1].value, 'Expected value from second option to have been set on the model.'); dispatchEvent(select, createKeyboardEvent('keydown', 69, undefined, 'e')); tick(200); expect(options[5].selected).toBe(true, 'Expected sixth option to be selected.'); expect(formControl.value).toBe(options[5].value, 'Expected value from sixth option to have been set on the model.'); })); it('should open the panel when pressing a vertical arrow key on a closed multiple select', fakeAsync(() => { fixture.destroy(); const multiFixture = TestBed.createComponent(MultiSelect); const instance = multiFixture.componentInstance; multiFixture.detectChanges(); select = multiFixture.debugElement.query(By.css('mc-select')).nativeElement; const initialValue = instance.control.value; expect(instance.select.panelOpen).toBe(false, 'Expected panel to be closed.'); const event = dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); expect(instance.select.panelOpen).toBe(true, 'Expected panel to be open.'); expect(instance.control.value).toBe(initialValue, 'Expected value to stay the same.'); expect(event.defaultPrevented).toBe(true, 'Expected default to be prevented.'); })); it('should open the panel when pressing a horizontal arrow key on closed multiple select', fakeAsync(() => { fixture.destroy(); const multiFixture = TestBed.createComponent(MultiSelect); const instance = multiFixture.componentInstance; multiFixture.detectChanges(); select = multiFixture.debugElement.query(By.css('mc-select')).nativeElement; const initialValue = instance.control.value; expect(instance.select.panelOpen).toBe(false, 'Expected panel to be closed.'); const event = dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW); expect(instance.select.panelOpen).toBe(true, 'Expected panel to be open.'); expect(instance.control.value).toBe(initialValue, 'Expected value to stay the same.'); expect(event.defaultPrevented).toBe(true, 'Expected default to be prevented.'); })); it('should do nothing when typing on a closed multi-select', fakeAsync(() => { fixture.destroy(); const multiFixture = TestBed.createComponent(MultiSelect); const instance = multiFixture.componentInstance; multiFixture.detectChanges(); select = multiFixture.debugElement.query(By.css('mc-select')).nativeElement; const initialValue = instance.control.value; expect(instance.select.panelOpen).toBe(false, 'Expected panel to be closed.'); dispatchEvent(select, createKeyboardEvent('keydown', 80, undefined, 'p')); expect(instance.select.panelOpen).toBe(false, 'Expected panel to stay closed.'); expect(instance.control.value).toBe(initialValue, 'Expected value to stay the same.'); })); it('should do nothing if the key manager did not change the active item', fakeAsync(() => { const formControl = fixture.componentInstance.control; expect(formControl.value).toBeNull('Expected form control value to be empty.'); expect(formControl.pristine).toBe(true, 'Expected form control to be clean.'); dispatchKeyboardEvent(select, 'keydown', 16); // Press a random key. expect(formControl.value).toBeNull('Expected form control value to stay empty.'); expect(formControl.pristine).toBe(true, 'Expected form control to stay clean.'); })); it('should continue from the selected option when the value is set programmatically', fakeAsync(() => { const formControl = fixture.componentInstance.control; formControl.setValue('eggs-5'); dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); expect(formControl.value).toBe('pasta-6'); expect(fixture.componentInstance.options.toArray()[6].selected).toBe(true); })); xit('should not shift focus when the selected options are updated programmatically ' + 'in a multi select', fakeAsync(() => { fixture.destroy(); const multiFixture = TestBed.createComponent(MultiSelect); multiFixture.detectChanges(); select = multiFixture.debugElement.query(By.css('mc-select')).nativeElement; multiFixture.componentInstance.select.open(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[3].focus(); expect(document.activeElement).toBe(options[3], 'Expected fourth option to be focused.'); multiFixture.componentInstance.control.setValue(['steak-0', 'sushi-7']); expect(document.activeElement) .toBe(options[3], 'Expected fourth option to remain focused.'); })); it('should not cycle through the options if the control is disabled', fakeAsync(() => { const formControl = fixture.componentInstance.control; formControl.setValue('eggs-5'); formControl.disable(); dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); expect(formControl.value).toBe('eggs-5', 'Expected value to remain unchaged.'); })); it('should not wrap selection after reaching the end of the options', fakeAsync(() => { const lastOption = fixture.componentInstance.options.last; fixture.componentInstance.options.forEach(() => { dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); }); expect(lastOption.selected).toBe(true, 'Expected last option to be selected.'); dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); expect(lastOption.selected).toBe(true, 'Expected last option to stay selected.'); })); it('should not open a multiple select when tabbing through', fakeAsync(() => { fixture.destroy(); const multiFixture = TestBed.createComponent(MultiSelect); multiFixture.detectChanges(); select = multiFixture.debugElement.query(By.css('mc-select')).nativeElement; expect(multiFixture.componentInstance.select.panelOpen) .toBe(false, 'Expected panel to be closed initially.'); dispatchKeyboardEvent(select, 'keydown', TAB); expect(multiFixture.componentInstance.select.panelOpen) .toBe(false, 'Expected panel to stay closed.'); })); it('should toggle the next option when pressing shift + DOWN_ARROW on a multi-select', fakeAsync(() => { fixture.destroy(); const multiFixture = TestBed.createComponent(MultiSelect); const event = createKeyboardEvent('keydown', DOWN_ARROW); Object.defineProperty(event, 'shiftKey', { get: () => true }); multiFixture.detectChanges(); select = multiFixture.debugElement.query(By.css('mc-select')).nativeElement; multiFixture.componentInstance.select.open(); multiFixture.detectChanges(); flush(); expect(multiFixture.componentInstance.select.value).toBeFalsy(); dispatchEvent(select, event); expect(multiFixture.componentInstance.select.value).toEqual(['pizza-1']); dispatchEvent(select, event); expect(multiFixture.componentInstance.select.value).toEqual(['pizza-1', 'tacos-2']); })); xit('should toggle the previous option when pressing shift + UP_ARROW on a multi-select', fakeAsync(() => { fixture.destroy(); const multiFixture = TestBed.createComponent(MultiSelect); const event = createKeyboardEvent('keydown', UP_ARROW); Object.defineProperty(event, 'shiftKey', { get: () => true }); multiFixture.detectChanges(); select = multiFixture.debugElement.query(By.css('mc-select')).nativeElement; multiFixture.componentInstance.select.open(); multiFixture.detectChanges(); flush(); // Move focus down first. for (let i = 0; i < 5; i++) { dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); multiFixture.detectChanges(); } expect(multiFixture.componentInstance.select.value).toBeFalsy(); dispatchEvent(select, event); expect(multiFixture.componentInstance.select.value).toEqual(['chips-4']); dispatchEvent(select, event); expect(multiFixture.componentInstance.select.value).toEqual(['sandwich-3', 'chips-4']); })); it('should prevent the default action when pressing space', fakeAsync(() => { const event = dispatchKeyboardEvent(select, 'keydown', SPACE); expect(event.defaultPrevented).toBe(true); })); it('should consider the selection a result of a user action when closed', fakeAsync(() => { const option = fixture.componentInstance.options.first; const spy = jasmine.createSpy('option selection spy'); const subscription = option.onSelectionChange.pipe(map((e) => e.isUserInput)).subscribe(spy); dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); expect(spy).toHaveBeenCalledWith(true); subscription.unsubscribe(); })); it('should be able to focus the select trigger', fakeAsync(() => { document.body.focus(); // ensure that focus isn't on the trigger already fixture.componentInstance.select.focus(); expect(document.activeElement).toBe(select, 'Expected select element to be focused.'); })); xit('should restore focus to the trigger after selecting an option in multi-select mode', fakeAsync(() => { fixture.destroy(); const multiFixture = TestBed.createComponent(MultiSelect); const instance = multiFixture.componentInstance; multiFixture.detectChanges(); select = multiFixture.debugElement.query(By.css('mc-select')).nativeElement; instance.select.open(); // Ensure that the select isn't focused to begin with. select.blur(); expect(document.activeElement).not.toBe(select, 'Expected trigger not to be focused.'); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); expect(document.activeElement).toBe(select, 'Expected trigger to be focused.'); })); }); describe('for options', () => { let fixture: ComponentFixture<BasicSelect>; let trigger: HTMLElement; let options: NodeListOf<HTMLElement>; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicSelect); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.click(); fixture.detectChanges(); flush(); options = overlayContainerElement.querySelectorAll('mc-option'); })); it('should set the tabindex of each option according to disabled state', fakeAsync(() => { expect(options[0].getAttribute('tabindex')).toEqual('0'); expect(options[1].getAttribute('tabindex')).toEqual('0'); expect(options[2].getAttribute('tabindex')).toEqual('-1'); })); }); }); describe('overlay panel', () => { let fixture: ComponentFixture<BasicSelect>; let trigger: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicSelect); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; })); it('should not throw when attempting to open too early', () => { // Create component and then immediately open without running change detection fixture = TestBed.createComponent(BasicSelect); expect(() => fixture.componentInstance.select.open()).not.toThrow(); }); it('should open the panel when trigger is clicked', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.panelOpen).toBe(true); expect(overlayContainerElement.textContent).toContain('Steak'); expect(overlayContainerElement.textContent).toContain('Pizza'); expect(overlayContainerElement.textContent).toContain('Tacos'); })); it('should close the panel when an item is clicked', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent).toEqual(''); expect(fixture.componentInstance.select.panelOpen).toBe(false); })); it('should close the panel when a click occurs outside the panel', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); document.body.click(); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent).toEqual(''); expect(fixture.componentInstance.select.panelOpen).toBe(false); })); it('should set the width of the overlay based on the trigger', fakeAsync(() => { trigger.style.width = '200px'; trigger.click(); fixture.detectChanges(); flush(); const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(pane.style.minWidth).toBe('200px'); })); it('should not attempt to open a select that does not have any options', fakeAsync(() => { fixture.componentInstance.foods = []; fixture.detectChanges(); trigger.click(); fixture.detectChanges(); expect(fixture.componentInstance.select.panelOpen).toBe(false); })); it('should close the panel when tabbing out', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.panelOpen).toBe(true); dispatchKeyboardEvent(trigger, 'keydown', TAB); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.panelOpen).toBe(false); })); it('should restore focus to the host before tabbing away', fakeAsync(() => { const select = fixture.nativeElement.querySelector('.mc-select'); trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.panelOpen).toBe(true); // Use a spy since focus can be flaky in unit tests. spyOn(select, 'focus').and.callThrough(); dispatchKeyboardEvent(trigger, 'keydown', TAB); fixture.detectChanges(); flush(); expect(select.focus).toHaveBeenCalled(); })); it('should close when tabbing out from inside the panel', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.panelOpen).toBe(true); const panel = overlayContainerElement.querySelector('.mc-select__panel')!; dispatchKeyboardEvent(panel, 'keydown', TAB); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.panelOpen).toBe(false); })); it('should focus the first option when pressing HOME', fakeAsync(() => { fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); const event = dispatchKeyboardEvent(trigger, 'keydown', HOME); fixture.detectChanges(); expect(fixture.componentInstance.select.keyManager.activeItemIndex).toBe(0); expect(event.defaultPrevented).toBe(true); })); it('should focus the last option when pressing END', fakeAsync(() => { fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); const event = dispatchKeyboardEvent(trigger, 'keydown', END); fixture.detectChanges(); expect(fixture.componentInstance.select.keyManager.activeItemIndex).toBe(7); expect(event.defaultPrevented).toBe(true); })); it('should be able to set extra classes on the panel', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const panel = overlayContainerElement.querySelector('.mc-select__panel') as HTMLElement; expect(panel.classList).toContain('custom-one'); expect(panel.classList).toContain('custom-two'); })); it('should prevent the default action when pressing SPACE on an option', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const option = overlayContainerElement.querySelector('mc-option') as Node; const event = dispatchKeyboardEvent(option, 'keydown', SPACE); expect(event.defaultPrevented).toBe(true); })); it('should prevent the default action when pressing ENTER on an option', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const option = overlayContainerElement.querySelector('mc-option') as Node; const event = dispatchKeyboardEvent(option, 'keydown', ENTER); expect(event.defaultPrevented).toBe(true); })); it('should be able to render options inside groups with an ng-container', fakeAsync(() => { fixture.destroy(); const groupFixture = TestBed.createComponent(SelectWithGroupsAndNgContainer); groupFixture.detectChanges(); trigger = groupFixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.click(); groupFixture.detectChanges(); flush(); expect(document.querySelectorAll('.cdk-overlay-container mc-option').length) .toBeGreaterThan(0, 'Expected at least one option to be rendered.'); })); it('should not consider itself as blurred if the trigger loses focus while the ' + 'panel is still open', fakeAsync(() => { const selectElement = fixture.nativeElement.querySelector('.mc-select'); const selectInstance = fixture.componentInstance.select; dispatchFakeEvent(selectElement, 'focus'); fixture.detectChanges(); /* tslint:disable-next-line:deprecation */ expect(selectInstance.focused).toBe(true, 'Expected select to be focused.'); selectInstance.open(); fixture.detectChanges(); flush(); dispatchFakeEvent(selectElement, 'blur'); fixture.detectChanges(); /* tslint:disable-next-line:deprecation */ expect(selectInstance.focused).toBe(true, 'Expected select element to remain focused.'); })); }); describe('selection logic', () => { let fixture: ComponentFixture<BasicSelect>; let trigger: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicSelect); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; })); it('should focus the first option if no option is selected', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.keyManager.activeItemIndex).toEqual(0); })); it('should select an option when it is clicked', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); let option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); fixture.detectChanges(); flush(); trigger.click(); fixture.detectChanges(); flush(); option = overlayContainerElement.querySelector('mc-option') as HTMLElement; expect(option.classList).toContain('mc-selected'); expect(fixture.componentInstance.options.first.selected).toBe(true); expect(fixture.componentInstance.select.selected) .toBe(fixture.componentInstance.options.first); })); it('should be able to select an option using the McOption API', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const optionInstances = fixture.componentInstance.options.toArray(); const optionNodes: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); optionInstances[1].select(); fixture.detectChanges(); flush(); expect(optionNodes[1].classList).toContain('mc-selected'); expect(optionInstances[1].selected).toBe(true); expect(fixture.componentInstance.select.selected).toBe(optionInstances[1]); })); it('should deselect other options when one is selected', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); let options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); fixture.detectChanges(); flush(); trigger.click(); fixture.detectChanges(); flush(); options = overlayContainerElement.querySelectorAll('mc-option'); expect(options[1].classList).not.toContain('mc-selected'); expect(options[2].classList).not.toContain('mc-selected'); const optionInstances = fixture.componentInstance.options.toArray(); expect(optionInstances[1].selected).toBe(false); expect(optionInstances[2].selected).toBe(false); })); it('should deselect other options when one is programmatically selected', fakeAsync(() => { const control = fixture.componentInstance.control; const foods = fixture.componentInstance.foods; trigger.click(); fixture.detectChanges(); flush(); let options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); fixture.detectChanges(); flush(); control.setValue(foods[1].value); fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); options = overlayContainerElement.querySelectorAll('mc-option'); expect(options[0].classList) .not.toContain('mc-selected', 'Expected first option to no longer be selected'); expect(options[1].classList) .toContain('mc-selected', 'Expected second option to be selected'); const optionInstances = fixture.componentInstance.options.toArray(); expect(optionInstances[0].selected) .toBe(false, 'Expected first option to no longer be selected'); expect(optionInstances[1].selected) .toBe(true, 'Expected second option to be selected'); })); it('should display the selected option in the trigger', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); fixture.detectChanges(); flush(); const value = fixture.debugElement.query(By.css('.mc-select__matcher')).nativeElement; expect(value.textContent).toContain('Steak'); })); it('should focus the selected option if an option is selected', fakeAsync(() => { // must wait for initial writeValue promise to finish flush(); fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); // must wait for animation to finish fixture.detectChanges(); expect(fixture.componentInstance.select.keyManager.activeItemIndex).toEqual(1); })); it('should select an option that was added after initialization', fakeAsync(() => { fixture.componentInstance.foods.push({ viewValue: 'Potatoes', value: 'potatoes-8' }); trigger.click(); fixture.detectChanges(); flush(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[8].click(); fixture.detectChanges(); flush(); expect(trigger.textContent).toContain('Potatoes'); expect(fixture.componentInstance.select.selected) .toBe(fixture.componentInstance.options.last); })); it('should update the trigger when the selected option label is changed', fakeAsync(() => { fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); expect(trigger.querySelector('.mc-select__matcher-text')!.textContent!.trim()) .toBe('Pizza'); fixture.componentInstance.foods[1].viewValue = 'Calzone'; fixture.detectChanges(); flush(); expect(trigger.querySelector('.mc-select__matcher-text')!.textContent!.trim()) .toBe('Calzone'); })); it('should not select disabled options', fakeAsync(() => { trigger.click(); fixture.detectChanges(); expect(fixture.componentInstance.select.selected).toBeUndefined(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[2].click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.panelOpen).toBe(true); expect(options[2].classList).not.toContain('mc-selected'); expect(fixture.componentInstance.select.selected).toBeUndefined(); })); it('should not select options inside a disabled group', fakeAsync(() => { fixture.destroy(); const groupFixture = TestBed.createComponent(SelectWithGroups); groupFixture.detectChanges(); groupFixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement.click(); groupFixture.detectChanges(); const disabledGroup = overlayContainerElement.querySelectorAll('mc-optgroup')[1]; const options: NodeListOf<HTMLElement> = disabledGroup.querySelectorAll('mc-option'); options[0].click(); groupFixture.detectChanges(); flush(); expect(groupFixture.componentInstance.select.panelOpen).toBe(true); expect(options[0].classList).not.toContain('mc-selected'); expect(groupFixture.componentInstance.select.selected).toBeUndefined(); })); it('should not throw if triggerValue accessed with no selected value', fakeAsync(() => { expect(() => fixture.componentInstance.select.triggerValue).not.toThrow(); })); it('should emit to `optionSelectionChanges` when an option is selected', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const spy = jasmine.createSpy('option selection spy'); const subscription = fixture.componentInstance.select.optionSelectionChanges.subscribe(spy); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); fixture.detectChanges(); flush(); expect(spy).toHaveBeenCalledWith(jasmine.any(McOptionSelectionChange)); subscription.unsubscribe(); })); it('should handle accessing `optionSelectionChanges` before the options are initialized', fakeAsync(() => { fixture.destroy(); fixture = TestBed.createComponent(BasicSelect); const spy = jasmine.createSpy('option selection spy'); let subscription: Subscription; expect(fixture.componentInstance.select.options).toBeFalsy(); expect(() => { subscription = fixture.componentInstance.select.optionSelectionChanges.subscribe(spy); }).not.toThrow(); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.click(); fixture.detectChanges(); flush(); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); fixture.detectChanges(); flush(); expect(spy).toHaveBeenCalledWith(jasmine.any(McOptionSelectionChange)); /* tslint:disable-next-line:no-unnecessary-type-assertion */ subscription!.unsubscribe(); })); }); describe('forms integration', () => { let fixture: ComponentFixture<BasicSelect>; let trigger: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicSelect); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; })); it('should take an initial view value with reactive forms', fakeAsync(() => { fixture.componentInstance.control = new FormControl('pizza-1'); fixture.detectChanges(); const value = fixture.debugElement.query(By.css('.mc-select__matcher')); expect(value.nativeElement.textContent) .toContain('Pizza', `Expected trigger to be populated by the control's initial value.`); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.click(); fixture.detectChanges(); flush(); const options = overlayContainerElement.querySelectorAll('mc-option'); expect(options[1].classList) .toContain('mc-selected', `Expected option with the control's initial value to be selected.`); })); it('should set the view value from the form', fakeAsync(() => { let value = fixture.debugElement.query(By.css('.mc-select__matcher')); expect(value.nativeElement.textContent.trim()).toBe('Food'); fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); value = fixture.debugElement.query(By.css('.mc-select__matcher')); expect(value.nativeElement.textContent) .toContain('Pizza', `Expected trigger to be populated by the control's new value.`); trigger.click(); fixture.detectChanges(); flush(); const options = overlayContainerElement.querySelectorAll('mc-option'); expect(options[1].classList).toContain( 'mc-selected', `Expected option with the control's new value to be selected.`); })); it('should update the form value when the view changes', fakeAsync(() => { expect(fixture.componentInstance.control.value) .toEqual(null, `Expected the control's value to be empty initially.`); trigger.click(); fixture.detectChanges(); flush(); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.value) .toEqual('steak-0', `Expected control's value to be set to the new option.`); })); it('should clear the selection when a nonexistent option value is selected', fakeAsync(() => { fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); fixture.componentInstance.control.setValue('gibberish'); fixture.detectChanges(); const value = fixture.debugElement.query(By.css('.mc-select__matcher')); expect(value.nativeElement.textContent.trim()) .toBe('Food', `Expected trigger to show the placeholder.`); expect(trigger.textContent) .not.toContain('Pizza', `Expected trigger is cleared when option value is not found.`); trigger.click(); fixture.detectChanges(); flush(); const options = overlayContainerElement.querySelectorAll('mc-option'); expect(options[1].classList) .not.toContain('mc-selected', `Expected option w/ the old value not to be selected.`); })); it('should clear the selection when the control is reset', fakeAsync(() => { fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); fixture.componentInstance.control.reset(); fixture.detectChanges(); const value = fixture.debugElement.query(By.css('.mc-select__matcher')); expect(value.nativeElement.textContent.trim()) .toBe('Food', `Expected trigger to show the placeholder.`); expect(trigger.textContent) .not.toContain('Pizza', `Expected trigger is cleared when option value is not found.`); trigger.click(); fixture.detectChanges(); flush(); const options = overlayContainerElement.querySelectorAll('mc-option'); expect(options[1].classList) .not.toContain('mc-selected', `Expected option w/ the old value not to be selected.`); })); it('should set the control to touched when the select is blurred', fakeAsync(() => { expect(fixture.componentInstance.control.touched) .toEqual(false, `Expected the control to start off as untouched.`); trigger.click(); dispatchFakeEvent(trigger, 'blur'); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.touched) .toEqual(false, `Expected the control to stay untouched when menu opened.`); document.body.click(); dispatchFakeEvent(trigger, 'blur'); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.touched) .toEqual(true, `Expected the control to be touched as soon as focus left the select.`); })); it('should set the control to touched when the panel is closed', fakeAsync(() => { expect(fixture.componentInstance.control.touched) .toBe(false, 'Expected the control to start off as untouched.'); trigger.click(); dispatchFakeEvent(trigger, 'blur'); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.touched) .toBe(false, 'Expected the control to stay untouched when dropdown opened.'); fixture.componentInstance.select.close(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.touched) .toBe(true, 'Expected the control to be touched when the panel was closed.'); })); it('should not set touched when a disabled select is touched', fakeAsync(() => { expect(fixture.componentInstance.control.touched) .toBe(false, 'Expected the control to start off as untouched.'); fixture.componentInstance.control.disable(); dispatchFakeEvent(trigger, 'blur'); expect(fixture.componentInstance.control.touched) .toBe(false, 'Expected the control to stay untouched.'); })); it('should set the control to dirty when the select value changes in DOM', fakeAsync(() => { expect(fixture.componentInstance.control.dirty) .toEqual(false, `Expected control to start out pristine.`); trigger.click(); fixture.detectChanges(); flush(); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.dirty) .toEqual(true, `Expected control to be dirty after value was changed by user.`); })); it('should not set the control to dirty when the value changes programmatically', fakeAsync(() => { expect(fixture.componentInstance.control.dirty) .toEqual(false, `Expected control to start out pristine.`); fixture.componentInstance.control.setValue('pizza-1'); expect(fixture.componentInstance.control.dirty) .toEqual(false, `Expected control to stay pristine after programmatic change.`); })); xit('should set an asterisk after the label if control is required', fakeAsync(() => { let requiredMarker = fixture.debugElement.query(By.css('.mc-form-field-required-marker')); expect(requiredMarker) .toBeNull(`Expected label not to have an asterisk, as control was not required.`); fixture.componentInstance.isRequired = true; fixture.detectChanges(); requiredMarker = fixture.debugElement.query(By.css('.mc-form-field-required-marker')); expect(requiredMarker) .not.toBeNull(`Expected label to have an asterisk, as control was required.`); })); }); describe('disabled behavior', () => { it('should disable itself when control is disabled programmatically', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelect); fixture.detectChanges(); fixture.componentInstance.control.disable(); fixture.detectChanges(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; expect(getComputedStyle(trigger).getPropertyValue('cursor')) .toEqual('default', `Expected cursor to be default arrow on disabled control.`); trigger.click(); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent) .toEqual('', `Expected select panel to stay closed.`); expect(fixture.componentInstance.select.panelOpen) .toBe(false, `Expected select panelOpen property to stay false.`); fixture.componentInstance.control.enable(); fixture.detectChanges(); expect(getComputedStyle(trigger).getPropertyValue('cursor')) .toEqual('pointer', `Expected cursor to be a pointer on enabled control.`); trigger.click(); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent) .toContain('Steak', `Expected select panel to open normally on re-enabled control`); expect(fixture.componentInstance.select.panelOpen) .toBe(true, `Expected select panelOpen property to become true.`); })); }); describe('keyboard scrolling', () => { let fixture: ComponentFixture<BasicSelect>; let host: HTMLElement; let panel: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicSelect); fixture.componentInstance.foods = []; for (let i = 0; i < 30; i++) { fixture.componentInstance.foods.push({ value: `value-${i}`, viewValue: `Option ${i}` }); } fixture.detectChanges(); fixture.componentInstance.select.open(); fixture.detectChanges(); flush(); host = fixture.debugElement.query(By.css('mc-select')).nativeElement; panel = overlayContainerElement.querySelector('.mc-select__content') as HTMLElement; })); it('should not scroll to options that are completely in the view', fakeAsync(() => { const initialScrollPosition = panel.scrollTop; [1, 2, 3].forEach(() => { dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW); }); expect(panel.scrollTop) .toBe(initialScrollPosition, 'Expected scroll position not to change'); })); it('should scroll down to the active option', fakeAsync(() => { for (let i = 0; i < 15; i++) { dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW); } expect(panel.scrollTop).toBe(316, 'Expected scroll to be at the 16th option.'); })); it('should scroll up to the active option', fakeAsync(() => { // Scroll to the bottom. for (let i = 0; i < fixture.componentInstance.foods.length; i++) { dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW); } for (let i = 0; i < 20; i++) { dispatchKeyboardEvent(host, 'keydown', UP_ARROW); } expect(panel.scrollTop).toBe(252, 'Expected scroll to be at the 9th option.'); })); it('should skip option group labels', fakeAsync(() => { fixture.destroy(); const groupFixture = TestBed.createComponent(SelectWithGroups); groupFixture.detectChanges(); groupFixture.componentInstance.select.open(); groupFixture.detectChanges(); flush(); host = groupFixture.debugElement.query(By.css('mc-select')).nativeElement; panel = overlayContainerElement.querySelector('.mc-select__content') as HTMLElement; for (let i = 0; i < 5; i++) { dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW); } // Note that we press down 5 times, but it will skip // 3 options because the second group is disabled. expect(panel.scrollTop).toBe(188, 'Expected scroll to be at the 9th option.'); })); it('should scroll top the top when pressing HOME', fakeAsync(() => { for (let i = 0; i < 20; i++) { dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW); fixture.detectChanges(); } expect(panel.scrollTop).toBeGreaterThan(0, 'Expected panel to be scrolled down.'); dispatchKeyboardEvent(host, 'keydown', HOME); fixture.detectChanges(); expect(panel.scrollTop).toBe(0, 'Expected panel to be scrolled to the top'); })); it('should scroll to the bottom of the panel when pressing END', fakeAsync(() => { dispatchKeyboardEvent(host, 'keydown', END); fixture.detectChanges(); expect(panel.scrollTop).toBe(728, 'Expected panel to be scrolled to the bottom'); })); it('should scroll to the active option when typing', fakeAsync(() => { for (let i = 0; i < 15; i++) { // Press the letter 'o' 15 times since all the options are named 'Option <index>' dispatchEvent(host, createKeyboardEvent('keydown', 79, undefined, 'o')); fixture.detectChanges(); tick(LETTER_KEY_DEBOUNCE_INTERVAL); } flush(); expect(panel.scrollTop).toBe(316, 'Expected scroll to be at the 16th option.'); })); }); describe('Events', () => { let fixture: ComponentFixture<BasicEvents>; let trigger: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicEvents); fixture.detectChanges(); flush(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; })); it('should fire openedChange event on open select', fakeAsync(() => { expect(fixture.componentInstance.openedChangeListener).not.toHaveBeenCalled(); trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.openedChangeListener).toHaveBeenCalled(); })); it('should fire openedChange event on close select', fakeAsync(() => { expect(fixture.componentInstance.openedChangeListener).not.toHaveBeenCalled(); trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.openedChangeListener).toHaveBeenCalled(); document.body.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.openedChangeListener).toHaveBeenCalledTimes(2); })); it('should fire opened event on open select', fakeAsync(() => { expect(fixture.componentInstance.openedListener).not.toHaveBeenCalled(); trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.openedListener).toHaveBeenCalled(); })); it('should fire closed event on close select', fakeAsync(() => { expect(fixture.componentInstance.closedListener).not.toHaveBeenCalled(); trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.closedListener).not.toHaveBeenCalled(); document.body.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.closedListener).toHaveBeenCalled(); })); }); }); describe('with a search', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([SelectWithSearch]))); let fixture: ComponentFixture<SelectWithSearch>; let trigger: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(SelectWithSearch); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; })); it('should have search input', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); expect(fixture.debugElement.query(By.css('input'))).toBeDefined(); })); it('should search filed should be focused after open', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const input = fixture.debugElement.query(By.css('input')).nativeElement; expect(input).toBe(document.activeElement); })); it('should search', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const inputElementDebug = fixture.debugElement.query(By.css('input')); inputElementDebug.nativeElement.value = 'lu'; inputElementDebug.triggerEventHandler('input', { target: inputElementDebug.nativeElement }); fixture.detectChanges(); flush(); const optionsTexts = fixture.debugElement.queryAll(By.css('mc-option')) .map((el) => el.nativeElement.innerText); expect(optionsTexts).toEqual(['Kaluga', 'Luga']); })); it('should clear search by esc', (() => { trigger.click(); fixture.detectChanges(); const inputElementDebug = fixture.debugElement.query(By.css('input')); inputElementDebug.nativeElement.value = 'lu'; inputElementDebug.triggerEventHandler('input', { target: inputElementDebug.nativeElement }); fixture.detectChanges(); dispatchKeyboardEvent(inputElementDebug.nativeElement, 'keydown', ESCAPE); fixture.detectChanges(); expect(inputElementDebug.nativeElement.value).toBe(''); })); it('should close list by esc if input is empty', () => { trigger.click(); fixture.detectChanges(); const inputElementDebug = fixture.debugElement.query(By.css('input')); dispatchKeyboardEvent(inputElementDebug.nativeElement, 'keydown', ESCAPE); fixture.detectChanges(); const selectInstance = fixture.componentInstance.select; expect(selectInstance.panelOpen).toBe(false); }); }); describe('with a selectionChange event handler', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([SelectWithChangeEvent]))); let fixture: ComponentFixture<SelectWithChangeEvent>; let trigger: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(SelectWithChangeEvent); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; })); it('should emit an event when the selected option has changed', fakeAsync(() => { trigger.click(); fixture.detectChanges(); (overlayContainerElement.querySelector('mc-option') as HTMLElement).click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.changeListener).toHaveBeenCalled(); })); xit('should not emit multiple change events for the same option', fakeAsync(() => { trigger.click(); fixture.detectChanges(); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); option.click(); expect(fixture.componentInstance.changeListener).toHaveBeenCalledTimes(1); })); it('should only emit one event when pressing arrow keys on closed select', fakeAsync(() => { const select = fixture.debugElement.query(By.css('mc-select')).nativeElement; dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW); expect(fixture.componentInstance.changeListener).toHaveBeenCalledTimes(1); })); }); describe('with ngModel', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([NgModelSelect]))); it('should disable itself when control is disabled using the property', fakeAsync(() => { const fixture = TestBed.createComponent(NgModelSelect); fixture.detectChanges(); fixture.componentInstance.isDisabled = true; fixture.detectChanges(); flush(); fixture.detectChanges(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; expect(getComputedStyle(trigger).getPropertyValue('cursor')) .toEqual('default', `Expected cursor to be default arrow on disabled control.`); trigger.click(); fixture.detectChanges(); expect(overlayContainerElement.textContent) .toEqual('', `Expected select panel to stay closed.`); expect(fixture.componentInstance.select.panelOpen) .toBe(false, `Expected select panelOpen property to stay false.`); fixture.componentInstance.isDisabled = false; fixture.detectChanges(); flush(); fixture.detectChanges(); expect(getComputedStyle(trigger).getPropertyValue('cursor')) .toEqual('pointer', `Expected cursor to be a pointer on enabled control.`); trigger.click(); fixture.detectChanges(); flush(); expect(overlayContainerElement.textContent) .toContain('Steak', `Expected select panel to open normally on re-enabled control`); expect(fixture.componentInstance.select.panelOpen) .toBe(true, `Expected select panelOpen property to become true.`); })); }); describe('with ngIf', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([NgIfSelect]))); it('should handle nesting in an ngIf', fakeAsync(() => { const fixture = TestBed.createComponent(NgIfSelect); fixture.detectChanges(); fixture.componentInstance.isShowing = true; fixture.detectChanges(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.style.width = '300px'; trigger.click(); fixture.detectChanges(); flush(); const value = fixture.debugElement.query(By.css('.mc-select__matcher')); expect(value.nativeElement.textContent) .toContain('Pizza', `Expected trigger to be populated by the control's initial value.`); const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(pane.style.minWidth).toEqual('300px'); expect(fixture.componentInstance.select.panelOpen).toBe(true); expect(overlayContainerElement.textContent).toContain('Steak'); expect(overlayContainerElement.textContent).toContain('Pizza'); expect(overlayContainerElement.textContent).toContain('Tacos'); })); }); describe('with multiple mc-select elements in one view', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ManySelects]))); let fixture: ComponentFixture<ManySelects>; let triggers: DebugElement[]; let options: NodeListOf<HTMLElement>; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(ManySelects); fixture.detectChanges(); triggers = fixture.debugElement.queryAll(By.css('.mc-select__trigger')); triggers[0].nativeElement.click(); fixture.detectChanges(); flush(); options = overlayContainerElement.querySelectorAll('mc-option'); })); it('should set the option id properly', fakeAsync(() => { const firstOptionID = options[0].id; expect(options[0].id) .toContain('mc-option', `Expected option ID to have the correct prefix.`); expect(options[0].id).not.toEqual(options[1].id, `Expected option IDs to be unique.`); document.body.click(); fixture.detectChanges(); flush(); triggers[1].nativeElement.click(); fixture.detectChanges(); flush(); options = overlayContainerElement.querySelectorAll('mc-option'); expect(options[0].id) .toContain('mc-option', `Expected option ID to have the correct prefix.`); expect(options[0].id).not.toEqual(firstOptionID, `Expected option IDs to be unique.`); expect(options[0].id).not.toEqual(options[1].id, `Expected option IDs to be unique.`); })); }); describe('with a sibling component that throws an error', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ SelectWithErrorSibling, ThrowsErrorOnInit ]))); it('should not crash the browser when a sibling throws an error on init', fakeAsync(() => { // Note that this test can be considered successful if the error being thrown didn't // end up crashing the testing setup altogether. expect(() => { TestBed.createComponent(SelectWithErrorSibling).detectChanges(); }).toThrowError(new RegExp('Oh no!', 'g')); })); }); describe('change events', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([SelectWithPlainTabindex]))); it('should complete the stateChanges stream on destroy', () => { const fixture = TestBed.createComponent(SelectWithPlainTabindex); fixture.detectChanges(); const debugElement = fixture.debugElement.query(By.directive(McSelect)); const select = debugElement.componentInstance; const spy = jasmine.createSpy('stateChanges complete'); const subscription = select.stateChanges.subscribe(undefined, undefined, spy); fixture.destroy(); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); }); describe('when initially hidden', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([BasicSelectInitiallyHidden]))); it('should set the width of the overlay if the element was hidden initially', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectInitiallyHidden); fixture.detectChanges(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.style.width = '200px'; fixture.componentInstance.isVisible = true; fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(pane.style.minWidth).toBe('200px'); })); }); describe('with no placeholder', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([BasicSelectNoPlaceholder]))); it('should set the width of the overlay if there is no placeholder', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectNoPlaceholder); fixture.detectChanges(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.click(); fixture.detectChanges(); flush(); const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement; expect(parseInt(pane.style.minWidth as string)).toBeGreaterThan(0); })); }); describe('with theming', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([BasicSelectWithTheming]))); let fixture: ComponentFixture<BasicSelectWithTheming>; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicSelectWithTheming); fixture.detectChanges(); })); it('should transfer the theme to the select panel', fakeAsync(() => { fixture.componentInstance.theme = 'error'; fixture.componentInstance.select.open(); fixture.detectChanges(); flush(); const panel = overlayContainerElement.querySelector('.mc-select__panel') as HTMLElement; expect(panel.classList).toContain('mc-error'); })); }); describe('when invalid inside a form', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([InvalidSelectInForm]))); it('should not throw SelectionModel errors in addition to ngModel errors', fakeAsync(() => { const fixture = TestBed.createComponent(InvalidSelectInForm); // The first change detection run will throw the "ngModel is missing a name" error. expect(() => fixture.detectChanges()).toThrowError(/the name attribute must be set/g); // The second run shouldn't throw selection-model related errors. expect(() => fixture.detectChanges()).not.toThrow(); })); }); describe('with ngModel using compareWith', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([NgModelCompareWithSelect]))); let fixture: ComponentFixture<NgModelCompareWithSelect>; let instance: NgModelCompareWithSelect; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(NgModelCompareWithSelect); instance = fixture.componentInstance; fixture.detectChanges(); })); describe('comparing by value', () => { it('should have a selection', fakeAsync(() => { const selectedOption = instance.select.selected as McOption; expect(selectedOption.value.value).toEqual('pizza-1'); })); it('should update when making a new selection', fakeAsync(() => { instance.options.last.selectViaInteraction(); fixture.detectChanges(); flush(); const selectedOption = instance.select.selected as McOption; expect(instance.selectedFood.value).toEqual('tacos-2'); expect(selectedOption.value.value).toEqual('tacos-2'); })); }); describe('comparing by reference', () => { beforeEach(fakeAsync(() => { spyOn(instance, 'compareByReference').and.callThrough(); instance.useCompareByReference(); fixture.detectChanges(); flush(); })); it('should use the comparator', fakeAsync(() => { expect(instance.compareByReference).toHaveBeenCalled(); })); it('should initialize with no selection despite having a value', fakeAsync(() => { expect(instance.selectedFood.value).toBe('pizza-1'); expect(instance.select.selected).toBeUndefined(); })); it('should not update the selection if value is copied on change', fakeAsync(() => { instance.options.first.selectViaInteraction(); fixture.detectChanges(); flush(); expect(instance.selectedFood.value).toEqual('steak-0'); expect(instance.select.selected).toBeUndefined(); })); it('should throw an error when using a non-function comparator', fakeAsync(() => { instance.useNullComparator(); expect(() => { fixture.detectChanges(); }).toThrowError(wrappedErrorMessage(getMcSelectNonFunctionValueError())); })); }); }); describe(`when the select's value is accessed on initialization`, () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([SelectEarlyAccessSibling]))); it('should not throw when trying to access the selected value on init', fakeAsync(() => { expect(() => { TestBed.createComponent(SelectEarlyAccessSibling).detectChanges(); }).not.toThrow(); })); }); describe('inside of a form group', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([SelectInsideFormGroup]))); let fixture: ComponentFixture<SelectInsideFormGroup>; let testComponent: SelectInsideFormGroup; let select: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(SelectInsideFormGroup); fixture.detectChanges(); testComponent = fixture.componentInstance; select = fixture.debugElement.query(By.css('mc-select')).nativeElement; })); it('should not set the invalid class on a clean select', fakeAsync(() => { expect(testComponent.formGroup.untouched).toBe(true, 'Expected the form to be untouched.'); expect(testComponent.formControl.invalid).toBe(false, 'Expected form control to be invalid.'); expect(select.classList) .not.toContain('mc-invalid', 'Expected select not to appear invalid.'); })); it('should not appear as invalid if it becomes touched', fakeAsync(() => { expect(select.classList) .not.toContain('mc-invalid', 'Expected select not to appear invalid.'); testComponent.formControl.markAsTouched(); fixture.detectChanges(); expect(select.classList) .not.toContain('mc-invalid', 'Expected select to appear invalid.'); })); it('should not have the invalid class when the select becomes valid', fakeAsync(() => { testComponent.formControl.markAsTouched(); fixture.detectChanges(); expect(select.classList) .not.toContain('mc-invalid', 'Expected select to appear invalid.'); testComponent.formControl.setValue('pizza-1'); fixture.detectChanges(); flush(); expect(select.classList) .not.toContain('mc-invalid', 'Expected select not to appear invalid.'); })); it('should appear as invalid when the parent form group is submitted', fakeAsync(() => { expect(select.classList) .not.toContain('mc-invalid', 'Expected select not to appear invalid.'); dispatchFakeEvent(fixture.debugElement.query(By.css('form')).nativeElement, 'submit'); fixture.detectChanges(); expect(select.classList) .toContain('mc-invalid', 'Expected select to appear invalid.'); })); xit('should render the error messages when the parent form is submitted', fakeAsync(() => { const debugEl = fixture.debugElement.nativeElement; expect(debugEl.querySelectorAll('mc-error').length).toBe(0, 'Expected no error messages'); dispatchFakeEvent(fixture.debugElement.query(By.css('form')).nativeElement, 'submit'); fixture.detectChanges(); expect(debugEl.querySelectorAll('mc-error').length).toBe(1, 'Expected one error message'); })); it('should override error matching behavior via injection token', fakeAsync(() => { const errorStateMatcher: ErrorStateMatcher = { isErrorState: jasmine.createSpy('error state matcher').and.returnValue(true) }; fixture.destroy(); TestBed.resetTestingModule().configureTestingModule({ imports: [McSelectModule, ReactiveFormsModule, FormsModule, NoopAnimationsModule], declarations: [SelectInsideFormGroup], providers: [{ provide: ErrorStateMatcher, useValue: errorStateMatcher }] }); const errorFixture = TestBed.createComponent(SelectInsideFormGroup); const component = errorFixture.componentInstance; errorFixture.detectChanges(); expect(component.select.errorState).toBe(true); expect(errorStateMatcher.isErrorState).toHaveBeenCalled(); })); }); describe('with custom error behavior', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([CustomErrorBehaviorSelect]))); it('should be able to override the error matching behavior via an @Input', fakeAsync(() => { const fixture = TestBed.createComponent(CustomErrorBehaviorSelect); const component = fixture.componentInstance; const matcher = jasmine.createSpy('error state matcher').and.returnValue(true); fixture.detectChanges(); expect(component.control.invalid).toBe(false); expect(component.select.errorState).toBe(false); fixture.componentInstance.errorStateMatcher = { isErrorState: matcher }; fixture.detectChanges(); expect(component.select.errorState).toBe(true); expect(matcher).toHaveBeenCalled(); })); }); describe('with preselected array values', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ SingleSelectWithPreselectedArrayValues ]))); xit('should be able to preselect an array value in single-selection mode', fakeAsync(() => { const fixture = TestBed.createComponent(SingleSelectWithPreselectedArrayValues); fixture.detectChanges(); flush(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; expect(trigger.textContent).toContain('Pizza'); expect(fixture.componentInstance.options.toArray()[1].selected).toBe(true); })); }); describe('with custom value accessor', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ CompWithCustomSelect, CustomSelectAccessor ]))); it('should support use inside a custom value accessor', fakeAsync(() => { const fixture = TestBed.createComponent(CompWithCustomSelect); spyOn(fixture.componentInstance.customAccessor, 'writeValue'); fixture.detectChanges(); expect(fixture.componentInstance.customAccessor.select.ngControl) .toBeFalsy('Expected mc-select NOT to inherit control from parent value accessor.'); expect(fixture.componentInstance.customAccessor.writeValue).toHaveBeenCalled(); })); }); describe('with a falsy value', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([FalsyValueSelect]))); it('should be able to programmatically select a falsy option', fakeAsync(() => { const fixture = TestBed.createComponent(FalsyValueSelect); fixture.detectChanges(); fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement.click(); fixture.componentInstance.control.setValue(0); fixture.detectChanges(); flush(); expect(fixture.componentInstance.options.first.selected) .toBe(true, 'Expected first option to be selected'); expect(overlayContainerElement.querySelectorAll('mc-option')[0].classList) .toContain('mc-selected', 'Expected first option to be selected'); })); }); describe('with OnPush', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ BasicSelectOnPush, BasicSelectOnPushPreselected ]))); xit('should set the trigger text based on the value when initialized', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectOnPushPreselected); fixture.detectChanges(); flush(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; fixture.detectChanges(); expect(trigger.textContent).toContain('Pizza'); })); xit('should update the trigger based on the value', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectOnPush); fixture.detectChanges(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); expect(trigger.textContent).toContain('Pizza'); fixture.componentInstance.control.reset(); fixture.detectChanges(); expect(trigger.textContent).not.toContain('Pizza'); })); }); describe('with custom trigger', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([SelectWithCustomTrigger]))); xit('should allow the user to customize the label', fakeAsync(() => { const fixture = TestBed.createComponent(SelectWithCustomTrigger); fixture.detectChanges(); fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); const label = fixture.debugElement.query(By.css('.mc-select__matcher')).nativeElement; expect(label.textContent).toContain('azziP', 'Expected the displayed text to be "Pizza" in reverse.'); })); }); describe('when reseting the value by setting null or undefined', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ResetValuesSelect]))); let fixture: ComponentFixture<ResetValuesSelect>; let trigger: HTMLElement; let formField: HTMLElement; let options: NodeListOf<HTMLElement>; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(ResetValuesSelect); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; formField = fixture.debugElement.query(By.css('.mc-form-field')).nativeElement; trigger.click(); fixture.detectChanges(); flush(); options = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); fixture.detectChanges(); flush(); })); it('should reset when an option with an undefined value is selected', fakeAsync(() => { options[4].click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.value).toBeUndefined(); expect(fixture.componentInstance.select.selected).toBeFalsy(); expect(formField.classList).not.toContain('mc-form-field-should-float'); expect(trigger.textContent).not.toContain('Undefined'); })); it('should reset when an option with a null value is selected', fakeAsync(() => { options[5].click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.value).toBeNull(); expect(fixture.componentInstance.select.selected).toBeFalsy(); expect(formField.classList).not.toContain('mc-form-field-should-float'); expect(trigger.textContent).not.toContain('Null'); })); it('should reset when a blank option is selected', fakeAsync(() => { options[6].click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.value).toBeUndefined(); expect(fixture.componentInstance.select.selected).toBeFalsy(); expect(formField.classList).not.toContain('mc-form-field-should-float'); expect(trigger.textContent).not.toContain('None'); })); it('should not mark the reset option as selected ', fakeAsync(() => { options[5].click(); fixture.detectChanges(); flush(); fixture.componentInstance.select.open(); fixture.detectChanges(); flush(); expect(options[5].classList).not.toContain('mc-selected'); })); it('should not reset when any other falsy option is selected', fakeAsync(() => { options[3].click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.control.value).toBe(false); expect(fixture.componentInstance.select.selected).toBeTruthy(); expect(trigger.textContent).toContain('Falsy'); })); xit('should not consider the reset values as selected when resetting the form control', fakeAsync(() => { fixture.componentInstance.control.reset(); fixture.detectChanges(); expect(fixture.componentInstance.control.value).toBeNull(); expect(fixture.componentInstance.select.selected).toBeFalsy(); expect(trigger.textContent).not.toContain('Null'); expect(trigger.textContent).not.toContain('Undefined'); })); }); describe('without Angular forms', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ BasicSelectWithoutForms, BasicSelectWithoutFormsPreselected, BasicSelectWithoutFormsMultiple ]))); it('should set the value when options are clicked', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectWithoutForms); fixture.detectChanges(); expect(fixture.componentInstance.selectedFood).toBeFalsy(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.click(); fixture.detectChanges(); flush(); (overlayContainerElement.querySelector('mc-option') as HTMLElement).click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.selectedFood).toBe('steak-0'); expect(fixture.componentInstance.select.value).toBe('steak-0'); expect(trigger.textContent).toContain('Steak'); trigger.click(); fixture.detectChanges(); flush(); (overlayContainerElement.querySelectorAll('mc-option')[2] as HTMLElement).click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.selectedFood).toBe('sandwich-2'); expect(fixture.componentInstance.select.value).toBe('sandwich-2'); expect(trigger.textContent).toContain('Sandwich'); })); xit('should mark options as selected when the value is set', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectWithoutForms); fixture.detectChanges(); fixture.componentInstance.selectedFood = 'sandwich-2'; fixture.detectChanges(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; expect(trigger.textContent).toContain('Sandwich'); trigger.click(); fixture.detectChanges(); const option = overlayContainerElement.querySelectorAll('mc-option')[2]; expect(option.classList).toContain('mc-selected'); expect(fixture.componentInstance.select.value).toBe('sandwich-2'); })); xit('should reset the label when a null value is set', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectWithoutForms); fixture.detectChanges(); expect(fixture.componentInstance.selectedFood).toBeFalsy(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.click(); fixture.detectChanges(); flush(); (overlayContainerElement.querySelector('mc-option') as HTMLElement).click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.selectedFood).toBe('steak-0'); expect(fixture.componentInstance.select.value).toBe('steak-0'); expect(trigger.textContent).toContain('Steak'); fixture.componentInstance.selectedFood = null; fixture.detectChanges(); expect(fixture.componentInstance.select.value).toBeNull(); expect(trigger.textContent).not.toContain('Steak'); })); xit('should reflect the preselected value', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectWithoutFormsPreselected); fixture.detectChanges(); flush(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; fixture.detectChanges(); expect(trigger.textContent).toContain('Pizza'); trigger.click(); fixture.detectChanges(); const option = overlayContainerElement.querySelectorAll('mc-option')[1]; expect(option.classList).toContain('mc-selected'); expect(fixture.componentInstance.select.value).toBe('pizza-1'); })); xit('should be able to select multiple values', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectWithoutFormsMultiple); fixture.detectChanges(); expect(fixture.componentInstance.selectedFoods).toBeFalsy(); const trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; trigger.click(); fixture.detectChanges(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); fixture.detectChanges(); expect(fixture.componentInstance.selectedFoods).toEqual(['steak-0']); expect(fixture.componentInstance.select.value).toEqual(['steak-0']); expect(trigger.textContent).toContain('Steak'); options[2].click(); fixture.detectChanges(); expect(fixture.componentInstance.selectedFoods).toEqual(['steak-0', 'sandwich-2']); expect(fixture.componentInstance.select.value).toEqual(['steak-0', 'sandwich-2']); expect(trigger.textContent).toContain('Steak, Sandwich'); options[1].click(); fixture.detectChanges(); expect(fixture.componentInstance.selectedFoods).toEqual(['steak-0', 'pizza-1', 'sandwich-2']); expect(fixture.componentInstance.select.value).toEqual(['steak-0', 'pizza-1', 'sandwich-2']); expect(trigger.textContent).toContain('Steak, Pizza, Sandwich'); })); it('should restore focus to the host element', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectWithoutForms); fixture.detectChanges(); fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement.click(); fixture.detectChanges(); flush(); (overlayContainerElement.querySelector('mc-option') as HTMLElement).click(); fixture.detectChanges(); flush(); const select = fixture.debugElement.nativeElement.querySelector('mc-select'); expect(document.activeElement).toBe(select, 'Expected trigger to be focused.'); })); it('should not restore focus to the host element when clicking outside', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectWithoutForms); const select = fixture.debugElement.nativeElement.querySelector('mc-select'); fixture.detectChanges(); fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement.click(); fixture.detectChanges(); flush(); expect(document.activeElement?.classList).toContain('mc-option', 'Expected option to be focused.'); select.blur(); // Blur manually since the programmatic click might not do it. document.body.click(); fixture.detectChanges(); flush(); expect(document.activeElement).not.toBe(select, 'Expected trigger not to be focused.'); })); it('should update the data binding before emitting the change event', fakeAsync(() => { const fixture = TestBed.createComponent(BasicSelectWithoutForms); const instance = fixture.componentInstance; const spy = jasmine.createSpy('change spy'); fixture.detectChanges(); instance.select.selectionChange.subscribe(() => spy(instance.selectedFood)); expect(instance.selectedFood).toBeFalsy(); fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement.click(); fixture.detectChanges(); flush(); (overlayContainerElement.querySelector('mc-option') as HTMLElement).click(); fixture.detectChanges(); flush(); expect(instance.selectedFood).toBe('steak-0'); expect(spy).toHaveBeenCalledWith('steak-0'); })); }); describe('with option centering disabled', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ SelectWithoutOptionCentering ]))); let fixture: ComponentFixture<SelectWithoutOptionCentering>; let trigger: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(SelectWithoutOptionCentering); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; })); it('should not align the active option with the trigger if centering is disabled', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const scrollContainer = document.querySelector('.cdk-overlay-pane .mc-select__panel')!; // The panel should be scrolled to 0 because centering the option disabled. expect(scrollContainer.scrollTop).toEqual(0, `Expected panel not to be scrolled.`); // The trigger should contain 'Pizza' because it was preselected expect(trigger.textContent).toContain('Pizza'); // The selected index should be 1 because it was preselected expect(fixture.componentInstance.options.toArray()[1].selected).toBe(true); })); }); describe('positioning', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([ BasicSelect, MultiSelect, SelectWithGroups ]))); let fixture: ComponentFixture<BasicSelect>; let trigger: HTMLElement; let formField: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(BasicSelect); fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; formField = fixture.debugElement.query(By.css('mc-form-field')).nativeElement; })); /** * Asserts that the given option is aligned with the trigger. * @param index The index of the option. * @param selectInstance Instance of the `mc-select` component to check against. */ function checkTriggerAlignedWithOption(index: number, selectInstance = fixture.componentInstance.select): void { const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane')!; const triggerTop: number = trigger.getBoundingClientRect().top; const overlayTop: number = overlayPane.getBoundingClientRect().top; const options: NodeListOf<HTMLElement> = overlayPane.querySelectorAll('mc-option'); const optionTop = options[index].getBoundingClientRect().top; const triggerFontSize = parseInt(window.getComputedStyle(trigger)['font-size']); const triggerLineHeightEm = 1.125; // Extra trigger height beyond the font size caused by the fact that the line-height is // greater than 1em. const triggerExtraLineSpaceAbove = (1 - triggerLineHeightEm) * triggerFontSize / 2; const topDifference = Math.floor(optionTop) - Math.floor(triggerTop - triggerFontSize - triggerExtraLineSpaceAbove); // Expect the coordinates to be within a pixel of each other. We can't rely on comparing // the exact value, because different browsers report the various sizes with slight (< 1px) // deviations. expect(Math.abs(topDifference) < 2) .toBe(true, `Expected trigger to align with option ${index}.`); // For the animation to start at the option's center, its origin must be the distance // from the top of the overlay to the option top + half the option height (48/2 = 24). const expectedOrigin = Math.floor(optionTop - overlayTop + 24); const rawYOrigin = selectInstance.transformOrigin.split(' ')[1].trim(); const origin = Math.floor(parseInt(rawYOrigin)); // Because the origin depends on the Y axis offset, we also have to // round down and check that the difference is within a pixel. expect(Math.abs(expectedOrigin - origin) < 2).toBe(true, `Expected panel animation to originate in the center of option ${index}.`); } describe('ample space to open', () => { beforeEach(fakeAsync(() => { // these styles are necessary because we are first testing the overlay's position // if there is room for it to open to its full extent in either direction. formField.style.position = 'fixed'; formField.style.top = '285px'; formField.style.left = '20px'; })); xit('should align the first option with trigger text if no option is selected', fakeAsync(() => { // We shouldn't push it too far down for this one, because the default may // end up being too much when running the tests on mobile browsers. formField.style.top = '100px'; trigger.click(); fixture.detectChanges(); flush(); const scrollContainer = document.querySelector('.cdk-overlay-pane .mc-select__panel')!; // The panel should be scrolled to 0 because centering the option is not possible. expect(scrollContainer.scrollTop).toEqual(0, `Expected panel not to be scrolled.`); checkTriggerAlignedWithOption(0); })); xit('should align a selected option too high to be centered with the trigger text', fakeAsync(() => { // Select the second option, because it can't be scrolled any further downward fixture.componentInstance.control.setValue('pizza-1'); fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); const scrollContainer = document.querySelector('.cdk-overlay-pane .mc-select__panel')!; // The panel should be scrolled to 0 because centering the option is not possible. expect(scrollContainer.scrollTop).toEqual(0, `Expected panel not to be scrolled.`); checkTriggerAlignedWithOption(1); })); xit('should align a selected option in the middle with the trigger text', fakeAsync(() => { // Select the fifth option, which has enough space to scroll to the center fixture.componentInstance.control.setValue('chips-4'); fixture.detectChanges(); flush(); trigger.click(); fixture.detectChanges(); flush(); const scrollContainer = document.querySelector('.cdk-overlay-pane .mc-select__panel')!; // The selected option should be scrolled to the center of the panel. // This will be its original offset from the scrollTop - half the panel height + half // the option height. 4 (index) * 48 (option height) = 192px offset from scrollTop // 192 - 256/2 + 48/2 = 88px expect(scrollContainer.scrollTop) .toEqual(88, `Expected overlay panel to be scrolled to center the selected option.`); checkTriggerAlignedWithOption(4); })); xit('should align a selected option at the scroll max with the trigger text', fakeAsync(() => { // Select the last option in the list fixture.componentInstance.control.setValue('sushi-7'); fixture.detectChanges(); flush(); trigger.click(); fixture.detectChanges(); flush(); const scrollContainer = document.querySelector('.cdk-overlay-pane .mc-select__panel')!; // The selected option should be scrolled to the max scroll position. // This will be the height of the scrollContainer - the panel height. // 8 options * 48px = 384 scrollContainer height, 384 - 256 = 128px max scroll expect(scrollContainer.scrollTop) .toEqual(128, `Expected overlay panel to be scrolled to its maximum position.`); checkTriggerAlignedWithOption(7); })); xit('should account for preceding label groups when aligning the option', fakeAsync(() => { // Test is off-by-one on edge for some reason, but verified that it looks correct through // manual testing. if (platform.EDGE) { return; } fixture.destroy(); const groupFixture = TestBed.createComponent(SelectWithGroups); groupFixture.detectChanges(); trigger = groupFixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; formField = groupFixture.debugElement.query(By.css('mc-form-field')).nativeElement; formField.style.position = 'fixed'; formField.style.top = '200px'; formField.style.left = '100px'; // Select an option in the third group, which has a couple of group labels before it. groupFixture.componentInstance.control.setValue('vulpix-7'); groupFixture.detectChanges(); trigger.click(); groupFixture.detectChanges(); flush(); const scrollContainer = document.querySelector('.cdk-overlay-pane .mc-select__content')!; // The selected option should be scrolled to the center of the panel. // This will be its original offset from the scrollTop - half the panel height + half the // option height. 10 (option index + 3 group labels before it) * 48 (option height) = 480 // 480 (offset from scrollTop) - 256/2 + 48/2 = 376px expect(Math.floor(scrollContainer.scrollTop)) .toBe(376, `Expected overlay panel to be scrolled to center the selected option.`); checkTriggerAlignedWithOption(7, groupFixture.componentInstance.select); })); }); describe('limited space to open vertically', () => { beforeEach(fakeAsync(() => { formField.style.position = 'fixed'; formField.style.left = '20px'; })); xit('should adjust position of centered option if there is little space above', fakeAsync(() => { const selectMenuHeight = 256; const selectMenuViewportPadding = 8; const selectItemHeight = 48; const selectedIndex = 4; const fontSize = 16; const lineHeightEm = 1.125; const expectedExtraScroll = 5; // Trigger element height. const triggerHeight = fontSize * lineHeightEm; // Ideal space above selected item in order to center it. const idealSpaceAboveSelectedItem = (selectMenuHeight - selectItemHeight) / 2; // Actual space above selected item. const actualSpaceAboveSelectedItem = selectItemHeight * selectedIndex; // Ideal scroll position to center. const idealScrollTop = actualSpaceAboveSelectedItem - idealSpaceAboveSelectedItem; // Top-most select-position that allows for perfect centering. const topMostPositionForPerfectCentering = idealSpaceAboveSelectedItem + selectMenuViewportPadding + (selectItemHeight - triggerHeight) / 2; // Position of select relative to top edge of mc-form-field. const formFieldTopSpace = trigger.getBoundingClientRect().top - formField.getBoundingClientRect().top; const formFieldTop = topMostPositionForPerfectCentering - formFieldTopSpace - expectedExtraScroll; formField.style.top = `${formFieldTop}px`; // Select an option in the middle of the list fixture.componentInstance.control.setValue('chips-4'); fixture.detectChanges(); flush(); trigger.click(); fixture.detectChanges(); flush(); const scrollContainer = document.querySelector('.cdk-overlay-pane .mc-select__panel')!; expect(Math.ceil(scrollContainer.scrollTop)) .toEqual(Math.ceil(idealScrollTop + 5), `Expected panel to adjust scroll position to fit in viewport.`); checkTriggerAlignedWithOption(4); })); xit('should adjust position of centered option if there is little space below', fakeAsync(() => { const selectMenuHeight = 256; const selectMenuViewportPadding = 8; const selectItemHeight = 48; const selectedIndex = 4; const fontSize = 16; const lineHeightEm = 1.125; const expectedExtraScroll = 5; // Trigger element height. const triggerHeight = fontSize * lineHeightEm; // Ideal space above selected item in order to center it. const idealSpaceAboveSelectedItem = (selectMenuHeight - selectItemHeight) / 2; // Actual space above selected item. const actualSpaceAboveSelectedItem = selectItemHeight * selectedIndex; // Ideal scroll position to center. const idealScrollTop = actualSpaceAboveSelectedItem - idealSpaceAboveSelectedItem; // Bottom-most select-position that allows for perfect centering. const bottomMostPositionForPerfectCentering = idealSpaceAboveSelectedItem + selectMenuViewportPadding + (selectItemHeight - triggerHeight) / 2; // Position of select relative to bottom edge of mc-form-field: const formFieldBottomSpace = formField.getBoundingClientRect().bottom - trigger.getBoundingClientRect().bottom; const formFieldBottom = bottomMostPositionForPerfectCentering - formFieldBottomSpace - expectedExtraScroll; // Push the select to a position with not quite enough space on the bottom to open // with the option completely centered (needs 113px at least: 256/2 - 48/2 + 9) formField.style.bottom = `${formFieldBottom}px`; // Select an option in the middle of the list fixture.componentInstance.control.setValue('chips-4'); fixture.detectChanges(); flush(); fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); const scrollContainer = document.querySelector('.cdk-overlay-pane .mc-select__panel')!; // Scroll should adjust by the difference between the bottom space available // (56px from the bottom of the screen - 8px padding = 48px) // and the height of the panel below the option (113px). // 113px - 48px = 75px difference. Original scrollTop 88px - 75px = 23px const difference = Math.ceil(scrollContainer.scrollTop) - Math.ceil(idealScrollTop - expectedExtraScroll); // Note that different browser/OS combinations report the different dimensions with // slight deviations (< 1px). We round the expectation and check that the values // are within a pixel of each other to avoid flakes. expect(Math.abs(difference) < 2) .toBe(true, `Expected panel to adjust scroll position to fit in viewport.`); checkTriggerAlignedWithOption(4); })); xit('should fall back to "above" positioning if scroll adjustment will not help', fakeAsync(() => { // Push the select to a position with not enough space on the bottom to open formField.style.bottom = '56px'; fixture.detectChanges(); // Select an option that cannot be scrolled any farther upward fixture.componentInstance.control.setValue('coke-0'); fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); const overlayPane = document.querySelector('.cdk-overlay-pane')!; const triggerBottom: number = trigger.getBoundingClientRect().bottom; const overlayBottom: number = overlayPane.getBoundingClientRect().bottom; const scrollContainer = overlayPane.querySelector('.mc-select__panel')!; // Expect no scroll to be attempted expect(scrollContainer.scrollTop).toEqual(0, `Expected panel not to be scrolled.`); const difference = Math.floor(overlayBottom) - Math.floor(triggerBottom); // Check that the values are within a pixel of each other. This avoids sub-pixel // deviations between OS and browser versions. expect(Math.abs(difference) < 2) .toEqual(true, `Expected trigger bottom to align with overlay bottom.`); expect(fixture.componentInstance.select.transformOrigin) .toContain(`bottom`, `Expected panel animation to originate at the bottom.`); })); xit('should fall back to "below" positioning if scroll adjustment won\'t help', fakeAsync(() => { // Push the select to a position with not enough space on the top to open formField.style.top = '85px'; // Select an option that cannot be scrolled any farther downward fixture.componentInstance.control.setValue('sushi-7'); fixture.detectChanges(); flush(); trigger.click(); fixture.detectChanges(); flush(); const overlayPane = document.querySelector('.cdk-overlay-pane')!; const triggerTop: number = trigger.getBoundingClientRect().top; const overlayTop: number = overlayPane.getBoundingClientRect().top; const scrollContainer = overlayPane.querySelector('.mc-select__panel')!; // Expect scroll to remain at the max scroll position expect(scrollContainer.scrollTop) .toEqual(128, `Expected panel to be at max scroll.`); expect(Math.floor(overlayTop)) .toEqual(Math.floor(triggerTop), `Expected trigger top to align with overlay top.`); expect(fixture.componentInstance.select.transformOrigin) .toContain(`top`, `Expected panel animation to originate at the top.`); })); }); /*describe('limited space to open horizontally', () => { beforeEach(fakeAsync(() => { formField.style.position = 'absolute'; formField.style.top = '200px'; })); // TODO Expected pixels xit('should stay within the viewport when overflowing on the left in ltr', fakeAsync(() => { formField.style.left = '-100px'; trigger.click(); fixture.detectChanges(); flush(); const panelLeft = document.querySelector('.mc-select__panel')!.getBoundingClientRect().left; expect(panelLeft).toBeGreaterThan(0, `Expected select panel to be inside the viewport in ltr.`); })); it('should stay within the viewport when overflowing on the left in rtl', fakeAsync(() => { dir.value = 'rtl'; formField.style.left = '-100px'; trigger.click(); fixture.detectChanges(); flush(); const panelLeft = document.querySelector('.mc-select__panel')!.getBoundingClientRect().left; expect(panelLeft).toBeGreaterThan(0, `Expected select panel to be inside the viewport in rtl.`); })); it('should stay within the viewport when overflowing on the right in ltr', fakeAsync(() => { formField.style.right = '-100px'; trigger.click(); fixture.detectChanges(); flush(); const viewportRect = viewportRuler.getViewportRect().right; const panelRight = document.querySelector('.mc-select__panel')!.getBoundingClientRect().right; expect(viewportRect - panelRight).toBeGreaterThan(0, `Expected select panel to be inside the viewport in ltr.`); })); xit('should stay within the viewport when overflowing on the right in rtl', fakeAsync(() => { dir.value = 'rtl'; formField.style.right = '-100px'; trigger.click(); fixture.detectChanges(); flush(); const viewportRect = viewportRuler.getViewportRect().right; const panelRight = document.querySelector('.mc-select__panel')!.getBoundingClientRect().right; expect(viewportRect - panelRight).toBeGreaterThan(0, `Expected select panel to be inside the viewport in rtl.`); })); // TODO Expected pixels xit('should keep the position within the viewport on repeat openings', fakeAsync(() => { formField.style.left = '-100px'; trigger.click(); fixture.detectChanges(); flush(); let panelLeft = document.querySelector('.mc-select__panel')!.getBoundingClientRect().left; expect(panelLeft) .toBeGreaterThanOrEqual(0, `Expected select panel to be inside the viewport.`); fixture.componentInstance.select.close(); fixture.detectChanges(); flush(); trigger.click(); fixture.detectChanges(); flush(); panelLeft = document.querySelector('.mc-select__panel')!.getBoundingClientRect().left; expect(panelLeft).toBeGreaterThanOrEqual(0, `Expected select panel continue being inside the viewport.`); })); });*/ describe('when scrolled', () => { const startingWindowHeight = window.innerHeight; // Need to set the scrollTop two different ways to support // both Chrome and Firefox. function setScrollTop(num: number) { document.body.scrollTop = num; document.documentElement.scrollTop = num; } beforeEach(fakeAsync(() => { // Make the div above the select very tall, so the page will scroll fixture.componentInstance.heightAbove = 2000; fixture.detectChanges(); setScrollTop(0); // Give the select enough horizontal space to open formField.style.marginLeft = '20px'; formField.style.marginRight = '20px'; })); xit('should fall back to "above" positioning properly when scrolled', fakeAsync(() => { // Give the select insufficient space to open below the trigger fixture.componentInstance.heightAbove = 0; fixture.componentInstance.heightBelow = 100; trigger.style.marginTop = '2000px'; fixture.detectChanges(); // Scroll the select into view setScrollTop(1400); // In the iOS simulator (BrowserStack & SauceLabs), adding the content to the // body causes karma's iframe for the test to stretch to fit that content once we attempt to // scroll the page. Setting width / height / maxWidth / maxHeight on the iframe does not // successfully constrain its size. As such, skip assertions in environments where the // window size has changed since the start of the test. if (window.innerHeight > startingWindowHeight) { return; } trigger.click(); fixture.detectChanges(); flush(); const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane')!; const triggerBottom: number = trigger.getBoundingClientRect().bottom; const overlayBottom: number = overlayPane.getBoundingClientRect().bottom; const difference = Math.floor(overlayBottom) - Math.floor(triggerBottom); // Check that the values are within a pixel of each other. This avoids sub-pixel // deviations between OS and browser versions. expect(Math.abs(difference) < 2) .toEqual(true, `Expected trigger bottom to align with overlay bottom.`); })); xit('should fall back to "below" positioning properly when scrolled', fakeAsync(() => { // Give plenty of space for the select to open below the trigger fixture.componentInstance.heightBelow = 650; fixture.detectChanges(); // Select an option too low in the list to fit in limited space above fixture.componentInstance.control.setValue('sushi-7'); fixture.detectChanges(); // Scroll the select so that it has insufficient space to open above the trigger setScrollTop(1950); // In the iOS simulator (BrowserStack & SauceLabs), adding the content to the // body causes karma's iframe for the test to stretch to fit that content once we attempt to // scroll the page. Setting width / height / maxWidth / maxHeight on the iframe does not // successfully constrain its size. As such, skip assertions in environments where the // window size has changed since the start of the test. if (window.innerHeight > startingWindowHeight) { return; } trigger.click(); fixture.detectChanges(); flush(); const overlayPane = overlayContainerElement.querySelector('.cdk-overlay-pane')!; const triggerTop: number = trigger.getBoundingClientRect().top; const overlayTop: number = overlayPane.getBoundingClientRect().top; expect(Math.floor(overlayTop)) .toEqual(Math.floor(triggerTop), `Expected trigger top to align with overlay top.`); })); }); describe('x-axis positioning', () => { beforeEach(fakeAsync(() => { formField.style.position = 'fixed'; formField.style.left = '30px'; })); xit('should align the trigger and the selected option on the x-axis in ltr', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const triggerLeft: number = trigger.getBoundingClientRect().left; const firstOptionLeft = document.querySelector('.cdk-overlay-pane mc-option')! .getBoundingClientRect().left; // Each option is 32px wider than the trigger, so it must be adjusted 16px // to ensure the text overlaps correctly. expect(Math.floor(firstOptionLeft)).toEqual(Math.floor(triggerLeft - 16), `Expected trigger to align with the selected option on the x-axis in LTR.`); })); xit('should align the trigger and the selected option on the x-axis in rtl', fakeAsync(() => { dir.value = 'rtl'; fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); const triggerRight: number = trigger.getBoundingClientRect().right; const firstOptionRight = document.querySelector('.cdk-overlay-pane mc-option')! .getBoundingClientRect().right; // Each option is 32px wider than the trigger, so it must be adjusted 16px // to ensure the text overlaps correctly. expect(Math.floor(firstOptionRight)) .toEqual(Math.floor(triggerRight + 16), `Expected trigger to align with the selected option on the x-axis in RTL.`); })); }); describe('x-axis positioning in multi select mode', () => { let multiFixture: ComponentFixture<MultiSelect>; beforeEach(fakeAsync(() => { multiFixture = TestBed.createComponent(MultiSelect); multiFixture.detectChanges(); formField = multiFixture.debugElement.query(By.css('.mc-form-field')).nativeElement; trigger = multiFixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; formField.style.position = 'fixed'; formField.style.left = '60px'; })); xit('should adjust for the checkbox in ltr', fakeAsync(() => { trigger.click(); multiFixture.detectChanges(); flush(); const triggerLeft: number = trigger.getBoundingClientRect().left; const firstOptionLeft = document.querySelector('.cdk-overlay-pane mc-option')! .getBoundingClientRect().left; // 44px accounts for the checkbox size, margin and the panel's padding. expect(Math.floor(firstOptionLeft)) .toEqual(Math.floor(triggerLeft - 44), `Expected trigger label to align along x-axis, accounting for the checkbox.`); })); xit('should adjust for the checkbox in rtl', fakeAsync(() => { dir.value = 'rtl'; trigger.click(); multiFixture.detectChanges(); flush(); const triggerRight: number = trigger.getBoundingClientRect().right; const firstOptionRight = document.querySelector('.cdk-overlay-pane mc-option')! .getBoundingClientRect().right; // 44px accounts for the checkbox size, margin and the panel's padding. expect(Math.floor(firstOptionRight)) .toEqual(Math.floor(triggerRight + 44), `Expected trigger label to align along x-axis, accounting for the checkbox.`); })); }); describe('x-axis positioning with groups', () => { let groupFixture: ComponentFixture<SelectWithGroups>; beforeEach(fakeAsync(() => { groupFixture = TestBed.createComponent(SelectWithGroups); groupFixture.detectChanges(); formField = groupFixture.debugElement.query(By.css('.mc-form-field')).nativeElement; trigger = groupFixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; formField.style.position = 'fixed'; formField.style.left = '60px'; })); xit('should adjust for the group padding in ltr', fakeAsync(() => { groupFixture.componentInstance.control.setValue('oddish-1'); groupFixture.detectChanges(); trigger.click(); groupFixture.detectChanges(); groupFixture.whenStable().then(() => { const group = document.querySelector('.cdk-overlay-pane mc-optgroup')!; const triggerLeft: number = trigger.getBoundingClientRect().left; const selectedOptionLeft = group.querySelector('mc-option.mc-selected')! .getBoundingClientRect().left; // 32px is the 16px default padding plus 16px of padding when an option is in a group. expect(Math.floor(selectedOptionLeft)).toEqual(Math.floor(triggerLeft - 32), `Expected trigger label to align along x-axis, accounting for the padding in ltr.`); }); })); xit('should adjust for the group padding in rtl', fakeAsync(() => { dir.value = 'rtl'; groupFixture.componentInstance.control.setValue('oddish-1'); groupFixture.detectChanges(); trigger.click(); groupFixture.detectChanges(); flush(); const group = document.querySelector('.cdk-overlay-pane mc-optgroup')!; const triggerRight = trigger.getBoundingClientRect().right; const selectedOptionRight = group.querySelector('mc-option.mc-selected')!.getBoundingClientRect().right; // 32px is the 16px default padding plus 16px of padding when an option is in a group. expect(Math.floor(selectedOptionRight)).toEqual(Math.floor(triggerRight + 32), `Expected trigger label to align along x-axis, accounting for the padding in rtl.`); })); xit('should not adjust if all options are within a group, except the selected one', fakeAsync(() => { groupFixture.componentInstance.control.setValue('mime-11'); groupFixture.detectChanges(); trigger.click(); groupFixture.detectChanges(); flush(); const selected = document.querySelector('.cdk-overlay-pane mc-option.mc-selected')!; const selectedOptionLeft = selected.getBoundingClientRect().left; const triggerLeft = trigger.getBoundingClientRect().left; // 16px is the default option padding expect(Math.floor(selectedOptionLeft)).toEqual(Math.floor(triggerLeft - 16)); })); xit('should align the first option to the trigger, if nothing is selected', fakeAsync(() => { // Push down the form field so there is space for the item to completely align. formField.style.top = '100px'; const menuItemHeight = 48; const triggerFontSize = 16; const triggerLineHeightEm = 1.125; const triggerHeight = triggerFontSize * triggerLineHeightEm; trigger.click(); groupFixture.detectChanges(); flush(); const triggerTop = trigger.getBoundingClientRect().top; const option = overlayContainerElement.querySelector('.cdk-overlay-pane mc-option'); const optionTop: number = option ? option.getBoundingClientRect().top : 0; // There appears to be a small rounding error on IE, so we verify that the value is close, // not exact. if (platform.TRIDENT) { const difference = Math.abs(optionTop + (menuItemHeight - triggerHeight) / 2 - triggerTop); expect(difference) .toBeLessThan(0.1, 'Expected trigger to align with the first option.'); } else { expect(Math.floor(optionTop + (menuItemHeight - triggerHeight) / 2)) .toBe(Math.floor(triggerTop), 'Expected trigger to align with the first option.'); } })); }); }); describe('with multiple selection', () => { beforeEach(waitForAsync(() => configureMcSelectTestingModule([MultiSelect]))); let fixture: ComponentFixture<MultiSelect>; let testInstance: MultiSelect; let trigger: HTMLElement; beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(MultiSelect); testInstance = fixture.componentInstance; fixture.detectChanges(); trigger = fixture.debugElement.query(By.css('.mc-select__trigger')).nativeElement; })); it('should be able to select multiple values', fakeAsync(() => { trigger.click(); fixture.detectChanges(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); options[2].click(); options[5].click(); fixture.detectChanges(); flush(); expect(testInstance.control.value).toEqual(['steak-0', 'tacos-2', 'eggs-5']); })); it('should be able to toggle an option on and off', fakeAsync(() => { trigger.click(); fixture.detectChanges(); const option = overlayContainerElement.querySelector('mc-option') as HTMLElement; option.click(); fixture.detectChanges(); expect(testInstance.control.value).toEqual(['steak-0']); option.click(); fixture.detectChanges(); flush(); expect(testInstance.control.value).toEqual([]); })); it('should update the label', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); options[2].click(); options[5].click(); fixture.detectChanges(); expect(Array.from(trigger.querySelectorAll('mc-tag'), (item) => item.textContent!.trim())) .toEqual(['Steak', 'Tacos', 'Eggs']); options[2].click(); fixture.detectChanges(); flush(); expect(Array.from(trigger.querySelectorAll('mc-tag'), (item) => item.textContent!.trim())) .toEqual(['Steak', 'Eggs']); })); it('should be able to set the selected value by taking an array', fakeAsync(() => { trigger.click(); testInstance.control.setValue(['steak-0', 'eggs-5']); fixture.detectChanges(); flush(); const optionNodes = overlayContainerElement.querySelectorAll('mc-option'); const optionInstances = testInstance.options.toArray(); expect(optionNodes[0].classList).toContain('mc-selected'); expect(optionNodes[5].classList).toContain('mc-selected'); expect(optionInstances[0].selected).toBe(true); expect(optionInstances[5].selected).toBe(true); })); it('should override the previously-selected value when setting an array', fakeAsync(() => { trigger.click(); fixture.detectChanges(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); fixture.detectChanges(); expect(options[0].classList).toContain('mc-selected'); testInstance.control.setValue(['eggs-5']); fixture.detectChanges(); flush(); expect(options[0].classList).not.toContain('mc-selected'); expect(options[5].classList).toContain('mc-selected'); })); it('should not close the panel when clicking on options', fakeAsync(() => { trigger.click(); fixture.detectChanges(); expect(testInstance.select.panelOpen).toBe(true); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); options[1].click(); fixture.detectChanges(); flush(); expect(testInstance.select.panelOpen).toBe(true); })); xit('should sort the selected options based on their order in the panel', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[2].click(); options[0].click(); options[1].click(); fixture.detectChanges(); expect(trigger.querySelector('.mc-select__match-list')!.textContent).toContain('Steak, Pizza, Tacos'); expect(fixture.componentInstance.control.value).toEqual(['steak-0', 'pizza-1', 'tacos-2']); })); xit('should sort the selected options in reverse in rtl', fakeAsync(() => { dir.value = 'rtl'; trigger.click(); fixture.detectChanges(); flush(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[2].click(); options[0].click(); options[1].click(); fixture.detectChanges(); expect(trigger.textContent).toContain('Tacos, Pizza, Steak'); expect(fixture.componentInstance.control.value).toEqual(['steak-0', 'pizza-1', 'tacos-2']); })); xit('should be able to customize the value sorting logic', fakeAsync(() => { fixture.componentInstance.sortComparator = (a, b, optionsArray) => { return optionsArray.indexOf(b) - optionsArray.indexOf(a); }; fixture.detectChanges(); trigger.click(); fixture.detectChanges(); flush(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); for (let i = 0; i < 3; i++) { options[i].click(); } fixture.detectChanges(); // Expect the items to be in reverse order. expect(trigger.querySelector('.mc-select__match-list')!.textContent).toContain('Tacos, Pizza, Steak'); expect(fixture.componentInstance.control.value).toEqual(['tacos-2', 'pizza-1', 'steak-0']); })); xit('should sort the values that get set via the model based on the panel order', fakeAsync(() => { trigger.click(); fixture.detectChanges(); testInstance.control.setValue(['tacos-2', 'steak-0', 'pizza-1']); fixture.detectChanges(); flush(); // expect(trigger.querySelector('.mc-select__match-list')!.textContent.trim()) // .toContain('Steak, Pizza, Tacos'); expect(trigger.textContent).toContain('Steak, Pizza, Tacos'); })); xit('should reverse sort the values, that get set via the model in rtl', fakeAsync(() => { dir.value = 'rtl'; trigger.click(); fixture.detectChanges(); testInstance.control.setValue(['tacos-2', 'steak-0', 'pizza-1']); fixture.detectChanges(); expect(trigger.textContent).toContain('Tacos, Pizza, Steak'); })); it('should throw an exception when trying to set a non-array value', fakeAsync(() => { expect(() => { testInstance.control.setValue('not-an-array'); }).toThrowError(wrappedErrorMessage(getMcSelectNonArrayValueError())); })); it('should throw an exception when trying to change multiple mode after init', fakeAsync(() => { expect(() => { testInstance.select.multiple = false; }).toThrowError(wrappedErrorMessage(getMcSelectDynamicMultipleError())); })); it('should pass the `multiple` value to all of the option instances', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); expect(testInstance.options.toArray().every((option: any) => option.multiple)) .toBe(true, 'Expected `multiple` to have been added to initial set of options.'); testInstance.foods.push({ value: 'cake-8', viewValue: 'Cake' }); fixture.detectChanges(); expect(testInstance.options.toArray().every((option) => !!option.multiple)).toBe(true, 'Expected `multiple` to have been set on dynamically-added option.'); })); it('should update the active item index on click', fakeAsync(() => { trigger.click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.keyManager.activeItemIndex).toBe(0); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[2].click(); fixture.detectChanges(); flush(); expect(fixture.componentInstance.select.keyManager.activeItemIndex).toBe(2); })); it('should be to select an option with a `null` value', fakeAsync(() => { fixture.componentInstance.foods = [ { value: null, viewValue: 'Steak' }, { value: 'pizza-1', viewValue: 'Pizza' }, { value: null, viewValue: 'Tacos' } ]; fixture.detectChanges(); trigger.click(); fixture.detectChanges(); const options: NodeListOf<HTMLElement> = overlayContainerElement.querySelectorAll('mc-option'); options[0].click(); options[1].click(); options[2].click(); fixture.detectChanges(); flush(); expect(testInstance.control.value).toEqual([null, 'pizza-1', null]); })); it('should select all options when pressing ctrl + a', () => { const selectElement = fixture.nativeElement.querySelector('mc-select'); const options = fixture.componentInstance.options.toArray(); expect(testInstance.control.value).toBeFalsy(); expect(options.every((option) => option.selected)).toBe(false); fixture.componentInstance.select.open(); fixture.detectChanges(); const event = createKeyboardEvent('keydown', A, selectElement); Object.defineProperty(event, 'ctrlKey', { get: () => true }); dispatchEvent(selectElement, event); fixture.detectChanges(); expect(options.every((option) => option.selected)).toBe(true); expect(testInstance.control.value).toEqual([ 'steak-0', 'pizza-1', 'tacos-2', 'sandwich-3', 'chips-4', 'eggs-5', 'pasta-6', 'sushi-7' ]); }); it('should skip disabled options when using ctrl + a', () => { const selectElement = fixture.nativeElement.querySelector('mc-select'); const options = fixture.componentInstance.options.toArray(); for (let i = 0; i < 3; i++) { options[i].disabled = true; } expect(testInstance.control.value).toBeFalsy(); fixture.componentInstance.select.open(); fixture.detectChanges(); const event = createKeyboardEvent('keydown', A, selectElement); Object.defineProperty(event, 'ctrlKey', { get: () => true }); dispatchEvent(selectElement, event); fixture.detectChanges(); expect(testInstance.control.value).toEqual([ 'sandwich-3', 'chips-4', 'eggs-5', 'pasta-6', 'sushi-7' ]); }); it('should select all options when pressing ctrl + a when some options are selected', () => { const selectElement = fixture.nativeElement.querySelector('mc-select'); const options = fixture.componentInstance.options.toArray(); options[0].select(); fixture.detectChanges(); expect(testInstance.control.value).toEqual(['steak-0']); expect(options.some((option) => option.selected)).toBe(true); fixture.componentInstance.select.open(); fixture.detectChanges(); const event = createKeyboardEvent('keydown', A, selectElement); Object.defineProperty(event, 'ctrlKey', { get: () => true }); dispatchEvent(selectElement, event); fixture.detectChanges(); expect(options.every((option) => option.selected)).toBe(true); expect(testInstance.control.value).toEqual([ 'steak-0', 'pizza-1', 'tacos-2', 'sandwich-3', 'chips-4', 'eggs-5', 'pasta-6', 'sushi-7' ]); }); it('should deselect all options with ctrl + a if all options are selected', () => { const selectElement = fixture.nativeElement.querySelector('mc-select'); const options = fixture.componentInstance.options.toArray(); options.forEach((option) => option.select()); fixture.detectChanges(); expect(testInstance.control.value).toEqual([ 'steak-0', 'pizza-1', 'tacos-2', 'sandwich-3', 'chips-4', 'eggs-5', 'pasta-6', 'sushi-7' ]); expect(options.every((option) => option.selected)).toBe(true); fixture.componentInstance.select.open(); fixture.detectChanges(); const event = createKeyboardEvent('keydown', A, selectElement); Object.defineProperty(event, 'ctrlKey', { get: () => true }); dispatchEvent(selectElement, event); fixture.detectChanges(); expect(options.some((option) => option.selected)).toBe(false); expect(testInstance.control.value).toEqual([]); }); }); });
the_stack
import {Size} from "./types" import {BBox} from "./util/bbox" import {Context2d} from "./util/canvas" import {font_metrics, /*glyph_metrics,*/ FontMetrics, parse_css_font_size} from "./util/text" import {max, max_by, sum} from "./util/array" import {isNumber} from "./util/types" import {Rect, AffineTransform} from "./util/affine" import {color2css} from "./util/color" import * as visuals from "./visuals" export const text_width: (text: string, font: string) => number = (() => { const canvas = document.createElement("canvas") const ctx = canvas.getContext("2d")! let current_font = "" return (text: string, font: string): number => { if (font != current_font) { current_font = font ctx.font = font } return ctx.measureText(text).width } })() export type Position = { sx: number sy: number x_anchor?: number | "left" | "center" | "right" y_anchor?: number | "top" | "center" | "baseline" | "bottom" } type Val = number | {value: number, unit: "px" | "%"} type Extents = {left: Val, right: Val, top: Val, bottom: Val} type Padding = Val | [v: Val, h: Val] | [top: Val, right: Val, bottom: Val, left: Val] | Extents export type TextHeightMetric = "x" | "cap" | "ascent" | "x_descent" | "cap_descent" | "ascent_descent" export abstract class GraphicsBox { _position: Position = {sx: 0, sy: 0} angle?: number width?: {value: number, unit: "%"} height?: {value: number, unit: "%"} padding?: Padding font_size_scale: number = 1.0 text_height_metric?: TextHeightMetric align: "auto" | "left" | "center" | "right" | "justify" = "left" _base_font_size: number = 13 // the same as .bk-root's font-size (13px) _x_anchor: "left" | "center" | "right" = "left" _y_anchor: "top" | "center" | "baseline" | "bottom" = "center" set base_font_size(v: number | null | undefined) { if (v != null) this._base_font_size = v } get base_font_size(): number { return this._base_font_size } set position(p: Position) { this._position = p } get position(): Position { return this._position } abstract set visuals(v: visuals.Text["Values"] | visuals.Line["Values"] | visuals.Fill["Values"]) abstract _rect(): Rect abstract _size(): Size abstract paint(ctx: Context2d): void infer_text_height(): TextHeightMetric { return "ascent_descent" } bbox(): BBox { const {p0, p1, p2, p3} = this.rect() const left = Math.min(p0.x, p1.x, p2.x, p3.x) const top = Math.min(p0.y, p1.y, p2.y, p3.y) const right = Math.max(p0.x, p1.x, p2.x, p3.x) const bottom = Math.max(p0.y, p1.y, p2.y, p3.y) return new BBox({left, right, top, bottom}) } size(): Size { const {width, height} = this._size() const {angle} = this if (!angle) return {width, height} else { const c = Math.cos(Math.abs(angle)) const s = Math.sin(Math.abs(angle)) return { width: Math.abs(width*c + height*s), height: Math.abs(width*s + height*c), } } } rect(): Rect { const rect = this._rect() const {angle} = this if (!angle) return rect else { const {sx, sy} = this.position const tr = new AffineTransform() tr.translate(sx, sy) tr.rotate(angle) tr.translate(-sx, -sy) return tr.apply_rect(rect) } } paint_rect(ctx: Context2d): void { const {p0, p1, p2, p3} = this.rect() ctx.save() ctx.strokeStyle = "red" ctx.lineWidth = 1 ctx.beginPath() const {round} = Math ctx.moveTo(round(p0.x), round(p0.y)) ctx.lineTo(round(p1.x), round(p1.y)) ctx.lineTo(round(p2.x), round(p2.y)) ctx.lineTo(round(p3.x), round(p3.y)) ctx.closePath() ctx.stroke() ctx.restore() } paint_bbox(ctx: Context2d): void { const {x, y, width, height} = this.bbox() ctx.save() ctx.strokeStyle = "blue" ctx.lineWidth = 1 ctx.beginPath() const {round} = Math ctx.moveTo(round(x), round(y)) ctx.lineTo(round(x), round(y + height)) ctx.lineTo(round(x + width), round(y + height)) ctx.lineTo(round(x + width), round(y)) ctx.closePath() ctx.stroke() ctx.restore() } } export class TextBox extends GraphicsBox { text: string color: string font: string line_height: number //padding: Padding private _visual_align: "left" | "center" | "right" = "left" set visuals(v: visuals.Text["Values"]) { const color = v.color const alpha = v.alpha const style = v.font_style let size = v.font_size const face = v.font const {font_size_scale, base_font_size} = this const res = parse_css_font_size(size) if (res != null) { let {value, unit} = res value *= font_size_scale if (unit == "em" && base_font_size) { value *= base_font_size unit = "px" } size = `${value}${unit}` } const font = `${style} ${size} ${face}` this.font = font this.color = color2css(color, alpha) this.line_height = v.line_height const align = v.align this._visual_align = align this._x_anchor = align const baseline = v.baseline this._y_anchor = (() => { switch (baseline) { case "top": return "top" case "middle": return "center" case "bottom": return "bottom" default: return "baseline" } })() } constructor({text}: {text: string}) { super() this.text = text } override infer_text_height() { if (this.text.includes("\n")) return "ascent_descent" else { function is_math_like(text: string): boolean { for (const c of new Set(text)) { if ("0" <= c && c <= "9") continue switch (c) { case ",": case ".": case "+": case "-": case "\u2212": case "e": continue default: return false } } return true } if (is_math_like(this.text)) return "cap" else return "ascent_descent" /* const {font} = this const fmetrics = font_metrics(font) let max_ascent = 0 let max_descent = 0 for (const c of this.text) { const metrics = glyph_metrics(c, font) max_ascent = Math.max(metrics.ascent) max_descent = Math.max(metrics.descent) } const ascent = (() => { if (max_ascent > fmetrics.cap_height) return "ascent" else if (max_ascent > fmetrics.x_height) return "cap" else return "x" })() return max_descent > 0 ? `${ascent}_descent` as const : ascent */ } } _text_line(fmetrics: FontMetrics): {height: number, ascent: number, descent: number} { const metric = this.text_height_metric ?? this.infer_text_height() const ascent = (() => { switch (metric) { case "x": case "x_descent": return fmetrics.x_height case "cap": case "cap_descent": return fmetrics.cap_height case "ascent": case "ascent_descent": return fmetrics.ascent } })() const descent = (() => { switch (metric) { case "x": case "cap": case "ascent": return 0 case "x_descent": case "cap_descent": case "ascent_descent": return fmetrics.descent } })() return {height: ascent + descent, ascent, descent} } get nlines(): number { const lines = this.text.split("\n") return lines.length } _size(): Size & {metrics: FontMetrics} { const {font} = this const fmetrics = font_metrics(font) const line_spacing = (this.line_height - 1)*fmetrics.height // TODO: max(trailing(L[n-1]), leading(L[n])) const empty = this.text == "" const lines = this.text.split("\n") const nlines = lines.length const widths = lines.map((line) => text_width(line, font)) const text_line = this._text_line(fmetrics) const text_height = text_line.height*nlines /* const heights: number[] = [] const ascents: number[] = [] const descents: number[] = [] for (const line of lines) { const metrics = [...line].map((c) => glyph_metrics(c, font)) const max_ascent = Math.max(max(metrics.map((m) => m.ascent)), fmetrics.cap_height) const max_descent = max(metrics.map((m) => m.descent)) ascents.push(max_ascent) descents.push(max_descent) heights.push(max_ascent + max_descent) } const text_height = sum(heights) */ const w_scale = this.width?.unit == "%" ? this.width.value : 1 const h_scale = this.height?.unit == "%" ? this.height.value : 1 const width = max(widths)*w_scale const height = empty ? 0 : (text_height + line_spacing*(nlines - 1))*h_scale return {width, height, metrics: fmetrics} } _computed_position(size: Size, metrics: FontMetrics, nlines: number): {x: number, y: number} { const {width, height} = size const {sx, sy, x_anchor=this._x_anchor, y_anchor=this._y_anchor} = this.position const x = sx - (() => { if (isNumber(x_anchor)) return x_anchor*width else { switch (x_anchor) { case "left": return 0 case "center": return 0.5*width case "right": return width } } })() const y = sy - (() => { if (isNumber(y_anchor)) return y_anchor*height else { switch (y_anchor) { case "top": return 0 case "center": return 0.5*height case "bottom": return height case "baseline": { if (nlines == 1) { const metric = this.text_height_metric ?? this.infer_text_height() switch (metric) { case "x": case "x_descent": return metrics.x_height case "cap": case "cap_descent": return metrics.cap_height case "ascent": case "ascent_descent": return metrics.ascent } } else return 0.5*height } } } })() return {x, y} } _rect(): Rect { const {width, height, metrics} = this._size() const nlines = this.text.split("\n").length const {x, y} = this._computed_position({width, height}, metrics, nlines) const bbox = new BBox({x, y, width, height}) return bbox.rect } paint(ctx: Context2d): void { const {font} = this const fmetrics = font_metrics(font) const line_spacing = (this.line_height - 1)*fmetrics.height // TODO: see above const lines = this.text.split("\n") const nlines = lines.length const widths = lines.map((line) => text_width(line, font)) const text_line = this._text_line(fmetrics) const text_height = text_line.height*nlines /* const heights: number[] = [] const ascents: number[] = [] const descents: number[] = [] for (const line of lines) { const metrics = [...line].map((c) => glyph_metrics(c, font)) const max_ascent = Math.max(max(metrics.map((m) => m.ascent)), fmetrics.cap_height) const max_descent = max(metrics.map((m) => m.descent)) ascents.push(max_ascent) descents.push(max_descent) heights.push(max_ascent + max_descent) } */ const w_scale = this.width?.unit == "%" ? this.width.value : 1 const h_scale = this.height?.unit == "%" ? this.height.value : 1 const width = max(widths)*w_scale const height = (text_height + line_spacing*(nlines - 1))*h_scale ctx.save() ctx.fillStyle = this.color ctx.font = this.font ctx.textAlign = "left" ctx.textBaseline = "alphabetic" const {sx, sy} = this.position const {align} = this const {angle} = this if (angle) { ctx.translate(sx, sy) ctx.rotate(angle) ctx.translate(-sx, -sy) } let {x, y} = this._computed_position({width, height}, fmetrics, nlines) if (align == "justify") { for (let i = 0; i < nlines; i++) { let xij = x const line = lines[i] const words = line.split(" ") const nwords = words.length const word_widths = words.map((word) => text_width(word, font)) const word_spacing = (width - sum(word_widths))/(nwords - 1) for (let j = 0; j < nwords; j++) { ctx.fillText(words[j], xij, y) xij += word_widths[j] + word_spacing } y += /*heights[i]*/ text_line.height + line_spacing } } else { for (let i = 0; i < nlines; i++) { const xi = x + (() => { switch (align == "auto" ? this._visual_align : align) { case "left": return 0 case "center": return 0.5*(width - widths[i]) case "right": return width - widths[i] } })() ctx.fillStyle = this.color ctx.fillText(lines[i], xi, y + /*ascents[i]*/ text_line.ascent) y += /*heights[i]*/ text_line.height + line_spacing } } ctx.restore() } } export class BaseExpo extends GraphicsBox { constructor(readonly base: GraphicsBox, readonly expo: GraphicsBox) { super() } get children(): GraphicsBox[] { return [this.base, this.expo] } override set base_font_size(v: number) { super.base_font_size = v this.base.base_font_size = v this.expo.base_font_size = v } override set position(p: Position) { this._position = p const bs = this.base.size() const es = this.expo.size() const shift = this._shift_scale()*bs.height const height = Math.max(bs.height, shift + es.height) this.base.position = { sx: 0, x_anchor: "left", sy: height, y_anchor: "bottom", } this.expo.position = { sx: bs.width, x_anchor: "left", sy: shift, y_anchor: "bottom", } } override get position(): Position { return this._position } set visuals(v: visuals.Text["Values"] | visuals.Line["Values"] | visuals.Fill["Values"]) { this.expo.font_size_scale = 0.7 this.base.visuals = v this.expo.visuals = v } _shift_scale(): number { if (this.base instanceof TextBox && this.base.nlines == 1) { const {x_height, cap_height} = font_metrics(this.base.font) return x_height/cap_height } else { return 2/3 } } override infer_text_height() { return this.base.infer_text_height() } _rect(): Rect { const bb = this.base.bbox() const eb = this.expo.bbox() const bbox = bb.union(eb) const {x, y} = this._computed_position() return bbox.translate(x, y).rect } _size(): Size { const bs = this.base.size() const es = this.expo.size() return { width: bs.width + es.width, height: Math.max(bs.height, this._shift_scale()*bs.height + es.height), } } paint(ctx: Context2d): void { ctx.save() const {angle} = this if (angle) { const {sx, sy} = this.position ctx.translate(sx, sy) ctx.rotate(angle) ctx.translate(-sx, -sy) } const {x, y} = this._computed_position() ctx.translate(x, y) this.base.paint(ctx) this.expo.paint(ctx) ctx.restore() } // paint_rect ... override paint_bbox(ctx: Context2d): void { super.paint_bbox(ctx) const {x, y} = this._computed_position() ctx.save() ctx.translate(x, y) for (const child of this.children) { child.paint_bbox(ctx) } ctx.restore() } _computed_position(): {x: number, y: number} { const {width, height} = this._size() const {sx, sy, x_anchor=this._x_anchor, y_anchor=this._y_anchor} = this.position const x = sx - (() => { if (isNumber(x_anchor)) return x_anchor*width else { switch (x_anchor) { case "left": return 0 case "center": return 0.5*width case "right": return width } } })() const y = sy - (() => { if (isNumber(y_anchor)) return y_anchor*height else { switch (y_anchor) { case "top": return 0 case "center": return 0.5*height case "bottom": return height case "baseline": return 0.5*height /* TODO */ } } })() return {x, y} } } export class GraphicsBoxes { constructor(readonly items: GraphicsBox[]) {} set base_font_size(v: number | null | undefined) { for (const item of this.items) { item.base_font_size = v } } get length(): number { return this.items.length } set visuals(v: visuals.Text["Values"] | visuals.Line["Values"] | visuals.Fill["Values"]) { for (const item of this.items) { item.visuals = v } const metric_map = {x: 0, cap: 1, ascent: 2, x_descent: 3, cap_descent: 4, ascent_descent: 5} const common = max_by(this.items.map((item) => item.infer_text_height()), (metric) => metric_map[metric]) for (const item of this.items) { item.text_height_metric = common } } set angle(a: number) { for (const item of this.items) { item.angle = a } } max_size(): Size { let width = 0 let height = 0 for (const item of this.items) { const size = item.size() width = Math.max(width, size.width) height = Math.max(height, size.height) } return {width, height} } }
the_stack
import { Entity, EntityRequest, fetchEntity, fetchQuestionBackLinks, fetchStoryBackLinks, getCollectionSchema, request, ResourceType, SearchBlockResult, searchBlocks, translateSmartQuery } from '@app/api' import { useAsync } from '@app/hooks' import { useWorkspace } from '@app/hooks/useWorkspace' import type { AvailableConfig, BackLinks, Dimension, ProfileConfig, Story, UserInfo, Workspace } from '@app/types' import { Editor } from '@app/types' import { queryClient } from '@app/utils' import { compact } from 'lodash' import { useCallback, useEffect, useMemo, useState } from 'react' import { QueryObserverResult, useInfiniteQuery, useMutation, useQuery, useQueryClient, UseQueryOptions } from 'react-query' import { useRecoilCallback, useRecoilValue, useRecoilValueLoadable, waitForAll } from 'recoil' import invariant from 'tiny-invariant' import { blockUpdater, QuerySnapshotAtom, QuerySnapshotIdAtom, TelleryBlockAtom, TellerySnapshotAtom, TelleryUserAtom } from '../store/block' import { useBatchQueries } from './useBatchQueries' export type User = { id: string avatar?: string name: string email: string status: 'active' | 'confirmed' | 'verifying' } export const useStory = (id: string) => { const result = useBlock<Story>(id) return result } export const useUpdateBlocks = () => { const updateBlocks = useRecoilCallback( (recoilInterface) => (blocks: Record<string, Editor.BaseBlock>) => { Object.values(blocks).forEach((block) => { const targetAtom = TelleryBlockAtom(block.id) const loadable = recoilInterface.snapshot.getInfo_UNSTABLE(targetAtom).loadable if (loadable === undefined || loadable.state !== 'hasValue') { recoilInterface.set(targetAtom, block) } else { recoilInterface.set(targetAtom, blockUpdater(block, loadable.contents) as Editor.BaseBlock) } }) }, [] ) return updateBlocks } export const useFetchStoryChunk = (id: string, suspense: boolean = true) => { const updateBlocks = useUpdateBlocks() const workspace = useWorkspace() useQuery( ['story', 'chunk', workspace, id], async () => request .post<{ blocks: Record<string, Editor.BaseBlock> }>('/api/stories/load', { workspaceId: workspace.id, storyId: id }) .then(({ data: { blocks } }) => { updateBlocks(blocks) return blocks }), { suspense: suspense } ) } export const useStoryPinnedStatus = (id?: string) => { const { data: view } = useWorkspaceView() return !!id && !!view?.pinnedList.includes(id) } // export const useStoryNameConflict = (keyword: string, storyId: string) => { // const result = useQuery( // ['stories', 'search', 'names', keyword], // async () => // request // .post('/api/stories/search', { // keyword, // workspaceId: WORKSPACEID, // filters: { type: 'story' } // }) // .then((res) => { // const data = res.data as { // results: { // blocks: { [key: string]: Editor.ContentBlock } // searchResults: string[] // } // } // const firstMatchedId = data.results.searchResults[0] // if (firstMatchedId) { // const matchedBlock = data.results.blocks[firstMatchedId] // const matchedTitle = matchedBlock?.content?.title?.[0]?.[0] // console.log('conflict', matchedTitle === keyword && firstMatchedId !== storyId) // return matchedTitle === keyword && firstMatchedId !== storyId // } else { // return false // } // }), // { enabled: !!keyword.length } // ) // return result // } export const useStoriesSearch = (keyword: string) => { const workspace = useWorkspace() const result = useInfiniteQuery( ['stories', 'search', workspace, keyword], async ({ pageParam }) => request .post('/api/stories/search', { keyword, workspaceId: workspace.id, next: pageParam }) .then((res) => { return res.data as { results: { blocks: { [key: string]: Editor.ContentBlock } users: { [k: string]: UserInfo } links: { [k: string]: string[] } searchResults: string[] highlights: { [k: string]: string } } next?: unknown } }), { getNextPageParam: ({ next }) => next, refetchOnMount: true } ) return result } export function useSearchBlocks<T extends Editor.BlockType>( keyword: string, limit: number, type?: T, options?: UseQueryOptions<SearchBlockResult<T>> ) { const workspace = useWorkspace() const blockUpdater = useUpdateBlocks() return useQuery<SearchBlockResult<T>>( ['search', 'block', type, keyword, limit], async () => searchBlocks(keyword, limit, workspace.id, type).then((results) => { blockUpdater(results.blocks) return results }), options ) } export function useSearchMetrics( keyword: string, limit: number, options?: UseQueryOptions<SearchBlockResult<Editor.BlockType.QueryBuilder>> ) { return useSearchBlocks(keyword, limit, Editor.BlockType.QueryBuilder, options) } export function useSearchSQLQueries( keyword: string, limit: number, options?: UseQueryOptions<SearchBlockResult<Editor.BlockType.SQL>> ) { return useSearchBlocks(keyword, limit, Editor.BlockType.SQL, options) } export function useSearchDBTBlocks( keyword: string, limit: number, options?: UseQueryOptions<SearchBlockResult<Editor.BlockType.DBT>> ) { return useSearchBlocks(keyword, limit, Editor.BlockType.DBT, options) } export const useRefetchMetrics = () => { const queryClient = useQueryClient() const refetch = useCallback(() => { queryClient.refetchQueries(['search', 'block', Editor.BlockType.QueryBuilder]) }, [queryClient]) return refetch } export const useListDatabases = () => { const workspace = useWorkspace() return useQuery( ['listDatabases', workspace], () => request .post<{ databases: string[] }>('/api/connectors/listDatabases', { connectorId: workspace.preferences.connectorId, profile: workspace.preferences.profile, workspaceId: workspace.id }) .then((res) => res.data.databases), { retry: false, enabled: !!(workspace.preferences.connectorId && workspace.preferences.profile) } ) } export const useListCollections = (database?: string) => { const workspace = useWorkspace() return useQuery( ['listCollections', workspace, database], () => request .post<{ collections: string[] }>('/api/connectors/listCollections', { connectorId: workspace.preferences.connectorId, profile: workspace.preferences.profile, database, workspaceId: workspace.id }) .then((res) => res.data.collections), { enabled: !!database, retry: false } ) } export const useGetCollectionSchema = (database?: string, collection?: string) => { const workspace = useWorkspace() return useQuery( ['getCollectionSchema', database, collection], () => { return getCollectionSchema({ database: database!, collection: collection!, workspaceId: workspace.id, profile: workspace.preferences.profile!, connectorId: workspace.preferences.connectorId! }) }, { enabled: !!(database && collection), retry: false } ) } const BatchGetOptions = { refetchOnMount: false, refetchOnWindowFocus: false, keepPreviousData: true } export const useMgetEntities = (entities: { type: ResourceType; args: EntityRequest }[]) => { const workspace = useWorkspace() const queriesArray = useMemo( () => entities ? entities.map((entitiy) => { return { queryKey: [entitiy.type, entitiy.args.id], queryFn: () => fetchEntity(entitiy.type, entitiy.args, workspace.id), ...BatchGetOptions } }) : [], // eslint-disable-next-line react-hooks/exhaustive-deps [JSON.stringify(entities)] ) const queries = useBatchQueries(queriesArray) as QueryObserverResult<Entity>[] const enabled = !!(entities && queries.length === entities.length) const isSuccess = useMemo(() => enabled && queries.every((query) => query.isSuccess), [enabled, queries]) const data = useMemo(() => { const resultMap = isSuccess ? queries.reduce( (acc, query) => { if (query.data?.id) { acc[query.data.resourceType][query.data.id] = query.data } return acc }, { link: {}, question: {}, user: {}, block: {} } as { [key: string]: Record<string, Entity> } ) : undefined return resultMap // eslint-disable-next-line react-hooks/exhaustive-deps }, [isSuccess]) return useMemo(() => ({ queries, isSuccess, data }), [data, isSuccess, queries]) } export const useMgetBlocks = (ids?: string[]): { data?: Record<string, Editor.BaseBlock>; isSuccess?: boolean } => { const atoms = useRecoilValueLoadable(waitForAll(ids?.map((id) => TelleryBlockAtom(id)) ?? [])) const [state, setState] = useState({}) useEffect(() => { if (!ids || !ids.length) { setState({}) return } switch (atoms.state) { case 'hasValue': setState({ data: atoms.contents.reduce((acc, block) => { invariant(block, 'block is undefined') if (block.id) { acc[block.id] = block } return acc }, {} as { [key: string]: Editor.BaseBlock }), isSuccess: true }) break case 'loading': setState({}) break } }, [atoms, ids]) return state } export const useMgetBlocksSuspense = (ids: string[]): Editor.BaseBlock[] => { const atoms = useRecoilValue(waitForAll(ids.map((id) => TelleryBlockAtom(id)))) return atoms as Editor.BaseBlock[] } export const useUser = (id: string | null): { data?: User; error?: { statusCode?: number } } => { const atom = useRecoilValueLoadable(TelleryUserAtom(id)) const [state, setState] = useState({}) useEffect(() => { if (!id) { return } switch (atom.state) { case 'hasValue': setState({ data: atom.contents }) break case 'loading': setState({}) break case 'hasError': setState({ error: atom.contents }) break } }, [atom.contents, atom.state, id]) return state } export const useMgetUsers = (ids?: string[]): { data?: Record<string, User>; isSuccess?: boolean } => { const atoms = useRecoilValueLoadable(waitForAll(ids?.map((id) => TelleryUserAtom(id)) ?? [])) const [state, setState] = useState({}) useEffect(() => { switch (atoms.state) { case 'hasValue': setState({ data: atoms.contents.reduce((acc, user) => { invariant(user, 'user is undefined') if (user.id) { acc[user.id] = user } return acc }, {} as { [key: string]: User }), isSuccess: true }) break case 'loading': setState({}) break } }, [atoms]) return state } export const useBlockSuspense = <T extends Editor.BaseBlock = Editor.BaseBlock>(id: string): T => { const atom = useRecoilValue(TelleryBlockAtom(id)) invariant(atom, 'atom is undefined') return atom as unknown as T } export const useBlock = <T extends Editor.BaseBlock = Editor.BaseBlock>( id: string ): { data?: T; error?: { statusCode?: number } } => { const atom = useRecoilValueLoadable(TelleryBlockAtom(id)) const [state, setState] = useState({}) useEffect(() => { if (!id) { setState({}) return } switch (atom.state) { case 'hasValue': setState({ data: atom.contents }) break case 'loading': setState({}) break case 'hasError': setState({ error: atom.contents }) break } }, [atom.contents, atom.state, id]) return state } export const useSnapshot = (id: string | null = null) => { const atom = useRecoilValue(TellerySnapshotAtom(id)) return atom // const workspace = useWorkspace() // return useQuery<Snapshot>(['snapshot', id], () => fetchSnapshot(id, workspace.id), { // enabled: !!id, // keepPreviousData: true // }) } export const useQuerySnapshotId = (queryId: string) => { const atom = useRecoilValue(QuerySnapshotIdAtom({ blockId: queryId })) return atom } export const useQuerySnapshot = (queryId: string) => { const atom = useRecoilValue(QuerySnapshotAtom({ blockId: queryId })) return atom } export const useGetSnapshot = () => { // const snapshot = useSnapshot(block?.content?.snapshotId) const getSnapshot = useRecoilCallback( (recoilCallback) => async ({ snapshotId }: { snapshotId?: string }) => { const snapshot = await recoilCallback.snapshot.getPromise(TellerySnapshotAtom(snapshotId ?? null)) return snapshot }, [] ) return getSnapshot } export const useGetBlock = () => { // const snapshot = useSnapshot(block?.content?.snapshotId) const getBlock = useRecoilCallback( (recoilCallback) => async (blockId: string) => { const snapshot = await recoilCallback.snapshot.getPromise(TelleryBlockAtom(blockId)) return snapshot as Editor.Block }, [] ) return getBlock } export const useQuestionBackLinks = (id: string = '') => { const workspace = useWorkspace() return useQuery<BackLinks>(['backlinks', 'question', id], () => fetchQuestionBackLinks(id, workspace.id), { enabled: !!id }) } export const useStoryBackLinks = (id: string = '') => { const workspace = useWorkspace() return useQuery<BackLinks>(['backlinks', 'story', id], () => fetchStoryBackLinks(id, workspace.id), { enabled: !!id }) } export const useQuestionDownstreams = (id?: string) => { const { data: links, refetch } = useQuestionBackLinks(id) const blockIds = useMemo( () => [ ...new Set(links?.backwardRefs.map(({ blockId }) => blockId)), ...new Set(links?.backwardRefs.map(({ storyId }) => storyId)) ], [links] ) const { data: blocks } = useMgetBlocks(blockIds) const items = useMemo( () => compact( links?.backwardRefs.filter((link) => link.type === 'question_ref')?.map(({ blockId }) => blocks?.[blockId]) ), [blocks, links?.backwardRefs] ) return { data: items, refetch } } export function useWorkspaceList(options?: Omit<UseQueryOptions, 'queryKey' | 'queryFn'>) { return useQuery( ['workspaces', 'list'], () => request.post<{ workspaces: Workspace[] }>('/api/workspaces/list').then((res) => res.data.workspaces), options ) } export function useWorkspaceView() { const workspace = useWorkspace() return useQuery(['workspaces', 'getView', workspace], () => request .post<{ id: string; pinnedList: string[] }>('/api/workspaces/getView', { workspaceId: workspace.id }) .then((res) => res.data) ) } export function useWorkspaceDetail() { const workspace = useWorkspace() return useQuery(['workspaces', 'getDetail', workspace], () => request .post<{ workspace: Workspace }>('/api/workspaces/getDetail', { workspaceId: workspace.id }) .then((res) => res.data.workspace) ) } export function useWorkspaceUpdate() { const workspace = useWorkspace() const handleUpdate = useCallback( (payload: { name?: string; avatar?: string; resetInviteCode?: boolean }) => request.post('/api/workspaces/update', { ...payload, workspaceId: workspace.id }), [workspace.id] ) return useAsync(handleUpdate) } export function useWorkspaceUpdateRole() { const workspace = useWorkspace() const handleUpdateRole = useCallback( (userId: string, role: Workspace['members'][0]['role']) => request.post('/api/workspaces/updateRole', { workspaceId: workspace.id, userId, role }), [workspace.id] ) return useAsync(handleUpdateRole) } export function useWorkspaceKickout() { const workspace = useWorkspace() const handleKickout = useCallback( (userIds: string[]) => request.post('/api/workspaces/kickout', { workspaceId: workspace.id, userIds }), [workspace] ) return useAsync(handleKickout) } export function useWorkspaceLeave() { const workspace = useWorkspace() const handleLeave = useCallback( () => request.post('/api/workspaces/leave', { workspaceId: workspace.id }), [workspace] ) return useAsync(handleLeave) } type StoryVisisRecord = { storyId: string; userId: string; lastVisitTimestamp: number }[] export const useStoryVisits = (storyId: string = '', limit = 5) => { const workspace = useWorkspace() return useQuery( ['story', storyId, 'visits', workspace], () => request .post<{ visits: StoryVisisRecord }>('/api/stories/getVisits', { workspaceId: workspace.id, storyId, limit }) .then((res) => res.data.visits), { enabled: !!storyId } ) } const recordVisits = ({ workspaceId, storyId }: { workspaceId: string; storyId: string; userId: string }) => { return request.post('/api/stories/recordVisit', { workspaceId, storyId }) } export const useRecordStoryVisits = () => { const mutation = useMutation(recordVisits, { onMutate: ({ storyId, userId }) => { // queryClient.invalidateQueries(['story', storyId, 'visits']) queryClient.setQueryData<StoryVisisRecord | undefined>(['story', storyId, 'visits'], (storyVisits) => { return [ { storyId, userId: userId, lastVisitTimestamp: Date.now() }, ...(storyVisits?.filter((visit) => visit.userId !== userId) ?? []) ] as StoryVisisRecord }) } }) return mutation } // export const useExecuteSQL = (id: string) => { // const executeSQL = useMutation(sqlRequest, { mutationKey: id }) // return executeSQL // } export const useConnectorsList = () => { const workspace = useWorkspace() return useQuery(['connector', 'list', workspace], () => request .post<{ connectors: { id: string; url: string; name: string }[] }>('/api/connectors/list', { workspaceId: workspace.id }) .then((res) => res.data.connectors) ) } export const useConnectorsGetProfile = (connectorId?: string) => { const workspace = useWorkspace() return useQuery( ['connector', 'getProfile', connectorId, workspace], () => request .post<{ profile: ProfileConfig }>('/api/connectors/getProfile', { connectorId, workspaceId: workspace.id }) .then((res) => res.data.profile), { enabled: !!connectorId } ) } export const useConnectorsGetProfileConfigs = (connectorId?: string) => { const workspace = useWorkspace() return useQuery( ['connector', 'getProfileConfigs', connectorId, workspace.id], () => request .post<{ configs: { type: string configs: AvailableConfig[] }[] }>('/api/connectors/getProfileConfigs', { connectorId, workspaceId: workspace.id }) .then((res) => res.data.configs), { enabled: !!connectorId } ) } export function useConnectorsUpsertProfile(connectorId: string) { const workspace = useWorkspace() const handleUpdateProfile = useCallback( (payload: ProfileConfig) => request.post('/api/connectors/upsertProfile', { ...payload, workspaceId: workspace.id, connectorId }), [connectorId, workspace.id] ) return useAsync(handleUpdateProfile) } export const useGetProfileSpec = () => { const workspace = useWorkspace() return useQuery( ['connector', 'getProfileSpec', workspace.id, workspace.preferences.connectorId, workspace.preferences.profile], () => request .post<{ queryBuilderSpec: { aggregation: Record<string, Record<string, string>> bucketization: Record<string, Record<string, string>> identifier: string stringLiteral: string } name: string tokenizer: string type: string }>('/api/connectors/getProfileSpec', { workspaceId: workspace.id, connectorId: workspace.preferences.connectorId, profile: workspace.preferences.profile }) .then((res) => res.data), { enabled: !!workspace.preferences.connectorId && !!workspace.preferences.profile } ) } export function useTranslateSmartQuery( queryBuilderId?: string, metricIds: string[] = [], dimensions: Dimension[] = [], filters?: Editor.FilterBuilder ) { const workspace = useWorkspace() return useQuery( [ 'connectors', 'translateSmartQuery', workspace.id, queryBuilderId, ...metricIds, JSON.stringify(dimensions), JSON.stringify(filters) ], () => translateSmartQuery( workspace.id, workspace.preferences?.connectorId!, queryBuilderId!, metricIds, dimensions, filters ).then((res) => res.data.sql), { enabled: !!queryBuilderId } ) } /** * dbt start */ export function useGenerateKeyPair( connectorId: string, profile?: ProfileConfig, dbtProjectName?: string, gitUrl?: string ) { const workspace = useWorkspace() const handleGenerateKeyPair = useCallback(async () => { if (!profile || !dbtProjectName || !gitUrl) { return } await request.post('/api/connectors/upsertProfile', { ...profile, configs: { ...profile.configs, 'Dbt Project Name': dbtProjectName, 'Git Url': gitUrl }, workspaceId: workspace.id, connectorId }) await request.post('/api/connectors/dbt/generateKeyPair', { profile: profile.name, workspaceId: workspace.id, connectorId }) }, [connectorId, dbtProjectName, gitUrl, profile, workspace.id]) return useAsync(handleGenerateKeyPair) } export function useRevokeKeyPair(connectorId: string, profile?: ProfileConfig) { const workspace = useWorkspace() const handleRevokeKeyPair = useCallback(async () => { if (!profile) { return } delete profile.configs['Dbt Project Name'] delete profile.configs['Git Url'] delete profile.configs['Public Key'] await request.post('/api/connectors/upsertProfile', { ...profile, configs: profile.configs, workspaceId: workspace.id, connectorId }) }, [connectorId, profile, workspace.id]) return useAsync(handleRevokeKeyPair) } export function usePushRepo(connectorId: string, profile?: string) { const workspace = useWorkspace() const handlePushRepo = useCallback(async () => { if (!profile) { return } await request.post('/api/connectors/dbt/pushRepo', { profile, workspaceId: workspace.id, connectorId }) }, [connectorId, profile, workspace.id]) return useAsync(handlePushRepo) } export function usePullRepo(connectorId: string, profile?: string) { const workspace = useWorkspace() const handlePullRepo = useCallback(async () => { if (!profile) { return } await request.post('/api/connectors/dbt/pullRepo', { profile, workspaceId: workspace.id, connectorId }) }, [connectorId, profile, workspace.id]) return useAsync(handlePullRepo) } export function useDowngradeQueryBuilder(queryBuilderId: string) { const workspace = useWorkspace() const handleDowngradeQueryBuilder = useCallback(async () => { await request.post('/api/queries/downgradeQueryBuilder', { workspaceId: workspace.id, connectorId: workspace.preferences.connectorId, queryBuilderId }) }, [queryBuilderId, workspace.id, workspace.preferences.connectorId]) return useAsync(handleDowngradeQueryBuilder) } /** * dbt end */ export const useAllThoughts = () => { const workspace = useWorkspace() const result = useQuery(['thought', 'loadAll', workspace], async () => { return request .post<{ thoughts: { id: string date: string }[] }>('/api/thought/loadAll', { workspaceId: workspace.id }) .then((res) => res.data.thoughts) }) return result }
the_stack
'use strict'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as _ from 'lodash'; import './index.less'; import 'butterfly-dag/dist/index.css'; import Canvas from './canvas/canvas'; import Edge from './canvas/edge'; import {transformInitData, diffPropsData} from './adaptor'; // 右键菜单配置 interface menu { title?: string, key: string, render?(key: string): void, onClick?(node: any): void, } // 画布配置 interface config { delayDraw: number, // 延迟加载 showActionIcon?: boolean,// 是否操作icon:放大,缩小,聚焦 focusCenter?: boolean, //是否初始化的时候把所有节点居中 draggable?: boolean, // 是否允许节点拖拽 diffOptions?: Array<string>, // 更新节点时,需要diff的字段集合(默认节点diff节点id) edge?: { //定制线段的类型,todo需要思考 type: string, config: any, }, group?: { enableSearch: boolean, // 是否开启节点组搜索节点 }, statusNote?: { enable: boolean, notes: [{ code: string, className: string, text: string, render?:() => JSX.Element }] }, labelRender?(label: string): JSX.Element, // 自定义label样式,没定义使用默认样式 nodeRender?(data: any): JSX.Element, // 自定义节点样式,没定义使用默认样式 autoLayout?: { enable: boolean, // 是否开启自动布局 isAlways: boolean, // 是否添加节点后就重新布局, todo config: any // 算法配置 }, minimap: { // 是否开启缩略图 enable: boolean, config: { nodeColor: any } } } interface ComProps { data: any, // 画布数据 width?: number | string, // 组件宽 height?: number | string, // 组件高 className?: string, // 组件classname nodeMenu: Array<menu> | ((node) => Array<menu>), // 节点右键菜单配置 nodeMenuClassName?: string, // 节点菜单样式 edgeMenu: Array<menu>, // 线段右键菜单配置 groupMenu: Array<menu>, // group右键配置 config?: config, // 画布配置 polling?: { // 支持轮训 enable: boolean, interval: number, getData(data): void }, registerStatus?: { // 自行注册状态,会根据node的status给节点加上class success: string, fail: string, // key:value的形式,可以自行注册,和node的status字段对应起来 }, onClickNode?(node: any): void, // 单击节点事件 onClickCanvas?():void, // 点击画布空白处事件 onContextmenuNode?(node: any): void, // 右键节点事件 onDblClickNode?(node: any): void, // 双击节点事件 onClickEdge?(edge: any): void, // 单击线段事件 onClickLabel?(label: string, edge: any): void, //单击label的事件 onContextmenuEdge?(edge: any): void, // 右键线段事件 onContextmenuGroup?(edge: any): void, // 右键线段事件 onChangePage?(data:any): void, // 分页事件 onLoaded?(data: any): void // 画布加载完成之后的回调 } export default class MonitorDag extends React.Component<ComProps, any> { protected canvas: any; protected canvasData: any; protected group: any; private _timer: any; private _focusNodes: any; private _focusLinks: any; private _statusNote: any; props: any; constructor(props: ComProps) { super(props); this.canvas = null; this.canvasData = null; this._focusNodes = []; this._focusLinks = []; this._timer = null; this._statusNote = { success: { className: 'success', text: '成功' }, fail: { className: 'fail', text: '失败' }, timeout: { className: 'timeout', text: '超时' }, running: { className: 'running', text: '正在运行' }, waiting: { className: 'waiting', text: '等待中' } }; } componentDidMount() { let root = ReactDOM.findDOMNode(this) as HTMLElement; if (this.props.width !== undefined) { root.style.width = this.props.width + 'px'; } if (this.props.height !== undefined) { root.style.height = this.props.height + 'px'; } let result = transformInitData({ config: this.props.config, nodeMenu: this.props.nodeMenu, edgeMenu: this.props.edgeMenu, groupMenu: this.props.groupMenu, nodeMenuClassName: this.props.nodeMenuClassName, data: _.cloneDeep(this.props.data || {nodes: [], edges: [], groups: []}), registerStatus: _.cloneDeep(this.props.registerStatus) }); let canvasObj = ({ root: root, disLinkable: false, linkable: false, draggable: _.get(this.props, 'config.draggable', true), zoomable: true, moveable: true, theme: { edge: { // todo, type: 'endpoint', shapeType: _.get(this, 'props.config.edge.shapeType', 'AdvancedBezier'), isExpandWidth: true, arrow: _.get(this, 'props.config.edge.config.arrow', true), arrowPosition: _.get(this, 'props.config.edge.config.arrowPosition', 1), arrowOffset: _.get(this, 'props.config.edge.config.arrowPosition', -8), Class: Edge }, } }); if (_.get(this.props, 'config.autoLayout.enable', false)) { canvasObj['layout'] = { type: 'dagreLayout', options: { rankdir: _.get(this.props, 'config.direction', 'top-bottom') === 'top-bottom' ? 'TB' : 'LR', nodesep: 40, ranksep: 40 } }; } this.canvas = new Canvas(canvasObj); setTimeout(() => { this.canvas.draw(result, (data) => { this.props.onLoaded && this.props.onLoaded(data); let minimap = _.get(this, 'props.config.minimap', {}); const minimapCfg = _.assign({}, minimap.config, { events: [ 'system.node.click', 'system.canvas.click' ] }); if (minimap && minimap.enable) { this.canvas.setMinimap(true, minimapCfg); } if (_.get(this, 'props.config.focusCenter')) { this.canvas.focusCenterWithAnimate(); } }); }, _.get(this.props, 'config.delayDraw', 0)); this.canvas.on('events', (data) => { // console.log(data); }); this.canvasData = result; // 监听事件 this.canvas.on('system.node.click', (data: any) => { this._focusNode([data.node]); this.props.onClickNode && this.props.onClickNode(data.node); }); this.canvas.on('custom.node.rightClick', (data: any) => { this.props.onContextmenuNode && this.props.onContextmenuNode(data.node); }); this.canvas.on('custom.node.dblClick', (data: any) => { this.props.onDblClickNode && this.props.onDblClickNode(data.node); }); this.canvas.on('custom.edge.rightClick', (data: any) => { this.props.onContextmenuEdge && this.props.onContextmenuEdge(data.edge); }); this.canvas.on('system.link.click', (data: any) => { this._focusLink([data.edge]); this.props.onClickEdge && this.props.onClickEdge(data.edge); }); this.canvas.on('custom.edge.labelClick', (data: any) => { this._focusLink([data.edge]); this.props.onClickLabel && this.props.onClickLabel(data.label, data.edge); }); this.canvas.on('system.canvas.click', (data: any) => { this._unfocus(); this.props.onClickCanvas && this.props.onClickCanvas(); }); this.canvas.on('custom.groups.rightClick', (data: any) => { this.props.onContextmenuGroup && this.props.onContextmenuGroup(data.groups); }); this.canvas.on('custom.group.search', (data: any) => { let nodes = data.nodes; this._focusNode(nodes); }); // 检测轮训 this._polling(); } shouldComponentUpdate(newProps: ComProps, newState: any) { let result = transformInitData({ config: this.props.config, nodeMenu: this.props.nodeMenu, edgeMenu: this.props.edgeMenu, groupMenu: this.props.groupMenu, nodeMenuClassName: this.props.nodeMenuClassName, data: _.cloneDeep(newProps.data), registerStatus: _.cloneDeep(newProps.registerStatus) }); let diffInfo = diffPropsData(result, this.canvasData, _.get(this, 'props.config.diffOptions', [])); if (diffInfo.rmNodes.length > 0) { this.canvas.removeNodes(diffInfo.rmNodes.map(item => item.id)); } if (diffInfo.addNodes.length > 0) { this.canvas.addNodes(diffInfo.addNodes); } if(diffInfo.updateNodes.length > 0) { let removeData = this.canvas.removeNodes(diffInfo.updateNodes.map(item => item.id), false, true); let _addNodes = this.canvas.addNodes(diffInfo.updateNodes, true); _addNodes.forEach(item => { item.mounted && item.mounted(); }); this.canvas.addEdges(removeData.edges.map(edge => { return edge.options; }), true); } if (diffInfo.addEdges.length > 0) { this.canvas.addEdges(diffInfo.addEdges); } if (diffInfo.rmEdges.length > 0) { this.canvas.removeEdges(diffInfo.rmEdges.map(item => item.id)); } if (diffInfo.updateStatus.length > 0) { diffInfo.updateStatus.forEach((item) => { let node = this.canvas.getNode(item.node.id); if (node) { node.updateStatusPoint(node.status); } }); } if ( _.get(this.props, 'config.autoLayout.isAlways', false) && ( diffInfo.addNodes.length > 0 || diffInfo.rmNodes.length > 0 || diffInfo.addEdges.length > 0 || diffInfo.rmEdges.length > 0 ) ) { this.canvas.redraw(); } this.canvasData = result; // 检测轮训 this._polling(newProps.polling); return true; } componentWillUnmount() { } render() { return ( <div className={this._genClassName()} > {this._createStatusNote()} {this._createActionIcon()} </div> ) } _createStatusNote() { let isShow = _.get(this, 'props.config.statusNote.enable', true); if (isShow) { let statusNote = _.get(this, 'props.config.statusNote.notes'); if (statusNote) { this._statusNote = statusNote; } let result = []; for(let key in this._statusNote) { if(typeof _.get(this._statusNote, `${key}.render`) === 'function') { result.push( <span className='status-box'> {this._statusNote[key].render()} </span> ) } else { result.push( <span className='status-box'> <span className={`status-point ${this._statusNote[key].className}`}></span> <span className="status-text">{this._statusNote[key].text}</span> </span> ); } } return ( <div className="status-container"> {result} </div> ); } } _createActionIcon() { let isShow = _.get(this, 'props.config.showActionIcon', true); if (isShow) { return ( <div className='monitor-canvas-action'> <div onClick={() => { this.canvas.zoom(this.canvas._zoomData + 0.1); }} > <i className="monitor-icon monitor-icon-zoom-in"></i> </div> <div onClick={() => { this.canvas.zoom(this.canvas._zoomData - 0.1); }} > <i className="monitor-icon monitor-icon-zoom-out"></i> </div> <div onClick={() => { this.canvas.focusCenterWithAnimate(); }}> <i className="monitor-icon monitor-icon-quanping2"></i> </div> </div> ); } return null; } _genClassName() { let classname = ''; if (this.props.className) { classname = this.props.className + ' butterfly-monitor-dag'; } else { classname = 'butterfly-monitor-dag'; } return classname; } _polling(pollingCfg = this.props.polling || {}) { if (!pollingCfg.enable) { if (this._timer) { clearInterval(this._timer); } } else { if (!this._timer) { this._timer = setInterval(() => { pollingCfg.getData(this.canvas.getDataMap()); }, pollingCfg.interval); } } } // 聚焦节点 _focusNode(nodes) { this._unfocus(); nodes.forEach((node) => { node.focus(); }); this._focusNodes = this._focusNodes.concat(nodes); } // 聚焦线段 _focusLink(edges) { this._unfocus(); edges.forEach((edge) => { edge.focus(); }); this._focusLinks = this._focusLinks.concat(edges); } // 失焦 _unfocus() { this._focusNodes.forEach((item) => { item.unfocus(); }); this._focusLinks.forEach((item) => { item.unfocus(); }); this._focusNodes = []; this._focusLinks = []; } }
the_stack
import * as React from 'react'; import { connect } from 'react-redux'; import Tour from 'reactour'; import { Localized } from '@fluent/react'; import './InteractiveTour.css'; import * as locale from 'core/locale'; import * as project from 'core/project'; import * as user from 'core/user'; import type { ReactourStep } from 'reactour'; import type { LocaleState } from 'core/locale'; import type { ProjectState } from 'core/project'; import type { UserState } from 'core/user'; import type { RootState, AppDispatch } from 'store'; type Props = { isTranslator: boolean; locale: LocaleState; project: ProjectState; user: UserState; }; type InternalProps = Props & { dispatch: AppDispatch }; type State = { isOpen: boolean; }; /** * Interactive Tour to be displayed on the "Tutorial" project * introducing the translate page of Pontoon. */ export class InteractiveTourBase extends React.Component<InternalProps, State> { constructor(props: InternalProps) { super(props); this.state = { isOpen: true, }; } createUpdateTourStatus: ( totalSteps: number, ) => null | ((currentStep: number) => void) = (totalSteps: number) => { if (!this.props.user.isAuthenticated) { return null; } return (currentStep: number) => { const step = currentStep === totalSteps - 1 ? -1 : currentStep + 1; this.props.dispatch(user.actions.updateTourStatus(step)); }; }; close: () => void = () => { this.setState({ isOpen: false }); }; render(): null | React.ReactNode { // Run the tour only on project with slug 'tutorial' if (this.props.project.slug !== 'tutorial') { return null; } const tourStatus = this.props.user.tourStatus || 0; // Run the tour only if the user hasn't completed it yet if (tourStatus === -1) { return null; } const steps: ReactourStep[] = [ { selector: '', content: ( <div> <Localized id='interactivetour-InteractiveTour--intro-title'> <h3>Hey there!</h3> </Localized> <Localized id='interactivetour-InteractiveTour--intro-content'> <p> Pontoon is a localization platform by Mozilla, used to localize Firefox and various other projects at Mozilla and other organizations. </p> </Localized> <Localized id='interactivetour-InteractiveTour--intro-footer'> <p>Follow this guide to learn how to use it.</p> </Localized> </div> ), }, { selector: '#app > header', content: ( <div> <Localized id='interactivetour-InteractiveTour--main-toolbar-title'> <h3>Main toolbar</h3> </Localized> <Localized id='interactivetour-InteractiveTour--main-toolbar-content'> <p> The main toolbar located on top of the screen shows the language, project and resource currently being localized. You can also see the progress of your current localization and additional project information. </p> </Localized> <Localized id='interactivetour-InteractiveTour--main-toolbar-footer'> <p> On the right hand side, logged in users can access notifications and settings. </p> </Localized> </div> ), style: { margin: '15px', }, }, { selector: '#app > .main-content > .panel-list', content: ( <div> <Localized id='interactivetour-InteractiveTour--string-list-title'> <h3>String List</h3> </Localized> <Localized id='interactivetour-InteractiveTour--string-list-content'> <p> The sidebar displays a list of strings in the current localization. Status of each string (e.g. Translated or Missing) is indicated by a different color of the square on the left. The square also acts as a checkbox for selecting strings to perform mass actions on. </p> </Localized> <Localized id='interactivetour-InteractiveTour--string-list-footer'> <p> On top of the list is a search box, which allows you to search source strings, translations, comments and string IDs. </p> </Localized> </div> ), style: { margin: '15px', }, }, { selector: '#app > .main-content > .panel-list', content: ( <div> <Localized id='interactivetour-InteractiveTour--filters-title'> <h3>Filters</h3> </Localized> <Localized id='interactivetour-InteractiveTour--filters-content'> <p> Strings can also be filtered by their status, translation time, translation authors and other criteria. Note that filter icons act as checkboxes, which allows you to filter by multiple criteria. </p> </Localized> </div> ), action: (node) => { node.querySelector( '.filters-panel .visibility-switch', ).click(); }, }, { selector: '#app > .main-content > .panel-content', content: ( <div> <Localized id='interactivetour-InteractiveTour--editor-title'> <h3>Editor</h3> </Localized> <Localized id='interactivetour-InteractiveTour--editor-content'> <p> Clicking a string in the list opens it in the editor. On top of it, you can see the source string with its context. Right under that is the translation input to type translation in, followed by the translation toolbar. </p> </Localized> </div> ), }, { selector: '#app > .main-content > .panel-content .editor', content: ( <div> <Localized id='interactivetour-InteractiveTour--submit-title'> <h3>Submit a Translation</h3> </Localized> {!this.props.user.isAuthenticated ? ( <Localized id='interactivetour-InteractiveTour--submit-content-unauthenticated'> <p> A user needs to be logged in to be able to submit translations. Non-authenticated users will see a link to Sign in instead of the translation toolbar with a button to save translations. </p> </Localized> ) : !this.props.isTranslator ? ( <Localized id='interactivetour-InteractiveTour--submit-content-contributor'> <p> When a translator is in Suggest Mode, or doesn’t have permission to submit translations directly, a blue SUGGEST button will appear in the translation toolbar. To make a suggestion, type it in the translation input and click SUGGEST. </p> </Localized> ) : ( <Localized id='interactivetour-InteractiveTour--submit-content-translator'> <p> If a translator has permission to add translations directly, the green SAVE button will appear in the translation toolbar. To submit a translation, type it in the translation input and click SAVE. </p> </Localized> )} </div> ), }, { selector: '#app > .main-content > .panel-content .entity-details .history', content: ( <div> <Localized id='interactivetour-InteractiveTour--history-title'> <h3>History</h3> </Localized> <Localized id='interactivetour-InteractiveTour--history-content'> <p> All suggestions and translations submitted for the current string can be found in the History Tab. Icons to the right of each entry indicate its review status (Approved, Rejected or Unreviewed). </p> </Localized> </div> ), }, { selector: '#app > .main-content > .panel-content .entity-details .third-column .top .react-tabs', content: ( <div> <Localized id='interactivetour-InteractiveTour--terms-title'> <h3>Terms</h3> </Localized> <Localized id='interactivetour-InteractiveTour--terms-content'> <p> The Terms panel contains specialized words (terms) found in the source string, along with their definitions, usage examples, part of speech and translations. By clicking on a term, its translation gets inserted into the editor. </p> </Localized> </div> ), action: (node) => { node.querySelector('#react-tabs-0').click(); }, }, { selector: '#app > .main-content > .panel-content .entity-details .third-column .top .react-tabs', content: ( <div> <Localized id='interactivetour-InteractiveTour--comments-title'> <h3>Comments</h3> </Localized> <Localized id='interactivetour-InteractiveTour--comments-content'> <p> In the Comments tab you can discuss how to translate content with your fellow team members. It’s also the place where you can request more context about or report an issue in the source string. </p> </Localized> </div> ), action: (node) => { node.querySelector('#react-tabs-2').click(); }, }, { selector: '#app > .main-content > .panel-content .entity-details .third-column .bottom .react-tabs', content: ( <div> <Localized id='interactivetour-InteractiveTour--machinery-title'> <h3>Machinery</h3> </Localized> <Localized id='interactivetour-InteractiveTour--machinery-content'> <p> The Machinery tab shows automated translation suggestions from Machine Translation, Translation Memory and Terminology services. Clicking on an entry copies it to the translation input. </p> </Localized> </div> ), action: (node) => { node.querySelector('#react-tabs-4').click(); }, }, { selector: '#app > .main-content > .panel-content .entity-details .third-column .bottom .react-tabs', content: ( <div> <Localized id='interactivetour-InteractiveTour--locales-title'> <h3>Locales</h3> </Localized> <Localized id='interactivetour-InteractiveTour--locales-content'> <p> Sometimes it’s useful to see general style choices by other localization communities. Approved translations of the current string to other languages are available in the Locales tab. </p> </Localized> </div> ), action: (node) => { node.querySelector('#react-tabs-6').click(); }, }, { selector: '', content: ( <div> <Localized id='interactivetour-InteractiveTour--end-title'> <h3>That’s (not) all, folks!</h3> </Localized> <Localized id='interactivetour-InteractiveTour--end-content' elems={{ a: ( // eslint-disable-next-line <a href='https://mozilla-l10n.github.io/localizer-documentation/' /> ), }} > <p>{`There’s a wide variety of tools to help you with translations, some of which we didn’t mention in this tutorial. For more topics of interest for localizers at Mozilla, please have a look at the <a>Localizer Documentation</a>.`}</p> </Localized> <Localized id='interactivetour-InteractiveTour--end-footer' elems={{ // eslint-disable-next-line a: <a href={`/${this.props.locale.code}/`} />, }} > <p>{`Next, feel free to explore this tutorial project or move straight to <a>translating live projects</a>.`}</p> </Localized> </div> ), }, ]; return ( <Tour accentColor={'#F36'} className={'interactive-tour'} closeWithMask={false} getCurrentStep={this.createUpdateTourStatus(steps.length)} isOpen={this.state.isOpen} onRequestClose={this.close} maskSpace={0} startAt={tourStatus} steps={steps} /> ); } } const mapStateToProps = (state: RootState): Props => { return { isTranslator: user.selectors.isTranslator(state), locale: state[locale.NAME], project: state[project.NAME], user: state[user.NAME], }; }; export default connect(mapStateToProps)(InteractiveTourBase) as any;
the_stack
import { Diagnostic, DiagnosticSeverity, Position, Range, TextDocument } from "vscode"; import { Block, BlockType, Chunk, ConsumerBlock, DynamicChunk, KafkaFileDocument, CalleeFunction, MustacheExpression, ProducerBlock, Property } from "../parser/kafkaFileParser"; import { ConsumerValidator } from "../../../validators/consumer"; import { ProducerValidator } from "../../../validators/producer"; import { CommonsValidator } from "../../../validators/commons"; import { fakerjsAPIModel, PartModelProvider } from "../model"; import { SelectedClusterProvider, TopicProvider } from "../kafkaFileLanguageService"; import { ClientState } from "../../../client"; import { BrokerConfigs } from "../../../client/config"; /** * Kafka file diagnostics support. */ export class KafkaFileDiagnostics { constructor(private selectedClusterProvider: SelectedClusterProvider, private topicProvider: TopicProvider) { } async doDiagnostics(document: TextDocument, kafkaFileDocument: KafkaFileDocument, producerFakerJSEnabled: boolean): Promise<Diagnostic[]> { const diagnostics: Diagnostic[] = []; for (const block of kafkaFileDocument.blocks) { if (block.type === BlockType.consumer) { await this.validateConsumerBlock(<ConsumerBlock>block, diagnostics); } else { await this.validateProducerBlock(<ProducerBlock>block, producerFakerJSEnabled, diagnostics); } } return diagnostics; } async validateConsumerBlock(block: ConsumerBlock, diagnostics: Diagnostic[]) { await this.validateProperties(block, false, diagnostics); } async validateProducerBlock(block: ProducerBlock, producerFakerJSEnabled: boolean, diagnostics: Diagnostic[]) { await this.validateProperties(block, producerFakerJSEnabled, diagnostics); this.validateProducerValue(block, producerFakerJSEnabled, diagnostics); } validateProducerValue(block: ProducerBlock, producerFakerJSEnabled: boolean, diagnostics: Diagnostic[]) { const value = block.value; // 1. Check if producer defines a value content const errorMessage = ProducerValidator.validateProducerValue(value?.content); if (errorMessage) { const range = new Range(block.start, new Position(block.start.line, block.start.character + 8)); diagnostics.push(new Diagnostic(range, errorMessage, DiagnosticSeverity.Error)); } // 2. Producer value can declare FakerJS expressions, validate them. if (producerFakerJSEnabled && value) { this.validateFakerJSExpressions(value, diagnostics); } } validateFakerJSExpressions(value: DynamicChunk, diagnostics: Diagnostic[]) { value.expressions.forEach(expression => { if (!expression.opened) { const range = expression.enclosedExpressionRange; diagnostics.push(new Diagnostic(range, `FakerJS expression '${expression.content}' must be opened with '{{'`, DiagnosticSeverity.Error)); return; } if (!expression.closed) { const range = expression.enclosedExpressionRange; diagnostics.push(new Diagnostic(range, `FakerJS expression '${expression.content}' must be closed with '}}'`, DiagnosticSeverity.Error)); return; } if (expression.unexpectedEdges.length > 0) { expression.unexpectedEdges.forEach(u => { const position = u.position; const range = new Range(position, new Position(position.line, position.character + 2)); diagnostics.push(new Diagnostic(range, `Unexpected token '${u.open ? '{{' : '}}'}' in expression '${expression.content}'`, DiagnosticSeverity.Error)); }); return; } // This following code follows the same behavior than FakerJS // See https://github.com/Marak/faker.js/blob/e073ace19cbf68857a5731dc3302fda0eb36cf24/lib/fake.js#L47 const token = expression.content; let method = token; //.replace('}}', '').replace('{{', ''); // extract method parameters const regExp = /\(([^)]+)\)/; const matches = regExp.exec(method); if (matches) { method = method.replace(regExp, ''); } // validate each parts of FakerJS expression (ex : {{random.words}}) const parts = method.split('.'); // We should have 2 parts (module + '.' + method) if (!this.validateFakerPartsLength(expression, parts, diagnostics)) { return; } let parentPartModel = <PartModelProvider>fakerjsAPIModel; let offset = 0; // loop for each parts (ex : random, words) and validate it for (let i = 0; i < parts.length; i++) { let part = parts[i]; if (i > 0) { // increment offset for '.' offset++; } // Check if the current part (ex : random) exists. const partModel = parentPartModel.getPart(part); if (!partModel) { // The part doesn't exists, report an error. const range = this.adjustExpressionRange(expression, offset, part.length); diagnostics.push(new Diagnostic(range, `Invalid ${i === 0 ? 'module' : 'method'}: '${part}'`, DiagnosticSeverity.Error)); return; } offset += part.length; parentPartModel = partModel; } }); } validateFakerPartsLength(expression: MustacheExpression, parts: string[], diagnostics: Diagnostic[]): boolean { if (parts.length === 2) { return true; } const content = expression.content; switch (parts.length) { case 1: { const range = expression.enclosedExpressionRange; const message = content.trim().length === 0 ? `Required expression` : `Missing '.' after '${content}'`; diagnostics.push(new Diagnostic(range, message, DiagnosticSeverity.Error)); break; } default: { const validContent = parts.slice(0, 2).join('.'); const startColumn = validContent.length + 1; const endColumn = content.length - startColumn; const invalidContent = content.substring(startColumn, content.length); const range = this.adjustExpressionRange(expression, startColumn, endColumn); diagnostics.push(new Diagnostic(range, `Invalid content: '${invalidContent}'`, DiagnosticSeverity.Error)); break; } } return false; } adjustExpressionRange(expression: MustacheExpression, startColumn: number, endColumn: number): Range { const expressionRange = expression.enclosedExpressionRange; const start = new Position(expressionRange.start.line, expressionRange.start.character + startColumn); const end = new Position(expressionRange.end.line, start.character + endColumn); return new Range(start, end); } async validateProperties(block: Block, producerFakerJSEnabled: boolean, diagnostics: Diagnostic[]) { const existingProperties = new Map<string, Property[]>(); let topicProperty: Property | undefined; for (const property of block.properties) { const propertyName = property.propertyName; this.validateProperty(property, block, producerFakerJSEnabled, diagnostics); if (propertyName === 'topic') { topicProperty = property; } if (propertyName) { let properties = existingProperties.get(propertyName); if (!properties) { properties = []; existingProperties.set(propertyName, properties); } properties.push(property); } } // Validate duplicate properties existingProperties.forEach((properties, propertyName) => { if (properties.length > 1) { properties.forEach(property => { const range = property.propertyKeyRange; diagnostics.push(new Diagnostic(range, `Duplicate property '${propertyName}'`, DiagnosticSeverity.Warning)); }); } }); if (!topicProperty) { const range = new Range(block.start, new Position(block.start.line, block.start.character + 8)); diagnostics.push(new Diagnostic(range, `The ${block.type === BlockType.consumer ? 'consumer' : 'producer'} must declare the 'topic:' property.`, DiagnosticSeverity.Error)); } else { await this.validateTopic(topicProperty, block.type, diagnostics); } } validateProperty(property: Property, block: Block, producerFakerJSEnabled: boolean, diagnostics: Diagnostic[]) { const propertyName = property.propertyName; // 1. Validate property syntax this.validateSyntaxProperty(propertyName, property, diagnostics); if (propertyName) { const definition = block.model.getDefinition(propertyName); if (!definition) { // 2. Validate unknown property this.validateUnknownProperty(propertyName, property, diagnostics); } else { // 3. Validate property value this.validatePropertyValue(property, block.type, producerFakerJSEnabled, diagnostics); } } } private validateSyntaxProperty(propertyName: string | undefined, property: Property, diagnostics: Diagnostic[]) { // 1.1. property must contains ':' assigner const assigner = property.assignerCharacter; if (!assigner) { // Error => topic const range = property.range(); diagnostics.push(new Diagnostic(range, `Missing ':' sign after '${propertyName}'`, DiagnosticSeverity.Error)); return; } // 1.2. property must declare a key if (!propertyName) { // Error => :string const range = property.range(); diagnostics.push(new Diagnostic(range, "Property must define a name before ':' sign", DiagnosticSeverity.Error)); return; } } validateUnknownProperty(propertyName: string, property: Property, diagnostics: Diagnostic[]) { const range = property.propertyKeyRange; diagnostics.push(new Diagnostic(range, `Unkwown property '${propertyName}'`, DiagnosticSeverity.Warning)); } async validatePropertyValue(property: Property, type: BlockType, producerFakerJSEnabled: boolean, diagnostics: Diagnostic[]) { const propertyName = property.propertyName; if (!propertyName) { return; } const propertyValue = property.propertyValue; const range = propertyValue ? property.propertyTrimmedValueRange : property.propertyKeyRange; if (!range) { return; } const errorMessage = await this.validateValue(propertyName, type, property.value); if (errorMessage) { diagnostics.push(new Diagnostic(range, errorMessage, DiagnosticSeverity.Error)); } if (producerFakerJSEnabled) { const nodeValue = <DynamicChunk>property.value; if (nodeValue && nodeValue.expressions) { // Property like 'key' can declare Faker expressions, validate them. this.validateFakerJSExpressions(nodeValue, diagnostics); } } } private async validateValue(propertyName: string, type: BlockType, propertyValue?: Chunk): Promise<string | undefined> { switch (propertyName) { case 'topic': return CommonsValidator.validateTopic(propertyValue?.content.trim()); case 'key-format': const keyFormat = (<CalleeFunction>propertyValue).functionName; return type === BlockType.consumer ? ConsumerValidator.validateKeyFormat(keyFormat) : ProducerValidator.validateKeyFormat(keyFormat); case 'value-format': const valueFormat = (<CalleeFunction>propertyValue).functionName; return type === BlockType.consumer ? ConsumerValidator.validateValueFormat(valueFormat) : ProducerValidator.validateValueFormat(valueFormat); case 'from': return ConsumerValidator.validateOffset(propertyValue?.content.trim()); case 'partitions': { return ConsumerValidator.validatePartitions(propertyValue?.content.trim()); } } } async validateTopic(topicProperty: Property | undefined, blockType: BlockType, diagnostics: Diagnostic[]) { if (!topicProperty) { return; } const topicId = topicProperty.value?.content.trim(); if (!topicId || topicId.length < 1) { return; } const { clusterId, clusterState } = this.selectedClusterProvider.getSelectedCluster(); if (clusterId) { switch (clusterState) { case ClientState.connected: { // The topic validation is done, only when the cluster is connected if (!await this.topicProvider.getTopic(clusterId, topicId)) { // The topic doesn't exist, report an error const range = topicProperty.propertyTrimmedValueRange || topicProperty.range(); const autoCreate = await this.topicProvider.getAutoCreateTopicEnabled(clusterId); const errorMessage = getTopicErrorMessage(topicId, autoCreate, blockType); const severity = getTopicErrorSeverity(autoCreate); diagnostics.push(new Diagnostic(range, errorMessage, severity)); } break; } case ClientState.disconnected: { // the cluster is disconnected, try to connect to the cluster, by trying retrieving the topic in async. // if kafka client can be connected, it will process the validation again. this.topicProvider.getTopic(clusterId, topicId); break; } } } } } function getTopicErrorMessage(topicId: string, autoCreate: BrokerConfigs.AutoCreateTopicResult, blockType: BlockType): string { switch (autoCreate.type) { case "enabled": return `Unknown topic '${topicId}'. Topic will be created automatically.`; case "disabled": return `Unknown topic '${topicId}'. Cluster does not support automatic topic creation.`; default: return `Unknown topic '${topicId}'. Cluster might not support automatic topic creation.`; } } function getTopicErrorSeverity(autoCreate: BrokerConfigs.AutoCreateTopicResult): DiagnosticSeverity { switch (autoCreate.type) { case "enabled": return DiagnosticSeverity.Information; case "disabled": return DiagnosticSeverity.Error; default: return DiagnosticSeverity.Warning; } }
the_stack
import { VoiceOpcodes } from 'discord-api-types/voice/v4'; import { VoiceUDPSocket } from './VoiceUDPSocket'; import { VoiceWebSocket } from './VoiceWebSocket'; import * as secretbox from '../util/Secretbox'; import { Awaited, noop } from '../util/util'; import type { CloseEvent } from 'ws'; import { TypedEmitter } from 'tiny-typed-emitter'; // The number of audio channels required by Discord const CHANNELS = 2; const TIMESTAMP_INC = (48000 / 100) * CHANNELS; const MAX_NONCE_SIZE = 2 ** 32 - 1; export const SUPPORTED_ENCRYPTION_MODES = ['xsalsa20_poly1305_lite', 'xsalsa20_poly1305_suffix', 'xsalsa20_poly1305']; /** * The different statuses that a networking instance can hold. The order * of the states between OpeningWs and Ready is chronological (first the * instance enters OpeningWs, then it enters Identifying etc.) */ export enum NetworkingStatusCode { OpeningWs, Identifying, UdpHandshaking, SelectingProtocol, Ready, Resuming, Closed, } /** * The initial Networking state. Instances will be in this state when a WebSocket connection to a Discord * voice gateway is being opened. */ export interface NetworkingOpeningWsState { code: NetworkingStatusCode.OpeningWs; ws: VoiceWebSocket; connectionOptions: ConnectionOptions; } /** * The state that a Networking instance will be in when it is attempting to authorize itself. */ export interface NetworkingIdentifyingState { code: NetworkingStatusCode.Identifying; ws: VoiceWebSocket; connectionOptions: ConnectionOptions; } /** * The state that a Networking instance will be in when opening a UDP connection to the IP and port provided * by Discord, as well as performing IP discovery. */ export interface NetworkingUdpHandshakingState { code: NetworkingStatusCode.UdpHandshaking; ws: VoiceWebSocket; udp: VoiceUDPSocket; connectionOptions: ConnectionOptions; connectionData: Pick<ConnectionData, 'ssrc'>; } /** * The state that a Networking instance will be in when selecting an encryption protocol for audio packets. */ export interface NetworkingSelectingProtocolState { code: NetworkingStatusCode.SelectingProtocol; ws: VoiceWebSocket; udp: VoiceUDPSocket; connectionOptions: ConnectionOptions; connectionData: Pick<ConnectionData, 'ssrc'>; } /** * The state that a Networking instance will be in when it has a fully established connection to a Discord * voice server. */ export interface NetworkingReadyState { code: NetworkingStatusCode.Ready; ws: VoiceWebSocket; udp: VoiceUDPSocket; connectionOptions: ConnectionOptions; connectionData: ConnectionData; preparedPacket?: Buffer; } /** * The state that a Networking instance will be in when its connection has been dropped unexpectedly, and it * is attempting to resume an existing session. */ export interface NetworkingResumingState { code: NetworkingStatusCode.Resuming; ws: VoiceWebSocket; udp: VoiceUDPSocket; connectionOptions: ConnectionOptions; connectionData: ConnectionData; preparedPacket?: Buffer; } /** * The state that a Networking instance will be in when it has been destroyed. It cannot be recovered from this * state. */ export interface NetworkingClosedState { code: NetworkingStatusCode.Closed; } /** * The various states that a networking instance can be in. */ export type NetworkingState = | NetworkingOpeningWsState | NetworkingIdentifyingState | NetworkingUdpHandshakingState | NetworkingSelectingProtocolState | NetworkingReadyState | NetworkingResumingState | NetworkingClosedState; /** * Details required to connect to the Discord voice gateway. These details * are first received on the main bot gateway, in the form of VOICE_SERVER_UPDATE * and VOICE_STATE_UPDATE packets. */ interface ConnectionOptions { serverId: string; userId: string; sessionId: string; token: string; endpoint: string; } /** * Information about the current connection, e.g. which encryption mode is to be used on * the connection, timing information for playback of streams. */ export interface ConnectionData { ssrc: number; encryptionMode: string; secretKey: Uint8Array; sequence: number; timestamp: number; packetsPlayed: number; nonce: number; nonceBuffer: Buffer; speaking: boolean; } /** * An empty buffer that is reused in packet encryption by many different networking instances. */ const nonce = Buffer.alloc(24); export interface NetworkingEvents { debug: (message: string) => Awaited<void>; error: (error: Error) => Awaited<void>; stateChange: (oldState: NetworkingState, newState: NetworkingState) => Awaited<void>; close: (code: number) => Awaited<void>; } /** * Manages the networking required to maintain a voice connection and dispatch audio packets */ export class Networking extends TypedEmitter<NetworkingEvents> { private _state: NetworkingState; /** * The debug logger function, if debugging is enabled. */ private readonly debug: null | ((message: string) => void); /** * Creates a new Networking instance. */ public constructor(options: ConnectionOptions, debug: boolean) { super(); this.onWsOpen = this.onWsOpen.bind(this); this.onChildError = this.onChildError.bind(this); this.onWsPacket = this.onWsPacket.bind(this); this.onWsClose = this.onWsClose.bind(this); this.onWsDebug = this.onWsDebug.bind(this); this.onUdpDebug = this.onUdpDebug.bind(this); this.onUdpClose = this.onUdpClose.bind(this); this.debug = debug ? (message: string) => this.emit('debug', message) : null; this._state = { code: NetworkingStatusCode.OpeningWs, ws: this.createWebSocket(options.endpoint), connectionOptions: options, }; } /** * Destroys the Networking instance, transitioning it into the Closed state. */ public destroy() { this.state = { code: NetworkingStatusCode.Closed, }; } /** * The current state of the networking instance. */ public get state(): NetworkingState { return this._state; } /** * Sets a new state for the networking instance, performing clean-up operations where necessary. */ public set state(newState: NetworkingState) { const oldWs = Reflect.get(this._state, 'ws') as VoiceWebSocket | undefined; const newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined; if (oldWs && oldWs !== newWs) { // The old WebSocket is being freed - remove all handlers from it oldWs.off('debug', this.onWsDebug); oldWs.on('error', noop); oldWs.off('error', this.onChildError); oldWs.off('open', this.onWsOpen); oldWs.off('packet', this.onWsPacket); oldWs.off('close', this.onWsClose); oldWs.destroy(); } const oldUdp = Reflect.get(this._state, 'udp') as VoiceUDPSocket | undefined; const newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined; if (oldUdp && oldUdp !== newUdp) { oldUdp.on('error', noop); oldUdp.off('error', this.onChildError); oldUdp.off('close', this.onUdpClose); oldUdp.off('debug', this.onUdpDebug); oldUdp.destroy(); } const oldState = this._state; this._state = newState; this.emit('stateChange', oldState, newState); /** * Debug event for Networking. * * @event Networking#debug * @type {string} */ this.debug?.(`state change:\nfrom ${stringifyState(oldState)}\nto ${stringifyState(newState)}`); } /** * Creates a new WebSocket to a Discord Voice gateway. * * @param endpoint - The endpoint to connect to * @param debug - Whether to enable debug logging */ private createWebSocket(endpoint: string) { const ws = new VoiceWebSocket(`wss://${endpoint}?v=4`, Boolean(this.debug)); ws.on('error', this.onChildError); ws.once('open', this.onWsOpen); ws.on('packet', this.onWsPacket); ws.once('close', this.onWsClose); ws.on('debug', this.onWsDebug); return ws; } /** * Propagates errors from the children VoiceWebSocket and VoiceUDPSocket. * * @param error - The error that was emitted by a child */ private onChildError(error: Error) { this.emit('error', error); } /** * Called when the WebSocket opens. Depending on the state that the instance is in, * it will either identify with a new session, or it will attempt to resume an existing session. */ private onWsOpen() { if (this.state.code === NetworkingStatusCode.OpeningWs) { const packet = { op: VoiceOpcodes.Identify, d: { server_id: this.state.connectionOptions.serverId, user_id: this.state.connectionOptions.userId, session_id: this.state.connectionOptions.sessionId, token: this.state.connectionOptions.token, }, }; this.state.ws.sendPacket(packet); this.state = { ...this.state, code: NetworkingStatusCode.Identifying, }; } else if (this.state.code === NetworkingStatusCode.Resuming) { const packet = { op: VoiceOpcodes.Resume, d: { server_id: this.state.connectionOptions.serverId, session_id: this.state.connectionOptions.sessionId, token: this.state.connectionOptions.token, }, }; this.state.ws.sendPacket(packet); } } /** * Called when the WebSocket closes. Based on the reason for closing (given by the code parameter), * the instance will either attempt to resume, or enter the closed state and emit a 'close' event * with the close code, allowing the user to decide whether or not they would like to reconnect. * * @param code - The close code */ private onWsClose({ code }: CloseEvent) { const canResume = code === 4015 || code < 4000; if (canResume && this.state.code === NetworkingStatusCode.Ready) { this.state = { ...this.state, code: NetworkingStatusCode.Resuming, ws: this.createWebSocket(this.state.connectionOptions.endpoint), }; } else if (this.state.code !== NetworkingStatusCode.Closed) { this.destroy(); this.emit('close', code); } } /** * Called when the UDP socket has closed itself if it has stopped receiving replies from Discord. */ private onUdpClose() { if (this.state.code === NetworkingStatusCode.Ready) { this.state = { ...this.state, code: NetworkingStatusCode.Resuming, ws: this.createWebSocket(this.state.connectionOptions.endpoint), }; } } /** * Called when a packet is received on the connection's WebSocket. * * @param packet - The received packet */ private onWsPacket(packet: any) { if (packet.op === VoiceOpcodes.Hello && this.state.code !== NetworkingStatusCode.Closed) { // eslint-disable-next-line @typescript-eslint/no-unsafe-argument this.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval); } else if (packet.op === VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) { const { ip, port, ssrc, modes } = packet.d; const udp = new VoiceUDPSocket({ ip, port }); udp.on('error', this.onChildError); udp.on('debug', this.onUdpDebug); udp.once('close', this.onUdpClose); udp // eslint-disable-next-line @typescript-eslint/no-unsafe-argument .performIPDiscovery(ssrc) .then((localConfig) => { if (this.state.code !== NetworkingStatusCode.UdpHandshaking) return; this.state.ws.sendPacket({ op: VoiceOpcodes.SelectProtocol, d: { protocol: 'udp', data: { address: localConfig.ip, port: localConfig.port, // eslint-disable-next-line @typescript-eslint/no-unsafe-argument mode: chooseEncryptionMode(modes), }, }, }); this.state = { ...this.state, code: NetworkingStatusCode.SelectingProtocol, }; }) .catch((error: Error) => this.emit('error', error)); this.state = { ...this.state, code: NetworkingStatusCode.UdpHandshaking, udp, connectionData: { ssrc, }, }; } else if ( packet.op === VoiceOpcodes.SessionDescription && this.state.code === NetworkingStatusCode.SelectingProtocol ) { const { mode: encryptionMode, secret_key: secretKey } = packet.d; this.state = { ...this.state, code: NetworkingStatusCode.Ready, connectionData: { ...this.state.connectionData, encryptionMode, // eslint-disable-next-line @typescript-eslint/no-unsafe-argument secretKey: new Uint8Array(secretKey), sequence: randomNBit(16), timestamp: randomNBit(32), nonce: 0, nonceBuffer: Buffer.alloc(24), speaking: false, packetsPlayed: 0, }, }; } else if (packet.op === VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) { this.state = { ...this.state, code: NetworkingStatusCode.Ready, }; this.state.connectionData.speaking = false; } } /** * Propagates debug messages from the child WebSocket. * * @param message - The emitted debug message */ private onWsDebug(message: string) { this.debug?.(`[WS] ${message}`); } /** * Propagates debug messages from the child UDPSocket. * * @param message - The emitted debug message */ private onUdpDebug(message: string) { this.debug?.(`[UDP] ${message}`); } /** * Prepares an Opus packet for playback. This includes attaching metadata to it and encrypting it. * It will be stored within the instance, and can be played by dispatchAudio() * * @remarks * Calling this method while there is already a prepared audio packet that has not yet been dispatched * will overwrite the existing audio packet. This should be avoided. * * @param opusPacket - The Opus packet to encrypt * * @returns The audio packet that was prepared */ public prepareAudioPacket(opusPacket: Buffer) { const state = this.state; if (state.code !== NetworkingStatusCode.Ready) return; state.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData); return state.preparedPacket; } /** * Dispatches the audio packet previously prepared by prepareAudioPacket(opusPacket). The audio packet * is consumed and cannot be dispatched again. */ public dispatchAudio() { const state = this.state; if (state.code !== NetworkingStatusCode.Ready) return false; if (typeof state.preparedPacket !== 'undefined') { this.playAudioPacket(state.preparedPacket); state.preparedPacket = undefined; return true; } return false; } /** * Plays an audio packet, updating timing metadata used for playback. * * @param audioPacket - The audio packet to play */ private playAudioPacket(audioPacket: Buffer) { const state = this.state; if (state.code !== NetworkingStatusCode.Ready) return; const { connectionData } = state; connectionData.packetsPlayed++; connectionData.sequence++; connectionData.timestamp += TIMESTAMP_INC; if (connectionData.sequence >= 2 ** 16) connectionData.sequence = 0; if (connectionData.timestamp >= 2 ** 32) connectionData.timestamp = 0; this.setSpeaking(true); state.udp.send(audioPacket); } /** * Sends a packet to the voice gateway indicating that the client has start/stopped sending * audio. * * @param speaking - Whether or not the client should be shown as speaking */ public setSpeaking(speaking: boolean) { const state = this.state; if (state.code !== NetworkingStatusCode.Ready) return; if (state.connectionData.speaking === speaking) return; state.connectionData.speaking = speaking; state.ws.sendPacket({ op: VoiceOpcodes.Speaking, d: { speaking: speaking ? 1 : 0, delay: 0, ssrc: state.connectionData.ssrc, }, }); } /** * Creates a new audio packet from an Opus packet. This involves encrypting the packet, * then prepending a header that includes metadata. * * @param opusPacket - The Opus packet to prepare * @param connectionData - The current connection data of the instance */ private createAudioPacket(opusPacket: Buffer, connectionData: ConnectionData) { const packetBuffer = Buffer.alloc(12); packetBuffer[0] = 0x80; packetBuffer[1] = 0x78; const { sequence, timestamp, ssrc } = connectionData; packetBuffer.writeUIntBE(sequence, 2, 2); packetBuffer.writeUIntBE(timestamp, 4, 4); packetBuffer.writeUIntBE(ssrc, 8, 4); packetBuffer.copy(nonce, 0, 0, 12); return Buffer.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]); } /** * Encrypts an Opus packet using the format agreed upon by the instance and Discord. * * @param opusPacket - The Opus packet to encrypt * @param connectionData - The current connection data of the instance */ private encryptOpusPacket(opusPacket: Buffer, connectionData: ConnectionData) { const { secretKey, encryptionMode } = connectionData; if (encryptionMode === 'xsalsa20_poly1305_lite') { connectionData.nonce++; if (connectionData.nonce > MAX_NONCE_SIZE) connectionData.nonce = 0; connectionData.nonceBuffer.writeUInt32BE(connectionData.nonce, 0); return [ secretbox.methods.close(opusPacket, connectionData.nonceBuffer, secretKey), connectionData.nonceBuffer.slice(0, 4), ]; } else if (encryptionMode === 'xsalsa20_poly1305_suffix') { const random = secretbox.methods.random(24, connectionData.nonceBuffer); return [secretbox.methods.close(opusPacket, random, secretKey), random]; } return [secretbox.methods.close(opusPacket, nonce, secretKey)]; } } /** * Returns a random number that is in the range of n bits. * * @param n - The number of bits */ function randomNBit(n: number) { return Math.floor(Math.random() * 2 ** n); } /** * Stringifies a NetworkingState. * * @param state - The state to stringify */ function stringifyState(state: NetworkingState) { return JSON.stringify({ ...state, ws: Reflect.has(state, 'ws'), udp: Reflect.has(state, 'udp'), }); } /** * Chooses an encryption mode from a list of given options. Chooses the most preferred option. * * @param options - The available encryption options */ function chooseEncryptionMode(options: string[]): string { const option = options.find((option) => SUPPORTED_ENCRYPTION_MODES.includes(option)); if (!option) { throw new Error(`No compatible encryption modes. Available include: ${options.join(', ')}`); } return option; }
the_stack
import * as cspell from 'cspell-lib'; import { getDefaultSettings, Pattern } from 'cspell-lib'; import * as os from 'os'; import * as Path from 'path'; import { Connection, WorkspaceFolder } from 'vscode-languageserver/node'; import { URI as Uri } from 'vscode-uri'; import { CSpellUserSettings } from '../config/cspellConfig'; import { escapeRegExp } from 'common-utils/util.js'; import { correctBadSettings, debugExports, DocumentSettings, ExcludedByMatch, isLanguageEnabled, isUriAllowed, isUriBlocked, __testing__, } from './documentSettings'; import { getConfiguration, getWorkspaceFolders } from './vscode.config'; jest.mock('vscode-languageserver/node'); jest.mock('./vscode.config'); const mockGetWorkspaceFolders = jest.mocked(getWorkspaceFolders); const mockGetConfiguration = jest.mocked(getConfiguration); const pathWorkspaceServer = Path.resolve(Path.join(__dirname, '..', '..')); const pathWorkspaceRoot = Path.resolve(Path.join(pathWorkspaceServer, '..', '..')); const pathWorkspaceClient = Path.resolve(Path.join(pathWorkspaceServer, '..', 'client')); const pathSampleSourceFiles = Path.join(pathWorkspaceServer, 'sampleSourceFiles'); const workspaceFolderServer: WorkspaceFolder = { uri: Uri.file(pathWorkspaceServer).toString(), name: '_server', }; const workspaceFolderRoot: WorkspaceFolder = { uri: Uri.file(pathWorkspaceRoot).toString(), name: 'vscode-spell-checker', }; const workspaceFolderClient: WorkspaceFolder = { uri: Uri.file(pathWorkspaceClient).toString(), name: 'client', }; const cspellConfigInVsCode: CSpellUserSettings = { name: 'Mock VS Code Config', ignorePaths: ['${workspaceFolder:_server}/**/*.json'], import: [ '${workspaceFolder:_server}/sampleSourceFiles/overrides/cspell.json', '${workspaceFolder:_server}/sampleSourceFiles/cSpell.json', ], enabledLanguageIds: ['typescript', 'javascript', 'php', 'json', 'jsonc'], }; const sampleFiles = { sampleClientEsLint: Path.resolve(pathWorkspaceRoot, 'packages/client/.eslintrc.js'), sampleClientReadme: Path.resolve(pathWorkspaceRoot, 'packages/client/README.md'), sampleNodePackage: require.resolve('cspell-lib'), sampleSamplesReadme: Path.resolve(pathWorkspaceRoot, 'samples/custom-dictionary/README.md'), sampleServerCSpell: Path.resolve(pathWorkspaceRoot, 'packages/_server/cspell.json'), sampleServerPackageLock: Path.resolve(pathWorkspaceRoot, 'packages/_server/package-lock.json'), }; const configFiles = { rootConfig: Path.resolve(pathWorkspaceRoot, 'cSpell.json'), clientConfig: Path.resolve(pathWorkspaceClient, 'cspell.json'), serverConfig: Path.resolve(pathWorkspaceServer, 'cspell.json'), rootConfigVSCode: Path.resolve(pathWorkspaceRoot, '.vscode/cSpell.json'), clientConfigVSCode: Path.resolve(pathWorkspaceClient, '.vscode/cspell.json'), serverConfigVSCode: Path.resolve(pathWorkspaceServer, '.vscode/cspell.json'), }; const ac = expect.arrayContaining; describe('Validate DocumentSettings', () => { beforeEach(() => { // Clear all mock instances and calls to constructor and all methods: mockGetWorkspaceFolders.mockClear(); }); test('version', () => { const docSettings = newDocumentSettings(); expect(docSettings.version).toEqual(0); docSettings.resetSettings(); expect(docSettings.version).toEqual(1); }); test('checks isUriAllowed', () => { expect(isUriAllowed(Uri.file(__filename).toString())).toBe(true); }); test('checks isUriBlocked', () => { const uriFile = Uri.file(__filename); expect(isUriBlocked(uriFile.toString())).toBe(false); const uriGit = uriFile.with({ scheme: 'debug' }); expect(isUriBlocked(uriGit.toString())).toBe(true); }); test('folders', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); const docSettings = newDocumentSettings(); const folders = await docSettings.folders; expect(folders).toBe(mockFolders); }); test('tests register config path', () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); const docSettings = newDocumentSettings(); const configFile = Path.join(pathSampleSourceFiles, 'cSpell.json'); expect(docSettings.version).toEqual(0); docSettings.registerConfigurationFile(configFile); expect(docSettings.version).toEqual(1); expect(docSettings.configsToImport).toContain(configFile); }); test('test getSettings', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([cspellConfigInVsCode, {}])); const docSettings = newDocumentSettings(); const configFile = Path.join(pathSampleSourceFiles, 'cspell-ext.json'); docSettings.registerConfigurationFile(configFile); const settings = await docSettings.getSettings({ uri: Uri.file(__filename).toString() }); expect(settings).toHaveProperty('name'); expect(settings.enabled).toBeUndefined(); expect(settings.language).toBe('en-gb'); }); test('test getSettings workspaceRootPath', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue( Promise.resolve([{ ...cspellConfigInVsCode, workspaceRootPath: '${workspaceFolder:client}' }, {}]) ); const docSettings = newDocumentSettings(); const configFile = Path.join(pathSampleSourceFiles, 'cspell-ext.json'); docSettings.registerConfigurationFile(configFile); const settings = await docSettings.getSettings({ uri: Uri.file(__filename).toString() }); expect(settings.workspaceRootPath?.toLowerCase()).toBe(pathWorkspaceClient.toLowerCase()); }); test('test isExcluded', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([{}, {}])); const docSettings = newDocumentSettings(); const configFile = Path.join(pathSampleSourceFiles, 'cSpell.json'); docSettings.registerConfigurationFile(configFile); const result = await docSettings.isExcluded(Uri.file(__filename).toString()); expect(result).toBe(false); }); test('test enableFiletypes', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue( Promise.resolve([{ ...cspellConfigInVsCode, enableFiletypes: ['!typescript', '!javascript', 'pug'] }, {}]) ); const docSettings = newDocumentSettings(); const configFile = Path.join(pathSampleSourceFiles, 'cSpell.json'); docSettings.registerConfigurationFile(configFile); const settings = await docSettings.getSettings({ uri: Uri.file(__filename).toString() }); expect(settings.enabledLanguageIds).not.toContain('typescript'); expect(settings.enabledLanguageIds).toEqual(expect.arrayContaining(['php', 'json', 'pug'])); }); test('applyEnableFiletypes', () => { const settings: CSpellUserSettings = { enabledLanguageIds: ['typescript', 'markdown', 'plaintext', 'json'], enableFiletypes: ['!json', '!!!javascript'], }; const enabled = __testing__.extractEnableFiletypes(settings, { enableFiletypes: ['typescript', '!plaintext', 'FreeFormFortran', '!!json', '!!javascript'], }); const r = __testing__.applyEnableFiletypes(enabled, settings); // cspell:ignore freeformfortran expect(r.enabledLanguageIds).toEqual(ac(['typescript', 'markdown', 'FreeFormFortran', 'json'])); }); test.each` languageId | settings | expected ${'typescript'} | ${{}} | ${false} ${'typescript'} | ${{ enableFiletypes: ['typescript'] }} | ${true} ${'typescript'} | ${{ enableFiletypes: ['!!!typescript'], enabledLanguageIds: ['typescript'] }} | ${false} ${'javascript'} | ${{ enableFiletypes: ['typescript'], checkOnlyEnabledFileTypes: false }} | ${true} ${'javascript'} | ${{ enableFiletypes: ['typescript'], checkOnlyEnabledFileTypes: true }} | ${false} ${'javascript'} | ${{ enableFiletypes: ['!javascript'], checkOnlyEnabledFileTypes: false }} | ${false} ${'typescript'} | ${{ enableFiletypes: ['*'] }} | ${true} ${'typescript'} | ${{ enableFiletypes: ['*'], checkOnlyEnabledFileTypes: true }} | ${true} ${'typescript'} | ${{ enableFiletypes: ['*'], checkOnlyEnabledFileTypes: false }} | ${true} ${'typescript'} | ${{ enableFiletypes: ['!*'], checkOnlyEnabledFileTypes: true }} | ${false} ${'typescript'} | ${{ enableFiletypes: ['!*'], checkOnlyEnabledFileTypes: false }} | ${true} ${'java'} | ${{ enableFiletypes: ['!*', 'java'], checkOnlyEnabledFileTypes: true }} | ${true} `('isLanguageEnabled $languageId $settings', ({ languageId, settings, expected }) => { expect(isLanguageEnabled(languageId, settings)).toBe(expected); }); test('isExcludedBy', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([{}, {}])); const docSettings = newDocumentSettings(); const configFile = Path.join(pathSampleSourceFiles, 'cSpell.json'); docSettings.registerConfigurationFile(configFile); const result = await docSettings.calcExcludedBy(Uri.file(__filename).toString()); expect(result).toHaveLength(0); }); test('test extractTargetDictionaries', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([cspellConfigInVsCode, {}])); const docSettings = newDocumentSettings(); const settings = await docSettings.getSettings({ uri: Uri.file(__filename).toString() }); const d = docSettings.extractTargetDictionaries(settings); expect(d).toEqual([ expect.objectContaining({ addWords: true, name: 'cspell-words', }), ]); }); test('test extractCSpellConfigurationFiles', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([cspellConfigInVsCode, {}])); const docSettings = newDocumentSettings(); const settings = await docSettings.getSettings({ uri: Uri.file(__filename).toString() }); const files = docSettings.extractCSpellConfigurationFiles(settings); expect(files.map((f) => f.toString())).toEqual( expect.arrayContaining([Uri.file(Path.join(pathWorkspaceServer, 'cspell.json')).toString()]) ); }); test('test extractCSpellFileConfigurations', async () => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([cspellConfigInVsCode, {}])); const docSettings = newDocumentSettings(); const settings = await docSettings.getSettings({ uri: Uri.file(__filename).toString() }); const configs = docSettings.extractCSpellFileConfigurations(settings); expect(configs.map((c) => c.name)).toEqual([ shortPathName(Path.join(pathWorkspaceServer, 'cspell.json')), shortPathName(Path.join(pathWorkspaceRoot, 'cSpell.json')), 'sampleSourceFiles/cSpell.json', 'sampleSourceFiles/cspell-ext.json', 'overrides/cspell.json', ]); }); interface IsExcludeByTest { filename: string; expected: ExcludedByMatch[]; } const pathCspellExcludeTests = Path.resolve('sampleSourceFiles/cspell-exclude-tests.json'); function oc<T>(t: T): T { return expect.objectContaining(t); } function ocGlob(glob: string, root: string = pathWorkspaceServer, source?: string) { return source ? oc({ glob, root, source }) : oc({ glob, root }); } function matchString(s: string) { return expect.stringMatching(new RegExp(`^${escapeRegExp(s)}$`, 'i')); } function ex(cfgFile: string, glob: string, root?: string) { cfgFile = Path.resolve(pathWorkspaceRoot, cfgFile); root = root || Path.dirname(cfgFile); const filename = matchString(cfgFile); return { glob: ocGlob(glob, matchString(root), filename), settings: oc({ source: oc({ filename }) }), }; } test.each` filename | expected ${sampleFiles.sampleClientEsLint} | ${[ex(pathCspellExcludeTests, '.eslintrc.js', pathWorkspaceRoot)]} ${sampleFiles.sampleSamplesReadme} | ${[ex(pathCspellExcludeTests, 'samples', pathWorkspaceRoot)]} ${sampleFiles.sampleClientEsLint} | ${[ex(pathCspellExcludeTests, '.eslintrc.js', pathWorkspaceRoot)]} ${sampleFiles.sampleClientReadme} | ${[]} ${sampleFiles.sampleServerCSpell} | ${[]} ${sampleFiles.sampleServerPackageLock} | ${[ex(pathCspellExcludeTests, 'package-lock.json', pathWorkspaceRoot), ex('cSpell.json', 'package-lock.json', pathWorkspaceRoot)]} `('isExcludedBy $filename', async ({ filename, expected }: IsExcludeByTest) => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([{}, {}])); const docSettings = newDocumentSettings(); const configFile = Path.join(pathSampleSourceFiles, 'cspell-exclude-tests.json'); docSettings.registerConfigurationFile(configFile); const uri = Uri.file(Path.resolve(pathWorkspaceRoot, filename)).toString(); const result = await docSettings.calcExcludedBy(uri); expect(result).toEqual(expected); }); test.each` filename | expected ${sampleFiles.sampleNodePackage} | ${true} ${Path.join(__dirname, 'temp/my_file.js')} | ${true} ${sampleFiles.sampleClientEsLint} | ${false} ${sampleFiles.sampleServerPackageLock} | ${false} `('isGitIgnored $filename', async ({ filename, expected }: IsExcludeByTest) => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([{}, {}])); const docSettings = newDocumentSettings(); docSettings.registerConfigurationFile(Path.join(pathWorkspaceRoot, 'cSpell.json')); const uri = Uri.file(Path.resolve(pathWorkspaceRoot, filename)); const result = await docSettings.isGitIgnored(uri); expect(result).toEqual(expected); }); function uf(f: string | Uri): Uri; function uf(f: (string | Uri)[]): Uri[]; function uf(f: (string | Uri)[] | (string | Uri)): Uri | Uri[] { if (Array.isArray(f)) { return f.map((u) => uf(u)); } return typeof f === 'string' ? Uri.file(f) : f; } function uft(f: string | Uri): string; function uft(f: (string | Uri)[]): string[]; function uft(f: (string | Uri)[] | (string | Uri)): string | string[] { if (Array.isArray(f)) { return uf(f).map((u) => u.toString()); } return uf(f).toString(); } type UriString = string; interface FilterConfigFilesToMatchInheritedPathOfFileTest { filename: UriString; configs: UriString[]; expected: UriString[]; } const samplesCustomDictionaryCspell = Path.resolve(pathWorkspaceRoot, 'samples/custom-dictionary/cspell.json'); test.each` filename | configs | expected ${uft(sampleFiles.sampleClientEsLint)} | ${uft([configFiles.clientConfig, configFiles.rootConfig])} | ${uft([configFiles.clientConfig, configFiles.rootConfig])} ${uft(sampleFiles.sampleNodePackage)} | ${uft([configFiles.clientConfig, configFiles.rootConfig])} | ${uft([configFiles.rootConfig])} ${uft(sampleFiles.sampleSamplesReadme)} | ${uft([samplesCustomDictionaryCspell])} | ${uft([samplesCustomDictionaryCspell])} ${uft(sampleFiles.sampleClientReadme)} | ${uft([configFiles.clientConfigVSCode, configFiles.rootConfig])} | ${uft([configFiles.clientConfigVSCode, configFiles.rootConfig])} ${uft(configFiles.clientConfigVSCode)} | ${uft([configFiles.clientConfigVSCode, configFiles.rootConfig])} | ${uft([configFiles.clientConfigVSCode, configFiles.rootConfig])} ${uft(sampleFiles.sampleServerPackageLock)} | ${uft([configFiles.serverConfigVSCode, configFiles.rootConfig])} | ${uft([configFiles.serverConfigVSCode, configFiles.rootConfig])} ${uft(sampleFiles.sampleServerPackageLock)} | ${uft([configFiles.rootConfigVSCode, configFiles.clientConfig])} | ${uft([configFiles.rootConfigVSCode])} `( 'filterConfigFilesToMatchInheritedPathOfFile against $filename $configs', async ({ filename, configs, expected }: FilterConfigFilesToMatchInheritedPathOfFileTest) => { const mockFolders: WorkspaceFolder[] = []; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([{}, {}])); const configUris = configs.map((u) => Uri.parse(u)); const result = debugExports.filterConfigFilesToMatchInheritedPathOfFile(configUris, Uri.parse(filename)); expect(result.map((f) => f.toString().toLowerCase())).toEqual(expected.map((u) => u.toLowerCase())); } ); interface FindCSpellConfigurationFilesForUriTest { filename: string; expected: (string | Uri)[]; } test.each` filename | expected ${sampleFiles.sampleClientEsLint} | ${[configFiles.clientConfig, configFiles.rootConfig]} ${sampleFiles.sampleNodePackage} | ${[configFiles.rootConfig]} ${sampleFiles.sampleSamplesReadme} | ${[Path.resolve(pathWorkspaceRoot, 'samples/custom-dictionary/cspell.json')]} ${sampleFiles.sampleClientReadme} | ${[configFiles.clientConfig, configFiles.rootConfig]} ${sampleFiles.sampleServerPackageLock} | ${[configFiles.serverConfig, configFiles.rootConfig]} `('findCSpellConfigurationFilesForUri $filename', async ({ filename, expected }: FindCSpellConfigurationFilesForUriTest) => { const mockFolders: WorkspaceFolder[] = [workspaceFolderRoot, workspaceFolderClient, workspaceFolderServer]; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([{}, {}])); const docSettings = newDocumentSettings(getDefaultSettings()); const uri = Uri.file(Path.resolve(pathWorkspaceRoot, filename)).toString(); const result = await docSettings.findCSpellConfigurationFilesForUri(uri); // Note: toLowerCase is needed because on MacOS and Windows cSpell.json and cspell.json will be considered the same file. expect(result.map((f) => f.toString().toLowerCase())).toEqual(expected.map((u) => filePathToUri(u).toString().toLowerCase())); }); test.each` filename | expected ${sampleFiles.sampleClientEsLint} | ${[configFiles.clientConfig, configFiles.rootConfig]} ${sampleFiles.sampleNodePackage} | ${[configFiles.rootConfig]} ${sampleFiles.sampleSamplesReadme} | ${[Path.resolve(pathWorkspaceRoot, 'samples/custom-dictionary/cspell.json')]} ${sampleFiles.sampleClientReadme} | ${[configFiles.clientConfig, configFiles.rootConfig]} ${sampleFiles.sampleServerPackageLock} | ${[configFiles.serverConfig, configFiles.rootConfig]} `('findCSpellConfigurationFilesForUri no folders $filename', async ({ filename, expected }: FindCSpellConfigurationFilesForUriTest) => { const mockFolders: WorkspaceFolder[] = []; mockGetWorkspaceFolders.mockReturnValue(Promise.resolve(mockFolders)); mockGetConfiguration.mockReturnValue(Promise.resolve([{}, {}])); const docSettings = newDocumentSettings(getDefaultSettings()); const uri = Uri.file(Path.resolve(pathWorkspaceRoot, filename)).toString(); const result = await docSettings.findCSpellConfigurationFilesForUri(uri); // Note: toLowerCase is needed because on MacOS and Windows cSpell.json and cspell.json will be considered the same file. expect(result.map((f) => f.toString().toLowerCase())).toEqual(expected.map((u) => filePathToUri(u).toString().toLowerCase())); }); test('resolvePath', () => { expect(debugExports.resolvePath(__dirname)).toBe(__dirname); expect(debugExports.resolvePath('~')).toBe(os.homedir()); }); function newDocumentSettings(defaultSettings: CSpellUserSettings = {}) { return new DocumentSettings({} as Connection, defaultSettings); } }); describe('Validate RegExp corrections', () => { test('fixRegEx', () => { const defaultSettings = cspell.getDefaultSettings(); // Make sure it doesn't change the defaults. expect(defaultSettings.patterns?.map((p) => p.pattern).map(debugExports.fixRegEx)).toEqual( defaultSettings.patterns?.map((p) => p.pattern) ); const sampleRegEx: Pattern[] = ['/#.*/', '/"""(.*?\\n?)+?"""/g', "/'''(.*?\\n?)+?'''/g", 'strings']; const expectedRegEx: Pattern[] = ['/#.*/', '/(""")[^\\1]*?\\1/g', "/(''')[^\\1]*?\\1/g", 'strings']; expect(sampleRegEx.map(debugExports.fixRegEx)).toEqual(expectedRegEx); }); test('fixPattern', () => { const defaultSettings = cspell.getDefaultSettings(); // Make sure it doesn't change the defaults. expect(defaultSettings.patterns?.map(debugExports.fixPattern)).toEqual(defaultSettings.patterns); }); test('fixPattern', () => { const defaultSettings = cspell.getDefaultSettings(); // Make sure it doesn't change the defaults. expect(correctBadSettings(defaultSettings)).toEqual(defaultSettings); const settings: CSpellUserSettings = { patterns: [ { name: 'strings', pattern: '/"""(.*?\\n?)+?"""/g', }, ], }; const expectedSettings: CSpellUserSettings = { patterns: [ { name: 'strings', pattern: '/(""")[^\\1]*?\\1/g', }, ], }; expect(correctBadSettings(settings)).toEqual(expectedSettings); expect(correctBadSettings(settings)).not.toEqual(settings); }); }); function filePathToUri(file: string | Uri): Uri { return typeof file == 'string' ? Uri.file(file) : file; } function shortPathName(file: string | Uri): string { const uri = filePathToUri(file); const parts = uri.toString().split('/'); return parts.slice(-2).join('/'); }
the_stack
import { expect, test } from '@jest/globals'; import 'reflect-metadata'; import { createBSONSizer, getBSONSerializer, getBSONSizer, getValueSize, hexToByte, uuidStringToByte } from '../src/bson-serialize'; import { ExtractClassType, f, getClassSchema, jsonSerializer, nodeBufferToArrayBuffer, t } from '@deepkit/type'; import bson from 'bson'; import { getBSONDecoder } from '../src/bson-jit-parser'; import { randomBytes } from 'crypto'; import { parseObject, ParserV2 } from '../src/bson-parser'; import { ObjectId } from '../src/model'; import { BSON_BINARY_SUBTYPE_BIGINT, BSONType } from '../src/utils'; const { Binary, calculateObjectSize, deserialize, Long, ObjectId: OfficialObjectId, serialize } = bson; test('hexToByte', () => { expect(hexToByte('00')).toBe(0); expect(hexToByte('01')).toBe(1); expect(hexToByte('0f')).toBe(15); expect(hexToByte('10')).toBe(16); expect(hexToByte('ff')).toBe(255); expect(hexToByte('f0')).toBe(240); expect(hexToByte('50')).toBe(80); expect(hexToByte('7f')).toBe(127); expect(hexToByte('f00f', 1)).toBe(15); expect(hexToByte('f0ff', 1)).toBe(255); expect(hexToByte('f00001', 2)).toBe(1); expect(hexToByte('f8')).toBe(16 * 15 + 8); expect(hexToByte('41')).toBe(16 * 4 + 1); expect(uuidStringToByte('bef8de96-41fe-442f-b70c-c3a150f8c96c', 1)).toBe(16 * 15 + 8); expect(uuidStringToByte('bef8de96-41fe-442f-b70c-c3a150f8c96c', 4)).toBe(16 * 4 + 1); expect(uuidStringToByte('bef8de96-41fe-442f-b70c-c3a150f8c96c', 6)).toBe(16 * 4 + 4); expect(uuidStringToByte('bef8de96-41fe-442f-b70c-c3a150f8c96c', 7)).toBe(16 * 2 + 15); expect(uuidStringToByte('bef8de96-41fe-442f-b70c-c3a150f8c96c', 8)).toBe(16 * 11 + 7); expect(uuidStringToByte('bef8de96-41fe-442f-b70c-c3a150f8c96c', 10)).toBe(16 * 12 + 3); expect(uuidStringToByte('bef8de96-41fe-442f-b70c-c3a150f8c96c', 11)).toBe(16 * 10 + 1); expect(uuidStringToByte('bef8de96-41fe-442f-b70c-c3a150f8c96c', 15)).toBe(16 * 6 + 12); }); test('basic string', () => { const object = { name: 'Peter' }; const expectedSize = 4 //size uint32 + 1 // type (string) + 'name\0'.length + ( 4 //string size uint32 + 'Peter'.length + 1 //string content + null ) + 1 //object null ; expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ name: t.string, }); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('basic number int', () => { const object = { position: 24 }; const expectedSize = 4 //size uint32 + 1 // type (number) + 'position\0'.length + ( 4 //int uint32 ) + 1 //object null ; expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ position: t.number, }); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('basic long', () => { const object = { position: 3364367088039355000n }; const expectedSize = 4 //size uint32 + 1 // type (number) + 'position\0'.length + ( 4 //uint32 low bits + 4 //uint32 high bits ) + 1 //object null ; const schema = t.schema({ position: t.number, }); const serializer = getBSONSerializer(schema); const deserializer = getBSONDecoder(schema); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(serializer(object).byteLength).toBe(expectedSize); const reParsed = getBSONDecoder(schema)(serializer(object)); expect(reParsed.position).toBe(3364367088039355000n); expect(serializer({ position: 123456n })).toEqual(serialize({ position: Long.fromNumber(123456) })); expect(serializer({ position: -123456n })).toEqual(serialize({ position: Long.fromNumber(-123456) })); expect(serializer({ position: 3364367088039355000n })).toEqual(serialize({ position: Long.fromBigInt(3364367088039355000n) })); expect(serializer({ position: -3364367088039355000n })).toEqual(serialize({ position: Long.fromBigInt(-3364367088039355000n) })); expect(deserializer(serializer({ position: 3364367088039355000n }))).toEqual({ position: 3364367088039355000n }); expect(deserializer(serializer({ position: -3364367088039355000n }))).toEqual({ position: -3364367088039355000n }); }); test('basic bigint', () => { const object = { position: 3364367088039355000n }; const expectedSize = 4 //size uint32 + 1 // type (binary) + 'position\0'.length + ( 4 //binary size + 1 //binary type + 9 //binary content ) + 1 //object null ; const schema = t.schema({ position: t.bigint, }); const serializer = getBSONSerializer(schema); const deserializer = getBSONDecoder(schema); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(serializer(object).byteLength).toBe(expectedSize); const reParsed = deserializer(serializer(object)); expect(reParsed.position).toBe(3364367088039355000n); //this cases are valid when dynamic bigint serialization is activated // expect(serializer({ position: 123456n })).toEqual(serialize({ position: 123456 })); // expect(serializer({ position: -123456n })).toEqual(serialize({ position: -123456 })); // expect(serializer({ position: 3364367088039355000n })).toEqual(serialize({ position: Long.fromBigInt(3364367088039355000n) })); // expect(serializer({ position: -3364367088039355000n })).toEqual(serialize({ position: Long.fromBigInt(-3364367088039355000n) })); // // expect(serializer({ position: 9223372036854775807n })).toEqual(serialize({ position: Long.fromBigInt(9223372036854775807n) })); // expect(serializer({ position: -9223372036854775807n })).toEqual(serialize({ position: Long.fromBigInt(-9223372036854775807n) })); expect(deserializer(serializer({ position: 123456n }))).toEqual({ position: 123456n }); expect(deserializer(serializer({ position: -123456n }))).toEqual({ position: -123456n }); expect(deserializer(serializer({ position: 3364367088039355000n }))).toEqual({ position: 3364367088039355000n }); expect(deserializer(serializer({ position: -3364367088039355000n }))).toEqual({ position: -3364367088039355000n }); expect(deserializer(serializer({ position: 9223372036854775807n }))).toEqual({ position: 9223372036854775807n }); expect(deserializer(serializer({ position: -9223372036854775807n }))).toEqual({ position: -9223372036854775807n }); { const bson = serializer({ position: 9223372036854775810n }); //force binary format expect(bson).toEqual(Buffer.from([ 29, 0, 0, 0, //size BSONType.BINARY, //type long 112, 111, 115, 105, 116, 105, 111, 110, 0, //position\n string 9, 0, 0, 0, //binary size, int32 BSON_BINARY_SUBTYPE_BIGINT, //binary type 1, //signum 128, 0, 0, 0, 0, 0, 0, 2, //binary data 0, //object null ])); } { const bson = serializer({ position: -9223372036854775810n }); //force binary format expect(bson).toEqual(Buffer.from([ 29, 0, 0, 0, //size BSONType.BINARY, //type long 112, 111, 115, 105, 116, 105, 111, 110, 0, //position\n string 9, 0, 0, 0, //binary size, int32 BSON_BINARY_SUBTYPE_BIGINT, //binary type 255, //signum, 255 = -1 128, 0, 0, 0, 0, 0, 0, 2, //binary data 0, //object null ])); } }); test('basic any bigint', () => { const object = { position: 3364367088039355000n }; const expectedSize = 4 //size uint32 + 1 // type (binary) + 'position\0'.length + ( 4 //binary size + 1 //binary type + 9 //binary content ) + 1 //object null ; const schema = t.schema({ position: t.any, }); const serializer = getBSONSerializer(schema); const deserializer = getBSONDecoder(schema); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(serializer(object).byteLength).toBe(expectedSize); const reParsed = getBSONDecoder(schema)(serializer(object)); expect(reParsed.position).toBe(3364367088039355000n); expect(deserializer(serializer({ position: 123456n }))).toEqual({ position: 123456n }); expect(deserializer(serializer({ position: -123456n }))).toEqual({ position: -123456n }); expect(deserializer(serializer({ position: 3364367088039355000n }))).toEqual({ position: 3364367088039355000n }); expect(deserializer(serializer({ position: -3364367088039355000n }))).toEqual({ position: -3364367088039355000n }); expect(deserializer(serializer({ position: 9223372036854775807n }))).toEqual({ position: 9223372036854775807n }); expect(deserializer(serializer({ position: -9223372036854775807n }))).toEqual({ position: -9223372036854775807n }); { const bson = serializer({ position: 9223372036854775810n }); //force binary format expect(bson).toEqual(Buffer.from([ 29, 0, 0, 0, //size BSONType.BINARY, //type long 112, 111, 115, 105, 116, 105, 111, 110, 0, //position\n string 9, 0, 0, 0, //binary size, int32 BSON_BINARY_SUBTYPE_BIGINT, //binary type 1, //signum 128, 0, 0, 0, 0, 0, 0, 2, //binary data 0, //object null ])); } { const bson = serializer({ position: -9223372036854775810n }); //force binary format expect(bson).toEqual(Buffer.from([ 29, 0, 0, 0, //size BSONType.BINARY, //type long 112, 111, 115, 105, 116, 105, 111, 110, 0, //position\n string 9, 0, 0, 0, //binary size, int32 BSON_BINARY_SUBTYPE_BIGINT, //binary type 255, //signum, 255 = -1 128, 0, 0, 0, 0, 0, 0, 2, //binary data 0, //object null ])); } }); test('basic long bigint', () => { const bla: { n: number, m: string }[] = [ { n: 1, m: '1' }, { n: 1 << 16, m: 'max uint 16' }, { n: (1 << 16) + 100, m: 'max uint 16 + 100' }, { n: 4294967296, m: 'max uint 32' }, { n: 4294967296 - 100, m: 'max uint 32 - 100' }, { n: 4294967296 - 1, m: 'max uint 32 - 1' }, { n: 4294967296 + 100, m: 'max uint 32 + 100' }, { n: 4294967296 + 1, m: 'max uint 32 + 1' }, { n: 4294967296 * 10 + 1, m: 'max uint 32 * 10 + 1' }, // {n: 9223372036854775807, m: 'max uint64'}, // {n: 9223372036854775807 + 1, m: 'max uint64 - 1'}, // {n: 9223372036854775807 - 1, m: 'max uint64 + 2'}, ]; for (const b of bla) { const long = Long.fromNumber(b.n); console.log(b.n, long.toNumber(), long, b.m); } }); test('basic number double', () => { const object = { position: 149943944399 }; const expectedSize = 4 //size uint32 + 1 // type (number) + 'position\0'.length + ( 8 //double, 64bit ) + 1 //object null ; const expectedSizeNull = 4 //size uint32 + 1 // type (number) + 'position\0'.length + ( 0 //undefined ) + 1 //object null ; expect(calculateObjectSize(object)).toBe(expectedSize); expect(calculateObjectSize({ position: null })).toBe(expectedSizeNull); expect(calculateObjectSize({ position: undefined })).toBe(5); const schema = t.schema({ position: t.number, }); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); expect(getBSONSerializer(schema)({ position: null }).byteLength).toBe(expectedSizeNull); expect(getBSONSerializer(schema)({ position: undefined }).byteLength).toBe(expectedSizeNull); //explicitely annotataed undefined is included expect(getBSONSerializer(schema)({}).byteLength).toBe(5); expect(getBSONSerializer(schema)({ position: null }).byteLength).toEqual(expectedSizeNull); expect(getBSONSerializer(schema)({ position: undefined }).byteLength).toEqual(expectedSizeNull); //explicitely annotataed undefined is included expect(getBSONSerializer(schema)({}).byteLength).toEqual(5); expect(getBSONSerializer(schema)({ position: null })).toEqual(serialize({ position: null })); expect(getBSONSerializer(schema)({})).toEqual(serialize({})); expect(getBSONSerializer(schema)({})).toEqual(serialize({ position: undefined })); //official bson drops undefined values }); test('basic boolean', () => { const object = { valid: true }; const expectedSize = 4 //size uint32 + 1 // type (boolean) + 'valid\0'.length + ( 1 //boolean ) + 1 //object null ; expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ valid: t.boolean, }); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('basic date', () => { const object = { created: new Date }; const expectedSize = 4 //size uint32 + 1 // type (date) + 'created\0'.length + ( 8 //date ) + 1 //object null ; expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ created: t.date, }); const serializer = getBSONSerializer(schema); const deserializer = getBSONDecoder(schema); // expect(serializer(object).byteLength).toBe(expectedSize); // expect(createBSONSizer(schema)(object)).toBe(expectedSize); // expect(serializer(object)).toEqual(serialize(object)); expect(serializer({created: new Date('2900-10-12T00:00:00.000Z') })).toEqual(serialize({ created: new Date('2900-10-12T00:00:00.000Z') })); expect(serializer({created: new Date('1900-10-12T00:00:00.000Z') })).toEqual(serialize({ created: new Date('1900-10-12T00:00:00.000Z') })); expect(serializer({created: new Date('1000-10-12T00:00:00.000Z') })).toEqual(serialize({ created: new Date('1000-10-12T00:00:00.000Z') })); expect(deserializer(serializer({created: new Date('2900-10-12T00:00:00.000Z') }))).toEqual({ created: new Date('2900-10-12T00:00:00.000Z') }); expect(deserializer(serializer({created: new Date('1900-10-12T00:00:00.000Z') }))).toEqual({ created: new Date('1900-10-12T00:00:00.000Z') }); expect(deserializer(serializer({created: new Date('1000-10-12T00:00:00.000Z') }))).toEqual({ created: new Date('1000-10-12T00:00:00.000Z') }); }); test('basic binary', () => { const object = { binary: new Uint16Array(32) }; const expectedSize = 4 //size uint32 + 1 // type (date) + 'binary\0'.length + ( 4 //size of binary, uin32 + 1 //sub type + 32 * 2 //size of data ) + 1 //object null ; expect(new Uint16Array(32).byteLength).toBe(32 * 2); //this doesn't support typed arrays // expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ binary: t.type(Uint16Array), }); expect(schema.getProperty('binary').type).toBe('Uint16Array'); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); //doesnt support typed arrays // expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); expect(getBSONDecoder(schema)(getBSONSerializer(schema)(object))).toEqual(object); }); test('basic arrayBuffer', () => { const arrayBuffer = new ArrayBuffer(5); const view = new Uint8Array(arrayBuffer); view[0] = 22; view[1] = 44; view[2] = 55; view[3] = 66; view[4] = 77; const object = { binary: arrayBuffer }; const expectedSize = 4 //size uint32 + 1 // type (date) + 'binary\0'.length + ( 4 //size of binary, uin32 + 1 //sub type + 5 //size of data ) + 1 //object null ; // expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ binary: t.type(ArrayBuffer), }); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONDecoder(schema)(getBSONSerializer(schema)(object))).toEqual(object); // expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('basic Buffer', () => { const object = { binary: new Uint8Array(32) }; const expectedSize = 4 //size uint32 + 1 // type (date) + 'binary\0'.length + ( 4 //size of binary, uin32 + 1 //sub type + 32 //size of data ) + 1 //object null ; // expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ binary: t.type(Uint8Array), }); expect(schema.getProperty('binary').type).toBe('Uint8Array'); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONDecoder(schema)(getBSONSerializer(schema)(object))).toEqual(object); Buffer.alloc(2); Buffer.alloc(200); Buffer.alloc(20000); expect(getBSONDecoder(schema)(getBSONSerializer(schema)({ binary: Buffer.alloc(44) }))).toEqual({ binary: new Uint8Array(44) }); }); test('basic uuid', () => { const uuidRandomBinary = new Binary( Buffer.allocUnsafe(16), Binary.SUBTYPE_UUID ); const object = { uuid: '75ed2328-89f2-4b89-9c49-1498891d616d' }; const expectedSize = 4 //size uint32 + 1 // type (date) + 'uuid\0'.length + ( 4 //size of binary + 1 //sub type + 16 //content of uuid ) + 1 //object null ; expect(calculateObjectSize({ uuid: uuidRandomBinary })).toBe(expectedSize); const schema = t.schema({ uuid: t.uuid, }); expect(getBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); const uuidPlain = Buffer.from([0x75, 0xed, 0x23, 0x28, 0x89, 0xf2, 0x4b, 0x89, 0x9c, 0x49, 0x14, 0x98, 0x89, 0x1d, 0x61, 0x6d]); const uuidBinary = new Binary(uuidPlain, 4); const objectBinary = { uuid: uuidBinary }; expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(objectBinary)); const bson = serialize(objectBinary); const parsed = parseObject(new ParserV2(bson)); expect(parsed.uuid).toBe('75ed2328-89f2-4b89-9c49-1498891d616d'); }); test('basic objectId', () => { const object = { _id: '507f191e810c19729de860ea' }; const expectedSize = 4 //size uint32 + 1 // type + '_id\0'.length + ( 12 //size of objectId ) + 1 //object null ; const nativeBson = { _id: new OfficialObjectId('507f191e810c19729de860ea') }; expect(calculateObjectSize(nativeBson)).toBe(expectedSize); const schema = t.schema({ _id: t.mongoId, }); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(nativeBson)); }); test('basic nested', () => { const object = { name: { anotherOne: 'Peter2' } }; const expectedSize = 4 //size uint32 + 1 //type (object) + 'name\0'.length + ( 4 //size uint32 + 1 //type (object) + 'anotherOne\0'.length + ( 4 //string size uint32 + 'Peter2'.length + 1 //string content + null ) + 1 //object null ) + 1 //object null ; expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ name: { anotherOne: t.string, }, }); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('basic map', () => { const object = { name: { anotherOne: 'Peter2' } }; const expectedSize = 4 //size uint32 + 1 //type (object) + 'name\0'.length + ( 4 //size uint32 + 1 //type (object) + 'anotherOne\0'.length + ( 4 //string size uint32 + 'Peter2'.length + 1 //string content + null ) + 1 //object null ) + 1 //object null ; expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ name: t.map(t.string) }); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('basic array', () => { const object = { name: ['Peter3'] }; const expectedSize = 4 //size uint32 + 1 //type (array) + 'name\0'.length + ( 4 //size uint32 of array + 1 //type (string) + '0\0'.length //key + ( 4 //string size uint32 + 'Peter3'.length + 1 //string content + null ) + 1 //object null ) + 1 //object null ; expect(calculateObjectSize(object)).toBe(expectedSize); const schema = t.schema({ name: t.array(t.string), }); expect(getBSONSerializer(schema)(object).byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('number', () => { const object = { name: 'Peter4', tags: ['a', 'b', 'c'], priority: 15, position: 149943944399, valid: true, created: new Date() }; const schema = t.schema({ name: t.string, tags: t.array(t.string), priority: t.number, position: t.number, valid: t.boolean, created: t.date, }); expect(createBSONSizer(schema)(object)).toBe(calculateObjectSize(object)); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('all supported types', () => { const object = { name: 'Peter4', tags: ['a', 'b', 'c'], priority: 15, position: 149943944399, valid: true, created: new Date() }; const schema = t.schema({ name: t.string, tags: t.array(t.string), priority: t.number, position: t.number, valid: t.boolean, created: t.date, }); expect(createBSONSizer(schema)(object)).toBe(calculateObjectSize(object)); expect(getBSONSerializer(schema)(object)).toEqual(serialize(object)); }); test('string utf8', () => { const schema = t.schema({ name: t.string, any: t.any, }); const serialize = getBSONSerializer(schema); const parse = getBSONDecoder(schema); expect(parse(serialize({ name: 'Peter' }))).toEqual({ name: 'Peter' }); expect(parse(serialize({ name: 'Peter✌️' }))).toEqual({ name: 'Peter✌️' }); expect(parse(serialize({ name: '✌️' }))).toEqual({ name: '✌️' }); expect(parse(serialize({ name: '🌉' }))).toEqual({ name: '🌉' }); expect(parse(serialize({ name: 'πøˆ️' }))).toEqual({ name: 'πøˆ️' }); expect(parse(serialize({ name: 'Ѓ' }))).toEqual({ name: 'Ѓ' }); expect(parse(serialize({ name: '㒨' }))).toEqual({ name: '㒨' }); expect(parse(serialize({ name: '﨣' }))).toEqual({ name: '﨣' }); expect(parse(serialize({ any: { base: true } }))).toEqual({ any: { base: true } }); expect(parse(serialize({ any: { '✌️': true } }))).toEqual({ any: { '✌️': true } }); expect(parse(serialize({ any: { 'Ѓ': true } }))).toEqual({ any: { 'Ѓ': true } }); expect(parse(serialize({ any: { 㒨: true } }))).toEqual({ any: { 㒨: true } }); expect(parse(serialize({ any: { 﨣: true } }))).toEqual({ any: { 﨣: true } }); }); test('optional field', () => { const findSchema = t.schema({ find: t.string, batchSize: t.number, limit: t.number.optional, skip: t.number.optional, }); const findSerializer = getBSONSerializer(findSchema); const bson = findSerializer({ find: 'user', batchSize: 1, limit: 1, }); const bsonOfficial = serialize({ find: 'user', batchSize: 1, limit: 1, }); expect(bson).toEqual(bsonOfficial); }); test('complex', () => { const findSchema = t.schema({ find: t.string, batchSize: t.number, limit: t.number.optional, filter: t.any, projection: t.any, sort: t.any, skip: t.number.optional, }); const findSerializer = getBSONSerializer(findSchema); const bson = findSerializer({ find: 'user', batchSize: 1, limit: 1, }); const bsonOfficial = serialize({ find: 'user', batchSize: 1, limit: 1, }); expect(bson).toEqual(bsonOfficial); }); test('any objectId', () => { const schema = t.schema({ _id: t.any, q: t.any, }); { const doc = { _id: new ObjectId('507f191e810c19729de860ea') }; const officialDoc = { _id: new OfficialObjectId('507f191e810c19729de860ea') }; const bson = getBSONSerializer(schema)(doc); const bsonOfficial = serialize(officialDoc); expect(bson).toEqual(bsonOfficial); const parsed = deserialize(Buffer.from(bson)); expect(parsed._id).toBeInstanceOf(OfficialObjectId); expect(parsed._id.toHexString()).toBe('507f191e810c19729de860ea'); const parsed2 = getBSONDecoder(schema)(bson); expect(parsed2._id).toBe('507f191e810c19729de860ea'); } { const doc = { q: { id: new ObjectId('507f191e810c19729de860ea') } }; const officialDoc = { q: { id: new OfficialObjectId('507f191e810c19729de860ea') } }; const bson = getBSONSerializer(schema)(doc); const bsonOfficial = serialize(officialDoc); expect(bson).toEqual(bsonOfficial); const parsed = deserialize(Buffer.from(bson)); expect(parsed.q.id).toBeInstanceOf(OfficialObjectId); expect(parsed.q.id.toHexString()).toBe('507f191e810c19729de860ea'); const parsed2 = getBSONDecoder(schema)(bson); expect(parsed2.q.id).toBe('507f191e810c19729de860ea'); } }); test('objectId string', () => { const schema = t.schema({ id: t.mongoId, }); { const doc = { id: '507f191e810c19729de860ea' }; const bson = getBSONSerializer(schema)(doc); const bsonOfficial = serialize({ id: new OfficialObjectId('507f191e810c19729de860ea') }); expect(bson).toEqual(bsonOfficial); const parsed = deserialize(Buffer.from(bson)); expect(parsed.id).toBeInstanceOf(OfficialObjectId); expect(parsed.id.toHexString()).toBe('507f191e810c19729de860ea'); const parsed2 = getBSONDecoder(schema)(bson); expect(parsed2.id).toBe('507f191e810c19729de860ea'); } }); test('model 1, missing `public`', () => { class User { @f ready?: boolean; @f.array(f.string) tags: string[] = []; @f priority: number = 0; constructor( @f.primary id: number, @f public name: string ) { } } const schema = getClassSchema(User); expect(schema.getMethodProperties('constructor').length).toBe(2); expect(schema.getPropertiesMap().size).toBe(5); { const user = new User(1, 'Peter ' + 1); user.ready = true; user.priority = 5; user.tags = ['a', 'b', 'c']; const bson = getBSONSerializer(User)(user); const size = getBSONSizer(User)(user); expect(size).toBe(calculateObjectSize(user)); const s = getBSONDecoder(User); const o = s(bson); expect(o).toEqual(deserialize(Buffer.from(bson))); } { const user = { ready: true, priority: 5, tags: ['a', 'b', 'c'], id: null, name: 'Peter 1', }; const bson = getBSONSerializer(User)(user); const s = getBSONDecoder(User); const o = s(bson); expect(o).not.toEqual(deserialize(Buffer.from(bson))); //because bson-js includes `id`, but we drop it since it's not assigned in the constructor } }); test('decorated', () => { class DecoratedValue { constructor( @t.array(t.string).decorated public items: string[] = [] ) { } } const object = { v: new DecoratedValue(['Peter3']) }; const expectedSize = 4 //size uint32 + 1 //type (array) + 'v\0'.length + ( 4 //size uint32 of array + 1 //type (string) + '0\0'.length //key + ( 4 //string size uint32 + 'Peter3'.length + 1 //string content + null ) + 1 //object null ) + 1 //object null ; expect(calculateObjectSize({ v: ['Peter3'] })).toBe(expectedSize); const schema = t.schema({ v: t.type(DecoratedValue), }); const bson = getBSONSerializer(schema)(object); const officialDeserialize = deserialize(Buffer.from(bson)); console.log('officialDeserialize', officialDeserialize); expect(officialDeserialize.v).toEqual(['Peter3']); expect(bson.byteLength).toBe(expectedSize); expect(createBSONSizer(schema)(object)).toBe(expectedSize); expect(bson).toEqual(serialize({ v: ['Peter3'] })); const back = getBSONDecoder(schema)(bson); expect(back.v).toBeInstanceOf(DecoratedValue); expect(back.v.items).toEqual(['Peter3']); expect(back).toEqual(object); }); test('reference', () => { class User { @t.primary id: number = 1; @t.array(User).backReference() managedUsers: User[] = []; @t name!: string; //self reference @t.optional.reference() manager?: User; } { const object = new User(); object.name = 'Peter'; (object as any).manager = null; const bson = getBSONSerializer(User)(object); const json = deserialize(bson); expect('manager' in json).toBe(true); //needs to be maintained in BSON since manager is optional. Only way to reset it. expect(json.manager).toBe(null); //needs to be maintained in BSON since manager is optional. Only way to reset it. const trip = getBSONDecoder(User)(bson); expect(trip.manager).toBe(undefined); expect('manager' in trip).toBe(false); //not part of the object since undefined/null } const updateSchema = t.schema({ update: t.string, $db: t.string, updates: t.array({ q: t.any, u: t.any, multi: t.boolean, }) }); { const object = { update: 'Nix', $db: 'admin', updates: [{ q: { id: 213 }, u: { manager: null } }] }; expect(getBSONSizer(updateSchema)(object)).toBe(calculateObjectSize(object)); const bson = getBSONSerializer(updateSchema)(object); expect(getBSONDecoder(updateSchema)(bson)).toEqual(deserialize(Buffer.from(bson))); } }); test('bson length', () => { const nonce = randomBytes(24); class SaslStartCommand extends t.class({ saslStart: t.literal(1), $db: t.string, mechanism: t.string, payload: t.type(Uint8Array), autoAuthorize: t.literal(1), options: { skipEmptyExchange: t.literal(true) } }) { } const message = { saslStart: 1, '$db': 'admin', mechanism: 'SCRAM-SHA-1', payload: Buffer.concat([Buffer.from('n,,', 'utf8'), Buffer.from(`n=Peter,r=${nonce.toString('base64')}`, 'utf8')]), autoAuthorize: 1, options: { skipEmptyExchange: true } }; expect(message.payload.byteLength).toBe(13 + nonce.toString('base64').length); const size = getBSONSizer(SaslStartCommand)(message); expect(size).toBe(calculateObjectSize(message)); const bson = getBSONSerializer(SaslStartCommand)(message); expect(bson).toEqual(serialize(message)); }); test('arrayBuffer', () => { const schema = t.schema({ name: t.string, secondId: t.mongoId, preview: t.type(ArrayBuffer), }); const message = jsonSerializer.for(schema).deserialize({ name: 'myName', secondId: '5bf4a1ccce060e0b38864c9e', preview: nodeBufferToArrayBuffer(Buffer.from('Baar', 'utf8')) }); expect(Buffer.from(message.preview).toString('utf8')).toBe('Baar'); const mongoMessage = { name: message.name, secondId: new OfficialObjectId(message.secondId), preview: new Binary(Buffer.from(message.preview)), }; const size = getBSONSizer(schema)(message); expect(size).toBe(calculateObjectSize(mongoMessage)); const bson = getBSONSerializer(schema)(message); expect(bson).toEqual(serialize(mongoMessage)); const back = getBSONDecoder(schema)(bson); expect(Buffer.from(back.preview).toString('utf8')).toBe('Baar'); expect(back.preview).toEqual(message.preview); }); test('typed array', () => { const schema = t.schema({ name: t.string, secondId: t.mongoId, preview: t.type(Uint16Array), }); const message = jsonSerializer.for(schema).deserialize({ name: 'myName', secondId: '5bf4a1ccce060e0b38864c9e', preview: new Uint16Array(nodeBufferToArrayBuffer(Buffer.from('LAA3AEIATQBYAA==', 'base64'))), //44, 55, 66, 77, 88 }); expect(message.preview).toBeInstanceOf(Uint16Array); expect(message.preview.byteLength).toBe(10); const mongoMessage = { name: message.name, secondId: new OfficialObjectId(message.secondId), preview: new Binary(Buffer.from(new Uint8Array(message.preview.buffer, message.preview.byteOffset, message.preview.byteLength))), }; const size = getBSONSizer(schema)(message); expect(size).toBe(calculateObjectSize(mongoMessage)); const bson = getBSONSerializer(schema)(message); expect(bson).toEqual(serialize(mongoMessage)); const back = getBSONDecoder(schema)(bson); expect(back.preview).toEqual(message.preview); }); test('typed any and undefined', () => { const schema = t.schema({ data: t.any, }); const message = jsonSerializer.for(schema).deserialize({ data: { $set: {}, $inc: undefined, }, }); // expect(getValueSize({ $inc: undefined })).toBe(calculateObjectSize({ $inc: undefined })); //official BSON does not include undefined values, but we do expect(getValueSize({ $inc: [undefined] })).toBe(calculateObjectSize({ $inc: [undefined] })); // const size = getBSONSizer(schema)(message); // expect(size).toBe(calculateObjectSize(message)); //official bson doesnt include undefined const bson = getBSONSerializer(schema)(message); // expect(bson).toEqual(serialize(message)); //official bson doesnt include undefined const back = getBSONDecoder(schema)(bson); expect(back.data.$set).toEqual({}); expect(back.data.$inc).toEqual(undefined); expect('$inc' in back.data).toEqual(true); }); test('test map map', () => { const schema = t.schema({ data: t.map(t.map(t.string)), }); const message = jsonSerializer.for(schema).deserialize({ data: { foo: { bar: 'abc' } }, }); const size = getBSONSizer(schema)(message); expect(size).toBe(calculateObjectSize(message)); const bson = getBSONSerializer(schema)(message); expect(bson).toEqual(serialize(message)); expect(getBSONDecoder(schema)(bson)).toEqual(message); }); test('test array array', () => { const schema = t.schema({ data: t.array(t.array(t.string)), }); const message = jsonSerializer.for(schema).deserialize({ data: [['abc']], }); const size = getBSONSizer(schema)(message); expect(size).toBe(calculateObjectSize(message)); const bson = getBSONSerializer(schema)(message); expect(bson).toEqual(serialize(message)); expect(getBSONDecoder(schema)(bson)).toEqual(message); }); test('test array optional', () => { const schema = t.schema({ data: t.array(t.date.optional), }); { const message = { data: [new Date, undefined] }; const size = getBSONSizer(schema)(message); expect(size).toBe(calculateObjectSize(message)); } }); test('test map optional 1', () => { const schema = t.schema({ data: t.map(t.date.optional), }); { const message = { data: { first: new Date, second: undefined } }; // const size = getBSONSizer(schema)(message); //we maintain undefined as null, in contrary to BSON official // expect(size).toBe(calculateObjectSize(message)); expect(getBSONDecoder(schema)(getBSONSerializer(schema)(message))).toEqual(message); // expect(getBSONSerializer(schema)(message)).toEqual(serialize(message)); } }); test('test map optional 2', () => { const schema = t.schema({ data: t.map(t.date.optional), }); { const message = { data: { first: new Date, second: undefined } }; // const size = getBSONSizer(schema)(message); //we maintain undefined as null, in contrary to BSON official // expect(size).toBe(calculateObjectSize(message)); expect(getBSONDecoder(schema)(getBSONSerializer(schema)(message))).toEqual(message); // expect(getBSONSerializer(schema)(message)).toEqual(serialize(message)); } }); test('test union optional', () => { const schema = t.schema({ data: t.union('foo', 'bar').optional }); { const message = { data: 'foo' }; const size = getBSONSizer(schema)(message); expect(size).toBe(calculateObjectSize(message)); const serializer = getBSONSerializer(schema); const bson = serializer(message); expect(bson).toEqual(serialize(message)); expect(getBSONDecoder(schema)(getBSONSerializer(schema)(message))).toEqual(message); } { const message = { data: undefined }; // const size = getBSONSizer(schema)(message); // expect(size).toBe(calculateObjectSize(message)); //official bson does not include undefined, but we do const trip = getBSONDecoder(schema)(getBSONSerializer(schema)(message)); expect('data' in trip).toBe(true); expect(trip.data).toEqual(undefined); // expect(getBSONSerializer(schema)(message)).toEqual(serialize(message)); } { const message = { data: 'bar' }; const size = getBSONSizer(schema)(message); expect(size).toBe(calculateObjectSize(message)); expect(getBSONDecoder(schema)(getBSONSerializer(schema)(message))).toEqual(message); expect(getBSONSerializer(schema)(message)).toEqual(serialize(message)); } }); test('test object', () => { class MyModel { excluded = true; @t type: string = ''; constructor( @t public name: string ) { } } const schema = t.schema({ data: t.type(MyModel), }); { const item = new MyModel('bar'); item.type = 'foo'; const message: ExtractClassType<typeof schema> = { data: item }; expect(getBSONSizer(schema)(message)).not.toBe(calculateObjectSize(message)); //should bee different, since we do not include `excluded`, but official bson does const bson = getBSONSerializer(schema)(message); const backOfficial = deserialize(Buffer.from(bson)); expect(backOfficial.data.excluded).toBe(undefined); //`excluded` should not be part of the BSON expect(bson).not.toEqual(serialize(message)); //should not be equal, since MyModel does not serialize `excluded` const back = getBSONDecoder(schema)(bson); expect(back.data).toBeInstanceOf(MyModel); expect(back.data.name).toBe('bar'); expect(back.data.type).toBe('foo'); expect(back).toEqual(message); } }); test('test union deep object', () => { class MyModel { excluded = true; @t.literal('model') d: 'model' = 'model'; @t type: string = ''; constructor( @t public name: string ) { } } const schema = t.schema({ data: t.union(t.string, MyModel), }); { const message: ExtractClassType<typeof schema> = { data: 'peter' }; expect(getBSONSizer(schema)(message)).toBe(calculateObjectSize(message)); const bson = getBSONSerializer(schema)(message); expect(bson).toEqual(serialize(message)); expect(getBSONDecoder(schema)(bson)).toEqual(message); } { const item = new MyModel('bar'); item.type = 'foo'; const message: ExtractClassType<typeof schema> = { data: item }; expect(getBSONSizer(schema)(message)).not.toBe(calculateObjectSize(message)); //should bee different, since we do not include `excluded`, but official bson does const bson = getBSONSerializer(schema)(message); const backOfficial = deserialize(Buffer.from(bson)); expect(backOfficial.data.excluded).toBe(undefined); //`excluded` should not be part of the BSON expect(bson).not.toEqual(serialize(message)); //should not be equal, since MyModel does not serialize `excluded` const back = getBSONDecoder(schema)(bson); expect(back.data).toBeInstanceOf(MyModel); expect((back.data as MyModel).name).toBe('bar'); expect((back.data as MyModel).type).toBe('foo'); expect(back).toEqual(message); } });
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p>The specified version does not match the version of the document.</p> */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } /** * <p>The input for the DeleteThingShadow operation.</p> */ export interface DeleteThingShadowRequest { /** * <p>The name of the thing.</p> */ thingName: string | undefined; /** * <p>The name of the shadow.</p> */ shadowName?: string; } export namespace DeleteThingShadowRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteThingShadowRequest): any => ({ ...obj, }); } /** * <p>The output from the DeleteThingShadow operation.</p> */ export interface DeleteThingShadowResponse { /** * <p>The state information, in JSON format.</p> */ payload: Uint8Array | undefined; } export namespace DeleteThingShadowResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteThingShadowResponse): any => ({ ...obj, }); } /** * <p>An unexpected error has occurred.</p> */ export interface InternalFailureException extends __SmithyException, $MetadataBearer { name: "InternalFailureException"; $fault: "server"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace InternalFailureException { /** * @internal */ export const filterSensitiveLog = (obj: InternalFailureException): any => ({ ...obj, }); } /** * <p>The request is not valid.</p> */ export interface InvalidRequestException extends __SmithyException, $MetadataBearer { name: "InvalidRequestException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace InvalidRequestException { /** * @internal */ export const filterSensitiveLog = (obj: InvalidRequestException): any => ({ ...obj, }); } /** * <p>The specified combination of HTTP verb and URI is not supported.</p> */ export interface MethodNotAllowedException extends __SmithyException, $MetadataBearer { name: "MethodNotAllowedException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace MethodNotAllowedException { /** * @internal */ export const filterSensitiveLog = (obj: MethodNotAllowedException): any => ({ ...obj, }); } /** * <p>The specified resource does not exist.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } /** * <p>The service is temporarily unavailable.</p> */ export interface ServiceUnavailableException extends __SmithyException, $MetadataBearer { name: "ServiceUnavailableException"; $fault: "server"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace ServiceUnavailableException { /** * @internal */ export const filterSensitiveLog = (obj: ServiceUnavailableException): any => ({ ...obj, }); } /** * <p>The rate exceeds the limit.</p> */ export interface ThrottlingException extends __SmithyException, $MetadataBearer { name: "ThrottlingException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace ThrottlingException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottlingException): any => ({ ...obj, }); } /** * <p>You are not authorized to perform this operation.</p> */ export interface UnauthorizedException extends __SmithyException, $MetadataBearer { name: "UnauthorizedException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace UnauthorizedException { /** * @internal */ export const filterSensitiveLog = (obj: UnauthorizedException): any => ({ ...obj, }); } /** * <p>The document encoding is not supported.</p> */ export interface UnsupportedDocumentEncodingException extends __SmithyException, $MetadataBearer { name: "UnsupportedDocumentEncodingException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace UnsupportedDocumentEncodingException { /** * @internal */ export const filterSensitiveLog = (obj: UnsupportedDocumentEncodingException): any => ({ ...obj, }); } /** * <p>The input for the GetRetainedMessage operation.</p> */ export interface GetRetainedMessageRequest { /** * <p>The topic name of the retained message to retrieve.</p> */ topic: string | undefined; } export namespace GetRetainedMessageRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetRetainedMessageRequest): any => ({ ...obj, }); } /** * <p>The output from the GetRetainedMessage operation.</p> */ export interface GetRetainedMessageResponse { /** * <p>The topic name to which the retained message was published.</p> */ topic?: string; /** * <p>The Base64-encoded message payload of the retained message body.</p> */ payload?: Uint8Array; /** * <p>The quality of service (QoS) level used to publish the retained message.</p> */ qos?: number; /** * <p>The Epoch date and time, in milliseconds, when the retained message was stored by IoT.</p> */ lastModifiedTime?: number; } export namespace GetRetainedMessageResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetRetainedMessageResponse): any => ({ ...obj, }); } /** * <p>The input for the GetThingShadow operation.</p> */ export interface GetThingShadowRequest { /** * <p>The name of the thing.</p> */ thingName: string | undefined; /** * <p>The name of the shadow.</p> */ shadowName?: string; } export namespace GetThingShadowRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetThingShadowRequest): any => ({ ...obj, }); } /** * <p>The output from the GetThingShadow operation.</p> */ export interface GetThingShadowResponse { /** * <p>The state information, in JSON format.</p> */ payload?: Uint8Array; } export namespace GetThingShadowResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetThingShadowResponse): any => ({ ...obj, }); } export interface ListNamedShadowsForThingRequest { /** * <p>The name of the thing.</p> */ thingName: string | undefined; /** * <p>The token to retrieve the next set of results.</p> */ nextToken?: string; /** * <p>The result page size.</p> */ pageSize?: number; } export namespace ListNamedShadowsForThingRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListNamedShadowsForThingRequest): any => ({ ...obj, }); } export interface ListNamedShadowsForThingResponse { /** * <p>The list of shadows for the specified thing.</p> */ results?: string[]; /** * <p>The token to use to get the next set of results, or <b>null</b> if there are no additional results.</p> */ nextToken?: string; /** * <p>The Epoch date and time the response was generated by IoT.</p> */ timestamp?: number; } export namespace ListNamedShadowsForThingResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListNamedShadowsForThingResponse): any => ({ ...obj, }); } export interface ListRetainedMessagesRequest { /** * <p>To retrieve the next set of results, the <code>nextToken</code> * value from a previous response; otherwise <b>null</b> to receive * the first set of results.</p> */ nextToken?: string; /** * <p>The maximum number of results to return at one time.</p> */ maxResults?: number; } export namespace ListRetainedMessagesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListRetainedMessagesRequest): any => ({ ...obj, }); } /** * <p>Information about a single retained message.</p> */ export interface RetainedMessageSummary { /** * <p>The topic name to which the retained message was published.</p> */ topic?: string; /** * <p>The size of the retained message's payload in bytes.</p> */ payloadSize?: number; /** * <p>The quality of service (QoS) level used to publish the retained message.</p> */ qos?: number; /** * <p>The Epoch date and time, in milliseconds, when the retained message was stored by IoT.</p> */ lastModifiedTime?: number; } export namespace RetainedMessageSummary { /** * @internal */ export const filterSensitiveLog = (obj: RetainedMessageSummary): any => ({ ...obj, }); } export interface ListRetainedMessagesResponse { /** * <p>A summary list the account's retained messages. The information returned doesn't include * the message payloads of the retained messages.</p> */ retainedTopics?: RetainedMessageSummary[]; /** * <p>The token for the next set of results, or null if there are no additional results.</p> */ nextToken?: string; } export namespace ListRetainedMessagesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListRetainedMessagesResponse): any => ({ ...obj, }); } /** * <p>The input for the Publish operation.</p> */ export interface PublishRequest { /** * <p>The name of the MQTT topic.</p> */ topic: string | undefined; /** * <p>The Quality of Service (QoS) level.</p> */ qos?: number; /** * <p>A Boolean value that determines whether to set the RETAIN flag when the message is published.</p> * <p>Setting the RETAIN flag causes the message to be retained and sent to new subscribers to the topic.</p> * <p>Valid values: <code>true</code> | <code>false</code> * </p> * <p>Default value: <code>false</code> * </p> */ retain?: boolean; /** * <p>The message body. MQTT accepts text, binary, and empty (null) message payloads.</p> * <p>Publishing an empty (null) payload with <b>retain</b> = * <code>true</code> deletes the retained message identified by <b>topic</b> from IoT Core.</p> */ payload?: Uint8Array; } export namespace PublishRequest { /** * @internal */ export const filterSensitiveLog = (obj: PublishRequest): any => ({ ...obj, }); } /** * <p>The payload exceeds the maximum size allowed.</p> */ export interface RequestEntityTooLargeException extends __SmithyException, $MetadataBearer { name: "RequestEntityTooLargeException"; $fault: "client"; /** * <p>The message for the exception.</p> */ message?: string; } export namespace RequestEntityTooLargeException { /** * @internal */ export const filterSensitiveLog = (obj: RequestEntityTooLargeException): any => ({ ...obj, }); } /** * <p>The input for the UpdateThingShadow operation.</p> */ export interface UpdateThingShadowRequest { /** * <p>The name of the thing.</p> */ thingName: string | undefined; /** * <p>The name of the shadow.</p> */ shadowName?: string; /** * <p>The state information, in JSON format.</p> */ payload: Uint8Array | undefined; } export namespace UpdateThingShadowRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateThingShadowRequest): any => ({ ...obj, }); } /** * <p>The output from the UpdateThingShadow operation.</p> */ export interface UpdateThingShadowResponse { /** * <p>The state information, in JSON format.</p> */ payload?: Uint8Array; } export namespace UpdateThingShadowResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateThingShadowResponse): any => ({ ...obj, }); }
the_stack
import React, { FC, useRef } from 'react'; import { useMutation, useQueryClient } from 'react-query'; import { Alert, Col, Grid, Row } from 'react-bootstrap'; import * as Yup from 'yup'; import { Field, FieldProps, Form, Formik, FormikProps } from 'formik'; import { toast } from 'react-toastify'; import { YBButton, YBFormInput, YBSegmentedButtonGroup, YBToggle } from '../../common/forms/fields'; import { YBCopyButton } from '../../common/descriptors'; import { api, QUERY_KEY } from '../../../redesign/helpers/api'; import { HAConfig, HAReplicationSchedule } from '../../../redesign/helpers/dtos'; import YBInfoTip from '../../common/descriptors/YBInfoTip'; import './HAReplicationForm.scss'; export enum HAInstanceTypes { Active = 'Active', Standby = 'Standby' } const INITIAL_VALUES = { configId: '', // hidden field, needed to provide config ID to mutations as part of form values instanceType: HAInstanceTypes.Active, instanceAddress: window.location.origin, replicationFrequency: 1, clusterKey: '', replicationEnabled: true }; type FormValues = typeof INITIAL_VALUES; interface HAReplicationFormProps { config?: HAConfig; schedule?: HAReplicationSchedule; backToViewMode(): void; } const validationSchema = Yup.object().shape({ instanceAddress: Yup.string() .required('Required field') .matches(/^(http|https):\/\/.+/i, 'Should be a valid URL'), clusterKey: Yup.string().required('Required field'), // fields below must be in DOM, otherwise conditional validation won't work replicationFrequency: Yup.mixed().when(['instanceType', 'replicationEnabled'], { is: (instanceType, replicationEnabled) => instanceType === HAInstanceTypes.Active && replicationEnabled, // eslint-disable-next-line no-template-curly-in-string then: Yup.number().min(1, 'Minimum value is ${min}').required('Required field') }) }); export const FREQUENCY_MULTIPLIER = 60000; export const HAReplicationForm: FC<HAReplicationFormProps> = ({ config, schedule, backToViewMode }) => { let initialValues = INITIAL_VALUES; const isEditMode = !!config && !!schedule; const formik = useRef({} as FormikProps<FormValues>); const queryClient = useQueryClient(); const generateKey = useMutation(api.generateHAKey, { onSuccess: (data) => formik.current.setFieldValue('clusterKey', data.cluster_key) }); const { mutateAsync: enableReplication } = useMutation((formValues: FormValues) => api.startHABackupSchedule(formValues.configId, formValues.replicationFrequency) ); const { mutateAsync: disableReplication } = useMutation((formValues: FormValues) => api.stopHABackupSchedule(formValues.configId) ); const { mutateAsync: createHAConfig } = useMutation<HAConfig, unknown, FormValues>((formValues) => api.createHAConfig(formValues.clusterKey) ); const { mutateAsync: createHAInstance } = useMutation((formValues: FormValues) => api.createHAInstance( formValues.configId, formValues.instanceAddress, formValues.instanceType === HAInstanceTypes.Active, true ) ); if (isEditMode && config && schedule) { const instance = config.instances.find((item) => item.is_local); if (instance) { initialValues = { configId: config.uuid, instanceType: instance.is_leader ? HAInstanceTypes.Active : HAInstanceTypes.Standby, instanceAddress: instance.address || '', replicationFrequency: schedule.frequency_milliseconds / FREQUENCY_MULTIPLIER, clusterKey: config.cluster_key, replicationEnabled: schedule.is_running }; } else { toast.error("Can't find an HA platform instance with is_local = true"); } } const submitForm = async (values: FormValues) => { const data = { ...values }; data.replicationFrequency = data.replicationFrequency * FREQUENCY_MULTIPLIER; try { if (isEditMode) { // in edit mode only replication schedule could be edited if (data.replicationEnabled) { await enableReplication(data); } else { await disableReplication(data); } } else { if (data.instanceType === HAInstanceTypes.Active) { data.configId = (await createHAConfig(data)).uuid; await createHAInstance(data); if (data.replicationEnabled) { await enableReplication(data); } } else { data.configId = (await createHAConfig(data)).uuid; await createHAInstance(data); } } // invalidating queries will trigger their re-fetching and updating components where they are used queryClient.invalidateQueries(QUERY_KEY.getHAConfig); queryClient.invalidateQueries(QUERY_KEY.getHAReplicationSchedule); backToViewMode(); } catch (error) { toast.error(`Error on ${isEditMode ? 'editing' : 'creating'} replication configuration`); } finally { formik.current.setSubmitting(false); } }; return ( <div className="ha-replication-form" data-testid="ha-replication-config-form"> <Formik<FormValues> initialValues={initialValues} validationSchema={validationSchema} onSubmit={submitForm} > {(formikProps) => { // workaround for outdated version of Formik to access form methods outside of <Formik> formik.current = formikProps; return ( <Form role="form"> <Grid fluid> {formikProps.values.instanceType === HAInstanceTypes.Standby && !isEditMode && ( <Row className="ha-replication-form__alert"> <Col xs={12}> <Alert bsStyle="warning"> Note: on standby instances you can only access the high availability configuration and other features won't be available until the configuration is deleted. </Alert> </Col> </Row> )} <Row className="ha-replication-form__row"> <Col xs={2} className="ha-replication-form__label"> Instance Type </Col> <Col xs={10}> <YBSegmentedButtonGroup disabled={isEditMode} name="instanceType" options={[HAInstanceTypes.Active, HAInstanceTypes.Standby]} /> <YBInfoTip title="Replication Configuration" content="The initial role for this platform instance" /> </Col> </Row> <Row className="ha-replication-form__row"> <Col xs={2} className="ha-replication-form__label"> IP Address / Hostname </Col> <Col xs={10}> <Field name="instanceAddress" type="text" disabled={isEditMode} component={YBFormInput} placeholder="http://" className="ha-replication-form__input" /> <YBInfoTip title="Replication Configuration" content="The current platform's IP address or hostname" /> </Col> </Row> <Row className="ha-replication-form__row"> <Col xs={2} className="ha-replication-form__label"> Shared Authentication Key </Col> <Col xs={10}> <div className="ha-replication-form__key-input"> <Field name="clusterKey" type="text" component={YBFormInput} disabled={ isEditMode || formikProps.values.instanceType === HAInstanceTypes.Active } className="ha-replication-form__input" /> <YBCopyButton text={formikProps.values.clusterKey} /> </div> {formikProps.values.instanceType === HAInstanceTypes.Active && ( <YBButton btnClass="btn btn-orange ha-replication-form__generate-key-btn" btnText="Generate Key" loading={generateKey.isLoading} disabled={isEditMode || generateKey.isLoading} onClick={generateKey.mutate} /> )} <YBInfoTip title="Replication Configuration" content={`The key used to authenticate the High Availability cluster ${ formikProps.values.instanceType === HAInstanceTypes.Standby ? '(generated on active instance)' : '' }`} /> </Col> </Row> <div hidden={formikProps.values.instanceType === HAInstanceTypes.Standby} data-testid="ha-replication-config-form-schedule-section" > <Row className="ha-replication-form__row"> <Col xs={2} className="ha-replication-form__label"> Replication Frequency </Col> <Col xs={10}> <Field name="replicationFrequency" type="number" component={YBFormInput} disabled={!formikProps.values.replicationEnabled} className="ha-replication-form__input ha-replication-form__input--frequency" /> <span>minute(s)</span> <YBInfoTip title="Replication Configuration" content="How frequently periodic backups are sent to standby platforms" /> </Col> </Row> <Row className="ha-replication-form__row"> <Col xs={2} className="ha-replication-form__label"> Enable Replication </Col> <Col xs={10}> <Field name="replicationEnabled"> {({ field }: FieldProps) => ( <YBToggle onToggle={formikProps.handleChange} name="replicationEnabled" input={{ value: field.value, onChange: field.onChange }} /> )} </Field> <YBInfoTip title="Replication Configuration" content="Enable/disable replication to standby platforms" /> </Col> </Row> </div> <Row className="ha-replication-form__row"> <Col xs={12} className="ha-replication-form__footer"> {isEditMode && <YBButton btnText="Cancel" onClick={backToViewMode} />} <YBButton btnType="submit" disabled={formikProps.isSubmitting || !formikProps.isValid} loading={formikProps.isSubmitting} btnClass="btn btn-orange" btnText={isEditMode ? 'Save' : 'Create'} /> </Col> </Row> </Grid> </Form> ); }} </Formik> </div> ); };
the_stack