text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
class MissingClientIdError extends Error { message = 'No oauth2ClientId found in app settings or config'; } enum GapiScopes { CLOUD, DRIVE, SIGNIN, } // The GapiAuth interface handles initialization and authorization of gapi. interface GapiAuth { getAccessToken(): Promise<string>; getSignedInEmail(): Promise<string>; listenForSignInChanges(signInChangedCallback: (isSignedIn: boolean) => void): Promise<void>; loadGapiAndScopes( moduleName: string, moduleVersion: string, scopes: GapiScopes): Promise<void>; signIn(doPrompt?: boolean): Promise<void>; signOut(): Promise<void>; isServerAuth(): boolean; } // Ask for all necesary scopes up front so we don't need to ask again later. // Cloud-platform scope covers BigQuery and GCS but not Drive. const initialScopes = [ GapiScopes.SIGNIN, GapiScopes.CLOUD, GapiScopes.DRIVE ]; class ClientAuth implements GapiAuth { private _clientId = ''; // Gets set by _loadClientId() private _currentUser: gapi.auth2.GoogleUser; // Gets set by _loadClientId private _loadPromise: Promise<void>; /** Always returns false because we do not do server-side auth flow. */ public isServerAuth() { return false; } /** * Starts the sign-in flow using gapi. * If the user has not previously authorized our app, this will redirect to oauth url * to ask the user to select an account and to consent to our use of the scopes. * If the user has previously signed in and the doPrompt flag is false, the redirect will * happen momentarily before automatically closing. If the doPrompt flag is set, then * the user will be prompted as if authorization has not previously been provided. */ public async signIn(doPrompt?: boolean): Promise<void> { const rePromptOptions = 'login consent select_account'; const promptFlags = doPrompt ? rePromptOptions : ''; const options = { prompt: promptFlags, }; await this._loadGapi(); gapi.auth2.getAuthInstance().signIn(options); } /** * Signs the user out using gapi. */ public signOut(): Promise<void> { return this._loadGapi() .then(() => gapi.auth2.getAuthInstance().signOut()); } /** * Returns a promise that resolves to the signed-in user's email address. */ public async getSignedInEmail(): Promise<string> { await this._loadGapi(); const user = await this.getCurrentUser(); return user.getBasicProfile().getEmail(); } /** * Observes changes to the sign in status, and calls the provided callback * with the changes. */ public listenForSignInChanges(signInChangedCallback: (isSignedIn: boolean) => void): Promise<void> { return this._loadGapi() .then(() => { // Initialize the callback now signInChangedCallback(gapi.auth2.getAuthInstance().isSignedIn.get()); // Listen for auth changes gapi.auth2.getAuthInstance().isSignedIn.listen(() => { signInChangedCallback(gapi.auth2.getAuthInstance().isSignedIn.get()); }); }); } /** * Gets the current user's access token. */ public async getAccessToken(): Promise<string> { const user = await this.getCurrentUser(); return user.getAuthResponse().access_token; } /** * Gets the info we need to pass along about our access token. */ public async getAccessTokenInfo() { const account = await this.getCurrentUser(); const token = account.getAuthResponse(); return { access_token: token.access_token, account: account.getBasicProfile().getEmail(), expires_in: token.expires_in, scopes: token.scope, token_type: 'Bearer', }; } /** * Loads the requested gapi module and ensures we have the requested scope. */ public async loadGapiAndScopes( moduleName: string, moduleVersion: string, scopes: GapiScopes): Promise<void> { await this._loadGapi(); await gapi.client.load(moduleName, moduleVersion); await this._grantScope(scopes); } /** * Get the currently logged in user. */ private async getCurrentUser(): Promise<gapi.auth2.GoogleUser> { await this._loadGapi(); return this._currentUser; } /** * Requests a new scope to be granted. */ private async _grantScope(scope: GapiScopes): Promise<any> { await this._loadGapi(); const currentUser = await this.getCurrentUser(); if (!currentUser.hasGrantedScopes(this._getScopeString(scope))) { return new Promise((resolve, reject) => { const options = new gapi.auth2.SigninOptionsBuilder(); options.setScope(this._getScopeString(scope)); options.setPrompt('consent'); gapi.auth2.getAuthInstance().signIn(options) .then(() => { resolve(); }, () => reject()); }); } return Promise.resolve(); } /** * Loads the gapi module and the auth2 modules. This can be called multiple * times, and it will only load the gapi module once. * @param signInChangedCallback callback to be called when the signed-in state changes * @returns a promise that completes when the load is done or has failed */ private _loadGapi(): Promise<void> { // Loads the gapi client library and the auth2 library together for efficiency. // Loading the auth2 library is optional here since `gapi.client.init` function will load // it if not already loaded. Loading it upfront can save one network request. if (!this._loadPromise) { this._loadPromise = new Promise((resolve, reject) => { return this._loadClientId() .then(() => gapi.load('client:auth2', resolve)) .catch((e: Error) => { if (e instanceof MissingClientIdError) { Utils.log.error(e.message); } reject(e); }); }) .then(() => this._initClient()); } return this._loadPromise; } /* * Initialize the client and initialize OAuth with an * OAuth 2.0 client ID and scopes (space delimited string) to request access. */ private _initClient(): Promise<void> { const initialScopeString = initialScopes.map( (scopeEnum) => this._getScopeString(scopeEnum)).join(' '); // TODO: Add state parameter to redirect the user back to the current URL // after the OAuth flow finishes. return gapi.auth2.init({ client_id: this._clientId, fetch_basic_profile: true, redirect_uri: Utils.getHostRoot(), scope: initialScopeString, ux_mode: 'redirect', }) // The return value of gapi.auth2.init is not a normal promise .then(() => { this._currentUser = gapi.auth2.getAuthInstance().currentUser.get(); }, (errorReason: any) => { throw new Error('Error in gapi auth: ' + errorReason.details); }); } /** * Loads the oauth2 client id. Looks first in the app settings, * then in the config-local file. */ private async _loadClientId(): Promise<void> { let clientId = await this._loadClientIdFromAppSettings(); if (!clientId) { clientId = await this._loadClientIdFromConfigFile(); } if (!clientId) { throw new MissingClientIdError(); } this._clientId = clientId; } /** * Loads the oauth2 client id from the app settings. */ private _loadClientIdFromAppSettings(): Promise<string> { return SettingsManager.getAppSettingsAsync() .then((settings: common.AppSettings) => { return settings.oauth2ClientId; }) .catch(() => { return ''; }); } /** * Loads the oauth2 client id from the config-local file. */ private _loadClientIdFromConfigFile(): Promise<string> { return SettingsManager.loadConfigToWindowDatalab() .catch() // We will detect errors below when we see if the clientId exists .then(() => { if (window.datalab && window.datalab.oauth2ClientId) { return window.datalab.oauth2ClientId; } else { return ''; } }); } private _getScopeString(scope: GapiScopes): string { // https://developers.google.com/identity/protocols/googlescopes switch (scope) { case GapiScopes.CLOUD: return 'https://www.googleapis.com/auth/cloud-platform'; case GapiScopes.DRIVE: const driveScopeList = [ 'https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.install', ]; return driveScopeList.join(' '); case GapiScopes.SIGNIN: return 'profile email'; default: throw new Error('Unknown gapi scope: ' + scope); } } } class ServerAuth implements GapiAuth { _isSignedIn: boolean; _signInChangedCallback: (isSignedIn: boolean) => void; private _loadPromise: Promise<void>; private _refreshTimeoutId: number; /** Always returns true because we do server-side auth flow. */ public isServerAuth() { return true; } /** * Starts the sign-in flow. * If the user has not previously authorized our app, this will redirect to oauth url * to ask the user to select an account and to consent to our use of the scopes. * If the user has previously signed in, the redirect will * happen momentarily before automatically closing. */ public async signIn(_doPrompt?: boolean): Promise<void> { let accessToken = await GapiManager.auth.getAccessToken(); if (!accessToken) { // We don't have an access token, but we might have a refresh token (which // we can't see because it is HttpOnly). Try refreshing our access token, // then check again to see if that worked. await this.refreshToken(); accessToken = await GapiManager.auth.getAccessToken(); } if (!accessToken) { // No access token, even after trying a refresh, so ask user to log in again. const currentPath = window.location.pathname; const authLoginUrl = window.location.origin + '/auth/login?page=' + currentPath; window.location.replace(authLoginUrl); return; } this.setIsSignedIn(true); } /** * Signs the user out. */ public async signOut(): Promise<void> { // We sign out by deleting our cookies. Utils.deleteCookie('DATALAB_ACCESS_TOKEN'); Utils.deleteCookie('DATALAB_REFRESH_TOKEN'); this.setIsSignedIn(false); await this.logout(); return Promise.resolve(); } /** * Returns a promise that resolves to the signed-in user's email address. */ public async getSignedInEmail(): Promise<string> { const userInfo = await this.getUserInfo(); return userInfo.email; } /** * Observes changes to the sign in status, and calls the provided callback * with the changes. */ public listenForSignInChanges(signInChangedCallback: (isSignedIn: boolean) => void): Promise<void> { this._signInChangedCallback = signInChangedCallback; return Promise.resolve(); } /** * Gets the current user's access token. */ public async getAccessToken(): Promise<string> { const accessTokenBase64 = Utils.readCookie('DATALAB_ACCESS_TOKEN', true); if (!accessTokenBase64) { return ''; } const json = atob(accessTokenBase64); const accessToken = JSON.parse(json); return accessToken.value; } /** * Gets the info we need to pass along about our access token. */ public async getAccessTokenInfo() { const xhrOptions: XhrOptions = { successCodes: [200, 401], // Auth errors are expected }; const accessToken = await this.getAccessToken(); const infoUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' + accessToken; const tokenInfo = await ApiManager.sendRequestAsync(infoUrl, xhrOptions, false); return { access_token: accessToken, account: tokenInfo.email, expires_in: tokenInfo.expiresIn, scopes: tokenInfo.scope, token_type: 'Bearer', }; } public async loadGapiAndScopes( moduleName: string, moduleVersion: string, _scopes: GapiScopes): Promise<void> { await this.signIn(); await this._loadGapi(); await gapi.client.load(moduleName, moduleVersion); } /** * Sets our internal flag as to whether we are signed in, and calls the * _signInChangedCallback if the signedIn value just changed and there is a * callback. */ private setIsSignedIn(isSignedIn: boolean) { if (isSignedIn !== this._isSignedIn) { this._isSignedIn = isSignedIn; if (this._signInChangedCallback) { this._signInChangedCallback(isSignedIn); } if (isSignedIn) { this.setRefreshTokenTimeout(); } else { Utils.log.verbose('Not signed in, clearing refresh token timeout'); this.clearRefreshTokenTimeout(); } } } private async getUserInfo(): Promise<any> { const xhrOptions: XhrOptions = { successCodes: [200, 401], // Auth errors are expected }; const userInfoPath = '/_auth/userinfo'; const userInfo = await ApiManager.sendRequestAsync(userInfoPath, xhrOptions, false); if (userInfo && userInfo.error && userInfo.error.code === 401) { // If we get an invalid-credentials errors, sign out so the user // will be asked for sign in on the next request. Utils.log.verbose('Auto-sign-out due to invalid credentials'); GapiManager.auth.signOut(); return {}; } return userInfo; } private async logout(): Promise<boolean> { const xhrOptions: XhrOptions = { successCodes: [200], }; const logoutPath = '/_auth/logout'; const result = await ApiManager.sendRequestAsync(logoutPath, xhrOptions, false); if (result && result.error) { return Promise.resolve(false); } return Promise.resolve(true); } /** * Gets the expiration time for the access token, or null if no token. */ private async getAccessTokenExpiry(): Promise<Date | null> { const accessTokenBase64 = Utils.readCookie('DATALAB_ACCESS_TOKEN', true); if (!accessTokenBase64) { return null; } const json = atob(accessTokenBase64); const accessToken = JSON.parse(json); const expiry = new Date(accessToken.expiry); Utils.log.verbose('Access token expires', expiry); return expiry; } /** * Sends a request to the service to refresh our access token. */ private async refreshToken(): Promise<void> { const xhrOptions: XhrOptions = { failureCodes: [401], successCodes: [200], }; const refreshPath = '/_auth/refresh'; try { await ApiManager.sendRequestAsync(refreshPath, xhrOptions, false); } catch (e) { // If we get an invalid-credentials errors, sign out so the user // will be asked for sign in on the next request. Utils.log.verbose('Auto-sign-out due to invalid credentials'); GapiManager.auth.signOut(); } } private async refreshTokenAndTimeout(): Promise<void> { await this.refreshToken(); if (this._isSignedIn) { this.setRefreshTokenTimeout(); } } private async setRefreshTokenTimeout() { this.clearRefreshTokenTimeout(); const timeoutMillis = await this.calculateRefreshTokenTimeoutMillis(); this._refreshTimeoutId = window.setTimeout(() => this.refreshTokenAndTimeout(), timeoutMillis); } private clearRefreshTokenTimeout() { if (this._refreshTimeoutId) { window.clearTimeout(this._refreshTimeoutId); this._refreshTimeoutId = 0; } } private async calculateRefreshTokenTimeoutMillis() { const now = Date.now(); const tokenExpirationTime = await this.getAccessTokenExpiry(); const expirationMillis = tokenExpirationTime ? tokenExpirationTime.getTime() : 0; const millisToExpiration = expirationMillis - now; const minCheckMillis = 60 * 1000; // If expiration is less than this, refresh quickly const minTimeoutMillis = 500; // Wait minimum half second before refresh to avoid spinning in case of bugs const timeoutMillis = millisToExpiration < minCheckMillis ? minTimeoutMillis : millisToExpiration / 2; Utils.log.verbose('Seconds until token refresh:', timeoutMillis / 1000); return timeoutMillis; } /** * Loads the gapi module and the gapi client modules. This can be called multiple * times, and it will only load the gapi module once. * @returns a promise that completes when the load is done or has failed */ private _loadGapi(): Promise<void> { // Loads the gapi client library. if (!this._loadPromise) { this._loadPromise = new Promise((resolve, reject) => { return Promise.resolve() .then(() => gapi.load('client', () => { Utils.log.verbose('gapi loaded'); resolve(); })) .catch((e: Error) => { if (e instanceof MissingClientIdError) { Utils.log.error(e.message); } reject(e); }); }) .then(() => this._initClient()); } return this._loadPromise; } /* * Initialize the client and initialize OAuth with an * OAuth 2.0 client ID and scopes (space delimited string) to request access. */ private async _initClient(): Promise<void> { Utils.log.verbose('in _initClient'); const accessToken = await this.getAccessToken(); if (accessToken) { gapi.client.setToken({access_token: accessToken}); } return Promise.resolve(); } } /** * This module contains a collection of functions that interact with gapi. */ class GapiManager { public static drive = class { public static getRoot(): Promise<gapi.client.drive.File> { const request: gapi.client.drive.GetFileRequest = { fileId: 'root', }; return this._load() .then(() => gapi.client.drive.files.get(request)) .then((response) => JSON.parse(response.body)); } /** * Creates a file with the specified name under the specified parent * directory. If the content argument isn't empty, it's patched to the file * in a subsequent request. */ public static async create(mimeType: string, parentId: string, name: string, content = '') : Promise<gapi.client.drive.File> { await this._load(); let createPromise = gapi.client.drive.files.create({ mimeType, name, parents: [parentId], }) .then((response) => response.result); if (content) { createPromise = createPromise .then((file) => this.patchContent(file.id, content)); } return createPromise; } /** * Makes a copy of the given file, and optionally moves this new copy into * the given parent directory. */ public static async copy(fileId: string, destinationId?: string) : Promise<gapi.client.drive.File> { await this._load(); return gapi.client.drive.files.copy({fileId}) .then((response) => { const newFile = response.result; if (destinationId) { return this.renameFile(newFile.id, newFile.name, destinationId); } else { return newFile; } }); } /** * Saves the given string content to the specified file. */ public static async patchContent(fileId: string, content: string) : Promise<gapi.client.drive.File> { await this._load(); return gapi.client.request({ body: content, method: 'PATCH', params: { uploadType: 'media' }, path: '/upload/drive/v3/files/' + fileId, }) .then((response) => response.result as gapi.client.drive.File); } /** * Rename the given file to the new name, and optionally move it to the * given parent directory. */ public static async renameFile(fileId: string, newName: string, newParentId?: string) { await this._load(); const request: gapi.client.drive.UpdateFileRequest = { fileId, resource: { name: newName, }, }; if (newParentId) { const file = await this.getFile(fileId, ['parents']); const prevParents = file.parents.join(','); request.addParents = newParentId; request.removeParents = prevParents; } return gapi.client.drive.files.update(request) .then((response) => response.result); } /** * Delete the given file. */ public static async deleteFile(fileId: string): Promise<void> { await this._load(); return gapi.client.drive.files.delete({fileId}) .then((response) => response.result); } /** * Gets a list of files with the specified query. */ public static async listFiles(fileFields: string[], queryPredicates: string[], orderBy?: string[]): Promise<gapi.client.drive.File[]> { await this._load(); return gapi.client.drive.files.list({ fields: 'nextPageToken, files(' + fileFields.join(',') + ')', orderBy: orderBy ? orderBy.join(',') : '', // TODO: Implement paging. pageSize: 1000, q: queryPredicates.join(' and '), }) .then((response: HttpResponse<gapi.client.drive.ListFilesResponse>) => { return response.result.files; }, (response: HttpResponse<{error: Error}>) => { throw response.result.error; }); } /** * Get the file object associated with the given id. */ public static async getFile(fileId: string, fields?: string[]): Promise<gapi.client.drive.File> { await this._load(); const request: gapi.client.drive.GetFileRequest = { fileId, }; if (fields) { request.fields = fields.join(','); } return gapi.client.drive.files.get(request) .then((response: HttpResponse<gapi.client.drive.File>) => response.result, (response: HttpResponse<{error: Error}>) => { throw response.result.error; }); } /** * Get the file data associated with the given id, along with its contents * as a string. Returns an array of the file object and its contents. */ public static async getFileWithContent(id: string) : Promise<[gapi.client.drive.File, string | null]> { await this._load(); const accessToken = await GapiManager.auth.getAccessToken(); const xhrOptions: XhrOptions = { headers: {Authorization: 'Bearer ' + accessToken}, noCache: true, }; const file: gapi.client.drive.File = await ApiManager.sendRequestAsync( 'https://www.googleapis.com/drive/v2/files/' + id, xhrOptions, false); let content = null; if (file.downloadUrl) { content = await ApiManager.sendTextRequestAsync(file.downloadUrl, xhrOptions, false); } return [file, content]; } public static load(): Promise<void> { return this._load(); } private static _load(): Promise<void> { return GapiManager.auth.loadGapiAndScopes('drive', 'v3', GapiScopes.DRIVE); } }; public static bigquery = class { /** * Gets the list of BigQuery projects, returns a Promise. */ public static listProjects(pageToken?: string): Promise<gapi.client.HttpRequestFulfilled<gapi.client.bigquery.ListProjectsResponse>> { const request = { maxResults: 1000, pageToken, } as gapi.client.bigquery.ListProjectsRequest; return this._load() .then(() => gapi.client.bigquery.projects.list(request)); } /** * Gets the list of BigQuery datasets in the specified project, returns a Promise. * @param projectId * @param filter A label filter of the form label.<name>[:<value>], as described in * https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets/list */ public static listDatasets(projectId: string, filter: string, pageToken?: string): Promise<gapi.client.HttpRequestFulfilled<gapi.client.bigquery.ListDatasetsResponse>> { const request = { filter, maxResults: 1000, pageToken, projectId, } as gapi.client.bigquery.ListDatasetsRequest; return this._load() .then(() => gapi.client.bigquery.datasets.list(request)); } /** * Gets the list of BigQuery tables in the specified project and dataset, * returns a Promise. */ public static listTables(projectId: string, datasetId: string, pageToken?: string): Promise<gapi.client.HttpRequestFulfilled<gapi.client.bigquery.ListTablesResponse>> { const request = { datasetId, maxResults: 1000, pageToken, projectId, } as gapi.client.bigquery.ListTablesRequest; return this._load() .then(() => gapi.client.bigquery.tables.list(request)); } /** * Fetches table details from BigQuery */ public static getTableDetails(projectId: string, datasetId: string, tableId: string): Promise<gapi.client.HttpRequestFulfilled<gapi.client.bigquery.Table>> { const request = { datasetId, projectId, tableId, }; return this._load() .then(() => gapi.client.bigquery.tables.get(request)); } /** * Fetches table rows from BigQuery */ public static getTableRows(projectId: string, datasetId: string, tableId: string, maxResults: number): Promise<gapi.client.HttpRequestFulfilled<gapi.client.bigquery.ListTabledataResponse>> { const request = { datasetId, maxResults, projectId, tableId, }; return this._load() .then(() => gapi.client.bigquery.tabledata.list(request)); } private static _load(): Promise<void> { return GapiManager.auth.loadGapiAndScopes('bigquery', 'v2', GapiScopes.CLOUD); } }; public static resourceManager = class { /** * Returns a list of all projects from the resource manager API. It concatenates * all projects returned into one long list. */ public static async listAllProjects() { await this._load(); let nextPageToken = null; const allProjects: gapi.client.cloudresourcemanager.Project[] = []; do { const result: any = await gapi.client.request({ method: 'GET', params: { pageToken: nextPageToken, }, path: 'https://cloudresourcemanager.googleapis.com/v1/projects', }) .then((response) => response.result); allProjects.push(...result.projects); nextPageToken = result.nextPageToken; } while (nextPageToken); return allProjects; } private static _load(): Promise<void> { return GapiManager.auth.loadGapiAndScopes('cloudresourcemanager', 'v1', GapiScopes.CLOUD); } }; /** * The auth class is responsible for initializing authorization, including * loading the gapi code and any data needed for oauth. */ public static auth = GapiManager._initAuth(); // Use server auth if the user has requested it by manually setting a cookie. // In the dev console, when on a Datalab page, enter this command: // document.cookie="DATALAB_USE_SERVER_AUTH=1" private static _initAuth() { if (!!Utils.readCookie('DATALAB_USE_SERVER_AUTH')) { Utils.log.verbose('Using ServerAuth'); return new ServerAuth(); } else { Utils.log.verbose('Using ClientAuth'); return new ClientAuth(); } } }
the_stack
import * as fs from 'fs'; import {UnifiedPath} from './misc/unifiedpath'; import * as vscode from 'vscode'; import {Breakpoint, DebugSession, InitializedEvent, Scope, Source, StackFrame, StoppedEvent, TerminatedEvent, Thread, ContinuedEvent, CapabilitiesEvent, InvalidatedEvent} from 'vscode-debugadapter/lib/main'; import {DebugProtocol} from 'vscode-debugprotocol/lib/debugProtocol'; import {Labels} from './labels/labels'; import {Log} from './log'; import {Remote, RemoteBreakpoint} from './remotes/remotebase'; import {MemoryDumpView} from './views/memorydumpview'; import {MemoryRegisterView} from './views/memoryregisterview'; import {Settings, SettingsParameters} from './settings'; import {DisassemblyVar, ShallowVar, MemorySlotsVar, RegistersMainVar, RegistersSecondaryVar, StackVar, StructVar, MemDumpVar, ImmediateMemoryValue} from './variables/shallowvar'; import {Utility} from './misc/utility'; import {Z80RegisterHoverFormat, Z80RegistersClass, Z80Registers, } from './remotes/z80registers'; import {RemoteFactory} from './remotes/remotefactory'; import {ZxNextSpritesView} from './views/zxnextspritesview'; import {TextView} from './views/textview'; import {BaseView} from './views/baseview'; import {ZxNextSpritePatternsView} from './views/zxnextspritepatternsview'; import {MemAttribute} from './disassembler/memory'; import {Decoration} from './decoration'; import {ZSimulationView} from './remotes/zsimulator/zsimulationview'; import {ZSimRemote} from './remotes/zsimulator/zsimremote'; import {CpuHistoryClass, CpuHistory, StepHistory} from './remotes/cpuhistory'; import {StepHistoryClass} from './remotes/stephistory'; import {DisassemblyClass, Disassembly} from './misc/disassembly'; import {TimeWait} from './misc/timewait'; import {MemoryArray} from './misc/memoryarray'; import {MemoryDumpViewWord} from './views/memorydumpviewword'; import {ExpressionVariable} from './misc/expressionvariable'; import {RefList} from './misc/reflist'; import {PromiseCallbacks} from './misc/promisecallbacks'; import {Z80UnitTestRunner} from './z80unittests/z80unittestrunner'; import {DiagnosticsHandler} from './diagnosticshandler'; /// State of the debug adapter. enum DbgAdapterState { NORMAL, // Normal debugging UNITTEST, // Debugging or running unit tests } /** * The Emulator Debug Adapter. * It receives the requests from vscode and sends events to it. */ export class DebugSessionClass extends DebugSession { /// The state of the debug adapter (unit tests or not) protected static state = DbgAdapterState.NORMAL; /// Functions set in 'unitTestsStart'. Will be called after debugger /// is started and initialized. //protected static unitTestStartResolve: ((da: DebugSessionClass) => void) | undefined; //protected static unitTestStartReject: ((reason: any) => void) | undefined; protected static unitTestsStartCallbacks: PromiseCallbacks<DebugSessionClass> | undefined; /// The address queue for the disassembler. This contains all stepped addresses. protected dasmAddressQueue = new Array<number>(); /// The text document used for the temporary disassembly. protected disasmTextDoc: vscode.TextDocument; /// A list for the VARIABLES (references) protected listVariables = new RefList<ShallowVar>(); // A list with the expressions used in the WATCHes panel and the Expressions section in the VARIABLES pane. protected constExpressionsList = new Map<string, ExpressionVariable>(); /// The disassembly that is shown in the VARIABLES section. protected disassemblyVar: DisassemblyVar; /// The local stack that is shown in the VARIABLES section. protected localStackVar: StackVar; /// Only one thread is supported. public static THREAD_ID = 1; /// Counts the number of stackTraceRequests. protected stackTraceResponses = new Array<DebugProtocol.StackTraceResponse>(); /// This array contains functions which are pushed on an emit (e.g. 'historySpot', not 'coverage') /// and which are executed after a stackTrace. /// The reason is that the disasm.asm file will not exist before and emits /// regarding this file would be lost. protected delayedDecorations = new Array<() => void>(); /// Set to true if pause has been requested. /// Used in stepOver. protected pauseRequested = false; /// With pressing keys for stepping (i.e. F10, F11) it is possible to /// e.g. enter the 'stepInRequest' while the previous stepInRequest is not yet finished. /// I.e. before a StoppedEvent is sent. With the GUI this is not possible /// since the GUI disables the stepIn button. But it seems that /// key presses are still allowed. /// This variable here is set every time a step (or similar) is done. /// And reset when the function is finished. Should some other similar /// request happen a response is send but the request is ignored otherwise. protected processingSteppingRequest = false; /// This is saved text that could not be printed yet because // the debug console was not there. // It is printed a soon as the console appears. protected debugConsoleSavedText: string; /// The text written to console on event 'debug_console' is indented by this amount. protected debugConsoleIndentation = " "; /** * Creates a new debug adapter that is used for one debug session. * We configure the default implementation of a debug adapter here. */ public constructor() { super(); // Init line numbering this.setDebuggerLinesStartAt1(false); this.setDebuggerColumnsStartAt1(false); } /** * Start the unit tests. * @param configName The debug launch configuration name. * @param handler * @returns If it was not possible to start unit test: false. */ public static unitTestsStart(configName: string): Promise<DebugSessionClass> { // Return if currently a debug session is running if (vscode.debug.activeDebugSession) throw Error("There is already an active debug session."); if (this.state != DbgAdapterState.NORMAL) throw Error("Debugger state is wrong."); // Need to find the corresponding workspace folder const rootFolder = Utility.getRootPath(); const rootFolderUri = vscode.Uri.file(rootFolder); const workspaceFolder = vscode.workspace.getWorkspaceFolder(rootFolderUri); Utility.assert(workspaceFolder); // Start debugger this.state = DbgAdapterState.UNITTEST; vscode.debug.startDebugging(workspaceFolder, configName); // The promise is fulfilled after launch of the debugger. return new Promise<DebugSessionClass>((resolve, reject) => { new PromiseCallbacks<DebugSessionClass>(this, 'unitTestsStartCallbacks', resolve, reject); // NOSONAR }); } /** * Used to show a warning to the user. * @param message The message to show. */ private showWarning(message: string) { Log.log(message) vscode.window.showWarningMessage(message); } /** * Used to show an error to the user. * @param message The message to show. */ private showError(message: string) { Log.log(message); vscode.window.showErrorMessage(message); } /** * Exit from the debugger. * Call Remote.terminate instead. The debug adapter listens for the * 'terminate' event and will execute the 'terminate' function. * @param message If defined the message is shown to the user as error. */ protected terminate(message?: string) { // Make sure every decoration gets output (important for debugging unit tests) this.processDelayedDecorations(); if (message) this.showError(message); Log.log("Exit debugger!"); // Remove all listeners this.removeAllListeners(); // Don't react on events anymore this.sendEvent(new TerminatedEvent()); } /** * Overload sendEvent to logger. */ public sendEvent(event: DebugProtocol.Event): void { Log.log(`<-: ${event.event}(${JSON.stringify(event.body)})`); super.sendEvent(event); } /** * Overload sendRequest to logger. */ public sendRequest(command: string, args: any, timeout: number, cb: (response: DebugProtocol.Response) => void): void { Log.log(`<-: ${command}(${JSON.stringify(args)})`); super.sendRequest(command, args, timeout, (resp) => { // Response Log.log(`->: ${resp.command}(${JSON.stringify(resp.body)})`); // callback cb(resp); }); } /** * Overload sendResponse to logger. */ public sendResponse(response: DebugProtocol.Response): void { Log.log(`<-: ${response.command}(${JSON.stringify(response.body)})`); super.sendResponse(response); } /** * Writes all requests to the logger. * @param request The DebugProtocol request. */ protected dispatchRequest(request: DebugProtocol.Request): void { Log.log(`->: ${request.command}(${JSON.stringify(request.arguments)})`); super.dispatchRequest(request); } /** * DebugAdapter disconnects. * End forcefully. * Is called * - when user presses red square * - when the ZEsarUX socket connection is terminated * Not called: * - If user presses circled arrow/restart. */ protected async disconnectRequest(response: DebugProtocol.DisconnectResponse, args: DebugProtocol.DisconnectArguments): Promise<void> { // Disconnect Remote etc. await this.disconnectAll(); // Send response this.sendResponse(response); } /** * Disconnects Remote, listeners, views. * Is called * - when user presses red square * - when the user presses relaunch (circled arrow/restart) * - when the ZEsarUX socket connection is terminated */ protected async disconnectAll(): Promise<void> { // Close views, e.g. register memory view BaseView.staticCloseAll(); this.removeListener('update', BaseView.staticCallUpdateFunctions); // Stop machine this.removeAllListeners(); // Don't react on events anymore // Disconnect await Remote?.disconnect(); // Clear the history instance CpuHistoryClass.removeCpuHistory(); // Clear Remote RemoteFactory.removeRemote(); // Also disposes // Remove disassembly text editor. vscode does not support closing directly, thus this hack: if (this.disasmTextDoc) { vscode.window.showTextDocument(this.disasmTextDoc.uri, {preview: true, preserveFocus: false}) .then(() => { return vscode.commands.executeCommand('workbench.action.closeActiveEditor'); }); } // Clear all decorations if (DebugSessionClass.state == DbgAdapterState.UNITTEST) { // Cancel unit tests await Z80UnitTestRunner.cancelUnitTests(); // Clear decoration Decoration?.clearAllButCodeCoverageDecorations(); } else { Decoration?.clearAllDecorations(); } DebugSessionClass.state = DbgAdapterState.NORMAL; } /** * 'initialize' request. * Respond with supported features. */ protected async initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): Promise<void> { //const dbgSession = vscode.debug.activeDebugSession; // build and return the capabilities of this debug adapter: response.body = response.body || {}; // the adapter implements the configurationDoneRequest. response.body.supportsConfigurationDoneRequest = false; // Is done in launchRequest: //response.body.supportsStepBack = true; // Maybe terminated on error response.body.supportTerminateDebuggee = true; // The PC value might be changed. //response.body.supportsGotoTargetsRequest = true; // I use my own "Move Program Counter to Cursor". // GotoTargetsRequest would be working now, but not in all cases. // If the file is not recognized yet. It does not work. // Thought it has something to do with loadSourcesRequest but it doesn't. response.body.supportsGotoTargetsRequest = false; // Support hovering over values (registers) response.body.supportsEvaluateForHovers = true; // Support changing of variables (e.g. registers) response.body.supportsSetVariable = true; // Supports conditional breakpoints response.body.supportsConditionalBreakpoints = true; // Handles debug 'Restart'. // If set to false the vscode restart button still occurs and // vscode internally calls disconnect and launchRequest. response.body.supportsRestartRequest = false; // Allows to set values in the watch pane. response.body.supportsSetExpression = true; this.sendResponse(response); // Note: The InitializedEvent will be send when the socket connection has been successful. Afterwards the breakpoints are set. } /** * Prints text to the debug console. */ protected debugConsoleAppend(text: string) { if (vscode.debug.activeDebugSession) vscode.debug.activeDebugConsole.append(text); else { // Save text this.debugConsoleSavedText += text; } } protected debugConsoleAppendLine(text: string) { this.debugConsoleAppend(text + '\n'); } /** * Called after 'initialize' request. * Loads the list file and connects the socket (if necessary). * Initializes the remote. * When the remote is connected and initialized an 'initialized' event * is sent. * @param response * @param args */ protected scopes: Array<Scope>; protected async launchRequest(response: DebugProtocol.LaunchResponse, args: SettingsParameters) { try { // Clear any diagnostics DiagnosticsHandler.clear(); // Initialize BaseView.staticInit(); ZxNextSpritePatternsView.staticInit(); // Action on changed value (i.e. when the user changed a value // vscode is informed and will e.g. update the watches.) BaseView.onChange(() => { // This ['variables'] seems to work: // See https://github.com/microsoft/debug-adapter-protocol/issues/171#issuecomment-754753935 this.sendEvent(new InvalidatedEvent(['variables'])); // Note: Calling this.memoryHasBeenChanged would result in an infinite loop. }); // Save args Settings.launch = Settings.Init(args); Settings.CheckSettings(); Utility.setRootPath(Settings.launch.rootFolder); // Persistent variable references this.listVariables.clear(); this.constExpressionsList.clear(); this.disassemblyVar = new DisassemblyVar(); this.disassemblyVar.count = Settings.launch.disassemblerArgs.numberOfLines; this.localStackVar = new StackVar(); this.scopes = [ new Scope("Registers", this.listVariables.addObject(new RegistersMainVar())), new Scope("Registers 2", this.listVariables.addObject(new RegistersSecondaryVar())), new Scope("Disassembly", this.listVariables.addObject(this.disassemblyVar)), new Scope("Memory Banks", this.listVariables.addObject(new MemorySlotsVar())), new Scope("Local Stack", this.listVariables.addObject(this.localStackVar)) ]; } catch (e) { // Some error occurred response.success = false; response.message = e.message; this.sendResponse(response); return; } // Register to get a note when debug session becomes active this.debugConsoleSavedText = ''; vscode.debug.onDidChangeActiveDebugSession(dbgSession => { if (dbgSession) { vscode.debug.activeDebugConsole.append(this.debugConsoleSavedText); this.debugConsoleSavedText = ''; } }); // Launch emulator await this.launch(response); } /** * Launches the emulator. Is called from launchRequest. * @param response */ protected async launch(response: DebugProtocol.Response) { // Setup the disassembler DisassemblyClass.createDisassemblyInstance(); // Init this.processingSteppingRequest = false; // Register to update the memoryview. this.removeListener('update', BaseView.staticCallUpdateFunctions); this.on('update', BaseView.staticCallUpdateFunctions); // Start the emulator and the connection. const msg = await this.startEmulator(); if (msg) { response.message = msg; response.success = (msg == undefined); } else { // Check if reverse debugging is enabled and send capabilities if (Settings.launch.history.reverseDebugInstructionCount > 0) { // Enable reverse debugging this.sendEvent(new CapabilitiesEvent({supportsStepBack: true})); } } this.sendResponse(response); } /** * Starts the emulator and sets up everything for setup after * connection is up and running. * @returns A Promise with an error text or undefined if no error. */ protected async startEmulator(): Promise<string | undefined> { try { // Init labels Labels.init(Settings.launch.smallValuesMaximum); } catch (e) { // Some error occurred Remote.terminate('Labels: ' + e.message); return "Error while initializing labels."; } // Reset all decorations Decoration.clearAllDecorations(); // Create the registers Z80RegistersClass.createRegisters(); // Make sure the history is cleared CpuHistoryClass.setCpuHistory(undefined); // Create the Remote RemoteFactory.createRemote(Settings.launch.remoteType); Remote.on('warning', message => { // Some problem occurred this.showWarning(message); }); Remote.on('debug_console', message => { // Show the message in the debug console this.debugConsoleIndentedText(message); }); Remote.once('error', err => { // Some error occurred Remote.disconnect(); this.terminate(err.message); }); Remote.once('terminated', message => { // Emulator has been terminated (e.g. by unit tests) this.terminate(message); }); // Check if a cpu history object has been created by the Remote. if (!(CpuHistory as any)) { // If not create a lite (step) history CpuHistoryClass.setCpuHistory(new StepHistoryClass()); } // Load files try { // Reads the list file and also retrieves all occurrences of WPMEM, ASSERTION and LOGPOINT. Remote.readListFiles(Settings.launch); } catch (err) { // Some error occurred during loading, e.g. file not found. // this.terminate(err.message); DebugSessionClass.unitTestsStartCallbacks?.reject(err); return err.message; } Remote.on('coverage', coveredAddresses => { // coveredAddresses: Only diff of addresses since last step-command. this.delayedDecorations.push(() => { // Covered addresses (since last break) have been sent Decoration.showCodeCoverage(coveredAddresses); }); }); StepHistory.on('revDbgHistory', addresses => { // addresses: The addresses (all) of the reverse history in the right order. this.delayedDecorations.push(() => { // Reverse debugging history addresses Decoration.showRevDbgHistory(addresses); }); }); StepHistory.on('historySpot', (startIndex, addresses, registers) => { // addresses: All addresses of the history spot. this.delayedDecorations.push(() => { // Short history addresses Decoration.showHistorySpot(startIndex, addresses, registers); }); }); return new Promise<undefined>(async (resolve, reject) => { // For now there is no unsuccessful (reject) execution Remote.once('initialized', async (text) => { // Print text if available, e.g. "dbg_uart_if initialized". if (text) { this.debugConsoleAppendLine(text); } // Get initial registers await Remote.getRegistersFromEmulator(); await Remote.getCallStackFromEmulator(); // Initialize Cpu- or StepHistory. if (!StepHistory.decoder) StepHistory.decoder = Z80Registers.decoder; StepHistory.init(); // Run user commands after load. for (const cmd of Settings.launch.commandsAfterLaunch) { this.debugConsoleAppendLine(cmd); try { const outText = await this.evaluateCommand(cmd); this.debugConsoleAppendLine(outText); } catch (err) { // Some problem occurred const output = "Error while executing '" + cmd + "' in 'commandsAfterLaunch': " + err.message; this.showWarning(output); } } // Special handling for custom code if (Remote instanceof ZSimRemote) { // Start custom code (if not unit test) const zsim = Remote; if (DebugSessionClass.state == DbgAdapterState.NORMAL) { // Special handling for zsim: Re-init custom code. zsim.customCode?.execute(); } // At the end, if remote type == ZX simulator, open its window. // Note: it was done this way and not in the Remote itself, otherwise // there would be a dependency in RemoteFactory to vscode which in turn // makes problems for the unit tests. // Adds a window that displays the ZX screen. new ZSimulationView(zsim); // NOSONAR } // Socket is connected, allow setting breakpoints this.sendEvent(new InitializedEvent()); // Respond resolve(undefined); // Check if program should be automatically started StepHistory.clear(); if (DebugSessionClass.unitTestsStartCallbacks) { DebugSessionClass.unitTestsStartCallbacks.resolve(this); } else { if (Settings.launch.startAutomatically) { setTimeout(() => { // Delay call because the breakpoints are set afterwards. this.handleRequest(undefined, async () => { // Normal operation return this.remoteContinue(); }); }, 500); } else { // Break this.sendEvent(new StoppedEvent('stop on start', DebugSessionClass.THREAD_ID)); } } }); // Initialize Remote try { await Remote.init(); } catch (e) { // Some error occurred const error = e.message || "Error"; Remote.terminate('Init remote: ' + error); reject(e); DebugSessionClass.unitTestsStartCallbacks?.reject(e); } }); } /** * The breakpoints are set for a path (file). * @param response * @param args lines=array with line numbers. source.path=the file path */ protected async setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): Promise<void> { const path = UnifiedPath.getUnifiedPath(<string>args.source.path); // convert breakpoints const givenBps = args.breakpoints || []; const bps = new Array<RemoteBreakpoint>(); for (const bp of givenBps) { try { const log = Remote.evalLogMessage(bp.logMessage); const mbp: RemoteBreakpoint = { bpId: 0, filePath: path, lineNr: this.convertClientLineToDebugger(bp.line), address: -1, // not known yet condition: (bp.condition) ? bp.condition : '', log: log }; bps.push(mbp); } catch (e) { // Show error this.showWarning(e.message); } } // Set breakpoints for the file. const currentBreakpoints = await Remote.setBreakpoints(path, bps); const source = this.createSource(path); // Now match all given breakpoints with the available. const vscodeBreakpoints = givenBps.map(gbp => { // Search in current list let foundCbp; const lineNr = gbp.line; for (const cbp of currentBreakpoints) { const cLineNr = this.convertDebuggerLineToClient(cbp.lineNr); if (cLineNr == lineNr) { foundCbp = cbp; break; } } // Create vscode breakpoint with verification const verified = (foundCbp != undefined) && (foundCbp.address >= 0); const bp = new Breakpoint(verified, lineNr, 0, source); if (foundCbp && foundCbp.address >= 0) { // Add address to source name. const addrString = Utility.getLongAddressString(foundCbp.address); // Add hover text let txt = addrString; const labels = Labels.getLabelsForNumber64k(foundCbp.address); labels.forEach(lbl => txt += '\n' + lbl); (bp as any).message = txt; } // Additional print warning if not verified if (!verified) { const text = JSON.stringify(bp); this.debugConsoleAppendLine('Unverified breakpoint: ' + text); if (foundCbp && foundCbp.error) { this.debugConsoleAppendLine(' Additional info: ' + foundCbp.error); } } return bp; }); // send back the actual breakpoint positions response.body = { breakpoints: vscodeBreakpoints }; this.sendResponse(response); } /** * Returns the one and only "thread". */ protected async threadsRequest(response: DebugProtocol.ThreadsResponse): Promise<void> { // Just return a default thread. response.body = { threads: [ new Thread(DebugSessionClass.THREAD_ID, "thread_default") ] }; this.sendResponse(response); } /** * Creates a source reference from the filePath. * @param filePath * @returns undefined if filePath is ''. */ private createSource(filePath: string): Source | undefined { if (filePath.length == 0) return undefined; const uFilePath = UnifiedPath.getUnifiedPath(filePath); const fname = UnifiedPath.basename(uFilePath); const debPath = this.convertDebuggerPathToClient(uFilePath); const uDebPath = UnifiedPath.getUnifiedPath(debPath); return new Source(fname, uDebPath, undefined, undefined, undefined); } /** * Returns the stack frames. */ protected async stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): Promise<void> { // vscode sometimes sends 2 stack trace requests one after the other. Because the lists are cleared this can lead to race conditions. this.stackTraceResponses.push(response); if (this.stackTraceResponses.length > 1) return; // Stack frames const sfrs = new Array<StackFrame>(); // Need to check if disassembly is required. let doDisassembly = false; const fetchAddresses = new Array<number>(); let frameCount = 0; // Get the call stack trace. let callStack; //let slots; if (StepHistory.isInStepBackMode()) { // Get callstack callStack = StepHistory.getCallStack(); } else { // Get callstack callStack = await Remote.getCallStackCache(); } // Go through complete call stack and get the sources. // If no source exists than get a hexdump and disassembly later. frameCount = callStack.length; for (let index = frameCount - 1; index >= 0; index--) { const frame = callStack[index]; // Get file for address const addr = frame.addr; const file = Labels.getFileAndLineForAddress(addr); // Store file, if it does not exist the name is empty const src = this.createSource(file.fileName); const lineNr = (src) ? this.convertDebuggerLineToClient(file.lineNr) : 0; const sf = new StackFrame(index + 1, frame.name, src, lineNr); sfrs.push(sf); // Create array with addresses that need to be fetched for disassembly if (!sf.source) { const csFrame = callStack[index]; fetchAddresses.push(csFrame.addr); } } // Create memory array. const fetchSize = 100; // N bytes const memArray = new MemoryArray(); for (const fetchAddress of fetchAddresses) { memArray.addRange(fetchAddress, fetchSize); // assume 100 bytes each } // Add some more memory from the history const fetchHistorySize = 20; const historyAddresses = new Array<number>(); for (let i = 1; i <= 10; i++) { const addr = StepHistory.getPreviousAddress(i); if (addr == undefined) break; // Add address memArray.addRange(addr, fetchHistorySize); // assume at least 4 bytes, assume some more to cover small jumps historyAddresses.unshift(addr); } // Check if we need to fetch any dump. for (const range of memArray.ranges) { const data = await Remote.readMemoryDump(range.address, range.size); range.data = data; } // Check if we need to fetch any dump. const fetchAddressesCount = fetchAddresses.length; if (!doDisassembly) { const checkSize = 40; // Needs to be smaller than fetch-size in order not to do a disassembly too often. if (fetchAddressesCount > 0) { // Now get hex-dumps for all non existing sources. for (let index = 0; index < fetchAddressesCount; index++) { // So fetch a memory dump const fetchAddress = fetchAddresses[index]; // Note: because of self-modifying code it may have changed // since it was fetched at the beginning. // Check if memory changed. for (let k = 0; k < checkSize; k++) { const val = Disassembly.memory.getValueAt((fetchAddress + k) & 0xFFFF); const memAttr = Disassembly.memory.getAttributeAt(fetchAddress + k); const newVal = memArray.getValueAtAddress((fetchAddress + k) & 0xFFFF); if ((val != newVal) || (memAttr == MemAttribute.UNUSED)) { doDisassembly = true; break; } } } } } // Check if a new address was used. for (let i = 0; i < fetchAddressesCount; i++) { // The current PC is for sure a code label. const addr = fetchAddresses[i]; if (this.dasmAddressQueue.indexOf(addr) < 0) this.dasmAddressQueue.unshift(addr); // Check if this requires a disassembly if (!doDisassembly) { const memAttr = Disassembly.memory.getAttributeAt(addr & 0xFFFF); if (!(memAttr & MemAttribute.CODE_FIRST)) doDisassembly = true; // If memory was not the start of an opcode. } } // Check if disassembly is required. if (doDisassembly) { // Do disassembly. /* const prevAddresses=new Array<number>(); const prevData=new Array<Uint8Array>(); // Check if history data is available. //if (StepHistory.isInStepBackMode()) { // Add a few more previous addresses if available for (let i=1; i<=10; i++) { const addr=StepHistory.getPreviousAddress(i); if (addr==undefined) break; // Add address prevAddresses.unshift(addr); const data=await Remote.readMemoryDump(addr, 4); // An opcode is max 4 bytes long prevData.unshift(data); } } */ // Create text document const absFilePath = DisassemblyClass.getAbsFilePath(); const uri = vscode.Uri.file(absFilePath); const editCreate = new vscode.WorkspaceEdit(); editCreate.createFile(uri, {overwrite: true}); await vscode.workspace.applyEdit(editCreate); const textDoc = await vscode.workspace.openTextDocument(absFilePath); // Store uri this.disasmTextDoc = textDoc; // Initialize disassembly Disassembly.initWithCodeAdresses([...historyAddresses, ...fetchAddresses], memArray.ranges); // Disassemble Disassembly.disassemble(); // Read data const text = Disassembly.getDisassemblyText(); // Get all source breakpoints of the disassembly file. const bps = vscode.debug.breakpoints; const disSrc = this.disasmTextDoc.uri.toString(); const sbps = bps.filter(bp => { if (bp.hasOwnProperty('location')) { const sbp = bp as vscode.SourceBreakpoint; const sbpSrc = sbp.location.uri.toString(); if (sbpSrc == disSrc) return true; } return false; }) as vscode.SourceBreakpoint[]; // Check if any breakpoint const changedBps = new Array<vscode.SourceBreakpoint>(); if (sbps.length > 0) { // Previous text const prevTextLines = this.disasmTextDoc.getText().split('\n'); // Loop all source breakpoints to compute changed BPs for (const sbp of sbps) { const lineNr = sbp.location.range.start.line; const line = prevTextLines[lineNr]; const addr = parseInt(line, 16); if (!isNaN(addr)) { // Get line number const nLineNr = Disassembly.getLineForAddress(addr) || -1; // Create breakpoint const nLoc = new vscode.Location(this.disasmTextDoc.uri, new vscode.Position(nLineNr, 0)); const cbp = new vscode.SourceBreakpoint(nLoc, sbp.enabled, sbp.condition, sbp.hitCondition, sbp.logMessage); // Store changedBps.push(cbp); } } } // Remove all old breakpoints. vscode.debug.removeBreakpoints(sbps); // Create and apply one replace edit const editReplace = new vscode.WorkspaceEdit(); editReplace.replace(this.disasmTextDoc.uri, new vscode.Range(0, 0, this.disasmTextDoc.lineCount, 0), text); await vscode.workspace.applyEdit(editReplace); // Save after edit (to be able to set breakpoints) await this.disasmTextDoc.save(); // Add all new breakpoints. vscode.debug.addBreakpoints(changedBps); // If disassembly text editor is open, then show decorations const editors = vscode.window.visibleTextEditors; for (const editor of editors) { if (editor.document == this.disasmTextDoc) { Decoration.setDisasmCoverageDecoration(editor); } } /* // Show document and get editor const editor=await vscode.window.showTextDocument(this.disasmTextDoc); // Update decorations if (editor) { Decoration.SetDisasmCoverageDecoration(editor); } */ } // Get lines for addresses and send response. // Determine line numbers (binary search) if (frameCount > 0) { const absFilePath = DisassemblyClass.getAbsFilePath(); const src = this.createSource(absFilePath) as Source; let indexDump = 0; for (let i = 0; i < frameCount; i++) { const sf = sfrs[i]; if (sf.source) continue; // Get line number for stack address const addr = fetchAddresses[indexDump]; // Get line number const foundLine = Disassembly.getLineForAddress(addr) || -1 const lineNr = this.convertDebuggerLineToClient(foundLine); // Store sf.source = src; sf.line = lineNr; // Next indexDump++; } } // Send as often as there have been requests while (this.stackTraceResponses.length > 0) { const resp = this.stackTraceResponses[0]; this.stackTraceResponses.shift(); resp.body = {stackFrames: sfrs, totalFrames: 1}; this.sendResponse(resp); } // At the end of the stack trace request the collected decoration events // are executed. This is because the disasm.asm did not exist before und thus // events like 'historySpot' would be lost. // Note: codeCoverage is handled differently because it is not sent during // step-back. this.processDelayedDecorations(); } /** * This is called at the end of a stack trace request btu also when a unit test case was finished debugging. * Writes everything in 'delayedDecorations' into the decorations. */ protected processDelayedDecorations() { for (const func of this.delayedDecorations) func(); this.delayedDecorations.length = 0; } /** * Returns the different scopes. E.g. 'Disassembly' or 'Registers' that are shown in the Variables area of vscode. * @param response * @param args */ protected async scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): Promise<void> { //this.listVariables.tmpList.clear(); // Clear temporary list. const frameId = args.frameId; //const frame = this.listFrames.getObject(frameId); let frame; if (StepHistory.isInStepBackMode()) frame = StepHistory.getCallStack().getObject(frameId); else { await Remote.getCallStackCache(); // make sure listFrames exist frame = Remote.getFrame(frameId); } if (!frame) { // No frame found, send empty response response.body = {scopes: []}; this.sendResponse(response); return; } // Set disassembly address this.disassemblyVar.address = frame.addr & 0xFFFF; // Create variable object for the stack this.localStackVar.setFrameAddress(frame.stack, frame.stackStartAddress); // Send response response.body = {scopes: this.scopes}; this.sendResponse(response); } /** * Returns the variables for the scopes (e.g. 'Disassembly' or 'Registers') * @param response * @param args */ protected async variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): Promise<void> { // Get the associated variable object const ref = args.variablesReference; const varObj = this.listVariables.getObject(ref); // Check if object exists if (varObj) { // Get contents const varList = await varObj.getContent(args.start, args.count); response.body = {variables: varList}; } else { // Return empty list response.body = {variables: new Array<DebugProtocol.Variable>()}; } this.sendResponse(response); } /** * Decorates the current PC source line with a reason. * @param "Breakpoint fired: PC=811EH" or undefined (prints nothing) */ public decorateBreak(breakReason: string) { if (!breakReason) return; // Get PC const pc = Remote.getPCLong(); Decoration.showBreak(pc, breakReason); } /** * This method is called before a step (stepOver, stepInto, stepOut, * continue, stepBack, etc.) is called. */ protected startProcessing() { // Start processing this.processingSteppingRequest = true; // Reset pause request this.pauseRequested = false; // Clear decorations Decoration.clearBreak(); // Do the same for the Remote Remote.startProcessing(); } /** * This method is called after a step (stepOver, stepInto, stepOut, * continue, stepBack, etc.) is called. */ protected stopProcessing() { // Stop processing this.processingSteppingRequest = false; // Do the same for the Remote Remote.stopProcessing(); } /** * vscode requested 'continue'. * @param response * @param args */ public async continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): Promise<void> { this.handleRequest(response, async () => { let event; // Check for reverse debugging. if (StepHistory.isInStepBackMode()) { await this.startStepInfo('Continue'); // Continue const breakReason = await StepHistory.continue(); // Check for output. if (breakReason) { this.debugConsoleIndentedText(breakReason); // Show break reason this.decorateBreak(breakReason); } // Send event event = new StoppedEvent('step', DebugSessionClass.THREAD_ID); } else { // Normal operation event = await this.remoteContinue(); } // Return return event; }); } /** * Calls 'continue' (run) on the remote (emulator). * Called at the beginning (startAutomatically) and from the * vscode UI (continueRequest). */ public async remoteContinue(): Promise<StoppedEvent> { await this.startStepInfo('Continue'); Decoration.clearBreak(); StepHistory.clear(); const breakReasonString = await Remote.continue(); // It returns here not immediately but only when a breakpoint is hit or pause is requested. // Safety check on termination if (Remote == undefined) return new StoppedEvent('exception', DebugSessionClass.THREAD_ID); // Display break reason if (breakReasonString) { // Send output event to inform the user about the reason this.debugConsoleIndentedText(breakReasonString); // Use reason for break-decoration. this.decorateBreak(breakReasonString); } // Display T-states and time await this.endStepInfo(); // Check if in unit test mode if (DebugSessionClass.state == DbgAdapterState.UNITTEST) { const finished = await Z80UnitTestRunner.dbgCheckUnitTest(breakReasonString); if (!finished) { this.sendEventBreakAndUpdate(); } // Send no further break return undefined as any; } // Send break return new StoppedEvent('break', DebugSessionClass.THREAD_ID); } /** * Is called by unit tests to simulate a 'break'. */ public async sendEventBreakAndUpdate(): Promise<void> { // Update memory dump etc. this.update(); // Send event this.sendEvent(new StoppedEvent('break', DebugSessionClass.THREAD_ID)); } /** * Sends a continued event to update the UI. */ public sendEventContinued() { // Send event this.sendEvent(new ContinuedEvent(DebugSessionClass.THREAD_ID)); } /** * vscode requested 'pause'. * @param response * @param args */ protected async pauseRequest(response: DebugProtocol.PauseResponse, args: DebugProtocol.PauseArguments): Promise<void> { try { this.pauseRequested = true; // Pause the remote or the history if (StepHistory.isInStepBackMode()) StepHistory.pause(); else await Remote.pause(); } catch (e) { this.showError(e.message); } // Response this.sendResponse(response); } /** * vscode requested 'reverse continue'. * @param response * @param args */ protected async reverseContinueRequest(response: DebugProtocol.ReverseContinueResponse, args: DebugProtocol.ReverseContinueArguments): Promise<void> { this.handleRequest(response, async () => { // Output await this.startStepInfo('Reverse-Continue', true); // Reverse continue const breakReason = await StepHistory.reverseContinue(); // Check for output. if (breakReason) { this.debugConsoleIndentedText(breakReason); // Show break reason this.decorateBreak(breakReason); } // Send event return new StoppedEvent('break', DebugSessionClass.THREAD_ID); }, 100); } /** * Is called by all request (step, stepInto, continue, etc.). * This handles the display in the vscode UI. * If the command can be handled in a short amount of time (e.g. in 1 sec) * then the response is sent after the command. * When the response is received by vscode it changes the current highlighted line * into an un-highlighted state and shows the 'pause' button. * I.e. for short commands this could lead to flickering, but if the * UI is changed after command no flickering appears. * On the other hand, if a command takes too long it is necessary to show * the 'pause' button. So a timer assures that the response is sent after a timeout. * The function takes care that the response is sent only once. */ protected handleRequest(response: any, command: () => Promise<StoppedEvent>, responseTime = 750) { if (this.processingSteppingRequest) { // Response is sent immediately if already something else going on this.sendResponse(response); return; } // Start processing this.startProcessing(); // Start timer to send response for long running commands let respTimer: NodeJS.Timeout | undefined; if (response) { respTimer = setTimeout(() => { // Send response after a short while so that the vscode UI can show the break button respTimer = undefined; this.sendResponse(response); }, responseTime); // 1 s } // Start command (async () => { const event = await command(); // Note: On termination/restart Remote could be undefined if (!Remote) return; // End processing this.stopProcessing(); // Update memory dump etc. (also in reverse debug because of the register display) this.update({step: true}); // Show decorations //await Remote.getRegisters(); StepHistory.emitHistory(); // Send response if (respTimer) { // If not already done before clearTimeout(respTimer); this.sendResponse(response); } // Send event if (event) this.sendEvent(event); })(); } /** * vscode requested 'step over'. * @param response Sends the response. If undefined nothing is sent. Used by Unit Tests. * @param args */ protected async nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): Promise<void> { this.handleRequest(response, async () => { await this.startStepInfo('Step-Over'); // T-states info and lite history const stepBackMode = StepHistory.isInStepBackMode(); // The stepOver should also step over macros, fake instructions, several instruction on the same line. // Therefore the stepOver is repeated until really a new // file/line correspondents to the PC value. //Remote.getRegisters(); const prevPc = Remote.getPCLong(); const prevFileLoc = Labels.getFileAndLineForAddress(prevPc); let i = 0; let breakReason; const timeWait = new TimeWait(500, 200, 100); while (true) { i++; // Give vscode some time for a break await timeWait.waitAtInterval(); // Print instruction const instr = await this.getCurrentInstruction(i); if (instr) this.debugConsoleIndentedText(instr); // Check for reverse debugging. if (stepBackMode) { // Step-Over breakReason = await StepHistory.stepOver(); } else { // Normal Step-Over breakReason = await Remote.stepOver(); } // Check for pause request if (this.pauseRequested) { breakReason = "Manual break"; } // Leave loop in case there is a break reason if (breakReason) { // Stop break; } // Get new file/line location //await Remote.getRegisters(); const pc = Remote.getPCLong(); const nextFileLoc = Labels.getFileAndLineForAddress(pc); // Compare with start location if (prevFileLoc.fileName == '') break; if (nextFileLoc.lineNr != prevFileLoc.lineNr) break; if (nextFileLoc.fileName != prevFileLoc.fileName) break; } // Check for output. if (breakReason) { // Show break reason this.debugConsoleIndentedText(breakReason); this.decorateBreak(breakReason); } // Print T-states if (!stepBackMode) { // Display T-states and time await this.endStepInfo(); } // Check if in unit test mode if (DebugSessionClass.state == DbgAdapterState.UNITTEST) { await Z80UnitTestRunner.dbgCheckUnitTest(breakReason); } // Send event return new StoppedEvent('step', DebugSessionClass.THREAD_ID); }, 100); } /** * Starts to print the step info. Use in conjunction with 'endStepInfo'. * Resets the t-states. * Print text to debug console. * Adds prefix "Time-travel " if in reverse debug mode or alwaysHistorical is true. * Adds suffix " (Lite)" if no true stepping is done. * @param text E.g. "Step-into" * @param alwaysHistorical Prints prefix "Time-travel " even if not (yet) in back step mode. */ protected async startStepInfo(text?: string, alwaysHistorical = false): Promise<void> { //Log.log('startStepInfo ->'); // Print text const stepBackMode = StepHistory.isInStepBackMode() || alwaysHistorical; if (text) { if (stepBackMode) { text = 'Time-travel ' + text; if (!(CpuHistory as any)) text += ' (Lite)'; } this.debugConsoleAppendLine(text); } // If not in step back mode if (!stepBackMode) { // Checks if lite history is used. // If so, store the history. if (!(CpuHistory as any)) { // Store as (lite step history) const regsCache = Z80Registers.getCache(); StepHistory.pushHistoryInfo(regsCache); const callStack = await Remote.getCallStackCache(); StepHistory.pushCallStack(callStack); } // Reset t-states counter await Remote.resetTstates(); } //Log.log('startStepInfo <-'); } /** * Prints a text, the disassembly and the used T-states and time to the debug console. * Assumes that something like "StepInto" has been printed before. * @param disasm The corresponding disassembly. */ protected async endStepInfo(): Promise<void> { // Get used T-states const tStates = await Remote.getTstates(); // Display T-states and time let tStatesText; if (tStates) { tStatesText = 'T-States: ' + tStates; // Get frequency const cpuFreq = await Remote.getCpuFrequency(); if (cpuFreq) { // Time let time = tStates / cpuFreq; let unit = 's'; if (time < 1e-3) { time *= 1e+6; unit = 'us'; } else if (time < 1) { time *= 1e+3; unit = 'ms'; } // CPU clock let clockStr = (cpuFreq * 1E-6).toPrecision(2); if (clockStr.endsWith('.0')) clockStr = clockStr.substr(0, clockStr.length - 2); tStatesText += ', time: ' + time.toPrecision(3) + unit + '@' + clockStr + 'MHz'; } } if (tStatesText) this.debugConsoleIndentedText(tStatesText); } /** * Returns the address and current instruction (at PC) as string. * Works in step-back and in normal mode. * Note: Does not retrieve the current PC from the remote. * @param count Optional. If count is bigger than e.g. 10 only "..." is returned. * If even bigger, undefined is returned. * @returns E.g. "8000 LD A,6" */ protected async getCurrentInstruction(count = 0): Promise<string | undefined> { const maxInstructionCount = 10; const pc = Remote.getPC(); const pcStr = Utility.getHexString(pc, 4); // Check if count too high if (count == maxInstructionCount) return pcStr + ' ...'; if (count > maxInstructionCount) return undefined; // Get instruction let disInstr; const stepBackMode = StepHistory.isInStepBackMode(); if (stepBackMode) { // Reverse debug mode disInstr = StepHistory.getCurrentInstruction(); } else { // Normal mode: Disassemble instruction const data = await Remote.readMemoryDump(pc, 4); disInstr = DisassemblyClass.getInstruction(pc, data); } // Construct result string let result; if (disInstr) result = pcStr + " " + disInstr; return result; } /** * vscode requested 'step into'. * @param response * @param args */ protected async stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments): Promise<void> { this.handleRequest(response, async () => { await this.startStepInfo('Step-Into'); // Print instruction const instr = await this.getCurrentInstruction(); if (instr) this.debugConsoleIndentedText(instr); // Check for reverse debugging. let breakReason; const stepBackMode = StepHistory.isInStepBackMode(); if (stepBackMode) { // StepInto breakReason = await StepHistory.stepInto(); } else { // Step-Into StepHistory.clear(); // Step into breakReason = await Remote.stepInto(); } // Check for output. if (breakReason) { this.debugConsoleIndentedText(breakReason); // Show break reason this.decorateBreak(breakReason); } if (!stepBackMode) { // Display info await this.endStepInfo(); } // Check if in unit test mode if (DebugSessionClass.state == DbgAdapterState.UNITTEST) { await Z80UnitTestRunner.dbgCheckUnitTest(breakReason); } // Send event return new StoppedEvent('step', DebugSessionClass.THREAD_ID); }); } /** * vscode requested 'step out'. * @param response * @param args */ protected async stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments): Promise<void> { this.handleRequest(response, async () => { await this.startStepInfo('Step-Out'); // Check for reverse debugging. let breakReasonString; const stepBackMode = StepHistory.isInStepBackMode(); if (stepBackMode) { // StepOut breakReasonString = await StepHistory.stepOut(); } else { // Normal Step-Out StepHistory.clear(); breakReasonString = await Remote.stepOut(); } // Print break reason if (breakReasonString) { // Output a possible problem (end of log reached) this.debugConsoleIndentedText(breakReasonString); // Show break reason this.decorateBreak(breakReasonString); } if (!stepBackMode) { // Display info await this.endStepInfo(); } // Check if in unit test mode if (DebugSessionClass.state == DbgAdapterState.UNITTEST) { await Z80UnitTestRunner.dbgCheckUnitTest(breakReasonString); } // Send event return new StoppedEvent('step', DebugSessionClass.THREAD_ID); }); } /** * vscode requested 'step backwards'. * @param response * @param args */ protected async stepBackRequest(response: DebugProtocol.StepBackResponse, args: DebugProtocol.StepBackArguments): Promise<void> { this.handleRequest(response, async () => { await this.startStepInfo('Step-Back', true); // Step back const breakReason = await StepHistory.stepBack(); // Print break reason if (breakReason) { // Output a possible problem (end of log reached) this.debugConsoleIndentedText(breakReason); // Show break reason this.decorateBreak(breakReason); } else { // Print instruction (it's only printed if no error, as the // only error that can occur is 'start of history reached'. const instr = await this.getCurrentInstruction(); if (instr) this.debugConsoleIndentedText(instr); } // Send event return new StoppedEvent('step', DebugSessionClass.THREAD_ID); }); } /** * Sets the value of an expression from the WATCH pane. * Does so only for the top level. I.e. if top level is an L-value. * E.g. a byte to change. * For structures or memory array is is already supported by the * StructVar and MemDumpVar. */ protected async setExpressionRequest(response: DebugProtocol.SetExpressionResponse, args: DebugProtocol.SetExpressionArguments, request?: DebugProtocol.Request) { response.success = false; // will be changed if successful. // Get immediate value const item = this.constExpressionsList.get(args.expression); if (item && item.immediateValue) { // Now set the value. const value = Utility.parseValue(args.value); const formattedString = await item.immediateValue.setValue(value); if (formattedString) { response.body = {value: formattedString}; response.success = true; if (ShallowVar.memoryChanged) { await this.memoryHasBeenChanged(); this.sendEvent(new InvalidatedEvent(['variables'])); // E.g. the disassembly would need to be updated on memory change } ShallowVar.clearChanged(); } } this.sendResponse(response); } /** * Evaluates the command and executes it. * The method might throw an exception if it cannot parse the command. * @param command E.g. "-exec tbblue-get-register 57" or "-wpmem disable". * @returns A Promise<string> with an text to output (e.g. an error). */ protected async evaluateCommand(command: string): Promise<string> { const expression = command.trim().replace(/\s+/g, ' '); const tokens = expression.split(' '); const cmd = tokens.shift(); if (!cmd) throw Error("No command."); // Check for "-view" let viewTitle; if (tokens[0] == '-view') { tokens.shift(); viewTitle = cmd.substr(1) + ' ' + tokens.join(' '); // strip '-' } // All commands start with "-" let output; if (cmd == '-help' || cmd == '-h') { output = await this.evalHelp(tokens); } else if (cmd == '-ASSERTION' || cmd == '-assertion') { output = await this.evalASSERTION(tokens); } else if (cmd == '-eval') { output = await this.evalEval(tokens); } else if (cmd == '-exec' || cmd == '-e') { output = await this.evalExec(tokens); } else if (cmd == '-label' || cmd == '-l') { output = await this.evalLabel(tokens); } else if (cmd == '-LOGPOINT' || cmd == '-logpoint') { output = await this.evalLOGPOINT(tokens); } else if (cmd == '-md') { output = await this.evalMemDump(tokens); } else if (cmd == '-msetb') { output = await this.evalMemSetByte(tokens); } else if (cmd == '-msetw') { output = await this.evalMemSetWord(tokens); } else if (cmd == '-ms') { output = await this.evalMemSave(tokens); } else if (cmd == '-mv') { output = await this.evalMemViewByte(tokens); } else if (cmd == '-mvw') { output = await this.evalMemViewWord(tokens); } else if (cmd == '-rmv') { output = await this.evalRegisterMemView(tokens); } else if (cmd == '-dasm') { output = await this.evalDasm(tokens); } else if (cmd == '-patterns') { output = await this.evalSpritePatterns(tokens); } else if (cmd == '-WPMEM' || cmd == '-wpmem') { output = await this.evalWPMEM(tokens); } else if (cmd == '-sprites') { output = await this.evalSprites(tokens); } else if (cmd == '-state') { output = await this.evalStateSaveRestore(tokens); } // Debug commands else if (cmd == '-dbg') { output = await this.evalDebug(tokens); } // else { // Unknown command throw Error("Unknown command: '" + expression + "'"); } // Check for output target if (viewTitle) { // Output text to new view. // Create new view const panel = new TextView(viewTitle, output); await panel.update(); // Send empty response return 'OK'; } else { // Output text to console return output; } } /** * Is called when hovering or when an expression is added to the watches. * Or if commands are input in the debug console. * All have different formats: * - hovering: "word", e.g. "data_b60" or ".loop" or "HL" * - debug console: starts with "-", e.g. "-wpmem enable" * - watch: anything else. * args.context contains info that the request comes from the console, watch panel or hovering. * 'watch': evaluate is run in a watch. * 'repl': evaluate is run from REPL console. * 'hover': evaluate is run from a data hover. */ protected async evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): Promise<void> { Log.log('evaluate.expression: ' + args.expression); Log.log('evaluate.context: ' + args.context); // Check if its a debugger command const expression = args.expression.trim(); const tokens = expression.split(' '); const cmd = tokens.shift(); if (cmd == undefined) { this.sendResponse(response); return; } // Check context switch (args.context) { // Debug Console case 'repl': let text; try { text = await this.evaluateCommand(expression); response.body = {result: text + "\n\n", type: undefined, presentationHint: undefined, variablesReference: 0, namedVariables: undefined, indexedVariables: undefined}; } catch (err) { text = "Error"; if (err.message) text += ': ' + err.message; } response.body = { result: text + "\n\n", type: undefined, presentationHint: undefined, variablesReference: 0, namedVariables: undefined, indexedVariables: undefined }; break; // Hover case 'hover': let formattedValue = ''; try { // Check for registers if (Z80RegistersClass.isRegister(expression)) { formattedValue = await Utility.getFormattedRegister(expression, Z80RegisterHoverFormat); } else { // Label // Check if a 2nd line (memory content) is required //if (!Z80RegistersClass.isSingleRegister(expression)) { // If hovering only the label address + byte and word contents are shown. // First check for module name and local label prefix (sjasmplus). const pcLongAddr = Remote.getPCLong(); const entry = Labels.getFileAndLineForAddress(pcLongAddr); // Local label and prefix const lastLabel = entry.lastLabel; const modulePrefix = entry.modulePrefix; // Get label value const labelValue = Utility.evalExpression(expression, true, modulePrefix, lastLabel); if (labelValue != undefined) { // Get content const memDump = await Remote.readMemoryDump(labelValue, 2); // Format byte const memByte = memDump[0]; const formattedByte = Utility.numberFormattedSync(memByte, 1, Settings.launch.formatting.watchByte, true); // Format word const memWord = memByte + 256 * memDump[1]; const formattedWord = Utility.numberFormattedSync(memWord, 2, Settings.launch.formatting.watchWord, true); // Format output const addrString = Utility.getHexString(labelValue, 4) + 'h'; if (!formattedValue) formattedValue = expression + ': ' + addrString; // Second line formattedValue += '\n(' + addrString + ')b=' + formattedByte + '\n(' + addrString + ')w=' + formattedWord; } //} } } catch { // Ignore any error during hovering. } // Response response.body = { result: formattedValue, variablesReference: 0 } break; // Watch case 'watch': try { // Create or get a variable (either a variable reference or an immediate value) const item = await this.evaluateLabelExpression(expression); let result = ''; if (item.immediateValue) { // Fill in immediate value (varRef is 0) result = await item.immediateValue.getValue(); } response.body = { result, variablesReference: item.varRef, type: item.description, indexedVariables: item.count }; } // try catch (e) { // Return empty response response.body = { result: e.message, variablesReference: 0 } } break; } // Respond this.sendResponse(response); } /** * Evaluates an expression/label and creates the ShallowVar structures. * @param expression E.g. "main,2,10" * @returns All that is required for the VARIABLES pane or WATCHES. */ protected async evaluateLabelExpression(expression: string): Promise<ExpressionVariable> { // Check if expression has been evaluated already const response = await this.constExpressionsList.get(expression); if (response) return response; // Check if it is a label (or double register). A label may have a special formatting: // Example: "LBL_TEXT[x],w,10" = Address: LBL_TEXT+2*x, 10 words // or even a complete struct // "invaders,INVADER,5" = Address: invaders, INVADER STRUCT, 5 elements // If the count is > 1 then an array is displayed. If left then 1 is assumed. // If the type is left, 'b' is assumed, e.g. "LBL_TEXT,,5" will show an array of 5 bytes. // If both are omitted, e.g. "LBL_TEXT" just the byte value contents of LBL_TEXT is shown. // Get everything before ; let text = expression; const k = text.indexOf(';'); if (k >= 0) text = text.slice(0, k); // Tokenize const tokens = text.split(','); if (tokens.length > 4) throw Error("Too many components in expression: " + expression); // Label let labelString = (tokens[0] || '').trim(); // May also contain a number (e.g. address) if (!labelString) throw Error("No expression found."); // Index inside label const matchIndex = /(.*)[^\[]*\[([^\]]+)\]/.exec(labelString); let lblIndexString = ''; if (matchIndex) { labelString = matchIndex[1].trim(); lblIndexString = matchIndex[2].trim(); } // Label type etc. let lblType = (tokens[1] || '').trim(); let elemCountString = (tokens[2] || '').trim(); // Endianess const endianess = (tokens[3] || 'little').trim().toLowerCase(); let littleEndian = true; if (endianess == 'big') littleEndian = false; // At the moment it is used only for immediate values else if (endianess != 'little') { throw Error("Unknown endianes: " + endianess); } // Defaults let labelValue; let lastLabel; let modulePrefix; let lblIndex = 0; let elemCount = 1; // Use 1 as default let elemSize = 1; // Use 1 as default (if no type/size given) // First check for module name and local label prefix (sjasmplus). const pcLongAddr = Remote.getPCLong(); const entry = Labels.getFileAndLineForAddress(pcLongAddr); // Local label and prefix lastLabel = entry.lastLabel; modulePrefix = entry.modulePrefix; // Convert label (+expression) labelValue = Utility.evalExpression(labelString, true, modulePrefix, lastLabel); if (isNaN(labelValue)) throw Error("Could not parse label: " + labelString); // Get size from type if (lblType) { //elemSize = Labels.getNumberFromString64k(lblType); elemSize = Utility.evalExpression(lblType, true, modulePrefix, lastLabel); if (isNaN(elemSize)) throw Error("Could not parse element size."); if (elemSize <= 0) throw Error("Element size must be > 0, is " + elemSize + "."); } // And index "[x]" if (lblIndexString) { lblIndex = Utility.evalExpression(lblIndexString, false, modulePrefix, lastLabel); if (isNaN(lblIndex)) throw Error("Could not parse index."); if (lblIndex < 0) throw Error("Index must be > 0, is " + lblIndex + "."); } // Check count if (elemCountString) { elemCount = Utility.evalExpression(elemCountString, true, modulePrefix, lastLabel); if (isNaN(elemCount)) throw Error("Could not parse element count."); if (elemCount <= 0) throw Error("Element count must be > 0, is " + elemCount + "."); } else { // If no count is given try to estimate it by calculating the distance to // the next label. // Note: labelValue is 64k only. So first check if the label name is simply a name without calculation. // If yes, use it. If no use labelValue. let distAddr = Labels.getNumberForLabel(labelString); // If not a long address then use the 64k value if (distAddr == undefined) distAddr = labelValue; // Try to get the distance to the next label: // Note: Does not work for structs as the next label would // be inside the struct. elemCount = Labels.getDistanceToNextLabel(distAddr!) || 1; // Check special case if (!lblType && elemCount == 2) { // Special case: 1 word. Exchange size and count elemSize = 2; elemCount = 1; } else { // Divide elemCount by elemSize elemCount = Math.floor((elemCount + elemSize - 1) / elemSize); // Limit minimal number if (elemCount < 1) elemCount = 1; // Limit max. number if (elemCount > 1000) elemCount = 1000; } } // Add index const indexOffset = lblIndex * elemSize; const labelValue64k = (labelValue + indexOffset) & 0xFFFF; // Create fullLabel //const fullLabel = Utility.createFullLabel(labelString, "", lastLabel); // Note: the module name comes from the PC location, this could be irritating. Therefore it is left off. // Create a label variable let labelVar; let immediateValue; // Check for sub labels (i.e. check for struct) let props; let propsLength = 0 if (lblType != undefined) { props = Labels.getSubLabels(lblType); propsLength = props.length; } // Get sub properties if (propsLength == 0) { // Check for elem size. If bigger than 6 rounding errors could occur. if (elemSize > 6) throw Error('The size of an element must be smaller than 7.'); // Check for single value or array (no sub properties) if (elemCount <= 1) { // Create variable immediateValue = new ImmediateMemoryValue(labelValue64k, elemSize, littleEndian); } else { // Simple memdump labelVar = new MemDumpVar(labelValue64k, elemCount, elemSize, littleEndian); } } else { // Not 1 or 2 was given as size but e.g. a struct label if (propsLength > 0) { // Structure labelVar = new StructVar(labelValue64k, elemCount, elemSize, lblType, props, this.listVariables, littleEndian); } if (!labelVar) { // Simple memdump labelVar = new MemDumpVar(labelValue64k, elemCount, elemSize, littleEndian); } } const description = Utility.getLongAddressString(labelValue64k); const varRef = this.listVariables.addObject(labelVar); const exprVar = { description, immediateValue, varRef, count: elemCount }; // Check if the address is constant, i.e. it does not contain a register const exprContainsRegs = Utility.exprContainsMainRegisters(labelString); if (!exprContainsRegs) { // Store, it's address is constant this.constExpressionsList.set(expression, exprVar); } return exprVar; } /** * Prints a help text for the debug console commands. * @param tokens The arguments. Unused. * @param A Promise with a text to print. */ protected async evalHelp(tokens: Array<string>): Promise<string> { const output = `Allowed commands are: "-ASSERTION enable|disable|status": - enable|disable: Enables/disables all breakpoints caused by ASSERTIONs set in the sources. All ASSERTIONs are by default enabled after startup of the debugger. - status: Shows enable status of ASSERTION breakpoints. "-dasm address count": Disassembles a memory area. count=number of lines. "-eval expr": Evaluates an expression. The expression might contain mathematical expressions and also labels. It will also return the label if the value correspondends to a label. "-exec|e cmd args": cmd and args are directly passed to ZEsarUX. E.g. "-exec get-registers". "-help|h": This command. Do "-e help" to get all possible ZEsarUX commands. "-label|-l XXX": Returns the matching labels (XXX) with their values. Allows wildcard "*". "-LOGPOINT enable|disable|status [group]": - enable|disable: Enables/disables all logpoints caused by LOGPOINTs of a certain group set in the sources. If no group is given all logpoints are affected. All logpoints are by default disabled after startup of the debugger. - status: Shows enable status of LOGPOINTs per group. "-md address size [dec|hex] [word] [little|big]": Memory dump at 'address' with 'size' bytes. Output is in 'hex' (default) or 'dec'imal. Per default data will be grouped in bytes. But if chosen, words are output. Last argument is the endianness which is little endian by default. "-msetb address value [repeat]:" - address: The address to fill. Can also be a label or expression. - value: The byte value to set. - repeat: (Optional) How often the value is repeated. Examples: "-msetb 8000h 0Fh" : Puts a 15 into memory location 0x8000. "-msetb 8000h 0 100h" : fills memory locations 0x8000 to 0x80FF with zeroes. "-msetb fill_colors_ptr+4 FEh": If fill_colors_ptr is e.g. 0xCF02 the value FEh is put into location 0xCF06. "-msetw address value [repeat [endianness]]:" - address: The address to fill. Can also be a label or expression. - value: The word value to set. - repeat: (Optional) How often the value is repeated. - endianness: (Optional) 'little' (default) or 'big'. Examples: "-msetw 8000h AF34h" : Puts 34h into location 0x8000 and AFh into location 0x8001. "-msetw 8000h AF34h 1 big" : Puts AFh into location 0x8000 and 34h into location 0x8001. "-msetw 8000h 1234h 100h" : fills memory locations 0x8000 to 0x81FF with the word value 1234h. "-ms address size filename": Saves a memory dump to a file. The file is saved to the temp directory. "-mv address size [address_n size_n]*": Memory view at 'address' with 'size' bytes. Will open a new view to display the memory contents. "-patterns [index[+count|-endindex] [...]": Shows the tbblue sprite patterns beginning at 'index' until 'endindex' or a number of 'count' indices. The values can be omitted. 'index' defaults to 0 and 'count' to 1. Without any parameter it will show all sprite patterns. You can concat several ranges. Example: "-patterns 10-15 20+3 33" will show sprite patterns at index 10, 11, 12, 13, 14, 15, 20, 21, 22, 33. "-rmv": Shows the memory register view. I.e. a dynamic view with the memory contents the registers point to. "-sprites [slot[+count|-endslot] [...]": Shows the tbblue sprite registers beginning at 'slot' until 'endslot' or a number of 'count' slots. The values can be omitted. 'slot' defaults to 0 and 'count' to 1. You can concat several ranges. Example: "-sprite 10-15 20+3 33" will show sprite slots 10, 11, 12, 13, 14, 15, 20, 21, 22, 33. Without any parameter it will show all visible sprites automatically. "-state save|restore|list|clear|clearall [statename]": Saves/restores the current state. I.e. the complete RAM + the registers. "-WPMEM enable|disable|status": - enable|disable: Enables/disables all WPMEM set in the sources. All WPMEM are by default enabled after startup of the debugger. - status: Shows enable status of WPMEM watchpoints. Some examples: "-exec h 0 100": Does a hexdump of 100 bytes at address 0. "-e write-memory 8000h 9fh": Writes 9fh to memory address 8000h. "-e gr": Shows all registers. "-eval 2+3*5": Results to "17". "-msetb mylabel 3": Sets the data at memory location 'mylabel' to 3. "-mv 0 10": Shows the memory at address 0 to address 9. "-sprites": Shows all visible sprites. "-state save 1": Stores the current state as 'into' 1. "-state restore 1": Restores the state 'from' 1. Notes: For all commands (if it makes sense or not) you can add "-view" as first parameter. This will redirect the output to a new view instead of the console. E.g. use "-help -view" to put the help text in an own view. `; this.sendEvent(new StoppedEvent('Value updated')); /* For debugging purposes there are a few more: -dbg serializer clear: Clears the call serializer queue. -dbg serializer print: Prints the current function. Use this to see where it hangs if it hangs. (Use 'setProgress' to debug.) */ return output; } /** * Evaluates a given expression. * @param tokens The arguments. I.e. the expression to evaluate. * @returns A Promise with a text to print. */ protected async evalEval(tokens: Array<string>): Promise<string> { const expr = tokens.join(' ').trim(); // restore expression if (expr.length == 0) { // Error Handling: No arguments throw new Error("Expression expected."); } // Evaluate expression let result; // Evaluate const value = Utility.evalExpression(expr); // convert to decimal result = value.toString(); // convert also to hex result += ', ' + value.toString(16).toUpperCase() + 'h'; // convert also to bin result += ', ' + value.toString(2) + 'b'; // check for label const labels = Labels.getLabelsPlusIndexForNumber64k(value); if (labels.length > 0) { result += ', ' + labels.join(', '); } return result; } /** * Executes a command in the emulator. * @param tokens The arguments. I.e. the command for the emulator. * @returns A Promise with a text to print. */ protected async evalExec(tokens: Array<string>): Promise<string> { // Execute const machineCmd = tokens.join(' '); const textData = await Remote.dbgExec(machineCmd); // Return value return textData; } /** * Evaluates a label. * evalEval almost gives the same information, but evalLabel allows * to use wildcards. * @param tokens The arguments. I.e. the label. E.g. "main" or "mai*". * @returns A Promise with a text to print. */ protected async evalLabel(tokens: Array<string>): Promise<string> { const expr = tokens.join(' ').trim(); // restore expression if (expr.length == 0) { // Error Handling: No arguments return "Label expected."; } // Find label with regex, every star is translated into ".*" const rString = '^' + expr.replace(/\*/g, '.*?') + '$'; // Now search all labels const labels = Labels.getLabelsForRegEx(rString); let result = ''; if (labels.length > 0) { labels.forEach(label => { let value = Labels.getNumberForLabel(label); if (value != undefined) value &= 0xFFFF; result += label + ': ' + Utility.getHexString(value, 4) + 'h\n'; }) } else { // No label found result = 'No label matches.'; } // return result return result; } /** * Shows a view with a memory dump. * @param tokens The arguments. I.e. the address and size. * @returns A Promise with a text to print. */ protected async evalMemDump(tokens: Array<string>): Promise<string> { // Check count of arguments if (tokens.length < 2) { // Error Handling: Too less arguments throw Error("Address and size expected."); } // Address const addressString = tokens[0]; const address = Utility.evalExpression(addressString); if (address < 0 || address > 0xFFFF) throw Error("Address (" + address + ") out of range."); // Size const sizeString = tokens[1]; const size = Utility.evalExpression(sizeString); if (size < 0 || size > 0xFFFF) throw Error("Size (" + size + ") out of range."); // Byte or word let unitSize = 1; // Default=byte let bigEndian = false; // Hex/dec let hex = true; const typeString = tokens[2]; if (typeString) { const typeStringLower = typeString.toLowerCase(); if (typeStringLower != "hex" && typeStringLower != "dec" && typeStringLower != "word") throw Error("'hex', 'dec' or 'word' expected but got '" + typeString + "'."); let k = 2; // Check for hex or dec if (typeString == 'hex') k++; else if (typeString == 'dec') { hex = false; k++; } // Check for unit size (word) const unitSizeString = tokens[k]; if (unitSizeString) { const unitSizeStringLower = unitSizeString.toLowerCase() if (unitSizeStringLower != "word") throw Error("'word' expected but got '" + unitSizeString + "'."); unitSize = 2; // Endianness const endianness = tokens[k + 1]; if (endianness) { const endiannessLower = endianness.toLowerCase(); if (endiannessLower == "big") { // Big endian bigEndian = true; } else if (endiannessLower != "little") { throw Error("'little' or 'big' expected but got '" + endianness + "'."); } } } } // Get memory const data = await Remote.readMemoryDump(address, size); // 'Print' let output = ''; for (let i = 0; i < size; i += unitSize) { let value = data[i]; if (unitSize == 2) { if (bigEndian) value = (value << 8) + data[i + 1]; else value += data[i + 1] << 8; } if (hex) output += Utility.getHexString(value, 2 * unitSize) + ' '; else output += value + ' '; } // Send response return output; } /** * Checks if the given string is 'little' or 'big' case insensitive. * Throws an exception if string evaluates to something different. * @param endiannessString The string to check. * @returns true for 'little' or undefined and 'false for 'big'. */ protected isLittleEndianString(endiannessString: string | undefined) { let littleEndian = true; if (endiannessString != undefined) { const s = endiannessString.toLowerCase(); if (s != 'little' && s != 'big') throw Error("Endianness (" + endiannessString + ") unknown."); littleEndian = (s == 'little'); } return littleEndian; } /** * Sets a memory location to some value. * @param valSize 1 or 2 for byte or word. * @param addressString A string with a labeg or hex/decimal number or an expression that is used as start address. * @param valueString The value to set. * @param repeatString How often the value gets repeated. Optional. Defaults to '1'. * @param endiannessString The endianness. For valSize==2. 'little' or 'big'. Optional. defaults to 'little'. * @returns A Promise with a text to print. */ protected async memSet(valSize: number, addressString: string, valueString: string, repeatString?: string, endiannessString?: string): Promise<string> { // Address const address = Utility.evalExpression(addressString); if (address < 0 || address > 0xFFFF) throw Error("Address (" + address + ") out of range."); // Value const value = Utility.evalExpression(valueString); const maxValue = 2 ** (valSize * 8); if (value >= maxValue || value < (-maxValue / 2)) throw Error("Value (" + value + ") too big (or too small)."); // Repeat const repeat = (repeatString != undefined) ? Utility.evalExpression(repeatString) : 1; const totalSize = valSize * repeat; if (totalSize <= 0 || totalSize > 0xFFFF) throw Error("Repetition (" + repeat + ") out of range."); // Endianness const littleEndian = this.isLittleEndianString(endiannessString); // Set (or fill) memory // Prepare data const data = new Uint8Array(totalSize); let index = 0; for (let r = 0; r < repeat; r++) { let val = value; for (let k = 0; k < valSize; k++) { if (littleEndian) { data[index + k] = val & 0xFF; } else { data[index + valSize - k - 1] = val & 0xFF; } // Next val = val >> 8; } // Next index += valSize; } // Write to remote await Remote.writeMemoryDump(address, data); // Update this.update(); // Send response return 'OK'; } /** * Sets a memory location to some byte value. * "-msetb address value repeat" * "-msetb 8000h 74h"" * @param tokens The arguments. I.e. the address, value and (optional) repeat. * @returns A Promise with a text to print. */ protected async evalMemSetByte(tokens: Array<string>): Promise<string> { // Check count of arguments if (tokens.length < 2) { // Error Handling: Too less arguments throw Error("At least address and value expected."); } // Check count of arguments if (tokens.length > 3) { // Error Handling: Too many arguments throw Error("Too many arguments."); } return this.memSet(1, tokens[0] /*address*/, tokens[1] /*value*/, tokens[2] /*repeat*/); } /** * Sets a memory location to some word value. * "-msetw address value repeat endianness" * "-msetw 8000h 7654h"" * @param tokens The arguments. I.e. the address, value, repeat and endianness. Only the first 2 are mandatory. * @returns A Promise with a text to print. */ protected async evalMemSetWord(tokens: Array<string>): Promise<string> { // Check count of arguments if (tokens.length < 2) { // Error Handling: Too less arguments throw Error("At least address and value expected."); } // Check count of arguments if (tokens.length > 4) { // Error Handling: Too many arguments throw Error("Too many arguments."); } return this.memSet(2, tokens[0] /*address*/, tokens[1] /*value*/, tokens[2] /*repeat*/, tokens[3] /*endianness*/); } /** * Saves a memory dump to a file. * @param tokens The arguments. I.e. the address and size. * @returns A Promise with a text to print. */ protected async evalMemSave(tokens: Array<string>): Promise<string> { // Check count of arguments if (tokens.length < 2) { // Error Handling: No arguments throw Error("Address and size expected."); } // Address const addressString = tokens[0]; const address = Utility.evalExpression(addressString); if (address < 0 || address > 0xFFFF) throw Error("Address (" + address + ") out of range."); // Size const sizeString = tokens[1]; const size = Utility.evalExpression(sizeString); if (size < 0 || size > 0xFFFF) throw Error("Size (" + size + ") out of range."); // Get filename const filename = tokens[2]; if (!filename) throw Error("No filename given."); // Get memory const data = await Remote.readMemoryDump(address, size); // Save to .tmp/filename const relPath = Utility.getRelTmpFilePath(filename); const absPath = Utility.getAbsFilePath(relPath); fs.writeFileSync(absPath, data); // Send response return 'OK'; } /** * Shows a view with a memory dump. * @param tokens The arguments. I.e. the address and size. * @returns A Promise with a text to print. */ protected async evalMemViewByte(tokens: Array<string>): Promise<string> { // Check count of arguments if (tokens.length == 0) { // Error Handling: No arguments throw new Error("Address and size expected."); } if (tokens.length % 2 != 0) { // Error Handling: No size given throw new Error("No size given for address '" + tokens[tokens.length - 1] + "'."); } // Get all addresses/sizes. const addrSizes = new Array<number>(); for (let k = 0; k < tokens.length; k += 2) { // Address const addressString = tokens[k]; const address = Utility.evalExpression(addressString); addrSizes.push(address); // Size const sizeString = tokens[k + 1]; const size = Utility.evalExpression(sizeString); addrSizes.push(size); } // Create new view const panel = new MemoryDumpView(); for (let k = 0; k < tokens.length; k += 2) { const start = addrSizes[k]; const size = addrSizes[k + 1] panel.addBlock(start, size, Utility.getHexString(start & 0xFFFF, 4) + 'h-' + Utility.getHexString((start + size - 1) & 0xFFFF, 4) + 'h'); } panel.mergeBlocks(); await panel.update(); // Send response return 'OK'; } /** * Shows a view with a memory dump. The memory is organized in * words instead of bytes. * One can choose little or blig endian. * @param tokens The arguments. I.e. the address, size and endianness. * @returns A Promise with a text to print. */ protected async evalMemViewWord(tokens: Array<string>): Promise<string> { // Check for endianness let littleEndian = true; if (tokens.length % 2 != 0) { // Last one should be endianness const endiannessString = tokens.pop() littleEndian = this.isLittleEndianString(endiannessString); } // Check count of arguments if (tokens.length == 0) { // Error Handling: No arguments throw new Error("Address and size expected."); } // Get all addresses/sizes. const addrSizes = new Array<number>(); for (let k = 0; k < tokens.length; k += 2) { // Address const addressString = tokens[k]; const address = Utility.evalExpression(addressString); addrSizes.push(address); // Size const sizeString = tokens[k + 1]; const size = Utility.evalExpression(sizeString); addrSizes.push(size); } // Create new view const panel = new MemoryDumpViewWord(littleEndian); for (let k = 0; k < tokens.length; k += 2) { const start = addrSizes[k]; const size = addrSizes[k + 1] panel.addBlock(start, size, Utility.getHexString(start & 0xFFFF, 4) + 'h-' + Utility.getHexString((start + 2 * size - 1) & 0xFFFF, 4) + 'h'); } panel.mergeBlocks(); await panel.update(); // Send response return 'OK'; } /** * Shows the register memory view. * @returns A Promise with a text to print. I.e. "OK" */ protected async evalRegisterMemView(tokens: Array<string>): Promise<string> { // Check count of arguments if (tokens.length != 0) { // Error Handling: No arguments throw new Error("No parameters expected."); } // Create memory/register dump view const registerMemoryView = new MemoryRegisterView(); const regs = Settings.launch.memoryViewer.registersMemoryView; registerMemoryView.addRegisters(regs); await registerMemoryView.update(); // Send response return 'OK'; } /** * Shows a a small disassembly in the console. * @param tokens The arguments. I.e. the address and size. * @returns A Promise with a text to print. */ protected async evalDasm(tokens: Array<string>): Promise<string> { // Check count of arguments if (tokens.length == 0) { // Error Handling: No arguments throw new Error("Address and number of lines expected."); } if (tokens.length > 2) { // Error Handling: Too many arguments throw new Error("Too many arguments."); } // Get address const addressString = tokens[0]; const address = Utility.evalExpression(addressString); // Get size const countString = tokens[1]; let count = 10; // Default if (tokens.length > 1) { // Count given count = Utility.evalExpression(countString); } // Get memory const data = await Remote.readMemoryDump(address, 4 * count); // Disassembly const dasmArray = DisassemblyClass.getLines(address, data, count); // Convert to text let txt = ''; for (const line of dasmArray) { txt += Utility.getHexString(line.address, 4) + '\t' + line.instruction + '\n'; } // Send response return txt; } /** * LOGPOINTS. Enable/disable/status. * @param tokens The arguments. * @returns A Promise<string> with a probably error text. */ protected async evalLOGPOINT(tokens: Array<string>): Promise<string> { const param = tokens[0] || ''; const group = tokens[1]; if (param == 'enable' || param == 'disable') { // Enable or disable all WPMEM watchpoints const enable = (param == 'enable'); await Remote.enableLogpointGroup(group, enable); } else if (param == 'status') { // Just show } else { // Unknown argument throw new Error("Unknown argument: '" + param + "'"); } // Always show enable status of all Logpoints let result = 'LOGPOINT groups:'; const enableMap = Remote.logpointsEnabled; if (enableMap.size == 0) result += ' none'; else { for (const [grp, enable] of enableMap) { result += '\n ' + grp + ': ' + ((enable) ? 'enabled' : 'disabled'); } } return result; } /** * ASSERTION. Enable/disable/status. * @param tokens The arguments. * @returns A Promise<string> with a probably error text. */ protected async evalASSERTION(tokens: Array<string>): Promise<string> { const param = tokens[0] || ''; if (param == 'enable' || param == 'disable') { // Enable or disable all ASSERTION breakpoints const paramEnable = (param == 'enable'); await Remote.enableAssertionBreakpoints(paramEnable); } else if (param == 'status') { // Just show } else { // Unknown argument throw new Error("Unknown argument: '" + param + "'"); } // Show enable status of all ASSERTION breakpoints const enable = Remote.assertionBreakpointsEnabled; const enableString = (enable) ? 'enabled' : 'disabled'; let result = 'ASSERTION breakpoints are ' + enableString + '.\n'; if (enable) { // Also list all assertion breakpoints const abps = Remote.getAllAssertionBreakpoints(); for (const abp of abps) { result += Utility.getLongAddressString(abp.address); const labels = Labels.getLabelsForLongAddress(abp.address); if (labels.length > 0) { const labelsString = labels.join(', '); result += ' (' + labelsString + ')'; } // Condition, remove the brackets result += ', Condition: ' + Utility.getAssertionFromCondition(abp.condition) + '\n'; } if (abps.length == 0) result += 'No ASSERTION breakpoints.\n'; } return result; } /** * WPMEM. Enable/disable/status. * @param tokens The arguments. * @returns A Promise<string> with a text to print. */ protected async evalWPMEM(tokens: Array<string>): Promise<string> { const param = tokens[0] || ''; if (param == 'enable' || param == 'disable') { // Enable or disable all WPMEM watchpoints const paramEnable = (param == 'enable'); await Remote.enableWPMEM(paramEnable); } else if (param == 'status') { // Just show } else { // Unknown argument throw Error("Unknown argument: '" + param + "'"); } // Show enable status of all WPMEM watchpoints const enable = Remote.wpmemEnabled; const enableString = (enable) ? 'enabled' : 'disabled'; let result = 'WPMEM watchpoints are ' + enableString + '.\n'; if (enable) { // Also list all watchpoints const wps = Remote.getAllWpmemWatchpoints(); for (const wp of wps) { result += Utility.getLongAddressString(wp.address); const labels = Labels.getLabelsForLongAddress(wp.address); if (labels.length > 0) { const labelsString = labels.join(', '); result += ' (' + labelsString + ')'; } // Condition, remove the brackets result += ', size=' + wp.size + '\n'; } if (wps.length == 0) result += 'No WPMEM watchpoints.\n'; } return result; } /** * Show the sprite patterns in a view. * @param tokens The arguments. * @returns A Promise<string> with a text to print. */ protected async evalSpritePatterns(tokens: Array<string>): Promise<string> { // Evaluate arguments let title; let params: Array<number> | undefined = []; if (tokens.length == 0) { // The view should choose the visible sprites automatically title = 'Sprite Patterns: 0-63'; params.push(0); params.push(64); } else { // Create title title = 'Sprite Patterns: ' + tokens.join(' '); // Get slot and count/endslot while (true) { // Get parameter const param = tokens.shift(); if (!param) break; // Evaluate const match = /([^+-]*)(([-+])(.*))?/.exec(param); if (!match) // Error Handling throw new Error("Can't parse: '" + param + "'"); // start slot const start = Utility.parseValue(match[1]); if (isNaN(start)) // Error Handling throw new Error("Expected slot but got: '" + match[1] + "'"); // count let countValue = 1; if (match[3]) { countValue = Utility.parseValue(match[4]); if (isNaN(countValue)) // Error Handling throw new Error("Can't parse: '" + match[4] + "'"); if (match[3] == "-") // turn range into count countValue += 1 - start; } // Check if (countValue <= 0) // Error Handling throw new Error("Not allowed count: '" + match[0] + "'"); // Add params.push(start); params.push(countValue); } const slotString = tokens[0] || '0'; const slot = Utility.parseValue(slotString); if (isNaN(slot)) { // Error Handling: Unknown argument throw new Error("Expected slot but got: '" + slotString + "'"); } const countString = tokens[1] || '1'; const count = Utility.parseValue(countString); if (isNaN(count)) { // Error Handling: Unknown argument throw new Error("Expected count but got: '" + countString + "'"); } } // Create new view const panel = new ZxNextSpritePatternsView(title, params); await panel.update(); // Send response return 'OK'; } /** * Show the sprites in a view. * @param tokens The arguments. * @returns A Promise<string> with a text to print. */ protected async evalSprites(tokens: Array<string>): Promise<string> { // First check for tbblue // Evaluate arguments let title; let params: Array<number> | undefined; if (tokens.length == 0) { // The view should choose the visible sprites automatically title = 'Visible Sprites'; } else { // Create title title = 'Sprites: ' + tokens.join(' '); // Get slot and count/endslot params = []; while (true) { // Get parameter const param = tokens.shift(); if (!param) break; // Evaluate const match = /([^+-]*)(([-+])(.*))?/.exec(param); if (!match) // Error Handling throw new Error("Can't parse: '" + param + "'"); // start slot const start = Utility.parseValue(match[1]); if (isNaN(start)) // Error Handling throw new Error("Expected slot but got: '" + match[1] + "'"); // count let countValue = 1; if (match[3]) { countValue = Utility.parseValue(match[4]); if (isNaN(countValue)) // Error Handling throw new Error("Can't parse: '" + match[4] + "'"); if (match[3] == "-") // turn range into count countValue += 1 - start; } // Check if (countValue <= 0) // Error Handling throw new Error("Not allowed count: '" + match[0] + "'"); // Add params.push(start); params.push(countValue); } const slotString = tokens[0] || '0'; const slot = Utility.parseValue(slotString); if (isNaN(slot)) { // Error Handling: Unknown argument throw new Error("Expected slot but got: '" + slotString + "'"); } const countString = tokens[1] || '1'; const count = Utility.parseValue(countString); if (isNaN(count)) { // Error Handling: Unknown argument throw new Error("Expected count but got: '" + countString + "'"); } } // Create new view const panel = new ZxNextSpritesView(title, params); await panel.update(); // Send response return 'OK'; } /** * Save/restore the state. * @param tokens The arguments. 'save'/'restore' * @returns A Promise<string> with a text to print. */ protected async evalStateSaveRestore(tokens: Array<string>): Promise<string> { const param = tokens[0] || ''; const stateName = tokens[1]; if (!stateName && (param == 'save' || param == 'restore' || param == 'clear')) throw new Error("Parameter missing: You need to add a name for the state, e.g. '0', '1' or more descriptive 'start'"); if (param == 'save') { // Save current state await this.stateSave(stateName); // Send response return "Saved state '" + stateName + "'."; } else if (param == 'restore') { // Restores the state await this.stateRestore(stateName); return "Restored state '" + stateName + "'."; } else if (param == 'list') { // List all files in the state dir. let files; try { const dir = Utility.getAbsStateFileName(''); files = fs.readdirSync(dir); } catch {} let text; if (files == undefined || files.length == 0) text = "No states saved yet."; else text = "All states:\n" + files.join('\n'); return text; } else if (param == 'clearall') { // Removes the files in the states directory try { const dir = Utility.getAbsStateFileName(''); const files = fs.readdirSync(dir); for (const file of files) { const path = Utility.getAbsStateFileName(file); fs.unlinkSync(path); } } catch (e) { return e.message; } return "All states deleted."; } else if (param == 'clear') { // Removes one state try { const path = Utility.getAbsStateFileName(stateName); fs.unlinkSync(path); } catch (e) { return e.message; } return "State '" + stateName + "' deleted."; } else { // Unknown argument throw new Error("Unknown argument: '" + param + "'"); } } /** * Debug commands. Not shown publicly. * @param tokens The arguments. * @returns A Promise<string> with a text to print. */ protected async evalDebug(tokens: Array<string>): Promise<string> { const param1 = tokens[0] || ''; let unknownArg = param1; // Unknown argument throw new Error("Unknown argument: '" + unknownArg + "'"); } /** * Called eg. if user changes a register value. */ protected async setVariableRequest(response: DebugProtocol.SetVariableResponse, args: DebugProtocol.SetVariableArguments) { const ref = args.variablesReference; const name = args.name; const value = Utility.parseValue(args.value); ShallowVar.clearChanged(); // Get variable object const varObj = this.listVariables.getObject(ref); response.success = false; // will be changed if successful. // Safety check if (varObj) { // Variables can be changed only if not in reverse debug mode const msg = varObj.changeable(name); if (msg) { // Change not allowed e.g. if in reverse debugging response.message = msg; } else { // Set value const formattedString = await varObj.setValue(name, value); // Send response if (formattedString) { response.body = {value: formattedString}; response.success = true; } } } this.sendResponse(response); // Now check what has been changed. if (ShallowVar.pcChanged) await this.pcHasBeenChanged(); if (ShallowVar.spChanged) await this.spHasBeenChanged(); if (ShallowVar.otherRegisterChanged) await this.otherRegisterHasBeenChanged(); if (ShallowVar.memoryChanged) { await this.memoryHasBeenChanged(); this.sendEvent(new InvalidatedEvent(['variables'])); // E.g. the disassembly would need to be updated on memory change } ShallowVar.clearChanged(); } /** * Should be called if PC is manually changed. */ protected async pcHasBeenChanged() { await Remote.getCallStackFromEmulator(); this.sendEvent(new StoppedEvent("PC changed", DebugSessionClass.THREAD_ID)); await BaseView.staticCallUpdateRegisterChanged(); } /** * Should be called if SP is manually changed. */ protected async spHasBeenChanged() { await Remote.getCallStackFromEmulator(); this.sendEvent(new InvalidatedEvent(['variables'])); await BaseView.staticCallUpdateRegisterChanged(); } /** * Should be called if any other register is manually changed. * Also for PC or SP. In that case both functions are called. */ protected async otherRegisterHasBeenChanged() { this.sendEvent(new InvalidatedEvent(['variables'])); await BaseView.staticCallUpdateRegisterChanged(); } /** * Should be called if memory content has been manually changed. */ protected async memoryHasBeenChanged() { //this.sendEvent(new InvalidatedEvent(['variables'])); // Not required. The VARIABLES and the WATCHes will be updated anyway. If uncommented then the WATCHes are not highlighted on a change. await BaseView.staticCallUpdateFunctions(); } /** * Change the Program Counter such that it points to the given file/line. * @param filename The absolute file path. * @param lineNr The lineNr. Starts at 0. */ protected async setPcToLine(filename: string, lineNr: number): Promise<void> { // Get address of file/line const realLineNr = lineNr; let addr = Remote.getAddrForFileAndLine(filename, realLineNr); if (addr < 0) return; // Check if bank is the same const slots = Remote.getSlots(); if (slots) { const bank = Z80Registers.getBankFromAddress(addr); if (bank >= 0) { const slotIndex = Z80Registers.getSlotFromAddress(addr); if (bank != slots[slotIndex]) { this.showError("Cannot set PC to a location (address=" + Utility.getHexString(addr & 0xFFFF, 4) + "h) of a bank (bank " + bank + ") that is currently not paged in."); return; } } } // Now change Program Counter await Remote.setRegisterValue('PC', addr & 0xFFFF); await Remote.getRegistersFromEmulator(); StepHistory.clear(); // Update vscode await this.pcHasBeenChanged(); } /** * Does a dissaembly to the debug console for the address at the cursor position. * @param filename The absolute file path. * @param fromLineNr The line. Starts at 0. * @param toLineNr The line. Starts at 0. */ protected async disassemblyAtCursor(filename: string, fromLineNr: number, toLineNr: number): Promise<void> { // Get address of file/line let fromAddr; while (fromLineNr <= toLineNr) { fromAddr = Remote.getAddrForFileAndLine(filename, fromLineNr) if (fromAddr >= 0) break; fromLineNr++; } let toAddr; while (fromLineNr <= toLineNr) { toAddr = Remote.getAddrForFileAndLine(filename, toLineNr) if (toAddr >= 0) break; toLineNr--; } if (fromAddr < 0) return; // Check if bank is the same const slots = Remote.getSlots(); if (slots) { const fromBank = Z80Registers.getBankFromAddress(fromAddr); if (fromBank >= 0) { const slotIndex = Z80Registers.getSlotFromAddress(fromAddr); if (fromBank != slots[slotIndex]) { this.debugConsoleAppendLine("Memory currently not paged in. (address=" + Utility.getHexString(fromBank & 0xFFFF, 4) + "h, bank=" + fromBank + ")"); return; } } const toBank = Z80Registers.getBankFromAddress(toAddr); if (toBank >= 0) { const slotIndex = Z80Registers.getSlotFromAddress(toAddr); if (toBank != slots[slotIndex]) { this.debugConsoleAppendLine("Memory currently not paged in. (address=" + Utility.getHexString(toBank & 0xFFFF, 4) + "h, bank=" + toBank + ")"); return; } } } // Read the memory. this.debugConsoleAppendLine(''); let size = (toAddr - fromAddr + 1) & 0xFFFF; if (size > 0x800) { size = 0x800; this.debugConsoleAppendLine('Note: Disassembly limited to ' + size + ' bytes.'); } fromAddr &= 0xFFFF //toAddr &= 0xFFFF; const data = await Remote.readMemoryDump(fromAddr, size + 3); // Disassemble const dasmArray = DisassemblyClass.getDasmMemory(fromAddr, data); // Output for (const addrInstr of dasmArray) { this.debugConsoleAppendLine(Utility.getHexString(addrInstr.address, 4) + " " + addrInstr.instruction); } } /** * Called from vscode when the user inputs a command in the command palette. * The method checks if the command is known and executes it. * If the command is unknown the super method is called. * @param command The command, e.g. 'set-memory' * @param response Used for responding. * @param args The arguments of the command. Usually just 1 text object. */ protected async customRequest(command: string, response: DebugProtocol.Response, args: any) { switch (command) { case 'setPcToLine': { const filename = args[0]; const lineNr = args[1]; await this.setPcToLine(filename, lineNr); this.sendResponse(response); } break; case 'disassemblyAtCursor': { const filename = args[0]; const fromLineNr = args[1]; const toLineNr = args[2]; await this.disassemblyAtCursor(filename, fromLineNr, toLineNr); this.sendResponse(response); } break; default: super.customRequest(command, response, args); return; } } /** * Called after a step, step-into, run, hit breakpoint, etc. * Is used to update anything that need to updated after some Z80 instructions have been executed. * E.g. the memory dump view. * @param reason The reason is a data object that contains additional information. * E.g. for 'step' it contains { step: true }; */ protected update(reason?: any) { this.emit('update', reason); } /** * Called from "-state save N" command. * Stores all RAM + the registers. * @param stateName A state name (or number) can be appended, so that different states might be saved. */ protected async stateSave(stateName: string): Promise<void> { // Save state const filePath = Utility.getAbsStateFileName(stateName); try { // Make sure .tmp/states directory exists try { const dir = Utility.getAbsStateFileName(''); fs.mkdirSync(dir); } catch {} // Save state await Remote.stateSave(filePath); } catch (e) { const errTxt = "Can't save '" + filePath + "': " + e.message; throw new Error(errTxt); } } /** * Called from "-state restore N" command. * Restores all RAM + the registers from a former "-state save". * @param stateName A state name (or number) can be appended, so that different states might be saved. */ protected async stateRestore(stateName: string): Promise<void> { // Check if (this.processingSteppingRequest) { throw new Error("Can't restore state while running. Please stop first."); } // Load data from temp directory let filePath; try { // Read data filePath = Utility.getAbsStateFileName(stateName); // Restore state await Remote.stateRestore(filePath); } catch (e) { const errTxt = "Can't load '" + filePath + "': " + e.message; throw new Error(errTxt); } // Clear history StepHistory.init(); // Clear decorations Decoration?.clearAllDecorations(); // Update registers await Remote.getRegistersFromEmulator(); await Remote.getCallStackFromEmulator(); // Update memory etc. this.update(); // Send event this.sendEvent(new StoppedEvent('restore', DebugSessionClass.THREAD_ID)); } /* protected async terminateRequest(response: DebugProtocol.TerminateResponse, args: DebugProtocol.TerminateArguments): Promise<void> { } */ /** * Output indented text to the console. * @param text The output string. */ protected debugConsoleIndentedText(text: string) { this.debugConsoleAppendLine(this.debugConsoleIndentation + text); } } DebugSessionClass.run(DebugSessionClass);
the_stack
import { ObservableArray } from "tns-core-modules/data/observable-array"; import { View, Property, booleanConverter, PropertyChangeData } from "tns-core-modules/ui/core/view"; import { AnimationCurve } from "tns-core-modules/ui/enums"; import { GridLayout } from "tns-core-modules/ui/layouts/grid-layout"; import { TextField } from "tns-core-modules/ui/text-field"; import { isIOS } from "tns-core-modules/platform"; import * as enums from "tns-core-modules/ui/enums"; let builder = require("tns-core-modules/ui/builder"); let unfilteredSource: Array<any> = []; let filtering: boolean = false; export const listWidthProperty = new Property<FilterableListpicker, string>({ name: "listWidth", defaultValue: "300" }); export const listHeightProperty = new Property<FilterableListpicker, string>({ name: "listHeight", defaultValue: "300" }); export const headingTitleProperty = new Property<FilterableListpicker, string>({ name: "headingTitle", defaultValue: undefined }); export const enableSearchProperty = new Property<FilterableListpicker, boolean>( { name: "enableSearch", defaultValue: true, valueConverter: booleanConverter } ); export const showCancelProperty = new Property<FilterableListpicker, boolean>({ name: "showCancel", defaultValue: true, valueConverter: booleanConverter }); export const dimmerColorProperty = new Property<FilterableListpicker, string>({ name: "dimmerColor", defaultValue: "rgba(0,0,0,0.8)" }); export const blurProperty = new Property<FilterableListpicker, string>({ name: "blur", defaultValue: "none" }); export const focusOnShowProperty = new Property<FilterableListpicker, boolean>({ name: "focusOnShow", defaultValue: false }); export const hideFilterProperty = new Property<FilterableListpicker, boolean>({ name: "hideFilter", defaultValue: false }); export const hintTextProperty = new Property<FilterableListpicker, string>({ name: "hintText", defaultValue: "Enter text to filter..." }); export const sourceProperty = new Property< FilterableListpicker, ObservableArray<any> >({ name: "source", defaultValue: undefined, affectsLayout: true, valueChanged: (target, oldValue, newValue) => { if (!filtering) { while (unfilteredSource.length) unfilteredSource.pop(); newValue.forEach(element => { unfilteredSource.push(element); }); } } }); export class FilterableListpicker extends GridLayout { constructor() { super(); this._searchFilter = this._searchFilterFn.bind(this); } onLoaded() { super.onLoaded(); //let innerComponent = builder.load(__dirname + '/filterable-listpicker.xml') as View; let innerComponent = builder.Builder.parse(` <GridLayout id="dc_flp_container" class="flp-container" visibility="collapsed" loaded="{{loadedContainer}}"> <StackLayout tap="{{cancel}}" width="100%" height="100%"></StackLayout> <GridLayout width="{{listWidth}}" verticalAlignment="middle" rows="auto, auto, auto, auto" id="dc_flp" class="flp-list-container" loaded="{{loadedInnerContainer}}"> <Label row="0" text="{{headingTitle ? headingTitle : ''}}" class="flp-heading-title" visibility="{{headingTitle ? 'visible' : 'collapsed'}}"></Label> <TextField hint="{{hintText}}" row="1" text="{{filterText}}" id="filterTextField" class="flp-hint-field" visibility="{{enableSearch ? 'visible' : 'collapsed'}}" loaded="{{loadedTextField}}"></TextField> <ListView items="{{ source }}" row="2" height="{{listHeight}}" itemTap="{{choose}}" class="flp-listview"> <ListView.itemTemplate> <StackLayout class="flp-row"> <GridLayout columns="auto, *, auto" visibility="{{title ? 'visible' : 'collapsed'}}" class="flp-row-container"> <Image src="{{image ? image : null}}" width="30" visibility="{{image ? 'visible' : 'collapsed'}}" stretch="aspectFit" rowSpan="2" class="flp-image"></Image> <StackLayout class="flp-title-container" col="1" verticalAlignment="middle"> <Label text="{{title ? title : ''}}" textWrap="true" class="flp-title"></Label> <Label text="{{description ? description : ''}}" textWrap="true" visibility="{{description ? 'visible' : 'collapsed'}}" class="flp-description"></Label> </StackLayout> <Label col="2" text="{{selected ? selected : ''}}" class="flp-item-selected" visibility="{{selected ? 'visible' : 'collapsed'}}"></Label> </GridLayout> <Label text="{{$value}}" textWrap="true" class="flp-no-title" visibility="{{title ? 'collapsed' : 'visible'}}"></Label> </StackLayout> </ListView.itemTemplate> </ListView> <StackLayout row="3" class="flp-cancel-container" visibility="{{showCancel ? 'visible' : 'collapsed'}}"> <Button text="Cancel" tap="{{cancel}}" verticalAlignment="middle" class="flp-btn-cancel"></Button> </StackLayout> </GridLayout> </GridLayout>`); innerComponent.bindingContext = this; this.addChild(innerComponent); } public static canceledEvent = "canceled"; public static itemTappedEvent = "itemTapped"; public source: any; public dimmerColor: any; public hintText: any; public hideFilter: any; public enableSearch: boolean; public blur: any; private blurView: any = false; public focusOnShow: any; private _container: GridLayout; private _picker: GridLayout; private _textField: TextField; private _searchFilter: (data: any) => void; private _isAutocomplete: boolean = false; private _suggestions: any; visibility: any = enums.Visibility.collapse; loadedContainer(args) { this._container = <GridLayout>args.object; } loadedInnerContainer(args) { this._picker = <GridLayout>args.object; } autocomplete(fn: Function) { if(!this.isAutocomplete) return; if(typeof fn !== "function") throw("[FilterableListPicker]: autotcomplete params must be a Function type !"); /** * Populate sources with suggestions if is defined is usefull if we have a most use list * for the moment user can't search into suggestion .. writing into Textfield will active autocomplete * */ if(!this.source) this.source = []; // Copy suggestion list to bind it when Textfield is empty this._suggestions = this.source; // bind custome autocomplete function this._textField.on("textChange", (data: PropertyChangeData) => { if(!data.value && this._suggestions.length > 0) { this.set("source", this._suggestions) this.notifyPropertyChange("source", this._suggestions); console.log(this._suggestions); return; } fn(data); }) } loadedTextField(args) { this._textField = <TextField>args.object; } public choose(args) { let item = this.source[args.index]; this.hide(); this.notify({ eventName: "itemTapped", object: this, selectedItem: item }); } public cancel() { this.notify({ eventName: "canceled", object: this }); this.hide(); } public hide() { if (this.enableSearch) { if (this._textField.dismissSoftInput) this._textField.dismissSoftInput(); this._textField.text = ""; } if (this.blurView) { UIView.animateWithDurationAnimationsCompletion( 0.3, () => { this.blurView.effect = null; }, () => { this.blurView.removeFromSuperview(); } ); } else { this._container .animate({ opacity: 0, duration: 200 }) .then(_ => {}, err => {}); } if (this.enableSearch) { // cleanup event when closing this._textField.off("textChange", this._searchFilter); } return this._picker .animate({ scale: { x: 0.7, y: 0.7 }, opacity: 0, duration: 400, curve: AnimationCurve.cubicBezier(0.1, 0.1, 0.1, 1) }) .then( () => { this.visibility = enums.Visibility.collapse; this._container.visibility = "collapse"; }, err => {} ); } public show() { this.visibility = enums.Visibility.visible; this._container.visibility = "visible"; this.source = unfilteredSource.filter(i => true); if (isIOS && this.blur && this.blur != "none") { let iosView: UIView = this._container.ios; let effectView = UIVisualEffectView.alloc().init(); effectView.frame = CGRectMake( 0, 0, iosView.bounds.size.width, iosView.bounds.size.height ); effectView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; this.blurView = effectView; iosView.addSubview(effectView); iosView.sendSubviewToBack(effectView); UIView.animateWithDurationAnimationsCompletion( 0.3, () => { let theme = UIBlurEffectStyle.Dark; if (this.blur == "light") theme = UIBlurEffectStyle.Light; effectView.effect = UIBlurEffect.effectWithStyle(theme); }, () => { // the animation is complete. } ); } else { this._container.opacity = 0; this._container.backgroundColor = this.dimmerColor; this._container .animate({ opacity: 1, duration: 200 }) .then(_ => {}, err => {}); } this._picker.scaleX = 0.7; this._picker.scaleY = 0.7; this._picker.opacity = 0; this._picker .animate({ scale: { x: 1, y: 1 }, opacity: 1, duration: 400, curve: AnimationCurve.cubicBezier(0.1, 0.1, 0.1, 1) }) .then(_ => {}, err => {}); if (this.enableSearch) { if (JSON.parse(this.focusOnShow)) this._textField.focus(); this._textField.on("textChange", this._searchFilter); } } get isAutocomplete(): boolean { return this._isAutocomplete; } set isAutocomplete(val: boolean) { if(val === false) { // remve listener for TextField console.log(val) this._textField.off("textChange"); } this._isAutocomplete = val; } private _searchFilterFn(data: any) { filtering = true; this.source = unfilteredSource.filter(item => { if (item.title) { return ( item.title.toLowerCase().indexOf(data.value.toLowerCase()) !== -1 ); } else { return item.toLowerCase().indexOf(data.value.toLowerCase()) !== -1; } }); filtering = false; } } listWidthProperty.register(FilterableListpicker); listHeightProperty.register(FilterableListpicker); headingTitleProperty.register(FilterableListpicker); enableSearchProperty.register(FilterableListpicker); showCancelProperty.register(FilterableListpicker); dimmerColorProperty.register(FilterableListpicker); focusOnShowProperty.register(FilterableListpicker); hideFilterProperty.register(FilterableListpicker); blurProperty.register(FilterableListpicker); hintTextProperty.register(FilterableListpicker); sourceProperty.register(FilterableListpicker); export interface SourcesInterface { title: string; image?: any; description?: string; } export class SourcesDataItem implements SourcesInterface { title: string; image?: any; description?: string; constructor(title: string, image?: any, description?: string) { this.title = title; this.image = image; this.description = description; } }
the_stack
import assert = require("assert") //import fs = require("fs") //import path = require("path") //import _=require("underscore") // //import def = require("raml-definition-system") // import ll=require("../lowLevelAST") import linter=require("../ast.core/linter") import yll=require("../jsyaml/jsyaml2lowLevel") ////import high = require("../highLevelImpl") import hl=require("../highLevelAST") // //import t3 = require("../artifacts/raml10parser") // import util = require("./test-utils") import tools = require("./testTools") import index = require("../../index"); import parserIndex = require("../../index") import parserCore = require("../wrapped-ast/parserCoreApi") //describe('Low level model', function() { describe('Parser integration tests',function(){ this.timeout(15000); it ("Instagram",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/Instagram/api.raml"),[ "Content is not valid according to schema: Expected type string but found type null", "Content is not valid according to schema: Expected type string but found type null", "Content is not valid according to schema: Expected type object but found type null", "Content is not valid according to schema: Expected type object but found type null" ]); }); it ("Omni",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/omni/api.raml")); }); it ("Omni 0.8",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/omni08/api.raml")); }); it ("Cosmetics Overlay",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/cosmetics/hypermedia.raml")); }); it ("Cosmetics Extension",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/cosmetics/hypermedia1.raml")); }); it ("Instagram 1.0",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/Instagram1.0/api.raml")); }); it ("Exchange",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/exchange/api.raml")); }); it ("core services",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/core-services/api.raml"),[ "Can not parse JSON example: Unexpected token '{'", "Can not parse JSON example: Cannot tokenize symbol 'O'", "Can not parse JSON example: Cannot tokenize symbol 'O'" ]); }); it ("cloudhub new logging",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/cloudhub-new-logging/api.raml"),["Can not parse JSON example: Unexpected token '}'"]); }); it ("audit logging",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/audit-logging-query/api.raml")); }); it ("application monitoring",function(){ this.timeout(15000) testErrors(util.data("../example-ramls/application-monitoring/api.raml"),[ "Unrecognized schema: 'appmonitor'" ]); }); //it ("api platform",function(){ // testErrors(util.data("../../../../example-ramls/api-platform/api.raml")); //}); it ("lib1",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/blog-users1/blog-users.raml")); }); it ("lib2",function(){ this.timeout(15000); testErrorsByNumber(util.data("../example-ramls/blog-users2/blog-users.raml"),2,1); }); it ("lib3",function(){ this.timeout(15000); testErrorsByNumber(util.data("../example-ramls/blog-users2/blog-users.raml"),2,1); }); it ("platform2",function(){ this.timeout(15000); testErrors(util.data("../example-ramls/platform2/api.raml"),[],true); }); }); describe('https connection tests',function(){ this.timeout(15000); it ("https 0.8",function(){ this.timeout(15000); testErrors(util.data("parser/https/tr1.raml")); }); it ("https 1.0",function(){ this.timeout(15000); testErrors(util.data("parser/https/tr2.raml")); }); }); describe('Id tests',function(){ this.timeout(15000); it ("Instagram",function(){ this.timeout(15000); testIds(util.data("../example-ramls/Instagram/api.raml")); }); }); describe('Transformers tests',function(){ this.timeout(15000); it ("All transformer from spec should be valid.",function(){ testErrors(util.data("parser/transformers/t1.raml"), ["Unknown function applied to parameter: \'!\\w+\'"]); }); }); describe('Security Schemes tests', function () { this.timeout(15000); it ("should fail if not all required settings specified" ,function(){ testErrors(util.data("parser/securitySchemes/ss1/securityScheme.raml"), ["Missing required property \'\\w+\'"]); }) it ("should pass when extra non-required settings specified" ,function(){ testErrors(util.data("parser/securitySchemes/ss2/securityScheme.raml")); }) it ("should pass when settings contains array property(0.8)" ,function(){ testErrors(util.data("parser/securitySchemes/ss3/securityScheme.raml")); }) it ("should fail when settings contains duplicate required properties(0.8)" ,function(){ testErrors(util.data("parser/securitySchemes/ss4/securityScheme.raml"),["property already used: 'accessTokenUri'", "property already used: 'accessTokenUri'"]); }) it ("should fail when settings contains duplicate required array properties(0.8)" ,function(){ testErrors(util.data("parser/securitySchemes/ss5/securityScheme.raml"), ["property already used: 'authorizationGrants'", "property already used: 'authorizationGrants'", "property already used: 'authorizationGrants'"]); }) it ("should fail when settings contains duplicate non-required properties(0.8)" ,function(){ testErrors(util.data("parser/securitySchemes/ss6/securityScheme.raml"), ["property already used: 'aaa'", "property already used: 'aaa'"]); }) it ("should pass when settings contains required array property(1.0)" ,function(){ testErrors(util.data("parser/securitySchemes/ss7/securityScheme.raml")); }) it ("should fail when settings contains duplicate required properties(1.0)" ,function(){ testErrors(util.data("parser/securitySchemes/ss8/securityScheme.raml"), ["property already used: 'accessTokenUri'", "property already used: 'accessTokenUri'"]); }) it ("should fail when settings contains duplicate required array properties(1.0)" ,function(){ testErrors(util.data("parser/securitySchemes/ss9/securityScheme.raml"), ["property already used: 'authorizationGrants'", "property already used: 'authorizationGrants'"]); }) it ("null-value security schema should be allowed for Api(0.8)" ,function(){ testErrors(util.data("parser/securitySchemes/ss10/securityScheme.raml")); }) it ("grant type validation" ,function(){ testErrors(util.data("parser/custom/oath2.raml"),["'authorizationGrants' value should be one of 'authorization_code', 'implicit', 'password', 'client_credentials' or to be an abolute URI"]); }) it ("security scheme should be a seq in 0.8" ,function(){ testErrorsByNumber(util.data("parser/custom/shemeShouldBeASeq.raml"),1); }) }); describe('Parser regression tests', function () { this.timeout(15000); it ("basic type expression cases should pass validation" ,function(){ testErrors(util.data("parser/typexpressions/basic.raml")); }) it ("inplace types" ,function(){ testErrors(util.data("parser/typexpressions/inplace.raml")); }) it ("template vars0" ,function(){ testErrors(util.data("parser/templates/unknown.raml")); }) //it ("multi dimension and signatures" ,function(){ // testErrors(util.data("parser/typexpressions/multiDimAndSig.raml")); //}) it ("example validation" ,function(){ testErrors(util.data("parser/examples/ex1.raml"), ["Can not parse JSON example: Unexpected token d"]); }) it ("example validation json against schema" ,function(){ testErrors(util.data("parser/examples/ex2.raml"), ["Content is not valid according to schema"]); }) it ("example validation yaml against schema" ,function(){ testErrors(util.data("parser/examples/ex3.raml"), ["Content is not valid according to schema: Additional properties not allowed: vlue"]); }) it ("example validation yaml against basic type" ,function(){ testErrors(util.data("parser/examples/ex4.raml"),["Required property 'c' is missing"]); }) it ("example validation yaml against inherited type" ,function(){ testErrors(util.data("parser/examples/ex5.raml"), ["Required property 'c' is missing"]); }) it ("example validation yaml against array" ,function(){ testErrors(util.data("parser/examples/ex6.raml"),["Required property 'c' is missing"]); }) it ("example in model" ,function(){ testErrors(util.data("parser/examples/ex7.raml"), ["Expected type 'string' but got 'number'","Expected type 'string' but got 'number'","Required property 'c' is missing"]); }) it ("another kind of examples" ,function(){ testErrors(util.data("parser/examples/ex13.raml"), ["Expected type 'boolean' but got 'number'"]); }) it ("example in parameter" ,function(){ testErrors(util.data("parser/examples/ex8.raml"), ["Expected type 'boolean' but got 'string'"]); }) it('Should correctly serialize multiple examples to JSON',function(){ var api=util.loadApi(util.data('parser/examples/ex45.raml')); api = util.expandHighIfNeeded(api); var topLevelApi : any = api.wrapperNode(); var json = topLevelApi.toJSON(); var serializedJSON = JSON.stringify(json); assert.equal(serializedJSON.indexOf("One") > 0, true) assert.equal(serializedJSON.indexOf("Two") > 0, true) }) it ("Should successfully process long string examples" ,function(){ testErrors(util.data("parser/examples/ex46.raml"),["Can not parse JSON example: Cannot tokenize symbol"]); }); it ("checking that node is actually primitive" ,function(){ testErrors(util.data("parser/examples/ex9.raml"), ["Expected type 'string' but got 'object'"]); }) it ("map" ,function(){ testErrors(util.data("parser/examples/ex10.raml")); }) it ("map1" ,function(){ testErrors(util.data("parser/examples/ex11.raml"), ["Expected type 'number' but got 'string'"]); }) it ("map2" ,function(){ testErrors(util.data("parser/examples/ex12.raml"),["Expected type 'number' but got 'string'"]); }) it ("objects are closed" ,function(){ testErrors(util.data("parser/examples/ex14.raml"), ["Unknown property: 'z'"]); }) it ("enums restriction" ,function(){ testErrors(util.data("parser/examples/ex15.raml"),["value should be one of: 'val1', 'val2', '3'"]); }) it ("array facets" ,function(){ testErrors(util.data("parser/examples/ex16.raml"), ["'Person.items.minItems=5' i.e. array items count should not be less than 5", "'Person.items2.maxItems=3' i.e. array items count should not be more than 3", "items should be unique"]); }) it ("array facets2" ,function(){ testErrors(util.data("parser/examples/ex17.raml")); }) it ("array facets3" ,function(){ testErrors(util.data("parser/examples/ex18.raml"), ["'SmallArray.minItems=5' i.e. array items count should not be less than 5"]); }) it ("array facets4" ,function(){ testErrors(util.data("parser/examples/ex19.raml"),["'SmallArray.minItems=5' i.e. array items count should not be less than 5"]); }) it ("object facets1" ,function(){ testErrors(util.data("parser/examples/ex20.raml"), ["'MyType.minProperties=2' i.e. object properties count should not be less than 2"]); }) it ("object facets2" ,function(){ testErrors(util.data("parser/examples/ex21.raml"), ["'MyType1.minProperties=2' i.e. object properties count should not be less than 2"]); }) it ("object facets3" ,function(){ testErrors(util.data("parser/examples/ex22.raml"), ["'MyType1.maxProperties=1' i.e. object properties count should not be more than 1"]); }) it ("object facets4" ,function(){ testErrors(util.data("parser/examples/ex23.raml")); }) it ("object facets5" ,function(){ testErrors(util.data("parser/examples/ex24.raml"), ["'MyType1.minProperties=3' i.e. object properties count should not be less than 3"]); }) it ("string facets1" ,function(){ testErrors(util.data("parser/examples/ex25.raml"), ["'MyType1.minLength=5' i.e. string length should not be less than 5", "'MyType2.maxLength=3' i.e. string length should not be more than 3"]); }) it ("string facets2" ,function(){ testErrors(util.data("parser/examples/ex26.raml")); }) it ("string facets3" ,function(){ testErrors(util.data("parser/examples/ex27.raml"), ["'MyType1.minLength=5' i.e. string length should not be less than 5"]); }) it ("string facets4" ,function(){ testErrors(util.data("parser/examples/ex28.raml"), ["string should match to '\\.5'"]); }) it ("number facets1" ,function(){ testErrors(util.data("parser/examples/ex29.raml"),["'MyType1.minimum=5' i.e. value should not be less than 5", "'MyType1.minimum=5' i.e. value should not be less than 5"]); }) it ("number facets2" ,function(){ testErrors(util.data("parser/examples/ex30.raml")); }) it ("self rec types" ,function(){ testErrors(util.data("parser/examples/ex31.raml")); }) it ("media type" ,function(){ testErrors(util.data("parser/examples/ex32.raml"),["Can not parse JSON example: Unexpected token p"]); }) it ("number 0" ,function(){ testErrors(util.data("parser/examples/ex33.raml")); }) it ("example inside of inplace type" ,function(){ testErrors(util.data("parser/examples/ex34.raml"), ["Required property 'x' is missing","Unknown property: 'x2'"]); }) it ("aws example" ,function(){ testErrors(util.data("parser/examples/ex35.raml")); }) it ("multi unions" ,function(){ testErrors(util.data("parser/examples/ex36.raml")); }) it ("seq and normal mix" ,function(){ testErrors(util.data("parser/custom/seqMix.raml")); }) it ("scalars in examples are parsed correctly" ,function(){ testErrors(util.data("parser/examples/ex42.raml")); }) it ("low level transform understands anchors" ,function(){ testErrors(util.data("parser/examples/ex43.raml")); }) it ("0.8 style of absolute path resolving" ,function(){ testErrors(util.data("parser/custom/res08.raml")); }) it ("example is string 0.8" ,function(){ testErrors(util.data("parser/examples/ex44.raml"),[ "Scalar is expected here" ]); }) it ("enums values restriction" ,function(){ testErrors(util.data("parser/examples/ex37.raml")); }) it ("anonymous type examples validation test 1" ,function(){ testErrors(util.data("parser/examples/ex38.raml")); }) it ("anonymous type examples validation test 2" ,function(){ testErrors(util.data("parser/examples/ex39.raml")); }) it ("example's property validation" ,function(){ testErrorsByNumber(util.data("parser/examples/ex40.raml"),1); }) it ("example's union type property validation" ,function(){ testErrorsByNumber(util.data("parser/examples/ex41.raml"),0); }) it ("union type in schema" ,function(){ testErrors(util.data("parser/typexpressions/unions/api.raml")); }) it ("uri parameters1" ,function(){ testErrors(util.data("parser/uris/u1.raml"), ["Base uri parameter unused"]); }) it ("uri parameters2" ,function(){ testErrors(util.data("parser/uris/u2.raml"), ["Uri parameter unused"]); }) it ("uri parameters3" ,function(){ testErrors(util.data("parser/uris/u3.raml"), ["Unmatched '{'"]); }) it ("uri parameters4" ,function(){ testErrors(util.data("parser/uris/u4.raml"), ["Unmatched '{'"]); }) // No more signatures support //it ("basic signatures" ,function(){ // testErrors(util.data("parser/signatures/basic.raml"), ["aoeu"]); //}) //it ("basic signatures2" ,function(){ // testErrors(util.data("parser/signatures/basic2.raml"), ["aoeu"]); //}) //it ("ok signature" ,function(){ // testErrors(util.data("parser/signatures/ok.raml")); //}) //it ("ok signature2" ,function(){ // testErrors(util.data("parser/signatures/ok2.raml")); //}) //it ("ok signature3" ,function(){ // testErrors(util.data("parser/signatures/ok3.raml")); //}) //it ("ok not signature3" ,function(){ // testErrors(util.data("parser/signatures/ok4.raml")); //}) //it ("ok not signature4" ,function(){ // testErrors(util.data("parser/signatures/ok5.raml")); //}) //it ("fail signature" ,function(){ // testErrors(util.data("parser/signatures/fail1.raml"), ["aoeu"]); //}) //it ("fail signature2" ,function(){ // testErrors(util.data("parser/signatures/fail2.raml"), ["aoeu"]); //}) it ("mediaType1" ,function(){ testErrors(util.data("parser/media/m1.raml"), ["invalid media type"]); }) it ("mediaType2" ,function(){ testErrors(util.data("parser/media/m2.raml"), ["invalid media type"]); }) it ("mediaType3" ,function(){ testErrors(util.data("parser/media/m3.raml"), ["Form related media types can not be used in responses"]); }) it ("annotations1" ,function(){ testErrors(util.data("parser/annotations/a.raml"), ["value should be one of: 'W', 'A'"]); }) it ("annotations2" ,function(){ testErrors(util.data("parser/annotations/a2.raml"), ["Expected type 'boolean' but got 'string'"]); }) it ("annotations3" ,function(){ testErrors(util.data("parser/annotations/a3.raml"), ["Required property 'items' is missing"]); }) it ("annotations4" ,function(){ testErrors(util.data("parser/annotations/a4.raml")); }) it ("annotations5" ,function(){ testErrors(util.data("parser/annotations/a5.raml"), ["Required property 'y' is missing"]); }) it ("annotations6" ,function(){ testErrors(util.data("parser/annotations/a6.raml")); }) it ("annotations7" ,function(){ testErrors(util.data("parser/annotations/a7.raml"), ["Expected type 'boolean' but got 'string'"]); }) it ("annotations8" ,function(){ testErrors(util.data("parser/annotations/a8.raml")); }) it ("annotations9" ,function(){ testErrors(util.data("parser/annotations/a9.raml"), ["Required property 'ee' is missing"]); }) it ("annotations10" ,function(){ testErrors(util.data("parser/annotations/a10.raml")); }) it ("annotations11" ,function(){ testErrors(util.data("parser/annotations/a11.raml"), ["Expected type 'object' but got 'string'"]); }) it ("annotations12" ,function(){ testErrors(util.data("parser/annotations/a12.raml"), ["Expected type 'number' but got 'string'"]); }) it ("annotations13" ,function(){ testErrors(util.data("parser/annotations/a13.raml")); }) it ("annotations14" ,function(){ testErrors(util.data("parser/annotations/a14.raml")); }) it ("annotations15" ,function(){ testErrors(util.data("parser/annotations/a15.raml"), ["Resource property already used: '(meta)'", "Resource property already used: '(meta)'"]); }) it ("annotations16" ,function(){ testErrors(util.data("parser/annotations/a16.raml")); }) it ("annotations17" ,function(){ testErrors(util.data("parser/annotations/a17.raml"), ["Null or undefined value is not allowed","Header 'header1' already exists","Header 'header1' already exists"]); }) it ("annotations18" ,function(){ testErrors(util.data("parser/annotations/a18.raml")); }) it ("annotations19" ,function(){ testErrors(util.data("parser/annotations/a19.raml"), ["inheriting from unknown type"]); }) it ("annotations21" ,function(){ testErrors(util.data("parser/annotations/a21.raml")); }) it ("annotations22" ,function(){ testErrors(util.data("parser/annotations/a22.raml")); }) it ("annotations23" ,function(){ testErrors(util.data("parser/annotations/a23.raml")); }) it ("annotations24" ,function(){ testErrors(util.data("parser/annotations/a24.raml")); }) it ("annotations25" ,function(){ testErrors(util.data("parser/annotations/a25.raml")); }) it ("annotations26 (annotated scalar)" ,function(){ testErrors(util.data("parser/annotations/a26.raml")); }) it ("annotations27 (annotated scalar (validation))" ,function(){ testErrors(util.data("parser/annotations/a27.raml"),["Expected type 'number' but got 'string'"]); }) it ("annotations28 (annotated scalar (unknown))" ,function(){ testErrors(util.data("parser/annotations/a28.raml"),["unknown annotation: 'z2'"]); }) it ("properties shortcut" ,function(){ testErrors(util.data("parser/typexpressions/p.raml")); }) it ("status" ,function(){ testErrors(util.data("parser/status/s1.raml"),["Status code should be 3 digits number."]); }) it ("node names" ,function(){ testErrors(util.data("parser/nodenames/n1.raml"), ["Resource type 'x' already exists","Resource property already used: 'description'","Resource type 'x' already exists","Resource property already used: 'description'"]); }) it ("node names2" ,function(){ testErrors(util.data("parser/nodenames/n2.raml"),["Resource '/frfr' already exists","Api property already used: 'resourceTypes'","Resource '/frfr' already exists","Api property already used: 'resourceTypes'"]); }) //TODO correct test after bug fix it ("recurrent errors" ,function(){ testErrors(util.data("parser/typexpressions/tr.raml"), ["recurrent array type definition","recurrent array type definition"]); }) it ("recurrent errors1" ,function(){ testErrors(util.data("parser/typexpressions/tr1.raml"),["recurrent type definition"] ); }) it ("recurrent errors2" ,function(){ //TODO REVIEW IT testErrorsByNumber(util.data("parser/typexpressions/tr2.raml"),2,1);//Ok for now lets improve later }) //TODO correct test after bug fix it ("recurrent errors3 " ,function(){ testErrors(util.data("parser/typexpressions/tr3.raml"),["recurrent type as an option of union type", "recurrent type as an option of union type", "recurrent type definition"]); }) //TODO correct test after bug fix it ("recurrent errors4" ,function(){ testErrors(util.data("parser/typexpressions/tr4.raml"),["recurrent array type definition", "recurrent array type definition"]); }) it ("recurrent errors5" ,function(){ testErrors(util.data("parser/typexpressions/tr14/test.raml")); }) it ("schema types 1" ,function(){ testErrors(util.data("parser/typexpressions/tr5.raml"));//Ok for now lets improve later }) it ("inheritance rules1" ,function(){ testErrors(util.data("parser/typexpressions/ri1.raml"));//Ok for now lets improve later }) it ("inheritance rules2" ,function(){ testErrors(util.data("parser/typexpressions/ri2.raml"));//Ok for now lets improve later }) it ("multiple default media types" ,function(){ testErrors(util.data("parser/media/m4.raml")); }) //TODO correct test after bug fix it ("inheritance rules3" ,function(){ testErrors(util.data("parser/typexpressions/ri3.raml"), ["Restrictions conflict","Restrictions conflict"]); }) it ("inheritance rules4" ,function(){ testErrors(util.data("parser/typexpressions/ri4.raml"));//Ok for now lets improve later }) //TODO correct test after bug fix it ("inheritance rules5" ,function(){ testErrors(util.data("parser/typexpressions/ri5.raml"),["Restrictions conflict"]); }) //TODO correct test after bug fix it ("inheritance rules6" ,function(){ testErrors(util.data("parser/typexpressions/ri6.raml"), ["Restrictions conflict"]); }) //TODO correct test after bug fix it ("inheritance rules7" ,function(){ testErrors(util.data("parser/typexpressions/ri7.raml"),["Restrictions conflict"]); }) it ("schemas are types 1" ,function(){ testErrors(util.data("parser/typexpressions/tr6.raml"), ["inheriting from unknown type"]); }) it ("type deps" ,function(){ testErrors(util.data("parser/typexpressions/tr7.raml"),["Required property 'element' is missing"]); }) it ("inplace types 00" ,function(){ testErrors(util.data("parser/typexpressions/tr8.raml"),["Null or undefined value is not allowed"]);//Ok for now lets improve later }) it ("unique keys" ,function(){ testErrors(util.data("parser/typexpressions/tr9.raml"),["Keys should be unique"]);//Ok for now lets improve later }) it ("runtime types value" ,function(){ testErrors(util.data("parser/typexpressions/tr10.raml"),["Required property 'y' is missing"]);//Ok for now lets improve later }) it ("runtime types value1" ,function(){ testErrors(util.data("parser/typexpressions/tr11.raml"),["Expected type 'object' but got 'string'"]);//Ok for now lets improve later }) it ("runtime types value2" ,function(){ testErrors(util.data("parser/typexpressions/tr12.raml"));//Ok for now lets improve later }) it ("union can be object at same moment sometimes" ,function(){ testErrors(util.data("parser/typexpressions/tr14.raml"));//Ok for now lets improve later }) it ("no unknown facets in union type are allowed" ,function(){ testErrorsByNumber(util.data("parser/typexpressions/tr15.raml"),1);//Ok for now lets improve later }) it ("sequence composition works in 0.8" ,function(){ testErrors(util.data("parser/custom/seq.raml"));//Ok for now lets improve later }) it ("sequence composition does not works in 1.0" ,function(){ testErrors(util.data("parser/custom/seq1.raml"),["Unknown node: 'a'","Unknown node: 'b'","'traits' should be a map in RAML 1.0"]); }) it ("empty 'traits' array is prohibited in 1.0" ,function(){ testErrors(util.data("parser/custom/seq2.raml"),["'traits' should be a map in RAML 1.0"]); }) it ("authorization grant is any absolute uri" ,function(){ testErrorsByNumber(util.data("parser/custom/grantIsAnyAbsoluteUri.raml"),0);//Ok for now lets improve later }) it ("empty schema is ok in 0.8" ,function(){ testErrorsByNumber(util.data("parser/custom/emptySchema.raml"),0);//Ok for now lets improve later }) it ("properties are map in 1.0" ,function(){ testErrorsByNumber(util.data("parser/custom/propMap.raml"),1);//Ok for now lets improve later }) it ("schema is yml" ,function(){ testErrorsByNumber(util.data("parser/custom/schemaIsyml.raml"),0);//Ok for now lets improve later }) it ("null tag support" ,function(){ testErrorsByNumber(util.data("parser/custom/nullTag.raml"),0);//Ok for now lets improve later }) it ("r2untime types value2" ,function(){ testErrorsByNumber(util.data("parser/typexpressions/tr13.raml"),1,1);//Ok for now lets improve later }) it ("date time format is checked in super types" ,function(){ testErrorsByNumber(util.data("parser/annotations/a31.raml"),0);//Ok for now lets improve later }) it ("date time format is checked in super types (negative)" ,function(){ testErrorsByNumber(util.data("parser/annotations/a32.raml"),1);//Ok for now lets improve later }) it ("unknown annotation in example" ,function(){ testErrors(util.data("parser/annotations/a35.raml"),["using unknown annotation type"]); }) //No more signatures //it ("signatures with inherited classes" ,function(){ // testErrors(util.data("parser/typexpressions/ct1.raml"));//Ok for now lets improve later //}) it ("custom api" ,function(){ testErrors(util.data("parser/custom/api.raml"), ["Missing required property 'title'"]);//Ok for now lets improve later }) it ("discriminator can only be used at top level" ,function(){ testErrorsByNumber(util.data("parser/custom/discTop.raml"), 1);//Ok for now lets improve later }) it ("schemas and types are mutually exclusive" ,function(){ testErrorsByNumber(util.data("parser/custom/schemasAndTypes.raml"), 1);//Ok for now lets improve later }) it ("halt" ,function(){ testErrorsByNumber(util.data("parser/custom/halt.raml"),2,1);//Ok for now lets improve later }) it ("naming rules" ,function(){ testErrors(util.data("parser/custom/naming1.raml"),["Type 'Person' already exists", "Trait 'qq' already exists", "Resource '/ee' already exists","Type 'Person' already exists", "Trait 'qq' already exists", "Resource '/ee' already exists"]); }) it ("resource types test with types" ,function(){ testErrors(util.data("parser/custom/rtypes.raml"));//Ok for now lets improve later }) it ("resource path name uses rightmost segment" ,function(){ testErrors(util.data("parser/resourceType/resType023.raml"));//Ok for now lets improve later }) it ("form parameters are properties" ,function(){ testErrors(util.data("parser/custom/noForm.raml"));//Ok for now lets improve later }) it ("endless loop" ,function(){ testErrorsByNumber(util.data("parser/custom/el.raml"),2,1);//Ok for now lets improve later }) it ("forms can not be in responses" ,function(){ testErrors(util.data("parser/custom/noForm2.raml"),["Form related media types can not be used in responses"]);//Ok for now lets improve later }) it ("APIKey" ,function(){ testErrors(util.data("parser/custom/apiKey.raml"));//Ok for now lets improve later }) it ("Oath1Sig" ,function(){ testErrors(util.data("parser/custom/oath1sig.raml"));//Ok for now lets improve later }) it ("regexp validation" ,function(){ testErrors(util.data("parser/custom/regexp.raml"),["Unterminated group"]); }) it ("regexp validation 2" ,function(){ testErrors(util.data("parser/custom/regexp2.raml"), ["Unterminated group"]); }) it ("regexp validation 3" ,function(){ testErrors(util.data("parser/custom/regexp3.raml"), ["Unterminated group"]); }) it ("spaces in keys" ,function(){ testErrors(util.data("parser/custom/keysSpace.raml"),["Keys should not have spaces '\\w+ '"]);//Ok for now lets improve later }) it ("facets11" ,function(){ testErrors(util.data("parser/facets/f1.raml")); }) it ("facets1" ,function(){ testErrors(util.data("parser/facets/f2.raml"), ["Expected type 'string' but got 'number'"]); }) it ("redeclare buildin" ,function(){ testErrors(util.data("parser/facets/f3.raml"),["redefining a built in type: datetime"]); }) //it ("recursive includes" ,function(){ // testErrors(util.data("parser/recursive/r1.raml")); //}) it ("Library usage in included resource" ,function(){ testErrors(util.data("parser/include/libUsage/api.raml")); }) it ("custom facets validator" ,function(){ testErrors(util.data("commonLibrary/api.raml"), ["Expected type 'string' but got 'number'","Expected type 'string' but got 'number'"]); }) it ("custom facets validator2" ,function(){ testErrors(util.data("commonLibrary/api2.raml"),[]); }) //it ("custom facets validator3" ,function(){ // testErrors(util.data("commonLibrary/api3.raml"), ["object is expected ../../../src/parser/test/data/commonLibrary/common.raml"]); //}) it ("overloading1" ,function(){ testErrors(util.data("parser/overloading/o1.raml"),["Method 'get' already exists","Method 'get' already exists"]); }) it ("overloading2" ,function(){ testErrors(util.data("parser/overloading/o2.raml"),[]); }) it ("overloading3" ,function(){ testErrors(util.data("parser/overloading/o3.raml"),["Resource '/{id}' already exists","Resource '/{id}' already exists"]); }) it ("overloading4" ,function(){ testErrors(util.data("parser/overloading/o4.raml"),[]); }) // it ("overloading6" ,function(){ // testErrors(util.data("parser/overloading/o6.raml"), ["Resources share same URI","Resources share same URI"]); // }) it ("overloading7" ,function(){ testErrors(util.data("parser/overloading/o7.raml"),[]); }) //TODO fix test after bug fix. it ("override1" ,function(){ testErrors(util.data("parser/inheritance/i1.raml"), ["Restrictions conflict"]); }) it ("override2" ,function(){ testErrors(util.data("parser/inheritance/i2.raml"),["Facet 'q' can not be overriden"]); }) it ("override3" ,function(){ testErrors(util.data("parser/inheritance/i3.raml")); }) it ("overlay1" ,function(){ testErrors(util.data("parser/overlay/o1/NewOverlay.raml")); }) it ("overlay2" ,function(){ testErrors(util.data("parser/overlay/o2/NewOverlay.raml"),["The '.env-org-pair2' node does not match any node of the master api."]); }) it ("Overlay: title" ,function(){ testErrors(util.data("parser/overlay/o3/NewOverlay.raml")); }) it ("Overlay: displayName" ,function(){ testErrors(util.data("parser/overlay/o4/NewOverlay.raml")); }) it ("Overlay: annotation types" ,function(){ testErrors(util.data("parser/overlay/o5/NewOverlay.raml")); }) it ("Overlay: types" ,function(){ testErrors(util.data("parser/overlay/o6/NewOverlay.raml")); }) it ("Overlay: schema" ,function(){ testErrors(util.data("parser/overlay/o7/NewOverlay.raml")); }) it ("Overlay: annotations" ,function(){ testErrors(util.data("parser/overlay/o8/NewOverlay.raml")); }) it ("Overlay: usage" ,function(){ testErrors(util.data("parser/overlay/o9/NewOverlay.raml")); }) it ("Overlay: documentation1" ,function(){ testErrors(util.data("parser/overlay/o10/NewOverlay.raml")); }) it ("Overlay: documentation2" ,function(){ testErrors(util.data("parser/overlay/o11/NewOverlay.raml")); }) it ("Overlay: documentation3" ,function(){ testErrors(util.data("parser/overlay/o12/NewOverlay.raml")); }) it ("Overlay: examples1" ,function(){ testErrors(util.data("parser/overlay/o13/NewOverlay.raml")); }) it ("Overlay: examples2" ,function(){ testErrors(util.data("parser/overlay/o14/NewOverlay.raml")); }) it ("Overlay: examples3" ,function(){ testErrors(util.data("parser/overlay/o15/NewOverlay.raml")); }) it ("Overlay: example1" ,function(){ testErrors(util.data("parser/overlay/o16/NewOverlay.raml")); }) it ("Overlay: example2" ,function(){ testErrors(util.data("parser/overlay/o17/NewOverlay.raml")); }) it ("Overlay: top-level illegal property" ,function(){ testErrors(util.data("parser/overlay/o18/NewOverlay.raml"), ["Property 'version' is not allowed to be overriden or added in overlays"]); }) it ("Overlay: sub-level illegal property" ,function(){ testErrors(util.data("parser/overlay/o19/NewOverlay.raml"), ["Property 'default' is not allowed to be overriden or added in overlays"]); }) it ("Overlay: top-level illegal node" ,function(){ testErrors(util.data("parser/overlay/o20/NewOverlay.raml"),["The './resource2' node does not match any node of the master api."]); }) it ("Overlay: sub-level illegal node 1" ,function(){ testErrors(util.data("parser/overlay/o21/NewOverlay.raml"),["The './resource./resource2' node does not match any node of the master api."]); }) it ("Overlay: sub-level illegal node 2" ,function(){ testErrors(util.data("parser/overlay/o22/NewOverlay.raml"),["The './resource.post' node does not match any node of the master api."]); }) it ("Is node must be an array in master API" ,function() { testErrors(util.data("parser/overlay/o23/NewOverlay.raml"), ["Property 'is' must be an array"]); }) it ("Absolute (from root) path are used in API. Ovelay is located in separate folder. The parser must not throw exceptions." ,function() { testErrors(util.data("parser/overlay/OverlayInSeparateFolder/overlays/overlay.raml"), ["Can not resolve /resource.raml","Node '/resource' can not be a scalar"]); }) it ("Security Scheme Fragment: new security scheme" ,function(){ testErrors(util.data("parser/securityschemefragments/ss1/securitySchemeFragment.raml")); }) it ("library is not user class" ,function(){ testErrors(util.data("parser/raml/raml.raml"),["It is only allowed to use scalar properties as discriminators"]); }) it ("library from christian" ,function(){ testErrors(util.data("parser/libraries/christian/api.raml")); }) it ("library in resource type fragment" ,function(){ testErrors(util.data("parser/libraries/fragment/api.raml")); }) it ("library in resource type fragment" ,function(){ testErrors(util.data("parser/libraries/fragment/api.raml")); }) it ("nested uses" ,function(){ testErrors(util.data("parser/libraries/nestedUses/index.raml")); }) it ("library require 1" ,function(){ testErrors(util.data("parser/libraries/require/a.raml")); }) it ("library require 2" ,function(){ testErrors(util.data("parser/libraries/require/b.raml")); }) it ("more complex union types1",function(){ testErrors(util.data("parser/union/apigateway-aws-overlay.raml")); }) it ("more complex union types2",function(){ testErrors(util.data("parser/union/unionSample.raml")); }) it ("external 1" ,function(){ testErrors(util.data("parser/external/e1.raml"),["Content is not valid according to schema: Missing required property: id"]); }) it ("external 2" ,function(){ testErrors(util.data("parser/external/e2.raml")); }) it ("strange names in parameters" ,function(){ testErrors(util.data("parser/custom/strangeParamNames.raml")); }) // it ("external 3" ,function(){ // testErrors(util.data("parser/external/e3.raml"),["Example does not conform to schema:Content is not valid according to schema:Expected type \\w+ but found type \\w+ \\w+,\\w+"]); // }) // it ("external 4" ,function(){ // testErrors(util.data("parser/external/e4.raml"),["Example does not conform to schema:Content is not valid according to schema:Missing required property: \\w+ \\w+"]); // }) // it ("external 5" ,function(){ // testErrors(util.data("parser/external/e5.raml")); // }) it ("should pass without exceptions 1" ,function(){ testErrorsByNumber(util.data("parser/api/api29.raml"), 1); }) it ("should pass without exceptions 2" ,function(){ testErrorsByNumber(util.data("parser/api/api30/api.raml"), 2); }) it ("should pass without exceptions 3" ,function(){ testErrors(util.data("parser/api/api31.raml"), ["Scalar is expected here"]); }) it ("empty type include should produce no error" ,function(){ testErrors(util.data("parser/type/t30.raml")); }) }); describe('XSD schemes tests', function () { this.timeout(15000); it("XSD Scheme test 1" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test1/apiValid.raml"), 0); }) it("XSD Scheme test 2" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test1/apiInvalid.raml"), 1); }) it("XSD Scheme test 3" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test2/apiValid.raml"), 0); }) it("XSD Scheme test 4" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test2/apiInvalid.raml"), 1); }) it("XSD Scheme test 5" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test3/apiValid.raml"), 0); }) it("XSD Scheme test 6" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test3/apiInvalid.raml"), 1); }) it("XSD Scheme test 7" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test4/apiValid.raml"), 0); }) it("XSD Scheme test 8" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test4/apiInvalid.raml"), 1); }) it("XSD Scheme test 9" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test5/apiValid.raml"), 0); }) it("XSD Scheme test 10" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test5/apiInvalid.raml"), 1); }) it("XSD Scheme test 11" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test6/apiValid.raml"), 0); }) it("XSD Scheme test 12" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test6/apiInvalid.raml"), 1); }) it("XSD Scheme test 13" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test7/apiValid.raml"), 0); }) it("XSD Scheme test 14" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test7/apiInvalid.raml"), 1); }) it("XSD Scheme test 15" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test8/apiValid.raml"), 0); }) it("XSD Scheme test 16" ,function() { testErrorsByNumber(util.data("parser/xsdscheme/test8/apiInvalid.raml"), 1); }) it("Empty schemas must not be reported as unresolved" ,function() { testErrors(util.data("parser/schemas/emptySchemaTest/api.raml")); }) it("Inlining schemas in JSON for RAML 0.8" ,function() { var api=util.loadApi(util.data("parser/schemas/RAML08SchemasInlining/api.raml")); var json = api.wrapperNode().toJSON({ rootNodeDetails: true, dumpSchemaContents: true }); util.compareToFileObject(json,util.data("parser/schemas/RAML08SchemasInlining/api-tck.json")); }) }); describe('XML parsing tests', function () { this.timeout(15000); it("XML parsing tests 1" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test1/apiValid.raml"), 0); }) it("XML parsing tests 2" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test1/apiInvalid1.raml"), 1); }) it("XML parsing tests 3" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test1/apiInvalid2.raml"), 1); }) it("XML parsing tests 4" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test1/apiInvalid3.raml"), 1); }) it("XML parsing tests 5" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test1/apiInvalid4.raml")); }) it("XML parsing tests 6" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test2/apiValid.raml"), 0); }) it("XML parsing tests 7" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test2/apiInvalid1.raml"), 1); }) it("XML parsing tests 8" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test2/apiInvalid2.raml"), 1); }) it("XML parsing tests 9" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test2/apiInvalid3.raml"), 1); }) it("XML parsing tests 10" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test2/apiInvalid4.raml"), 1); }) it("XML parsing tests 11" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test2/apiInvalid5.raml"), 1); }) it("XML parsing tests 12" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test3/apiValid.raml"), 0); }) it("XML parsing tests 13" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test3/apiInvalid1.raml"), 1); }) it("XML parsing tests 14" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test3/apiInvalid2.raml"), 1); }) it("XML parsing tests 15" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test3/apiInvalid3.raml"), 2); }) it("XML parsing tests 16" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test3/apiInvalid4.raml"), 1); }) it("XML parsing tests 17" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test3/apiInvalid5.raml"), 1); }) it("XML parsing tests 18" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test3/apiInvalid6.raml"), 1); }) it("XML parsing tests 19" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test3/apiInvalid7.raml"), 1); }) it("XML parsing tests 20" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test4/apiValid.raml"), 0); }) it("XML parsing tests 21" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test4/apiInvalid1.raml"), 1); }) it("XML parsing tests 22" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test4/apiInvalid2.raml"), 1); }) it("XML parsing tests 23" ,function() { testErrorsByNumber(util.data("parser/xmlfacets/test4/apiInvalid3.raml"), 1); }) }); describe('JSON schemes tests', function () { this.timeout(15000); it("JSON Scheme test 1" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test1/apiValid.raml")); }) it("JSON Scheme test 2" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test1/apiInvalid.raml"), ["Missing required property: name"]); }) it("JSON Scheme test 3" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test2/apiValid.raml")); }) it("JSON Scheme test 4" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test2/apiInvalid.raml"), ["Missing required property: name"]); }) it("JSON Scheme test 5" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test3/apiValid.raml")); }) it("JSON Scheme test 6" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test3/apiInvalid.raml"), ["Missing required property: name"]); }) it("JSON Scheme test 7" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test4/apiValid.raml")); }) it("JSON Scheme test 8" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test4/apiInvalid.raml"), ["Missing required property: name"]); }) it("JSON Scheme test 9" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test5/apiValid.raml")); }) it("JSON Scheme test 10" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test5/apiInvalid.raml"), ["Missing required property: innerTypeName"]); }) it("JSON Scheme test 11" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test6/apiValid.raml")); }) it("JSON Scheme test 12" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test6/apiInvalid.raml"), ["Missing required property: innerTypeName"]); }) it("JSON Scheme test 13" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test7/apiValid.raml")); }) it("JSON Scheme test 14" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test7/apiInvalid.raml"), ["Missing required property: innerTypeName"]); }) it("JSON Scheme test 15" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test8/apiValid.raml")); }) it("JSON Scheme test 16" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test8/apiInvalid.raml"), ["Missing required property: childName"]); }) it("JSON Scheme test 17" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test9/apiValid.raml")); }) it("JSON Scheme test 18" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test9/apiInvalid.raml"), ["Missing required property: childName"]); }) it("JSON Scheme test 19" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test10/apiValid.raml")); }) it("JSON Scheme test 20" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test10/apiInvalid.raml"), ["Missing required property: innerTypeName"]); }) it("JSON Scheme test 21" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test11/apiValid.raml")); }) it("JSON Scheme test 22" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test11/apiInvalid.raml"), ["Missing required property: innerTypeName"]); }) it("JSON Scheme test 23" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test8/apiValid0.raml")); }) it("JSON Scheme test 24" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test8/apiInvalid0.raml"), ["Missing required property: childName"]); }) it("JSON Scheme test 25" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test12/api.raml"), ["Can not parse JSON example: Unexpected token '}'"]); }) it("JSON Scheme test 26" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test13/api.raml"), ["Invalid JSON schema: Reference could not be resolved:"]); }) it("Ignore unknown strig format 1" ,function() { this.timeout(15000); testErrors(util.data("schema/ignoreFormats1.raml")); }) it("Ignore unknown number format 1" ,function() { this.timeout(15000); testErrors(util.data("schema/ignoreFormats2.raml")); }) it("String instead of object as property definition" ,function() { this.timeout(15000); testErrors(util.data("schema/invalidProperty.raml"),["(Invalid JSON schema: Unexpected value)|(Invalid JSON schema: Assignment to non-object.)"]); }) it("JOSN schema test Pets 10-3-inline-rtype-included-schema-filename.raml" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test-pets/ramls/10-3-inline-rtype-included-schema-filename.raml")); }); it("JOSN schema test Pets 10-1-included-rtype-included-schema-flat.raml" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test-pets/ramls/10-1-included-rtype-included-schema-flat.raml")); }); it("JOSN schema test Pets 10-2-included-rtype-included-schema-filename.raml" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test-pets/ramls/10-2-included-rtype-included-schema-filename.raml")); }); it("JOSN schema test Pets 08-1-included-rtype-included-schema-flat.raml" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test-pets/ramls/08-1-included-rtype-included-schema-flat.raml")); }); it("JOSN schema test Pets 08-2-included-rtype-included-schema-filename.raml" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test-pets/ramls/08-2-included-rtype-included-schema-filename.raml")); }); it("JOSN schema test Pets 08-3-inline-rtype-included-schema-filename.raml" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test-pets/ramls/08-3-inline-rtype-included-schema-filename.raml")); }); it("JOSN schema test Pets 08-4-included-schema-filename.raml" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test-pets/ramls/08-4-included-schema-filename.raml")); }); it("JOSN schema test Pets 10-4-included-schema-filename.raml" ,function() { this.timeout(15000); testErrors(util.data("parser/jsonscheme/test-pets/ramls/10-4-included-schema-filename.raml")); }); }); describe("Include tests + typesystem",function (){ this.timeout(15000); it("Include test" ,function() { this.timeout(15000); testErrorsByNumber(util.data("parser/include/includeTypes.raml")); }) it("Combination of empty include with expansion" ,function() { this.timeout(15000); testErrors(util.data("parser/include/emptyInclude.raml"),["JS-YAML: !include without value", "Can not resolve null"]); }) it("Including empty fragments" ,function() { this.timeout(15000); testErrors(util.data("parser/include/includeEmptyFiles/api.raml"),["Missing required property 'type'"]); }) }) describe('Parse strings', function () { this.timeout(15000); it('scalar should include both start/end quotes #parse-str1', function () { var api = util.loadApi(util.data('parser/strings/str1.raml')); //console.log(api.lowLevel().unit().contents()); //api.lowLevel().show('API'); var elementsOfKind = api.elementsOfKind('resources'); var resource = <hl.IHighLevelNode>tools.collectionItem(elementsOfKind,0); //console.log('is text: ' + (<jsyaml.ASTNode>resource.attr('description').lowLevel()).text()); var attr = resource.attr('description'); //attr.lowLevel().show('ATTR:'); util.assertText(attr, 'description: "hello world"'); util.assertValue(attr, 'hello world'); util.assertValueText(attr, '"hello world"'); }); it('scalar should include both start/end quotes #parse-str2', function () { var api = util.loadApi(util.data('parser/strings/str2.raml')); //console.log(api.lowLevel().unit().contents()); //(<yll.ASTNode>api.lowLevel()).show('ORIGINAL API'); var elementsOfKind = api.elementsOfKind('resources'); var resource = <hl.IHighLevelNode>tools.collectionItem(elementsOfKind,0); //console.log('is text: ' + (<jsyaml.ASTNode>resource.attr('description').lowLevel()).text()); var attr = resource.attr('description'); util.assertText(attr, "description: 'hello world'"); util.assertValue(attr, 'hello world'); util.assertValueText(attr, "'hello world'"); }); it('scalar should include both start/end quotes #parse-str3', function () { var api = util.loadApi(util.data('parser/strings/str3.raml')); //console.log(api.lowLevel().unit().contents()); //(<yll.ASTNode>api.lowLevel()).show('ORIGINAL API'); var elementsOfKind = api.elementsOfKind('resources'); var resource = <hl.IHighLevelNode>tools.collectionItem(elementsOfKind,0); //console.log('is text: ' + (<jsyaml.ASTNode>resource.attr('description').lowLevel()).text()); var attr = resource.attr('description'); util.assertText(attr, 'description: ""'); util.assertValue(attr, ''); util.assertValueText(attr, '""'); }); it('scalar should include both start/end quotes #parse-str4', function () { var api = util.loadApi(util.data('parser/strings/str4.raml')); //console.log(api.lowLevel().unit().contents()); //(<yll.ASTNode>api.lowLevel()).show('ORIGINAL API'); var elementsOfKind = api.elementsOfKind('resources'); var resource = <hl.IHighLevelNode>tools.collectionItem(elementsOfKind,0); //console.log('is text: ' + (<jsyaml.ASTNode>resource.attr('description').lowLevel()).text()); var attr = resource.attr('description'); util.assertText(attr, "description: ''"); util.assertValue(attr, ''); util.assertValueText(attr, "''"); }); }); describe('Property override tests',function(){ this.timeout(15000); it ("Planets",function(){ testErrors(util.data("parser/propertyOverride/test1.raml"),["'enum' facet value must be defined by array"]); }); it ("User type properties: correct",function(){ testErrors(util.data("parser/propertyOverride/test2.raml")); }); //TODO fix test after bug fix it ("User type properties: incorrect",function(){ testErrors(util.data("parser/propertyOverride/test3.raml"), ["Restrictions conflict"]); }); it ("Value type properties 1",function(){ testErrors(util.data("parser/propertyOverride/test4.raml")); }); it ("Value type properties 2",function(){ testErrors(util.data("parser/propertyOverride/test5.raml")); }); it ("Value type properties 3",function(){ testErrors(util.data("parser/propertyOverride/test6.raml")); }); it ("Required property overridden as optional",function(){ testErrors(util.data("parser/propertyOverride/test7.raml"), ["Can not override required property 'testProperty' to be optional"]); }); it ("Value type properties 4",function(){ testErrors(util.data("parser/propertyOverride/test8.raml")); }); it ("Facet override",function(){ testErrors(util.data("parser/propertyOverride/test9.raml"), ["Facet 'test' can not be overriden","missing required facets"]); }); it ("Optional property overridden as required",function(){ testErrors(util.data("parser/propertyOverride/test10.raml")); }); //TODO this test should be revised. //it ("Not existing include should not throw exception in java",function(){ // testErrors(util.data("parser/custom/includes1.raml")); //}); it ("existing include should not report any errros",function(){ testErrors(util.data("parser/custom/includes2.raml")); }); it ("should parse types which are valid only after expansion",function(){ testErrors(util.data("parser/templates/validAfterExpansion.raml")); }); it ("should not accept resouces which are not valid only after expansion",function(){ testErrorsByNumber(util.data("parser/templates/invalidAfterExpansion.raml"),1); }); it ("resource definition should be a map",function(){ testErrors(util.data("parser/custom/resShouldBeMap.raml"),["Resource definition should be a map"]); }); it ("documentation should be a sequence",function(){ testErrors(util.data("parser/custom/docShouldBeSequence.raml"),["Property 'documentation' should be a sequence"]); }); it ("Title value must be specified in 0.8",function(){ testErrors(util.data("parser/custom/missedTitle.raml"),["Value is not provided for required property 'title'"]); }); it ("Title value must be specified in 1.0",function(){ testErrors(util.data("parser/custom/missedTitle10.raml"),["Value is not provided for required property 'title'"]); }); it ("expander not halted by this sample any more",function(){ testErrorsByNumber(util.data("parser/custom/expanderHalt.raml"),10); }); }); describe('Line mapper tests',function() { this.timeout(15000); it("Test that columns and line numbers start from 1", function () { testErrorsWithLineNumber(util.data("parser/lineNumbers/t1.raml"),3,0); }); it("Test that columns and line numbers start from 1 another incarnation", function () { testErrorsWithLineNumber(util.data("parser/lineNumbers/t2.raml"),2,0); }); it("Test that end is not to big", function () { testErrorsEnd(util.data("parser/custom/positionFix.raml")); }); }); describe('Fragment loading', function () { this.timeout(15000); it('DataType loading', function () { var fragment = util.loadRAML(util.data('parser/fragment/DataType.raml')); var fragmentName = fragment.definition().nameId(); assert.equal(fragmentName, "ObjectTypeDeclaration") }); it('Trait loading', function () { var fragment = util.loadRAML(util.data('parser/fragment/Trait.raml')); var fragmentName = fragment.definition().nameId(); assert.equal(fragmentName, "Trait") }); // it('AnnotationTypeDeclaration loading', function () { // testErrorsByNumber(util.data("parser/fragment/AnnotationTypeDeclaration.raml"), 0); // }); }); describe('Optional template parameters tests', function () { this.timeout(15000); it("Should not report error on unspecified parameter, which is not used after expansion #1.", function () { testErrors(util.data("parser/optionalTemplateParameters/api01.raml")); }); it("Should report error on unspecified parameter, which is used after expansion #1.", function () { testErrors(util.data("parser/optionalTemplateParameters/api02.raml") ,["Value is not provided for parameter: 'param1'"]); }); it("Should not report error on unspecified parameter, which is not used after expansion #2.", function () { testErrors(util.data("parser/optionalTemplateParameters/api03.raml")); }); it("Should report error on unspecified parameter, which is used after expansion #2.", function () { testErrors(util.data("parser/optionalTemplateParameters/api04.raml") ,["Value is not provided for parameter: 'param1'"]); }); it("Should not report error on unspecified parameter, which is not used after expansion #3.", function () { testErrors(util.data("parser/optionalTemplateParameters/api05.raml")); }); it("Should not report error on unspecified parameter, which is not used after expansion #4.", function () { testErrors(util.data("parser/optionalTemplateParameters/api06.raml")); }); it("Should not report error on unspecified parameter, which is not used after expansion #5.", function () { testErrors(util.data("parser/optionalTemplateParameters/api07.raml")); }); it("Should not report error on unspecified parameter, which is not used after expansion #6.", function () { testErrors(util.data("parser/optionalTemplateParameters/api08.raml")); }); it("Should not report error on unspecified parameter, which is not used after expansion #7.", function () { testErrors(util.data("parser/optionalTemplateParameters/api09.raml")); }); it("Only methods are permitted to be optional in sense of templates expansion.", function () { testErrors(util.data("parser/illegalOptionalParameters/api01.raml") ,["Only method nodes can be optional"]); }); }); describe('RAML10/Dead Loop Tests/Includes',function(){ this.timeout(15000); it("test001", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Includes/test001/api.raml"),["Recursive definition"]); }); it("test002", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Includes/test002/api.raml"),["Recursive definition"]); }); it("test003", function () { this.timeout(15000); testErrorsByNumber(util.data("./parser/deadLoopTests/Includes/test003/file1.raml"),2); }); it("test004", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Includes/test002/api.raml"),["Recursive definition"]); }); }); describe('RAML10/Dead Loop Tests/JSONSchemas',function(){ this.timeout(15000); it("test001", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/JSONSchemas/test001/api.raml"),["JSON schema contains circular references","JSON schema contains circular references"]); }); it("test002", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/JSONSchemas/test002/api.raml"),["JSON schema contains circular references","JSON schema contains circular references"]); }); it("test003", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/JSONSchemas/test003/api.raml"),[ "Can not parse JSON example: Unexpected end of JSON input", "Can not parse JSON example: Unexpected end of JSON input" ]); }); }); describe('RAML10/Dead Loop Tests/Libraries',function(){ this.timeout(15000); it("test001", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Libraries/test001/lib.raml")); }); it("test002", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Libraries/test002/lib.raml")); }); it("test003", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Libraries/test003/lib1.raml")); }); it("test003", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Libraries/test003/lib2.raml")); }); it("test004", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Libraries/test004/lib1.raml")); }); it("test004", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Libraries/test004/lib2.raml")); }); it("test005", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Libraries/test005/api.raml")); }); it("test006", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/Libraries/test006/api.raml"),["Property 'p1' refers to unknown type 'Issue1Reason'", "Property 'p2' refers to unknown type 'Issue2Reason'"]); }); }); describe('RAML10/Dead Loop Tests/ResourceTypes',function(){ this.timeout(15000); it("test001", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/ResourceTypes/test001/api.raml"),["Resource type definition contains cycle"]); }); it("test002", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/ResourceTypes/test002/lib1.raml")); }); it("test003", function () { this.timeout(15000); testErrors(util.data("./parser/deadLoopTests/ResourceTypes/test002/lib2.raml")); }); }); describe('Dumps',function(){ this.timeout(15000); it("dump1", function () { testDump(util.data("dump/dump1/api.raml"), {dumpXMLRepresentationOfExamples: true}); }); }); describe('New API',function(){ this.timeout(15000); it("'expandLibraries' == true by default", function () { var p = util.data("parser/libraries/nestedUses/index.raml"); var json = index.loadSync(p); var spec = json['specification']; assert(spec['traits'][0]['name']=='files.hello'); }); }); describe('JSON Extension default attributes',function(){ this.timeout(15000); it("securedBy", function () { var p = util.data("extensions/test58Extension.raml"); var json = index.loadSync(p); var spec = json['specification']; assert(spec['resources'][0]['methods'][0]['securedBy'][0]["name"]=="oauth2_0"); }); it("securedBy2", function () { var p = util.data("extensions/test59Extension.raml"); var json = index.loadSync(p); var spec = json['specification']; assert(spec['resources'][0]['methods'][0]['securedBy'][0]["name"]=="oauth2_0"); }); }); describe('Template tests', function () { it("templates test 1", function () { testErrors(util.data("./parser/templates/example_1/api.raml"), [], false, [],{ rejectOnErrors: true}); }); it("templates test 2", function () { testErrors(util.data("./parser/templates/example_2/api.raml"), [], false, [],{ rejectOnErrors: true}); }); }); describe('Errors in extensions',function(){ this.timeout(15000); it("error in base", function () { this.timeout(15000); testErrors(util.data("./extensions/examples/error_in_base/base.raml"), ["Inheriting from unknown type"], false, [util.data("./extensions/examples/error_in_base/extension_1.raml"), util.data("./extensions/examples/error_in_base/extension_2.raml")]); }); it("error in extension 1", function () { this.timeout(15000); testErrors(util.data("./extensions/examples/error_in_extension_1/base.raml"), ["Inheriting from unknown type"], false, [util.data("./extensions/examples/error_in_extension_1/extension_1.raml"), util.data("./extensions/examples/error_in_extension_1/extension_2.raml")]); }); it("error in extension 2", function () { this.timeout(15000); testErrors(util.data("./extensions/examples/error_in_extension_2/base.raml"), ["Inheriting from unknown type"], false, [util.data("./extensions/examples/error_in_extension_2/extension_1.raml"), util.data("./extensions/examples/error_in_extension_2/extension_2.raml")]); }); }); function testDump(apiPath: string, options: any) { var api = util.loadApi(apiPath); var dumpPath = util.dumpPath(apiPath); util.compareDump(api.wrapperNode().toJSON(options), dumpPath, apiPath); } function testErrorsWithLineNumber(p:string,lineNumber: number, column:number) { var api = util.loadApi(p); var errors:any = util.validateNode(api); var issue:hl.ValidationIssue =errors[0]; var position:ll.TextPosition=null; if (typeof issue.node =="function"){ var javaposition=(<any>issue).start(); assert.equal(javaposition.column(),column); assert.equal(javaposition.line(),lineNumber); } else{ position=issue.node.lowLevel().unit().lineMapper().position(issue.start); assert.equal(position.column,column); assert.equal(position.line,lineNumber); } } function testErrorsEnd(p:string) { var api = util.loadApi(p); var errors:any = util.validateNode(api); var issue:hl.ValidationIssue =errors[0]; assert.equal(issue.end<api.lowLevel().unit().contents().length,true); } export function testErrors(p:string, expectedErrors=[],ignoreWarnings:boolean=false, extensions:string[] = [],opts:parserCore.Options = {}){ console.log("Starting test errors for " + p) // var api=util.loadApi(p); // api = util.expandHighIfNeeded(api); let topLevel = parserIndex.loadRAMLSync(p, extensions, opts); let api = topLevel.highLevel(); api = util.expandHighIfNeeded(<any>api); var errors:any=util.validateNode(api); if (ignoreWarnings){ errors=errors.filter(x=>!x.isWarning); } var testErrors; var hasUnexpectedErr = false; if(expectedErrors.length>0){ testErrors = validateErrors(errors, expectedErrors); hasUnexpectedErr = testErrors.unexpected.length > 0 || testErrors.lostExpected.length > 0; } var condition:boolean = false; condition = errors.length == expectedErrors.length; if(!condition) { if (errors.length > 0) { errors.forEach(error=>{ if (typeof error.message == 'string') { console.error(error.message); } else { console.error(error); } console.error("\n"); }) } } var errorMsg = ''; if (hasUnexpectedErr){ if (testErrors.unexpected.length > 0) { errorMsg += "\nUnexpected errors: \n\n"; testErrors.unexpected.forEach(unexpectedError=> { errorMsg += unexpectedError + "\n\n"; }); } if (testErrors.lostExpected.length > 0){ errorMsg += "\nDisappeared expected errors: \n\n" testErrors.lostExpected.forEach(lostExpected=>{ errorMsg += lostExpected + "\n\n"; }); } } if (hasUnexpectedErr || errors.length != expectedErrors.length) { console.warn("Expected errors:"); expectedErrors.forEach(expectedError=>console.warn(expectedError)); var unitContents = api.lowLevel().unit().contents(); console.warn("Actual errors:"); errors.forEach(error=>console.warn(error.message + " : " + unitContents.substr(error.start, error.end-error.start))); } console.log("Before asserting test errors for " + p) assert.equal(hasUnexpectedErr, false, "Unexpected errors found\n"+errorMsg); assert.equal(errors.length, expectedErrors.length, "Wrong number of errors\n"+errorMsg); console.log("Finishing test errors for " + p) } function testIds(p:string){ var api=util.loadApi(p); testId(api); } function testId(n:hl.IParseResult){ //console.log(n.id()); if (n!=n.root()) { var nnn = n.root().findById(n.id()); assert.equal(nnn != null, true) } var children = n.children(); var l = tools.getLength(children); for(var i = 0 ; i < l ; i++){ var item = tools.collectionItem(children,i); testId(item); } } function escapeRegexp(regexp: string) { return regexp.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } function validateErrors(realErrors:any, expectedErrors:string[]){ var errors = {'unexpected': [], 'lostExpected': []}; if (realErrors.length > 0){ realErrors.forEach(error=>{ var realError: string; if (typeof error.message == 'string'){ realError = error.message; }else{ realError = error; } var isExpectedError:boolean = false; expectedErrors.forEach(expectedError=>{ var index = realError.search(new RegExp(expectedError, "mi")); if (index>-1) { isExpectedError = true; } else { index = realError.search(new RegExp(escapeRegexp(expectedError), "mi")); if (index>-1) isExpectedError = true; } }); if (!isExpectedError) errors.unexpected.push(realError); }); expectedErrors.forEach(expectedError=>{ var isLostError = true; realErrors.forEach(error=>{ var realError: string; if (typeof error.message == 'string'){ realError = error.message; }else{ realError = error; } var index = realError.search(new RegExp(expectedError, "i")) if (index > -1) { isLostError = false; } else { index = realError.search(new RegExp(escapeRegexp(expectedError), "i")); if (index > -1) isLostError = false; } }); if (isLostError) errors.lostExpected.push(expectedError); }); } return errors; } function testErrorsByNumber(p:string,count:number=0,deviations:number=0){ var api=util.loadApi(p); var errors:any=util.validateNode(api); var condition:boolean = false; if(deviations==0){ condition = errors.length == count; } else if(deviations>0){ condition = errors.length >= count; } else{ condition = errors.length <= count; } if(!condition) { if (errors.length > 0) { errors.forEach(error=>{ if (typeof error.message == 'string') { console.warn(error.message); } else { console.warn(error); } console.warn("\n"); }) } else { //console.log(errors) } } if(deviations==0) { assert.equal(errors.length, count); } else if(deviations>0){ assert.equal(errors.length>=count, true); } else{ assert.equal(errors.length<=count, true); } }
the_stack
* Defines the alignment for the elements in map. */ export type Alignment = /** Specifies the element to be placed near the maps. */ 'Near' | /** Specifies the element to be placed at the center of the maps. */ 'Center' | /** Specifies the element to be placed far from the maps. */ 'Far'; /** * Defines the theme supported for maps. */ export type MapsTheme = /** Renders a map with material theme. */ 'Material' | /** Renders a map with fabric theme. */ 'Fabric' | /** Renders a map with highcontrast light theme. */ 'HighContrastLight' | /** Renders a map with bootstrap theme. */ 'Bootstrap' | /** Renders a map with material dark theme. */ 'MaterialDark'| /** Renders a map with fabric dark theme. */ 'FabricDark'| /** Renders a map with highcontrast dark theme. */ 'HighContrast'| /** Renders a map with bootstrap dark theme. */ 'BootstrapDark'| /** Renders a map with bootstrap4 theme. */ 'Bootstrap4' | /** Renders a map with Tailwind theme. */ 'Tailwind' | /** Renders a map with TailwindDark theme. */ 'TailwindDark' | /** Renders a map with Bootstrap5 theme. */ 'Bootstrap5' | /** Render a map with Bootstrap5 dark theme. */ 'Bootstrap5Dark' | /** Renders a map with Fluent theme. */ 'Fluent' | /** Render a map with Fluent dark theme. */ 'FluentDark'; /** * Defines the position of the legend. */ export type LegendPosition = /** Specifies the legend to be placed on the top of maps. */ 'Top' | /** Specifies the legend to be placed to the left of maps. */ 'Left' | /** Specifies the legend to be placed at the bottom of maps. */ 'Bottom' | /** Specifies the legend to be placed to the right of maps. */ 'Right' | /** Specifies the legend to be placed based on given x and y location. */ 'Float'; /** * Defines the type of the element in the map for which legend is to be rendered. */ export type LegendType = /** Renders the legend based on layers. */ 'Layers' | /** Renders the legend based on bubbles. */ 'Bubbles' | /** Renders the legend based on markers. */ 'Markers'; /** * Defines the smart label mode for the data-label. Smart label handles the data label text when it exceeds the shape. */ export type SmartLabelMode = /** Trims the datalabel which exceed the region. */ 'Trim' | /** Smart label mode is not applied. */ 'None' | /** Hides the datalabel which exceeds the region. */ 'Hide'; /** * Defines the arrow position in navigation line. */ export type ArrowPosition = /** Defines the arrow to be positioned at the start of the navigation line. */ 'Start' | /** Defines the arrow to be positioned at the end of the navigation line. */ 'End'; /** * Defines the label intersect action. Label interaction action handles the data label text * when it intersects with other data label contents. */ export type IntersectAction = /** Specifies the data label to be trimmed when it intersects. */ 'Trim' | /** Specifies that no action will be taken when it intersects. */ 'None' | /** Specifies the data label to be hidden when it intersects. */ 'Hide'; /** * Defines the mode of the legend. */ export type LegendMode = /** Specifies the legend as static. */ 'Default' | /** Specifies the legend as interactive. */ 'Interactive'; /** * Defines the type of the layer in the map. */ export type ShapeLayerType = /** * Defines the map layer as geometry shapes. */ 'Geometry' | /** * Defines the map layer as open street map. */ 'OSM' | /** * Defines the map layer as bing. */ 'Bing' | /** * Specifies the map layer as google static map. */ 'GoogleStaticMap' | /** * Specifies the map layer as google map. */ 'Google'; /** * Defines the type of the layer in maps. */ export type Type = /** * Specifies the layer type as main layer in the maps component. */ 'Layer' | /** * Specifies the layer type as sublayer in the maps component. This layer will be a part of the layer provided in the maps. */ 'SubLayer'; /** * Defines the type of markers in the maps component. */ export type MarkerType = /** Specifies to render the marker shape as circle on maps. */ 'Circle' | /** Specifies to render the marker shape as rectangle on maps. */ 'Rectangle' | /** Specifies to render the marker shape as cross on maps. */ 'Cross' | /** Specifies to render the marker shape as diamond on maps. */ 'Diamond' | /** Specifies to render the marker shape as star on maps. */ 'Star' | /** Specifies to render the marker shape as balloon on maps. */ 'Balloon' | /** Specifies to render the marker shape as triangle on maps. */ 'Triangle' | /** Specifies to render the marker shape as horizontal line on maps. */ 'HorizontalLine' | /** Specifies to render the marker shape as vertical line on maps. */ 'VerticalLine' | /** Specifies to render the marker shape as image on maps. */ 'Image' | /** Specifies to render the marker shape as inverted triangle on maps. */ 'InvertedTriangle' | /** Specifies to render the marker shape as pentagon on maps. */ 'Pentagon'; /** * Defines the projection type of the maps. */ export type ProjectionType = /** Specifies the maps to render in mercator projection type. */ 'Mercator' | /** Specifies the maps to render in winklel3 projection type. */ 'Winkel3' | /** Specifies the maps to render in miller projection type. */ 'Miller' | /** Specifies the maps to render in eckert3 projection type. */ 'Eckert3' | /** Specifies the maps to render in eckert5 projection type. */ 'Eckert5' | /** Specifies the maps to render in eckert6 projection type. */ 'Eckert6' | /** Specifies the maps to render in ait off projection type. */ 'AitOff' | /** Specifies the maps to render in equirectangular projection type. */ 'Equirectangular'; /** * Defines the types of bing map. */ export type BingMapType = /** Defines the maps to render bing map layer with aerial type. */ 'Aerial' | /** Defines the maps to render bing map layer with aerial with label type. */ 'AerialWithLabel' | /** Defines the maps to render bing map layer with road type. */ 'Road' | /** Defines the maps to render a dark version of the road maps. */ 'CanvasDark' | /** Defines the maps to render a lighter version of the road maps. */ 'CanvasLight' | /** Defines the maps to render a grayscale version of the road maps. */ 'CanvasGray'; /** * Defines the types of maps. */ export type StaticMapType = /** Specifies the maps to render google map layer with road map type. */ 'RoadMap' | /** Specifies the maps to render google map layer with terrain type. */ 'Terrain' | /** Specifies the maps to render google map layer with satellite type. */ 'Satellite' | /** Specifies the maps to render the google map with hybrid type. */ 'Hybrid'; /** * Defines the zooming tool bar orientation. */ export type Orientation = /** Specifies the zooming toolbar to be placed horizontally. */ 'Horizontal' | /** Specifies the zooming toolbar to be placed vertically. */ 'Vertical'; /** * Defines the shape of legend. */ export type LegendShape = /** Specifies the legend shape as a circle. */ 'Circle' | /** Specifies the legend shape as a rectangle. */ 'Rectangle' | /** Specifies the legend shape as a triangle. */ 'Triangle' | /** Specifies the legend shape as a diamond. */ 'Diamond' | /** Specifies the legend shape as a cross. */ 'Cross' | /** Specifies the legend shape as a star. */ 'Star' | /** Specifies the legend shape as a horizontal line. */ 'HorizontalLine' | /** Specifies the legend shape as a vertical line. */ 'VerticalLine' | /** Specifies the legend shape as a pentagon. */ 'Pentagon' | /** Specifies the legend shape as a inverted triangle. */ 'InvertedTriangle'| /** Specifies to render the marker shape as balloon on maps. */ 'Balloon'; /** * Defines the legend arrangement in the maps component. */ export type LegendArrangement = /** Specifies the legend item to be placed by default based on legend orientation. */ 'None' | /** Specifies the legend items to be placed horizontally. */ 'Horizontal' | /** Specifies the legend items to be placed vertically. */ 'Vertical'; /** * Defines the alignment for the annotation. */ export type AnnotationAlignment = /** Specifies the annotation to be placed by default alignement. */ 'None' | /** Specifies the annotation to be placed near the maps with respect to the position of the legend. */ 'Near' | /** Specifies the annotation to be placed at the center of the maps with respect to the position of the legend. */ 'Center' | /** Specifies the annotation to be placed far from the maps with respect to the position of the legend. */ 'Far'; /** * Defines the geometry type. */ export type GeometryType = /** Specifies the geometry rendering in the layer of the maps. */ 'Geographic' | /** Specifies the maps in normal rendering. */ 'Normal'; /** * Defines the type of the bubble. */ export type BubbleType = /** Specifies the bubble as circle type. */ 'Circle' | /** Specifies the bubble as square type. */ 'Square'; /** * Defines the placement type of the label. */ export type LabelPosition = /** Specifies the label placement as before. */ 'Before' | /** Specifies the label placement as after. */ 'After'; /** * Defines the label intersect action in the maps component. */ export type LabelIntersectAction = /** * Specifies that no action will be taken when the label contents intersect. */ 'None' | /** * Specifies the data label to be trimmed when it intersects. */ 'Trim' | /** * Specifies the data label to be hidden when it intersects. */ 'Hide'; /** * Specifies the export type for the maps. */ export type ExportType = /** Specifies the rendered maps to be exported in the png format. */ 'PNG' | /** Specifies the rendered maps to be exported in the jpeg format. */ 'JPEG' | /** Specifies the rendered maps to be exported in the svg format. */ 'SVG' | /** Specifies the rendered maps to be exported in the pdf format. */ 'PDF'; /** * Specifies the direction of panning. */ export type PanDirection = /** Specifies the maps to pan in the left direction. */ 'Left' | /** Specifies the maps to pan in the right direction. */ 'Right' | /** Specifies the maps to pan in the top direction. */ 'Top' | /** Specifies the maps to pan in the bottom direction. */ 'Bottom' | /** Specifies the maps to pan map by mouse move. */ 'None'; /** * Specifies the tooltip to be rendered on mouse operation. */ export type TooltipGesture = /** Specifies the tooltip to be shown on mouse hover event. */ 'MouseMove' | /** Specifies the tooltip to be shown on click event. */ 'Click' | /** Specifies the tooltip to be shown on double click event. */ 'DoubleClick';
the_stack
import { faFile, faFolder } from '@fortawesome/free-regular-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { History, LocationState } from 'history'; import React from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { Button, Form, FormGroup, Input, Label, Table } from 'reactstrap'; import { AnyAction, compose, Dispatch } from 'redux'; import { FileView, withErrors, withFetchDataFromPath, withFluidContainer, withLoadingMessage, withTextAreaResize, Paginator, } from '@alluxio/common-ui/src/components'; import { IAlertErrors, IFileBlockInfo, IFileInfo, IRequest, ICommonState } from '@alluxio/common-ui/src/constants'; import { createAlertErrors, disableFormSubmit, renderFileNameLink } from '@alluxio/common-ui/src/utilities'; import { IApplicationState } from '../../../store'; import { fetchRequest } from '../../../store/browse/actions'; import { IBrowse } from '../../../store/browse/types'; import { IInit } from '../../../store/init/types'; import './Browse.css'; import { routePaths } from '../../../constants'; export interface IPropsFromState extends ICommonState { browseData: IBrowse; initData: IInit; } interface IPropsFromDispatch { fetchRequest: typeof fetchRequest; } interface IBrowseProps { history: History<LocationState>; location: { search: string }; queryStringSuffix: string; request: IRequest; textAreaHeight: number; updateRequestParameter: (reqParam: string, value: string | undefined) => void; } export type AllProps = IPropsFromState & IBrowseProps & IPropsFromDispatch; export class BrowsePresenter extends React.Component<AllProps> { public render(): JSX.Element { const { browseData, initData, queryStringSuffix } = this.props; return ( <div className="col-12"> {!browseData.currentDirectory.isDirectory ? this.renderFileView(initData, browseData, queryStringSuffix) : this.renderDirectoryListing(initData, browseData)} </div> ); } private renderFileView(initData: IInit, browseData: IBrowse, queryStringSuffix: string): JSX.Element { const { request: { offset, end, path }, history, textAreaHeight, } = this.props; const offsetInputHandler = this.createInputChangeHandler('offset').bind(this); const beginInputHandler = this.createButtonHandler('end', undefined).bind(this); const endInputHandler = this.createButtonHandler('end', '1').bind(this); return ( <React.Fragment> <FileView allowDownload={true} beginInputHandler={beginInputHandler} end={end} endInputHandler={endInputHandler} offset={offset} offsetInputHandler={offsetInputHandler} path={path} queryStringPrefix={routePaths.browse} queryStringSuffix={queryStringSuffix} textAreaHeight={textAreaHeight} viewData={browseData} history={history} proxyDownloadApiUrl={initData.proxyDownloadFileApiUrl} /> <hr /> <h6>Detailed blocks information (block capacity is {browseData.blockSizeBytes} Bytes):</h6> <Table hover={true}> <thead> <tr> <th>ID</th> <th>Size (Byte)</th> <th>In {browseData.highestTierAlias}</th> <th>Locations</th> </tr> </thead> <tbody> {browseData.fileBlocks.map((fileBlock: IFileBlockInfo) => ( <tr key={fileBlock.id}> <td>{fileBlock.id}</td> <td>{fileBlock.blockLength}</td> <td>{fileBlock.isInHighestTier ? 'YES' : 'NO'}</td> <td> {fileBlock.locations.map((location: string) => ( <div key={location}>{location}</div> ))} </td> </tr> ))} </tbody> </Table> </React.Fragment> ); } private renderDirectoryListing(initData: IInit, browseData: IBrowse): JSX.Element { const { request: { limit, offset, path }, history, } = this.props; const fileInfos = browseData.fileInfos; const pathInputHandler = this.createInputChangeHandler('path').bind(this); return ( <React.Fragment> <Form className="mb-3 browse-directory-form" id="browseDirectoryForm" inline={true} onSubmit={disableFormSubmit} > <FormGroup className="mb-2 mr-sm-2"> <Button tag={Link} to={`/browse?path=/`} color="secondary" outline={true}> Root </Button> </FormGroup> <FormGroup className="mb-2 mr-sm-2"> <Label for="browsePath" className="mr-sm-2"> Path </Label> <Input type="text" id="browsePath" placeholder="Enter a Path" value={path || '/'} onChange={pathInputHandler} onKeyUp={this.createInputEnterHandler(history, () => `/browse?path=${path}`)} /> </FormGroup> <FormGroup className="mb-2 mr-sm-2"> <Button tag={Link} to={`/browse?path=${encodeURIComponent(path || '/')}`} color="secondary"> Go </Button> </FormGroup> </Form> <Table hover={true}> <thead> <tr> <th /> {/* Icon placeholder */} <th>File Name</th> <th>Size</th> <th>Block Size</th> <th>In-Alluxio</th> {browseData.showPermissions && ( <React.Fragment> <th>Mode</th> <th>Owner</th> <th>Group</th> </React.Fragment> )} <th>Persistence State</th> <th>Pin</th> <th>Creation Time</th> <th>Modification Time</th> {initData.debug && ( <React.Fragment> <th>[D]DepID</th> <th>[D]INumber</th> <th>[D]UnderfsPath</th> <th>[D]File Locations</th> </React.Fragment> )} </tr> </thead> <tbody> {fileInfos && fileInfos.map((fileInfo: IFileInfo) => ( <tr key={fileInfo.absolutePath}> <td> <FontAwesomeIcon icon={fileInfo.isDirectory ? faFolder : faFile} /> </td> <td>{renderFileNameLink(fileInfo.absolutePath, `/browse?path=`)}</td> <td>{fileInfo.size}</td> <td>{fileInfo.blockSizeBytes}</td> <td>{fileInfo.inAlluxioPercentage}%</td> {browseData.showPermissions && ( <React.Fragment> <td> <pre className="mb-0"> <code>{fileInfo.mode}</code> </pre> </td> <td>{fileInfo.owner}</td> <td>{fileInfo.group}</td> </React.Fragment> )} <td>{fileInfo.persistenceState}</td> <td>{fileInfo.pinned ? 'YES' : 'NO'}</td> <td>{fileInfo.creationTime}</td> <td>{fileInfo.modificationTime}</td> {initData.debug && ( <React.Fragment> <td>{fileInfo.id}</td> <td> {fileInfo.fileLocations.map((location: string) => ( <div key={location}>location</div> ))} </td> <td>{fileInfo.absolutePath}</td> <td> {fileInfo.fileLocations.map((location: string) => ( <div key={location}>{location}</div> ))} </td> </React.Fragment> )} </tr> ))} </tbody> </Table> <Paginator baseUrl={routePaths.browse} path={path} total={browseData.ntotalFile} offset={offset} limit={limit} /> </React.Fragment> ); } private createInputChangeHandler(reqParam: string): (e: React.ChangeEvent<HTMLInputElement>) => void { return (event: React.ChangeEvent<HTMLInputElement>): void => { this.props.updateRequestParameter(reqParam, event.target.value); }; } private createButtonHandler(reqParam: string, value: string | undefined): () => void { return (): void => { this.props.updateRequestParameter(reqParam, value); }; } private createInputEnterHandler( history: History<LocationState>, stateValueCallback: (value: string) => string | undefined, ) { return (event: React.KeyboardEvent<HTMLInputElement>): void => { const value = event.key; if (event.key === 'Enter') { const newPath = stateValueCallback(value); if (newPath) { if (history) { history.push(newPath); } } } }; } } const mapStateToProps = ({ browse, init, refresh }: IApplicationState): IPropsFromState => { const errors: IAlertErrors = createAlertErrors(init.errors !== undefined || browse.errors !== undefined, [ browse.data.accessControlException, browse.data.fatalError, browse.data.fileDoesNotExistException, browse.data.invalidPathError, browse.data.invalidPathException, ]); return { browseData: browse.data, initData: init.data, refresh: refresh.data, loading: browse.loading || init.loading, class: 'browse-page', errors: errors, }; }; const mapDispatchToProps = (dispatch: Dispatch): { fetchRequest: (request: IRequest) => AnyAction } => ({ fetchRequest: (request: IRequest): AnyAction => dispatch(fetchRequest(request)), }); export default compose( connect( mapStateToProps, mapDispatchToProps, ), withFetchDataFromPath, withErrors, withLoadingMessage, withTextAreaResize, withFluidContainer, )(BrowsePresenter) as typeof React.Component;
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as Data from './dex-data'; import {Condition, DexConditions} from './dex-conditions'; import {DataMove, DexMoves} from './dex-moves'; import {Item, DexItems} from './dex-items'; import {Ability, DexAbilities} from './dex-abilities'; import {Species, DexSpecies} from './dex-species'; import {Format, DexFormats} from './dex-formats'; import {Utils} from '../lib'; const BASE_MOD = 'gen8' as ID; // to account for Sucrase const DATA_PATH = __dirname.endsWith('.sim-dist') ? `../.data-dist` : `../data`; const DATA_DIR = path.resolve(__dirname, DATA_PATH); const MODS_DIR = path.resolve(DATA_DIR, './mods'); const dexes: {[mod: string]: ModdedDex} = Object.create(null); type DataType = 'Abilities' | 'Rulesets' | 'FormatsData' | 'Items' | 'Learnsets' | 'Moves' | 'Natures' | 'Pokedex' | 'Scripts' | 'Conditions' | 'TypeChart'; const DATA_TYPES: (DataType | 'Aliases')[] = [ 'Abilities', 'Rulesets', 'FormatsData', 'Items', 'Learnsets', 'Moves', 'Natures', 'Pokedex', 'Scripts', 'Conditions', 'TypeChart', ]; const DATA_FILES = { Abilities: 'abilities', Aliases: 'aliases', Rulesets: 'rulesets', FormatsData: 'formats-data', Items: 'items', Learnsets: 'learnsets', Moves: 'moves', Natures: 'natures', Pokedex: 'pokedex', Scripts: 'scripts', Conditions: 'conditions', TypeChart: 'typechart', }; interface DexTable<T> { [key: string]: T; } interface DexTableData { Abilities: DexTable<AbilityData>; Aliases: {[id: string]: string}; Rulesets: DexTable<FormatData>; FormatsData: DexTable<import('./dex-species').ModdedSpeciesFormatsData>; Items: DexTable<ItemData>; Learnsets: DexTable<LearnsetData>; Moves: DexTable<MoveData>; Natures: DexTable<NatureData>; Pokedex: DexTable<SpeciesData>; Scripts: DexTable<AnyObject>; Conditions: DexTable<EffectData>; TypeChart: DexTable<TypeData>; } interface TextTableData { Abilities: DexTable<AbilityText>; Items: DexTable<ItemText>; Moves: DexTable<MoveText>; Pokedex: DexTable<PokedexText>; Default: DexTable<DefaultText>; } export const toID = Data.toID; export class ModdedDex { readonly Data = Data; readonly Condition = Condition; readonly Ability = Ability; readonly Item = Item; readonly Move = DataMove; readonly Species = Species; readonly Format = Format; readonly ModdedDex = ModdedDex; readonly name = "[ModdedDex]"; readonly isBase: boolean; readonly currentMod: string; readonly dataDir: string; readonly toID = Data.toID; gen = 0; parentMod = ''; modsLoaded = false; dataCache: DexTableData | null; textCache: TextTableData | null; deepClone = Utils.deepClone; readonly formats: DexFormats; readonly abilities: DexAbilities; readonly items: DexItems; readonly moves: DexMoves; readonly species: DexSpecies; readonly conditions: DexConditions; readonly natures: Data.DexNatures; readonly types: Data.DexTypes; readonly stats: Data.DexStats; constructor(mod = 'base') { this.isBase = (mod === 'base'); this.currentMod = mod; this.dataDir = (this.isBase ? DATA_DIR : MODS_DIR + '/' + this.currentMod); this.dataCache = null; this.textCache = null; this.formats = new DexFormats(this); this.abilities = new DexAbilities(this); this.items = new DexItems(this); this.moves = new DexMoves(this); this.species = new DexSpecies(this); this.conditions = new DexConditions(this); this.natures = new Data.DexNatures(this); this.types = new Data.DexTypes(this); this.stats = new Data.DexStats(this); } get data(): DexTableData { return this.loadData(); } get dexes(): {[mod: string]: ModdedDex} { this.includeMods(); return dexes; } mod(mod: string | undefined): ModdedDex { if (!dexes['base'].modsLoaded) dexes['base'].includeMods(); return dexes[mod || 'base']; } forGen(gen: number) { if (!gen) return this; return this.mod(`gen${gen}`); } forFormat(format: Format | string): ModdedDex { if (!this.modsLoaded) this.includeMods(); const mod = this.formats.get(format).mod; return dexes[mod || BASE_MOD].includeData(); } modData(dataType: DataType, id: string) { if (this.isBase) return this.data[dataType][id]; if (this.data[dataType][id] !== dexes[this.parentMod].data[dataType][id]) return this.data[dataType][id]; return (this.data[dataType][id] = Utils.deepClone(this.data[dataType][id])); } effectToString() { return this.name; } /** * Sanitizes a username or Pokemon nickname * * Returns the passed name, sanitized for safe use as a name in the PS * protocol. * * Such a string must uphold these guarantees: * - must not contain any ASCII whitespace character other than a space * - must not start or end with a space character * - must not contain any of: | , [ ] * - must not be the empty string * - must not contain Unicode RTL control characters * * If no such string can be found, returns the empty string. Calling * functions are expected to check for that condition and deal with it * accordingly. * * getName also enforces that there are not multiple consecutive space * characters in the name, although this is not strictly necessary for * safety. */ getName(name: any): string { if (typeof name !== 'string' && typeof name !== 'number') return ''; name = ('' + name).replace(/[|\s[\],\u202e]+/g, ' ').trim(); if (name.length > 18) name = name.substr(0, 18).trim(); // remove zalgo name = name.replace( /[\u0300-\u036f\u0483-\u0489\u0610-\u0615\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06ED\u0E31\u0E34-\u0E3A\u0E47-\u0E4E]{3,}/g, '' ); name = name.replace(/[\u239b-\u23b9]/g, ''); return name; } /** * Returns false if the target is immune; true otherwise. * Also checks immunity to some statuses. */ getImmunity( source: {type: string} | string, target: {getTypes: () => string[]} | {types: string[]} | string[] | string ): boolean { const sourceType: string = typeof source !== 'string' ? source.type : source; // @ts-ignore const targetTyping: string[] | string = target.getTypes?.() || target.types || target; if (Array.isArray(targetTyping)) { for (const type of targetTyping) { if (!this.getImmunity(sourceType, type)) return false; } return true; } const typeData = this.types.get(targetTyping); if (typeData && typeData.damageTaken[sourceType] === 3) return false; return true; } getEffectiveness( source: {type: string} | string, target: {getTypes: () => string[]} | {types: string[]} | string[] | string ): number { const sourceType: string = typeof source !== 'string' ? source.type : source; // @ts-ignore const targetTyping: string[] | string = target.getTypes?.() || target.types || target; let totalTypeMod = 0; if (Array.isArray(targetTyping)) { for (const type of targetTyping) { totalTypeMod += this.getEffectiveness(sourceType, type); } return totalTypeMod; } const typeData = this.types.get(targetTyping); if (!typeData) return 0; switch (typeData.damageTaken[sourceType]) { case 1: return 1; // super-effective case 2: return -1; // resist // in case of weird situations like Gravity, immunity is handled elsewhere default: return 0; } } getDescs(table: keyof TextTableData, id: ID, dataEntry: AnyObject) { if (dataEntry.shortDesc) { return { desc: dataEntry.desc, shortDesc: dataEntry.shortDesc, }; } const entry = this.loadTextData()[table][id]; if (!entry) return null; const descs = { desc: '', shortDesc: '', }; for (let i = this.gen; i < dexes['base'].gen; i++) { const curDesc = entry[`gen${i}` as keyof typeof entry]?.desc; const curShortDesc = entry[`gen${i}` as keyof typeof entry]?.shortDesc; if (!descs.desc && curDesc) { descs.desc = curDesc; } if (!descs.shortDesc && curShortDesc) { descs.shortDesc = curShortDesc; } if (descs.desc && descs.shortDesc) break; } if (!descs.shortDesc) descs.shortDesc = entry.shortDesc || ''; if (!descs.desc) descs.desc = entry.desc || descs.shortDesc; return descs; } /** * Ensure we're working on a copy of a move (and make a copy if we aren't) * * Remember: "ensure" - by default, it won't make a copy of a copy: * moveCopy === Dex.getActiveMove(moveCopy) * * If you really want to, use: * moveCopyCopy = Dex.getActiveMove(moveCopy.id) */ getActiveMove(move: Move | string): ActiveMove { if (move && typeof (move as ActiveMove).hit === 'number') return move as ActiveMove; move = this.moves.get(move); const moveCopy: ActiveMove = this.deepClone(move); moveCopy.hit = 0; return moveCopy; } getHiddenPower(ivs: AnyObject) { const hpTypes = [ 'Fighting', 'Flying', 'Poison', 'Ground', 'Rock', 'Bug', 'Ghost', 'Steel', 'Fire', 'Water', 'Grass', 'Electric', 'Psychic', 'Ice', 'Dragon', 'Dark', ]; const tr = this.trunc; const stats = {hp: 31, atk: 31, def: 31, spe: 31, spa: 31, spd: 31}; if (this.gen <= 2) { // Gen 2 specific Hidden Power check. IVs are still treated 0-31 so we get them 0-15 const atkDV = tr(ivs.atk / 2); const defDV = tr(ivs.def / 2); const speDV = tr(ivs.spe / 2); const spcDV = tr(ivs.spa / 2); return { type: hpTypes[4 * (atkDV % 4) + (defDV % 4)], power: tr( (5 * ((spcDV >> 3) + (2 * (speDV >> 3)) + (4 * (defDV >> 3)) + (8 * (atkDV >> 3))) + (spcDV % 4)) / 2 + 31 ), }; } else { // Hidden Power check for Gen 3 onwards let hpTypeX = 0; let hpPowerX = 0; let i = 1; for (const s in stats) { hpTypeX += i * (ivs[s] % 2); hpPowerX += i * (tr(ivs[s] / 2) % 2); i *= 2; } return { type: hpTypes[tr(hpTypeX * 15 / 63)], // After Gen 6, Hidden Power is always 60 base power power: (this.gen && this.gen < 6) ? tr(hpPowerX * 40 / 63) + 30 : 60, }; } } /** * Truncate a number into an unsigned 32-bit integer, for * compatibility with the cartridge games' math systems. */ trunc(num: number, bits = 0) { if (bits) return (num >>> 0) % (2 ** bits); return num >>> 0; } dataSearch( target: string, searchIn?: ('Pokedex' | 'Moves' | 'Abilities' | 'Items' | 'Natures')[] | null, isInexact?: boolean ): AnyObject[] | null { if (!target) return null; searchIn = searchIn || ['Pokedex', 'Moves', 'Abilities', 'Items', 'Natures']; const searchObjects = { Pokedex: 'species', Moves: 'moves', Abilities: 'abilities', Items: 'items', Natures: 'natures', } as const; const searchTypes = { Pokedex: 'pokemon', Moves: 'move', Abilities: 'ability', Items: 'item', Natures: 'nature', } as const; let searchResults: AnyObject[] | null = []; for (const table of searchIn) { const res: AnyObject = this[searchObjects[table]].get(target); if (res.exists && res.gen <= this.gen) { searchResults.push({ isInexact, searchType: searchTypes[table], name: res.name, }); } } if (searchResults.length) return searchResults; if (isInexact) return null; // prevent infinite loop const cmpTarget = toID(target); let maxLd = 3; if (cmpTarget.length <= 1) { return null; } else if (cmpTarget.length <= 4) { maxLd = 1; } else if (cmpTarget.length <= 6) { maxLd = 2; } searchResults = null; for (const table of [...searchIn, 'Aliases'] as DataType[]) { const searchObj = this.data[table]; if (!searchObj) continue; for (const j in searchObj) { const ld = Utils.levenshtein(cmpTarget, j, maxLd); if (ld <= maxLd) { const word = (searchObj[j] as DexTable<any>).name || (searchObj[j] as DexTable<any>).species || j; const results = this.dataSearch(word, searchIn, word); if (results) { searchResults = results; maxLd = ld; } } } } return searchResults; } loadDataFile(basePath: string, dataType: DataType | 'Aliases'): AnyObject { try { const filePath = basePath + DATA_FILES[dataType]; const dataObject = require(filePath); if (!dataObject || typeof dataObject !== 'object') { throw new TypeError(`${filePath}, if it exists, must export a non-null object`); } if (dataObject[dataType]?.constructor?.name !== 'Object') { throw new TypeError(`${filePath}, if it exists, must export an object whose '${dataType}' property is an Object`); } return dataObject[dataType]; } catch (e: any) { if (e.code !== 'MODULE_NOT_FOUND' && e.code !== 'ENOENT') { throw e; } } return {}; } loadTextFile( name: string, exportName: string ): DexTable<MoveText | ItemText | AbilityText | PokedexText | DefaultText> { return require(`${DATA_DIR}/text/${name}`)[exportName]; } includeMods(): this { if (!this.isBase) throw new Error(`This must be called on the base Dex`); if (this.modsLoaded) return this; for (const mod of fs.readdirSync(MODS_DIR)) { dexes[mod] = new ModdedDex(mod); } this.modsLoaded = true; return this; } includeModData(): this { for (const mod in this.dexes) { dexes[mod].includeData(); } return this; } includeData(): this { this.loadData(); return this; } loadTextData() { if (dexes['base'].textCache) return dexes['base'].textCache; dexes['base'].textCache = { Pokedex: this.loadTextFile('pokedex', 'PokedexText') as DexTable<PokedexText>, Moves: this.loadTextFile('moves', 'MovesText') as DexTable<MoveText>, Abilities: this.loadTextFile('abilities', 'AbilitiesText') as DexTable<AbilityText>, Items: this.loadTextFile('items', 'ItemsText') as DexTable<ItemText>, Default: this.loadTextFile('default', 'DefaultText') as DexTable<DefaultText>, }; return dexes['base'].textCache; } loadData(): DexTableData { if (this.dataCache) return this.dataCache; dexes['base'].includeMods(); const dataCache: {[k in keyof DexTableData]?: any} = {}; const basePath = this.dataDir + '/'; const Scripts = this.loadDataFile(basePath, 'Scripts'); this.parentMod = this.isBase ? '' : (Scripts.inherit || 'base'); let parentDex; if (this.parentMod) { parentDex = dexes[this.parentMod]; if (!parentDex || parentDex === this) { throw new Error( `Unable to load ${this.currentMod}. 'inherit' in scripts.ts should specify a parent mod from which to inherit data, or must be not specified.` ); } } if (!parentDex) { // Formats are inherited by mods and used by Rulesets this.includeFormats(); } for (const dataType of DATA_TYPES.concat('Aliases')) { const BattleData = this.loadDataFile(basePath, dataType); if (BattleData !== dataCache[dataType]) dataCache[dataType] = Object.assign(BattleData, dataCache[dataType]); if (dataType === 'Rulesets' && !parentDex) { for (const format of this.formats.all()) { BattleData[format.id] = {...format, ruleTable: null}; } } } if (parentDex) { for (const dataType of DATA_TYPES) { const parentTypedData: DexTable<any> = parentDex.data[dataType]; const childTypedData: DexTable<any> = dataCache[dataType] || (dataCache[dataType] = {}); for (const entryId in parentTypedData) { if (childTypedData[entryId] === null) { // null means don't inherit delete childTypedData[entryId]; } else if (!(entryId in childTypedData)) { // If it doesn't exist it's inherited from the parent data if (dataType === 'Pokedex') { // Pokedex entries can be modified too many different ways // e.g. inheriting different formats-data/learnsets childTypedData[entryId] = this.deepClone(parentTypedData[entryId]); } else { childTypedData[entryId] = parentTypedData[entryId]; } } else if (childTypedData[entryId] && childTypedData[entryId].inherit) { // {inherit: true} can be used to modify only parts of the parent data, // instead of overwriting entirely delete childTypedData[entryId].inherit; // Merge parent into children entry, preserving existing childs' properties. for (const key in parentTypedData[entryId]) { if (key in childTypedData[entryId]) continue; childTypedData[entryId][key] = parentTypedData[entryId][key]; } } } } dataCache['Aliases'] = parentDex.data['Aliases']; } // Flag the generation. Required for team validator. this.gen = dataCache.Scripts.gen; if (!this.gen) throw new Error(`Mod ${this.currentMod} needs a generation number in scripts.js`); this.dataCache = dataCache as DexTableData; // Execute initialization script. if (Scripts.init) Scripts.init.call(this); return this.dataCache; } includeFormats(): this { this.formats.load(); return this; } } dexes['base'] = new ModdedDex(); // "gen8" is an alias for the current base data dexes[BASE_MOD] = dexes['base']; export const Dex = dexes['base']; export namespace Dex { export type Species = import('./dex-species').Species; export type Item = import('./dex-items').Item; export type Move = import('./dex-moves').Move; export type Ability = import('./dex-abilities').Ability; export type HitEffect = import('./dex-moves').HitEffect; export type SecondaryEffect = import('./dex-moves').SecondaryEffect; export type RuleTable = import('./dex-formats').RuleTable; } export default Dex;
the_stack
import { ts } from 'ts-morph'; import { Position, TextDocument } from 'vscode-html-languageservice'; import { MarkupKind } from 'vscode-languageserver'; import { UriUtils } from '../../common/view/uri-utils'; import { AbstractRegion } from '../../core/regions/ViewRegions'; import { AureliaProgram } from '../../core/viewModel/AureliaProgram'; export const VIRTUAL_SOURCE_FILENAME = 'virtual.ts'; export const VIRTUAL_METHOD_NAME = '__vir'; export interface VirtualSourceFileInfo { virtualSourcefile: ts.SourceFile; virtualCursorIndex: number; viewModelFilePath?: string; } interface VirtualLanguageServiceOptions { /** * If triggered in my-compo.html, then go to my-compo.ts */ relatedViewModel?: boolean; /** * Will overwrite `relatedViewModel`, for custom source file */ sourceFile?: ts.SourceFile; /** * Extract data from given region. */ region?: AbstractRegion; /** * Content to be passed into virtual file. */ virtualContent?: string; /** * Offset for language service */ virtualCursorOffset?: number; /** * In the virtual file put the cursor at the start of the method name. * Used when eg. you want to get definition info. */ startAtBeginningOfMethodInVirtualFile?: boolean; } const DEFAULT_VIRTUAL_LANGUAGE_SERVICE_OPTIONS: VirtualLanguageServiceOptions = {}; /** * Leaned on ts.LanguageService. */ export interface VirtualLanguageService { getCompletionsAtPosition: () => void; getCompletionEntryDetails: () => void; getDefinitionAtPosition: () => readonly ts.DefinitionInfo[] | undefined; getQuickInfoAtPosition: () => CustomHover | undefined; } export async function createVirtualLanguageService( aureliaProgram: AureliaProgram, position: Position, document: TextDocument, options: VirtualLanguageServiceOptions = DEFAULT_VIRTUAL_LANGUAGE_SERVICE_OPTIONS ): Promise<VirtualLanguageService | undefined> { const documentUri = document.uri; // 1. Get content for virtual file let virtualContent: string = ''; if (options.region) { const region = options.region; if (region.sourceCodeLocation === undefined) return; const { startOffset, endOffset } = region.sourceCodeLocation; virtualContent = document.getText().slice(startOffset, endOffset - 1); } else if (options.virtualContent !== undefined) { virtualContent = options.virtualContent; } if (!virtualContent) { throw new Error('No virtual content'); } // 2. Create virtual file const virtualFileWithContent = createVirtualFileWithContent( aureliaProgram, documentUri, virtualContent ); const { virtualSourcefile } = virtualFileWithContent!; let { virtualCursorIndex } = virtualFileWithContent!; if (options.startAtBeginningOfMethodInVirtualFile !== undefined) { virtualCursorIndex -= virtualContent.length - 1; // -1 to start at beginning of method name; } const program = aureliaProgram.getProgram(); if (program === undefined) return; const languageService = getVirtualLangagueService(virtualSourcefile, program); return { getCompletionsAtPosition: () => getCompletionsAtPosition(), getCompletionEntryDetails: () => getCompletionEntryDetails(), getDefinitionAtPosition: () => getDefinitionAtPosition( languageService, virtualSourcefile, virtualCursorIndex ), getQuickInfoAtPosition: () => getQuickInfoAtPosition( languageService, virtualSourcefile, virtualCursorIndex ), }; } function getCompletionsAtPosition() { // cls.getCompletionsAtPosition(fileName, 132, undefined); /*?*/ } function getCompletionEntryDetails() { // cls.getCompletionEntryDetails( fileName, 190, "toView", undefined, undefined, undefined); /*?*/ } function getDefinitionAtPosition( languageService: ts.LanguageService, virtualSourcefile: ts.SourceFile, virtualCursorIndex: number ) { const defintion = languageService.getDefinitionAtPosition( UriUtils.toSysPath(virtualSourcefile.fileName), virtualCursorIndex ); return defintion; } export interface CustomHover { contents: { kind: MarkupKind; value: string; }; documentation: string; } function getQuickInfoAtPosition( languageService: ts.LanguageService, virtualSourcefile: ts.SourceFile, virtualCursorIndex: number ): CustomHover | undefined { /** * 1. * Workaround: The normal ls.getQuickInfoAtPosition returns for objects and arrays just * `{}`, that's why we go through `getDefinitionAtPosition`. */ const defintion = languageService.getDefinitionAtPosition( UriUtils.toSysPath(virtualSourcefile.fileName), virtualCursorIndex ); if (!defintion) return; if (defintion.length > 1) { // TODO: Add VSCode warning, to know how to actually handle this case. // Currently, I think, only one defintion will be returned. throw new Error('Unsupported: Multiple definitions.'); } /** * Workaround: Here, we have to substring the desired info from the original **source code** * --> hence the naming of this variable. * * BUG: Method: In using `contextSpan` for methods, the whole method body will be * taken into the 'context' */ const span = defintion[0].contextSpan; if (!span) return; const sourceCodeText = virtualSourcefile .getText() .slice(span?.start, span?.start + span?.length); /** * 2. Documentation */ const quickInfo = languageService.getQuickInfoAtPosition( UriUtils.toSysPath(virtualSourcefile.fileName), virtualCursorIndex ); let finalDocumentation = ''; if (quickInfo === undefined) return; const { documentation } = quickInfo; if (Array.isArray(documentation) && documentation.length > 1) { finalDocumentation = documentation[0].text; } /** * 3. Result * Format taken from VSCode hovering */ const result = '```ts\n' + `(${defintion[0].kind}) ${defintion[0].containerName}.${sourceCodeText}` + '\n```'; return { contents: { kind: MarkupKind.Markdown, value: result, }, documentation: finalDocumentation, }; } export function getVirtualLangagueService( sourceFile: ts.SourceFile, watchProgram: ts.Program ): ts.LanguageService { // const compilerSettings = watchProgram?.getCompilerOptions(); const compilerSettings = { // module: 99, // skipLibCheck: true, // types: ['jasmine'], // typeRoots: [ // '/home/hdn/dev/work/repo/labfolder-web/labfolder-eln-v2/node_modules/@types', // ], // removeComments: true, // emitDecoratorMetadata: true, // experimentalDecorators: true, // sourceMap: true, // target: 1, // lib: ['lib.es2020.d.ts', 'lib.dom.d.ts'], // moduleResolution: 2, baseUrl: '/home/hdn/dev/work/repo/labfolder-web/labfolder-eln-v2/src', // resolveJsonModule: true, // allowJs: true, // esModuleInterop: true, // configFilePath: // '/home/hdn/dev/work/repo/labfolder-web/labfolder-eln-v2/tsconfig.json', }; const watcherProgram = watchProgram; const lSHost: ts.LanguageServiceHost = { getCompilationSettings: () => compilerSettings, getScriptFileNames: () => { const finalScriptFileName = [UriUtils.toSysPath(sourceFile.fileName)]; return finalScriptFileName; }, getScriptVersion: () => '0', getScriptSnapshot: (fileName) => { let sourceFileText; if (fileName === VIRTUAL_SOURCE_FILENAME) { sourceFileText = sourceFile.getText(); } else { const sourceFile = watcherProgram?.getSourceFile(fileName); sourceFileText = sourceFile?.getText() ?? ''; } return ts.ScriptSnapshot.fromString(sourceFileText); }, getCurrentDirectory: () => process.cwd(), getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(options), fileExists: ts.sys.fileExists, readFile: ts.sys.readFile, readDirectory: ts.sys.readDirectory, writeFile: ts.sys.writeFile, }; const cls = ts.createLanguageService(lSHost, ts.createDocumentRegistry()); return cls; } /** * With a virtual file, get access to file scope juicyness via a virtual progrm. * * 1. In the virtual view model source file * 2. Split up * 2.1 Need to visit each node * 2.2 (or are we regexing it?) * * @param originalSourceFile - * @param virtualContent - * @param targetClassName - Name of the class associated to your view */ export function createVirtualViewModelSourceFile( originalSourceFile: ts.SourceFile, virtualContent: string, targetClassName: string ): VirtualSourceFileInfo { /** Match [...] export class MyCustomElement { [...] */ const virtualViewModelContent = originalSourceFile.getText(); const classDeclaration = 'class '; const classNameToOpeningBracketRegex = new RegExp( `${classDeclaration}${targetClassName}(.*?{)` ); const classNameAndOpeningBracketMatch = classNameToOpeningBracketRegex.exec( virtualViewModelContent ); if (!classNameAndOpeningBracketMatch) { throw new Error( `No match found in File: ${UriUtils.toSysPath( originalSourceFile.fileName )} with target class name: ${targetClassName}` ); } /** class Foo >{<-- index */ const classNameStartIndex = classNameAndOpeningBracketMatch?.index; const toOpeningBracketLength = classNameAndOpeningBracketMatch[1]?.length; const classOpeningBracketIndex = classDeclaration.length + targetClassName.length + classNameStartIndex + toOpeningBracketLength; /** Split on class MyClass >{< ..otherContent */ const starter = virtualViewModelContent.slice(0, classOpeningBracketIndex); const ender = virtualViewModelContent.slice(classOpeningBracketIndex); /** Create temp content */ const tempMethodTextStart = `${VIRTUAL_METHOD_NAME}() {this.`; const tempMethodTextEnd = '};\n '; const tempMethodText = tempMethodTextStart + virtualContent + tempMethodTextEnd; const tempWithContent = starter + tempMethodText + ender; const virtualSourcefile = ts.createSourceFile( VIRTUAL_SOURCE_FILENAME, tempWithContent, 99 ); const virtualCursorIndex = classOpeningBracketIndex + tempMethodTextStart.length + virtualContent.length; return { virtualSourcefile, virtualCursorIndex, }; } export function createVirtualFileWithContent( aureliaProgram: AureliaProgram, documentUri: string, content: string ): VirtualSourceFileInfo | undefined { // 1. Get original viewmodel file associated with view const componentList = aureliaProgram.aureliaComponents.getAll(); const targetComponent = componentList.find((component) => { if (component.viewFilePath === undefined) return false; if (component.viewFilePath.length > 0) { const targetView = documentUri.includes(component.viewFilePath); if (targetView) { return targetView; } } if (component.viewModelFilePath.length > 0) { const targetViewModel = documentUri.includes(component.viewModelFilePath); if (targetViewModel) { return targetViewModel; } } return false; }); const targetSourceFile = targetComponent?.sourceFile; if (!targetSourceFile) { console.log(`No source file found for current view: ${documentUri}`); return; } const customElementClassName = componentList.find((component) => { const result = component.viewModelFilePath === UriUtils.toSysPath(targetSourceFile.fileName); return result; })?.className; if (customElementClassName === undefined) return; // 2. Create virtual source file const virtualViewModelSourceFile = ts.createSourceFile( VIRTUAL_SOURCE_FILENAME, targetSourceFile?.getText(), 99 ); const { virtualCursorIndex, virtualSourcefile } = createVirtualViewModelSourceFile( virtualViewModelSourceFile, content, customElementClassName ); return { virtualCursorIndex, virtualSourcefile, viewModelFilePath: UriUtils.toSysPath(targetSourceFile.fileName), }; }
the_stack
import Grid from "../Grid"; import { MOUNT_STATE, PROPERTY_TYPE } from "../consts"; import { GridOptions, Properties, GridOutlines } from "../types"; import { getRangeCost, GetterSetter, isObject } from "../utils"; import { find_path } from "./lib/dijkstra"; import { GridItem } from "../GridItem"; interface Link { path: number[]; cost: number; length: number; currentNode: number; isOver?: boolean; } function splitItems(items: GridItem[], path: string[]) { const length = path.length; const groups: GridItem[][] = []; for (let i = 0; i < length - 1; ++i) { const path1 = parseInt(path[i], 10); const path2 = parseInt(path[i + 1], 10); groups.push(items.slice(path1, path2)); } return groups; } function getExpectedColumnSize(item: GridItem, rowSize: number) { const inlineSize = item.orgInlineSize; const contentSize = item.orgContentSize; if (!inlineSize || !contentSize) { return rowSize; } const inlineOffset = parseFloat(item.gridData.inlineOffset) || 0; const contentOffset = parseFloat(item.gridData.contentOffset) || 0; const ratio = contentSize <= contentOffset ? 1 : (inlineSize - inlineOffset) / (contentSize - contentOffset); return ratio * (rowSize - contentOffset) + inlineOffset; } /** * @typedef * @memberof Grid.JustifiedGrid * @extends Grid.GridOptions * @property - The minimum and maximum number of items per line. (default: [1, 8]) <ko> 한 줄에 들어가는 아이템의 최소, 최대 개수. (default: [1, 8]) </ko> * @property - The minimum and maximum number of rows in a group, 0 is not set. (default: 0) <ko> 한 그룹에 들어가는 행의 최소, 최대 개수, 0은 미설정이다. (default: 0) </ko> * @property - The minimum and maximum size by which the item is adjusted. If it is not calculated, it may deviate from the minimum and maximum sizes. (default: [0, Infinity]) <ko>아이템이 조정되는 최소, 최대 사이즈. 계산이 되지 않는 경우 최소, 최대 사이즈를 벗어날 수 있다. (default: [0, Infinity])</ko> * @property - Maximum number of rows to be counted for container size. You can hide it on the screen by setting overflow: hidden. -1 is not set. (default: -1)<ko>컨테이너 크기에 계산될 최대 row 개수. overflow: hidden을 설정하면 화면에 가릴 수 있다. -1은 미설정이다. (default: -1)</ko> * @property - Whether to crop when the row size is out of sizeRange. If set to true, this ratio can be broken. (default: false) <ko>row사이즈가 sizeRange에 벗어나면 크롭할지 여부. true로 설정하면 비율이 깨질 수 있다. (default: false)</ko> */ export interface JustifiedGridOptions extends GridOptions { columnRange?: number | number[]; rowRange?: number | number[]; sizeRange?: number | number[]; displayedRow?: number; isCroppedSize?: boolean; } /** * 'justified' is a printing term with the meaning that 'it fits in one row wide'. JustifiedGrid is a grid that the item is filled up on the basis of a line given a size. * If 'data-grid-inline-offset' or 'data-grid-content-offset' are set for item element, the ratio is maintained except for the offset value. * If 'data-grid-maintained-target' is set for an element whose ratio is to be maintained, the item is rendered while maintaining the ratio of the element. * @ko 'justified'는 '1행의 너비에 맞게 꼭 들어찬'이라는 의미를 가진 인쇄 용어다. JustifiedGrid는 용어의 의미대로 너비가 주어진 사이즈를 기준으로 아이템가 가득 차도록 배치하는 Grid다. * 아이템 엘리먼트에 'data-grid-inline-offset' 또는 'data-grid-content-offset'를 설정하면 offset 값을 제외하고 비율을 유지한다. * 비율을 유지하고 싶은 엘리먼트에 'data-grid-maintained-target'을 설정한다면 해당 엘리먼트의 비율을 유지하면서 아이템이 렌더링이 된다. * @memberof Grid * @param {HTMLElement | string} container - A base element for a module <ko>모듈을 적용할 기준 엘리먼트</ko> * @param {Grid.JustifiedGrid.JustifiedGridOptions} options - The option object of the JustifiedGrid module <ko>JustifiedGrid 모듈의 옵션 객체</ko> */ @GetterSetter export class JustifiedGrid extends Grid<JustifiedGridOptions> { public static propertyTypes = { ...Grid.propertyTypes, columnRange: PROPERTY_TYPE.RENDER_PROPERTY, rowRange: PROPERTY_TYPE.RENDER_PROPERTY, sizeRange: PROPERTY_TYPE.RENDER_PROPERTY, isCroppedSize: PROPERTY_TYPE.RENDER_PROPERTY, displayedRow: PROPERTY_TYPE.RENDER_PROPERTY, }; public static defaultOptions: Required<JustifiedGridOptions> = { ...Grid.defaultOptions, columnRange: [1, 8], rowRange: 0, sizeRange: [0, Infinity], displayedRow: -1, isCroppedSize: false, }; public applyGrid(items: GridItem[], direction: "start" | "end", outline: number[]): GridOutlines { const { attributePrefix, horizontal, } = this.options; items.forEach((item) => { if (!item.isUpdate) { return; } const element = item.element; const attributes = item.attributes; const gridData = item.gridData; let inlineOffset = parseFloat(attributes.inlineOffset) || gridData.inlineOffset || 0; let contentOffset = parseFloat(attributes.contentOffset) || gridData.contentOffset | 0; if ( element && !("inlineOffset" in attributes) && !("contentOffset" in attributes) && item.mountState === MOUNT_STATE.MOUNTED ) { const maintainedTarget = element.querySelector(`[${attributePrefix}maintained-target]`); if (maintainedTarget) { const widthOffset = element.offsetWidth - element.clientWidth + element.scrollWidth - maintainedTarget.clientWidth; const heightOffset = element.offsetHeight - element.clientHeight + element.scrollHeight - maintainedTarget.clientHeight; if (horizontal) { inlineOffset = heightOffset; contentOffset = widthOffset; } else { inlineOffset = widthOffset; contentOffset = heightOffset; } } } gridData.inlineOffset = inlineOffset; gridData.contentOffset = contentOffset; }); const rowRange = this.options.rowRange; let path: string[] = []; if (items.length) { path = rowRange ? this._getRowPath(items) : this._getPath(items); } return this._setStyle(items, path, outline, direction === "end"); } private _getRowPath(items: GridItem[]) { const columnRange = this._getColumnRange(); const rowRange = this._getRowRange(); const pathLink = this._getRowLink(items, { path: [0], cost: 0, length: 0, currentNode: 0, }, columnRange, rowRange); return pathLink?.path.map((node) => `${node}`) ?? []; } private _getRowLink( items: GridItem[], currentLink: Link, columnRange: number[], rowRange: number[] ): Link { const [minColumn] = columnRange; const [minRow, maxRow] = rowRange; const lastNode = items.length; const { path, length: pathLength, cost, currentNode, } = currentLink; // not reached lastNode but path is exceed or the number of remaining nodes is less than minColumn. if (currentNode < lastNode && (maxRow <= pathLength || currentNode + minColumn > lastNode)) { const rangeCost = getRangeCost(lastNode - currentNode, columnRange); const lastCost = rangeCost * Math.abs(this._getCost(items, currentNode, lastNode)); return { ...currentLink, length: pathLength + 1, path: [...path, lastNode], currentNode: lastNode, cost: cost + lastCost, isOver: true, }; } else if (currentNode >= lastNode) { return { ...currentLink, currentNode: lastNode, isOver: minRow > pathLength || maxRow < pathLength, }; } else { return this._searchRowLink(items, currentLink, lastNode, columnRange, rowRange); } } private _searchRowLink( items: GridItem[], currentLink: Link, lastNode: number, columnRange: number[], rowRange: number[] ) { const [minColumn, maxColumn] = columnRange; const { currentNode, path, length: pathLength, cost, } = currentLink; const length = Math.min(lastNode, currentNode + maxColumn); const links: Link[] = []; for (let nextNode = currentNode + minColumn; nextNode <= length; ++nextNode) { if (nextNode === currentNode) { continue; } const nextCost = Math.abs(this._getCost(items, currentNode, nextNode)); const nextLink = this._getRowLink(items, { path: [...path, nextNode], length: pathLength + 1, cost: cost + nextCost, currentNode: nextNode, }, columnRange, rowRange); if (nextLink) { links.push(nextLink); } } links.sort((a, b) => { const aIsOver = a.isOver; const bIsOver = b.isOver; if (aIsOver !== bIsOver) { // If it is over, the cost is high. return aIsOver ? 1 : -1; } const aRangeCost = getRangeCost(a.length, rowRange); const bRangeCost = getRangeCost(b.length, rowRange); return aRangeCost - bRangeCost || a.cost - b.cost; }); // It returns the lowest cost link. return links[0]; } private _getExpectedRowSize(items: GridItem[]) { const { gap, } = this.options; let containerInlineSize = this.getContainerInlineSize()! - gap * (items.length - 1); let ratioSum = 0; let inlineSum = 0; items.forEach((item) => { const inlineSize = item.orgInlineSize; const contentSize = item.orgContentSize; if (!inlineSize || !contentSize) { ratioSum += 1; return; } // sum((expect - offset) * ratio) = container inline size const inlineOffset = parseFloat(item.gridData.inlineOffset) || 0; const contentOffset = parseFloat(item.gridData.contentOffset) || 0; const maintainedRatio = contentSize <= contentOffset ? 1 : (inlineSize - inlineOffset) / (contentSize - contentOffset); ratioSum += maintainedRatio; inlineSum += contentOffset * maintainedRatio; containerInlineSize -= inlineOffset; }); return ratioSum ? (containerInlineSize + inlineSum) / ratioSum : 0; } private _getExpectedInlineSize(items: GridItem[], rowSize: number) { const { gap, } = this.options; const size = items.reduce((sum, item) => { return sum + getExpectedColumnSize(item, rowSize); }, 0); return size ? size + gap * (items.length - 1) : 0; } private _getCost( items: GridItem[], i: number, j: number, ) { const lineItems = items.slice(i, j); const rowSize = this._getExpectedRowSize(lineItems); const [minSize, maxSize] = this._getSizeRange(); if (this.isCroppedSize) { if (minSize <= rowSize && rowSize <= maxSize) { return 0; } const expectedInlineSize = this._getExpectedInlineSize( lineItems, rowSize < minSize ? minSize : maxSize, ); return Math.pow(expectedInlineSize - this.getContainerInlineSize(), 2); } if (isFinite(maxSize)) { // if this size is not in range, the cost increases sharply. if (rowSize < minSize) { return Math.pow(rowSize - minSize, 2) + Math.pow(maxSize, 2); } else if (rowSize > maxSize) { return Math.pow(rowSize - maxSize, 2) + Math.pow(maxSize, 2); } } else if (rowSize < minSize) { return Math.max(Math.pow(minSize, 2), Math.pow(rowSize, 2)) + Math.pow(maxSize, 2); } // if this size in range, the cost is row return rowSize - minSize; } private _getPath(items: GridItem[]) { const lastNode = items.length; const columnRangeOption = this.options.columnRange; const [minColumn, maxColumn]: number[] = isObject(columnRangeOption) ? columnRangeOption : [columnRangeOption, columnRangeOption]; const graph = (nodeKey: string) => { const results: { [key: string]: number } = {}; const currentNode = parseInt(nodeKey, 10); for (let nextNode = Math.min(currentNode + minColumn, lastNode); nextNode <= lastNode; ++nextNode) { if (nextNode - currentNode > maxColumn) { break; } let cost = this._getCost( items, currentNode, nextNode, ); if (cost < 0 && nextNode === lastNode) { cost = 0; } results[`${nextNode}`] = Math.pow(cost, 2); } return results; }; // shortest path for items' total height. return find_path(graph, "0", `${lastNode}`); } private _setStyle( items: GridItem[], path: string[], outline: number[] = [], isEndDirection: boolean, ) { const { gap, isCroppedSize, displayedRow, } = this.options; const sizeRange = this._getSizeRange(); const startPoint = outline[0] || 0; const containerInlineSize = this.getContainerInlineSize(); const groups = splitItems(items, path); let contentPos = startPoint; let displayedSize = 0; groups.forEach((groupItems, rowIndex) => { const length = groupItems.length; let rowSize = this._getExpectedRowSize(groupItems); if (isCroppedSize) { rowSize = Math.max(sizeRange[0], Math.min(rowSize, sizeRange[1])); } const expectedInlineSize = this._getExpectedInlineSize(groupItems, rowSize); const allGap = gap * (length - 1); const scale = (containerInlineSize - allGap) / (expectedInlineSize - allGap); groupItems.forEach((item, i) => { let columnSize = getExpectedColumnSize(item, rowSize); const prevItem = groupItems[i - 1]; const inlinePos = prevItem ? prevItem.cssInlinePos! + prevItem.cssInlineSize! + gap : 0; if (isCroppedSize) { columnSize *= scale; } item.setCSSGridRect({ inlinePos, contentPos, inlineSize: columnSize, contentSize: rowSize, }); }); contentPos += gap + rowSize; if (displayedRow < 0 || rowIndex < displayedRow) { displayedSize = contentPos; } }); if (isEndDirection) { // previous group's end outline is current group's start outline return { start: [startPoint], end: [displayedSize], }; } // always start is lower than end. // contentPos is endPoinnt const height = contentPos - startPoint; items.forEach((item) => { item.cssContentPos! -= height; }); return { start: [startPoint - height], end: [startPoint], // endPoint - height = startPoint }; } public getComputedOutlineLength() { return 1; } public getComputedOutlineSize() { return this.getContainerInlineSize(); } private _getRowRange() { const rowRange = this.rowRange; return isObject(rowRange) ? rowRange : [rowRange, rowRange]; } private _getColumnRange() { const columnRange = this.columnRange; return isObject(columnRange) ? columnRange : [columnRange, columnRange]; } private _getSizeRange() { const sizeRange = this.sizeRange; return isObject(sizeRange) ? sizeRange : [sizeRange, sizeRange]; } } export interface JustifiedGrid extends Properties<typeof JustifiedGrid> { } /** * The minimum and maximum number of items per line. * @ko 한 줄에 들어가는 아이템의 최소, 최대 개수. * @name Grid.JustifiedGrid#columnRange * @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["columnRange"]} * @default [1, 8] * @example * ```js * import { JustifiedGrid } from "@egjs/grid"; * * const grid = new JustifiedGrid(container, { * columnRange: [1, 8], * }); * * grid.columnRange = [3, 6]; * ``` */ /** * The minimum and maximum number of rows in a group, 0 is not set. * @ko 한 그룹에 들어가는 행의 최소, 최대 개수, 0은 미설정이다. * @name Grid.JustifiedGrid#rowRange * @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["rowRange"]} * @default 0 * @example * ```js * import { JustifiedGrid } from "@egjs/grid"; * * const grid = new JustifiedGrid(container, { * rowRange: 0, * }); * * grid.rowRange = [3, 4]; * ``` */ /** * The minimum and maximum size by which the item is adjusted. If it is not calculated, it may deviate from the minimum and maximum sizes. * @ko 아이템이 조정되는 최소, 최대 사이즈. 계산이 되지 않는 경우 최소, 최대 사이즈를 벗어날 수 있다. * @name Grid.JustifiedGrid#sizeRange * @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["sizeRange"]} * @default [0, Infinity] * @example * ```js * import { JustifiedGrid } from "@egjs/grid"; * * const grid = new JustifiedGrid(container, { * sizeRange: [0, Infinity], * }); * * grid.sizeRange = [200, 800]; * ``` */ /** * Maximum number of rows to be counted for container size. You can hide it on the screen by setting overflow: hidden. -1 is not set. * @ko - 컨테이너 크기에 계산될 최대 row 개수. overflow: hidden을 설정하면 화면에 가릴 수 있다. -1은 미설정이다. * @name Grid.JustifiedGrid#displayedRow * @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["displayedRow"]} * @default -1 * @example * ```js * import { JustifiedGrid } from "@egjs/grid"; * * const grid = new JustifiedGrid(container, { * displayedRow: -1, * }); * * grid.displayedRow = 3; * ``` */ /** * Whether to crop when the row size is out of sizeRange. If set to true, this ratio can be broken. * @ko - row 사이즈가 sizeRange에 벗어나면 크롭할지 여부. true로 설정하면 비율이 깨질 수 있다. * @name Grid.JustifiedGrid#isCroppedSize * @type {$ts:Grid.JustifiedGrid.JustifiedGridOptions["isCroppedSize"]} * @default false * @example * ```js * import { JustifiedGrid } from "@egjs/grid"; * * const grid = new JustifiedGrid(container, { * sizeRange: [200, 250], * isCroppedSize: false, * }); * * grid.isCroppedSize = true; * ``` */
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'; interface Blob {} declare class ResourceGroups extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: ResourceGroups.Types.ClientConfiguration) config: Config & ResourceGroups.Types.ClientConfiguration; /** * Creates a group with a specified name, description, and resource query. */ createGroup(params: ResourceGroups.Types.CreateGroupInput, callback?: (err: AWSError, data: ResourceGroups.Types.CreateGroupOutput) => void): Request<ResourceGroups.Types.CreateGroupOutput, AWSError>; /** * Creates a group with a specified name, description, and resource query. */ createGroup(callback?: (err: AWSError, data: ResourceGroups.Types.CreateGroupOutput) => void): Request<ResourceGroups.Types.CreateGroupOutput, AWSError>; /** * Deletes a specified resource group. Deleting a resource group does not delete resources that are members of the group; it only deletes the group structure. */ deleteGroup(params: ResourceGroups.Types.DeleteGroupInput, callback?: (err: AWSError, data: ResourceGroups.Types.DeleteGroupOutput) => void): Request<ResourceGroups.Types.DeleteGroupOutput, AWSError>; /** * Deletes a specified resource group. Deleting a resource group does not delete resources that are members of the group; it only deletes the group structure. */ deleteGroup(callback?: (err: AWSError, data: ResourceGroups.Types.DeleteGroupOutput) => void): Request<ResourceGroups.Types.DeleteGroupOutput, AWSError>; /** * Returns information about a specified resource group. */ getGroup(params: ResourceGroups.Types.GetGroupInput, callback?: (err: AWSError, data: ResourceGroups.Types.GetGroupOutput) => void): Request<ResourceGroups.Types.GetGroupOutput, AWSError>; /** * Returns information about a specified resource group. */ getGroup(callback?: (err: AWSError, data: ResourceGroups.Types.GetGroupOutput) => void): Request<ResourceGroups.Types.GetGroupOutput, AWSError>; /** * Returns the resource query associated with the specified resource group. */ getGroupQuery(params: ResourceGroups.Types.GetGroupQueryInput, callback?: (err: AWSError, data: ResourceGroups.Types.GetGroupQueryOutput) => void): Request<ResourceGroups.Types.GetGroupQueryOutput, AWSError>; /** * Returns the resource query associated with the specified resource group. */ getGroupQuery(callback?: (err: AWSError, data: ResourceGroups.Types.GetGroupQueryOutput) => void): Request<ResourceGroups.Types.GetGroupQueryOutput, AWSError>; /** * Returns a list of tags that are associated with a resource, specified by an ARN. */ getTags(params: ResourceGroups.Types.GetTagsInput, callback?: (err: AWSError, data: ResourceGroups.Types.GetTagsOutput) => void): Request<ResourceGroups.Types.GetTagsOutput, AWSError>; /** * Returns a list of tags that are associated with a resource, specified by an ARN. */ getTags(callback?: (err: AWSError, data: ResourceGroups.Types.GetTagsOutput) => void): Request<ResourceGroups.Types.GetTagsOutput, AWSError>; /** * Returns a list of ARNs of resources that are members of a specified resource group. */ listGroupResources(params: ResourceGroups.Types.ListGroupResourcesInput, callback?: (err: AWSError, data: ResourceGroups.Types.ListGroupResourcesOutput) => void): Request<ResourceGroups.Types.ListGroupResourcesOutput, AWSError>; /** * Returns a list of ARNs of resources that are members of a specified resource group. */ listGroupResources(callback?: (err: AWSError, data: ResourceGroups.Types.ListGroupResourcesOutput) => void): Request<ResourceGroups.Types.ListGroupResourcesOutput, AWSError>; /** * Returns a list of existing resource groups in your account. */ listGroups(params: ResourceGroups.Types.ListGroupsInput, callback?: (err: AWSError, data: ResourceGroups.Types.ListGroupsOutput) => void): Request<ResourceGroups.Types.ListGroupsOutput, AWSError>; /** * Returns a list of existing resource groups in your account. */ listGroups(callback?: (err: AWSError, data: ResourceGroups.Types.ListGroupsOutput) => void): Request<ResourceGroups.Types.ListGroupsOutput, AWSError>; /** * Returns a list of AWS resource identifiers that matches a specified query. The query uses the same format as a resource query in a CreateGroup or UpdateGroupQuery operation. */ searchResources(params: ResourceGroups.Types.SearchResourcesInput, callback?: (err: AWSError, data: ResourceGroups.Types.SearchResourcesOutput) => void): Request<ResourceGroups.Types.SearchResourcesOutput, AWSError>; /** * Returns a list of AWS resource identifiers that matches a specified query. The query uses the same format as a resource query in a CreateGroup or UpdateGroupQuery operation. */ searchResources(callback?: (err: AWSError, data: ResourceGroups.Types.SearchResourcesOutput) => void): Request<ResourceGroups.Types.SearchResourcesOutput, AWSError>; /** * Adds specified tags to a resource with the specified ARN. Existing tags on a resource are not changed if they are not specified in the request parameters. */ tag(params: ResourceGroups.Types.TagInput, callback?: (err: AWSError, data: ResourceGroups.Types.TagOutput) => void): Request<ResourceGroups.Types.TagOutput, AWSError>; /** * Adds specified tags to a resource with the specified ARN. Existing tags on a resource are not changed if they are not specified in the request parameters. */ tag(callback?: (err: AWSError, data: ResourceGroups.Types.TagOutput) => void): Request<ResourceGroups.Types.TagOutput, AWSError>; /** * Deletes specified tags from a specified resource. */ untag(params: ResourceGroups.Types.UntagInput, callback?: (err: AWSError, data: ResourceGroups.Types.UntagOutput) => void): Request<ResourceGroups.Types.UntagOutput, AWSError>; /** * Deletes specified tags from a specified resource. */ untag(callback?: (err: AWSError, data: ResourceGroups.Types.UntagOutput) => void): Request<ResourceGroups.Types.UntagOutput, AWSError>; /** * Updates an existing group with a new or changed description. You cannot update the name of a resource group. */ updateGroup(params: ResourceGroups.Types.UpdateGroupInput, callback?: (err: AWSError, data: ResourceGroups.Types.UpdateGroupOutput) => void): Request<ResourceGroups.Types.UpdateGroupOutput, AWSError>; /** * Updates an existing group with a new or changed description. You cannot update the name of a resource group. */ updateGroup(callback?: (err: AWSError, data: ResourceGroups.Types.UpdateGroupOutput) => void): Request<ResourceGroups.Types.UpdateGroupOutput, AWSError>; /** * Updates the resource query of a group. */ updateGroupQuery(params: ResourceGroups.Types.UpdateGroupQueryInput, callback?: (err: AWSError, data: ResourceGroups.Types.UpdateGroupQueryOutput) => void): Request<ResourceGroups.Types.UpdateGroupQueryOutput, AWSError>; /** * Updates the resource query of a group. */ updateGroupQuery(callback?: (err: AWSError, data: ResourceGroups.Types.UpdateGroupQueryOutput) => void): Request<ResourceGroups.Types.UpdateGroupQueryOutput, AWSError>; } declare namespace ResourceGroups { export interface CreateGroupInput { /** * The name of the group, which is the identifier of the group in other operations. A resource group name cannot be updated after it is created. A resource group name can have a maximum of 127 characters, including letters, numbers, hyphens, dots, and underscores. The name cannot start with AWS or aws; these are reserved. A resource group name must be unique within your account. */ Name: GroupName; /** * The description of the resource group. Descriptions can have a maximum of 511 characters, including letters, numbers, hyphens, underscores, punctuation, and spaces. */ Description?: GroupDescription; /** * The resource query that determines which AWS resources are members of this group. */ ResourceQuery: ResourceQuery; /** * The tags to add to the group. A tag is a string-to-string map of key-value pairs. Tag keys can have a maximum character length of 127 characters, and tag values can have a maximum length of 255 characters. */ Tags?: Tags; } export interface CreateGroupOutput { /** * A full description of the resource group after it is created. */ Group?: Group; /** * The resource query associated with the group. */ ResourceQuery?: ResourceQuery; /** * The tags associated with the group. */ Tags?: Tags; } export interface DeleteGroupInput { /** * The name of the resource group to delete. */ GroupName: GroupName; } export interface DeleteGroupOutput { /** * A full description of the deleted resource group. */ Group?: Group; } export type ErrorMessage = string; export interface GetGroupInput { /** * The name of the resource group. */ GroupName: GroupName; } export interface GetGroupOutput { /** * A full description of the resource group. */ Group?: Group; } export interface GetGroupQueryInput { /** * The name of the resource group. */ GroupName: GroupName; } export interface GetGroupQueryOutput { /** * The resource query associated with the specified group. */ GroupQuery?: GroupQuery; } export interface GetTagsInput { /** * The ARN of the resource for which you want a list of tags. The resource must exist within the account you are using. */ Arn: GroupArn; } export interface GetTagsOutput { /** * The ARN of the tagged resource. */ Arn?: GroupArn; /** * The tags associated with the specified resource. */ Tags?: Tags; } export interface Group { /** * The ARN of a resource group. */ GroupArn: GroupArn; /** * The name of a resource group. */ Name: GroupName; /** * The description of the resource group. */ Description?: GroupDescription; } export type GroupArn = string; export type GroupDescription = string; export type GroupList = Group[]; export type GroupName = string; export interface GroupQuery { /** * The name of a resource group that is associated with a specific resource query. */ GroupName: GroupName; /** * The resource query which determines which AWS resources are members of the associated resource group. */ ResourceQuery: ResourceQuery; } export interface ListGroupResourcesInput { /** * The name of the resource group. */ GroupName: GroupName; /** * The maximum number of group member ARNs that are returned in a single call by ListGroupResources, in paginated output. By default, this number is 50. */ MaxResults?: MaxResults; /** * The NextToken value that is returned in a paginated ListGroupResources request. To get the next page of results, run the call again, add the NextToken parameter, and specify the NextToken value. */ NextToken?: NextToken; } export interface ListGroupResourcesOutput { /** * The ARNs and resource types of resources that are members of the group that you specified. */ ResourceIdentifiers?: ResourceIdentifierList; /** * The NextToken value to include in a subsequent ListGroupResources request, to get more results. */ NextToken?: NextToken; } export interface ListGroupsInput { /** * The maximum number of resource group results that are returned by ListGroups in paginated output. By default, this number is 50. */ MaxResults?: MaxResults; /** * The NextToken value that is returned in a paginated ListGroups request. To get the next page of results, run the call again, add the NextToken parameter, and specify the NextToken value. */ NextToken?: NextToken; } export interface ListGroupsOutput { /** * A list of resource groups. */ Groups?: GroupList; /** * The NextToken value to include in a subsequent ListGroups request, to get more results. */ NextToken?: NextToken; } export type MaxResults = number; export type NextToken = string; export type Query = string; export type QueryType = "TAG_FILTERS_1_0"|string; export type ResourceArn = string; export interface ResourceIdentifier { /** * The ARN of a resource. */ ResourceArn?: ResourceArn; /** * The resource type of a resource, such as AWS::EC2::Instance. */ ResourceType?: ResourceType; } export type ResourceIdentifierList = ResourceIdentifier[]; export interface ResourceQuery { /** * The type of the query. The valid value in this release is TAG_FILTERS_1_0. TAG_FILTERS_1_0: A JSON syntax that lets you specify a collection of simple tag filters for resource types and tags, as supported by the AWS Tagging API GetResources operation. When more than one element is present, only resources that match all filters are part of the result. If a filter specifies more than one value for a key, a resource matches the filter if its tag value matches any of the specified values. */ Type: QueryType; /** * The query that defines a group or a search. */ Query: Query; } export type ResourceType = string; export interface SearchResourcesInput { /** * The search query, using the same formats that are supported for resource group definition. */ ResourceQuery: ResourceQuery; /** * The maximum number of group member ARNs returned by SearchResources in paginated output. By default, this number is 50. */ MaxResults?: MaxResults; /** * The NextToken value that is returned in a paginated SearchResources request. To get the next page of results, run the call again, add the NextToken parameter, and specify the NextToken value. */ NextToken?: NextToken; } export interface SearchResourcesOutput { /** * The ARNs and resource types of resources that are members of the group that you specified. */ ResourceIdentifiers?: ResourceIdentifierList; /** * The NextToken value to include in a subsequent SearchResources request, to get more results. */ NextToken?: NextToken; } export interface TagInput { /** * The ARN of the resource to which to add tags. */ Arn: GroupArn; /** * The tags to add to the specified resource. A tag is a string-to-string map of key-value pairs. Tag keys can have a maximum character length of 127 characters, and tag values can have a maximum length of 255 characters. */ Tags: Tags; } export type TagKey = string; export type TagKeyList = TagKey[]; export interface TagOutput { /** * The ARN of the tagged resource. */ Arn?: GroupArn; /** * The tags that have been added to the specified resource. */ Tags?: Tags; } export type TagValue = string; export type Tags = {[key: string]: TagValue}; export interface UntagInput { /** * The ARN of the resource from which to remove tags. */ Arn: GroupArn; /** * The keys of the tags to be removed. */ Keys: TagKeyList; } export interface UntagOutput { /** * The ARN of the resource from which tags have been removed. */ Arn?: GroupArn; /** * The keys of tags that have been removed. */ Keys?: TagKeyList; } export interface UpdateGroupInput { /** * The name of the resource group for which you want to update its description. */ GroupName: GroupName; /** * The description of the resource group. Descriptions can have a maximum of 511 characters, including letters, numbers, hyphens, underscores, punctuation, and spaces. */ Description?: GroupDescription; } export interface UpdateGroupOutput { /** * The full description of the resource group after it has been updated. */ Group?: Group; } export interface UpdateGroupQueryInput { /** * The name of the resource group for which you want to edit the query. */ GroupName: GroupName; /** * The resource query that determines which AWS resources are members of the resource group. */ ResourceQuery: ResourceQuery; } export interface UpdateGroupQueryOutput { /** * The resource query associated with the resource group after the update. */ GroupQuery?: GroupQuery; } /** * 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-11-27"|"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 ResourceGroups client. */ export import Types = ResourceGroups; } export = ResourceGroups;
the_stack
import { join, } from 'path'; import { AutoScalingGroup, BlockDeviceVolume, UpdatePolicy, } from '@aws-cdk/aws-autoscaling'; import { ICertificate, } from '@aws-cdk/aws-certificatemanager'; import { Connections, IConnectable, InstanceType, ISecurityGroup, IVpc, Port, SubnetSelection, SubnetType, } from '@aws-cdk/aws-ec2'; import { Cluster, ContainerImage, Ec2TaskDefinition, LogDriver, PlacementConstraint, Scope, UlimitName, } from '@aws-cdk/aws-ecs'; import { ApplicationLoadBalancedEc2Service, } from '@aws-cdk/aws-ecs-patterns'; import { ApplicationListener, ApplicationLoadBalancer, ApplicationProtocol, ApplicationTargetGroup, CfnTargetGroup, } from '@aws-cdk/aws-elasticloadbalancingv2'; import { IGrantable, IPrincipal, ManagedPolicy, PolicyStatement, ServicePrincipal, } from '@aws-cdk/aws-iam'; import { ILogGroup, } from '@aws-cdk/aws-logs'; import { IHostedZone, IPrivateHostedZone, PrivateHostedZone } from '@aws-cdk/aws-route53'; import { ISecret, } from '@aws-cdk/aws-secretsmanager'; import { Construct, IConstruct, Stack, } from '@aws-cdk/core'; import { ECSConnectOptions, InstanceConnectOptions, IRepository, IVersion, RenderQueueExternalTLSProps, RenderQueueHostNameProps, RenderQueueProps, RenderQueueSizeConstraints, SubnetIdentityRegistrationSettingsProps, VersionQuery, } from '.'; import { ConnectableApplicationEndpoint, ImportedAcmCertificate, LogGroupFactory, ScriptAsset, X509CertificatePem, X509CertificatePkcs12, } from '../../core'; import { DeploymentInstance } from '../../core/lib/deployment-instance'; import { tagConstruct, } from '../../core/lib/runtime-info'; import { RenderQueueConnection, } from './rq-connection'; import { SecretsManagementIdentityRegistration, } from './secrets-management'; import { Version } from './version'; import { WaitForStableService, } from './wait-for-stable-service'; /** * Interface for Deadline Render Queue. */ export interface IRenderQueue extends IConstruct, IConnectable { /** * The Deadline Repository that the Render Queue services. */ readonly repository: IRepository; /** * The endpoint used to connect to the Render Queue */ readonly endpoint: ConnectableApplicationEndpoint; /** * A connections object for controlling access of the compute resources that host the render queue. */ readonly backendConnections: Connections; /** * Configures an ECS cluster to be able to connect to a RenderQueue * @returns An environment mapping that is used to configure the Docker Images */ configureClientECS(params: ECSConnectOptions): { [name: string]: string }; /** * Configure an Instance/Autoscaling group to connect to a RenderQueue */ configureClientInstance(params: InstanceConnectOptions): void; /** * Configure a rule to automatically register all Deadline Secrets Management identities connecting from a given * subnet to a specified role and status. * * See https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/secrets-management/deadline-secrets-management.html#identity-management-registration-settings-ref-label * for details. * * All RFDK constructs that require Deadline Secrets Management identity registration call this method internally. * End-users of RFDK should not need to use this method unless they have a special need and understand its inner * workings. * * @param props Properties that specify the configuration to be applied to the Deadline Secrets Management identity * registration settings. This specifies a VPC subnet and configures Deadline to automatically register identities of * clients connecting from the subnet to a chosen Deadline Secrets Management role and status. */ configureSecretsManagementAutoRegistration(props: SubnetIdentityRegistrationSettingsProps): void; } /** * Interface for information about the render queue's TLS configuration */ interface TlsInfo { /** * The certificate the Render Queue's server will use for the TLS connection. */ readonly serverCert: ICertificate; /** * The certificate chain clients can use to verify the certificate. */ readonly certChain: ISecret; /** * The private hosted zone that the render queue's load balancer will be placed in. */ readonly domainZone: IPrivateHostedZone; /** * The fully qualified domain name that will be given to the load balancer in the private * hosted zone. */ readonly fullyQualifiedDomainName: string; } /** * Base class for Render Queue providers */ abstract class RenderQueueBase extends Construct implements IRenderQueue { /** * The endpoint that Deadline clients can use to connect to the Render Queue */ public abstract readonly endpoint: ConnectableApplicationEndpoint; /** * Allows specifying security group connections for the Render Queue. */ public abstract readonly connections: Connections; /** * @inheritdoc */ public abstract readonly repository: IRepository; /** * @inheritdoc */ public abstract readonly backendConnections: Connections; /** * Configures an ECS cluster to be able to connect to a RenderQueue * @returns An environment mapping that is used to configure the Docker Images */ public abstract configureClientECS(params: ECSConnectOptions): { [name: string]: string }; /** * Configure an Instance/Autoscaling group to connect to a RenderQueue */ public abstract configureClientInstance(params: InstanceConnectOptions): void; /** * @inheritdoc */ public abstract configureSecretsManagementAutoRegistration(props: SubnetIdentityRegistrationSettingsProps): void; } /** * The RenderQueue construct deploys an Elastic Container Service (ECS) service that serves Deadline's REST HTTP API * to Deadline Clients. * * Most Deadline clients will connect to a Deadline render farm via the the RenderQueue. The API provides Deadline * clients access to Deadline's database and repository file-system in a way that is secure, performant, and scalable. * * ![architecture diagram](/diagrams/deadline/RenderQueue.svg) * * Resources Deployed * ------------------------ * - An Amazon Elastic Container Service (ECS) cluster. * - An AWS EC2 auto-scaling group that provides the instances that host the ECS service. * - An ECS service with a task definition that deploys the Deadline Remote Connetion Server (RCS) in a container. * - A Amazon CloudWatch log group for streaming logs from the Deadline RCS. * - An application load balancer, listener and target group that balance incoming traffic among the RCS containers. * * Security Considerations * ------------------------ * - The instances deployed by this construct download and run scripts from your CDK bootstrap bucket when that instance * is launched. You must limit write access to your CDK bootstrap bucket to prevent an attacker from modifying the actions * performed by these scripts. We strongly recommend that you either enable Amazon S3 server access logging on your CDK * bootstrap bucket, or enable AWS CloudTrail on your account to assist in post-incident analysis of compromised production * environments. * - Care must be taken to secure what can connect to the RenderQueue. The RenderQueue does not authenticate API * requests made against it. You must limit access to the RenderQueue endpoint to only trusted hosts. Those hosts * should be governed carefully, as malicious software could use the API to remotely execute code across the entire render farm. * - The RenderQueue can be deployed with network encryption through Transport Layer Security (TLS) or without it. Unencrypted * network communications can be eavesdropped upon or modified in transit. We strongly recommend deploying the RenderQueue * with TLS enabled in production environments and it is configured to be on by default. */ export class RenderQueue extends RenderQueueBase implements IGrantable { /** * Container listening ports for each protocol. */ private static readonly RCS_PROTO_PORTS = { [ApplicationProtocol.HTTP]: 8080, [ApplicationProtocol.HTTPS]: 4433, }; private static readonly DEFAULT_HOSTNAME = 'renderqueue'; private static readonly DEFAULT_DOMAIN_NAME = 'aws-rfdk.com'; private static readonly DEFAULT_VPC_SUBNETS_ALB: SubnetSelection = { subnetType: SubnetType.PRIVATE, onePerAz: true }; private static readonly DEFAULT_VPC_SUBNETS_OTHER: SubnetSelection = { subnetType: SubnetType.PRIVATE }; /** * The minimum Deadline version required for the Remote Connection Server to support load-balancing */ private static readonly MINIMUM_LOAD_BALANCING_VERSION = new Version([10, 1, 10, 0]); /** * Regular expression that validates a hostname (portion in front of the subdomain). */ private static readonly RE_VALID_HOSTNAME = /^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/i; /** * Information for the RCS user. */ private static readonly RCS_USER = { uid: 1000, gid: 1000, username: 'ec2-user' }; /** * The principal to grant permissions to. */ public readonly grantPrincipal: IPrincipal; /** * The Amazon ECS cluster that is hosting the fleet of Deadline RCS applications. */ public readonly cluster: Cluster; /** * @inheritdoc */ public readonly connections: Connections; /** * @inheritdoc */ public readonly endpoint: ConnectableApplicationEndpoint; /** * The application load balancer that serves the traffic. */ public readonly loadBalancer: ApplicationLoadBalancer; /** * The Amazon EC2 Auto Scaling Group within the {@link RenderQueue.cluster} * that contains the Deadline RCS's instances. */ public readonly asg: AutoScalingGroup; /** * The version of Deadline that the RenderQueue uses */ public readonly version: IVersion; /** * The secret containing the cert chain for external connections. */ public readonly certChain?: ISecret; /** * @inheritdoc */ public readonly repository: IRepository; /** * @inheritdoc */ public readonly backendConnections: Connections; /** * Whether SEP policies have been added */ private haveAddedSEPPolicies: boolean = false; /** * Whether Resource Tracker policies have been added */ private haveAddedResourceTrackerPolicies: boolean = false; /** * The log group where the RCS container will log to */ private readonly logGroup: ILogGroup; /** * Instance of the Application Load Balanced EC2 service pattern. */ private readonly pattern: ApplicationLoadBalancedEc2Service; /** * The certificate used by the ALB for external Traffic */ private readonly clientCert?: ICertificate; /** * The connection object that contains the logic for how clients can connect to the Render Queue. */ private readonly rqConnection: RenderQueueConnection; /** * Constraints on the number of Deadline RCS processes that can be run as part of this * RenderQueue. */ private readonly renderQueueSize: RenderQueueSizeConstraints; /** * The listener on the ALB that is redirecting traffic to the RCS. */ private readonly listener: ApplicationListener; /** * The ECS task for the RCS. */ private readonly taskDefinition: Ec2TaskDefinition; /** * Depend on this to ensure that ECS Service is stable. */ private ecsServiceStabilized: WaitForStableService; constructor(scope: Construct, id: string, private readonly props: RenderQueueProps) { super(scope, id); this.repository = props.repository; this.renderQueueSize = props?.renderQueueSize ?? {min: 1, max: 1}; if (props.version.isLessThan(RenderQueue.MINIMUM_LOAD_BALANCING_VERSION)) { // Deadline versions earlier than 10.1.10 do not support horizontal scaling behind a load-balancer, so we limit to at most one instance if ((this.renderQueueSize.min ?? 0) > 1) { throw new Error(`renderQueueSize.min for Deadline version less than ${RenderQueue.MINIMUM_LOAD_BALANCING_VERSION.toString()} cannot be greater than 1 - got ${this.renderQueueSize.min}`); } if ((this.renderQueueSize.desired ?? 0) > 1) { throw new Error(`renderQueueSize.desired for Deadline version less than ${RenderQueue.MINIMUM_LOAD_BALANCING_VERSION.toString()} cannot be greater than 1 - got ${this.renderQueueSize.desired}`); } if ((this.renderQueueSize.max ?? 0) > 1) { throw new Error(`renderQueueSize.max for Deadline version less than ${RenderQueue.MINIMUM_LOAD_BALANCING_VERSION.toString()} cannot be greater than 1 - got ${this.renderQueueSize.max}`); } } this.version = props?.version; const externalProtocol = props.trafficEncryption?.externalTLS?.enabled === false ? ApplicationProtocol.HTTP : ApplicationProtocol.HTTPS; let loadBalancerFQDN: string | undefined; let domainZone: IHostedZone | undefined; if ( externalProtocol === ApplicationProtocol.HTTPS ) { const tlsInfo = this.getOrCreateTlsInfo(props); this.certChain = tlsInfo.certChain; this.clientCert = tlsInfo.serverCert; loadBalancerFQDN = tlsInfo.fullyQualifiedDomainName; domainZone = tlsInfo.domainZone; } else { if (props.hostname) { loadBalancerFQDN = this.generateFullyQualifiedDomainName(props.hostname.zone, props.hostname.hostname); domainZone = props.hostname.zone; } } this.version = props.version; const internalProtocol = props.trafficEncryption?.internalProtocol ?? ApplicationProtocol.HTTPS; this.cluster = new Cluster(this, 'Cluster', { vpc: props.vpc, }); const minCapacity = props.renderQueueSize?.min ?? 1; if (minCapacity < 1) { throw new Error(`renderQueueSize.min capacity must be at least 1: got ${minCapacity}`); } const maxCapacity = this.renderQueueSize.max ?? this.renderQueueSize?.desired; if (this.renderQueueSize?.desired && maxCapacity && this.renderQueueSize?.desired > maxCapacity) { throw new Error(`renderQueueSize.desired capacity cannot be more than ${maxCapacity}: got ${this.renderQueueSize.desired}`); } this.asg = this.cluster.addCapacity('RCS Capacity', { vpcSubnets: props.vpcSubnets ?? RenderQueue.DEFAULT_VPC_SUBNETS_OTHER, instanceType: props.instanceType ?? new InstanceType('c5.large'), minCapacity, desiredCapacity: this.renderQueueSize?.desired, maxCapacity, blockDevices: [{ deviceName: '/dev/xvda', // See: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-ami-storage-config.html // We want the volume to be encrypted. The default AMI size is 30-GiB. volume: BlockDeviceVolume.ebs(30, { encrypted: true }), }], updateType: undefined, // Workaround -- See: https://github.com/aws/aws-cdk/issues/11581 updatePolicy: UpdatePolicy.rollingUpdate(), // addCapacity doesn't specifically take a securityGroup, but it passes on its properties to the ASG it creates, // so this security group will get applied there // @ts-ignore securityGroup: props.securityGroups?.backend, }); this.backendConnections = this.asg.connections; /** * The ECS-optimized AMI that is defaulted to when adding capacity to a cluster does not include the awscli or unzip * packages as is the case with the standard Amazon Linux AMI. These are required by RFDK scripts to configure the * direct connection on the host container instances. */ this.asg.userData.addCommands( 'yum install -yq awscli unzip', ); if (props.enableLocalFileCaching ?? false) { // Has to be done before any filesystems mount. this.enableFilecaching(this.asg); } const externalPortNumber = RenderQueue.RCS_PROTO_PORTS[externalProtocol]; const internalPortNumber = RenderQueue.RCS_PROTO_PORTS[internalProtocol]; this.logGroup = LogGroupFactory.createOrFetch(this, 'LogGroupWrapper', id, { logGroupPrefix: '/renderfarm/', ...props.logGroupProps, }); this.logGroup.grantWrite(this.asg); if (props.repository.secretsManagementSettings.enabled) { const errors = []; if (props.version.isLessThan(Version.MINIMUM_SECRETS_MANAGEMENT_VERSION)) { errors.push(`The supplied Deadline version (${props.version.versionString}) does not support Deadline Secrets Management in RFDK. Either upgrade Deadline to the minimum required version (${Version.MINIMUM_SECRETS_MANAGEMENT_VERSION.versionString}) or disable the feature in the Repository's construct properties.`); } if (props.repository.secretsManagementSettings.credentials === undefined) { errors.push('The Repository does not have Secrets Management credentials'); } if (internalProtocol !== ApplicationProtocol.HTTPS) { errors.push('The internal protocol on the Render Queue is not HTTPS.'); } if (externalProtocol !== ApplicationProtocol.HTTPS) { errors.push('External TLS on the Render Queue is not enabled.'); } if (errors.length > 0) { throw new Error(`Deadline Secrets Management is enabled on the supplied Repository but cannot be enabled on the Render Queue for the following reasons:\n${errors.join('\n')}`); } } const taskDefinition = this.createTaskDefinition({ image: props.images.remoteConnectionServer, portNumber: internalPortNumber, protocol: internalProtocol, repository: props.repository, runAsUser: RenderQueue.RCS_USER, secretsManagementOptions: props.repository.secretsManagementSettings.enabled ? { credentials: props.repository.secretsManagementSettings.credentials!, posixUsername: RenderQueue.RCS_USER.username, } : undefined, }); this.taskDefinition = taskDefinition; // The fully-qualified domain name to use for the ALB const loadBalancer = new ApplicationLoadBalancer(this, 'LB', { vpc: this.cluster.vpc, vpcSubnets: props.vpcSubnetsAlb ?? RenderQueue.DEFAULT_VPC_SUBNETS_ALB, internetFacing: false, deletionProtection: props.deletionProtection ?? true, securityGroup: props.securityGroups?.frontend, }); this.pattern = new ApplicationLoadBalancedEc2Service(this, 'AlbEc2ServicePattern', { certificate: this.clientCert, cluster: this.cluster, desiredCount: this.renderQueueSize?.desired, domainZone, domainName: loadBalancerFQDN, listenerPort: externalPortNumber, loadBalancer, protocol: externalProtocol, taskDefinition, // This is required to right-size our host capacity and not have the ECS service block on updates. We set a memory // reservation, but no memory limit on the container. This allows the container's memory usage to grow unbounded. // We want 1:1 container to container instances to not over-spend, but this comes at the price of down-time during // cloudformation updates. minHealthyPercent: 0, maxHealthyPercent: 100, // This is required to ensure that the ALB listener's security group does not allow any ingress by default. openListener: false, }); // An explicit dependency is required from the Service to the Client certificate // Otherwise cloud formation will try to remove the cert before the ALB using it is disposed. if (this.clientCert) { this.pattern.node.addDependency(this.clientCert); } // An explicit dependency is required from the service to the ASG providing its capacity. // See: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html this.pattern.service.node.addDependency(this.asg); this.loadBalancer = this.pattern.loadBalancer; // Enabling dropping of invalid HTTP header fields on the load balancer to prevent http smuggling attacks. this.loadBalancer.setAttribute('routing.http.drop_invalid_header_fields.enabled', 'true'); if (props.accessLogs) { const accessLogsBucket = props.accessLogs.destinationBucket; // Policies are applied according to // https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html accessLogsBucket.addToResourcePolicy( new PolicyStatement({ actions: ['s3:PutObject'], principals: [new ServicePrincipal('delivery.logs.amazonaws.com')], resources: [`${accessLogsBucket.bucketArn}/*`], conditions: { StringEquals: { 's3:x-amz-acl': 'bucket-owner-full-control', }, }, })); accessLogsBucket.addToResourcePolicy(new PolicyStatement({ actions: [ 's3:GetBucketAcl' ], principals: [ new ServicePrincipal('delivery.logs.amazonaws.com')], resources: [ accessLogsBucket.bucketArn ], })); this.loadBalancer.logAccessLogs( accessLogsBucket, props.accessLogs.prefix); } // Ensure tasks are run on separate container instances this.pattern.service.addPlacementConstraints(PlacementConstraint.distinctInstances()); /** * Uses an escape-hatch to set the target group protocol to HTTPS. We cannot configure server certificate * validation, but at least traffic is encrypted and terminated at the application layer. */ const listener = this.loadBalancer.node.findChild('PublicListener'); this.listener = listener as ApplicationListener; const targetGroup = listener.node.findChild('ECSGroup') as ApplicationTargetGroup; const targetGroupResource = targetGroup.node.defaultChild as CfnTargetGroup; targetGroupResource.protocol = ApplicationProtocol[internalProtocol]; targetGroupResource.port = internalPortNumber; this.grantPrincipal = taskDefinition.taskRole; this.connections = new Connections({ defaultPort: Port.tcp(externalPortNumber), securityGroups: this.pattern.loadBalancer.connections.securityGroups, }); this.endpoint = new ConnectableApplicationEndpoint({ address: loadBalancerFQDN ?? this.pattern.loadBalancer.loadBalancerDnsName, port: externalPortNumber, connections: this.connections, protocol: externalProtocol, }); if ( externalProtocol === ApplicationProtocol.HTTP ) { this.rqConnection = RenderQueueConnection.forHttp({ endpoint: this.endpoint, }); } else { this.rqConnection = RenderQueueConnection.forHttps({ endpoint: this.endpoint, caCert: this.certChain!, }); } props.repository.secretsManagementSettings.credentials?.grantRead(this); this.ecsServiceStabilized = new WaitForStableService(this, 'WaitForStableService', { service: this.pattern.service, }); this.node.defaultChild = taskDefinition; // Tag deployed resources with RFDK meta-data tagConstruct(this); } protected onValidate(): string[] { const validationErrors = []; // Using the output of VersionQuery across stacks can cause issues. CloudFormation stack outputs cannot change if // a resource in another stack is referencing it. if (this.version instanceof VersionQuery) { const versionStack = Stack.of(this.version); const thisStack = Stack.of(this); if (versionStack != thisStack) { validationErrors.push('A VersionQuery can not be supplied from a different stack'); } } return validationErrors; } /** * @inheritdoc */ public configureClientECS(param: ECSConnectOptions): { [name: string]: string } { param.hosts.forEach( host => this.addChildDependency(host) ); return this.rqConnection.configureClientECS(param); } /** * @inheritdoc */ public configureClientInstance(param: InstanceConnectOptions): void { this.addChildDependency(param.host); this.rqConnection.configureClientInstance(param); } /** * @inheritdoc */ public configureSecretsManagementAutoRegistration(props: SubnetIdentityRegistrationSettingsProps) { if (!this.repository.secretsManagementSettings.enabled) { // Secrets management is not enabled, so do nothing return; } this.identityRegistrationSettings.addSubnetIdentityRegistrationSetting(props); } /** * Adds AWS Managed Policies to the Render Queue so it is able to control Deadline's Spot Event Plugin. * * See: https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/event-spot.html for additonal information. * * @param includeResourceTracker Whether or not the Resource tracker admin policy should also be added (Default: True) */ public addSEPPolicies(includeResourceTracker: boolean = true): void { if (!this.haveAddedSEPPolicies) { const sepPolicy = ManagedPolicy.fromAwsManagedPolicyName('AWSThinkboxDeadlineSpotEventPluginAdminPolicy'); this.taskDefinition.taskRole.addManagedPolicy(sepPolicy); this.haveAddedSEPPolicies = true; } if (!this.haveAddedResourceTrackerPolicies) { if (includeResourceTracker) { const rtPolicy = ManagedPolicy.fromAwsManagedPolicyName('AWSThinkboxDeadlineResourceTrackerAdminPolicy'); this.taskDefinition.taskRole.addManagedPolicy(rtPolicy); this.haveAddedResourceTrackerPolicies = true; } } } /** * Add an ordering dependency to another Construct. * * All constructs in the child's scope will be deployed after the RenderQueue has been deployed and is ready to recieve traffic. * * This can be used to ensure that the RenderQueue is fully up and serving queries before a client attempts to connect to it. * * @param child The child to make dependent upon this RenderQueue. */ public addChildDependency(child: IConstruct): void { // Narrowly define the dependencies to reduce the probability of cycles // ex: cycles that involve the security group of the RenderQueue & child. child.node.addDependency(this.listener); child.node.addDependency(this.taskDefinition); child.node.addDependency(this.pattern.service); child.node.addDependency(this.ecsServiceStabilized); } /** * Adds security groups to the frontend of the Render Queue, which is its load balancer. * @param securityGroups The security groups to add. */ public addFrontendSecurityGroups(...securityGroups: ISecurityGroup[]): void { securityGroups.forEach(securityGroup => this.loadBalancer.addSecurityGroup(securityGroup)); } /** * Adds security groups to the backend components of the Render Queue, which consists of the AutoScalingGroup for the Deadline RCS. * @param securityGroups The security groups to add. */ public addBackendSecurityGroups(...securityGroups: ISecurityGroup[]): void { securityGroups.forEach(securityGroup => this.asg.addSecurityGroup(securityGroup)); } private enableFilecaching(asg: AutoScalingGroup): void { const script = ScriptAsset.fromPathConvention(this, 'FilecachingScript', { osType: asg.osType, baseName: 'enableCacheFilesd', rootDir: join(__dirname, '..', 'scripts'), }); // A comment in userData to make this easier to test. asg.userData.addCommands('# RenderQueue file caching enabled'); script.executeOn({ host: asg, }); } private createTaskDefinition(props: { image: ContainerImage, portNumber: number, protocol: ApplicationProtocol, repository: IRepository, runAsUser?: { uid: number, gid?: number }, secretsManagementOptions?: { credentials: ISecret, posixUsername: string }, }) { const { image, portNumber, protocol, repository } = props; const taskDefinition = new Ec2TaskDefinition(this, 'RCSTask'); // Mount the repo filesystem to RenderQueue.HOST_REPO_FS_MOUNT_PATH const connection = repository.configureClientECS({ containerInstances: { hosts: [this.asg], }, containers: { taskDefinition, }, }); const environment = connection.containerEnvironment; if (protocol === ApplicationProtocol.HTTPS) { // Generate a self-signed X509 certificate, private key and passphrase for use by the RCS containers. // Note: the Application Load Balancer does not validate the certificate in any way. const rcsCertPem = new X509CertificatePem(this, 'TlsCaCertPem', { subject: { cn: 'renderfarm.local', }, }); const rcsCertPkcs = new X509CertificatePkcs12(this, 'TlsRcsCertBundle', { sourceCertificate: rcsCertPem, }); [rcsCertPem.cert, rcsCertPkcs.cert, rcsCertPkcs.passphrase].forEach(secret => { secret.grantRead(taskDefinition.taskRole); }); environment.RCS_TLS_CA_CERT_URI = rcsCertPem.cert.secretArn; environment.RCS_TLS_CERT_URI = rcsCertPkcs.cert.secretArn; environment.RCS_TLS_CERT_PASSPHRASE_URI = rcsCertPkcs.passphrase.secretArn; environment.RCS_TLS_REQUIRE_CLIENT_CERT = 'no'; } if (props.secretsManagementOptions !== undefined) { environment.RCS_SM_CREDENTIALS_URI = props.secretsManagementOptions.credentials.secretArn; } // We can ignore this in test coverage because we always use RenderQueue.RCS_USER /* istanbul ignore next */ const user = props.runAsUser ? `${props.runAsUser.uid}:${props.runAsUser.gid}` : undefined; const containerDefinition = taskDefinition.addContainer('ContainerDefinition', { image, memoryReservationMiB: 2048, environment, logging: LogDriver.awsLogs({ logGroup: this.logGroup, streamPrefix: 'RCS', }), user, }); containerDefinition.addMountPoints(connection.readWriteMountPoint); if (props.secretsManagementOptions !== undefined) { // Create volume to persist the RSA keypairs generated by Deadline between ECS tasks // This makes it so subsequent ECS tasks use the same initial Secrets Management identity const volumeName = 'deadline-user-keypairs'; taskDefinition.addVolume({ name: volumeName, dockerVolumeConfiguration: { scope: Scope.SHARED, autoprovision: true, driver: 'local', }, }); // Mount the volume into the container at the location where Deadline expects it containerDefinition.addMountPoints({ readOnly: false, sourceVolume: volumeName, containerPath: `/home/${props.secretsManagementOptions.posixUsername}/.config/.mono/keypairs`, }); } // Increase ulimits containerDefinition.addUlimits( { name: UlimitName.NOFILE, softLimit: 200000, hardLimit: 200000, }, { name: UlimitName.NPROC, softLimit: 64000, hardLimit: 64000, }, ); containerDefinition.addPortMappings({ containerPort: portNumber, hostPort: portNumber, }); return taskDefinition; } /** * Checks if the user supplied any certificate to use for TLS and uses them, or creates defaults to use. * @param props * @returns TlsInfo either based on input to the render queue, or the created defaults */ private getOrCreateTlsInfo(props: RenderQueueProps): TlsInfo { if ( (props.trafficEncryption?.externalTLS?.acmCertificate !== undefined ) || (props.trafficEncryption?.externalTLS?.rfdkCertificate !== undefined) ) { if (props.hostname === undefined) { throw new Error('The hostname for the render queue must be defined if supplying your own certificates.'); } return this.getTlsInfoFromUserProps( props.trafficEncryption.externalTLS, props.hostname, ); } return this.createDefaultTlsInfo(props.vpc, props.hostname); } /** * Creates a default certificate to use for TLS and a PrivateHostedZone to put the load balancer in. * @param vpc * @param hostname * @returns default TlsInfo */ private createDefaultTlsInfo(vpc: IVpc, hostname?: RenderQueueHostNameProps) { const domainZone = hostname?.zone ?? new PrivateHostedZone(this, 'DnsZone', { vpc: vpc, zoneName: RenderQueue.DEFAULT_DOMAIN_NAME, }); const fullyQualifiedDomainName = this.generateFullyQualifiedDomainName(domainZone, hostname?.hostname); const rootCa = new X509CertificatePem(this, 'RootCA', { subject: { cn: 'RenderQueueRootCA', }, }); const rfdkCert = new X509CertificatePem(this, 'RenderQueuePemCert', { subject: { cn: fullyQualifiedDomainName, }, signingCertificate: rootCa, }); const serverCert = new ImportedAcmCertificate( this, 'AcmCert', rfdkCert ); const certChain = rfdkCert.certChain!; return { domainZone, fullyQualifiedDomainName, serverCert, certChain, }; } /** * Gets the certificate and PrivateHostedZone provided in the Render Queue's construct props. * @param externalTLS * @param hostname * @returns The provided certificate and domain info */ private getTlsInfoFromUserProps(externalTLS: RenderQueueExternalTLSProps, hostname: RenderQueueHostNameProps): TlsInfo { let serverCert: ICertificate; let certChain: ISecret; if ( (externalTLS.acmCertificate !== undefined ) && (externalTLS.rfdkCertificate !== undefined) ) { throw new Error('Exactly one of externalTLS.acmCertificate and externalTLS.rfdkCertificate must be provided when using externalTLS.'); } if (!hostname.hostname) { throw new Error('A hostname must be supplied if a certificate is supplied, ' + 'with the common name of the certificate matching the hostname + domain name.'); } const fullyQualifiedDomainName = this.generateFullyQualifiedDomainName(hostname.zone, hostname.hostname); if ( externalTLS.acmCertificate ) { if ( externalTLS.acmCertificateChain === undefined ) { throw new Error('externalTLS.acmCertificateChain must be provided when using externalTLS.acmCertificate.'); } serverCert = externalTLS.acmCertificate; certChain = externalTLS.acmCertificateChain; } else { // Using externalTLS.rfdkCertificate if ( externalTLS.rfdkCertificate!.certChain === undefined ) { throw new Error('Provided rfdkCertificate does not contain a certificate chain.'); } serverCert = new ImportedAcmCertificate( this, 'AcmCert', externalTLS.rfdkCertificate! ); certChain = externalTLS.rfdkCertificate!.certChain; } return { domainZone: hostname.zone, fullyQualifiedDomainName, serverCert, certChain, }; } /** * Helper method to create the fully qualified domain name for the given hostname and PrivateHostedZone. * @param hostname * @param zone * @returns The fully qualified domain name */ private generateFullyQualifiedDomainName(zone: IPrivateHostedZone, hostname: string = RenderQueue.DEFAULT_HOSTNAME): string { if (!RenderQueue.RE_VALID_HOSTNAME.test(hostname)) { throw new Error(`Invalid RenderQueue hostname: ${hostname}`); } return `${hostname}.${zone.zoneName}`; } /** * The instance that runs commands during the deployment. */ private get deploymentInstance(): DeploymentInstance { const CONFIGURE_REPOSITORY_CONSTRUCT_ID = 'ConfigureRepository'; const deploymentInstanceNode = this.node.tryFindChild(CONFIGURE_REPOSITORY_CONSTRUCT_ID); if (deploymentInstanceNode === undefined) { return new DeploymentInstance(this, CONFIGURE_REPOSITORY_CONSTRUCT_ID, { vpc: this.props.vpc, vpcSubnets: this.props.vpcSubnets ?? RenderQueue.DEFAULT_VPC_SUBNETS_OTHER, }); } else if (deploymentInstanceNode instanceof DeploymentInstance) { return deploymentInstanceNode; } else { throw new Error(`Unexpected type for ${deploymentInstanceNode.node.path}. Expected ${DeploymentInstance.name}, but found ${typeof(deploymentInstanceNode)}.`); } } /** * The construct that manages Deadline Secrets Management identity registration settings */ private get identityRegistrationSettings(): SecretsManagementIdentityRegistration { const IDENTITY_REGISTRATION_CONSTRUCT_ID = 'SecretsManagementIdentityRegistration'; const secretsManagementIdentityRegistration = this.node.tryFindChild(IDENTITY_REGISTRATION_CONSTRUCT_ID); if (!secretsManagementIdentityRegistration) { return new SecretsManagementIdentityRegistration( this, IDENTITY_REGISTRATION_CONSTRUCT_ID, { deploymentInstance: this.deploymentInstance, repository: this.repository, renderQueueSubnets: this.props.vpc.selectSubnets( this.props.vpcSubnetsAlb ?? RenderQueue.DEFAULT_VPC_SUBNETS_ALB, ), version: this.props.version, }, ); } else if (secretsManagementIdentityRegistration instanceof SecretsManagementIdentityRegistration) { return secretsManagementIdentityRegistration; } else { throw new Error(`Unexpected type for ${secretsManagementIdentityRegistration.node.path}. Expected ${SecretsManagementIdentityRegistration.name}, but found ${typeof(secretsManagementIdentityRegistration)}.`); } } }
the_stack
import type * as pg from 'pg'; import { performance } from 'perf_hooks'; import { getConfig, SQLQuery } from './config'; import { isPOJO, NoInfer } from './utils'; import type { Updatable, Whereable, Table, Column, } from 'zapatos/schema'; // === symbols, types, wrapper classes and shortcuts === /** * Compiles to `DEFAULT` for use in `INSERT`/`UPDATE` queries. */ export const Default = Symbol('DEFAULT'); export type DefaultType = typeof Default; /** * Compiles to the current column name within a `Whereable`. */ export const self = Symbol('self'); export type SelfType = typeof self; /** * Signals all rows are to be returned (without filtering via a `WHERE` clause) */ export const all = Symbol('all'); export type AllType = typeof all; /** * JSON types */ export type JSONValue = null | boolean | number | string | JSONObject | JSONArray; export type JSONObject = { [k: string]: JSONValue }; export type JSONArray = JSONValue[]; /** * `int8` value represented as a string */ export type Int8String = `${number}`; /** * Generic range value represented as a string */ export type RangeString<Bound extends string | number> = `${'[' | '('}${Bound},${Bound}${']' | ')'}`; /** * `tsrange`, `tstzrange` or `daterange` value represented as a string. The * format of the upper and lower bound `date`, `timestamp` or `timestamptz` * values depends on pg's `DateStyle` setting. */ export type DateRangeString = RangeString<string>; /** * `int4range`, `int8range` or `numrange` value represented as a string */ export type NumberRangeString = RangeString<number | ''>; /** * `bytea` value representated as a hex string. Note: for large objects, use * something like https://www.npmjs.com/package/pg-large-object instead. */ export type ByteArrayString = `\\x${string}`; /** * Make a function `STRICT` in the Postgres sense — where it's an alias for * `RETURNS NULL ON NULL INPUT` — with appropriate typing. * * For example, Zapatos' `toBuffer()` function is defined as: * * ``` * export const toBuffer = strict((ba: ByteArrayString) => Buffer.from(ba.slice(2), 'hex')); * ``` * * The generic input and output types `FnIn` and `FnOut` can be inferred from * `fn`, as seen above, but can also be explicitly narrowed. For example, to * convert specifically from `TimestampTzString` to Luxon's `DateTime`, but * pass through `null`s unchanged: * * ``` * const toDateTime = db.strict<db.TimestampTzString, DateTime>(DateTime.fromISO); * ``` * * @param fn The single-argument transformation function to be made strict. */ export function strict<FnIn, FnOut>(fn: (x: FnIn) => FnOut): <T extends FnIn | null>(d: T) => T extends FnIn ? Exclude<T, FnIn> | FnOut : T { return function <T extends FnIn | null>(d: T) { return (d === null ? null : fn(d as FnIn)) as any; }; } /** * Convert a `bytea` hex representation to a JavaScript `Buffer`. Note: for * large objects, use something like * [pg-large-object](https://www.npmjs.com/package/pg-large-object) instead. * * @param ba The `ByteArrayString` hex representation (or `null`) */ export const toBuffer = strict((ba: ByteArrayString) => Buffer.from(ba.slice(2), 'hex')); /** * Compiles to a numbered query parameter (`$1`, `$2`, etc) and adds the wrapped value * at the appropriate position of the values array passed to `pg`. * @param x The value to be wrapped * @param cast Optional cast type. If a string, the parameter will be cast to * this type within the query e.g. `CAST($1 AS type)` instead of plain `$1`. If * `true`, the value will be JSON stringified and cast to `json` (irrespective * of the configuration parameters `castArrayParamsToJson` and * `castObjectParamsToJson`). If `false`, the value will **not** be JSON- * stringified or cast to `json` (again irrespective of the configuration * parameters `castArrayParamsToJson` and `castObjectParamsToJson`). */ export class Parameter<T = any> { constructor(public value: T, public cast?: boolean | string) { } } /** * Returns a `Parameter` instance, which compiles to a numbered query parameter * (`$1`, `$2`, etc) and adds its wrapped value at the appropriate position of * the values array passed to `pg`. * @param x The value to be wrapped * @param cast Optional cast type. If a string, the parameter will be cast to * this type within the query e.g. `CAST($1 AS type)` instead of plain `$1`. If * `true`, the value will be JSON stringified and cast to `json` (irrespective * of the configuration parameters `castArrayParamsToJson` and * `castObjectParamsToJson`). If `false`, the value will **not** be JSON * stringified or cast to `json` (again irrespective of the configuration * parameters `castArrayParamsToJson` and `castObjectParamsToJson`). */ export function param<T = any>(x: T, cast?: boolean | string) { return new Parameter(x, cast); } /** * 💥💥💣 **DANGEROUS** 💣💥💥 * * Compiles to the wrapped string value, as is, which may enable SQL injection * attacks. */ export class DangerousRawString { constructor(public value: string) { } } /** * 💥💥💣 **DANGEROUS** 💣💥💥 * * Remember [Little Bobby Tables](https://xkcd.com/327/). * Did you want `db.param` instead? * --- * Returns a `DangerousRawString` instance, wrapping a string. * `DangerousRawString` compiles to the wrapped string value, as-is, which may * enable SQL injection attacks. */ export function raw(x: string) { return new DangerousRawString(x); } /** * Wraps either an array or object, and compiles to a quoted, comma-separated * list of array values (for use in a `SELECT` query) or object keys (for use * in an `INSERT`, `UPDATE` or `UPSERT` query, alongside `ColumnValues`). */ export class ColumnNames<T> { constructor(public value: T) { } } /** * Returns a `ColumnNames` instance, wrapping either an array or an object. * `ColumnNames` compiles to a quoted, comma-separated list of array values (for * use in a `SELECT` query) or object keys (for use in an `INSERT`, `UDPATE` or * `UPSERT` query alongside a `ColumnValues`). */ export function cols<T>(x: T) { return new ColumnNames<T>(x); } /** * Compiles to a quoted, comma-separated list of object keys for use in an * `INSERT`, `UPDATE` or `UPSERT` query, alongside `ColumnNames`. */ export class ColumnValues<T> { constructor(public value: T) { } } /** * Returns a ColumnValues instance, wrapping an object. ColumnValues compiles to * a quoted, comma-separated list of object keys for use in an INSERT, UPDATE * or UPSERT query alongside a `ColumnNames`. */ export function vals<T>(x: T) { return new ColumnValues<T>(x); } /** * Compiles to the name of the column it wraps in the table of the parent query. * @param value The column name */ export class ParentColumn<T extends Column = Column> { constructor(public value: T) { } } /** * Returns a `ParentColumn` instance, wrapping a column name, which compiles to * that column name of the table of the parent query. */ export function parent<T extends Column = Column>(x: T) { return new ParentColumn<T>(x); } export type GenericSQLExpression = SQLFragment<any, any> | Parameter | DefaultType | DangerousRawString | SelfType; export type SQLExpression = Table | ColumnNames<Updatable | (keyof Updatable)[]> | ColumnValues<Updatable | any[]> | Whereable | Column | GenericSQLExpression; export type SQL = SQLExpression | SQLExpression[]; export type Queryable = pg.ClientBase | pg.Pool; // === SQL tagged template strings === /** * Tagged template function returning a `SQLFragment`. The first generic type * argument defines what interpolated value types are allowed. The second * defines what type the `SQLFragment` produces, where relevant (i.e. when * calling `.run(...)` on it, or using it as the value of an `extras` object). */ export function sql< Interpolations = SQL, RunResult = pg.QueryResult['rows'], Constraint = never, >(literals: TemplateStringsArray, ...expressions: NoInfer<Interpolations>[]) { return new SQLFragment<RunResult, Constraint>(Array.prototype.slice.apply(literals), expressions); } let preparedNameSeq = 0; export class SQLFragment<RunResult = pg.QueryResult['rows'], Constraint = never> { protected constraint?: Constraint; /** * When calling `run`, this function is applied to the object returned by `pg` * to produce the result that is returned. By default, the `rows` array is * returned — i.e. `(qr) => qr.rows` — but some shortcut functions alter this * in order to match their declared `RunResult` type. */ runResultTransform: (qr: pg.QueryResult) => any = qr => qr.rows; parentTable?: string = undefined; // used for nested shortcut select queries preparedName?: string = undefined; // for prepared statements noop = false; // if true, bypass actually running the query unless forced to e.g. for empty INSERTs noopResult: any; // if noop is true and DB is bypassed, what should be returned? constructor(protected literals: string[], protected expressions: SQL[]) { } /** * Instruct Postgres to treat this as a prepared statement: see * https://node-postgres.com/features/queries#prepared-statements * @param name A name for the prepared query. If not specified, it takes the * value '_zapatos_prepared_N', where N is an increasing sequence number. */ prepared = (name = `_zapatos_prepared_${preparedNameSeq++}`) => { this.preparedName = name; return this; }; /** * Compile and run this query using the provided database connection. What's * returned is piped via `runResultTransform` before being returned. * @param queryable A database client or pool * @param force If true, force this query to hit the DB even if it's marked as a no-op */ run = async (queryable: Queryable, force = false): Promise<RunResult> => { const query = this.compile(), config = getConfig(), txnId = (queryable as any)._zapatos?.txnId; if (config.queryListener) config.queryListener(query, txnId); const startMs = performance.now(); let result; if (!this.noop || force) { const qr = await queryable.query(query); result = this.runResultTransform(qr); } else { result = this.noopResult; } if (config.resultListener) config.resultListener(result, txnId, performance.now() - startMs); return result; }; /** * Compile this query, returning a `{ text: string, values: any[] }` object * that could be passed to the `pg` query function. Arguments are generally * only passed when the function calls itself recursively. */ compile = (result: SQLQuery = { text: '', values: [] }, parentTable?: string, currentColumn?: Column) => { if (this.parentTable) parentTable = this.parentTable; if (this.noop) result.text += "/* marked no-op: won't hit DB unless forced -> */ "; result.text += this.literals[0]; for (let i = 1, len = this.literals.length; i < len; i++) { this.compileExpression(this.expressions[i - 1], result, parentTable, currentColumn); result.text += this.literals[i]; } if (this.preparedName != null) result.name = this.preparedName; return result; }; compileExpression = (expression: SQL, result: SQLQuery = { text: '', values: [] }, parentTable?: string, currentColumn?: Column) => { if (this.parentTable) parentTable = this.parentTable; if (expression instanceof SQLFragment) { // another SQL fragment? recursively compile this one expression.compile(result, parentTable, currentColumn); } else if (typeof expression === 'string') { // if it's a string, it should be a x.Table or x.Column type, so just needs quoting result.text += expression.charAt(0) === '"' ? expression : `"${expression}"`; } else if (expression instanceof DangerousRawString) { // Little Bobby Tables passes straight through ... result.text += expression.value; } else if (Array.isArray(expression)) { // an array's elements are compiled one by one -- note that an empty array can be used as a non-value for (let i = 0, len = expression.length; i < len; i++) this.compileExpression(expression[i], result, parentTable, currentColumn); } else if (expression instanceof Parameter) { // parameters become placeholders, and a corresponding entry in the values array const placeholder = '$' + String(result.values.length + 1), // 1-based indexing config = getConfig(); if ( ((expression.cast !== false && (expression.cast === true || config.castArrayParamsToJson)) && Array.isArray(expression.value)) || ((expression.cast !== false && (expression.cast === true || config.castObjectParamsToJson)) && isPOJO(expression.value)) ) { result.values.push(JSON.stringify(expression.value)); result.text += `CAST(${placeholder} AS "json")`; } else if (typeof expression.cast === 'string') { result.values.push(expression.value); result.text += `CAST(${placeholder} AS "${expression.cast}")`; } else { result.values.push(expression.value); result.text += placeholder; } } else if (expression === Default) { // a column default result.text += 'DEFAULT'; } else if (expression === self) { // alias to the latest column, if applicable if (!currentColumn) throw new Error(`The 'self' column alias has no meaning here`); result.text += `"${currentColumn}"`; } else if (expression instanceof ParentColumn) { // alias to the parent table (plus supplied column name) of a nested query, if applicable if (!parentTable) throw new Error(`The 'parent' table alias has no meaning here`); result.text += `"${parentTable}"."${expression.value}"`; } else if (expression instanceof ColumnNames) { // a ColumnNames-wrapped object -> quoted names in a repeatable order // OR a ColumnNames-wrapped array -> quoted array values const columnNames = Array.isArray(expression.value) ? expression.value : Object.keys(expression.value).sort(); result.text += columnNames.map(k => `"${k}"`).join(', '); } else if (expression instanceof ColumnValues) { // a ColumnValues-wrapped object OR array // -> values (in ColumnNames-matching order, if applicable) punted as SQLFragments or Parameters if (Array.isArray(expression.value)) { const values: any[] = expression.value; for (let i = 0, len = values.length; i < len; i++) { const value = values[i]; if (i > 0) result.text += ', '; if (value instanceof SQLFragment) this.compileExpression(value, result, parentTable); else this.compileExpression(new Parameter(value), result, parentTable); } } else { const columnNames = <Column[]>Object.keys(expression.value).sort(), columnValues = columnNames.map(k => (<any>expression.value)[k]); for (let i = 0, len = columnValues.length; i < len; i++) { const columnName = columnNames[i], columnValue = columnValues[i]; if (i > 0) result.text += ', '; if (columnValue instanceof SQLFragment || columnValue instanceof Parameter || columnValue === Default) this.compileExpression(columnValue, result, parentTable, columnName); else this.compileExpression(new Parameter(columnValue), result, parentTable, columnName); } } } else if (typeof expression === 'object') { // must be a Whereable object, so put together a WHERE clause const columnNames = <Column[]>Object.keys(expression).sort(); if (columnNames.length) { // if the object is not empty result.text += '('; for (let i = 0, len = columnNames.length; i < len; i++) { const columnName = columnNames[i], columnValue = (<any>expression)[columnName]; if (i > 0) result.text += ' AND '; if (columnValue instanceof SQLFragment) { result.text += '('; this.compileExpression(columnValue, result, parentTable, columnName); result.text += ')'; } else { result.text += `"${columnName}" = `; this.compileExpression(columnValue instanceof ParentColumn ? columnValue : new Parameter(columnValue), result, parentTable, columnName); } } result.text += ')'; } else { // or if it is empty, it should always match result.text += 'TRUE'; } } else { throw new Error(`Alien object while interpolating SQL: ${expression}`); } }; }
the_stack
import * as React from 'react'; import { IWebPartContext} from '@microsoft/sp-webpart-base'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import { IconButton, IButtonProps } from 'office-ui-fabric-react/lib/Button'; import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel'; import { Spinner, SpinnerType } from 'office-ui-fabric-react/lib/Spinner'; import { Environment, EnvironmentType } from '@microsoft/sp-core-library'; import { IPropertyFieldTermSetPickerPropsInternal, ISPTermStores, ISPTermStore, ISPTermGroups, ISPTermGroup, ISPTermSets, ISPTermSet, ISPTermObject } from './PropertyFieldTermSetPicker'; import { SPHttpClient, SPHttpClientResponse, ISPHttpClientOptions } from '@microsoft/sp-http'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; require('react-ui-tree-draggable/dist/react-ui-tree.css'); var Tree: any = require('react-ui-tree-draggable/dist/react-ui-tree'); /** * @interface * PropertyFieldTermSetPickerHost properties interface * */ export interface IPropertyFieldTermSetPickerHostProps extends IPropertyFieldTermSetPickerPropsInternal { } /** * @interface * PropertyFieldTermSetPickerHost state interface * */ export interface IPropertyFieldFontPickerHostState { termStores: ISPTermStores; errorMessage?: string; openPanel: boolean; loaded: boolean; activeNodes: ISPTermSets; } /** * @class * Renders the controls for PropertyFieldTermSetPicker component */ export default class PropertyFieldTermSetPickerHost extends React.Component<IPropertyFieldTermSetPickerHostProps, IPropertyFieldFontPickerHostState> { private async: Async; private delayedValidate: (value: ISPTermSets) => void; /** * @function * Constructor */ constructor(props: IPropertyFieldTermSetPickerHostProps) { super(props); this.state = { activeNodes: this.props.initialValues !== undefined ? this.props.initialValues : [], termStores: [], loaded: false, openPanel: false, errorMessage: '' }; this.onOpenPanel = this.onOpenPanel.bind(this); this.onClosePanel = this.onClosePanel.bind(this); this.renderNode = this.renderNode.bind(this); this.onClickNode = this.onClickNode.bind(this); this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); } /** * @function * Loads the list from SharePoint current web site */ private loadTermStores(): void { var termsService: SPTermStorePickerService = new SPTermStorePickerService(this.props, this.props.context); termsService.getTermStores().then((response: ISPTermStores) => { this.state.termStores = response; this.state.loaded = true; this.setState(this.state); response.map((termStore: ISPTermStore, index: number) => { termsService.getTermStoresGroups(termStore).then((groupsResponse: ISPTermGroups) => { termStore.children = groupsResponse; this.setState(this.state); groupsResponse.map((group: ISPTermGroup) => { termsService.getTermSets(termStore, group).then((termSetsResponse: ISPTermSets) => { group.children = termSetsResponse; this.setState(this.state); }); }); }); }); }); } /** * @function * Validates the new custom field value */ private validate(value: ISPTermSets): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.props.initialValues, value); return; } var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || []); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.props.initialValues, value); this.state.errorMessage = result; this.setState(this.state); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.props.initialValues, value); this.state.errorMessage = errorMessage; this.setState(this.state); }); } } else { this.notifyAfterValidate(this.props.initialValues, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: ISPTermSets, newValue: ISPTermSets) { if (this.props.onPropertyChange && newValue != null) { this.props.properties[this.props.targetProperty] = newValue; this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); if (!this.props.disableReactivePropertyChanges && this.props.render != null) this.props.render(); } } /** * @function * Open the right Panel */ private onOpenPanel(): void { if (this.props.disabled === true) return; this.state.openPanel = true; this.state.loaded = false; this.loadTermStores(); this.setState(this.state); } /** * @function * Close the panel */ private onClosePanel(): void { this.state.openPanel = false; this.state.loaded = false; this.setState(this.state); } /** * clicks on a node * @param node */ private onClickNode(node: ISPTermSet): void { if (node.children !== undefined && node.children.length != 0) return; if (this.props.allowMultipleSelections === false) { this.state.activeNodes = [node]; } else { var index = this.getSelectedNodePosition(node); if (index != -1) this.state.activeNodes.splice(index, 1); else this.state.activeNodes.push(node); } this.setState(this.state); this.delayedValidate(this.state.activeNodes); } /** * @function * Gets the given node position in the active nodes collection * @param node */ private getSelectedNodePosition(node: ISPTermSet): number { for (var i = 0; i < this.state.activeNodes.length; i++) { if (node.Guid === this.state.activeNodes[i].Guid) return i; } return -1; } /** * @function * Called when the component will unmount */ public componentWillUnmount() { if (this.async !== undefined) this.async.dispose(); } /** * @function * Renders the given node * @param node */ private renderNode(node: ISPTermObject): JSX.Element { var style: any = { padding: '4px 5px', width: '100%', display: 'flex'}; var selected: boolean = false; var isFolder: boolean = false; if (node.leaf === false || (node.children !== undefined && node.children.length != 0)) isFolder = true; var checkBoxAvailable: boolean = true; if (isFolder === true) checkBoxAvailable = false; var picUrl: string = ''; if (node.type === "TermStore") { picUrl = this.props.context.pageContext.web.absoluteUrl + '/_layouts/15/Images/EMMRoot.png'; } else if (node.type === "TermGroup") { picUrl = this.props.context.pageContext.web.absoluteUrl + '/_layouts/15/Images/EMMGroup.png'; } else if (node.type === "TermSet") { picUrl = this.props.context.pageContext.web.absoluteUrl + '/_layouts/15/Images/EMMTermSet.png'; selected = this.getSelectedNodePosition(node as ISPTermSet) != -1; if (selected === true) { style.backgroundColor = '#EAEAEA'; } } return ( <div style={style} onClick={this.onClickNode.bind(null, node)} name={node.Guid} id={node.Guid} role="menuitem"> { checkBoxAvailable ? <div style={{marginRight: '5px'}}> <Checkbox checked={selected} disabled={this.props.disabled} label='' onChange={this.onClickNode.bind(null, node)} /> </div> : '' } <div style={{paddingTop: '7px'}}> { picUrl !== undefined && picUrl != '' ? <img src={picUrl} width="18" height="18" style={{paddingRight: '5px'}} alt={node.Name}/> : '' } { node.type === "TermStore" ? <strong>{node.Name}</strong> : node.Name } </div> </div> ); } /** * @function * Renders the SPListpicker controls with Office UI Fabric */ public render(): JSX.Element { var termSetsString: string = ''; if (this.state.activeNodes !== undefined) { this.state.activeNodes.map((termSet: ISPTermSet, index: number) => { if (index > 0) termSetsString += '; '; termSetsString += termSet.Name; }); } //Renders content return ( <div> <Label>{this.props.label}</Label> <table style={{width: '100%', borderSpacing: 0}}> <tbody> <tr> <td width="*"> <TextField disabled={this.props.disabled} style={{width:'100%'}} onChanged={null} readOnly={true} value={termSetsString} /> </td> <td width="32"> <IconButton disabled={this.props.disabled} iconProps={ { iconName: 'Tag' } } onClick={this.onOpenPanel} /> </td> </tr> </tbody> </table> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div style={{paddingBottom: '8px'}}><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} <Panel isOpen={this.state.openPanel} hasCloseButton={true} onDismiss={this.onClosePanel} isLightDismiss={true} type={PanelType.medium} headerText={this.props.panelTitle}> { this.state.loaded === false ? <Spinner type={ SpinnerType.normal } /> : '' } { this.state.loaded === true ? this.state.termStores.map((rootNode: ISPTermStore, index: number) => { return ( <Tree paddingLeft={15} tree={rootNode} isNodeCollapsed={false} renderNode={this.renderNode} draggable={false} key={'termRootNode-' + index} /> ); }) : '' } </Panel> </div> ); } } /** * @class * Service implementation to manage term stores in SharePoint */ class SPTermStorePickerService { private context: IWebPartContext; private props: IPropertyFieldTermSetPickerHostProps; private taxonomySession: string; private formDigest: string; /** * @function * Service constructor */ constructor(_props: IPropertyFieldTermSetPickerHostProps, pageContext: IWebPartContext){ this.props = _props; this.context = pageContext; } /** * @function * Gets the collection of term stores in the current SharePoint env */ public getTermStores(): Promise<ISPTermStores> { if (Environment.type === EnvironmentType.Local) { //If the running environment is local, load the data from the mock return this.getTermStoresFromMock(); } else { //First gets the FORM DIGEST VALUE var contextInfoUrl: string = this.context.pageContext.web.absoluteUrl + "/_api/contextinfo"; var httpPostOptions: ISPHttpClientOptions = { headers: { "accept": "application/json", "content-type": "application/json" } }; return this.context.spHttpClient.post(contextInfoUrl, SPHttpClient.configurations.v1, httpPostOptions).then((response: SPHttpClientResponse) => { return response.json().then((jsonResponse: any) => { this.formDigest = jsonResponse.FormDigestValue; //Build the Client Service Request var clientServiceUrl = this.context.pageContext.web.absoluteUrl + '/_vti_bin/client.svc/ProcessQuery'; var data = '<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="Javascript Library"><Actions><ObjectPath Id="1" ObjectPathId="0" /><ObjectIdentityQuery Id="2" ObjectPathId="0" /><Query Id="3" ObjectPathId="0"><Query SelectAllProperties="true"><Properties /></Query></Query><ObjectPath Id="5" ObjectPathId="4" /><Query Id="6" ObjectPathId="4"><Query SelectAllProperties="true"><Properties /></Query><ChildItemQuery SelectAllProperties="true"><Properties /></ChildItemQuery></Query></Actions><ObjectPaths><StaticMethod Id="0" Name="GetTaxonomySession" TypeId="{981cbc68-9edc-4f8d-872f-71146fcbb84f}" /><Property Id="4" ParentId="0" Name="TermStores" /></ObjectPaths></Request>'; httpPostOptions = { headers: { 'accept': 'application/json', 'content-type': 'application/json', "X-RequestDigest": this.formDigest }, body: data }; return this.context.spHttpClient.post(clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions).then((serviceResponse: SPHttpClientResponse) => { return serviceResponse.json().then((serviceJSONResponse: any) => { //Construct results var res: ISPTermStores = []; serviceJSONResponse.map((child: any) => { if (child != null && child['_ObjectType_'] !== undefined) { var objType = child['_ObjectType_']; if (objType === "SP.Taxonomy.TaxonomySession") { this.taxonomySession = child['_ObjectIdentity_']; } else if (objType === "SP.Taxonomy.TermStoreCollection") { var childTermStores = child['_Child_Items_']; childTermStores.map((childTerm: any) => { var newTermStore: ISPTermStore = { Name: childTerm['Name'] !== undefined ? childTerm['Name'] : '', Guid: childTerm['Id'] !== undefined ? this.cleanGuid(childTerm['Id']): '', Identity: childTerm['_ObjectIdentity_'] !== undefined ? childTerm['_ObjectIdentity_'] : '', IsOnline: childTerm['IsOnline'] !== undefined ? childTerm['IsOnline'] : '', WorkingLanguage: childTerm['WorkingLanguage'] !== undefined ? childTerm['WorkingLanguage'] : '', DefaultLanguage: childTerm['DefaultLanguage'] !== undefined ? childTerm['DefaultLanguage'] : '', Languages: childTerm['Languages'] !== undefined ? childTerm['Languages'] : [], leaf: false, type: 'TermStore' }; if (!(this.props.excludeOfflineTermStores === true && newTermStore.IsOnline === false)) res.push(newTermStore); }); } } }); return res; }); }); }); }); } } public getTermStoresGroups(termStore: ISPTermStore): Promise<ISPTermGroups> { if (Environment.type === EnvironmentType.Local) { //If the running environment is local, load the data from the mock return this.getTermStoresGroupsFromMock(termStore.Identity); } else { //Build the Client Service Request var clientServiceUrl = this.context.pageContext.web.absoluteUrl + '/_vti_bin/client.svc/ProcessQuery'; var data = '<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="Javascript Library"><Actions><ObjectPath Id="16" ObjectPathId="15" /><Query Id="17" ObjectPathId="15"><Query SelectAllProperties="true"><Properties /></Query><ChildItemQuery SelectAllProperties="true"><Properties /></ChildItemQuery></Query></Actions><ObjectPaths><Property Id="15" ParentId="5" Name="Groups" /><Identity Id="5" Name="' + termStore.Identity + '" /></ObjectPaths></Request>'; var httpPostOptions = { headers: { 'accept': 'application/json', 'content-type': 'application/json', "X-RequestDigest": this.formDigest }, body: data }; return this.context.spHttpClient.post(clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions).then((serviceResponse: SPHttpClientResponse) => { return serviceResponse.json().then((serviceJSONResponse: any) => { var res: ISPTermGroups = []; serviceJSONResponse.map((child: any) => { var objType = child['_ObjectType_']; if (objType === "SP.Taxonomy.TermGroupCollection") { if (child['_Child_Items_'] !== undefined) { child['_Child_Items_'].map((childGroup: any) => { var objGroup: ISPTermGroup = { Name: childGroup['Name'] !== undefined ? childGroup['Name'] : '', Guid: childGroup['Id'] !== undefined ? this.cleanGuid(childGroup['Id']) : '', Identity: childGroup['_ObjectIdentity_'] !== undefined ? childGroup['_ObjectIdentity_'] : '', IsSiteCollectionGroup: childGroup['IsSiteCollectionGroup'] !== undefined ? childGroup['IsSiteCollectionGroup'] : '', IsSystemGroup: childGroup['IsSystemGroup'] !== undefined ? childGroup['IsSystemGroup'] : '', CreatedDate: childGroup['CreatedDate'] !== undefined ? childGroup['CreatedDate'] : '', LastModifiedDate: childGroup['LastModifiedDate'] !== undefined ? childGroup['LastModifiedDate'] : '', leaf: false, type: 'TermGroup' }; if (this.props.excludeSystemGroup === true) { if (objGroup.IsSystemGroup !== true) res.push(objGroup); } else { res.push(objGroup); } }); } } }); return res; }); }); } } public getTermSets(termStore: ISPTermStore, group: ISPTermGroup): Promise<ISPTermSets> { if (Environment.type === EnvironmentType.Local) { //If the running environment is local, load the data from the mock return this.getTermSetsFromMock(termStore.Identity, group.Guid); } else { //Build the Client Service Request var clientServiceUrl = this.context.pageContext.web.absoluteUrl + '/_vti_bin/client.svc/ProcessQuery'; var data = '<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="Javascript Library"><Actions><ObjectPath Id="26" ObjectPathId="25" /><ObjectIdentityQuery Id="27" ObjectPathId="25" /><ObjectPath Id="29" ObjectPathId="28" /><Query Id="30" ObjectPathId="28"><Query SelectAllProperties="true"><Properties /></Query><ChildItemQuery SelectAllProperties="true"><Properties /></ChildItemQuery></Query></Actions><ObjectPaths><Method Id="25" ParentId="15" Name="GetById"><Parameters><Parameter Type="String">' + group.Guid + '</Parameter></Parameters></Method><Property Id="28" ParentId="25" Name="TermSets" /><Property Id="15" ParentId="5" Name="Groups" /><Identity Id="5" Name="' + termStore.Identity + '" /></ObjectPaths></Request>'; var httpPostOptions = { headers: { 'accept': 'application/json', 'content-type': 'application/json', "X-RequestDigest": this.formDigest }, body: data }; return this.context.spHttpClient.post(clientServiceUrl, SPHttpClient.configurations.v1, httpPostOptions).then((serviceResponse: SPHttpClientResponse) => { return serviceResponse.json().then((serviceJSONResponse: any) => { var res: ISPTermSets = []; serviceJSONResponse.map((child: any) => { var objType = child['_ObjectType_']; if (objType === "SP.Taxonomy.TermSetCollection") { if (child['_Child_Items_'] !== undefined) { child['_Child_Items_'].map((childGroup: any) => { var objGroup: ISPTermSet = { Name: childGroup['Name'] !== undefined ? childGroup['Name'] : '', Guid: childGroup['Id'] !== undefined ? this.cleanGuid(childGroup['Id']) : '', Identity: childGroup['_ObjectIdentity_'] !== undefined ? childGroup['_ObjectIdentity_'] : '', CustomSortOrder: childGroup['CustomSortOrder'] !== undefined ? childGroup['CustomSortOrder'] : '', IsAvailableForTagging: childGroup['IsAvailableForTagging'] !== undefined ? childGroup['IsAvailableForTagging'] : '', Owner: childGroup['Owner'] !== undefined ? childGroup['Owner'] : '', Contact: childGroup['Contact'] !== undefined ? childGroup['Contact'] : '', Description: childGroup['Description'] !== undefined ? childGroup['Description'] : '', IsOpenForTermCreation: childGroup['IsOpenForTermCreation'] !== undefined ? childGroup['IsOpenForTermCreation'] : '', TermStoreGuid: termStore.Guid, leaf: true, type: 'TermSet' }; if (this.props.displayOnlyTermSetsAvailableForTagging === true) { if (objGroup.IsAvailableForTagging === true) res.push(objGroup); } else { res.push(objGroup); } }); } } }); return res; }); }); } } /** * @function * Clean the Guid from the Web Service response * @param guid */ private cleanGuid(guid: string): string { if (guid !== undefined) return guid.replace('/Guid(', '').replace('/', '').replace(')', ''); else return ''; } /** * @function * Returns 3 fake SharePoint lists for the Mock mode */ private getTermStoresFromMock(): Promise<ISPTermStores> { return SPTermStoreMockHttpClient.getTermStores(this.context.pageContext.web.absoluteUrl).then(() => { const mockData: ISPTermStores = [ { Name: 'Taxonomy_jHIKWt45FAQsxsbHfZ3r1Q==', Guid: '/Guid(8ca33abb-2ee5-42d4-acb6-bd138adec078)/', Identity: '8ca33abb-2ee5-42d4-acb6-bd138adec078', IsOnline: true, WorkingLanguage: '1033', DefaultLanguage: '1033', Languages:[], leaf: false, type: 'TermStore' } ]; return mockData; }) as Promise<ISPTermStores>; } private getTermStoresGroupsFromMock(termStoreIdentity: string): Promise<ISPTermGroups> { return SPTermStoreMockHttpClient.getTermStoresGroups(this.context.pageContext.web.absoluteUrl).then(() => { const mockData: ISPTermGroups = [ { Name: 'People', Guid: '/Guid(8ca33abb-2ee5-42d4-acb6-bd138adec078)/', Identity: '8ca33abb-2ee5-42d4-acb6-bd138adec078', IsSiteCollectionGroup: false, IsSystemGroup: false, CreatedDate: '', LastModifiedDate: '', leaf: false, type: 'TermGroup' }, { Name: 'Search Dictionaries', Guid: '/Guid(8ca33acc-2ee5-42d4-acb6-bd138adec078)/', Identity: '8ca33abb-2ee5-42d4-acb6-bd138adec078', IsSiteCollectionGroup: false, IsSystemGroup: false, CreatedDate: '', LastModifiedDate: '', leaf: false, type: 'TermGroup' } ]; return mockData; }) as Promise<ISPTermGroups>; } private getTermSetsFromMock(termStoreIdentity: string, groupGuid: string): Promise<ISPTermSets> { return SPTermStoreMockHttpClient.getTermSetsFromMock(this.context.pageContext.web.absoluteUrl).then(() => { const mockData: ISPTermSets = [ { Name: 'People', Guid: '/Guid(8ca44acc-2ee5-42d4-acb6-bd138adec078)/', Identity: '8ca44acc-2ee5-42d4-acb6-bd138adec078', CustomSortOrder: '', IsAvailableForTagging: true, Owner: '', Contact: '', Description: '', IsOpenForTermCreation: true, TermStoreGuid: '8ca33abb-2ee5-42d4-acb6-bd138adec078', leaf: true, type: 'TermSet' }, { Name: 'Job Title', Guid: '/Guid(8ca44acc-2ff4-42d4-acb6-bd138adec078)/', Identity: '8ca44acc-2ff4-42d4-acb6-bd138adec078', CustomSortOrder: '', IsAvailableForTagging: true, Owner: '', Contact: '', Description: '', IsOpenForTermCreation: true, TermStoreGuid: '8ca33abb-2ee5-42d4-acb6-bd138adec078', leaf: true, type: 'TermSet' } ]; return mockData; }) as Promise<ISPTermSets>; } } /** * @class * Defines a http client to request mock data to use the web part with the local workbench */ class SPTermStoreMockHttpClient { /** * @var * Mock SharePoint result sample */ private static _mockTermStores: ISPTermStores = []; private static _mockTermStoresGroups: ISPTermGroups = []; private static _mockTermSets: ISPTermSets = []; /** * @function * Mock search People method */ public static getTermStores(restUrl: string, options?: any): Promise<ISPTermStores> { return new Promise<ISPTermStores>((resolve) => { resolve(SPTermStoreMockHttpClient._mockTermStores); }); } public static getTermStoresGroups(restUrl: string, options?: any): Promise<ISPTermGroups> { return new Promise<ISPTermGroups>((resolve) => { resolve(SPTermStoreMockHttpClient._mockTermStoresGroups); }); } public static getTermSetsFromMock(restUrl: string, options?: any): Promise<ISPTermSets> { return new Promise<ISPTermSets>((resolve) => { resolve(SPTermStoreMockHttpClient._mockTermSets); }); } }
the_stack
import * as React from "react"; import { SelectedFeatureSet, SelectedFeature, LayerMetadata, SelectedLayer, FeatureProperty } from "../api/contracts/query"; import { Toolbar, IItem, DEFAULT_TOOLBAR_SIZE, TOOLBAR_BACKGROUND_COLOR } from "./toolbar"; import { tr as xlate, DEFAULT_LOCALE } from "../api/i18n"; import { GenericEvent, ICompositeSelection } from "../api/common"; import { Callout, Intent, HTMLSelect } from '@blueprintjs/core'; import { strIsNullOrEmpty } from "../utils/string"; export interface ISelectedFeatureProps { selectedFeature: SelectedFeature; selectedLayer?: LayerMetadata; locale: string; allowHtmlValues: boolean; cleanHTML?: (html: string) => string; } const DefaultSelectedFeature = (props: ISelectedFeatureProps) => { const { selectedFeature, selectedLayer, locale, allowHtmlValues, cleanHTML } = props; const featureProps = [] as FeatureProperty[]; if (selectedLayer?.Property) { for (const lp of selectedLayer.Property) { const matches = selectedFeature.Property.filter(fp => fp.Name === lp.DisplayName); if (matches.length === 1) { featureProps.push(matches[0]); } } } else { for (const fp of selectedFeature.Property) { featureProps.push(fp); } } return <table className="selection-panel-property-grid bp3-html-table bp3-html-table-condensed bp3-html-table-bordered"> <thead> <tr> <th>{xlate("SELECTION_PROPERTY", locale)}</th> <th>{xlate("SELECTION_VALUE", locale)}</th> </tr> </thead> <tbody> {featureProps.map(prop => { return <tr key={prop.Name}> <td className="property-name-cell" data-property-name={prop.Name}>{prop.Name}</td> {(() => { let value = prop.Value; if (allowHtmlValues && !strIsNullOrEmpty(value)) { if (cleanHTML) { value = cleanHTML(value); } return <td className="property-value-cell" data-property-value-for={prop.Name} dangerouslySetInnerHTML={{ __html: value }} /> } else { return <td className="property-value-cell" data-property-value-for={prop.Name}>{prop.Value}</td>; } })()} </tr>; })} </tbody> </table>; }; /** * SelectionPanel component props * * @export * @interface ISelectionPanelProps */ export interface ISelectionPanelProps { locale?: string; /** * @since 0.14 */ selection: ICompositeSelection; onResolveLayerLabel?: (layerId: string, layerName: string) => string | undefined; onRequestZoomToFeature: (feat: SelectedFeature) => void; onShowSelectedFeature: (layerId: string, selectionKey: string) => void; maxHeight?: number; selectedFeatureRenderer?: (props: ISelectedFeatureProps) => JSX.Element; /** * Controls whether HTML values are allowed be rendered in property values * * @since 0.11 * @type {boolean} * @memberof ISelectionPanelProps */ allowHtmlValues: boolean; /** * If allowHtmlValues = true, defines a custom function for sanitizing the given HTML string * to guard against cross-site scripting attacks. You are strongly recommended to provide * a santitization function if your HTML property values come from an un-trusted source * * @since 0.11 * @memberof ISelectionPanelProps */ cleanHTML?: (html: string) => string; } interface ISelectionPanel { locale: string; canGoPrev(): boolean; canGoNext(): boolean; prevFeature(): void; nextFeature(): void; canZoomSelectedFeature(): boolean; zoomSelectedFeature(): void; } function buildToolbarItems(selPanel: ISelectionPanel): IItem[] { return [ { bpIconName: "arrow-left", tooltip: xlate("SELECTION_PREV_FEATURE", selPanel.locale), enabled: () => selPanel.canGoPrev(), invoke: () => selPanel.prevFeature() }, { bpIconName: "arrow-right", tooltip: xlate("SELECTION_NEXT_FEATURE", selPanel.locale), enabled: () => selPanel.canGoNext(), invoke: () => selPanel.nextFeature() }, { isSeparator: true }, { bpIconName: "path-search", tooltip: xlate("SELECTION_ZOOMTO_FEATURE", selPanel.locale), enabled: () => selPanel.canZoomSelectedFeature(), invoke: () => selPanel.zoomSelectedFeature() } ]; } const SELECTION_TOOLBAR_STYLE: React.CSSProperties = { float: "right", height: DEFAULT_TOOLBAR_SIZE }; const SELECTION_PANEL_TOOLBAR_STYLE: React.CSSProperties = { height: DEFAULT_TOOLBAR_SIZE, backgroundColor: TOOLBAR_BACKGROUND_COLOR }; const LAYER_COMBO_STYLE: React.CSSProperties = { float: "left", height: DEFAULT_TOOLBAR_SIZE }; const FloatClear = () => <div style={{ clear: "both" }} />; /** * Displays attributes of selected features with the ability to zoom in on selected features * @param props */ export const SelectionPanel = (props: ISelectionPanelProps) => { const { maxHeight, selection, selectedFeatureRenderer, allowHtmlValues, cleanHTML, onShowSelectedFeature, onRequestZoomToFeature } = props; const [selectedLayerIndex, setSelectedLayerIndex] = React.useState(-1); const [featureIndex, setFeatureIndex] = React.useState(-1); React.useEffect(() => { if (selection.getLayerCount() > 0) { if (selectedLayerIndex < 0) { setSelectedLayerIndex(0); setFeatureIndex(0); } else { const sl = selection.getLayerAt(selectedLayerIndex); if (!sl) { setSelectedLayerIndex(0); setFeatureIndex(0); } else { if (featureIndex < 0 && sl.getFeatureCount() > 0) { setFeatureIndex(0); } } } } }, [selection]); const getCurrentLayer = () => { return selection.getLayerAt(selectedLayerIndex); }; const getFeatureAt = (index: number) => { return selection.getFeatureAt(selectedLayerIndex, index); }; const getCurrentFeature = () => { return getFeatureAt(featureIndex); }; const canGoPrev = (): boolean => { return featureIndex > 0; }; const canGoNext = (): boolean => { const layer = getCurrentLayer(); if (layer != null) { return featureIndex + 1 < layer.getFeatureCount(); } return false; }; const canZoomSelectedFeature = (): boolean => { const feat = getCurrentFeature(); return feat?.Bounds != null; }; const prevFeature = () => { const newIndex = featureIndex - 1; setFeatureIndex(newIndex); const layer = getCurrentLayer(); if (layer) { const layerId = layer.getLayerId(); const sKey = getFeatureAt(newIndex)?.SelectionKey; if (sKey && layerId) { onShowSelectedFeature?.(layerId, sKey); } } }; const nextFeature = () => { const newIndex = featureIndex + 1; setFeatureIndex(newIndex); const layer = getCurrentLayer(); if (layer) { const layerId = layer.getLayerId(); const sKey = getFeatureAt(newIndex)?.SelectionKey; if (sKey && layerId) { onShowSelectedFeature?.(layerId, sKey); } } }; const zoomSelectedFeature = () => { const feat = getCurrentFeature(); if (feat) { onRequestZoomToFeature(feat); } }; const onSelectedLayerChanged = (e: GenericEvent) => { setSelectedLayerIndex(e.target.value); setFeatureIndex(0); }; const locale = props.locale || DEFAULT_LOCALE; let feat: SelectedFeature | undefined; let meta: LayerMetadata | undefined; if (selection != null && selectedLayerIndex >= 0 && featureIndex >= 0) { const selLayer = selection.getLayerAt(selectedLayerIndex); feat = selLayer?.getFeatureAt(featureIndex); meta = selLayer?.getLayerMetadata(); } let selBodyStyle: React.CSSProperties | undefined; if (maxHeight) { selBodyStyle = { overflowY: "auto", maxHeight: maxHeight - DEFAULT_TOOLBAR_SIZE }; } else { selBodyStyle = { overflow: "auto", position: "absolute", top: DEFAULT_TOOLBAR_SIZE, bottom: 0, right: 0, left: 0 } } return <div> {(() => { if (selection?.getLayerCount() > 0) { const selectionToolbarItems = buildToolbarItems({ locale, canGoPrev, canGoNext, prevFeature, nextFeature, canZoomSelectedFeature, zoomSelectedFeature }); return <div className="selection-panel-toolbar" style={SELECTION_PANEL_TOOLBAR_STYLE}> <div className="bp3-select selection-panel-layer-selector"> <HTMLSelect value={selectedLayerIndex} style={LAYER_COMBO_STYLE} onChange={onSelectedLayerChanged}> {selection.getLayers().map((layer, index) => { const lid = layer.getLayerId(); const lname = layer.getName(); const lkey = lid ?? index; const label = lid ? (props?.onResolveLayerLabel?.(lid, lname) ?? lname) : lname; return <option key={`selected-layer-${lkey}`} value={`${index}`}>{label}</option> })} </HTMLSelect> </div> <Toolbar childItems={selectionToolbarItems} containerStyle={SELECTION_TOOLBAR_STYLE} /> <FloatClear /> </div>; } })()} <div className="selection-panel-body" style={selBodyStyle}> {(() => { if (feat) { if (selectedFeatureRenderer) { return selectedFeatureRenderer({ selectedFeature: feat, cleanHTML: cleanHTML, allowHtmlValues: allowHtmlValues, selectedLayer: meta, locale: locale }); } else { return <DefaultSelectedFeature selectedFeature={feat} cleanHTML={cleanHTML} allowHtmlValues={allowHtmlValues} selectedLayer={meta} locale={locale} />; } } else if (!(selection?.getLayerCount() > 0)) { return <Callout intent={Intent.PRIMARY} icon="info-sign"> <p className="selection-panel-no-selection">{xlate("NO_SELECTED_FEATURES", locale)}</p> </Callout>; } })()} </div> </div>; }
the_stack
import React from "react" import { createResponsiveComponents } from "./DynamicResponsive" import { MediaQueries } from "./MediaQueries" import { intersection, propKey, createClassName, castBreakpointsToIntegers, } from "./Utils" import { BreakpointConstraint } from "./Breakpoints" /** * A render prop that can be used to render a different container element than * the default `div`. * * @see {@link MediaProps.children}. */ export type RenderProp = ( className: string, renderChildren: boolean ) => React.ReactNode // TODO: All of these props should be mutually exclusive. Using a union should // probably be made possible by https://github.com/Microsoft/TypeScript/pull/27408. export interface MediaBreakpointProps<BreakpointKey = string> { /** * Children will only be shown if the viewport matches the specified * breakpoint. That is, a viewport width that’s higher than the configured * breakpoint value, but lower than the value of the next breakpoint, if any * larger breakpoints exist at all. * * @example ```tsx // With breakpoints defined like these { xs: 0, sm: 768, md: 1024 } // Matches a viewport that has a width between 0 and 768 <Media at="xs">ohai</Media> // Matches a viewport that has a width between 768 and 1024 <Media at="sm">ohai</Media> // Matches a viewport that has a width over 1024 <Media at="md">ohai</Media> ``` * */ at?: BreakpointKey /** * Children will only be shown if the viewport is smaller than the specified * breakpoint. * * @example ```tsx // With breakpoints defined like these { xs: 0, sm: 768, md: 1024 } // Matches a viewport that has a width from 0 to 767 <Media lessThan="sm">ohai</Media> // Matches a viewport that has a width from 0 to 1023 <Media lessThan="md">ohai</Media> ``` * */ lessThan?: BreakpointKey /** * Children will only be shown if the viewport is greater than the specified * breakpoint. * * @example ```tsx // With breakpoints defined like these { xs: 0, sm: 768, md: 1024 } // Matches a viewport that has a width from 768 to infinity <Media greaterThan="xs">ohai</Media> // Matches a viewport that has a width from 1024 to infinity <Media greaterThan="sm">ohai</Media> ``` * */ greaterThan?: BreakpointKey /** * Children will only be shown if the viewport is greater or equal to the * specified breakpoint. * * @example ```tsx // With breakpoints defined like these { xs: 0, sm: 768, md: 1024 } // Matches a viewport that has a width from 0 to infinity <Media greaterThanOrEqual="xs">ohai</Media> // Matches a viewport that has a width from 768 to infinity <Media greaterThanOrEqual="sm">ohai</Media> // Matches a viewport that has a width from 1024 to infinity <Media greaterThanOrEqual="md">ohai</Media> ``` * */ greaterThanOrEqual?: BreakpointKey /** * Children will only be shown if the viewport is between the specified * breakpoints. That is, a viewport width that’s higher than or equal to the * small breakpoint value, but lower than the value of the large breakpoint. * * @example ```tsx // With breakpoints defined like these { xs: 0, sm: 768, md: 1024 } // Matches a viewport that has a width from 0 to 767 <Media between={["xs", "sm"]}>ohai</Media> // Matches a viewport that has a width from 0 to 1023 <Media between={["xs", "md"]}>ohai</Media> ``` * */ between?: [BreakpointKey, BreakpointKey] } export interface MediaProps<BreakpointKey, Interaction> extends MediaBreakpointProps<BreakpointKey> { /** * Children will only be shown if the interaction query matches. * * @example ```tsx // With interactions defined like these { hover: "(hover: hover)" } // Matches an input device that is capable of hovering <Media interaction="hover">ohai</Media> ``` */ interaction?: Interaction /** * The component(s) that should conditionally be shown, depending on the media * query matching. * * In case a different element is preferred, a render prop can be provided * that receives the class-name it should use to have the media query styling * applied. * * Additionally, the render prop receives a boolean that indicates wether or * not its children should be rendered, which will be `false` if the media * query is not included in the `onlyMatch` list. Use this flag if your * component’s children may be expensive to render and you want to avoid any * unnecessary work. * (@see {@link MediaContextProviderProps.onlyMatch} for details) * * @example * ```tsx const Component = () => ( <Media greaterThan="xs"> {(className, renderChildren) => ( <span className={className}> {renderChildren && "ohai"} </span> )} </Media> ) ``` * */ children: React.ReactNode | RenderProp /** * Additional classNames to passed down and applied to Media container */ className?: string } export interface MediaContextProviderProps<M> { /** * This list of breakpoints and interactions can be used to limit the rendered * output to these. * * For instance, when a server knows for some user-agents that certain * breakpoints will never apply, omitting them altogether will lower the * rendered byte size. */ onlyMatch?: M[] /** * Disables usage of browser MediaQuery API to only render at the current * breakpoint. * * Use this with caution, as disabling this means React components for all * breakpoints will be mounted client-side and all associated life-cycle hooks * will be triggered, which could lead to unintended side-effects. */ disableDynamicMediaQueries?: boolean } export interface CreateMediaConfig { /** * The breakpoint definitions for your application. Width definitions should * start at 0. * * @see {@link createMedia} */ breakpoints: { [key: string]: number | string } /** * The interaction definitions for your application. */ interactions?: { [key: string]: string } } export interface CreateMediaResults<BreakpointKey, Interactions> { /** * The React component that you use throughout your application. * * @see {@link MediaBreakpointProps} */ Media: React.ComponentType<MediaProps<BreakpointKey, Interactions>> /** * The React Context provider component that you use to constrain rendering of * breakpoints to a set list and to enable client-side dynamic constraining. * * @see {@link MediaContextProviderProps} */ MediaContextProvider: React.ComponentType< MediaContextProviderProps<BreakpointKey | Interactions> > /** * Generates a set of CSS rules that you should include in your application’s * styling to enable the hiding behaviour of your `Media` component uses. */ createMediaStyle(breakpointKeys?: BreakpointConstraint[]): string /** * A list of your application’s breakpoints sorted from small to large. */ SortedBreakpoints: BreakpointKey[] /** * Creates a list of your application’s breakpoints that support the given * widths and everything in between. */ findBreakpointsForWidths( fromWidth: number, throughWidth: number ): BreakpointKey[] | undefined /** * Finds the breakpoint that matches the given width. */ findBreakpointAtWidth(width: number): BreakpointKey | undefined /** * Maps a list of values for various breakpoints to props that can be used * with the `Media` component. * * The values map to corresponding indices in the sorted breakpoints array. If * less values are specified than the number of breakpoints your application * has, the last value will be applied to all subsequent breakpoints. */ valuesWithBreakpointProps<SizeValue>( values: SizeValue[] ): Array<[SizeValue, MediaBreakpointProps<BreakpointKey>]> } /** * This is used to generate a Media component, its context provider, and CSS * rules based on your application’s breakpoints and interactions. * * Note that the interaction queries are entirely up to you to define and they * should be written in such a way that they match when you want the element to * be hidden. * * @example * ```tsx const MyAppMedia = createMedia({ breakpoints: { xs: 0, sm: 768, md: 900 lg: 1024, xl: 1192, }, interactions: { hover: `not all and (hover:hover)` }, }) export const Media = MyAppMedia.Media export const MediaContextProvider = MyAppMedia.MediaContextProvider export const createMediaStyle = MyAppMedia.createMediaStyle ``` * */ export function createMedia< MediaConfig extends CreateMediaConfig, BreakpointKey extends keyof MediaConfig["breakpoints"], Interaction extends keyof MediaConfig["interactions"] >(config: MediaConfig): CreateMediaResults<BreakpointKey, Interaction> { const breakpoints = castBreakpointsToIntegers(config.breakpoints) const mediaQueries = new MediaQueries<BreakpointKey>( breakpoints, config.interactions || {} ) const DynamicResponsive = createResponsiveComponents() const MediaContext = React.createContext< MediaContextProviderProps<BreakpointKey | Interaction> >({}) MediaContext.displayName = "Media.Context" const MediaParentContext = React.createContext<{ hasParentMedia: boolean breakpointProps: MediaBreakpointProps<BreakpointKey> }>({ hasParentMedia: false, breakpointProps: {} }) MediaContext.displayName = "MediaParent.Context" const MediaContextProvider: React.FunctionComponent< MediaContextProviderProps<BreakpointKey | Interaction> > = ({ disableDynamicMediaQueries, onlyMatch, children }) => { if (disableDynamicMediaQueries) { return ( <MediaContext.Provider value={{ onlyMatch, }} > {children} </MediaContext.Provider> ) } else { return ( <DynamicResponsive.Provider mediaQueries={mediaQueries.dynamicResponsiveMediaQueries} initialMatchingMediaQueries={intersection( mediaQueries.mediaQueryTypes, onlyMatch )} > <DynamicResponsive.Consumer> {matches => { const matchingMediaQueries = Object.keys(matches).filter( key => matches[key] ) return ( <MediaContext.Provider value={{ onlyMatch: intersection(matchingMediaQueries, onlyMatch), }} > {children} </MediaContext.Provider> ) }} </DynamicResponsive.Consumer> </DynamicResponsive.Provider> ) } } const Media = class extends React.Component< MediaProps<BreakpointKey, Interaction> > { constructor(props) { super(props) validateProps(props) } static defaultProps = { className: "", } static contextType = MediaParentContext render() { const props = this.props const { children, className: passedClassName, interaction, ...breakpointProps } = props return ( <MediaParentContext.Consumer> {mediaParentContext => { return ( <MediaParentContext.Provider value={{ hasParentMedia: true, breakpointProps }} > <MediaContext.Consumer> {({ onlyMatch } = {}) => { let className: string | null if (props.interaction) { className = createClassName( "interaction", props.interaction ) } else { if (props.at) { const largestBreakpoint = mediaQueries.breakpoints.largestBreakpoint if (props.at === largestBreakpoint) { // TODO: We should look into making React’s __DEV__ available // and have webpack completely compile these away. let ownerName = null try { const owner = (this as any)._reactInternalFiber ._debugOwner.type ownerName = owner.displayName || owner.name } catch (err) { // no-op } console.warn( "[@artsy/fresnel] " + "`at` is being used with the largest breakpoint. " + "Consider using `<Media greaterThanOrEqual=" + `"${largestBreakpoint}">\` to account for future ` + `breakpoint definitions outside of this range.${ ownerName ? ` It is being used in the ${ownerName} component.` : "" }` ) } } const type = propKey(breakpointProps) const breakpoint = breakpointProps[type]! className = createClassName(type, breakpoint) } const doesMatchParent = !mediaParentContext.hasParentMedia || intersection( mediaQueries.breakpoints.toVisibleAtBreakpointSet( mediaParentContext.breakpointProps ), mediaQueries.breakpoints.toVisibleAtBreakpointSet( breakpointProps ) ).length > 0 const renderChildren = doesMatchParent && (onlyMatch === undefined || mediaQueries.shouldRenderMediaQuery( { ...breakpointProps, interaction }, onlyMatch )) if (props.children instanceof Function) { return props.children(className, renderChildren) } else { return ( <div className={`fresnel-container ${className} ${passedClassName}`} suppressHydrationWarning={!renderChildren} > {renderChildren ? props.children : null} </div> ) } }} </MediaContext.Consumer> </MediaParentContext.Provider> ) }} </MediaParentContext.Consumer> ) } } return { Media, MediaContextProvider, createMediaStyle: mediaQueries.toStyle, SortedBreakpoints: [...mediaQueries.breakpoints.sortedBreakpoints], findBreakpointAtWidth: mediaQueries.breakpoints.findBreakpointAtWidth, findBreakpointsForWidths: mediaQueries.breakpoints.findBreakpointsForWidths, valuesWithBreakpointProps: mediaQueries.breakpoints.valuesWithBreakpointProps, } } const MutuallyExclusiveProps: string[] = MediaQueries.validKeys() function validateProps(props) { const selectedProps = Object.keys(props).filter(prop => MutuallyExclusiveProps.includes(prop) ) if (selectedProps.length < 1) { throw new Error(`1 of ${MutuallyExclusiveProps.join(", ")} is required.`) } else if (selectedProps.length > 1) { throw new Error( `Only 1 of ${selectedProps.join(", ")} is allowed at a time.` ) } }
the_stack
import * as AST from "./ast.js"; // eslint-disable-next-line no-duplicate-imports import type {Resource, Entry} from "./ast.js"; import { EOF, EOL, FluentParserStream } from "./stream.js"; import { ParseError } from "./errors.js"; const trailingWSRe = /[ \t\n\r]+$/; type ParseFn<T> = // eslint-disable-next-line @typescript-eslint/no-explicit-any (this: FluentParser, ps: FluentParserStream, ...args: Array<any>) => T; function withSpan<T extends AST.SyntaxNode>(fn: ParseFn<T>): ParseFn<T> { return function ( this: FluentParser, ps: FluentParserStream, ...args: Array<unknown> ): T { if (!this.withSpans) { return fn.call(this, ps, ...args); } const start = ps.index; const node = fn.call(this, ps, ...args); // Don't re-add the span if the node already has it. This may happen when // one decorated function calls another decorated function. if (node.span) { return node; } const end = ps.index; node.addSpan(start, end); return node; }; } export interface FluentParserOptions { withSpans?: boolean; } export class FluentParser { public withSpans: boolean; constructor({ withSpans = true }: FluentParserOptions = {}) { this.withSpans = withSpans; // Poor man's decorators. /* eslint-disable @typescript-eslint/unbound-method */ this.getComment = withSpan(this.getComment); this.getMessage = withSpan(this.getMessage); this.getTerm = withSpan(this.getTerm); this.getAttribute = withSpan(this.getAttribute); this.getIdentifier = withSpan(this.getIdentifier); this.getVariant = withSpan(this.getVariant); this.getNumber = withSpan(this.getNumber); this.getPattern = withSpan(this.getPattern); this.getTextElement = withSpan(this.getTextElement); this.getPlaceable = withSpan(this.getPlaceable); this.getExpression = withSpan(this.getExpression); this.getInlineExpression = withSpan(this.getInlineExpression); this.getCallArgument = withSpan(this.getCallArgument); this.getCallArguments = withSpan(this.getCallArguments); this.getString = withSpan(this.getString); this.getLiteral = withSpan(this.getLiteral); this.getComment = withSpan(this.getComment); /* eslint-enable @typescript-eslint/unbound-method */ } parse(source: string): Resource { const ps = new FluentParserStream(source); ps.skipBlankBlock(); const entries: Array<AST.Entry> = []; let lastComment: AST.Comment | null = null; while (ps.currentChar()) { const entry = this.getEntryOrJunk(ps); const blankLines = ps.skipBlankBlock(); // Regular Comments require special logic. Comments may be attached to // Messages or Terms if they are followed immediately by them. However // they should parse as standalone when they're followed by Junk. // Consequently, we only attach Comments once we know that the Message // or the Term parsed successfully. if (entry instanceof AST.Comment && blankLines.length === 0 && ps.currentChar()) { // Stash the comment and decide what to do with it in the next pass. lastComment = entry; continue; } if (lastComment) { if (entry instanceof AST.Message || entry instanceof AST.Term) { entry.comment = lastComment; if (this.withSpans) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion entry.span!.start = entry.comment.span!.start; } } else { entries.push(lastComment); } // In either case, the stashed comment has been dealt with; clear it. lastComment = null; } // No special logic for other types of entries. entries.push(entry); } const res = new AST.Resource(entries); if (this.withSpans) { res.addSpan(0, ps.index); } return res; } /* * Parse the first Message or Term in `source`. * * Skip all encountered comments and start parsing at the first Message or * Term start. Return Junk if the parsing is not successful. * * Preceding comments are ignored unless they contain syntax errors * themselves, in which case Junk for the invalid comment is returned. */ parseEntry(source: string): Entry { const ps = new FluentParserStream(source); ps.skipBlankBlock(); while (ps.currentChar() === "#") { const skipped = this.getEntryOrJunk(ps); if (skipped instanceof AST.Junk) { // Don't skip Junk comments. return skipped; } ps.skipBlankBlock(); } return this.getEntryOrJunk(ps); } getEntryOrJunk(ps: FluentParserStream): AST.Entry { const entryStartPos = ps.index; try { const entry = this.getEntry(ps); ps.expectLineEnd(); return entry; } catch (err) { if (!(err instanceof ParseError)) { throw err; } let errorIndex = ps.index; ps.skipToNextEntryStart(entryStartPos); const nextEntryStart = ps.index; if (nextEntryStart < errorIndex) { // The position of the error must be inside of the Junk's span. errorIndex = nextEntryStart; } // Create a Junk instance const slice = ps.string.substring(entryStartPos, nextEntryStart); const junk = new AST.Junk(slice); if (this.withSpans) { junk.addSpan(entryStartPos, nextEntryStart); } const annot = new AST.Annotation(err.code, err.args, err.message); annot.addSpan(errorIndex, errorIndex); junk.addAnnotation(annot); return junk; } } getEntry(ps: FluentParserStream): AST.Entry { if (ps.currentChar() === "#") { return this.getComment(ps); } if (ps.currentChar() === "-") { return this.getTerm(ps); } if (ps.isIdentifierStart()) { return this.getMessage(ps); } throw new ParseError("E0002"); } getComment(ps: FluentParserStream): AST.Comments { // 0 - comment // 1 - group comment // 2 - resource comment let level = -1; let content = ""; while (true) { let i = -1; while (ps.currentChar() === "#" && (i < (level === -1 ? 2 : level))) { ps.next(); i++; } if (level === -1) { level = i; } if (ps.currentChar() !== EOL) { ps.expectChar(" "); let ch; while ((ch = ps.takeChar(x => x !== EOL))) { content += ch; } } if (ps.isNextLineComment(level)) { content += ps.currentChar(); ps.next(); } else { break; } } let Comment; switch (level) { case 0: Comment = AST.Comment; break; case 1: Comment = AST.GroupComment; break; default: Comment = AST.ResourceComment; } return new Comment(content); } getMessage(ps: FluentParserStream): AST.Message { const id = this.getIdentifier(ps); ps.skipBlankInline(); ps.expectChar("="); const value = this.maybeGetPattern(ps); const attrs = this.getAttributes(ps); if (value === null && attrs.length === 0) { throw new ParseError("E0005", id.name); } return new AST.Message(id, value, attrs); } getTerm(ps: FluentParserStream): AST.Term { ps.expectChar("-"); const id = this.getIdentifier(ps); ps.skipBlankInline(); ps.expectChar("="); const value = this.maybeGetPattern(ps); if (value === null) { throw new ParseError("E0006", id.name); } const attrs = this.getAttributes(ps); return new AST.Term(id, value, attrs); } getAttribute(ps: FluentParserStream): AST.Attribute { ps.expectChar("."); const key = this.getIdentifier(ps); ps.skipBlankInline(); ps.expectChar("="); const value = this.maybeGetPattern(ps); if (value === null) { throw new ParseError("E0012"); } return new AST.Attribute(key, value); } getAttributes(ps: FluentParserStream): Array<AST.Attribute> { const attrs = []; ps.peekBlank(); while (ps.isAttributeStart()) { ps.skipToPeek(); const attr = this.getAttribute(ps); attrs.push(attr); ps.peekBlank(); } return attrs; } getIdentifier(ps: FluentParserStream): AST.Identifier { let name = ps.takeIDStart(); let ch; while ((ch = ps.takeIDChar())) { name += ch; } return new AST.Identifier(name); } getVariantKey(ps: FluentParserStream): AST.Identifier | AST.NumberLiteral { const ch = ps.currentChar(); if (ch === EOF) { throw new ParseError("E0013"); } const cc = ch.charCodeAt(0); if ((cc >= 48 && cc <= 57) || cc === 45) { // 0-9, - return this.getNumber(ps); } return this.getIdentifier(ps); } getVariant(ps: FluentParserStream, hasDefault: boolean = false): AST.Variant { let defaultIndex = false; if (ps.currentChar() === "*") { if (hasDefault) { throw new ParseError("E0015"); } ps.next(); defaultIndex = true; } ps.expectChar("["); ps.skipBlank(); const key = this.getVariantKey(ps); ps.skipBlank(); ps.expectChar("]"); const value = this.maybeGetPattern(ps); if (value === null) { throw new ParseError("E0012"); } return new AST.Variant(key, value, defaultIndex); } getVariants(ps: FluentParserStream): Array<AST.Variant> { const variants: Array<AST.Variant> = []; let hasDefault = false; ps.skipBlank(); while (ps.isVariantStart()) { const variant = this.getVariant(ps, hasDefault); if (variant.default) { hasDefault = true; } variants.push(variant); ps.expectLineEnd(); ps.skipBlank(); } if (variants.length === 0) { throw new ParseError("E0011"); } if (!hasDefault) { throw new ParseError("E0010"); } return variants; } getDigits(ps: FluentParserStream): string { let num = ""; let ch; while ((ch = ps.takeDigit())) { num += ch; } if (num.length === 0) { throw new ParseError("E0004", "0-9"); } return num; } getNumber(ps: FluentParserStream): AST.NumberLiteral { let value = ""; if (ps.currentChar() === "-") { ps.next(); value += `-${this.getDigits(ps)}`; } else { value += this.getDigits(ps); } if (ps.currentChar() === ".") { ps.next(); value += `.${this.getDigits(ps)}`; } return new AST.NumberLiteral(value); } // maybeGetPattern distinguishes between patterns which start on the same line // as the identifier (a.k.a. inline signleline patterns and inline multiline // patterns) and patterns which start on a new line (a.k.a. block multiline // patterns). The distinction is important for the dedentation logic: the // indent of the first line of a block pattern must be taken into account when // calculating the maximum common indent. maybeGetPattern(ps: FluentParserStream): AST.Pattern | null { ps.peekBlankInline(); if (ps.isValueStart()) { ps.skipToPeek(); return this.getPattern(ps, false); } ps.peekBlankBlock(); if (ps.isValueContinuation()) { ps.skipToPeek(); return this.getPattern(ps, true); } return null; } getPattern(ps: FluentParserStream, isBlock: boolean): AST.Pattern { const elements: Array<AST.PatternElement | Indent> = []; let commonIndentLength; if (isBlock) { // A block pattern is a pattern which starts on a new line. Store and // measure the indent of this first line for the dedentation logic. const blankStart = ps.index; const firstIndent = ps.skipBlankInline(); elements.push(this.getIndent(ps, firstIndent, blankStart)); commonIndentLength = firstIndent.length; } else { commonIndentLength = Infinity; } let ch; elements: while ((ch = ps.currentChar())) { switch (ch) { case EOL: { const blankStart = ps.index; const blankLines = ps.peekBlankBlock(); if (ps.isValueContinuation()) { ps.skipToPeek(); const indent = ps.skipBlankInline(); commonIndentLength = Math.min(commonIndentLength, indent.length); elements.push(this.getIndent(ps, blankLines + indent, blankStart)); continue elements; } // The end condition for getPattern's while loop is a newline // which is not followed by a valid pattern continuation. ps.resetPeek(); break elements; } case "{": elements.push(this.getPlaceable(ps)); continue elements; case "}": throw new ParseError("E0027"); default: elements.push(this.getTextElement(ps)); } } const dedented = this.dedent(elements, commonIndentLength); return new AST.Pattern(dedented); } // Create a token representing an indent. It's not part of the AST and it will // be trimmed and merged into adjacent TextElements, or turned into a new // TextElement, if it's surrounded by two Placeables. getIndent(ps: FluentParserStream, value: string, start: number): Indent { return new Indent(value, start, ps.index); } // Dedent a list of elements by removing the maximum common indent from the // beginning of text lines. The common indent is calculated in getPattern. dedent( elements: Array<AST.PatternElement | Indent>, commonIndent: number ): Array<AST.PatternElement> { const trimmed: Array<AST.PatternElement> = []; for (let element of elements) { if (element instanceof AST.Placeable) { trimmed.push(element); continue; } if (element instanceof Indent) { // Strip common indent. element.value = element.value.slice( 0, element.value.length - commonIndent); if (element.value.length === 0) { continue; } } let prev = trimmed[trimmed.length - 1]; if (prev && prev instanceof AST.TextElement) { // Join adjacent TextElements by replacing them with their sum. const sum = new AST.TextElement(prev.value + element.value); if (this.withSpans) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion sum.addSpan(prev.span!.start, element.span!.end); } trimmed[trimmed.length - 1] = sum; continue; } if (element instanceof Indent) { // If the indent hasn't been merged into a preceding TextElement, // convert it into a new TextElement. const textElement = new AST.TextElement(element.value); if (this.withSpans) { textElement.addSpan(element.span.start, element.span.end); } element = textElement; } trimmed.push(element); } // Trim trailing whitespace from the Pattern. const lastElement = trimmed[trimmed.length - 1]; if (lastElement instanceof AST.TextElement) { lastElement.value = lastElement.value.replace(trailingWSRe, ""); if (lastElement.value.length === 0) { trimmed.pop(); } } return trimmed; } getTextElement(ps: FluentParserStream): AST.TextElement { let buffer = ""; let ch; while ((ch = ps.currentChar())) { if (ch === "{" || ch === "}") { return new AST.TextElement(buffer); } if (ch === EOL) { return new AST.TextElement(buffer); } buffer += ch; ps.next(); } return new AST.TextElement(buffer); } getEscapeSequence(ps: FluentParserStream): string { const next = ps.currentChar(); switch (next) { case "\\": case "\"": ps.next(); return `\\${next}`; case "u": return this.getUnicodeEscapeSequence(ps, next, 4); case "U": return this.getUnicodeEscapeSequence(ps, next, 6); default: throw new ParseError("E0025", next); } } getUnicodeEscapeSequence( ps: FluentParserStream, u: string, digits: number ): string { ps.expectChar(u); let sequence = ""; for (let i = 0; i < digits; i++) { const ch = ps.takeHexDigit(); if (!ch) { throw new ParseError( "E0026", `\\${u}${sequence}${ps.currentChar()}`); } sequence += ch; } return `\\${u}${sequence}`; } getPlaceable(ps: FluentParserStream): AST.Placeable { ps.expectChar("{"); ps.skipBlank(); const expression = this.getExpression(ps); ps.expectChar("}"); return new AST.Placeable(expression); } getExpression(ps: FluentParserStream): AST.Expression | AST.Placeable { const selector = this.getInlineExpression(ps); ps.skipBlank(); if (ps.currentChar() === "-") { if (ps.peek() !== ">") { ps.resetPeek(); return selector; } // Validate selector expression according to // abstract.js in the Fluent specification if (selector instanceof AST.MessageReference) { if (selector.attribute === null) { throw new ParseError("E0016"); } else { throw new ParseError("E0018"); } } else if (selector instanceof AST.TermReference) { if (selector.attribute === null) { throw new ParseError("E0017"); } } else if (selector instanceof AST.Placeable) { throw new ParseError("E0029"); } ps.next(); ps.next(); ps.skipBlankInline(); ps.expectLineEnd(); const variants = this.getVariants(ps); return new AST.SelectExpression(selector, variants); } if (selector instanceof AST.TermReference && selector.attribute !== null) { throw new ParseError("E0019"); } return selector; } getInlineExpression( ps: FluentParserStream ): AST.InlineExpression | AST.Placeable { if (ps.currentChar() === "{") { return this.getPlaceable(ps); } if (ps.isNumberStart()) { return this.getNumber(ps); } if (ps.currentChar() === '"') { return this.getString(ps); } if (ps.currentChar() === "$") { ps.next(); const id = this.getIdentifier(ps); return new AST.VariableReference(id); } if (ps.currentChar() === "-") { ps.next(); const id = this.getIdentifier(ps); let attr; if (ps.currentChar() === ".") { ps.next(); attr = this.getIdentifier(ps); } let args; ps.peekBlank(); if (ps.currentPeek() === "(") { ps.skipToPeek(); args = this.getCallArguments(ps); } return new AST.TermReference(id, attr, args); } if (ps.isIdentifierStart()) { const id = this.getIdentifier(ps); ps.peekBlank(); if (ps.currentPeek() === "(") { // It's a Function. Ensure it's all upper-case. if (!/^[A-Z][A-Z0-9_-]*$/.test(id.name)) { throw new ParseError("E0008"); } ps.skipToPeek(); let args = this.getCallArguments(ps); return new AST.FunctionReference(id, args); } let attr; if (ps.currentChar() === ".") { ps.next(); attr = this.getIdentifier(ps); } return new AST.MessageReference(id, attr); } throw new ParseError("E0028"); } getCallArgument( ps: FluentParserStream ): AST.InlineExpression | AST.NamedArgument { const exp = this.getInlineExpression(ps); ps.skipBlank(); if (ps.currentChar() !== ":") { return exp; } if (exp instanceof AST.MessageReference && exp.attribute === null) { ps.next(); ps.skipBlank(); const value = this.getLiteral(ps); return new AST.NamedArgument(exp.id, value); } throw new ParseError("E0009"); } getCallArguments(ps: FluentParserStream): AST.CallArguments { const positional: Array<AST.InlineExpression> = []; const named: Array<AST.NamedArgument> = []; const argumentNames: Set<string> = new Set(); ps.expectChar("("); ps.skipBlank(); while (true) { if (ps.currentChar() === ")") { break; } const arg = this.getCallArgument(ps); if (arg instanceof AST.NamedArgument) { if (argumentNames.has(arg.name.name)) { throw new ParseError("E0022"); } named.push(arg); argumentNames.add(arg.name.name); } else if (argumentNames.size > 0) { throw new ParseError("E0021"); } else { positional.push(arg); } ps.skipBlank(); if (ps.currentChar() === ",") { ps.next(); ps.skipBlank(); continue; } break; } ps.expectChar(")"); return new AST.CallArguments(positional, named); } getString(ps: FluentParserStream): AST.StringLiteral { ps.expectChar("\""); let value = ""; let ch; while ((ch = ps.takeChar(x => x !== '"' && x !== EOL))) { if (ch === "\\") { value += this.getEscapeSequence(ps); } else { value += ch; } } if (ps.currentChar() === EOL) { throw new ParseError("E0020"); } ps.expectChar("\""); return new AST.StringLiteral(value); } getLiteral(ps: FluentParserStream): AST.Literal { if (ps.isNumberStart()) { return this.getNumber(ps); } if (ps.currentChar() === '"') { return this.getString(ps); } throw new ParseError("E0014"); } } class Indent { public type = "Indent"; public span: AST.Span; public value: string; constructor(value: string, start: number, end: number) { this.value = value; this.span = new AST.Span(start, end); } }
the_stack
import path from 'path' import fs from 'fs' import deepmerge from 'deepmerge' import { isBinaryFileSync } from 'isbinaryfile' import ejs from 'ejs' import { resolveFile, resolveFiles } from '../util/files' import { hasPlugin } from '../util/plugins' import consola from 'consola' import { ConfigTransform, stringifyJS, ConfigTransformOptions } from '@nodepack/config-transformer' import { mergeDeps } from '../util/mergeDeps' import { resolveModule } from '@nodepack/module' import { MigrationOperation, FileMiddleware, FilePostProcessor } from './MigrationOperation' import { NoticeType } from './Migrator' export interface SimpleFile { /** Folder including last slash. */ path: string /** File name without extension. */ name: string /** File extension without starting dot. */ ext: string } const isObject = val => val && typeof val === 'object' const mergeArrayWithDedupe = (a, b) => Array.from(new Set([...a, ...b])) export class MigrationOperationAPI { migrationOperation: MigrationOperation constructor (migrationOperation: MigrationOperation) { this.migrationOperation = migrationOperation } /** * Resolves the data when rendering templates. * * @private */ _resolveData (additionalData: any) { return Object.assign({ options: this.migrationOperation.options, rootOptions: this.migrationOperation.rootOptions, }, additionalData) } /** * Inject a file processing middleware. * * @private * @param middleware - A middleware function that receives the * virtual files tree object, and an ejs render function. Can be async. */ _injectFileMiddleware (middleware: FileMiddleware) { this.migrationOperation.fileMiddlewares.push(middleware) } /** * Plugin id. */ get pluginId () { return this.migrationOperation.migration.plugin.id } /** * Current working directory. */ get cwd () { return this.migrationOperation.cwd } /** * Resolve path in the project. * * @param filePath - Relative path from project root * @return The resolved absolute path. */ resolve (filePath: string) { return resolveFile(this.cwd, filePath) } /** * Check if the project has a plugin installed * @param id Plugin id */ hasPlugin (id: string) { return hasPlugin( id, this.migrationOperation.migrator.plugins, this.migrationOperation.pkg, ) } /** * Configure how config files are extracted. * * @param key - Config key in package.json (for example `'nodepack'` or `'babel'`) * @param options - Options */ addConfigTransform (key: string, options: ConfigTransformOptions) { const hasReserved = Object.keys(this.migrationOperation.reservedConfigTransforms).includes(key) if ( hasReserved || !options || !options.file ) { if (hasReserved) { consola.warn(`Reserved config transform '${key}'`) } return } this.migrationOperation.configTransforms[key] = new ConfigTransform(options) } /** * Extend the package.json of the project. * Nested fields are deep-merged unless `merge: false` is passed. * Also resolves dependency conflicts between plugins. * Tool configuration fields may be extracted into standalone files before * files are written to disk. * * @param fields - Fields to merge. * @param merge - Deep-merge nested fields. */ extendPackage<TFields = any> (fields: TFields | ((pkg: any) => TFields), merge = true) { const pkg = this.migrationOperation.pkg const toMerge = typeof fields === 'function' ? (fields as (pkg: any) => TFields)(pkg) : fields for (const key in toMerge) { const value: any = toMerge[key] const existing = pkg[key] if (isObject(value) && (key === 'dependencies' || key === 'devDependencies')) { // use special version resolution merge pkg[key] = mergeDeps( this.pluginId, existing || {}, value, this.migrationOperation.depSources, ) } else if (!(key in pkg)) { pkg[key] = value } else if (Array.isArray(value) && Array.isArray(existing)) { pkg[key] = mergeArrayWithDedupe(existing, value) } else if (isObject(value) && isObject(existing) && merge) { pkg[key] = deepmerge(existing, value, { arrayMerge: mergeArrayWithDedupe }) } else { pkg[key] = value } } } /** * Render template files into the virtual files tree object. * * @param source - * Can be one of: * - relative path to a directory; * - Object hash of { sourceTemplate: targetFile } mappings; * - a custom file middleware function. * @param additionalData - additional data available to templates. * @param ejsOptions - options for ejs. */ render<TSource = any> (source: string | TSource | FileMiddleware, additionalData: any = {}, ejsOptions: any = {}) { const baseDir = extractCallDir() if (typeof source === 'string') { let sourceBasePath = source as string sourceBasePath = path.resolve(baseDir, sourceBasePath) this._injectFileMiddleware(async (files) => { const data = this._resolveData(additionalData) const globby = require('globby') const _files = await globby(['**/*'], { cwd: sourceBasePath }) for (const rawPath of _files) { const targetPath = rawPath.split('/').map(filename => { // dotfiles are ignored when published to npm, therefore in templates // we need to use underscore instead (e.g. "_gitignore") if (filename.charAt(0) === '_' && filename.charAt(1) !== '_') { return `.${filename.slice(1)}` } if (filename.charAt(0) === '_' && filename.charAt(1) === '_') { return `${filename.slice(1)}` } return filename }).join('/') const sourcePath = path.resolve(sourceBasePath, rawPath) let content if (path.extname(sourcePath) !== '.ejs') { content = renderFile(sourcePath, data, ejsOptions) } else { content = fs.readFileSync(sourcePath, { encoding: 'utf8' }) } // only set file if it's not all whitespace, or is a Buffer (binary files) if (Buffer.isBuffer(content) || /[^\s]/.test(content)) { this.migrationOperation.writeFile(targetPath, content, files) } } }) } else if (isObject(source)) { const obj: any = source this._injectFileMiddleware(files => { const data = this._resolveData(additionalData) for (const targetPath in obj) { const sourcePath = path.resolve(baseDir, obj[targetPath]) const content = renderFile(sourcePath, data, ejsOptions) if (Buffer.isBuffer(content) || content.trim()) { this.migrationOperation.writeFile(targetPath, content, files) } } }) } else if (typeof source === 'function') { const fm = source as FileMiddleware this._injectFileMiddleware(fm) } } /** * Delete files from the virtual files tree object. Opposite of `render`. * * @param source - * Can be one of: * - relative path to a directory; * - Object hash of { sourceTemplate: targetFile } mappings; * - a custom file middleware function. */ unrender<TSource = any> (source: string | TSource | FileMiddleware) { const baseDir = extractCallDir() if (typeof source === 'string') { source = path.resolve(baseDir, source) this._injectFileMiddleware(async (files) => { const globby = require('globby') const _files = await globby(['**/*'], { cwd: source }) for (const rawPath of _files) { const targetPath = rawPath.split('/').map(filename => { // dotfiles are ignored when published to npm, therefore in templates // we need to use underscore instead (e.g. "_gitignore") if (filename.charAt(0) === '_' && filename.charAt(1) !== '_') { return `.${filename.slice(1)}` } if (filename.charAt(0) === '_' && filename.charAt(1) === '_') { return `${filename.slice(1)}` } return filename }).join('/') delete files[targetPath] } }) } else if (isObject(source)) { const obj: any = source this._injectFileMiddleware(files => { for (const targetPath in obj) { delete files[targetPath] } }) } else if (typeof source === 'function') { const fm = source as FileMiddleware this._injectFileMiddleware(fm) } } /** * Move files. * * @param from `globby` pattern. * @param to Name transform. */ move (from: string, to: (file: SimpleFile) => string) { this._injectFileMiddleware(async (files) => { const resolvedFiles = await resolveFiles(this.cwd, from) for (const file in resolvedFiles) { const ext = path.extname(file) const newFile = to({ path: path.dirname(file) + '/', name: path.basename(file, ext), ext: ext.substr(1), }) if (newFile !== file) { const f = files[newFile] = files[file] f.move(newFile) delete files[file] } } }) } /** * Modify a file. * * @param filePath Path of the file in the project. * @param cb File transform. */ modifyFile (filePath: string, cb: (content: string | Buffer) => string | Buffer | Promise<string | Buffer>) { this._injectFileMiddleware(async (files) => { const file = files[filePath] if (file) { file.source = await cb(file.source) } }) } /** * Push a file middleware that will be applied after all normal file * middelwares have been applied. */ postProcessFiles (cb: FilePostProcessor) { this.migrationOperation.postProcessFilesCbs.push(cb) } /** * convenience method for generating a js config file from json */ genJSConfig (value: any) { return `module.exports = ${stringifyJS(value)}` } /** * Displays a message for the user at the end of all migration operations. */ addNotice (message: string, type: NoticeType = 'info') { this.migrationOperation.migrator.notices.push({ pluginId: this.migrationOperation.migration.plugin.id, type, message, }) } /** * Called once after migration operation is completed. */ onComplete (cb: Function) { this.migrationOperation.completeCbs.push(cb) } } function extractCallDir () { // extract api.render() callsite file location using error stack const obj: any = {} Error.captureStackTrace(obj) const callSite = obj.stack.split('\n')[3] const fileName = callSite.match(/\s\((.*):\d+:\d+\)$/)[1] return path.dirname(fileName) } const replaceBlockRE = /<%# REPLACE %>([^]*?)<%# END_REPLACE %>/g function renderFile (name, data, ejsOptions) { if (isBinaryFileSync(name)) { return fs.readFileSync(name) // return buffer } const template = fs.readFileSync(name, 'utf-8') // custom template inheritance via yaml front matter. // --- // extend: 'source-file' // replace: !!js/regexp /some-regex/ // OR // replace: // - !!js/regexp /foo/ // - !!js/regexp /bar/ // --- const yaml = require('yaml-front-matter') const parsed = yaml.loadFront(template) const content = parsed.__content let finalTemplate = content.trim() + `\n` if (parsed.extend) { const extendPath = path.isAbsolute(parsed.extend) ? parsed.extend : resolveModule(parsed.extend, path.dirname(name)) finalTemplate = fs.readFileSync(extendPath, 'utf-8') if (parsed.replace) { if (Array.isArray(parsed.replace)) { const replaceMatch = content.match(replaceBlockRE) if (replaceMatch) { const replaces = replaceMatch.map(m => { return m.replace(replaceBlockRE, '$1').trim() }) parsed.replace.forEach((r, i) => { finalTemplate = finalTemplate.replace(r, replaces[i]) }) } } else { finalTemplate = finalTemplate.replace(parsed.replace, content.trim()) } } if (parsed.when) { finalTemplate = ( `<%_ if (${parsed.when}) { _%>` + finalTemplate + `<%_ } _%>` ) } } return ejs.render(finalTemplate, data, ejsOptions) }
the_stack
import { InspectorConsoleView } from "../../../src/extension/networkInspector/views/inspectorConsoleView"; import { OutputChannelLogger } from "../../../src/extension/log/OutputChannelLogger"; import { Response, Request } from "../../../src/extension/networkInspector/networkMessageData"; import { URL } from "url"; import * as assert from "assert"; import * as querystring from "querystring"; suite("inspectorConsoleView", function () { suite("createNetworkRequestData", function () { const inspectorConsoleView = new InspectorConsoleView( OutputChannelLogger.getChannel("Network Inspector test"), ); test("should return network request data with text response body", () => { const request: Request = { headers: [ { key: "Accept-Encoding", value: "gzip" }, { key: "Connection", value: "Keep-Alive" }, ], id: "6826df34-173d-4351-a7e5-d435328f2e54", method: "GET", timestamp: 1617959200269, url: "https://test.org", }; const response: Response = { headers: [ { key: "Content-Encoding", value: "gzip" }, { key: "x-frame-options", value: "deny" }, ], data: "H4sIAAAAAAAA/ytJLS5RKEmtKDHkKoExjQB0Qz3xFQAAAA==", id: "6826df34-173d-4351-a7e5-d435328f2e54", index: 0, isMock: false, status: 200, timestamp: 1617959201269, totalChunks: 1, reason: "", }; const url = new URL(request.url); const networkRequestDataReference = { title: `%cNetwork request: ${request.method} ${ url ? url.host + url.pathname : "<unknown>" }`, networkRequestData: { URL: request.url, Method: request.method, Status: response.status, Duration: "1000ms", "Request Headers": { "Accept-Encoding": "gzip", Connection: "Keep-Alive", }, "Response Headers": { "Content-Encoding": "gzip", "x-frame-options": "deny", }, "Request Body": "", "Response Body": "test text1\ntest text2", }, }; const networkRequestData = (<any>inspectorConsoleView).createNetworkRequestData( request, response, ); assert.deepStrictEqual(networkRequestData, networkRequestDataReference); }); test("should return network request data with JSON response body", () => { const request: Request = { headers: [ { key: "Accept-Encoding", value: "gzip" }, { key: "Connection", value: "Keep-Alive" }, { key: "Content-Type", value: "application/json;charset=utf-8" }, ], data: "eyJ0ZXN0U3RyIjoidGVzdCIsInRlc3RPYmoiOnsidGVzdE51bSI6MTMyNCwidGVzdFN0cjEiOiJ0\nZXN0MSJ9fQ==\n", id: "6826df34-173d-4351-a7e5-d435328f2e54", method: "POST", timestamp: 1617959200269, url: "https://test.org", }; const response: Response = { headers: [ { key: "server", value: "nginx" }, { key: "x-frame-options", value: "deny" }, { key: "content-type", value: "application/json; charset=utf-8" }, ], data: "eyJzdWNjZXNzIjp0cnVlfQ==\n", id: "6826df34-173d-4351-a7e5-d435328f2e54", index: 0, isMock: false, status: 200, timestamp: 1617959201269, totalChunks: 1, reason: "", }; const url = new URL(request.url); const networkRequestDataReference = { title: `%cNetwork request: ${request.method} ${ url ? url.host + url.pathname : "<unknown>" }`, networkRequestData: { URL: request.url, Method: request.method, Status: response.status, Duration: "1000ms", "Request Headers": { "Accept-Encoding": "gzip", Connection: "Keep-Alive", "Content-Type": "application/json;charset=utf-8", }, "Response Headers": { server: "nginx", "x-frame-options": "deny", "content-type": "application/json; charset=utf-8", }, "Request Body": { testStr: "test", testObj: { testNum: 1324, testStr1: "test1" }, }, "Response Body": { success: true }, }, }; const networkRequestData = (<any>inspectorConsoleView).createNetworkRequestData( request, response, ); assert.deepStrictEqual(networkRequestData, networkRequestDataReference); }); test("should correctly process a graphQL request", () => { const request: Request = { headers: [ { key: "Accept-Encoding", value: "gzip" }, { key: "Connection", value: "Keep-Alive" }, { key: "Content-Type", value: "application/json;charset=utf-8" }, ], data: "eyJxdWVyeSI6Ilxue1xucmF0ZXMoY3VycmVuY3k6IFwiVVNEXCIpIHtcbmN1cnJlbmN5XG5yYXRlXG59XG59XG4ifQ==", id: "6826df34-173d-4351-a7e5-d435328f2e54", method: "POST", timestamp: 1617959200269, url: "https://test.org", }; const response: Response = { headers: [ { key: "content-encoding", value: "gzip" }, { key: "server", value: "cloudflare" }, { key: "content-type", value: "application/json;charset=utf-8" }, ], data: "H4sIAAAAAAAA/6tWSkksSVSyqlYqSixJLVayiq5WSi4tKkrNS65UslJydHVR0gFLATnGembmxkq1sbW1AO2x5pE2AAAA\n", id: "6826df34-173d-4351-a7e5-d435328f2e54", index: 0, isMock: false, status: 200, timestamp: 1617959201269, totalChunks: 1, reason: "", }; const url = new URL(request.url); const networkRequestDataReference = { title: `%cNetwork request: ${request.method} ${ url ? url.host + url.pathname : "<unknown>" }`, networkRequestData: { URL: request.url, Method: request.method, Status: response.status, Duration: "1000ms", "Request Headers": { "Accept-Encoding": "gzip", Connection: "Keep-Alive", "Content-Type": "application/json;charset=utf-8", }, "Response Headers": { server: "cloudflare", "content-encoding": "gzip", "content-type": "application/json;charset=utf-8", }, "Request Body": { query: '\n{\nrates(currency: "USD") {\ncurrency\nrate\n}\n}\n', }, "Response Body": { data: { rates: [{ currency: "AED", rate: "3.673" }] } }, }, }; const networkRequestData = (<any>inspectorConsoleView).createNetworkRequestData( request, response, ); assert.deepStrictEqual(networkRequestData, networkRequestDataReference); }); test("should correctly process a request with URL search parameters", () => { const request: Request = { headers: [ { key: "Accept-Encoding", value: "gzip" }, { key: "Connection", value: "Keep-Alive" }, ], id: "6826df34-173d-4351-a7e5-d435328f2e54", method: "GET", timestamp: 1617959200269, url: "https://test.org?query=query%20aTest(%24arg1%3A%20String!)%20%7B%20test(who%3A%20%24arg1)%20%7D&operationName=aTest&variables=%7B%22arg1%22%3A%22me%22%7D", }; const response: Response = { headers: [ { key: "vary", value: "Accept-Encoding" }, { key: "content-type", value: "application/json;charset=utf-8" }, ], data: "eyJlcnJvciI6ICJ0ZXN0RXJyb3IifQ==", id: "6826df34-173d-4351-a7e5-d435328f2e54", index: 0, isMock: false, status: 400, timestamp: 1617959201269, totalChunks: 1, reason: "", }; const url = new URL(request.url); const networkRequestDataReference = { title: `%cNetwork request: ${request.method} ${ url ? url.host + url.pathname : "<unknown>" }`, networkRequestData: { URL: request.url, Method: request.method, Status: response.status, Duration: "1000ms", "Request Headers": { "Accept-Encoding": "gzip", Connection: "Keep-Alive", }, "Response Headers": { vary: "Accept-Encoding", "content-type": "application/json;charset=utf-8", }, "Request Body": "", "Request Query Parameters": { operationName: "aTest", query: "query aTest($arg1: String!) { test(who: $arg1) }", variables: '{"arg1":"me"}', }, "Response Body": { error: "testError" }, }, }; const networkRequestData = (<any>inspectorConsoleView).createNetworkRequestData( request, response, ); assert.deepStrictEqual(networkRequestData, networkRequestDataReference); }); test("should correctly process a request with form data", () => { const request: Request = { headers: [ { key: "Accept-Encoding", value: "gzip" }, { key: "Connection", value: "Keep-Alive" }, { key: "Content-Type", value: "application/x-www-form-urlencoded;charset=UTF-8", }, ], data: "dXNlck5hbWU9dGVzdE5hbWUmdGVzdFByb3A9dGVzdFByb3BWYWw=\n", id: "6826df34-173d-4351-a7e5-d435328f2e54", method: "POST", timestamp: 1617959200269, url: "https://test.org", }; const response: Response = { headers: [ { key: "server", value: "nginx" }, { key: "content-type", value: "application/json;charset=utf-8" }, ], data: "eyJzdWNjZXNzIjp0cnVlfQ==\n", id: "6826df34-173d-4351-a7e5-d435328f2e54", index: 0, isMock: false, status: 200, timestamp: 1617959201269, totalChunks: 1, reason: "", }; const url = new URL(request.url); const networkRequestDataReference = { title: `%cNetwork request: ${request.method} ${ url ? url.host + url.pathname : "<unknown>" }`, networkRequestData: { URL: request.url, Method: request.method, Status: response.status, Duration: "1000ms", "Request Headers": { "Accept-Encoding": "gzip", Connection: "Keep-Alive", "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", }, "Response Headers": { server: "nginx", "content-type": "application/json;charset=utf-8", }, "Request Body": querystring.parse("userName=testName&testProp=testPropVal"), "Response Body": { success: true }, }, }; const networkRequestData = (<any>inspectorConsoleView).createNetworkRequestData( request, response, ); assert.deepStrictEqual(networkRequestData, networkRequestDataReference); }); }); });
the_stack
import { Command, DOMSerializer, EditorState, EditorView, Fragment, MarkType, Node, NodeType, Plugin, PluginKey, ResolvedPos, Schema, Selection, Slice, Transaction, } from '@bangle.dev/pm'; import { findParentNode, findSelectedNodeOfType, safeInsert, } from './pm-utils-reexport'; export class GapCursorSelection extends Selection {} type PredicateFunction = (state: EditorState, view?: EditorView) => any; export function rafCommandExec(view: EditorView, command: Command) { requestAnimationFrame(() => { command(view.state, view.dispatch, view); }); } export function filter( predicates: PredicateFunction | PredicateFunction[], cmd?: Command, ): Command { return (state, dispatch, view) => { if (cmd == null) { return false; } if (!Array.isArray(predicates)) { predicates = [predicates]; } if (predicates.some((pred) => !pred(state, view))) { return false; } return cmd(state, dispatch, view) || false; }; } export function isMarkActiveInSelection( type: MarkType, ): (state: EditorState) => boolean { return (state) => { const { from, $from, to, empty } = state.selection; if (empty) { return Boolean(type.isInSet(state.tr.storedMarks || $from.marks())); } return Boolean(state.doc.rangeHasMark(from, to, type)); }; } export const validPos = (pos: number, doc: Node) => Number.isInteger(pos) && pos >= 0 && pos < doc.content.size; export const validListParent = ( type: NodeType, schemaNodes: Schema['nodes'], ) => { const { bulletList, orderedList } = schemaNodes; return [bulletList, orderedList].includes(type); }; // TODO document this, probably gets the attributes of the mark of the current selection export function getMarkAttrs(editorState: EditorState, type: MarkType) { const { from, to } = editorState.selection; let marks: Node['marks'] = []; editorState.doc.nodesBetween(from, to, (node) => { marks = [...marks, ...node.marks]; }); const mark = marks.find((markItem) => markItem.type.name === type.name); return mark ? mark.attrs : {}; } export function nodeIsActive( state: EditorState, type: NodeType, attrs: Node['attrs'] = {}, ) { const predicate = (node: Node) => node.type === type; const node = findSelectedNodeOfType(type)(state.selection) || findParentNode(predicate)(state.selection); if (!Object.keys(attrs).length || !node) { return !!node; } return node.node.hasMarkup(type, { ...node.node.attrs, ...attrs }); } // export function findChangedNodesFromTransaction(tr: Transaction) { // const nodes: Node[] = []; // const steps = tr.steps || []; // steps.forEach((step) => { // const { to, from, slice } = step; // const size = slice && slice.content ? slice.content.size : 0; // for (let i = from; i <= to + size; i++) { // if (i <= tr.doc.content.size) { // const topLevelNode = tr.doc.resolve(i).node(1); // if (topLevelNode && !nodes.find((n) => n === topLevelNode)) { // nodes.push(topLevelNode); // } // } // } // }); // return nodes; // } /** * from atlaskit * Returns false if node contains only empty inline nodes and hardBreaks. */ export function hasVisibleContent(node: Node) { const isInlineNodeHasVisibleContent = (inlineNode: Node) => { return inlineNode.isText ? !!inlineNode.textContent.trim() : inlineNode.type.name !== 'hardBreak'; }; if (node.isInline) { return isInlineNodeHasVisibleContent(node); } else if (node.isBlock && (node.isLeaf || node.isAtom)) { return true; } else if (!node.childCount) { return false; } for (let index = 0; index < node.childCount; index++) { const child = node.child(index); if (hasVisibleContent(child)) { return true; } } return false; } /** * * from atlaskit * Checks if a node has any content. Ignores node that only contain empty block nodes. */ export function isNodeEmpty(node: Node) { if (node && node.textContent) { return false; } if ( !node || !node.childCount || (node.childCount === 1 && isEmptyParagraph(node.firstChild!)) ) { return true; } const block: Node[] = []; const nonBlock: Node[] = []; node.forEach((child) => { child.isInline ? nonBlock.push(child) : block.push(child); }); return ( !nonBlock.length && !block.filter( (childNode) => (!!childNode.childCount && !( childNode.childCount === 1 && isEmptyParagraph(childNode.firstChild!) )) || childNode.isAtom, ).length ); } /** * Checks if a node looks like an empty document */ export function isEmptyDocument(node: Node) { const nodeChild = node.content.firstChild; if (node.childCount !== 1 || !nodeChild) { return false; } return ( nodeChild.type.name === 'paragraph' && !nodeChild.childCount && nodeChild.nodeSize === 2 && (!nodeChild.marks || nodeChild.marks.length === 0) ); } /* * from atlaskit * Checks if node is an empty paragraph. */ export function isEmptyParagraph(node: Node) { return ( !node || (node.type.name === 'paragraph' && !node.textContent && !node.childCount) ); } // from atlaskit // https://github.com/ProseMirror/prosemirror-commands/blob/master/bangle-play/commands.js#L90 // Keep going left up the tree, without going across isolating boundaries, until we // can go along the tree at that same level // // You can think of this as, if you could construct each document like we do in the tests, // return the position of the first ) backwards from the current selection. export function findCutBefore($pos: ResolvedPos) { // parent is non-isolating, so we can look across this boundary if (!$pos.parent.type.spec.isolating) { // search up the tree from the pos's *parent* for (let i = $pos.depth - 1; i >= 0; i--) { // starting from the inner most node's parent, find out // if we're not its first child if ($pos.index(i) > 0) { return $pos.doc.resolve($pos.before(i + 1)); } if ($pos.node(i).type.spec.isolating) { break; } } } return null; } export function isRangeOfType( doc: Node, $from: ResolvedPos, $to: ResolvedPos, nodeType: NodeType, ) { return ( getAncestorNodesBetween(doc, $from, $to).filter( (node) => node.type !== nodeType, ).length === 0 ); } /** * Returns all top-level ancestor-nodes between $from and $to */ export function getAncestorNodesBetween( doc: Node, $from: ResolvedPos, $to: ResolvedPos, ) { const nodes = []; const maxDepth = findAncestorPosition(doc, $from).depth; let current = doc.resolve($from.start(maxDepth)); while (current.pos <= $to.start($to.depth)) { const depth = Math.min(current.depth, maxDepth); const node = current.node(depth); if (node) { nodes.push(node); } if (depth === 0) { break; } let next = doc.resolve(current.after(depth)); if (next.start(depth) >= doc.nodeSize - 2) { break; } if (next.depth !== current.depth) { next = doc.resolve(next.pos + 2); } if (next.depth) { current = doc.resolve(next.start(next.depth)); } else { current = doc.resolve(next.end(next.depth)); } } return nodes; } /** * Traverse the document until an "ancestor" is found. Any nestable block can be an ancestor. */ export function findAncestorPosition(doc: Node, pos: ResolvedPos) { const nestableBlocks = ['blockquote', 'bulletList', 'orderedList']; if (pos.depth === 1) { return pos; } let node = pos.node(pos.depth); let newPos = pos; while (pos.depth >= 1) { pos = doc.resolve(pos.before(pos.depth)); node = pos.node(pos.depth); if (node && nestableBlocks.indexOf(node.type.name) !== -1) { newPos = pos; } } return newPos; } export const isEmptySelectionAtStart = (state: EditorState) => { const { empty, $from } = state.selection; return ( empty && ($from.parentOffset === 0 || state.selection instanceof GapCursorSelection) ); }; /** * Removes marks from nodes in the current selection that are not supported */ export const sanitiseSelectionMarksForWrapping = ( state: EditorState, newParentType: NodeType, ) => { let tr: Transaction | null = null; let { from, to } = state.tr.selection; state.doc.nodesBetween( from, to, (node, pos, parent) => { // If iterate over a node thats out of our defined range // We skip here but continue to iterate over its children. if (node.isText || pos < from || pos > to) { return true; } node.marks.forEach((mark) => { if ( !parent.type.allowsMarkType(mark.type) || (newParentType && !newParentType.allowsMarkType(mark.type)) ) { const filteredMarks = node.marks.filter((m) => m.type !== mark.type); const position = pos > 0 ? pos - 1 : 0; let targetNode = state.doc.nodeAt(position); // you cannot set markup for text node if (!targetNode || targetNode.isText) { return; } tr = (tr || state.tr).setNodeMarkup( position, undefined, node.attrs, filteredMarks, ); } }); }, from, ); return tr; }; // This will return (depth - 1) for root list parent of a list. export const getListLiftTarget = ( type: NodeType | null | undefined, schema: Schema, resPos: ResolvedPos, ): number => { let target = resPos.depth; const { bulletList, orderedList } = schema.nodes; let listItem = type; if (!listItem) { ({ listItem } = schema.nodes); } for (let i = resPos.depth; i > 0; i--) { const node = resPos.node(i); if (node.type === bulletList || node.type === orderedList) { target = i; } if ( node.type !== bulletList && node.type !== orderedList && node.type !== listItem ) { break; } } return target - 1; }; export function mapChildren<T>( node: Node | Fragment, callback: (child: Node, index: number, frag: Fragment) => T, ): T[] { const array = []; for (let i = 0; i < node.childCount; i++) { array.push( callback( node.child(i), i, node instanceof Fragment ? node : node.content, ), ); } return array; } export const isFirstChildOfParent = (state: EditorState): boolean => { const { $from } = state.selection; return $from.depth > 1 ? (state.selection instanceof GapCursorSelection && $from.parentOffset === 0) || $from.index($from.depth - 1) === 0 : true; }; type MapFragmentCallback = ( node: Node, parent: Node | undefined, index: number, ) => Node | Node[] | Fragment | null; export function mapSlice(slice: Slice, callback: MapFragmentCallback) { const fragment = mapFragment(slice.content, callback); return new Slice(fragment, slice.openStart, slice.openEnd); } export function mapFragment( content: Fragment, callback: MapFragmentCallback, parent?: Node, /*: ( node: Node, parent: Node | null, index: number, ) => Node | Node[] | Fragment | null,*/ ): Fragment { const children = []; for (let i = 0, size = content.childCount; i < size; i++) { const node = content.child(i); const transformed = node.isLeaf ? callback(node, parent, i) : callback( node.copy(mapFragment(node.content, callback, node)), parent, i, ); if (transformed) { if (transformed instanceof Fragment) { children.push(...getFragmentBackingArray(transformed)); } else if (Array.isArray(transformed)) { children.push(...transformed); } else { children.push(transformed); } } } return Fragment.fromArray(children); } export function getFragmentBackingArray(fragment: Fragment) { // @ts-ignore @types/prosemirror-model doesn't have Fragment.content return fragment.content; } /** * * @param {*} type The schema type of object to create * @param {*} placement The placement of the node - above or below * @param {*} nestable putting this true will create the * empty node at -1. Set this to true for nodes * which are nested, for example in: * `<ul> p1 <li> p2 <p>abc</p> p7 </li> p8 <ul>` * we want to insert empty `<li>` above, for which we * will insert it at pos p1 and not p2. If nested was false, * the function would hav inserted at p2. */ export function insertEmpty( type: NodeType, placement: 'above' | 'below' = 'above', nestable: boolean = false, attrs?: Node['attrs'], ): Command { const isAbove = placement === 'above'; const depth = nestable ? -1 : undefined; return (state, dispatch) => { const insertPos = isAbove ? state.selection.$from.before(depth) : state.selection.$from.after(depth); const nodeToInsert = type.createAndFill(attrs); const tr = state.tr; let newTr = safeInsert(nodeToInsert!, insertPos)(state.tr); if (tr === newTr) { return false; } if (dispatch) { dispatch(newTr.scrollIntoView()); } return true; }; } export function findFirstMarkPosition( mark: MarkType, doc: Node, from: number, to: number, ) { let markPos = { start: -1, end: -1 }; doc.nodesBetween(from, to, (node, pos) => { // stop recursing if result is found if (markPos.start > -1) { return false; } if (markPos.start === -1 && mark.isInSet(node.marks)) { markPos = { start: pos, end: pos + Math.max(node.textContent.length, 1), }; } }); return markPos; } /** * Creates a plugin which allows for saving of value * Helpful for use cases when you just want to store * a value in the state and the value will not change * over time. * * Good to know: you get the value by doing `key.getState(state)` */ export function valuePlugin<T>(key: PluginKey<T>, value: T): Plugin<T> { return new Plugin({ key, state: { init() { return value; }, apply(_, v) { return v; }, }, }); } export function toHTMLString(state: EditorState) { const div = document.createElement('div'); const fragment = DOMSerializer.fromSchema(state.schema).serializeFragment( state.doc.content, ); div.appendChild(fragment); return div.innerHTML; } export function extendDispatch( dispatch: ((tr: Transaction) => void) | undefined, tapTr: (tr: Transaction) => any, ): ((tr: Transaction) => void) | undefined { return ( dispatch && ((tr) => { if (tr.isGeneric) { tapTr(tr); } dispatch(tr); }) ); }
the_stack
import * as fs from "fs"; import { join } from "path"; import * as protobufjs from "protobufjs"; import * as yargs from "yargs"; function camelToLowerCamel(value: string) { return value.substr(0, 1).toLowerCase() + value.substr(1, value.length - 1); } const argv = yargs .option("protos", { required: true, description: "Source .proto files.", type: "array" }) .option("root-paths", { required: false, type: "array", default: ["."], description: "Paths from which to resolve proto imports." }) .option("service", { required: true, type: "string", description: "The name of the service to process." }) .option("output-path", { required: true, type: "string", description: "Output typescript file path." }) .option("root-name", { type: "string", required: true, description: "The name of the root object where protos live (e.g. rootName.MyProto)." }) .option("protos-import", { type: "string", required: true, description: "The import to use for the generated protobufs library (e.g. import protos from 'protosImport')." }).argv; protobufjs.Root.prototype.resolvePath = (_, fileName) => { for (const rootPath of argv["root-paths"]) { const path = join(rootPath, fileName); // tslint:disable-next-line: tsr-detect-non-literal-fs-filename if (fs.existsSync(path)) { return path; } } throw new Error( `Could not find proto import ${fileName} in roots: ${JSON.stringify(argv["root-paths"])}` ); }; protobufjs .load((argv.protos as string[]).map(protoPath => String(protoPath))) .then(root => { const processedRoot = processPackage(argv["root-name"], root); writeAllServices([processedRoot.name], processedRoot); }) // tslint:disable-next-line: no-console .catch(e => console.error(e)); // TODO: This produces broken results for nested messages/enums. We need to: // (a) fix isPackage (probably !isService && !isMessage && !isEnum) // (b) change the IPackage interface to allow messages/enums to be nested inside other messages const isPackage = (value: any) => !isService(value) && !isMessage(value) && !isEnum(value) && !isHttpRule(value); const isService = (value: any) => !!value.methods; const isMessage = (value: any) => !!value.fields; const isEnum = (value: any) => !!value.values; const isHttpRule = (value: any) => value.type === "HttpRule"; interface IPackage { name: string; subpackages: IPackage[]; services: IService[]; messages: IMessage[]; enums: IEnum[]; } interface IService { name: string; methods: Array<{ name: string; requestType: string; responseType: string; // TODO: Find out what these types actually are and replace "any" with that. requestStream: any; responseStream: any; }>; } interface IMessage { name: string; } interface IEnum { name: string; } function processPackage(name: string, root: any): IPackage { const processedPackage: IPackage = { name, subpackages: [], services: [], messages: [], enums: [] }; for (const key of Object.keys(root.nested)) { const value = root.nested[key]; if (isPackage(value)) { processedPackage.subpackages.push(processPackage(key, value)); } else if (isService(value)) { const methods = Object.keys(value.methods).map(methodName => { const method = value.methods[methodName]; return { name: methodName, requestType: method.requestType, responseType: method.responseType, requestStream: method.requestStream, responseStream: method.responseStream }; }); processedPackage.services.push({ name: key, methods }); } else if (isMessage(value)) { processedPackage.messages.push({ name: key }); } else if (isEnum(value)) { processedPackage.enums.push({ name: key }); } else if (isHttpRule(value)) { // These are for grpc-gateway and can be ignored. } else { throw new Error("Unrecognized entry in 'nested' property of protobufjs package:" + value); } } return processedPackage; } interface IFoundService { packageNameParts: string[]; processedPackage: IPackage; service: IService; } function writeAllServices(rootPackageNameParts: string[], rootPackage: IPackage) { const foundServices: IFoundService[] = []; const findPackages = (packageNameParts: string[], processedPackage: IPackage) => { return processedPackage.subpackages.forEach(subpackage => { subpackage.services.forEach(service => foundServices.push({ packageNameParts: [...packageNameParts, subpackage.name], service, processedPackage }) ); findPackages([].concat([...packageNameParts, subpackage.name]), subpackage); }); }; findPackages(rootPackageNameParts, rootPackage); const serviceToWrite = foundServices.find( service => fullyQualifyService(service) === argv.service ); if (!serviceToWrite) { throw new Error( `Could not find service named "${argv.service}" in services: [${foundServices .map(service => fullyQualifyService(service)) .join(", ")}]` ); } write( serviceToWrite.processedPackage, serviceToWrite.packageNameParts, serviceToWrite.service, argv["output-path"] ); } function write( currentPackage: IPackage, currentNamespaceParts: string[], service: IService, outputPath: string ) { // TODO: We should probably namespace the generated files inside the currentNamespaceParts fields. // tslint:disable-next-line: tsr-detect-non-literal-fs-filename fs.writeFileSync( outputPath, // tslint:disable-next-line: tsr-detect-sql-literal-injection `// GENERATED CODE. import * as grpc from "grpc"; import { promisify } from "util"; import * as protos from "${argv["protos-import"]}"; export const NAME = "${service.name}"; export interface IService { ${service.methods .map(method => { return ` ${camelToLowerCamel(method.name)}(call: grpc.ServerUnaryCall<${fullyQualify( currentNamespaceParts, method.requestType, true )}>): Promise<${fullyQualify(currentNamespaceParts, method.responseType, true)}>;`; }) .join("")} } export interface IGrpcMethodCallResults { timeNanos: number; err?: Error; } function computeElapsedNanosSince(hrtimeStart: [number, number]) { const delta = process.hrtime(hrtimeStart); return delta[0] * 1e9 + delta[1]; } class GrpcError extends Error { constructor(message: string, public readonly code: grpc.status) { super(message); } } export class ServicePromiseWrapper { private impl: IService; private afterInterceptor: (method: string, call: grpc.ServerUnaryCall<any>, grpcMethodCallResults: IGrpcMethodCallResults) => void; // Note that the 'any' typings here are required because we don't know the request type in advance (it depends on the API method which is called). constructor(impl: IService, afterInterceptor?: (method: string, call: grpc.ServerUnaryCall<any>, grpcMethodCallResults: IGrpcMethodCallResults) => void) { this.impl = impl; this.afterInterceptor = afterInterceptor || (() => undefined); } ${service.methods .map(method => { return ` public ${camelToLowerCamel(method.name)}(call: grpc.ServerUnaryCall<${fullyQualify( currentNamespaceParts, method.requestType, true )}>, callback: (err: any, response: ${fullyQualify( currentNamespaceParts, method.responseType, true )}) => void) { const asyncInner = async () => { const startTime = process.hrtime(); try { const response = await this.impl.${camelToLowerCamel(method.name)}(call); this.afterInterceptor("${method.name}", call, { timeNanos: computeElapsedNanosSince(startTime) }); callback(null, response); } catch (err) { this.afterInterceptor("${method.name}", call, { timeNanos: computeElapsedNanosSince(startTime), err }); callback(err, null); } }; // tslint:disable-next-line: no-console asyncInner().catch(e => console.log("Unhandled gRPC error!" + e.message)); } `; }) .join("")} } export class Client { private client: any; constructor(address: string, options?: object) { this.client = new grpc.Client(address, grpc.credentials.createInsecure(), options); } ${service.methods .map(method => { return ` public async ${camelToLowerCamel(method.name)}(request: ${fullyQualify( currentNamespaceParts, method.requestType, true )}, options?: grpc.CallOptions): Promise<${fullyQualify( currentNamespaceParts, method.responseType, false )}> { try { return await promisify(this.client.makeUnaryRequest.bind(this.client))( DEFINITION.${camelToLowerCamel(method.name)}.path, DEFINITION.${camelToLowerCamel(method.name)}.requestSerialize, DEFINITION.${camelToLowerCamel(method.name)}.responseDeserialize, request, new grpc.Metadata(), (options || {}) as any ); } catch (e) { throw new GrpcError(String(e), e.code); } } `; }) .join("")} } export const DEFINITION = { ${service.methods .map(method => { return ` ${camelToLowerCamel(method.name)}: { path: '/${currentNamespaceParts // We need to skip the first entry (argv["root-name"]), because it refers to protobuf type namespaces, not actual package names as specified in .proto files. .slice(1) .map(part => `${part}.`) .join("")}${service.name}/${method.name}', requestStream: ${!!method.requestStream}, responseStream: ${!!method.responseStream}, requestType: ${fullyQualify(currentNamespaceParts, method.requestType, false)}, responseType: ${fullyQualify(currentNamespaceParts, method.responseType, false)}, requestSerialize: (v: ${fullyQualify( currentNamespaceParts, method.requestType, true )}) => Buffer.from(${fullyQualify( currentNamespaceParts, method.requestType, false )}.encode(v).finish()), requestDeserialize: (v: Buffer) => ${fullyQualify( currentNamespaceParts, method.requestType, false )}.decode(new Uint8Array(v)), responseSerialize: (v: ${fullyQualify( currentNamespaceParts, method.responseType, true )}) => Buffer.from(${fullyQualify( currentNamespaceParts, method.responseType, false )}.encode(v).finish()), responseDeserialize: (v: Buffer) => ${fullyQualify( currentNamespaceParts, method.responseType, false )}.decode(new Uint8Array(v)), }`; }) .join(",")} } // TODO: Delete this, it's only intended temporarily, for rolling out the above (fixed) service definition. export const UNNAMESPACED_SERVICE_DEFINITION = { ${service.methods .map(method => { return ` ${camelToLowerCamel(method.name)}: { path: '/${service.name}/${method.name}', requestStream: ${!!method.requestStream}, responseStream: ${!!method.responseStream}, requestType: ${fullyQualify(currentNamespaceParts, method.requestType, false)}, responseType: ${fullyQualify(currentNamespaceParts, method.responseType, false)}, requestSerialize: (v: ${fullyQualify( currentNamespaceParts, method.requestType, true )}) => Buffer.from(${fullyQualify( currentNamespaceParts, method.requestType, false )}.encode(v).finish()), requestDeserialize: (v: Buffer) => ${fullyQualify( currentNamespaceParts, method.requestType, false )}.decode(new Uint8Array(v)), responseSerialize: (v: ${fullyQualify( currentNamespaceParts, method.responseType, true )}) => Buffer.from(${fullyQualify( currentNamespaceParts, method.responseType, false )}.encode(v).finish()), responseDeserialize: (v: Buffer) => ${fullyQualify( currentNamespaceParts, method.responseType, false )}.decode(new Uint8Array(v)), }`; }) .join(",")} } ` ); } function fullyQualifyService(foundService: IFoundService) { return `${foundService.packageNameParts .slice(1) .map(part => `${part}.`) .join("")}${foundService.service.name}`; } function fullyQualify(currentNamespaceParts: string[], type: string, asInterface: boolean) { const fullPackageString = determinePackagePath(currentNamespaceParts, type).join("."); const typeWithoutPackage = type.split(".").slice(-1)[0]; const iTypeString = `${asInterface ? "I" : ""}${typeWithoutPackage}`; return `${fullPackageString}.${iTypeString}`; } function determinePackagePath(currentNamespaceParts: string[], type: string) { const typeParts = type.split("."); if (typeParts.length > 1) { // This type is already package-qualified, thus it must live outside of the current package, // and we can just use the value more or less as-is. return [].concat([argv["root-name"]], typeParts.slice(0, -1)); } // The type is un-namespaced. Thus it must be in the current package. return currentNamespaceParts; }
the_stack
import {TaskTestData} from "models/pipeline_configs/spec/test_data"; import { AbstractTask, AntTaskAttributes, ExecTask, NantTaskAttributes, RakeTaskAttributes, Task } from "models/pipeline_configs/task"; import {PluginInfo, PluginInfos} from "models/shared/plugin_infos_new/plugin_info"; import {TaskPluginInfo} from "models/shared/plugin_infos_new/spec/test_data"; describe("Task", () => { describe("Exec", () => { it("validates attributes", () => { const t: Task = new ExecTask("", []); expect(t.isValid()).toBe(false); expect(t.attributes().errors().count()).toBe(1); expect(t.attributes().errors().keys()).toEqual(["command"]); expect(t.attributes().errors().errorsForDisplay("command")).toBe("Command must be present."); expect(new ExecTask("ls", ["-lA"]).isValid()); }); it("adopts errors in server response", () => { const task = new ExecTask("whoami", []); const unmatched = task.consumeErrorsResponse({ errors: { command: ["who are you?"], not_exist: ["well, ain't that a doozy"] } }); expect(unmatched.hasErrors()).toBe(true); expect(unmatched.errorsForDisplay("execTask.notExist")).toBe("well, ain't that a doozy."); expect(task.attributes().errors().errorsForDisplay("command")).toBe("who are you?."); }); it("serializes", () => { expect(new ExecTask("ls", ["-la"]).toJSON()).toEqual({ type: "exec", attributes: { command: "ls", arguments: ["-la"], run_if: [] } }); }); it("serializes when args is specified", () => { expect(new ExecTask("ls", [], "-al").toJSON()).toEqual({ type: "exec", attributes: { command: "ls", args: "-al", run_if: [] } }); }); it("should provide description", () => { const task = new ExecTask("", []); expect(task.description(new PluginInfos())).toEqual("Custom Command"); }); it("should provide properties", () => { const task = new ExecTask("ls", ["-a", "-h", "-l"], undefined, "/tmp"); expect(task.attributes().properties()).toEqual(new Map([ ["Command", "ls"], ["Arguments", "-a -h -l"], ["Working Directory", "/tmp"] ])); }); it("should provide properties when argument is specified", () => { const task = new ExecTask("ls", [], "-alh", "/tmp"); expect(task.attributes().properties()).toEqual(new Map([ ["Command", "ls"], ["Arguments", "-alh"], ["Working Directory", "/tmp"] ])); }); }); describe("Ant", () => { it("should deserialize from json", () => { const task = AbstractTask.fromJSON(TaskTestData.ant().toJSON()); expect(task.type).toBe("ant"); const attributes = task.attributes() as AntTaskAttributes; expect(attributes.buildFile()).toEqual("ant-build-file"); expect(attributes.target()).toEqual("target"); expect(attributes.workingDirectory()).toEqual("/tmp"); expect(attributes.onCancel()!.type).toEqual("exec"); expect(attributes.runIf()).toEqual(["any"]); }); it("should provide properties", () => { const task = AbstractTask.fromJSON(TaskTestData.ant().toJSON()); expect(task.attributes().properties()).toEqual(new Map([ ["Build File", "ant-build-file"], ["Target", "target"], ["Working Directory", "/tmp"] ])); }); it("should provide api payload", () => { const task = AbstractTask.fromJSON(TaskTestData.ant().toJSON()); const expected = { run_if: ["any"], on_cancel: { type: "exec", attributes: { run_if: ["passed"], working_directory: "/tmp", command: "ls", arguments: [] } }, build_file: "ant-build-file", target: "target", working_directory: "/tmp" }; expect(task.attributes().toApiPayload()).toEqual(expected); }); it("should provide description", () => { const task = TaskTestData.ant(); expect(task.description(new PluginInfos())).toEqual("Ant"); }); }); describe("NAnt", () => { it("should deserialize from json", () => { const task = AbstractTask.fromJSON(TaskTestData.nant().toJSON()); expect(task.type).toBe("nant"); const attributes = task.attributes() as NantTaskAttributes; expect(attributes.buildFile()).toEqual("nant-build-file"); expect(attributes.nantPath()).toEqual("path-to-nant-exec"); expect(attributes.target()).toEqual("target"); expect(attributes.workingDirectory()).toEqual("/tmp"); expect(attributes.onCancel()!.type).toEqual("exec"); expect(attributes.runIf()).toEqual(["any"]); }); it("should provide properties", () => { const task = AbstractTask.fromJSON(TaskTestData.nant().toJSON()); expect(task.attributes().properties()).toEqual(new Map([ ["Build File", "nant-build-file"], ["Target", "target"], ["Working Directory", "/tmp"], ["Nant Path", "path-to-nant-exec"] ])); }); it("should provide api payload", () => { const task = AbstractTask.fromJSON(TaskTestData.nant().toJSON()); const expected = { run_if: ["any"], on_cancel: { type: "exec", attributes: { run_if: ["passed"], working_directory: "/tmp", command: "ls", arguments: [] } }, nant_path: "path-to-nant-exec", build_file: "nant-build-file", target: "target", working_directory: "/tmp" }; expect(task.attributes().toApiPayload()).toEqual(expected); }); it("should provide description", () => { const task = TaskTestData.nant(); expect(task.description(new PluginInfos())).toEqual("NAnt"); }); }); describe("Rake", () => { it("should deserialize from json", () => { const task = AbstractTask.fromJSON(TaskTestData.rake().toJSON()); expect(task.type).toBe("rake"); const attributes = task.attributes() as RakeTaskAttributes; expect(attributes.buildFile()).toEqual("rake-build-file"); expect(attributes.target()).toEqual("target"); expect(attributes.workingDirectory()).toEqual("/tmp"); expect(attributes.onCancel()!.type).toEqual("exec"); expect(attributes.runIf()).toEqual(["any"]); }); it("should provide properties", () => { const task = AbstractTask.fromJSON(TaskTestData.rake().toJSON()); expect(task.attributes().properties()).toEqual(new Map([ ["Build File", "rake-build-file"], ["Target", "target"], ["Working Directory", "/tmp"] ])); }); it("should provide api payload", () => { const task = AbstractTask.fromJSON(TaskTestData.rake().toJSON()); const expected = { run_if: ["any"], on_cancel: { type: "exec", attributes: { run_if: ["passed"], working_directory: "/tmp", command: "ls", arguments: [] } }, build_file: "rake-build-file", target: "target", working_directory: "/tmp" }; expect(task.attributes().toApiPayload()).toEqual(expected); }); it("should provide description", () => { const task = TaskTestData.rake(); expect(task.description(new PluginInfos())).toEqual("Rake"); }); }); describe("Fetch Artifact", () => { it("should deserialize from JSON", () => { const task = TaskTestData.fetchGoCDTask(); const copy = AbstractTask.fromJSON(task.toJSON()); expect(task.toJSON()).toEqual(copy.toJSON()); }); it("should provide properties for gocd artifact", () => { const task = TaskTestData.fetchGoCDTask(); expect(task.attributes().properties()).toEqual(new Map([ ["Pipeline Name", "pipeline"], ["Stage Name", "stage"], ["Job Name", "job"], ["Source", "source-file"], ["Destination", "destination-file"] ])); }); it("should provide properties for external artifact", () => { const task = TaskTestData.fetchExternalTask(); expect(task.attributes().properties()).toEqual(new Map([ ["Pipeline Name", "pipeline"], ["Stage Name", "stage"], ["Job Name", "job"] ])); }); it("should provide description for GoCD Artifact", () => { const task = TaskTestData.fetchGoCDTask(); expect(task.description(new PluginInfos())).toEqual("Fetch Artifact"); }); it("should provide description for external Artifact", () => { const task = TaskTestData.fetchExternalTask(); expect(task.description(new PluginInfos())).toEqual("Fetch Artifact"); }); }); describe("Pluggable Artifact", () => { it("should deserialize from JSON", () => { const task = TaskTestData.pluggableTask(); const copy = AbstractTask.fromJSON(task.toJSON()); expect(task.toJSON()).toEqual(copy.toJSON()); }); it("should provide properties for pluggable task", () => { const task = TaskTestData.pluggableTask(); expect(task.attributes().properties()).toEqual(new Map([ ["username", "bob"], ["password", "********************************"], ])); }); it("should provide description", () => { const task = TaskTestData.pluggableTask(); const data = TaskPluginInfo.scriptExecutor(); const pluginInfos = new PluginInfos(PluginInfo.fromJSON(data)); expect(task.description(pluginInfos)).toEqual("Script Executor"); }); }); });
the_stack
import bigInteger from "big-integer"; import { Int } from "./int"; import { CoinUtils } from "./coin-utils"; import { exponentDecStringToDecString, isExponentDecString, isValidDecimalString, } from "./etc"; export class Dec { public static readonly precision = 18; // Bytes required to represent the above precision is 18. // Ceiling[Log2[999 999 999 999 999 999]] protected static readonly decimalPrecisionBits = 60; // Max bit length for `Dec` is 256 + 60(decimalPrecisionBits) // The int in the `Dec` is handled as integer assuming that it has 18 precision. // (2 ** (256 + 60) - 1) protected static readonly maxDec = bigInteger( "133499189745056880149688856635597007162669032647290798121690100488888732861290034376435130433535" ); protected static readonly precisionMultipliers: { [key: string]: bigInteger.BigInteger | undefined; } = {}; protected static calcPrecisionMultiplier( prec: number ): bigInteger.BigInteger { if (prec < 0) { throw new Error("Invalid prec"); } if (prec > Dec.precision) { throw new Error("Too much precision"); } if (Dec.precisionMultipliers[prec.toString()]) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return Dec.precisionMultipliers[prec.toString()]!; } const zerosToAdd = Dec.precision - prec; const multiplier = bigInteger(10).pow(zerosToAdd); Dec.precisionMultipliers[prec.toString()] = multiplier; return multiplier; } protected static reduceDecimalsFromString( str: string ): { res: string; isDownToZero: boolean } { const decimalPointIndex = str.indexOf("."); if (decimalPointIndex < 0) { return { res: str, isDownToZero: false, }; } const exceededDecimals = str.length - 1 - decimalPointIndex - Dec.precision; if (exceededDecimals <= 0) { return { res: str, isDownToZero: false, }; } const res = str.slice(0, str.length - exceededDecimals); return { res, isDownToZero: /^[0.]*$/.test(res), }; } protected int: bigInteger.BigInteger; /** * Create a new Dec from integer with decimal place at prec * @param int - Parse a number | bigInteger | string into a Dec. * If int is string and contains dot(.), prec is ignored and automatically calculated. * @param prec - Precision */ constructor(int: bigInteger.BigNumber | Int, prec: number = 0) { if (typeof int === "number") { int = int.toString(); } if (typeof int === "string") { if (int.length === 0) { throw new Error("empty string"); } if (!isValidDecimalString(int)) { if (isExponentDecString(int)) { int = exponentDecStringToDecString(int); } else { throw new Error(`invalid decimal: ${int}`); } } // Even if an input with more than 18 decimals, it does not throw an error and ignores the rest. const reduced = Dec.reduceDecimalsFromString(int); if (reduced.isDownToZero) { // However, as a result, if the input becomes 0, a problem may occur in mul or quo. In this case, print a warning. console.log( `WARNING: Got ${int}. Dec can only handle up to 18 decimals. However, since the decimal point of the input exceeds 18 digits, the remainder is discarded. As a result, input becomes 0.` ); } int = reduced.res; if (int.indexOf(".") >= 0) { prec = int.length - int.indexOf(".") - 1; int = int.replace(".", ""); } this.int = bigInteger(int); } else if (int instanceof Int) { this.int = bigInteger(int.toString()); } else if (typeof int === "bigint") { this.int = bigInteger(int); } else { this.int = bigInteger(int); } this.int = this.int.multiply(Dec.calcPrecisionMultiplier(prec)); this.checkBitLen(); } protected checkBitLen(): void { if (this.int.abs().gt(Dec.maxDec)) { throw new Error(`Integer out of range ${this.int.toString()}`); } } public isZero(): boolean { return this.int.eq(bigInteger(0)); } public isNegative(): boolean { return this.int.isNegative(); } public isPositive(): boolean { return this.int.isPositive(); } public equals(d2: Dec): boolean { return this.int.eq(d2.int); } /** * Alias for the greater method. */ public gt(d2: Dec): boolean { return this.int.gt(d2.int); } /** * Alias for the greaterOrEquals method. */ public gte(d2: Dec): boolean { return this.int.geq(d2.int); } /** * Alias for the lesser method. */ public lt(d2: Dec): boolean { return this.int.lt(d2.int); } /** * Alias for the lesserOrEquals method. */ public lte(d2: Dec): boolean { return this.int.leq(d2.int); } /** * reverse the decimal sign. */ public neg(): Dec { return new Dec(this.int.negate(), Dec.precision); } /** * Returns the absolute value of a decimals. */ public abs(): Dec { return new Dec(this.int.abs(), Dec.precision); } public add(d2: Dec): Dec { return new Dec(this.int.add(d2.int), Dec.precision); } public sub(d2: Dec): Dec { return new Dec(this.int.subtract(d2.int), Dec.precision); } public pow(n: Int): Dec { if (n.isZero()) { return new Dec(1); } if (n.isNegative()) { return new Dec(1).quo(this.pow(n.abs())); } let base = new Dec(this.int, Dec.precision); let tmp = new Dec(1); for (let i = n; i.gt(new Int(1)); i = i.div(new Int(2))) { if (!i.mod(new Int(2)).isZero()) { tmp = tmp.mul(base); } base = base.mul(base); } return base.mul(tmp); } public mul(d2: Dec): Dec { return new Dec(this.mulRaw(d2).chopPrecisionAndRound(), Dec.precision); } public mulTruncate(d2: Dec): Dec { return new Dec(this.mulRaw(d2).chopPrecisionAndTruncate(), Dec.precision); } protected mulRaw(d2: Dec): Dec { return new Dec(this.int.multiply(d2.int), Dec.precision); } public quo(d2: Dec): Dec { return new Dec(this.quoRaw(d2).chopPrecisionAndRound(), Dec.precision); } public quoTruncate(d2: Dec): Dec { return new Dec(this.quoRaw(d2).chopPrecisionAndTruncate(), Dec.precision); } public quoRoundUp(d2: Dec): Dec { return new Dec(this.quoRaw(d2).chopPrecisionAndRoundUp(), Dec.precision); } protected quoRaw(d2: Dec): Dec { const precision = Dec.calcPrecisionMultiplier(0); // multiply precision twice const mul = this.int.multiply(precision).multiply(precision); return new Dec(mul.divide(d2.int), Dec.precision); } public isInteger(): boolean { const precision = Dec.calcPrecisionMultiplier(0); return this.int.remainder(precision).equals(bigInteger(0)); } /** * Remove a Precision amount of rightmost digits and perform bankers rounding * on the remainder (gaussian rounding) on the digits which have been removed. */ protected chopPrecisionAndRound(): bigInteger.BigInteger { // Remove the negative and add it back when returning if (this.isNegative()) { const absoulteDec = this.abs(); const choped = absoulteDec.chopPrecisionAndRound(); return choped.negate(); } const precision = Dec.calcPrecisionMultiplier(0); const fivePrecision = precision.divide(bigInteger(2)); // Get the truncated quotient and remainder const { quotient, remainder } = this.int.divmod(precision); // If remainder is zero if (remainder.equals(bigInteger(0))) { return quotient; } if (remainder.lt(fivePrecision)) { return quotient; } else if (remainder.gt(fivePrecision)) { return quotient.add(bigInteger(1)); } else { // always round to an even number if (quotient.divide(bigInteger(2)).equals(bigInteger(0))) { return quotient; } else { return quotient.add(bigInteger(1)); } } } protected chopPrecisionAndRoundUp(): bigInteger.BigInteger { // Remove the negative and add it back when returning if (this.isNegative()) { const absoulteDec = this.abs(); // truncate since d is negative... const choped = absoulteDec.chopPrecisionAndTruncate(); return choped.negate(); } const precision = Dec.calcPrecisionMultiplier(0); // Get the truncated quotient and remainder const { quotient, remainder } = this.int.divmod(precision); // If remainder is zero if (remainder.equals(bigInteger(0))) { return quotient; } return quotient.add(bigInteger(1)); } /** * Similar to chopPrecisionAndRound, but always rounds down */ protected chopPrecisionAndTruncate(): bigInteger.BigInteger { const precision = Dec.calcPrecisionMultiplier(0); return this.int.divide(precision); } public toString( prec: number = Dec.precision, locale: boolean = false ): string { const precision = Dec.calcPrecisionMultiplier(0); const int = this.int.abs(); const { quotient: integer, remainder: fraction } = int.divmod(precision); let fractionStr = fraction.toString(10); for (let i = 0, l = fractionStr.length; i < Dec.precision - l; i++) { fractionStr = "0" + fractionStr; } fractionStr = fractionStr.substring(0, prec); const isNegative = this.isNegative() && !(integer.eq(bigInteger(0)) && fractionStr.length === 0); const integerStr = locale ? // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore CoinUtils.integerStringToUSLocaleString(integer.toString()) : integer.toString(); return `${isNegative ? "-" : ""}${integerStr}${ fractionStr.length > 0 ? "." + fractionStr : "" }`; } public round(): Int { return new Int(this.chopPrecisionAndRound()); } public roundUp(): Int { return new Int(this.chopPrecisionAndRoundUp()); } public truncate(): Int { return new Int(this.chopPrecisionAndTruncate()); } public roundDec(): Dec { return new Dec(this.chopPrecisionAndRound(), 0); } public roundUpDec(): Dec { return new Dec(this.chopPrecisionAndRoundUp(), 0); } public truncateDec(): Dec { return new Dec(this.chopPrecisionAndTruncate(), 0); } }
the_stack
import config from '../../config'; import * as fs from 'fs'; import axios, { AxiosResponse } from 'axios'; import * as http from 'http'; import * as https from 'https'; import { SocksProxyAgent } from 'socks-proxy-agent'; import { BisqBlocks, BisqBlock, BisqTransaction, BisqStats, BisqTrade } from './interfaces'; import { Common } from '../common'; import { BlockExtended } from '../../mempool.interfaces'; import { StaticPool } from 'node-worker-threads-pool'; import backendInfo from '../backend-info'; import logger from '../../logger'; class Bisq { private static BLOCKS_JSON_FILE_PATH = config.BISQ.DATA_PATH + '/json/all/blocks.json'; private latestBlockHeight = 0; private blocks: BisqBlock[] = []; private allBlocks: BisqBlock[] = []; private transactions: BisqTransaction[] = []; private transactionIndex: { [txId: string]: BisqTransaction } = {}; private blockIndex: { [hash: string]: BisqBlock } = {}; private addressIndex: { [address: string]: BisqTransaction[] } = {}; private stats: BisqStats = { minted: 0, burnt: 0, addresses: 0, unspent_txos: 0, spent_txos: 0, }; private price: number = 0; private priceUpdateCallbackFunction: ((price: number) => void) | undefined; private topDirectoryWatcher: fs.FSWatcher | undefined; private subdirectoryWatcher: fs.FSWatcher | undefined; private jsonParsePool = new StaticPool({ size: 4, task: (blob: string) => JSON.parse(blob), }); constructor() {} startBisqService(): void { try { this.checkForBisqDataFolder(); } catch (e) { logger.info('Retrying to start bisq service in 3 minutes'); setTimeout(this.startBisqService.bind(this), 180000); return; } this.loadBisqDumpFile(); setInterval(this.updatePrice.bind(this), 1000 * 60 * 60); this.updatePrice(); this.startTopDirectoryWatcher(); this.startSubDirectoryWatcher(); } handleNewBitcoinBlock(block: BlockExtended): void { if (block.height - 10 > this.latestBlockHeight && this.latestBlockHeight !== 0) { logger.warn(`Bitcoin block height (#${block.height}) has diverged from the latest Bisq block height (#${this.latestBlockHeight}). Restarting watchers...`); this.startTopDirectoryWatcher(); this.startSubDirectoryWatcher(); } } getTransaction(txId: string): BisqTransaction | undefined { return this.transactionIndex[txId]; } getTransactions(start: number, length: number, types: string[]): [BisqTransaction[], number] { let transactions = this.transactions; if (types.length) { transactions = transactions.filter((tx) => types.indexOf(tx.txType) > -1); } return [transactions.slice(start, length + start), transactions.length]; } getBlock(hash: string): BisqBlock | undefined { return this.blockIndex[hash]; } getAddress(hash: string): BisqTransaction[] { return this.addressIndex[hash]; } getBlocks(start: number, length: number): [BisqBlock[], number] { return [this.blocks.slice(start, length + start), this.blocks.length]; } getStats(): BisqStats { return this.stats; } setPriceCallbackFunction(fn: (price: number) => void) { this.priceUpdateCallbackFunction = fn; } getLatestBlockHeight(): number { return this.latestBlockHeight; } private checkForBisqDataFolder() { if (!fs.existsSync(Bisq.BLOCKS_JSON_FILE_PATH)) { logger.warn(Bisq.BLOCKS_JSON_FILE_PATH + ` doesn't exist. Make sure Bisq is running and the config is correct before starting the server.`); throw new Error(`Cannot load BISQ ${Bisq.BLOCKS_JSON_FILE_PATH} file`); } } private startTopDirectoryWatcher() { if (this.topDirectoryWatcher) { this.topDirectoryWatcher.close(); } let fsWait: NodeJS.Timeout | null = null; this.topDirectoryWatcher = fs.watch(config.BISQ.DATA_PATH + '/json', () => { if (fsWait) { clearTimeout(fsWait); } if (this.subdirectoryWatcher) { this.subdirectoryWatcher.close(); } fsWait = setTimeout(() => { logger.debug(`Bisq restart detected. Resetting both watchers in 3 minutes.`); setTimeout(() => { this.startTopDirectoryWatcher(); this.startSubDirectoryWatcher(); this.loadBisqDumpFile(); }, 180000); }, 15000); }); } private startSubDirectoryWatcher() { if (this.subdirectoryWatcher) { this.subdirectoryWatcher.close(); } if (!fs.existsSync(Bisq.BLOCKS_JSON_FILE_PATH)) { logger.warn(Bisq.BLOCKS_JSON_FILE_PATH + ` doesn't exist. Trying to restart sub directory watcher again in 3 minutes.`); setTimeout(() => this.startSubDirectoryWatcher(), 180000); return; } let fsWait: NodeJS.Timeout | null = null; this.subdirectoryWatcher = fs.watch(config.BISQ.DATA_PATH + '/json/all', () => { if (fsWait) { clearTimeout(fsWait); } fsWait = setTimeout(() => { logger.debug(`Change detected in the Bisq data folder.`); this.loadBisqDumpFile(); }, 2000); }); } private async updatePrice() { type axiosOptions = { headers: { 'User-Agent': string }; timeout: number; httpAgent?: http.Agent; httpsAgent?: https.Agent; } const setDelay = (secs: number = 1): Promise<void> => new Promise(resolve => setTimeout(() => resolve(), secs * 1000)); const BISQ_URL = (config.SOCKS5PROXY.ENABLED === true) && (config.SOCKS5PROXY.USE_ONION === true) ? config.EXTERNAL_DATA_SERVER.BISQ_ONION : config.EXTERNAL_DATA_SERVER.BISQ_URL; const isHTTP = (new URL(BISQ_URL).protocol.split(':')[0] === 'http') ? true : false; const axiosOptions: axiosOptions = { headers: { 'User-Agent': (config.MEMPOOL.USER_AGENT === 'mempool') ? `mempool/v${backendInfo.getBackendInfo().version}` : `${config.MEMPOOL.USER_AGENT}` }, timeout: config.SOCKS5PROXY.ENABLED ? 30000 : 10000 }; let retry = 0; while(retry < config.MEMPOOL.EXTERNAL_MAX_RETRY) { try { if (config.SOCKS5PROXY.ENABLED) { const socksOptions: any = { agentOptions: { keepAlive: true, }, hostname: config.SOCKS5PROXY.HOST, port: config.SOCKS5PROXY.PORT }; if (config.SOCKS5PROXY.USERNAME && config.SOCKS5PROXY.PASSWORD) { socksOptions.username = config.SOCKS5PROXY.USERNAME; socksOptions.password = config.SOCKS5PROXY.PASSWORD; } else { // Retry with different tor circuits https://stackoverflow.com/a/64960234 socksOptions.username = `circuit${retry}`; } // Handle proxy agent for onion addresses if (isHTTP) { axiosOptions.httpAgent = new SocksProxyAgent(socksOptions); } else { axiosOptions.httpsAgent = new SocksProxyAgent(socksOptions); } } const data: AxiosResponse = await axios.get(`${BISQ_URL}/trades/?market=bsq_btc`, axiosOptions); if (data.statusText === 'error' || !data.data) { throw new Error(`Could not fetch data from Bisq market, Error: ${data.status}`); } const prices: number[] = []; data.data.forEach((trade) => { prices.push(parseFloat(trade.price) * 100000000); }); prices.sort((a, b) => a - b); this.price = Common.median(prices); if (this.priceUpdateCallbackFunction) { this.priceUpdateCallbackFunction(this.price); } logger.debug('Successfully updated Bisq market price'); break; } catch (e) { logger.err('Error updating Bisq market price: ' + (e instanceof Error ? e.message : e)); await setDelay(config.MEMPOOL.EXTERNAL_RETRY_INTERVAL); retry++; } } } private async loadBisqDumpFile(): Promise<void> { this.allBlocks = []; try { await this.loadData(); this.buildIndex(); this.calculateStats(); } catch (e) { logger.info('Cannot load bisq dump file because: ' + (e instanceof Error ? e.message : e)); } } private buildIndex() { const start = new Date().getTime(); this.transactions = []; this.transactionIndex = {}; this.addressIndex = {}; this.allBlocks.forEach((block) => { /* Build block index */ if (!this.blockIndex[block.hash]) { this.blockIndex[block.hash] = block; } /* Build transactions index */ block.txs.forEach((tx) => { this.transactions.push(tx); this.transactionIndex[tx.id] = tx; }); }); /* Build address index */ this.transactions.forEach((tx) => { tx.inputs.forEach((input) => { if (!this.addressIndex[input.address]) { this.addressIndex[input.address] = []; } if (this.addressIndex[input.address].indexOf(tx) === -1) { this.addressIndex[input.address].push(tx); } }); tx.outputs.forEach((output) => { if (!this.addressIndex[output.address]) { this.addressIndex[output.address] = []; } if (this.addressIndex[output.address].indexOf(tx) === -1) { this.addressIndex[output.address].push(tx); } }); }); const time = new Date().getTime() - start; logger.debug('Bisq data index rebuilt in ' + time + ' ms'); } private calculateStats() { let minted = 0; let burned = 0; let unspent = 0; let spent = 0; this.transactions.forEach((tx) => { tx.outputs.forEach((output) => { if (output.opReturn) { return; } if (output.txOutputType === 'GENESIS_OUTPUT' || output.txOutputType === 'ISSUANCE_CANDIDATE_OUTPUT' && output.isVerified) { minted += output.bsqAmount; } if (output.isUnspent) { unspent++; } else { spent++; } }); burned += tx['burntFee']; }); this.stats = { addresses: Object.keys(this.addressIndex).length, minted: minted / 100, burnt: burned / 100, spent_txos: spent, unspent_txos: unspent, }; } private async loadData(): Promise<any> { if (!fs.existsSync(Bisq.BLOCKS_JSON_FILE_PATH)) { throw new Error(Bisq.BLOCKS_JSON_FILE_PATH + ` doesn't exist`); } const readline = require('readline'); const events = require('events'); const rl = readline.createInterface({ input: fs.createReadStream(Bisq.BLOCKS_JSON_FILE_PATH), crlfDelay: Infinity }); let blockBuffer = ''; let readingBlock = false; let lineCount = 1; const start = new Date().getTime(); logger.debug('Processing Bisq data dump...'); rl.on('line', (line) => { if (lineCount === 2) { line = line.replace(' "chainHeight": ', ''); this.latestBlockHeight = parseInt(line, 10); } if (line === ' {') { readingBlock = true; } else if (line === ' },') { blockBuffer += '}'; try { const block: BisqBlock = JSON.parse(blockBuffer); this.allBlocks.push(block); readingBlock = false; blockBuffer = ''; } catch (e) { logger.debug(blockBuffer); throw Error(`Unable to parse Bisq data dump at line ${lineCount}` + (e instanceof Error ? e.message : e)); } } if (readingBlock === true) { blockBuffer += line; } ++lineCount; }); await events.once(rl, 'close'); this.allBlocks.reverse(); this.blocks = this.allBlocks.filter((block) => block.txs.length > 0); const time = new Date().getTime() - start; logger.debug('Bisq dump processed in ' + time + ' ms'); } } export default new Bisq();
the_stack
import { PdfGrid } from './pdf-grid'; import { PdfGridCell, PdfGridCellCollection } from './pdf-grid-cell'; import { PdfGridRowStyle } from './styles/style'; import { PdfLayoutResult } from '../../graphics/figures/base/element-layouter'; import { PdfGridColumn } from './../../structured-elements/grid/pdf-grid-column'; /** * `PdfGridRow` class provides customization of the settings for the particular row. */ export class PdfGridRow { //Fields /** * `Cell collecton` of the current row.. * @private */ private gridCells : PdfGridCellCollection; /** * Stores the current `grid`. * @private */ private pdfGrid : PdfGrid; /** * The grid row `style`. * @private */ private rowStyle : PdfGridRowStyle; /** * Stores the row `break height`. * @private */ private gridRowBreakHeight : number; /** * Stores the index of the overflowing row. * @private */ private gridRowOverflowIndex : number = 0; /** * The `height` of the row. * @private */ private rowHeight : number = 0; /** * The `width` of the row. * @private */ private rowWidth : number = 0; /** * The `isFinish` of the row. * @private */ public isrowFinish : boolean = false; /** * Check whether the Row span row height `is set explicitly`. * @default false * @public */ public isRowSpanRowHeightSet : boolean = false; /** * The grid row `Layout Result`. * @private */ private gridResult : PdfLayoutResult ; /** * The `Maximum span` of the row. * @public */ public maximumRowSpan : number; /** * The `page count` of the row. * @public */ public noOfPageCount : number = 0 ; /** * Check whether the row height `is set explicitly`. * @default false * @private */ public isRowHeightSet : boolean = false; public isRowBreaksNextPage : boolean ; public rowBreakHeightValue : number; public isPageBreakRowSpanApplied : boolean = false; /** * Checks whether the `columns span is exist or not`. * @private */ private bColumnSpanExists : boolean; /** * Check weather the row merge `is completed` or not. * @default true * @private */ private isRowMergeComplete : boolean = true; /** * Checks whether the `row span is exist or not`. * @private */ private bRowSpanExists : boolean; public repeatFlag : boolean = false; public repeatRowNumber : number; public rowFontSplit : boolean = false; public isHeaderRow: boolean = false; //Constructor /** * Initializes a new instance of the `PdfGridRow` class with the parent grid. * @private */ public constructor(grid : PdfGrid) { this.pdfGrid = grid; } //Properties /** * Gets or sets a value indicating [`row span exists`]. * @private */ public get rowSpanExists() : boolean { return this.bRowSpanExists; } public set rowSpanExists(value : boolean) { this.bRowSpanExists = value; } /** * Gets the `cells` from the selected row.[Read-Only]. * @private */ public get cells() : PdfGridCellCollection { if (this.gridCells == null) { this.gridCells = new PdfGridCellCollection(this); } return this.gridCells; } /** * Gets or sets the parent `grid`. * @private */ public get grid() : PdfGrid { return this.pdfGrid; } public set grid(value : PdfGrid) { this.pdfGrid = value; } /** * Gets or sets the row `style`. * @private */ public get style() : PdfGridRowStyle { if (typeof this.rowStyle === 'undefined') { this.rowStyle = new PdfGridRowStyle(); this.rowStyle.setParent(this); } return this.rowStyle; } public set style(value : PdfGridRowStyle) { this.rowStyle = value; for (let i : number = 0; i < this.cells.count; i++) { this.cells.getCell(i).style.borders = value.border; if (typeof value.font !== 'undefined') { this.cells.getCell(i).style.font = value.font; } if (typeof value.backgroundBrush !== 'undefined') { this.cells.getCell(i).style.backgroundBrush = value.backgroundBrush; } if (typeof value.backgroundImage !== 'undefined') { this.cells.getCell(i).style.backgroundImage = value.backgroundImage; } if (typeof value.textBrush !== 'undefined') { this.cells.getCell(i).style.textBrush = value.textBrush; } if (typeof value.textPen !== 'undefined') { this.cells.getCell(i).style.textPen = value.textPen; } } } /** * `Height` of the row yet to be drawn after split. * @private */ public get rowBreakHeight() : number { if (typeof this.gridRowBreakHeight === 'undefined') { this.gridRowBreakHeight = 0; } return this.gridRowBreakHeight; } public set rowBreakHeight(value : number) { this.gridRowBreakHeight = value; } /** * `over flow index` of the row. * @private */ public get rowOverflowIndex() : number { return this.gridRowOverflowIndex; } public set rowOverflowIndex(value : number) { this.gridRowOverflowIndex = value; } /** * Gets or sets the `height` of the row. * @private */ public get height() : number { if (!this.isRowHeightSet) { this.rowHeight = this.measureHeight(); } return this.rowHeight; } public set height(value : number) { this.rowHeight = value; this.isRowHeightSet = true; } /** * Gets or sets the `width` of the row. * @private */ public get width() : number { if (this.rowWidth === 0 || typeof this.rowWidth === 'undefined') { this.rowWidth = this.measureWidth(); } return this.rowWidth; } /** * Gets or sets the row `Nested grid Layout Result`. * @private */ public get NestedGridLayoutResult() : PdfLayoutResult{ return this.gridResult; } public set NestedGridLayoutResult(value : PdfLayoutResult ) { this.gridResult = value; } /** * Gets or sets a value indicating [`column span exists`]. * @private */ public get columnSpanExists() : boolean { return this.bColumnSpanExists; } public set columnSpanExists(value : boolean) { this.bColumnSpanExists = value; } /** * Check whether the Row `has row span or row merge continue`. * @private */ public get rowMergeComplete() : boolean { return this.isRowMergeComplete; } public set rowMergeComplete(value : boolean) { this.isRowMergeComplete = value; } /** * Returns `index` of the row. * @private */ public get rowIndex() : number { return this.grid.rows.rowCollection.indexOf(this); } //Implementation /** * `Calculates the height`. * @private */ private measureHeight() : number { let rowSpanRemainingHeight : number = 0; let rowHeight : number; let maxHeight : number = 0; if (this.cells.getCell(0).rowSpan > 1) { rowHeight = 0; } else { rowHeight = this.cells.getCell(0).height; } for (let i : number = 0; i < this.cells.count; i++) { let cell : PdfGridCell = this.cells.getCell(i); //get the maximum rowspan remaining height. if (cell.rowSpanRemainingHeight > rowSpanRemainingHeight) { rowSpanRemainingHeight = cell.rowSpanRemainingHeight; } //skip the cell if row spanned. // if (cell.isRowMergeContinue) { // continue; // } // if (!cell.isRowMergeContinue) { // this.rowMergeComplete = false; // } this.rowMergeComplete = false; if (cell.rowSpan > 1) { let cellIn : number = i; let rowin : number = this.isHeaderRow ? this.grid.headers.indexOf(this) : this.grid.rows.rowCollection.indexOf(this); for (let j : number = 0; j < cell.rowSpan; j++ ) { if ( (j + 1) < cell.rowSpan) { (this.isHeaderRow ? this.grid.headers.getHeader(rowin + j + 1) : this.grid.rows.getRow(rowin + j + 1)).cells.getCell(cellIn).hasRowSpan = true; } } if (maxHeight < cell.height) { maxHeight = cell.height; } continue; } rowHeight = Math.max(rowHeight, cell.height); } if (maxHeight > rowHeight) { rowHeight = maxHeight; } if (rowHeight === 0) { rowHeight = maxHeight; } else if (rowSpanRemainingHeight > 0) { rowHeight += rowSpanRemainingHeight; } return rowHeight; } private measureWidth() : number { let rowWid : number = 0; for (let i : number = 0; i < this.grid.columns.count; i++) { let column : PdfGridColumn = this.grid.columns.getColumn(i); rowWid += column.width; } return rowWid; } } /** * `PdfGridRowCollection` class provides access to an ordered, strongly typed collection of 'PdfGridRow' objects. * @private */ export class PdfGridRowCollection { // Fields /** * @hidden * @private */ private grid : PdfGrid; /** * The row collection of the `grid`. * @private */ private rows : PdfGridRow[]; // Constructor /** * Initializes a new instance of the `PdfGridRowCollection` class with the parent grid. * @private */ public constructor(grid : PdfGrid) { this.rows = []; this.grid = grid; } //Properties /** * Gets the number of header in the `PdfGrid`.[Read-Only]. * @private */ public get count() : number { return this.rows.length; } //Implementation /** * Return the row collection of the `grid`. * @private */ public get rowCollection() : PdfGridRow[] { return this.rows; } /** * `Adds` the specified row. * @private */ public addRow() : PdfGridRow /** * `Adds` the specified row. * @private */ public addRow(row : PdfGridRow) : void public addRow(arg ?: PdfGridRow) : void | PdfGridRow { if (typeof arg === 'undefined') { let temprow : PdfGridRow = new PdfGridRow(this.grid); this.addRow(temprow); return temprow; } else { arg.style.setBackgroundBrush(this.grid.style.backgroundBrush); arg.style.setFont(this.grid.style.font); arg.style.setTextBrush(this.grid.style.textBrush); arg.style.setTextPen(this.grid.style.textPen); if (arg.cells.count === 0) { for (let i : number = 0; i < this.grid.columns.count; i++) { arg.cells.add(new PdfGridCell()); } } this.rows.push(arg); } } /** * Return the row by index. * @private */ public getRow(index : number) : PdfGridRow { return this.rows[index]; } } /** * `PdfGridHeaderCollection` class provides customization of the settings for the header. * @private */ export class PdfGridHeaderCollection { /** * The `grid`. * @private */ private grid : PdfGrid; /** * The array to store the `rows` of the grid header. * @private */ private rows : PdfGridRow[] = []; //constructor /** * Initializes a new instance of the `PdfGridHeaderCollection` class with the parent grid. * @private */ public constructor(grid : PdfGrid) { this.grid = grid; this.rows = []; } //Properties /** * Gets a 'PdfGridRow' object that represents the `header` row in a 'PdfGridHeaderCollection' control.[Read-Only]. * @private */ public getHeader(index : number) : PdfGridRow { // if (index < 0 || index >= Count) { // throw new IndexOutOfRangeException(); // } return (this.rows[index]); } /** * Gets the `number of header` in the 'PdfGrid'.[Read-Only] * @private */ public get count() : number { return this.rows.length; } //Implementation /** * `Adds` the specified row. * @private */ public add(row : PdfGridRow) : void /** * `Adds` the specified row. * @private */ public add(count : number) : PdfGridRow[] public add(arg : number|PdfGridRow) : void|PdfGridRow[] { if (typeof arg === 'number') { let row : PdfGridRow; for (let i : number = 0; i < arg; i++) { row = new PdfGridRow(this.grid); row.isHeaderRow = true; for (let j : number = 0; j < this.grid.columns.count; j++) { row.cells.add(new PdfGridCell()); } this.rows.push(row); } return this.rows; } else { this.rows.push(arg); } } public indexOf(row : PdfGridRow) : number { return this.rows.indexOf(row); } }
the_stack
import { FunctionalComponent } from 'preact'; import { html } from 'htm/preact'; import { useState, useEffect, useRef, useContext } from 'preact/hooks'; import { JsonRpcMethod } from '@algosigner/common/messaging/types'; import { sendMessage } from 'services/Messaging'; import { StoreContext } from 'services/StoreContext'; import TxAcfg from 'components/TransactionDetail/TxAcfg'; import TxPay from 'components/TransactionDetail/TxPay'; import TxKeyreg from 'components/TransactionDetail/TxKeyreg'; import TxAxfer from 'components/TransactionDetail/TxAxfer'; import TxAfrz from 'components/TransactionDetail/TxAfrz'; import TxAppl from 'components/TransactionDetail/TxAppl'; const BACKGROUND_REFRESH_TIMER: number = 10000; const INNER_TXN_DESCRIPTIONS = { axfer: 'Asset Transfer', pay: 'Payment', afrz: 'Asset Freeze', keyreg: 'Key Registration', acfg: 'Asset Config', appl: 'Application', }; const TransactionsList: FunctionalComponent = (props: any) => { const store: any = useContext(StoreContext); const { address, ledger } = props; const [date, setDate] = useState<any>(new Date()); const [results, setResults] = useState<any>([]); const [pending, setPending] = useState<any>([]); const [isLoading, setLoading] = useState<any>(true); const [showTx, setShowTx] = useState<any>(null); const [nextToken, setNextToken] = useState<any>(null); const resultsRef = useRef([]); const pendingRef = useRef([]); const fetchApi = async () => { setLoading(true); const params = { 'ledger': ledger, 'address': address, 'next-token': nextToken, 'limit': 20, }; sendMessage(JsonRpcMethod.Transactions, params, function (response) { setLoading(false); // If there are already transactions, just append the new ones if (results.length > 0) { setResults(results.concat(response.transactions)); } else { resultsRef.current = response.transactions; pendingRef.current = response.pending; setResults(resultsRef.current); setPending(pendingRef.current); if (pendingRef.current && pendingRef.current.length) { setTimeout(backgroundFetch, BACKGROUND_REFRESH_TIMER); } } const nextToken = response['next-token'] || null; setNextToken(nextToken); }); }; const backgroundFetch = async () => { setLoading(true); const params = { ledger: ledger, address: address, limit: resultsRef.current.length + pendingRef.current.length, }; sendMessage(JsonRpcMethod.Transactions, params, function (response) { setLoading(false); setDate(new Date()); setResults(response.transactions); setPending(response.pending); // If there are still pending tx after the update, we request another background fetch if (response.pending && response.pending.length) { setTimeout(backgroundFetch, BACKGROUND_REFRESH_TIMER); } if (response['next-token']) setNextToken(response['next-token']); else setNextToken(null); }); }; const handleClick = (tx) => { switch (tx['tx-type']) { case 'pay': setShowTx(html`<${TxPay} tx=${tx} ledger=${ledger} />`); break; case 'keyreg': setShowTx(html`<${TxKeyreg} tx=${tx} ledger=${ledger} />`); break; case 'acfg': setShowTx(html`<${TxAcfg} tx=${tx} ledger=${ledger} />`); break; case 'axfer': setShowTx(html`<${TxAxfer} tx=${tx} ledger=${ledger} />`); break; case 'afrz': setShowTx(html`<${TxAfrz} tx=${tx} ledger=${ledger} />`); break; case 'appl': setShowTx(html`<${TxAppl} tx=${tx} ledger=${ledger} />`); break; } }; useEffect(() => { setDate(new Date()); fetchApi(); }, []); if (!results) return null; const loadMore = () => { fetchApi(); }; const getTxInfo = (tx, date): any => { function getTime(date, roundTime) { const MINUTESTHRESHOLD = 60000; const HOURSTHRESHOLD = 3600000; const roundDate = new Date(roundTime * 1000); const diffTime = date - roundDate.getTime(); if (diffTime < 86400000) { let time, label; if (diffTime < MINUTESTHRESHOLD) { time = diffTime / 1000; label = 'sec'; } else if (diffTime < HOURSTHRESHOLD) { time = diffTime / MINUTESTHRESHOLD; label = 'min'; } else { time = diffTime / HOURSTHRESHOLD; label = 'hour'; } time = Math.floor(time); if (time > 1) return time + ' ' + label + 's ago'; else return time + ' ' + label + ' ago'; } else { return roundDate.toDateString(); } } const id = tx.id; const time = getTime(date, tx['round-time']); let title, subtitle, info; switch (tx['tx-type']) { case 'pay': info = tx['payment-transaction'].amount / 1e6 + ' Algos'; if (tx.sender === address) { subtitle = 'Payment To'; title = tx['payment-transaction'].receiver; } else { subtitle = 'Payment From'; title = tx.sender; } break; case 'keyreg': title = 'Key registration'; break; case 'acfg': subtitle = 'Asset config'; title = tx['asset-config-transaction'].params.name; break; case 'axfer': info = tx['asset-transfer-transaction']['amount']; store.getAssetDetails(ledger, address, (assets) => { const id = tx['asset-transfer-transaction']['asset-id']; // Check if the asset has not been deleted before getting info about it if (assets[id]) { const dec = assets[id].decimals || 0; const amount = info / Math.pow(10, dec); info = `${amount} ${assets[id].unitName}`; } }); // TODO Close-to txs // Clawback if there is a sender in the transfer object if (tx['asset-transfer-transaction'].sender) { if (tx['asset-transfer-transaction'].receiver === address) { subtitle = 'ASA From (clawback)'; title = tx['asset-transfer-transaction']['sender']; } else { subtitle = 'ASA To (clawback)'; title = tx['asset-transfer-transaction']['receiver']; } } else { if (tx['asset-transfer-transaction'].receiver === address) { subtitle = 'ASA From'; title = tx['sender']; } else { subtitle = 'ASA To'; title = tx['asset-transfer-transaction']['receiver']; } } break; case 'afrz': title = tx['asset-freeze-transaction']['asset-id']; if (tx['asset-freeze-transaction']['new-freeze-status']) { subtitle = 'Asset freezed'; } else { subtitle = 'Asset unfreezed'; } break; case 'appl': if ('application-id' in tx['application-transaction']) { subtitle = tx['application-transaction']['application-id'] || 'application'; info = tx['application-transaction']['on-completion']; title = 'Application'; } else { subtitle = 'appl'; title = 'Application Transaction'; } break; } return { title, subtitle, info, id, time, }; }; const getTxTemplate = (tx, date) => { const { title, subtitle, info, id, time } = getTxInfo(tx, date); return html` <div style="display: flex; justify-content: space-between;" data-transaction-id="${id}"> <div style="max-width: 60%; white-space: nowrap;"> <h2 class="subtitle is-size-7 is-uppercase has-text-grey-light">${subtitle}</h2> <h1 style="text-overflow: ellipsis; overflow: hidden;" class="title is-size-6"> ${title} </h1> </div> <div class="has-text-right"> <h2 class="subtitle is-size-7 has-text-grey-light is-uppercase">${time}</h2> <h1 class="title is-size-6">${info}</h1> </div> </div> ${tx['inner-txns'] && html` <span class="has-text-grey-light is-size-7 is-uppercase pt-2">Inner Transaction(s):</span> <div class="is-size-7 pl-1"> ${tx['inner-txns'].map( (inner: any) => { const innerTxInfo = getTxInfo(inner, date); return html` <div class="is-flex is-justify-content-space-between"> <i class="fas fa-angle-double-right mr-1" aria-hidden="true" /> <span class="is-uppercase">${INNER_TXN_DESCRIPTIONS[inner['tx-type']]}</span> <div class="has-text-right is-flex-grow-1">${innerTxInfo.info}</div> </div> `;} )} </div> `} `; }; const getPendingTxInfo = (tx) => { let title, subtitle, info; switch (tx['type']) { case 'pay': info = tx.amount / 1e6 + ' Algos'; if (tx.sender === address) { subtitle = 'Pending Payment to'; title = tx.receiver; } else { subtitle = 'Pending Payment from'; title = tx.sender; } break; case 'keyreg': subtitle = 'Pending transaction'; title = 'Key Registration'; break; case 'acfg': subtitle = 'Pending Asset Config Transaction'; title = tx.id; break; case 'axfer': info = tx.assetName ? `${tx.amount} ${tx.assetName}` : null; // Clawback if there is a sender in the transfer object if (tx.assetSender) { if (tx.receiver === address) { subtitle = 'Pending Asset Clawback From'; title = tx.assetSender; } else { subtitle = 'Pending Asset Clawback To'; title = tx.receiver; } } else { if (tx.receiver === address) { subtitle = 'Pending Asset Transfer From'; title = tx.sender; } else { subtitle = 'Pending Asset Transfer To'; title = tx.receiver; } } break; case 'afrz': subtitle = 'Pending Asset Freeze Transaction'; title = tx.assetName; break; case 'appl': subtitle = 'Pending Application Transaction'; title = tx.id; break; } return html` <div style="display: flex; justify-content: space-between;"> <div style="max-width: 60%; white-space: nowrap;"> <h2 class="subtitle is-size-7 is-uppercase has-text-grey-light"> <i>${subtitle}</i> </h2> <h1 style="text-overflow: ellipsis; overflow: hidden;" class="title is-size-6 has-text-grey" > <i>${title}</i> </h1> </div> ${info && html` <div class="has-text-right" style="margin-top: 17px;"> <h1 class="title is-size-6 has-text-grey"> <i>${info}</i> </h1> </div> `} </div> `; }; return html` <div class="py-2"> <span class="px-4 has-text-weight-bold is-size-5">Transactions</span> ${pending.map( (tx: any) => html` <div class="py-3 px-4" style="border-top: 1px solid rgba(138, 159, 168, 0.2);"> ${getPendingTxInfo(tx)} </div> ` )} ${results && results.map( (tx: any) => html` <div class="py-3 px-4" style="border-top: 1px solid rgba(138, 159, 168, 0.2); cursor: pointer;" onClick=${() => handleClick(tx)} > ${getTxTemplate(tx, date)} </div> ` )} ${!isLoading && nextToken && html` <div class="py-3 px-4 has-text-centered" style="border-top: 1px solid rgba(138, 159, 168, 0.2);" > <a onClick=${loadMore}> Load more transactions </a> </div> `} ${isLoading && html` <div style="padding: 10px 0;"> <span class="loader" style="position: relative; left: calc(50% - 0.5em);"></span> </div> `} </div> <div class=${`modal ${showTx ? 'is-active' : ''}`}> <div class="modal-background"></div> <div class="modal-content">${showTx}</div> <button class="modal-close is-large" aria-label="close" onClick=${() => setShowTx(null)} /> </div> `; }; export default TransactionsList;
the_stack
import { ethers, deployments, run } from 'hardhat' import { Signer } from '@ethersproject/abstract-signer' import { BigNumberish, BigNumber } from '@ethersproject/bignumber' import { BytesLike, hexConcat, zeroPad } from '@ethersproject/bytes' import { ContractTransaction } from '@ethersproject/contracts' import { assert, expect } from 'chai' import { Challenge, RollupAdminFacet, RollupUserFacet } from '../build/types' import { initializeAccounts } from './utils' import { Node, Assertion, RollupContract, challengeHash, nodeHash, nodeStateHash, ExecutionState, assertionExecutionHash, assertionGasUsed, makeAssertion, forceCreateNode, } from './common/rolluplib' import { bisectExecution } from './common/challenge' const initialVmState = '0x9900000000000000000000000000000000000000000000000000000000000000' const zerobytes32 = ethers.constants.HashZero const stakeRequirement = 10 const stakeToken = ethers.constants.AddressZero const confirmationPeriodBlocks = 100 const avmGasSpeedLimitPerBlock = 1000000 const minimumAssertionPeriod = 75 const sequencerDelayBlocks = 15 const sequencerDelaySeconds = 900 const ZERO_ADDR = ethers.constants.AddressZero let rollup: RollupContract let rollupAdmin: RollupAdminFacet let accounts: Signer[] type RollupConfig = [ BytesLike, BigNumberish, BigNumberish, BigNumberish, BigNumberish, string, string, string, BigNumberish, BigNumberish, BytesLike ] async function getDefaultConfig( _confirmationPeriodBlocks = confirmationPeriodBlocks ): Promise<RollupConfig> { return [ initialVmState, _confirmationPeriodBlocks, 0, avmGasSpeedLimitPerBlock, stakeRequirement, stakeToken, await accounts[0].getAddress(), // owner await accounts[1].getAddress(), // sequencer sequencerDelayBlocks, sequencerDelaySeconds, '0x', ] } async function createRollup( shouldDebug = process.env['ROLLUP_DEBUG'] === '1', rollupConfig?: RollupConfig ): Promise<{ rollupCon: RollupUserFacet blockCreated: number }> { if (!rollupConfig) rollupConfig = await getDefaultConfig() let receipt let rollupCreator if (shouldDebug) { // this deploys the rollup contracts without proxies to facilitate debugging const ChallengeFactory = await deployments.get('ChallengeFactory') const RollupCreatorNoProxy = await ethers.getContractFactory( 'RollupCreatorNoProxy' ) rollupCreator = await RollupCreatorNoProxy.deploy( ChallengeFactory.address, ...rollupConfig ) receipt = await rollupCreator.deployTransaction.wait() } else { rollupCreator = await ethers.getContractAt( 'RollupCreator', ( await deployments.get('RollupCreator') ).address ) const createRollupTx = await rollupCreator.createRollup(...rollupConfig) receipt = await createRollupTx.wait() } if (!receipt.logs) { throw Error('expected receipt to have logs') } const ev = rollupCreator.interface.parseLog( receipt.logs[receipt.logs.length - 1] ) expect(ev.name).to.equal('RollupCreated') const parsedEv = ev as any as { args: { rollupAddress: string } } const Rollup = (await ethers.getContractFactory('RollupUserFacet')).connect( accounts[8] ) const RollupAdmin = ( await ethers.getContractFactory('RollupAdminFacet') ).connect(accounts[0]) rollupAdmin = RollupAdmin.attach(parsedEv.args.rollupAddress) await rollupAdmin.setValidator( [ await accounts[1].getAddress(), await accounts[2].getAddress(), await accounts[8].getAddress(), ], [true, true, true] ) const rollupCon = Rollup.attach(parsedEv.args.rollupAddress) return { rollupCon: rollupCon, blockCreated: receipt.blockNumber!, } } async function tryAdvanceChain(blocks: number): Promise<void> { try { for (let i = 0; i < blocks; i++) { await ethers.provider.send('evm_mine', []) } } catch (e) { // EVM mine failed. Try advancing the chain by sending txes if the node // is in dev mode and mints blocks when txes are sent for (let i = 0; i < blocks; i++) { const tx = await accounts[0].sendTransaction({ value: 0, to: await accounts[0].getAddress(), }) await tx.wait() } } } async function advancePastAssertion(a: Assertion): Promise<void> { const checkTime = assertionGasUsed(a).div(avmGasSpeedLimitPerBlock).toNumber() await tryAdvanceChain(confirmationPeriodBlocks + checkTime) } async function makeSimpleNode( rollup: RollupContract, parentNode: Node, prevNode?: Node ): Promise<{ tx: ContractTransaction; node: Node }> { const block = await ethers.provider.getBlock('latest') const challengedAssertion = makeSimpleAssertion( parentNode.assertion.afterState, (block.number - parentNode.proposedBlock + 1) * avmGasSpeedLimitPerBlock ) const { tx, node, event } = await rollup.stakeOnNewNode( parentNode, challengedAssertion, zerobytes32, '0x', prevNode ) assert.equal(event.nodeHash, node.nodeHash) assert.equal(event.executionHash, assertionExecutionHash(node.assertion)) return { tx, node } } const makeSends = (count: number, batchStart = 0) => { return [...Array(count)].map((_, i) => hexConcat([ [0], zeroPad([i + batchStart], 32), zeroPad([0], 32), zeroPad([1], 32), ]) ) } function makeSimpleAssertion( prevState: ExecutionState, gasUsed: BigNumberish ): Assertion { return makeAssertion(prevState, gasUsed, zerobytes32, [], [], []) } async function makeNode( rollup: RollupContract, parentNode: Node, prevNode?: Node, sends: BytesLike[] = [] ): Promise<{ tx: ContractTransaction; node: Node }> { const block = await ethers.provider.getBlock('latest') const gasUsed = (block.number - parentNode.proposedBlock + 1) * avmGasSpeedLimitPerBlock const assertion = makeAssertion( parentNode.assertion.afterState, gasUsed, zerobytes32, [], sends, [] ) const { tx, node, event } = await rollup.stakeOnNewNode( parentNode, assertion, zerobytes32, '0x', prevNode ) expect(node.assertion).to.eql(assertion) assert.equal(event.nodeHash, node.nodeHash) assert.equal(event.executionHash, assertionExecutionHash(node.assertion)) return { tx, node } } let prevNode: Node const initNewRollup = async () => { const { rollupCon, blockCreated } = await createRollup() rollup = new RollupContract(rollupCon) const originalNode = await rollup.latestConfirmed() const nodeAddress = await rollup.getNode(originalNode) const NodeContract = await ethers.getContractFactory('Node') const node = NodeContract.attach(nodeAddress) const initialExecState = { gasUsed: 0, machineHash: initialVmState, inboxCount: 0, sendCount: 0, logCount: 0, sendAcc: zerobytes32, logAcc: zerobytes32, } const initialAssertion = makeAssertion( initialExecState, 0, initialVmState, [], [], [] ) prevNode = { assertion: initialAssertion, proposedBlock: blockCreated, inboxMaxCount: 1, nodeHash: zerobytes32, } assert.equal( await node.stateHash(), nodeStateHash(prevNode), 'initial confirmed node should have set initial state' ) return rollup } describe('ArbRollup', () => { it('should deploy contracts', async function () { accounts = await initializeAccounts() await run('deploy', { tags: 'test' }) }) it('should initialize', async function () { rollup = await initNewRollup() }) it('should always init logic contract', async function () { const RollupTester = await ethers.getContractFactory('Rollup') await expect(RollupTester.deploy(0)).to.be.revertedWith( 'CONSTRUCTOR_NOT_INIT' ) }) it('should not be able to use invalid init param', async function () { // set confirm period blocks to 0 const config = await getDefaultConfig(0) await expect(createRollup(true, config)).to.be.revertedWith( 'INITIALIZE_NOT_INIT' ) }) it('should only initialize once', async function () { const RollupDispatch = await ethers.getContractFactory('Rollup') const rollupDispatch = RollupDispatch.attach(rollup.rollup.address) await expect( rollupDispatch.initialize( initialVmState, [0, 0, 0, 0], ZERO_ADDR, ZERO_ADDR, zerobytes32, [ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR], [ZERO_ADDR, ZERO_ADDR], [0, 0] ) ).to.be.revertedWith('ALREADY_INIT') }) it('should validate facets in initialization', async function () { const rollupCreator = await ethers.getContractAt( 'RollupCreator', ( await deployments.get('RollupCreator') ).address ) const rollupLogic = await rollupCreator.rollupTemplate() const TransparentProxy = await ethers.getContractFactory( 'TransparentUpgradeableProxy' ) const proxy = await TransparentProxy.deploy( rollupLogic, await accounts[9].getAddress(), '0x' ) const freshRollup = (await ethers.getContractFactory('Rollup')).attach( proxy.address ) await expect( freshRollup.initialize( initialVmState, [0, 0, 0, 0], ZERO_ADDR, ZERO_ADDR, zerobytes32, [ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR], [ZERO_ADDR, ZERO_ADDR], [0, 0] ) ).to.be.revertedWith('FACET_0_NOT_CONTRACT') const adminFacet = await ( await ethers.getContractFactory('RollupAdminFacet') ).deploy() await expect( freshRollup.initialize( initialVmState, [0, 0, 0, 0], ZERO_ADDR, ZERO_ADDR, zerobytes32, [ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR], [adminFacet.address, ZERO_ADDR], [0, 0] ) ).to.be.revertedWith('FACET_1_NOT_CONTRACT') await expect( freshRollup.initialize( initialVmState, [0, 0, 0, 0], ZERO_ADDR, ZERO_ADDR, zerobytes32, [ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR, ZERO_ADDR], [adminFacet.address, adminFacet.address], [0, 0] ) ).to.be.revertedWith('FAIL_INIT_FACET') }) it('should assign facets correctly', async function () { const expectedAdmin = (await deployments.get('RollupAdminFacet')).address const expectedUser = (await deployments.get('RollupUserFacet')).address const RollupDispatch = await ethers.getContractFactory('Rollup') const rollupDispatch = RollupDispatch.attach(rollup.rollup.address) const actualFacets = await rollupDispatch.getFacets() expect(actualFacets[0]).to.equal(expectedAdmin) expect(actualFacets[1]).to.equal(expectedUser) }) it('should validate facets during dispatch', async function () { await expect( accounts[1].sendTransaction({ to: rollup.rollup.address, data: '0x', }) ).to.be.revertedWith('NO_FUNC_SIG') const RollupDispatch = await ethers.getContractFactory('Rollup') const rollupDispatch = RollupDispatch.attach(rollup.rollup.address) const initialFacets = await rollupDispatch.getFacets() // we set the user facet to address(0) await rollupAdmin.setFacets(initialFacets[0], ZERO_ADDR) await expect( accounts[1].sendTransaction({ to: rollup.rollup.address, data: '0x123123123123', }) ).to.be.revertedWith('TARGET_NOT_CONTRACT') // reset user facet to original value await rollupAdmin.setFacets(initialFacets[0], initialFacets[1]) }) it('should place stake', async function () { const stake = await rollup.currentRequiredStake() const tx = await rollup.newStake({ value: stake }) const receipt = await tx.wait() const staker = await rollup.rollup.getStakerAddress(0) expect(staker.toLowerCase()).to.equal( (await accounts[8].getAddress()).toLowerCase() ) const blockCreated = await rollup.rollup.lastStakeBlock() expect(blockCreated).to.equal(receipt.blockNumber) }) it('should place stake on new node', async function () { await tryAdvanceChain(minimumAssertionPeriod) const { node } = await makeSimpleNode(rollup, prevNode) prevNode = node }) it('should let a new staker place on existing node', async function () { await rollup.connect(accounts[1]).newStake({ value: 10 }) await rollup.connect(accounts[1]).stakeOnExistingNode(1, prevNode.nodeHash) }) it('should move stake to a new node', async function () { await tryAdvanceChain(minimumAssertionPeriod) const { node } = await makeSimpleNode(rollup, prevNode) prevNode = node }) it('should let the second staker place on the new node', async function () { await rollup.connect(accounts[1]).stakeOnExistingNode(2, prevNode.nodeHash) }) it('should confirm node', async function () { await tryAdvanceChain(confirmationPeriodBlocks * 2) await rollup.confirmNextNode(zerobytes32, 0, [], zerobytes32, 0) }) it('should confirm next node', async function () { await tryAdvanceChain(minimumAssertionPeriod) await rollup.confirmNextNode(zerobytes32, 0, [], zerobytes32, 0) }) let challengedNode: Node let validNode: Node it('should let the first staker make another node', async function () { await tryAdvanceChain(minimumAssertionPeriod) const { node } = await makeSimpleNode(rollup, prevNode) challengedNode = node validNode = node }) let challengerNode: Node it('should let the second staker make a conflicting node', async function () { await tryAdvanceChain(minimumAssertionPeriod) const { node } = await makeSimpleNode( rollup.connect(accounts[1]), prevNode, validNode ) challengerNode = node }) it('should fail to confirm first staker node', async function () { await advancePastAssertion(challengedNode.assertion) await expect( rollup.confirmNextNode(zerobytes32, 0, [], zerobytes32, 0) ).to.be.revertedWith('NOT_ALL_STAKED') }) let challenge: Challenge it('should initiate a challenge', async function () { const tx = rollup.createChallenge( await accounts[8].getAddress(), 3, await accounts[1].getAddress(), 4, challengedNode, challengerNode ) const receipt = await (await tx).wait() const ev = rollup.rollup.interface.parseLog( receipt.logs![receipt.logs!.length - 1] ) expect(ev.name).to.equal('RollupChallengeStarted') const parsedEv = ev as any as { args: { challengeContract: string } } const Challenge = await ethers.getContractFactory('Challenge') challenge = Challenge.attach(parsedEv.args.challengeContract) }) it('should make a new node', async function () { const { node } = await makeSimpleNode(rollup, validNode) challengedNode = node }) it('new staker should make a conflicting node', async function () { const stake = await rollup.currentRequiredStake() await rollup.connect(accounts[2]).newStake({ value: stake }) await rollup.connect(accounts[2]).stakeOnExistingNode(3, validNode.nodeHash) const { node } = await makeSimpleNode( rollup.connect(accounts[2]), validNode, challengedNode ) challengerNode = node }) it('asserter should win via timeout', async function () { await advancePastAssertion(challengedNode.assertion) await challenge.connect(accounts[1]).timeout() }) it('confirm first staker node', async function () { await rollup.confirmNextNode(zerobytes32, 0, [], zerobytes32, 0) }) it('should reject out of order second node', async function () { await rollup.rejectNextNode(stakeToken) }) it('should initiate another challenge', async function () { const tx = rollup.createChallenge( await accounts[8].getAddress(), 5, await accounts[2].getAddress(), 6, challengedNode, challengerNode ) const receipt = await (await tx).wait() const ev = rollup.rollup.interface.parseLog( receipt.logs![receipt.logs!.length - 1] ) expect(ev.name).to.equal('RollupChallengeStarted') const parsedEv = ev as any as { args: { challengeContract: string } } const Challenge = await ethers.getContractFactory('Challenge') challenge = Challenge.attach(parsedEv.args.challengeContract) await expect( rollup.rollup.completeChallenge( await accounts[1].getAddress(), await accounts[3].getAddress() ) ).to.be.revertedWith('NO_CHAL') await expect( rollup.rollup.completeChallenge( await accounts[8].getAddress(), await accounts[1].getAddress() ) ).to.be.revertedWith('DIFF_IN_CHAL') await expect( rollup.rollup.completeChallenge( await accounts[8].getAddress(), await accounts[2].getAddress() ) ).to.be.revertedWith('WRONG_SENDER') }) it('challenger should reply in challenge', async function () { const chunks = Array(401).fill(zerobytes32) chunks[0] = challengeHash(challengedNode.assertion.beforeState) await bisectExecution( challenge.connect(accounts[2]), [], 0, challengedNode.assertion, chunks ) }) it('challenger should win via timeout', async function () { await advancePastAssertion(challengedNode.assertion) await challenge.timeout() }) it('should reject out of order second node', async function () { await rollup.rejectNextNode(await accounts[2].getAddress()) }) it('confirm next node', async function () { await tryAdvanceChain(confirmationPeriodBlocks) await rollup.confirmNextNode(zerobytes32, 0, [], zerobytes32, 0) }) it('should add and remove stakes correctly', async function () { /* RollupUser functions that alter stake and their respective Core logic user: newStake core: createNewStake user: addToDeposit core: increaseStakeBy user: reduceDeposit core: reduceStakeTo user: returnOldDeposit core: withdrawStaker user: withdrawStakerFunds core: withdrawFunds */ const initialStake = await rollup.rollup.amountStaked( await accounts[2].getAddress() ) await rollup.connect(accounts[2]).reduceDeposit(initialStake) await expect( rollup.connect(accounts[2]).reduceDeposit(initialStake.add(1)) ).to.be.revertedWith('TOO_LITTLE_STAKE') await rollup .connect(accounts[2]) .addToDeposit(await accounts[2].getAddress(), { value: 5 }) await rollup.connect(accounts[2]).reduceDeposit(5) const prevBalance = await accounts[2].getBalance() const prevWithdrawablefunds = await rollup.rollup.withdrawableFunds( await accounts[2].getAddress() ) const tx = await rollup.rollup .connect(accounts[2]) .withdrawStakerFunds(await accounts[2].getAddress()) const receipt = await tx.wait() const gasPaid = receipt.gasUsed.mul(receipt.effectiveGasPrice) const postBalance = await accounts[2].getBalance() const postWithdrawablefunds = await rollup.rollup.withdrawableFunds( await accounts[2].getAddress() ) expect(postWithdrawablefunds).to.equal(0) expect(postBalance.add(gasPaid)).to.equal( prevBalance.add(prevWithdrawablefunds) ) // this gets deposit and removes staker await rollup.rollup .connect(accounts[2]) .returnOldDeposit(await accounts[2].getAddress()) // all stake is now removed }) it('should pause the contracts then resume', async function () { const prevIsPaused = await rollup.rollup.paused() expect(prevIsPaused).to.equal(false) await rollupAdmin.pause() const postIsPaused = await rollup.rollup.paused() expect(postIsPaused).to.equal(true) await expect( rollup .connect(accounts[2]) .addToDeposit(await accounts[2].getAddress(), { value: 5 }) ).to.be.revertedWith('Pausable: paused') await rollupAdmin.resume() }) it('should allow admin to alter rollup while paused', async function () { const prevLatestConfirmed = await rollup.rollup.latestConfirmed() expect(prevLatestConfirmed.toNumber()).to.equal(6) // prevNode is prevLatestConfirmed prevNode = challengerNode const stake = await rollup.currentRequiredStake() await rollup.newStake({ value: stake }) const { node: node1 } = await makeSimpleNode(rollup, prevNode) const node1Num = await rollup.rollup.latestNodeCreated() await tryAdvanceChain(minimumAssertionPeriod) await rollup.connect(accounts[1]).newStake({ value: stake }) const { node: node2 } = await makeSimpleNode( rollup.connect(accounts[1]), prevNode, node1 ) const node2Num = await rollup.rollup.latestNodeCreated() const tx = await rollup.createChallenge( await accounts[8].getAddress(), node1Num, await accounts[1].getAddress(), node2Num, node1, node2 ) const receipt = await tx.wait() const ev = rollup.rollup.interface.parseLog( receipt.logs![receipt.logs!.length - 1] ) expect(ev.name).to.equal('RollupChallengeStarted') const parsedEv = ev as any as { args: { challengeContract: string } } const Challenge = await ethers.getContractFactory('Challenge') challenge = Challenge.attach(parsedEv.args.challengeContract) const preCode = await ethers.provider.getCode(challenge.address) expect(preCode).to.not.equal('0x') await expect( rollupAdmin.forceResolveChallenge( [await accounts[8].getAddress()], [await accounts[1].getAddress()] ) ).to.be.revertedWith('Pausable: not paused') await expect( rollup.createChallenge( await accounts[8].getAddress(), node1Num, await accounts[1].getAddress(), node2Num, node1, node2 ) ).to.be.revertedWith('IN_CHAL') await rollupAdmin.pause() await rollupAdmin.forceResolveChallenge( [await accounts[8].getAddress()], [await accounts[1].getAddress()] ) // challenge should have been destroyed const postCode = await ethers.provider.getCode(challenge.address) expect(postCode).to.equal('0x') const challengeA = await rollupAdmin.currentChallenge( await accounts[8].getAddress() ) const challengeB = await rollupAdmin.currentChallenge( await accounts[1].getAddress() ) expect(challengeA).to.equal(ZERO_ADDR) expect(challengeB).to.equal(ZERO_ADDR) await rollupAdmin.forceRefundStaker([ await accounts[8].getAddress(), await accounts[1].getAddress(), ]) const block = await ethers.provider.getBlock('latest') const assertion = makeSimpleAssertion( prevNode.assertion.afterState, (block.number - prevNode.proposedBlock + 1) * avmGasSpeedLimitPerBlock ) const hasSibling = true const newNodeHash = async () => nodeHash( hasSibling, await rollup.rollup.getNodeHash( await rollup.rollup.latestNodeCreated() ), assertionExecutionHash(assertion), zerobytes32 ) const forceNode1Hash = await newNodeHash() const { node: forceCreatedNode1 } = await forceCreateNode( rollupAdmin, forceNode1Hash, assertion, '0x', prevNode, prevLatestConfirmed ) expect(forceCreatedNode1.assertion).to.eql(assertion) const adminNodeNum = await rollup.rollup.latestNodeCreated() const midLatestConfirmed = await rollup.rollup.latestConfirmed() expect(midLatestConfirmed.toNumber()).to.equal(6) expect(adminNodeNum.toNumber()).to.equal(node2Num.toNumber() + 1) await forceCreateNode( rollupAdmin, await newNodeHash(), assertion, '0x', prevNode, prevLatestConfirmed ) const postLatestCreated = await rollup.rollup.latestNodeCreated() const sends: Array<BytesLike> = [] const messageData = ethers.utils.concat(sends) const messageLengths = sends.map(msg => msg.length) await rollupAdmin.forceConfirmNode( adminNodeNum, zerobytes32, messageData, messageLengths, 0, zerobytes32, 0 ) const postLatestConfirmed = await rollup.rollup.latestConfirmed() expect(postLatestCreated).to.equal(adminNodeNum.add(1)) expect(postLatestConfirmed).to.equal(adminNodeNum) await rollupAdmin.resume() // should create node after resuming prevNode = forceCreatedNode1 await tryAdvanceChain(minimumAssertionPeriod) await expect( rollup .connect(accounts[1]) .newStake({ value: await rollup.currentRequiredStake() }) ).to.be.revertedWith('STAKER_IS_ZOMBIE') await expect( makeSimpleNode(rollup.connect(accounts[1]), prevNode) ).to.be.revertedWith('NOT_STAKED') await rollup.rollup.connect(accounts[1]).removeOldZombies(0) await rollup .connect(accounts[1]) .newStake({ value: await rollup.currentRequiredStake() }) await makeSimpleNode(rollup.connect(accounts[1]), prevNode) }) it('should not allow node to be re initialized', async function () { const Node = await ethers.getContractFactory('Node') const node = await Node.deploy() await expect( node.initialize(ZERO_ADDR, zerobytes32, zerobytes32, zerobytes32, 0, 0) ).to.be.revertedWith('ROLLUP_ADDR') await node.initialize( await accounts[0].getAddress(), zerobytes32, zerobytes32, zerobytes32, 0, 0 ) await expect( node.initialize( rollup.rollup.address, zerobytes32, zerobytes32, zerobytes32, 0, 0 ) ).to.be.revertedWith('ALREADY_INIT') await expect( node.connect(accounts[1]).addStaker(await accounts[1].getAddress()) ).to.be.revertedWith('ROLLUP_ONLY') node.connect(accounts[0]).addStaker(await accounts[1].getAddress()) await expect( node.connect(accounts[0]).addStaker(await accounts[1].getAddress()) ).to.be.revertedWith('ALREADY_STAKED') }) it('should initialize a fresh rollup', async function () { rollup = await initNewRollup() }) it('should place stake', async function () { const stake = await rollup.currentRequiredStake() await rollup.newStake({ value: stake }) }) const limitSends = makeSends(100) it('should move stake to a new node with maximum # of sends', async function () { await tryAdvanceChain(minimumAssertionPeriod) const { node } = await makeNode(rollup, prevNode, undefined, limitSends) prevNode = node }) it('should confirm node with sends and it should take under 3 million gas [ @skip-on-coverage ]', async function () { await tryAdvanceChain(confirmationPeriodBlocks * 2) const { beforeState: prevExecState, afterState: postExecState } = prevNode.assertion const res = await rollup.confirmNextNode( prevExecState.sendAcc, prevExecState.sendCount, limitSends, postExecState.logAcc, postExecState.logCount ) const rec = await res.wait() console.log('Gas used in 100 send assertion:', rec.gasUsed.toString()) expect(rec.gasUsed.lt(BigNumber.from(3000000))).to.be.true }) const aboveLimitSends = makeSends(101, 101) it('should revert when trying to make an assertion with too many sends', async function () { await tryAdvanceChain(minimumAssertionPeriod) await expect( makeNode(rollup, prevNode, undefined, aboveLimitSends) ).to.be.revertedWith('TOO_MANY_SENDS') }) })
the_stack
import bigInt from 'big-integer'; import { range } from 'd3-array'; import { generateDate, randomNumber } from './utils'; export const generateData = (count, minVal = 1, maxVal = 50) => range(count) .map(i => ({ id: (i + 1).toString(), key: generateDate(i), data: randomNumber(minVal, maxVal) })) .reverse(); // generateData(100); export const largeDateData = [ { id: '100', key: new Date('2019-11-24T08:00:00.000Z'), data: 39 }, { id: '99', key: new Date('2019-11-25T08:00:00.000Z'), data: 5 }, { id: '98', key: new Date('2019-11-26T08:00:00.000Z'), data: 12 }, { id: '97', key: new Date('2019-11-27T08:00:00.000Z'), data: 39 }, { id: '96', key: new Date('2019-11-28T08:00:00.000Z'), data: 17 }, { id: '95', key: new Date('2019-11-29T08:00:00.000Z'), data: 22 }, { id: '94', key: new Date('2019-11-30T08:00:00.000Z'), data: 12 }, { id: '93', key: new Date('2019-12-01T08:00:00.000Z'), data: 43 }, { id: '92', key: new Date('2019-12-02T08:00:00.000Z'), data: 40 }, { id: '91', key: new Date('2019-12-03T08:00:00.000Z'), data: 47 }, { id: '90', key: new Date('2019-12-04T08:00:00.000Z'), data: 15 }, { id: '89', key: new Date('2019-12-05T08:00:00.000Z'), data: 31 }, { id: '88', key: new Date('2019-12-06T08:00:00.000Z'), data: 42 }, { id: '87', key: new Date('2019-12-07T08:00:00.000Z'), data: 37 }, { id: '86', key: new Date('2019-12-08T08:00:00.000Z'), data: 4 }, { id: '85', key: new Date('2019-12-09T08:00:00.000Z'), data: 38 }, { id: '84', key: new Date('2019-12-10T08:00:00.000Z'), data: 32 }, { id: '83', key: new Date('2019-12-11T08:00:00.000Z'), data: 27 }, { id: '82', key: new Date('2019-12-12T08:00:00.000Z'), data: 22 }, { id: '81', key: new Date('2019-12-13T08:00:00.000Z'), data: 45 }, { id: '80', key: new Date('2019-12-14T08:00:00.000Z'), data: 42 }, { id: '79', key: new Date('2019-12-15T08:00:00.000Z'), data: 36 }, { id: '78', key: new Date('2019-12-16T08:00:00.000Z'), data: 20 }, { id: '77', key: new Date('2019-12-17T08:00:00.000Z'), data: 34 }, { id: '76', key: new Date('2019-12-18T08:00:00.000Z'), data: 24 }, { id: '75', key: new Date('2019-12-19T08:00:00.000Z'), data: 42 }, { id: '74', key: new Date('2019-12-20T08:00:00.000Z'), data: 23 }, { id: '73', key: new Date('2019-12-21T08:00:00.000Z'), data: 49 }, { id: '72', key: new Date('2019-12-22T08:00:00.000Z'), data: 12 }, { id: '71', key: new Date('2019-12-23T08:00:00.000Z'), data: 29 }, { id: '70', key: new Date('2019-12-24T08:00:00.000Z'), data: 1 }, { id: '69', key: new Date('2019-12-25T08:00:00.000Z'), data: 42 }, { id: '68', key: new Date('2019-12-26T08:00:00.000Z'), data: 24 }, { id: '67', key: new Date('2019-12-27T08:00:00.000Z'), data: 40 }, { id: '66', key: new Date('2019-12-28T08:00:00.000Z'), data: 41 }, { id: '65', key: new Date('2019-12-29T08:00:00.000Z'), data: 39 }, { id: '64', key: new Date('2019-12-30T08:00:00.000Z'), data: 2 }, { id: '63', key: new Date('2019-12-31T08:00:00.000Z'), data: 3 }, { id: '62', key: new Date('2020-01-01T08:00:00.000Z'), data: 23 }, { id: '61', key: new Date('2020-01-02T08:00:00.000Z'), data: 31 }, { id: '60', key: new Date('2020-01-03T08:00:00.000Z'), data: 46 }, { id: '59', key: new Date('2020-01-04T08:00:00.000Z'), data: 16 }, { id: '58', key: new Date('2020-01-05T08:00:00.000Z'), data: 30 }, { id: '57', key: new Date('2020-01-06T08:00:00.000Z'), data: 23 }, { id: '56', key: new Date('2020-01-07T08:00:00.000Z'), data: 18 }, { id: '55', key: new Date('2020-01-08T08:00:00.000Z'), data: 14 }, { id: '54', key: new Date('2020-01-09T08:00:00.000Z'), data: 43 }, { id: '53', key: new Date('2020-01-10T08:00:00.000Z'), data: 4 }, { id: '52', key: new Date('2020-01-11T08:00:00.000Z'), data: 20 }, { id: '51', key: new Date('2020-01-12T08:00:00.000Z'), data: 23 }, { id: '50', key: new Date('2020-01-13T08:00:00.000Z'), data: 25 }, { id: '49', key: new Date('2020-01-14T08:00:00.000Z'), data: 24 }, { id: '48', key: new Date('2020-01-15T08:00:00.000Z'), data: 6 }, { id: '47', key: new Date('2020-01-16T08:00:00.000Z'), data: 41 }, { id: '46', key: new Date('2020-01-17T08:00:00.000Z'), data: 10 }, { id: '45', key: new Date('2020-01-18T08:00:00.000Z'), data: 39 }, { id: '44', key: new Date('2020-01-19T08:00:00.000Z'), data: 48 }, { id: '43', key: new Date('2020-01-20T08:00:00.000Z'), data: 45 }, { id: '42', key: new Date('2020-01-21T08:00:00.000Z'), data: 29 }, { id: '41', key: new Date('2020-01-22T08:00:00.000Z'), data: 18 }, { id: '40', key: new Date('2020-01-23T08:00:00.000Z'), data: 18 }, { id: '39', key: new Date('2020-01-24T08:00:00.000Z'), data: 23 }, { id: '38', key: new Date('2020-01-25T08:00:00.000Z'), data: 46 }, { id: '37', key: new Date('2020-01-26T08:00:00.000Z'), data: 36 }, { id: '36', key: new Date('2020-01-27T08:00:00.000Z'), data: 1 }, { id: '35', key: new Date('2020-01-28T08:00:00.000Z'), data: 7 }, { id: '34', key: new Date('2020-01-29T08:00:00.000Z'), data: 5 }, { id: '33', key: new Date('2020-01-30T08:00:00.000Z'), data: 41 }, { id: '32', key: new Date('2020-01-31T08:00:00.000Z'), data: 29 }, { id: '31', key: new Date('2020-02-01T08:00:00.000Z'), data: 41 }, { id: '30', key: new Date('2020-02-02T08:00:00.000Z'), data: 11 }, { id: '29', key: new Date('2020-02-03T08:00:00.000Z'), data: 33 }, { id: '28', key: new Date('2020-02-04T08:00:00.000Z'), data: 35 }, { id: '27', key: new Date('2020-02-05T08:00:00.000Z'), data: 38 }, { id: '26', key: new Date('2020-02-06T08:00:00.000Z'), data: 49 }, { id: '25', key: new Date('2020-02-07T08:00:00.000Z'), data: 22 }, { id: '24', key: new Date('2020-02-08T08:00:00.000Z'), data: 38 }, { id: '23', key: new Date('2020-02-09T08:00:00.000Z'), data: 6 }, { id: '22', key: new Date('2020-02-10T08:00:00.000Z'), data: 15 }, { id: '21', key: new Date('2020-02-11T08:00:00.000Z'), data: 37 }, { id: '20', key: new Date('2020-02-12T08:00:00.000Z'), data: 18 }, { id: '19', key: new Date('2020-02-13T08:00:00.000Z'), data: 20 }, { id: '18', key: new Date('2020-02-14T08:00:00.000Z'), data: 38 }, { id: '17', key: new Date('2020-02-15T08:00:00.000Z'), data: 48 }, { id: '16', key: new Date('2020-02-16T08:00:00.000Z'), data: 31 }, { id: '15', key: new Date('2020-02-17T08:00:00.000Z'), data: 20 }, { id: '14', key: new Date('2020-02-18T08:00:00.000Z'), data: 7 }, { id: '13', key: new Date('2020-02-19T08:00:00.000Z'), data: 48 }, { id: '12', key: new Date('2020-02-20T08:00:00.000Z'), data: 35 }, { id: '11', key: new Date('2020-02-21T08:00:00.000Z'), data: 9 }, { id: '10', key: new Date('2020-02-22T08:00:00.000Z'), data: 3 }, { id: '9', key: new Date('2020-02-23T08:00:00.000Z'), data: 10 }, { id: '8', key: new Date('2020-02-24T08:00:00.000Z'), data: 25 }, { id: '7', key: new Date('2020-02-25T08:00:00.000Z'), data: 31 }, { id: '6', key: new Date('2020-02-26T08:00:00.000Z'), data: 39 }, { id: '5', key: new Date('2020-02-27T08:00:00.000Z'), data: 19 }, { id: '4', key: new Date('2020-02-28T08:00:00.000Z'), data: 17 }, { id: '3', key: new Date('2020-02-29T08:00:00.000Z'), data: 25 }, { id: '2', key: new Date('2020-03-01T08:00:00.000Z'), data: 45 }, { id: '1', key: new Date('2020-03-02T08:00:00.000Z'), data: 25 } ]; // generateData(50); export const medDateData = [ { id: '50', key: new Date('2020-01-13T08:00:00.000Z'), data: 16 }, { id: '49', key: new Date('2020-01-14T08:00:00.000Z'), data: 44 }, { id: '48', key: new Date('2020-01-15T08:00:00.000Z'), data: 12 }, { id: '47', key: new Date('2020-01-16T08:00:00.000Z'), data: 26 }, { id: '46', key: new Date('2020-01-17T08:00:00.000Z'), data: 41 }, { id: '45', key: new Date('2020-01-18T08:00:00.000Z'), data: 25 }, { id: '44', key: new Date('2020-01-19T08:00:00.000Z'), data: 24 }, { id: '43', key: new Date('2020-01-20T08:00:00.000Z'), data: 23 }, { id: '42', key: new Date('2020-01-21T08:00:00.000Z'), data: 26 }, { id: '41', key: new Date('2020-01-22T08:00:00.000Z'), data: 21 }, { id: '40', key: new Date('2020-01-23T08:00:00.000Z'), data: 32 }, { id: '39', key: new Date('2020-01-24T08:00:00.000Z'), data: 11 }, { id: '38', key: new Date('2020-01-25T08:00:00.000Z'), data: 33 }, { id: '37', key: new Date('2020-01-26T08:00:00.000Z'), data: 3 }, { id: '36', key: new Date('2020-01-27T08:00:00.000Z'), data: 7 }, { id: '35', key: new Date('2020-01-28T08:00:00.000Z'), data: 8 }, { id: '34', key: new Date('2020-01-29T08:00:00.000Z'), data: 9 }, { id: '33', key: new Date('2020-01-30T08:00:00.000Z'), data: 7 }, { id: '32', key: new Date('2020-01-31T08:00:00.000Z'), data: 9 }, { id: '31', key: new Date('2020-02-01T08:00:00.000Z'), data: 50 }, { id: '30', key: new Date('2020-02-02T08:00:00.000Z'), data: 19 }, { id: '29', key: new Date('2020-02-03T08:00:00.000Z'), data: 48 }, { id: '28', key: new Date('2020-02-04T08:00:00.000Z'), data: 15 }, { id: '27', key: new Date('2020-02-05T08:00:00.000Z'), data: 42 }, { id: '26', key: new Date('2020-02-06T08:00:00.000Z'), data: 29 }, { id: '25', key: new Date('2020-02-07T08:00:00.000Z'), data: 40 }, { id: '24', key: new Date('2020-02-08T08:00:00.000Z'), data: 34 }, { id: '23', key: new Date('2020-02-09T08:00:00.000Z'), data: 4 }, { id: '22', key: new Date('2020-02-10T08:00:00.000Z'), data: 24 }, { id: '21', key: new Date('2020-02-11T08:00:00.000Z'), data: 1 }, { id: '20', key: new Date('2020-02-12T08:00:00.000Z'), data: 35 }, { id: '19', key: new Date('2020-02-13T08:00:00.000Z'), data: 26 }, { id: '18', key: new Date('2020-02-14T08:00:00.000Z'), data: 8 }, { id: '17', key: new Date('2020-02-15T08:00:00.000Z'), data: 30 }, { id: '16', key: new Date('2020-02-16T08:00:00.000Z'), data: 5 }, { id: '15', key: new Date('2020-02-17T08:00:00.000Z'), data: 8 }, { id: '14', key: new Date('2020-02-18T08:00:00.000Z'), data: 1 }, { id: '13', key: new Date('2020-02-19T08:00:00.000Z'), data: 36 }, { id: '12', key: new Date('2020-02-20T08:00:00.000Z'), data: 25 }, { id: '11', key: new Date('2020-02-21T08:00:00.000Z'), data: 34 }, { id: '10', key: new Date('2020-02-22T08:00:00.000Z'), data: 42 }, { id: '9', key: new Date('2020-02-23T08:00:00.000Z'), data: 38 }, { id: '8', key: new Date('2020-02-24T08:00:00.000Z'), data: 23 }, { id: '7', key: new Date('2020-02-25T08:00:00.000Z'), data: 10 }, { id: '6', key: new Date('2020-02-26T08:00:00.000Z'), data: 16 }, { id: '5', key: new Date('2020-02-27T08:00:00.000Z'), data: 26 }, { id: '4', key: new Date('2020-02-28T08:00:00.000Z'), data: 45 }, { id: '3', key: new Date('2020-02-29T08:00:00.000Z'), data: 39 }, { id: '2', key: new Date('2020-03-01T08:00:00.000Z'), data: 38 }, { id: '1', key: new Date('2020-03-02T08:00:00.000Z'), data: 17 } ]; // generateData(15); export const smallDateData = [ { id: '15', key: new Date('2020-02-17T08:00:00.000Z'), data: 4 }, { id: '14', key: new Date('2020-02-18T08:00:00.000Z'), data: 16 }, { id: '13', key: new Date('2020-02-19T08:00:00.000Z'), data: 39 }, { id: '12', key: new Date('2020-02-20T08:00:00.000Z'), data: 10 }, { id: '11', key: new Date('2020-02-21T08:00:00.000Z'), data: 37 }, { id: '10', key: new Date('2020-02-22T08:00:00.000Z'), data: 41 }, { id: '9', key: new Date('2020-02-23T08:00:00.000Z'), data: 31 }, { id: '8', key: new Date('2020-02-24T08:00:00.000Z'), data: 47 }, { id: '7', key: new Date('2020-02-25T08:00:00.000Z'), data: 47 }, { id: '6', key: new Date('2020-02-26T08:00:00.000Z'), data: 8 }, { id: '5', key: new Date('2020-02-27T08:00:00.000Z'), data: 35 }, { id: '4', key: new Date('2020-02-28T08:00:00.000Z'), data: 32 }, { id: '3', key: new Date('2020-02-29T08:00:00.000Z'), data: 17 }, { id: '2', key: new Date('2020-03-01T08:00:00.000Z'), data: 15 }, { id: '1', key: new Date('2020-03-02T08:00:00.000Z'), data: 50 } ]; // generateDateData() from sonar.ts export const singleDateData = [ { id: '0', key: new Date('2020-02-17T08:00:00.000Z'), data: 10 }, { id: '1', key: new Date('2020-02-21T08:00:00.000Z'), data: 18 }, { id: '2', key: new Date('2020-02-26T08:00:00.000Z'), data: 2 }, { id: '3', key: new Date('2020-02-29T08:00:00.000Z'), data: 10 } ]; // export const multiDateData = [ // { // key: 'Threat Intel', // data: generateDateData() // }, // { // key: 'DLP', // data: generateDateData() // }, // { // key: 'Syslog', // data: generateDateData() // } // ]; export const multiDateData = [ { key: 'Threat Intel', data: [ { key: new Date('2020-02-17T08:00:00.000Z'), id: '0', data: 18 }, { key: new Date('2020-02-21T08:00:00.000Z'), id: '1', data: 3 }, { key: new Date('2020-02-26T08:00:00.000Z'), id: '2', data: 14 }, { key: new Date('2020-02-29T08:00:00.000Z'), id: '3', data: 18 } ] }, { key: 'DLP', data: [ { key: new Date('2020-02-17T08:00:00.000Z'), id: '0', data: 12 }, { key: new Date('2020-02-21T08:00:00.000Z'), id: '1', data: 8 }, { key: new Date('2020-02-26T08:00:00.000Z'), id: '2', data: 7 }, { key: new Date('2020-02-29T08:00:00.000Z'), id: '3', data: 16 } ] }, { key: 'Syslog', data: [ { key: new Date('2020-02-17T08:00:00.000Z'), id: '0', data: 12 }, { key: new Date('2020-02-21T08:00:00.000Z'), id: '1', data: 9 }, { key: new Date('2020-02-26T08:00:00.000Z'), id: '2', data: 4 }, { key: new Date('2020-02-29T08:00:00.000Z'), id: '3', data: 1 } ] } ]; // export const nonZeroDateData = [ // { // key: generateDate(14), // data: [5, 10] // }, // { // key: generateDate(10), // data: [8, 14] // }, // { // key: generateDate(5), // data: [5, 6] // }, // { // key: generateDate(2), // data: [10, 18] // } // ]; export const nonZeroDateData = [ { key: new Date('2020-02-17T08:00:00.000Z'), data: [5, 10] }, { key: new Date('2020-02-21T08:00:00.000Z'), data: [8, 14] }, { key: new Date('2020-02-26T08:00:00.000Z'), data: [5, 6] }, { key: new Date('2020-02-29T08:00:00.000Z'), data: [10, 18] } ]; // export const singleDateBigIntData = [ // { // key: generateDate(14), // data: bigInt(98476124342) // }, // { // key: generateDate(10), // data: bigInt(76129235932) // }, // { // key: generateDate(5), // data: bigInt(60812341342) // }, // { // key: generateDate(2), // data: bigInt(76129235932) // } // ]; export const singleDateBigIntData = [ { key: new Date('2020-02-17T08:00:00.000Z'), data: bigInt(98476124342) }, { key: new Date('2020-02-21T08:00:00.000Z'), data: bigInt(76129235932) }, { key: new Date('2020-02-26T08:00:00.000Z'), data: bigInt(60812341342) }, { key: new Date('2020-02-29T08:00:00.000Z'), data: bigInt(76129235932) } ];
the_stack
import {Attribute, Entity, Table} from '@typedorm/common'; import {Organisation} from '@typedorm/core/__mocks__/organisation'; import {table} from '@typedorm/core/__mocks__/table'; import {User} from '@typedorm/core/__mocks__/user'; import {UserUniqueEmail} from '@typedorm/core/__mocks__/user-unique-email'; import {createTestConnection, resetTestConnection} from '@typedorm/testing'; import {ReadBatch} from '../../batch/read-batch'; import {WriteBatch} from '../../batch/write-batch'; import {Connection} from '../../connection/connection'; import {DocumentClientBatchTransformer} from '../document-client-batch-transformer'; jest.mock('uuid', () => ({ v4: jest.fn().mockReturnValue('66a7b3d6-323a-49b0-a12d-c99afff5005a'), validate: jest.fn().mockReturnValue(true), v5: jest.requireActual('uuid').v5, })); let connection: Connection; let dcBatchTransformer: DocumentClientBatchTransformer; beforeEach(() => { connection = createTestConnection({ entities: [User, Organisation, UserUniqueEmail], table, }); dcBatchTransformer = new DocumentClientBatchTransformer(connection); }); afterEach(() => { resetTestConnection(); }); test('correctly extends low order transformers', () => { expect(dcBatchTransformer.connection).toEqual(connection); }); /** * @group toDynamoWriteBatchItem */ test('transforms into batch write items', () => { const user1 = new User(); user1.id = '1'; user1.status = 'inactive'; user1.name = 'user 1'; const user2 = new UserUniqueEmail(); user2.id = '2'; user2.status = 'active'; user2.name = 'user 2'; user2.email = 'user@test.com'; const writeBatch = new WriteBatch().add([ // simple create item { create: { item: user1, }, }, // simple delete item { delete: { item: Organisation, primaryKey: { id: 'ORG_ID_1', }, }, }, // delete item that has one ore more unique attributes { delete: { item: UserUniqueEmail, primaryKey: { id: '3', }, }, }, // create item that has one or more unique attributes { create: { item: user2, }, }, ]); const transformed = dcBatchTransformer.toDynamoWriteBatchItems(writeBatch); expect(transformed).toMatchObject({ // items that can be processed as batch items // each item in the list represents new bath requests batchWriteRequestMapItems: [ { 'test-table': [ { PutRequest: { Item: { GSI1PK: 'USER#STATUS#inactive', GSI1SK: 'USER#user 1', PK: 'USER#1', SK: 'USER#1', __en: 'user', id: '1', name: 'user 1', status: 'inactive', }, }, }, { DeleteRequest: { Key: { PK: 'ORG#ORG_ID_1', SK: 'ORG#ORG_ID_1', }, }, }, ], }, ], lazyTransactionWriteItemListLoaderItems: [ // items that needs to be lazily resolved by managers { rawInput: { delete: { item: UserUniqueEmail, primaryKey: { id: '3', }, }, }, transformedInput: { entityClass: UserUniqueEmail, lazyLoadTransactionWriteItems: expect.any(Function), primaryKeyAttributes: { id: '3', }, }, }, ], transactionListItems: [ // list of transactItems input, that must be processed over the transaction api { rawInput: { create: { item: user2, }, }, transformedInput: [ { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, Item: { GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#user 2', PK: 'USER#2', SK: 'USER#2', __en: 'user-unique-email', email: 'user@test.com', id: '2', name: 'user 2', status: 'active', }, 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@test.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@test.com', }, TableName: 'test-table', }, }, ], }, ], }); expect(transformed.metadata).toMatchObject({ itemTransformHashMap: expect.any(Map), namespaceId: '66a7b3d6-323a-49b0-a12d-c99afff5005a', }); }); test('transforms requests into multiple batch requests when there are more than allowed items to write', () => { let largeBatchOfUsers = Array(60).fill({}); largeBatchOfUsers = largeBatchOfUsers.map((empty, index) => { const user = new User(); user.id = (++index).toString(); user.status = 'active'; user.name = `User ${index}`; return { create: { item: user, }, }; }); const writeBatch = new WriteBatch().add(largeBatchOfUsers); const transformed = dcBatchTransformer.toDynamoWriteBatchItems(writeBatch); expect(transformed.batchWriteRequestMapItems.length).toEqual(3); expect(transformed.batchWriteRequestMapItems[0][table.name].length).toEqual( 25 ); expect(transformed.batchWriteRequestMapItems[1][table.name].length).toEqual( 25 ); expect(transformed.batchWriteRequestMapItems[2][table.name].length).toEqual( 10 ); }); test('transforms requests of items with multiple tables', () => { resetTestConnection(); const oldUserTable = new Table({ name: 'old-user-table', partitionKey: 'PK', }); @Entity({ name: 'old-user', primaryKey: { partitionKey: 'OLD_USER#{{id}}', }, table: oldUserTable, }) class OldUser { @Attribute() id: string; } connection = createTestConnection({ entities: [User, OldUser], table, }); dcBatchTransformer = new DocumentClientBatchTransformer(connection); let largeBatchOfMixedUsers = Array(32).fill({}); largeBatchOfMixedUsers = largeBatchOfMixedUsers.map((empty, index) => { const user = new User(); user.id = index.toString(); user.status = 'active'; user.name = `User ${index}`; const oldUser = new OldUser(); oldUser.id = index.toString(); return { create: { // randomize request with mixed old and new users item: index % 2 === 0 ? user : oldUser, }, }; }); const writeBatch = new WriteBatch().add(largeBatchOfMixedUsers); const { batchWriteRequestMapItems, } = dcBatchTransformer.toDynamoWriteBatchItems(writeBatch); expect(batchWriteRequestMapItems.length).toEqual(2); expect(batchWriteRequestMapItems[0][table.name].length).toEqual(16); expect(batchWriteRequestMapItems[0][oldUserTable.name].length).toEqual(9); expect(batchWriteRequestMapItems[1][oldUserTable.name].length).toEqual(7); }); /** * @group toWriteBatchInputList */ test('reverse transforms batch item input in initial input', () => { // create mock item transform hash const user = new User(); user.id = '1111-1111'; user.status = 'active'; user.name = 'User 1'; const writeBatch = new WriteBatch().add([ { create: { item: user, }, }, { delete: { item: User, primaryKey: { id: '1111-1111', }, }, }, ]); const {metadata} = dcBatchTransformer.toDynamoWriteBatchItems(writeBatch); const original = dcBatchTransformer.toWriteBatchInputList( { 'test-table': [ { DeleteRequest: { Key: { PK: 'USER#1111-1111', SK: 'USER#1111-1111', }, }, }, { PutRequest: { Item: { __en: 'user', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#User 1', id: '1111-1111', name: 'User 1', PK: 'USER#1111-1111', SK: 'USER#1111-1111', status: 'active', }, }, }, ], }, { itemTransformHashMap: metadata.itemTransformHashMap, namespaceId: metadata.namespaceId, } ); expect(original).toEqual([ { delete: { item: User, primaryKey: { id: '1111-1111', }, }, }, { create: { item: { id: '1111-1111', name: 'User 1', status: 'active', }, }, }, ]); }); /** * @group toDynamoReadBatchItems */ test('transforms simple batch read items', () => { const transformed = dcBatchTransformer.toDynamoReadBatchItems( new ReadBatch().add([ { item: User, primaryKey: { id: '1', }, }, { item: User, primaryKey: { id: '2', }, }, ]) ); expect(transformed.batchRequestItemsList).toEqual([ { 'test-table': { Keys: [ { PK: 'USER#1', SK: 'USER#1', }, { PK: 'USER#2', SK: 'USER#2', }, ], }, }, ]); expect(transformed.metadata).toEqual({ itemTransformHashMap: expect.any(Map), namespaceId: '66a7b3d6-323a-49b0-a12d-c99afff5005a', }); }); test('transforms requests into multiple batch requests when there are more than allowed items to read', () => { let largeBatchOfItems = Array(120).fill({}); largeBatchOfItems = largeBatchOfItems.map((empty, index) => { return { item: User, primaryKey: { id: index.toString(), }, }; }); const readBatch = new ReadBatch().add(largeBatchOfItems); const transformed = dcBatchTransformer.toDynamoReadBatchItems(readBatch); expect(transformed.batchRequestItemsList.length).toEqual(2); expect(transformed.batchRequestItemsList[0][table.name].Keys.length).toEqual( 100 ); expect(transformed.batchRequestItemsList[1][table.name].Keys.length).toEqual( 20 ); }); test('transforms batch requests of items with multiple tables', () => { resetTestConnection(); const oldUserTable = new Table({ name: 'old-user-table', partitionKey: 'PK', }); @Entity({ name: 'old-user', primaryKey: { partitionKey: 'OLD_USER#{{id}}', }, table: oldUserTable, }) class OldUser { @Attribute() id: string; } connection = createTestConnection({ entities: [User, OldUser], table, }); dcBatchTransformer = new DocumentClientBatchTransformer(connection); let largeBatchOfMixedUsers = Array(132).fill({}); largeBatchOfMixedUsers = largeBatchOfMixedUsers.map((empty, index) => { const user = { item: User, primaryKey: { id: index.toString(), }, }; const oldUser = { item: OldUser, primaryKey: { id: index.toString(), }, }; return index % 2 === 0 ? user : oldUser; }); const readBatch = new ReadBatch().add(largeBatchOfMixedUsers); const transformed = dcBatchTransformer.toDynamoReadBatchItems(readBatch); expect(transformed.batchRequestItemsList).toMatchSnapshot(); expect(transformed.batchRequestItemsList.length).toEqual(2); expect(transformed.batchRequestItemsList[0][table.name].Keys.length).toEqual( 66 ); expect( transformed.batchRequestItemsList[0][oldUserTable.name].Keys.length ).toEqual(34); expect( transformed.batchRequestItemsList[1][oldUserTable.name].Keys.length ).toEqual(32); }); /** * @group toReadBatchInputList */ test('reverse transforms read batch item request', () => { const originalInput = [ { item: User, primaryKey: { id: '1', }, }, { item: User, primaryKey: { id: '2', }, }, ]; const readBatch = new ReadBatch().add(originalInput); const {metadata} = dcBatchTransformer.toDynamoReadBatchItems(readBatch); const transformedOriginal = dcBatchTransformer.toReadBatchInputList( { 'test-table': { Keys: [ { PK: 'USER#1', SK: 'USER#1', }, { PK: 'USER#2', SK: 'USER#2', }, ], }, }, { itemTransformHashMap: metadata.itemTransformHashMap, namespaceId: metadata.namespaceId, } ); expect(transformedOriginal).toEqual(originalInput); });
the_stack
import { Component, OnInit, TemplateRef, ChangeDetectionStrategy, Input, OnChanges, SimpleChanges} from "@angular/core"; import { IdprestapiService } from "../../idprestapi.service"; import { IdpService } from "../../idp-service.service"; import { IdpdataService } from "../../idpdata.service"; import { NgForm } from "@angular/forms"; import { FormsModule } from "@angular/forms"; import { Router } from "@angular/router"; import { Validators } from "@angular/forms"; import { ViewChild } from "@angular/core"; import { ParentFormConnectComponent } from "../../parent-form-connect/parent-form-connect.component"; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: "app-ant-ctrl", templateUrl: "./ant-ctrl.component.html", styleUrls: ["./ant-ctrl.component.css"] }) export class AntCtrlComponent implements OnInit { @Input() public formName: string; tempsecurityAnalysislist: any = ["App Scan"]; @Input() buildInfo: any = this.IdpdataService.data.buildInfo; @Input() tempObject: any = this.IdpdataService.data.checkboxStatus.buildInfo; formStatusObject: any = this.IdpdataService.data.formStatus; nameErrorMessage: any = ""; javalist: any = []; ejbList: any = []; warList: any = []; tempCodeAnalysis: any = ["sonar", "pmd", "checkStyle", "findBugs"]; checkBoxObject: any; distributionList: any = []; /* Constructor */ constructor( private IdpdataService: IdpdataService, private IdpService: IdpService, private IdprestapiService: IdprestapiService, private router: Router ) { this.IdpdataService.ejbVal = "false"; this.IdpdataService.warVal = "false"; this.IdpdataService.jarVal = "false"; if (this.formStatusObject.operation === "copy" || this.formStatusObject.operation === "edit") { this.checkCheckBox(); } if (this.buildInfo.modules.length === 0) { this.addItem(); } this.checkBoxObject = "on"; this.javaOptionList(); this.ejbOptionList(); this.warOptionList(); } setCheckBoxObject() { } /* Checks Code Analysis Status & sets flag */ checkCodeAnalysisOn(i) { if ( this.tempObject.modules[i].codeAnalysis === "on" ) { if ( this.buildInfo.modules[i].codeAnalysis[0] === "off" && this.buildInfo.modules[i].codeAnalysis[1] === "off" && this.buildInfo.modules[i].codeAnalysis[2] === "off" && this.buildInfo.modules[i].codeAnalysis[3] === "off") { this.IdpdataService.pa = false; } else { this.IdpdataService.pa = true; } } else { this.IdpdataService.pa = true; } } /* Sets default values for code_cov, Packaging, unit Testing */ setSomeValues1(i) { this.buildInfo.modules[i].javaMainClass = ""; this.buildInfo.modules[i].ejbDescriptor = ""; this.buildInfo.modules[i].warPackaging = ""; this.buildInfo.modules[i].compile = "off"; this.buildInfo.modules[i].unitTesting = "off"; this.buildInfo.modules[i].codeCoverage = "off"; this.buildInfo.modules[i].codeAnalysis[0] = "off"; this.buildInfo.modules[i].codeAnalysis[1] = "off"; this.buildInfo.modules[i].codeAnalysis[2] = "off"; this.buildInfo.modules[i].codeAnalysis[3] = "off"; this.tempObject.modules[i].chkjar = "off"; this.tempObject.modules[i].WARPackaging = "off"; return false; } /* Clear Code Analysis on unchecking */ clearCodeAnalysis(i) { this.buildInfo.modules[i].codeAnalysis = []; return "off"; } clearSonarqube() { console.log(this.buildInfo.modules[0]); this.buildInfo.modules[0].sonarUrl =""; this.buildInfo.modules[0].sonarUserName =""; this.buildInfo.modules[0].sonarPassword =""; this.buildInfo.modules[0].sonarProjectKey =""; this.buildInfo.modules[0].sonarProperties =""; return "off"; } /* Default Code Analysis, security Analysis status */ createCodeAnalysis(i) { this.buildInfo.modules[i].codeAnalysis = ["off" , "off" , "off" , "off"]; return "on"; } setContinuecontrolFalse() { this.IdpdataService.continuecontrol = false; return false; } setContinuecontrolTrue() { this.IdpdataService.continuecontrol = true; return false; } /* Setting custom build xml,compile for each module if selected */ setcustomBuildXml(i) { this.tempObject.modules[i].customBuildXml = "on"; return false; } setcodeAnalysisthree(i) { this.buildInfo.modules[i].codeAnalysis[3] = "off"; this.tempObject.modules[i].WARPackaging = "off"; return false; } setCompileOff(i) { this.setWarPack(i); return "off"; } setCustomBuildOn(i) { this.buildInfo.modules[i].javaMainClass = ""; this.buildInfo.modules[i].ejbDescriptor = ""; this.buildInfo.modules[i].warPackaging = ""; this.buildInfo.modules[i].compile = "off"; this.buildInfo.modules[i].unitTesting = "off"; this.buildInfo.modules[i].codeCoverage = "off"; this.buildInfo.modules[i].codeAnalysis[1] = "off"; this.buildInfo.modules[i].codeAnalysis[2] = "off"; this.buildInfo.modules[i].codeAnalysis[3] = "off"; this.tempObject.modules[i].chkjar = "off"; this.tempObject.modules[i].WARPackaging = "off"; return "on"; } setCustomBuildOff(i) { this.buildInfo.modules[i].customBuildXml = ""; this.buildInfo.modules[i].args = ""; return "off"; } setWarPack(i) { this.tempObject.modules[i].WARPackaging = "off"; this.buildInfo.modules[i].warPackaging = ""; return false; } setpaFalse() { this.IdpdataService.pa = false; return false; } setpaTrue() { this.IdpdataService.pa = true; return false; } setargsCustomBuild(i) { this.buildInfo.modules[i].args = ""; this.buildInfo.modules[i].customBuildXml = ""; return false; } setpaCodeAnalysis(i) { this.buildInfo.modules[i].codeAnalysis = []; this.IdpdataService.pa = true; return false; } setunitTestcodeCoverage(i) { this.buildInfo.modules[i].unitTestDir = ""; this.buildInfo.modules[i].codeCoverage = "off"; return false; } setejbejbVal(i) { this.IdpdataService.ejbVal = false; this.buildInfo.modules[i].ejbDescriptor = ""; return false; } setjavaMain(i) { this.IdpdataService.jarVal = false; this.buildInfo.modules[i].javaMainClass = ""; return false; } setejbValTrue() { this.IdpdataService.ejbVal = true; return false; } setejbValFalse() { this.IdpdataService.ejbVal = false; return false; } setejbejbVal2(i) { this.buildInfo.modules[i].ejbDescriptor = ""; this.buildInfo.modules[i].javaMainClass = ""; this.IdpdataService.ejbVal = false; this.IdpdataService.jarVal = false; } /* Default Values for Module, War Packaging, web modules, ejb modules */ setwarValTrue() { this.IdpdataService.warVal = true; return false; } setwarValFalse() { this.IdpdataService.warVal = false; return false; } setmodulewarVal(i) { this.buildInfo.modules[i].warPackaging = ""; this.IdpdataService.warVal = false; return false; } setJavaModules() { this.buildInfo.javaModules = ""; return false; } setEjbModules() { this.buildInfo.ejbModules = ""; return false; } setwebModules() { this.buildInfo.webModules = ""; return false; } setwebejbjavaModules() { this.buildInfo.ejbModules = ""; this.buildInfo.webModules = ""; this.buildInfo.javaModules = ""; return false; } /* Checks input required for EAr packaging */ checkForEarPack() { if (( this.tempObject.javalist === undefined || this.tempObject.javalist.length === 0) && (this.tempObject.ejbList === undefined || this.tempObject.ejbList.length === 0) && (this.tempObject.warList === undefined || this.tempObject.warList.length === 0) ) { return true; } else { return false; } } checkForEarPackJava() { if ( !( this.tempObject.javalist === undefined || this.tempObject.javalist.length === 0) ) { return true; } else { return false; } } /* Sets true if inputs for EJB packaging is available */ checkForEarPackEJB() { if ( !( this.tempObject.ejbList === undefined || this.tempObject.ejbList.length === 0) ) { return true; } else { return false; } } checkForEarPackWAR() { if (!(this.tempObject.warList === undefined || this.tempObject.warList.length === 0) ) { return true; } else { return false; } } /* Addition of each Ant Module */ addItem() { this.buildInfo.modules.push({ codeAnalysis: [], ossDistributionType: "" }); if (this.tempObject.modules === undefined) { this.tempObject.modules = []; } this.tempObject.modules.push({}); } onClick(key) { if (this.buildInfo.modules[key].compile === "off" || this.buildInfo.modules[key].compile === undefined || this.buildInfo.modules[key].compile === null) { this.buildInfo.modules[key].codeAnalysis[3].disabled = true; } else { this.buildInfo.modules[key].codeAnalysis[3].disabled = false; } } /* Checks for unique module name */ checkModuleName(index) { for (let i = 0; i < this.buildInfo.modules.length; i++) { if (this.buildInfo.modules[i].moduleName !== undefined && this.buildInfo.modules[index].moduleName !== undefined && this.buildInfo.modules[i].moduleName.toLowerCase() === this.buildInfo.modules[index].moduleName.toLowerCase() && i !== index) { this.nameErrorMessage = "Module name must be unique."; break; } else { this.nameErrorMessage = ""; } } } /* Checks for mainclass for each Ant module */ javaOptionList() { this.javalist = []; for (let i = 0; i < this.buildInfo.modules.length; i++) { if (this.buildInfo.modules[i].moduleName !== undefined && this.buildInfo.modules[i].moduleName !== null && this.buildInfo.modules[i].moduleName !== "" && this.buildInfo.modules[i].javaMainClass !== undefined && this.buildInfo.modules[i].javaMainClass !== "" && this.buildInfo.modules[i].javaMainClass !== null) { this.javalist.push(this.buildInfo.modules[i].moduleName); } } this.tempObject.javalist = this.javalist; return true; } /* Checks for EJB descr for each module, if EJB is enabled, and pushes the values to service */ ejbOptionList() { this.ejbList = []; for (let i = 0; i < this.buildInfo.modules.length; i++) { if ( this.buildInfo.modules[i].moduleName !== undefined && this.buildInfo.modules[i].moduleName !== null && this.buildInfo.modules[i].moduleName !== "" && this.buildInfo.modules[i].ejbDescriptor !== undefined && this.buildInfo.modules[i].ejbDescriptor !== null && this.buildInfo.modules[i].ejbDescriptor !== "") { this.ejbList.push(this.buildInfo.modules[i].moduleName); } } this.tempObject.ejbList = this.ejbList; return true; } /* Checks for war packaging for each module, if enabled, it pushes the value of each module to service */ warOptionList() { this.warList = []; for (let i = 0; i < this.buildInfo.modules.length; i++) { if ( this.buildInfo.modules[i].moduleName !== undefined && this.buildInfo.modules[i].moduleName !== null && this.buildInfo.modules[i].moduleName !== "" && this.buildInfo.modules[i].warPackaging !== undefined && this.buildInfo.modules[i].warPackaging !== null && this.buildInfo.modules[i].warPackaging !== "" ) { this.warList.push(this.buildInfo.modules[i].moduleName); } } this.tempObject.warList = this.warList; return true; } codeAnalysisCheckbox(index) { if (this.tempObject.modules[index].codeAnalysis === "on") { this.buildInfo.modules[index].codeAnalysis = [null, null, null, null]; } } /* Removal of ANT module */ deleteItem(index) { const x = confirm("Are you sure to remove the Module ?"); if (x) { this.buildInfo.modules.splice(index, 1); this.tempObject.modules.splice(index, 1); } } /* Checks for status of each checkbbox, including compile, packaging, code Analysis, modules,.. and gets the status */ checkCheckBox() { if (this.tempObject.modules === undefined) { this.tempObject.modules = []; } for (let i = 0; i < this.buildInfo.modules.length; i++) { let customBuildXml = "off"; let codeAnalysis = "off"; let securityAnalysis = "off"; const JARPackaging = "off"; let WARPackaging = "off"; let checkjar = "off"; let secAnal = ""; const schdulePeriodicFullScan = "off"; let ear = "off"; let ossCheck = "off"; if (this.buildInfo.modules[i].customBuildXml !== "" && this.buildInfo.modules[i].customBuildXml !== undefined) { customBuildXml = "on"; } if (this.buildInfo.modules[i].codeAnalysis.length !== 0) { codeAnalysis = "on"; } if (this.buildInfo.modules[i].pafFilePath !== "" && this.buildInfo.modules[i].pafFilePath !== undefined) { securityAnalysis = "on"; } if (this.buildInfo.modules[i].warPackaging !== "" && this.buildInfo.modules[i].warPackaging !== undefined) { WARPackaging = "on"; } if (this.buildInfo.modules[i].javaMainClass !== undefined && this.buildInfo.modules[i].javaMainClass !== "" ) { checkjar = "on"; } else if (this.buildInfo.modules[i].ejbDescriptor !== undefined && this.buildInfo.modules[i].ejbDescriptor !== "") { checkjar = "on"; } if ((this.buildInfo.javaModules !== undefined && this.buildInfo.javaModules !== null && this.buildInfo.javaModules !== "") || (this.buildInfo.ejbModules !== undefined && this.buildInfo.ejbModules !== null && this.buildInfo.ejbModules !== "") || (this.buildInfo.webModules !== undefined && this.buildInfo.webModules !== null && this.buildInfo.webModules !== "")) { ear = "on"; } if (this.buildInfo.modules[i].pafFilePath !== undefined && this.buildInfo.modules[i].pafFilePath !== "") { securityAnalysis = "on"; secAnal = "App Scan"; } if (this.buildInfo.modules[i].ossMailRecipients !== "" && this.buildInfo.modules[i].ossMailRecipients !== undefined) { ossCheck = "on"; } this.tempObject.modules.push({ // Pushes the status/value of each field "customBuildXml": customBuildXml, "codeAnalysis": codeAnalysis, "securityAnalysis": securityAnalysis, "WARPackaging": WARPackaging, "chkjar": checkjar, "secAnal": secAnal, "schdulePeriodicFullScan": schdulePeriodicFullScan, "ossCheck": ossCheck }); this.tempObject.ear = ear; } } ngOnInit() { this.distributionList = [{ "name": "Internal", "value": "Internal" }, { "name": "Hosted Service (Infosys Infrastructure) ", "value": "Hosted Service" }, { "name": "Bundling", "value": "Bundling" }, { "name": "Dynamic Library", "value": "Dynamic Library" }, { "name": "Deliverable Application", "value": "Deliverable Application" }]; } /* Initializing OSS inputs on checking and unchecking */ ossCompliance(index,checked){ if (checked) { this.tempObject.modules[index].ossCheck = "on"; } else { this.tempObject.modules[index].ossCheck = "off"; this.buildInfo.modules[index].ossMailRecipients = ""; this.buildInfo.modules[index].ossDistributionType = ""; this.buildInfo.modules[index].ossAnalysisType = ""; } } }
the_stack
import { createProxy, isChanged } from '../src/index'; const noop = (_arg: unknown) => { // do nothing }; describe('shallow object spec', () => { it('no property access', () => { const s1 = { a: 'a', b: 'b' }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); noop(p1); expect(isChanged(s1, { a: 'a', b: 'b' }, a1, undefined)).toBe(true); expect(isChanged(s1, { a: 'a2', b: 'b' }, a1, undefined)).toBe(true); expect(isChanged(s1, { a: 'a', b: 'b2' }, a1, undefined)).toBe(true); }); it('one property access', () => { const s1 = { a: 'a', b: 'b' }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); noop(p1.a); expect(isChanged(s1, { a: 'a', b: 'b' }, a1)).toBe(false); expect(isChanged(s1, { a: 'a2', b: 'b' }, a1)).toBe(true); expect(isChanged(s1, { a: 'a', b: 'b2' }, a1)).toBe(false); }); }); describe('deep object spec', () => { it('intermediate property access', () => { const s1 = { a: { b: 'b', c: 'c' } }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); noop(p1.a); expect(isChanged(s1, { a: s1.a }, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b2', c: 'c' } }, a1)).toBe(true); expect(isChanged(s1, { a: { b: 'b', c: 'c2' } }, a1)).toBe(true); }); it('leaf property access', () => { const s1 = { a: { b: 'b', c: 'c' } }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); noop(p1.a.b); expect(isChanged(s1, { a: s1.a }, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b2', c: 'c' } }, a1)).toBe(true); expect(isChanged(s1, { a: { b: 'b', c: 'c2' } }, a1)).toBe(false); }); }); describe('reference equality spec', () => { it('simple', () => { const proxyCache = new WeakMap(); const s1 = { a: 'a', b: 'b' }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a); const s2 = s1; // keep the reference const a2 = new WeakMap(); const p2 = createProxy(s2, a2, proxyCache); noop(p2.b); expect(p1).toBe(p2); expect(isChanged(s1, { a: 'a', b: 'b' }, a1)).toBe(false); expect(isChanged(s1, { a: 'a2', b: 'b' }, a1)).toBe(true); expect(isChanged(s1, { a: 'a', b: 'b2' }, a1)).toBe(false); expect(isChanged(s2, { a: 'a', b: 'b' }, a2)).toBe(false); expect(isChanged(s2, { a: 'a2', b: 'b' }, a2)).toBe(false); expect(isChanged(s2, { a: 'a', b: 'b2' }, a2)).toBe(true); }); it('nested', () => { const proxyCache = new WeakMap(); const s1 = { a: { b: 'b', c: 'c' } }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a.b); const s2 = { a: s1.a }; // keep the reference const a2 = new WeakMap(); const p2 = createProxy(s2, a2, proxyCache); noop(p2.a.c); expect(p1).not.toBe(p2); expect(p1.a).toBe(p2.a); expect(isChanged(s1, { a: { b: 'b', c: 'c' } }, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b2', c: 'c' } }, a1)).toBe(true); expect(isChanged(s1, { a: { b: 'b', c: 'c2' } }, a1)).toBe(false); expect(isChanged(s2, { a: { b: 'b', c: 'c' } }, a2)).toBe(false); expect(isChanged(s2, { a: { b: 'b2', c: 'c' } }, a2)).toBe(false); expect(isChanged(s2, { a: { b: 'b', c: 'c2' } }, a2)).toBe(true); }); }); describe('array spec', () => { it('length', () => { const s1 = [1, 2, 3]; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); noop(p1.length); expect(isChanged(s1, [1, 2, 3], a1)).toBe(false); expect(isChanged(s1, [1, 2, 3, 4], a1)).toBe(true); expect(isChanged(s1, [1, 2], a1)).toBe(true); expect(isChanged(s1, [1, 2, 4], a1)).toBe(false); }); it('forEach', () => { const s1 = [1, 2, 3]; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); p1.forEach(noop); expect(isChanged(s1, [1, 2, 3], a1)).toBe(false); expect(isChanged(s1, [1, 2, 3, 4], a1)).toBe(true); expect(isChanged(s1, [1, 2], a1)).toBe(true); expect(isChanged(s1, [1, 2, 4], a1)).toBe(true); }); it('for-of', () => { const s1 = [1, 2, 3]; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); // eslint-disable-next-line no-restricted-syntax for (const x of p1) { noop(x); } expect(isChanged(s1, [1, 2, 3], a1)).toBe(false); expect(isChanged(s1, [1, 2, 3, 4], a1)).toBe(true); expect(isChanged(s1, [1, 2], a1)).toBe(true); expect(isChanged(s1, [1, 2, 4], a1)).toBe(true); }); }); describe('keys spec', () => { it('object keys', () => { const s1 = { a: { b: 'b' }, c: 'c' }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); noop(Object.keys(p1)); expect(isChanged(s1, { a: s1.a, c: 'c' }, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b' }, c: 'c' }, a1)).toBe(false); expect(isChanged(s1, { a: s1.a }, a1)).toBe(true); expect(isChanged(s1, { a: s1.a, c: 'c', d: 'd' }, a1)).toBe(true); }); it('for-in', () => { const s1 = { a: { b: 'b' }, c: 'c' }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); // eslint-disable-next-line no-restricted-syntax, guard-for-in for (const k in p1) { noop(k); } expect(isChanged(s1, { a: s1.a, c: 'c' }, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b' }, c: 'c' }, a1)).toBe(false); expect(isChanged(s1, { a: s1.a }, a1)).toBe(true); expect(isChanged(s1, { a: s1.a, c: 'c', d: 'd' }, a1)).toBe(true); }); it('single in operator', () => { const s1 = { a: { b: 'b' }, c: 'c' }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1); noop('a' in p1); expect(isChanged(s1, { a: s1.a, c: 'c' }, a1)).toBe(false); expect(isChanged(s1, { a: s1.a }, a1)).toBe(false); expect(isChanged(s1, { c: 'c', d: 'd' }, a1)).toBe(true); }); }); describe('special objects spec', () => { it('object with cycles', () => { const proxyCache = new WeakMap(); const s1: any = { a: 'a' }; s1.self = s1; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); const c1 = new WeakMap(); noop(p1.self.a); expect(isChanged(s1, s1, a1, c1)).toBe(false); expect(isChanged(s1, { a: 'a', self: s1 }, a1, c1)).toBe(false); const s2: any = { a: 'a' }; s2.self = s2; expect(isChanged(s1, s2, a1, c1)).toBe(false); const s3: any = { a: 'a2' }; s3.self = s3; expect(isChanged(s1, s3, a1, c1)).toBe(true); }); it('object with cycles 2', () => { const proxyCache = new WeakMap(); const s1: any = { a: { b: 'b' } }; s1.self = s1; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); const c1 = new WeakMap(); noop(p1.self.a); expect(isChanged(s1, s1, a1, c1)).toBe(false); expect(isChanged(s1, { a: s1.a, self: s1 }, a1, c1)).toBe(false); const s2: any = { a: { b: 'b' } }; s2.self = s2; expect(isChanged(s1, s2, a1, c1)).toBe(true); }); it('frozen object', () => { const proxyCache = new WeakMap(); const s1 = { a: { b: 'b' }, c: 'c' as string | undefined }; Object.freeze(s1); const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a.b); expect(isChanged(s1, s1, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b' } }, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b2' } }, a1)).toBe(true); expect(() => { p1.a = { b: 'b3' }; }).toThrow(); expect(() => { delete p1.c; }).toThrow(); }); it('object with defineProperty (non-configurable and non-writable)', () => { const proxyCache = new WeakMap(); const s1: any = {}; Object.defineProperty(s1, 'a', { value: { b: 'b' } }); const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a.b); expect(isChanged(s1, s1, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b' } }, a1)).toBe(false); expect(isChanged(s1, { a: { b: 'b2' } }, a1)).toBe(true); }); }); describe('builtin objects spec', () => { // we can't track builtin objects it('boolean', () => { /* eslint-disable no-new-wrappers */ const proxyCache = new WeakMap(); const s1 = { a: new Boolean(false) }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a.valueOf()); expect(isChanged(s1, s1, a1)).toBe(false); expect(isChanged(s1, { a: new Boolean(false) }, a1)).toBe(true); /* eslint-enable no-new-wrappers */ }); it('error', () => { const proxyCache = new WeakMap(); const s1 = { a: new Error('e') }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a.message); expect(isChanged(s1, s1, a1)).toBe(false); expect(isChanged(s1, { a: new Error('e') }, a1)).toBe(true); }); it('date', () => { const proxyCache = new WeakMap(); const s1 = { a: new Date('2019-05-11T12:22:29.293Z') }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a.getTime()); expect(isChanged(s1, s1, a1)).toBe(false); expect(isChanged(s1, { a: new Date('2019-05-11T12:22:29.293Z') }, a1)).toBe(true); }); it('regexp', () => { const proxyCache = new WeakMap(); const s1 = { a: /a/ }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a.test('a')); expect(isChanged(s1, s1, a1)).toBe(false); expect(isChanged(s1, { a: /a/ }, a1)).toBe(true); }); it('map', () => { const proxyCache = new WeakMap(); const s1 = { a: new Map() }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a.entries()); expect(isChanged(s1, s1, a1)).toBe(false); expect(isChanged(s1, { a: new Map() }, a1)).toBe(true); }); it('typed array', () => { const proxyCache = new WeakMap(); const s1 = { a: Int8Array.from([1]) }; const a1 = new WeakMap(); const p1 = createProxy(s1, a1, proxyCache); noop(p1.a[0]); expect(isChanged(s1, s1, a1)).toBe(false); expect(isChanged(s1, { a: Int8Array.from([1]) }, a1)).toBe(true); }); });
the_stack
import * as assert from 'assert'; import {DelayedLog} from './delayedlog'; import {MAX_MEM_SIZE} from './basememory'; import {Memory, MemAttribute} from './memory'; import {Opcode, OpcodeFlag} from './opcode'; import {NumberType, getNumberTypeAsString} from './numbertype' import {DisLabel} from './dislabel'; import {Comment} from './comment'; import {SubroutineStatistics} from './statistics'; import {EventEmitter} from 'events'; import {Format} from './format'; import {readFileSync} from 'fs'; /** * The main Disassembler class. */ export class Disassembler extends EventEmitter { /// A function that can be set to assign other than the standard /// label names. public funcAssignLabels: (address: number) => string; /// The memory area to disassemble. public memory = new Memory(); /// The labels. public labels: Map<number, DisLabel>; /// The reverted labels map. Created when a callgraph is output. protected revertedLabelMap: Map<string, number>; /// Temporarily offset labels. Just an offset number of the address of the real label. protected offsetLabels: Map<number, number>; /// Here the association from an address to it's parent, i.e. the subroutine it // belongs to is stored for each address. protected addressParents: Array<DisLabel>; /// Queue for start addresses only addresses of opcodes protected addressQueue = new Array<number>(); // Used for (user) comments for labels (addresses). protected addressComments = new Map<number, Comment>(); /// Map for statistics (size of subroutines, cyclomatic complexity) protected subroutineStatistics = new Map<DisLabel, SubroutineStatistics>(); /// The statistics maximum protected statisticsMax: SubroutineStatistics = {sizeInBytes: 0, countOfInstructions: 0, CyclomaticComplexity: 0}; /// The statistics minimum protected statisticsMin: SubroutineStatistics = {sizeInBytes: Number.MAX_SAFE_INTEGER, countOfInstructions: Number.MAX_SAFE_INTEGER, CyclomaticComplexity: Number.MAX_SAFE_INTEGER}; /// Labels that should be marked (with a color) are put here. String contains the color of the label for the dot graphic. protected dotMarkedLabels = new Map<number | string, string>(); // dot-color for warning-marks for labels. protected dotWarningMark = 'lightblue'; /// Choose opcodes in lower or upper case. public opcodesLowerCase = true; /// Choose how many lines should separate code blocks in the disassembly listing public numberOfLinesBetweenBlocks = 2; /// Choose if references should be added to SUBs public addReferencesToSubroutines = true; /// Choose if references should be added to LBLs public addReferencesToAbsoluteLabels = true; /// Choose if references should be added to RST labels public addReferencesToRstLabels = true; /// Choose if references should be added to DATA labels public addReferencesToDataLabels = true; /// Choose to add the opcode bytes also, e.g. "CB 01" for "RLC C" public addOpcodeBytes = true; /// Label prefixes public labelSubPrefix = "SUB"; public labelLblPrefix = "LBL"; public labelRstPrefix = "RST"; public labelDataLblPrefix = "DATA"; public labelSelfModifyingPrefix = "SELF_MOD"; // I guess this is not used anymore if DATA_LBL priority is below CODE_LBLs public labelLocalLablePrefix = "_l"; public labelLoopPrefix = "_loop"; public labelIntrptPrefix = "INTRPT"; /// If set the disassemble will automatically add address 0 or the SNA address to the labels. public automaticAddresses = true; /// Column areas. e.g. area for the bytes shown before each command public clmnsAddress = 5; ///< size for the address at the beginning of each line. If 0 no address is shown. public clmnsBytes = 4 * 3 + 1; ///< 4* length of hex-byte public clmnsOpcodeFirstPart = 4 + 1; ///< First part of the opcodes, e.g. "LD" in "LD A,7" public clmsnOpcodeTotal = 5 + 6 + 1; ///< Total length of the opcodes. After this an optional comment may start. // Dot format options for the node. E.g. "${label}\n${address}\nCC=${CC}\nSize=${size}\ninstr=${instructions}\n" public dotFormatString = "rankdir=TB;"; // Graph direction // Dot format options for the node. E.g. "${label}\n${address}\nCC=${CC}\nSize=${size}\ninstr=${instructions}\n" public nodeFormatString = "${label}\\n0x${address}\\nSize=${size}\\n"; /// RST addresses that shouldn't be followed on a disassembly. /// Note: It can happen that code around ORG 0000h has to be disassembled. /// But at the same time the ESXDOS RST 8 is used for file handling. /// This is a hardwired RST. It does not exist in ROM. /// RST addresses that appear in this list will not be followed/disassembled. public rstDontFollowAddresses = new Array<number>(); /// An array that either contains label names or addresses, /// but both as string. If defined only the labels inside this /// list are used for the dot graphics. public graphLabels = new Array<string | number>(); /// The disassembled lines. protected disassembledLines: Array<string>; // The SNA start address. protected snaStartAddress = -1; /// Used to prohibit that empty lines are written more than once. protected emptyLinesWritten = false; /// For debugging: protected DBG_COLLECT_LABELS = false; //true; /// Add decimal conversion to addresses (at beginning of line) protected DBG_ADD_DEC_ADDRESS = false; //true; // Warnings /// true = disable warning when trying to disassemble unassigned memory. /// will be set to true automatically if SNA has been selected. protected no_warning_disassemble_unassigned_memory = false; // For DeZog. Used to turn off any comments in the disassembled text. public disableCommentsInDisassembly = false; /** * Initializes the Opcode formatting. */ constructor() { super(); this.initLabels(); Opcode.setConvertToLabelHandler(value => { let valueName; let label; let offsString = ''; if (this.labels) label = this.labels.get(value); if (!label) { // Check for offset label const offs = this.offsetLabels.get(value); if (offs) { label = this.labels.get(value + offs); if (label) offsString = (offs > 0) ? '' + (-offs) : '+' + (-offs); } } if (label) valueName = label.name + offsString; return valueName; }); } /** * Adds address 0 to the labels if it has not been added already * or the SNA address. */ public addAutomaticAddresses() { if (!this.automaticAddresses) return; // If a SNA address is already given, omit address 0 if (this.snaStartAddress >= 0) { // Use sna address this.addressQueue.push(this.snaStartAddress); } else { // Use address 0. // Check for code label at address 0. if (this.memory.getAttributeAt(0) & MemAttribute.ASSIGNED) { // Check if label exists let label0 = this.labels.get(0); if (!label0) { this.setFixedCodeLabel(0, 'ORG_0000'); } else { // Make sure it is a code label label0.type = NumberType.CODE_LBL; } this.addressQueue.push(0); // Note: if address 0 was already previously pushed it is now pushed again. But it doesn't harm. } } } /** * Returns the disassembled lines as an array of strings. * Make sure to run 'disassemble' beforehand. */ public getDisassemblyLines(): string[] { if (!this.disassembledLines) { this.emit('warning', 'No disassembly was done.'); return ['']; } return this.disassembledLines; } /** * Returns the disassembled lines as a string. * Make sure to run 'disassemble' beforehand. */ public getDisassemblyText(): string { return this.getDisassemblyLines().join('\n'); } /** * Disassembles the memory area. * Disassembly is done in a few passes. * Afterwards the disassembledLines are set: * An array of strings with the disassembly. */ public disassemble() { // Add address 0 this.addAutomaticAddresses(); // Collect labels this.collectLabels(); // Find interrupts this.findInterruptLabels(); // Add special labels, e.g. the start of a ROM this.setSpecialLabels(); // Sort all labels by address this.sortLabels(); // Find self-modifying code this.adjustCodePointingLabels(); // Add more references if e.g. a SUB flows through to another SUB. this.addFlowThroughReferences(); // Check if labels "LBL" are subroutines this.turnLBLintoSUB(); // Determine local labels inside subroutines this.findLocalLabelsInSubroutines(); // Add parent references to each address and remove self referenced labels this.addParentReferences(); // Add 'calls' list to subroutine labels this.addCallsListToLabels(); // Count statistics (size of subroutines, cyclomatic complexity) this.countStatistics(); // Assign label names this.assignLabelNames(); // Add label comments if (!this.disableCommentsInDisassembly) this.addLabelComments(); // Disassemble opcode with label names const disLines = this.disassembleMemory(); // Add all EQU labels to the beginning of the disassembly this.disassembledLines = this.getEquLabelsDisassembly(); // Add the real disassembly this.disassembledLines.push(...disLines); // Remove any preceeding empty lines while (this.disassembledLines.length) { if (this.disassembledLines[0].length > 0) break; this.disassembledLines.splice(0, 1); } } /** * Define the memory area to disassemble. * @param origin The start address of the memory area. * @param memory The memory area. */ public setMemory(origin: number, memory: Uint8Array) { this.memory.setMemory(origin, memory); // Set start label //this.setLabel(origin, 'BIN_START_'+origin, NumberType.DATA_LBL); //const size = memory.length; //this.setLabel(origin+size, 'BIN_END_'+origin, NumberType.DATA_LBL); } /** * Reads a memory area as binary from a file. * @param origin The start address of the memory area. * @param path The file path to a binary file. */ public readBinFile(origin: number, path: string) { const bin = readFileSync(path); this.setMemory(origin, bin); } /** * Reads a .sna (ZX snapshot) file directly. Takes the start address from the .sna file. * @param path The file path to a binary file. */ public readSnaFile(path: string) { let sna = readFileSync(path); const header = sna.slice(0, 27); const bin = sna.slice(27); // Read start address const sp = header[23] + 256 * header[24]; // Stackpointer const spIndex = sp - 0x4000; const start = bin[spIndex] + 256 * bin[spIndex + 1]; // Get start address from stack this.setMemory(0x4000, bin); /* In most cases (snapshot) this is a random address, so it does not make sense to use it as a label: // Set start label this.setLabel(start, 'SNA_LBL_MAIN_START_'+start.toString(16).toUpperCase(), NumberType.CODE_LBL); */ this.snaStartAddress = start; // Disable warnings when trying to disassemble unassigned memory: // SNA files don't contain the Spectrum ROM, it is clear that this will result in warnings. this.no_warning_disassemble_unassigned_memory = true; } /** * Clears all labels collected so far. * Useful for dot generation of a particular subroutine. */ public clearLabels() { // get new arrays/maps. this.labels = new Map<number, DisLabel>(); this.offsetLabels = new Map<number, number>(); this.addressQueue = new Array<number>(); // ? Maybe the address Parents are missing here. } /** * Clears all labels. * Is done at start of disassembly. */ public initLabels() { // get new arrays/maps. this.labels = new Map<number, DisLabel>(); this.offsetLabels = new Map<number, number>(); this.addressParents = new Array<DisLabel>(); this.addressComments = new Map<number, Comment>(); } /** * You can set one (or more) initial labels here. * At least one label should be set, so that the disassembly * algorithm knows where to start from. * More labels could be set e.g. to tell where the interrupt starts at. * Optionally a name for the label can be given. * @param address The address of the label. * @param name An optional name for the label. * @param type of the label. Default is CODE_LBL. */ public setLabel(address: number, name?: string, type = NumberType.CODE_LBL) { // Check if label already set. let label = this.labels.get(address); if (label) { // Exists already, just overwrite the name if (!label.name || !label.isFixed) // Don't overwrite names given for fixed addresses. (label.name as any) = name; return; } // Create a new label label = new DisLabel(type); this.labels.set(address, label); (label.name as any) = name; // allow undefined // Check if out of range const attr = this.memory.getAttributeAt(address); if (attr & MemAttribute.ASSIGNED) { if (type == NumberType.CODE_LBL || type == NumberType.CODE_LOCAL_LBL || type == NumberType.CODE_LOCAL_LOOP || type == NumberType.CODE_RST || type == NumberType.CODE_SUB ) this.addressQueue.push(address); } else { // out of range -> EQU label.isEqu = true; } } /** * Used to set a label as the user. * I.e. those labels should be fixed, i.e. not changable by the algorithm. * Note: this affects only the change of the type. The name is anyhow not changed if it * has been set by the user. * @param address * @param name */ public setFixedCodeLabel(address: number, name?: string) { // Check if label already set. let label = this.labels.get(address); if (!label) { // Create new label label = new DisLabel(NumberType.CODE_LBL); this.labels.set(address, label); } // Set name if (name) (label.name as any) = name; // Check if out of range const attr = this.memory.getAttributeAt(address); if (attr & MemAttribute.ASSIGNED) this.addressQueue.push(address); else label.isEqu = true; // out of range -> EQU // Set as fixed label.isFixed = true; } /** * Sets a new address queue. * @param queue The new queue. */ public setAddressQueue(queue: number[]) { this.addressQueue = queue; } /** * Adds the addresses from a call table (in memory) to the labels. * @param address Address of the start of the call table. * @param count The number of jmp addresses. */ public setJmpTable(address: number, count: number) { // Loop over all jmp addresses for (let i = 0; i < count; i++) { // Get address let jmpAddress = this.memory.getWordValueAt(address); // Set label this.setFixedCodeLabel(jmpAddress); // Next address += 2; } } /** * Reads a MAME .tr (trace) file. * MAME trace files contain the opcode addresses of a run of the program. * These are used as starting points for the disassembly. * If a trace file is given it is normally not required to give additional * label info like start of the program or start of the interrupt rsubroutine. * @param path The file path to the trace (.tr) file. (An ASCII file). * Trace files can become very big, a few seconds already result in MB of data. */ public useMameTraceFile(path: string) { const trace = readFileSync(path).toString(); if (trace.length < 5) return; /* Doesn't make sense: // Use first address as start address const startAddress = trace.substr(0,5); this.setLabel(parseInt(startAddress, 16), 'TR_LBL_MAIN_START_'+ startAddress); */ // Loop over the complete trace file const buffer = new Array<boolean>(MAX_MEM_SIZE); // initialized to undefined let k = 0; let jpHlRef; //let lineNr = 1; do { //const text = trace.substr(k,100); //console.log('log: "' + text + '"'); const addressString = trace.substr(k, 5); if (addressString.length == 5 && addressString[4] == ':') { // Use address const addr = parseInt(addressString, 16); buffer[addr] = true; k += 5; // Check if previous opcode was a 'jp (hl)' const memAttr = this.memory.getAttributeAt(addr); if (jpHlRef) { // If so: add a label with a reference this.setFoundLabel(addr, new Set([jpHlRef]), NumberType.CODE_LBL, memAttr); jpHlRef = undefined; } // check if opcode is a "jp (hl)" if (memAttr & MemAttribute.ASSIGNED) { const opcodeString = trace.substr(k, 10); if (opcodeString == ' jp (hl)') { // remember address jpHlRef = addr; k += 10; } } } // next k = trace.indexOf('\n', k) + 1; //lineNr ++; } while (k != 0); // Now add the addresses to the queue for (let addr = 0; addr < MAX_MEM_SIZE; addr++) { if (buffer[addr]) this.addressQueue.push(addr); } } /** * Prints all labels to the console. */ /* public printLabels() { for(let [address, label] of this.labels) { // Label console.log('0x' + address.toString(16) + ': ' + label.name + ', ' + label.getTypeAsString() + ', EQU=' + label.isEqu); // References const refArray = label.references.map(value => '0x'+value.toString(16)); console.log('\tReferenced by: ' + refArray.toString() ); } } */ /** * Puts all EQU labels in an array of strings. * @returns Array of strings. */ public getEquLabelsDisassembly(): Array<string> { let firstLabel = true; const lines = new Array<string>(); for (let [address, label] of this.labels) { // Check if EQU if (label.isEqu) { if (firstLabel) { if (!this.disableCommentsInDisassembly) { // At the start of the EQU area print a comment. lines.push('; EQU:'); lines.push('; Data addresses used by the opcodes that point to uninitialized memory areas.'); } firstLabel = false; } // "Disassemble" const statement = Format.addSpaces(label.name + ':', this.clmnsBytes - 1) + ' ' + this.rightCase('EQU ') + Format.fillDigits(Format.getHexString(address, 4), ' ', 5) + 'h'; // Comment const comment = this.addressComments.get(address); const commentLines = Comment.getLines(comment, statement, this.disableCommentsInDisassembly); // Store lines.push(...commentLines); } } return lines; } /** * Parses the memory area for opcodes with labels. * Stores all labels with a categorization in an array. * Priorization of labels: * 1. "SUB"-labels: Everything called by "CALL nn" or "CALL cc,nn" * 2. "LBL"-labels: Everything jumped to "JP nn" or "JP cc,nn" * 3. "loop"-labels: Everything jumped to by "DJNZ" * 4. "l"-labels: Everything jumped to by "JR n" or "JR cc,n" * "loop" and "lbl" labels are prefixed by a previous "SUB"- or "LBL"-label with a prefix * ".subNNN_" or ".lblNNN_". E.g. ".sub001_l5", ".sub001_loop1", ".lbl788_l89", ".lbl788_loop23". * All labels are stored into this.labels. At the end the list is sorted by the address. */ protected collectLabels() { let address; let opcode; // get new address from queue while ((address = this.addressQueue.shift()) != undefined) { //console.log('address=0x' + address.toString(16)); // disassemble until stop-code //console.log('==='); do { //console.log('addr=' + address.toString(16)); // Check if memory has already been disassembled let attr = this.memory.getAttributeAt(address); if (attr & MemAttribute.CODE) break; // Yes, already disassembled if (!(attr & MemAttribute.ASSIGNED)) { // Error: trying to disassemble unassigned memory areas if (!this.no_warning_disassemble_unassigned_memory) this.emit('warning', 'Trying to disassemble unassigned memory area at 0x' + address.toString(16) + '.'); break; } // Read memory value opcode = Opcode.getOpcodeAt(this.memory, address); if (this.DBG_COLLECT_LABELS) console.log(Format.getHexString(address) + '\t' + opcode.disassemble().mnemonic); // Check if memory area has already been PARTLY disassembled const len = opcode.length; let memAddress = address; let quitDoWhile = false; for (let i = 1; i < len; i++) { memAddress++; attr = this.memory.getAttributeAt(memAddress); if (attr & MemAttribute.CODE) { // It has already been disassembled -> error. const otherOpcode = Opcode.getOpcodeAt(this.memory, memAddress); // emit warning this.emit('warning', 'Aborting disassembly: Ambiguous disassembly: Trying to disassemble opcode "' + opcode.name + '" at address 0x' + address.toString(16) + ' but address 0x' + memAddress.toString(16) + ' already contains opcode "' + otherOpcode.name + '".'); //assert(attr & MemAttribute.CODE_FIRST, 'Internal error: Expected CODE_FIRST'); //return; // Just quit current thread. quitDoWhile = true; break; } } if (quitDoWhile) break; // Mark memory area this.memory.addAttributeAt(address, 1, MemAttribute.CODE_FIRST); this.memory.addAttributeAt(address, opcode.length, MemAttribute.CODE); /* // Mark as stop code? if(opcode.flags & OpcodeFlag.STOP) this.memory.addAttributeAt(address, opcode.length, MemAttribute.CODE_STOP); */ // Check opcode for labels if (!this.disassembleForLabel(address, opcode)) { return; } // Check for stop code. (JP, JR, RET) if (opcode.flags & OpcodeFlag.STOP) break; // Next address address += opcode.length; // Check for end of disassembly (JP, RET) } while (!(opcode.flags & OpcodeFlag.STOP)); if (this.DBG_COLLECT_LABELS) console.log('\n'); } } /** * Sets or creates a label and sets its type. * @param address The address for the label. * @param referenceAddresses Set with addresses that reference the label. Usually only the opcode address. * @param type The NumberType. * @param attr The memory attribute at address. */ protected setFoundLabel(address: number, referenceAddresses: Set<number>, type: NumberType, attr: MemAttribute) { // Check if label already exists let label = this.labels.get(address); if (label) { // label already exists: prioritize if (label.type < type) label.type = type; } else { // Label does not exist yet, just add it label = new DisLabel(type); this.labels.set(address, label); // Check if out of range if (!(attr & MemAttribute.ASSIGNED)) label.isEqu = true; } // Add reference(s). Do a union of both sets. //label.references = new Set([...label.references, ...referenceAddresses]); for (let ref of referenceAddresses) { if (ref != address) { label.references.add(ref); } } } /** * Sets the label for a possibly SNA start address and * labels that show where memory areas start if the memory area * is not continuous. */ protected setSpecialLabels() { if (this.automaticAddresses) { // Do special SNA handling. I.e. check if the SNA start address is meaningful if (this.snaStartAddress >= 0) { const label = this.labels.get(this.snaStartAddress); if (!label) // if not found by other means. this.setLabel(this.snaStartAddress, 'SNA_LBL_MAIN_START_' + this.snaStartAddress.toString(16).toUpperCase(), NumberType.CODE_LBL); } } // Check whole memory let prevAttr = 0; for (let addr = 0; addr < MAX_MEM_SIZE; addr++) { const memAttr = this.memory.getAttributeAt(addr); if ((prevAttr ^ memAttr) & MemAttribute.ASSIGNED) { // Assignment status changed if (memAttr & MemAttribute.ASSIGNED) { // Is assigned now, set a label (maybe) const label = this.labels.get(addr); if (!label) { this.setLabel(addr, 'BIN_START_' + Format.getHexString(addr).toUpperCase(), NumberType.DATA_LBL); } } } // Next prevAttr = memAttr; } } /** * Finds interrupt labels. I.e. start of program code * that doesn't have any lable yet. * As z80dismblr uses CFG analysis this can normally not happen. * But if you e.g. provide a trace (tr) file this also includes interrupt traces. * So z80dismblr will also follow these paths, but since there * is no label associated this code would be presented without 'Start' label. * 'findInterruptLabels' finds these code parts and assigns a label. * Several rules are used: * - It is checked if a label exists at a change from data or unassigned to opcode area * - For a transition from stop code to opcode and there is no associated label * * Note: Another strategy to find interrupts would be to examine the trace from the * tr file. If an address change happens that is bigger than +/-128 it must be * at least a JP/CALL label or an interrupt call. The label can be added here. * Later the JP/CALL labels would be found anyway (most probably). */ protected findInterruptLabels() { const foundInterrupts = new Array<number>(); // Check the whole memory let prevAttr = 0; let prevCodeAddr = -1; for (let address = 0x0000; address < MAX_MEM_SIZE; address++) { // check memory attribute const memAttr = this.memory.getAttributeAt(address); // Only if not the SNA address if (address != this.snaStartAddress) { if (memAttr & MemAttribute.CODE_FIRST && memAttr & MemAttribute.ASSIGNED) { // Check if label exists const label = this.labels.get(address); if (!label) { // Only if label not yet exists // Check for transition unassigned or data (= not CODE) to code if (!(prevAttr & MemAttribute.ASSIGNED) || !(prevAttr & MemAttribute.CODE)) { // Only if not the SNA address if (address != this.snaStartAddress) { // Assign label this.setFixedCodeLabel(address, this.labelIntrptPrefix); foundInterrupts.push(address); } } // Check for transition from stop code else if (prevCodeAddr >= 0) { const opcode = Opcode.getOpcodeAt(this.memory, prevCodeAddr); if (opcode.flags & OpcodeFlag.STOP) { // Assign label this.setFixedCodeLabel(address, this.labelIntrptPrefix); foundInterrupts.push(address); } } } } } // Backup values prevAttr = memAttr; if (!(memAttr & MemAttribute.CODE)) prevCodeAddr = -1; if (memAttr & MemAttribute.CODE_FIRST) prevCodeAddr = address; } // Add numbers const count = foundInterrupts.length; if (count > 1) { for (let index = 0; index < count; index++) { const addr = foundInterrupts[index]; const label = this.labels.get(addr); assert(label, 'findInterruptLabels'); if (label) label.name += index + 1; } } } /** * Sorts all labels by address. */ protected sortLabels() { this.labels = new Map([...this.labels.entries()].sort(([a], [b]) => a - b)); } /** * "Disassembles" one label. I.e. the opcode is disassembled and checked if it includes * a label. * If so, the label is stored together with the call information. * @param opcode The opcode to search for a label. * @param opcodeAddress The current address. * @returns false if problem occurred. */ protected disassembleForLabel(opcodeAddress: number, opcode: Opcode): boolean { // Check for branching etc. (CALL, RST, JP, JR) if (opcode.flags & OpcodeFlag.BRANCH_ADDRESS) { // It is a label. // Get branching memory attribute const branchAddress = opcode.value; const attr = this.memory.getAttributeAt(branchAddress); // Create new label or prioritize if label already exists let vType = opcode.valueType; if (vType == NumberType.CODE_LOCAL_LBL) { // A relative jump backwards will become a "loop" if (branchAddress <= opcodeAddress) vType = NumberType.CODE_LOCAL_LOOP; } else if (vType == NumberType.CODE_LBL) { // Treat JP to unassigned memory area as a CALL. if (!(attr & MemAttribute.ASSIGNED)) vType = NumberType.CODE_SUB; } // Set label with correct type this.setFoundLabel(branchAddress, new Set([opcodeAddress]), vType, attr); // Check if code from the branching address has already been disassembled if (!(attr & MemAttribute.CODE)) { // It has not been disassembled yet if (attr & MemAttribute.ASSIGNED) { // memory location exists, so queue it for disassembly if (vType != NumberType.CODE_RST || this.rstDontFollowAddresses.indexOf(branchAddress) < 0) { // But only if it is not a RST address which was banned by the user. this.addressQueue.push(branchAddress); } } } } else if (opcode.valueType == NumberType.DATA_LBL) { // It's a data label, like "LD A,(nn)" let address = opcode.value; // Check if it the top of stack if (opcode.flags & OpcodeFlag.LOAD_STACK_TOP) { // yes, top of stack i.e. "LD SP,nn". // In this case the data 2 byte below is shown as last stack element const offs = -2; // add offset label this.offsetLabels.set(address, offs); // change address address += offs; // add comment if (!this.addressComments.get(address)) { const comment = new Comment(); comment.addBefore('; Last element of stack:'); this.addressComments.set(address, comment); } } // "normal", e.g. "LD A,(nn)" const attr = this.memory.getAttributeAt(address); // Create new label or prioritize if label already exists this.setFoundLabel(address, new Set([opcodeAddress]), opcode.valueType, attr); } // Everything fine return true; } /** * Finds data labels that point into code areas. * If the pointer points to the start of the opcode nothing needs to be done here. * Everything is handled by the assignLabelNames method. * But if the pointer points into the middle of an instruction the label * need to be adjusted: * 1. The current label is exchanged with an offset label * 2. Another label is created at the start of the opcode. */ protected adjustCodePointingLabels() { const changeMap = new Map<number, DisLabel>(); // Loop through all labels for (let [address, label] of this.labels) { switch (label.type) { case NumberType.CODE_LBL: case NumberType.CODE_LOCAL_LBL: case NumberType.CODE_LOCAL_LOOP: case NumberType.CODE_RST: case NumberType.CODE_SUB: case NumberType.DATA_LBL: const memAttr = this.memory.getAttributeAt(address); if (memAttr & MemAttribute.CODE) { if (!(memAttr & MemAttribute.CODE_FIRST)) { // Hit in the middle of an opcode. // Remember to change: changeMap.set(address, label); } } break; } } // Now change labels in original map for (let [address, label] of changeMap) { // Search start of opcode. let addrStart = address; let attr; do { addrStart--; assert(address - addrStart <= 4, 'adjustSelfModifyingLabels'); // Opcode should be smaller than 5 bytes attr = this.memory.getAttributeAt(addrStart); } while (!(attr & MemAttribute.CODE_FIRST)); // Use label and put it to the new address this.setFoundLabel(addrStart, label.references, label.type, attr); // Remove old label this.labels.delete(address); // Add offset label const offs = addrStart - address; // negative this.offsetLabels.set(address, offs); } } /** * Check if a LBL/SUB references another LBL/SUB just by flow-through. * I.e in. * SUB01: * LD A,1 * SUB02: * LD B,3 * SUB01 would otherwise not reference SUB02 although it flows through which * is equivalent to a JP or CALL;RET. * This "references" are added here. * Note: This could add an address a reference to 2 different labels. * Note: Also works in labels. */ protected addFlowThroughReferences() { // Loop through all labels for (let [address, label] of this.labels) { switch (label.type) { case NumberType.CODE_LBL: case NumberType.CODE_SUB: case NumberType.CODE_RST: // Find the next label that is reached not by a JP, JR or CALL const found = this.findNextFlowThroughLabel(address); if (found) { // add reference const foundLabel = found.label; if (label != foundLabel) { foundLabel.references.add(found.address); } } } } } /** * Finds the next label in the path. * Uses the direct path, i.e. it doesnot follow any branch addresses. * Returns at a STOP code. * Is used to find "flow-through" references. I.e. references from a SUB * to another that are creates because the program flow simply flows * through to the other subroutine instead of jumping to it or calling * it. * @param address The start address of the path. * @returns The found label or undefined if nothing found. */ protected findNextFlowThroughLabel(address: number,): {label: DisLabel, address: number} | undefined { // Check if memory exists let memAttr = this.memory.getAttributeAt(address); if (!(memAttr & MemAttribute.ASSIGNED)) { return undefined; } // Get opcode let opcode = Opcode.getOpcodeAt(this.memory, address); // Loop over addresses while (!(opcode.flags & OpcodeFlag.STOP)) { // Next address const prevAddress = address; address += opcode.length; // Check if label exists const foundLabel = this.labels.get(address); if (foundLabel) { // Check if it is LBL or SUB const type = foundLabel.type; switch (type) { case NumberType.CODE_LBL: case NumberType.CODE_SUB: return {label: foundLabel, address: prevAddress}; } } // Check if memory exists const memAttr = this.memory.getAttributeAt(address); if (!(memAttr & MemAttribute.ASSIGNED)) { return undefined; } // Get opcode opcode = Opcode.getOpcodeAt(this.memory, address); } // nothing found return undefined; } /** * Checks if LBLs are SUBs and if so turns them into SUBs. * Therefore it iterates through all LBL labels. * Then it walks through the LBL and stops if it finds a RET, RET cc or RETI. * Note 1: It does not check necessarily all branches. Once it finds a * RET it assumes that also the other branches will end with a RET. * Note 2: When this function is done there should be only 2 LBL left: * - the main program and * - the interrupt. */ protected turnLBLintoSUB() { // Loop through all labels for (let [address, label] of this.labels) { if (label.type == NumberType.CODE_LBL) { // Log DelayedLog.startLog(); // Find a "RET" on the path const addrsArray = new Array<number>(); const retFound = this.findRET(address, addrsArray); if (retFound) { // Debug DelayedLog.logIf(address, () => 'Addresses: ' + addrsArray.map(addr => addr.toString(16)).join(' ')); DelayedLog.logIf(address, () => 'turnLBLintoSUB: Turned Label ' + getNumberTypeAsString(label.type) + ' into CODE_SUB.'); // It is a subroutine, so turn the LBL into a SUB. label.type = NumberType.CODE_SUB; } DelayedLog.stopLog(); } } } /** * Tries to find a "RET(I)" in the path. * @param address The start address of the path. * @param addrsArray An empty array in the beginning that is filled with * all addresses of the path. * @returns true if an "RET(I)" was found otherwise false. */ protected findRET(address: number, addrsArray: Array<number>): boolean { let opcodeClone; do { // Check if memory exists const memAttr = this.memory.getAttributeAt(address); if (!(memAttr & MemAttribute.ASSIGNED)) { DelayedLog.log(() => 'findRET: address=' + DelayedLog.getNumber(address) + ': returns. memory not assigned.'); return false; } // Unfortunately it needs to be checked if address has been checked already if (addrsArray.indexOf(address) >= 0) { DelayedLog.log(() => 'findRET: address=' + DelayedLog.getNumber(address) + ': returns. memory already checked.'); return false; // already checked } // Check if a label for address exists that already is a subroutine. const addrLabel = this.labels.get(address); if (addrLabel) { const type = addrLabel.type; if (type == NumberType.CODE_SUB || type == NumberType.CODE_RST) { DelayedLog.log(() => 'findRET: address=' + DelayedLog.getNumber(address) + ': SUB FOUND. address belongs already to a SUB.'); return true; } } // check opcode const opcode = Opcode.getOpcodeAt(this.memory, address); opcodeClone = {...opcode}; // Required otherwise opcode is overwritten on next call to 'getOpcodeAt' if it's the same opcode. // Check if RET if (opcodeClone.flags & OpcodeFlag.RET) { DelayedLog.log(() => 'findRET: address=' + DelayedLog.getNumber(address) + ': SUB FOUND. RET code = ' + opcodeClone.name + '.'); return true; } // Add to array addrsArray.push(address); // And maybe branch address (but not a CALL) if (opcodeClone.flags & OpcodeFlag.BRANCH_ADDRESS) { if (!(opcodeClone.flags & OpcodeFlag.CALL)) { const branchAddress = opcodeClone.value; DelayedLog.log(() => 'findRET: address=' + DelayedLog.getNumber(address) + ': branching to ' + DelayedLog.getNumber(branchAddress) + '.'); DelayedLog.pushTab(); const res = this.findRET(branchAddress, addrsArray); DelayedLog.popTab(); if (res) return true; // SUB found } } // Now check next address address += opcodeClone.length; } while (!(opcodeClone.flags & OpcodeFlag.STOP)); // no RET return false; } /** * After Labels have been assigned: * Iterate through all subroutine labels. * Walkthrough each subroutine and store the address belonging to the * subroutine in an (temporary) array. The subroutine ends if each branch * ends with a stop code (RET or JP). * Then iterate the array. * Each address with a Label of type CODE_LBL/SUB is checked. If it contains * reference addresses outside the range of the array then it stays a CODE_LBL/SUB * otherwise it is turned into a local label CODE_LOCAL_LBL or CODE_LOCAL_LOOP. */ protected findLocalLabelsInSubroutines() { // Loop through all labels for (let [address, label] of this.labels) { switch (label.type) { case NumberType.CODE_LBL: case NumberType.CODE_SUB: case NumberType.CODE_RST: // Log DelayedLog.startLog(); // Get all addresses belonging to the subroutine const addrsArray = new Array<number>(); this.getSubroutineAddresses(address, addrsArray); // Now reduce array. I.e. only a coherent block will be treated as a subroutine. this.reduceSubroutineAddresses(address, addrsArray); // Iterate array for (let addr of addrsArray) { // Don't check start address if (addr == address) continue; // get corresponding label const addrLabel = this.labels.get(addr); // Check label if (!addrLabel) continue; // Check label type (not for RST) if (addrLabel.type != NumberType.CODE_LBL && addrLabel.type != NumberType.CODE_SUB) continue; if (addrLabel.isFixed) continue; // It is a CODE_LBL. Check references. const refs = addrLabel.references; let outsideFound = false; for (const ref of refs) { if (addrsArray.indexOf(ref) < 0) { // Found an address outside of the subroutine, // I.e. leave the label unchanged. outsideFound = true; break; } } if (!outsideFound) { // Debug DelayedLog.logIf(addr, () => 'Addresses: ' + addrsArray.map(addr => addr.toString(16)).join(' ')); DelayedLog.logIf(addr, () => 'findLocalLabelsInSubroutines: Turned Label' + getNumberTypeAsString(addrLabel.type) + ' into CODE_LOCAL_LBL.'); // No reference outside the subroutine found // -> turn CODE_LBL into local label addrLabel.type = NumberType.CODE_LOCAL_LBL; // If any reference addr is bigger than address use CODE_LOCAL_LOOP, // otherwise CODE_LOCAL_LBL for (const ref of refs) { const diff = ref - addr; if (diff >= 0 && diff <= 128) { // Use loop addrLabel.type = NumberType.CODE_LOCAL_LOOP; break; } } } } DelayedLog.stopLog(); } } } /** * Returns an array with all addresses used by the subroutine * given at 'address'. * Does NOT stop if it reaches a lable of another subroutine. * Works recursively. * @param address The start address of the subroutine. * @param addrsArray An empty array in the beginning that is filled with * all addresses of the subroutine. */ protected getSubroutineAddresses(address: number, addrsArray: Array<number>) { let opcodeClone; do { // Check if memory exists const memAttr = this.memory.getAttributeAt(address); if (!(memAttr & MemAttribute.ASSIGNED)) { DelayedLog.log(() => 'getSubroutineAddresses: address=' + DelayedLog.getNumber(address) + ': returns. memory not assigned.'); break; } // Unfortunately it needs to be checked if address has been checked already if (addrsArray.indexOf(address) >= 0) { DelayedLog.log(() => 'getSubroutineAddresses: address=' + DelayedLog.getNumber(address) + ': returns. memory already checked.'); break; // already checked } // check opcode const opcode = Opcode.getOpcodeAt(this.memory, address); opcodeClone = {...opcode}; // Required otherwise opcode is overwritten on next call to 'getOpcodeAt' if it's the same opcode. // Add to array addrsArray.push(address); // And maybe branch address if (opcodeClone.flags & OpcodeFlag.BRANCH_ADDRESS) { if (!(opcodeClone.flags & OpcodeFlag.CALL)) { const branchAddress = opcodeClone.value; DelayedLog.log(() => 'getSubroutineAddresses: address=' + DelayedLog.getNumber(address) + ': branching to ' + DelayedLog.getNumber(branchAddress) + '.'); DelayedLog.pushTab(); this.getSubroutineAddresses(branchAddress, addrsArray); DelayedLog.popTab(); } } // Now check next address address += opcodeClone.length; } while (!(opcodeClone.flags & OpcodeFlag.STOP)); } /** * Reduces the given array to a coherent area. I.e. if there is a "hole" * inside the subroutine the parts are treated as two separte subroutines. * @param address The start address of the subroutine. * @param addrsArray The array with addresses (was filled by this.getSubroutineAddresses). */ protected reduceSubroutineAddresses(address: number, addrsArray: Array<number>) { // sort array addrsArray.sort((a, b) => a - b); // Throw away all addresses smaller than the start address const array = addrsArray.filter(value => value >= address); // It's just required to disassemble the straight line of addresses, no branches. addrsArray.length = 0; // clear array let nextAddress = address; for (const addr of array) { // Check for coherent block if (addr != nextAddress) break; // get opcode const opcode = Opcode.getOpcodeAt(this.memory, addr); // Add to array addrsArray.push(nextAddress); // Next nextAddress = addr + opcode.length; } } /** * Iterates through all Labels. * Fills the 'this.addressParents' array with the parent references for each address. * Afterwards it removes all self-references in Labels.references. */ protected addParentReferences() { for (let [address, label] of this.labels) { // Get all addresses belonging to a subroutine and set the parent values of // the associated labels. const type = label.type; if (type == NumberType.CODE_SUB || type == NumberType.CODE_RST || type == NumberType.CODE_LBL) { // Collect all addresses belonging to a subroutine DelayedLog.startLog(); this.setSubroutineParent(address, label); DelayedLog.logIf(address, () => '' + Format.getHexString(address, 4) + ' processed.' ); DelayedLog.stopLog(); } } // Remove self references, e.g. a subroutine that includes a loop that // jumps to itself. for (let [address, label] of this.labels) { const refs = label.references; let anyRefOutside = false; for (let ref of refs) { const addr = ref; const parentLabel = this.addressParents[addr]; if (parentLabel == label) { // self-reference: // Check if reference is a call: const memAttr = this.memory.getAttributeAt(ref); assert(memAttr & MemAttribute.ASSIGNED); assert(memAttr & MemAttribute.CODE); assert(memAttr & MemAttribute.CODE_FIRST); // Check opcode const opcode = Opcode.getOpcodeAt(this.memory, ref); if (!(opcode.flags & OpcodeFlag.CALL)) { // No, it was no call, so it must be a jump. Remove reference. refs.delete(ref); } } else { // There was at least one reference from outside the sub routine anyRefOutside = true; } } // Check if sub routine cannot be called from outside. if (!anyRefOutside && (label.type == NumberType.CODE_SUB || label.type == NumberType.CODE_RST) && refs.size > 0) { // If there is no call/jp from outside the subroutine itself and if label // is a subroutine then the CALL did only come from the subroutine // itself -> do a warning. Maybe this was a programming error in the assembler code. // Note: It is also checked if there is no ref at all to exclude the interrupts. this.emit('warning', 'Address: ' + Format.getHexString(address, 4) + 'h. A subroutine was found that calls itself recursively but is not called from any other location.'); this.dotMarkedLabels.set(address, this.dotWarningMark); } } } /** * Collects an array with all addresses used by the subroutine * given at 'address'. * Does stop if it reaches a label of another subroutine. * The array also contains the start address. * Fills the 'this.addressParents' array. * Works recursively. * Note: does work also on CODE_LBL. * @param addr The start address of the subroutine. * @param parentLabel The label to associate the found addresses with. */ protected setSubroutineParent(addr: number, parentLabel: DisLabel) { let opcodeClone; let address = addr; do { // Check if memory exists const memAttr = this.memory.getAttributeAt(address); if (!(memAttr & MemAttribute.ASSIGNED)) { DelayedLog.log(() => 'setSubroutineParent: address=' + DelayedLog.getNumber(address) + ': returns. memory not assigned.'); break; } // Check if parent already assigned const memLabel = this.addressParents[address]; if (memLabel) { DelayedLog.log(() => 'setSubroutineParent: address=' + DelayedLog.getNumber(address) + ': returns. memory already checked.'); break; // already checked } // Check if label is sub routine const label = this.labels.get(address); if (label) { if (label != parentLabel) { // Omit start address const type = label.type; if (type == NumberType.CODE_SUB || type == NumberType.CODE_RST || type == NumberType.CODE_LBL ) break; // Stop if label which is LBL, CALL or RST is reached } } // check opcode const opcode = Opcode.getOpcodeAt(this.memory, address); opcodeClone = {...opcode}; // Required otherwise opcode is overwritten on next call to 'getOpcodeAt' if it's the same opcode. // Add to array this.addressParents[address] = parentLabel; DelayedLog.log(() => 'setSubroutineParent: address=' + DelayedLog.getNumber(address) + ': added. ' + opcodeClone.name); // And maybe branch address if (opcodeClone.flags & OpcodeFlag.BRANCH_ADDRESS) { // if(!(opcodeClone.flags & OpcodeFlag.CALL)) { // Check if a label exists to either a subroutine or another absolute label. const branchAddress = opcodeClone.value; /*const branchLabel = this.labels.get(branchAddress); if(!branchLabel || branchLabel.type == NumberType.CODE_LBL || branchLabel.type == NumberType.CODE_SUB || branchLabel.type == NumberType.CODE_RST) */ { DelayedLog.log(() => 'setSubroutineParent: address=' + DelayedLog.getNumber(address) + ': branching to ' + DelayedLog.getNumber(branchAddress) + '.\n'); DelayedLog.pushTab(); this.setSubroutineParent(branchAddress, parentLabel); DelayedLog.popTab(); } } // Now check next address address += opcodeClone.length; } while (!(opcodeClone.flags & OpcodeFlag.STOP)); DelayedLog.log(() => 'setSubroutineParent: address=' + DelayedLog.getNumber(address) + ': stop.\n'); } /** * Adds the 'calls'-list to the subroutine labels. * The reference list already includes the references (subroutines) who * call the label. * Now a list should be added to the label which contains all called * subroutines. * This is for call-graphs and for the comments in the listing. */ protected addCallsListToLabels() { for (let [, label] of this.labels) { switch (label.type) { case NumberType.CODE_SUB: case NumberType.CODE_RST: case NumberType.CODE_LBL: // go through references const refs = label.references; for (const ref of refs) { // Get parent const parent = this.addressParents[ref]; if (parent) { // add label to call list of parent parent.calls.push(label); } } } } } /** * Calculates the statistics like size or cyclomatic complexity of all * subroutines. * Fills the 'subroutineStatistics' map. */ protected countStatistics() { // Loop through all labels for (let [address, label] of this.labels) { if (label.isEqu) continue; switch (label.type) { case NumberType.CODE_RST: // Check if rst is turned off if (this.rstDontFollowAddresses.indexOf(address) >= 0) { const statistics = {sizeInBytes: 0, countOfInstructions: 0, CyclomaticComplexity: 0}; this.subroutineStatistics.set(label, statistics); break; // Don't count statistics. } // Otherwise flow through. case NumberType.CODE_SUB: case NumberType.CODE_LBL: // Get all addresses belonging to the subroutine const addresses = new Array<number>(); const statistics = this.countAddressStatistic(address, addresses); statistics.CyclomaticComplexity++; // Add 1 as default this.subroutineStatistics.set(label, statistics); // Get max if (statistics.sizeInBytes > this.statisticsMax.sizeInBytes) this.statisticsMax.sizeInBytes = statistics.sizeInBytes; if (statistics.countOfInstructions > this.statisticsMax.countOfInstructions) this.statisticsMax.countOfInstructions = statistics.countOfInstructions; if (statistics.CyclomaticComplexity > this.statisticsMax.CyclomaticComplexity) this.statisticsMax.CyclomaticComplexity = statistics.CyclomaticComplexity; // Get min if (statistics.sizeInBytes < this.statisticsMin.sizeInBytes) this.statisticsMin.sizeInBytes = statistics.sizeInBytes; if (statistics.countOfInstructions < this.statisticsMin.countOfInstructions) this.statisticsMin.countOfInstructions = statistics.countOfInstructions; if (statistics.CyclomaticComplexity < this.statisticsMin.CyclomaticComplexity) this.statisticsMin.CyclomaticComplexity = statistics.CyclomaticComplexity; } } } /** * Calculates statistics like size or cyclomatic complexity. * Works recursively. * @param address The start address of the subroutine. * @param addresses An empty array in the beginning that is filled with * all addresses of the subroutine. Used to escape from loops. * @returns statistics: size so far, cyclomatic complexity. */ protected countAddressStatistic(address: number, addresses: Array<number>): SubroutineStatistics { let statistics = {sizeInBytes: 0, countOfInstructions: 0, CyclomaticComplexity: 0}; let opcodeClone; do { // Check if memory exists const memAttr = this.memory.getAttributeAt(address); if (!(memAttr & MemAttribute.ASSIGNED)) { return statistics; } // Unfortunately it needs to be checked if address has been checked already if (addresses.indexOf(address) >= 0) return statistics; // already checked // Add to array addresses.push(address); // check opcode const opcode = Opcode.getOpcodeAt(this.memory, address); opcodeClone = {...opcode}; // Required otherwise opcode is overwritten on next call to 'getOpcodeAt' if it's the same opcode. // Add statistics statistics.sizeInBytes += opcodeClone.length; statistics.countOfInstructions++; // Cyclomatic complexity: add 1 for each conditional branch if (opcodeClone.flags & OpcodeFlag.BRANCH_ADDRESS) { // Now exclude unconditional CALLs, JPs and JRs if (opcode.name.indexOf(',') >= 0) statistics.CyclomaticComplexity++; } else if ((opcodeClone.flags & OpcodeFlag.RET) && (opcodeClone.flags & OpcodeFlag.CONDITIONAL)) { // It is a conditional return statistics.CyclomaticComplexity++; } // And maybe branch address if (opcodeClone.flags & OpcodeFlag.BRANCH_ADDRESS) { if (!(opcodeClone.flags & OpcodeFlag.CALL)) { // Only branch if no CALL, but for conditional and conditional JP or JR. // At last check if the JP/JR might jump to a subroutine. This wouldn't be followed. const branchAddress = opcodeClone.value; const branchLabel = this.labels.get(branchAddress); let isSUB = false; if (branchLabel) if (branchLabel.type == NumberType.CODE_SUB || branchLabel.type == NumberType.CODE_RST) isSUB = true; // Only if no subroutine if (!isSUB) { const addStat = this.countAddressStatistic(branchAddress, addresses); statistics.sizeInBytes += addStat.sizeInBytes; statistics.countOfInstructions += addStat.countOfInstructions; statistics.CyclomaticComplexity += addStat.CyclomaticComplexity; } } } // Next address += opcodeClone.length; // Stop at flow-through const nextLabel = this.labels.get(address); if (nextLabel) { const type = nextLabel.type; if (type == NumberType.CODE_SUB || type == NumberType.CODE_RST) break; // Stop when entering another subroutine. } } while (!(opcodeClone.flags & OpcodeFlag.STOP)); // return return statistics; } /// Assign label names. /// Is done in 2 passes: /// 1. the major labels (e.g. "SUBnnn") are assigned and also the local label names without number. /// 2. Now the local label name numbers are assigned. /// Reason is that the count of digits for the local label numbers is not known upfront. protected assignLabelNames() { // Check if a custom function should be used. if (this.funcAssignLabels) { for (const [address, label] of this.labels) { label.name = this.funcAssignLabels(address); } return; } // Count labels ---------------- // Count all local labels. const localLabels = new Map<DisLabel, Array<DisLabel>>(); const localLoops = new Map<DisLabel, Array<DisLabel>>(); // Count labels let labelSubCount = 0; let labelLblCount = 0; let labelDataLblCount = 0; let labelSelfModifyingCount = 0; // Loop through all labels for (const [address, label] of this.labels) { const type = label.type; switch (type) { // Count main labels case NumberType.CODE_SUB: labelSubCount++; break; case NumberType.CODE_LBL: labelLblCount++; break; case NumberType.DATA_LBL: const memAttr = this.memory.getAttributeAt(address); if (memAttr & MemAttribute.CODE) { labelSelfModifyingCount++; } else { labelDataLblCount++; } break; // Collect local labels case NumberType.CODE_LOCAL_LBL: case NumberType.CODE_LOCAL_LOOP: const parentLabel = this.addressParents[address]; //assert(parentLabel, 'assignLabelNames 1'); if (parentLabel) { // This might not be set if address was set by addAddressToQueue. const arr = (type == NumberType.CODE_LOCAL_LBL) ? localLabels : localLoops; let labelsArray = arr.get(parentLabel); if (!labelsArray) { labelsArray = new Array<DisLabel>(); arr.set(parentLabel, labelsArray); } labelsArray.push(label); } break; } } // Calculate digit counts const labelSubCountDigits = labelSubCount.toString().length; const labelLblCountDigits = labelLblCount.toString().length; const labelDataLblCountDigits = labelDataLblCount.toString().length; const labelSelfModifyingCountDigits = labelSelfModifyingCount.toString().length; // Assign names. First the main labels. // Start indexes let subIndex = 1; // CODE_SUB let lblIndex = 1; // CODE_LBL let dataLblIndex = 1; // DATA_LBL let dataSelfModifyingIndex = 1; // SELF_MOD // Loop through all labels (labels is sorted by address) for (const [address, label] of this.labels) { // Check if label was already set (e.g. from commandline) if (label.name) continue; // Process label const type = label.type; switch (type) { case NumberType.CODE_SUB: // Set name label.name = (label.belongsToInterrupt) ? this.labelIntrptPrefix : '' + this.labelSubPrefix + this.getIndex(subIndex, labelSubCountDigits); // Next subIndex++; break; case NumberType.CODE_LBL: // Set name label.name = (label.belongsToInterrupt) ? this.labelIntrptPrefix : '' + this.labelLblPrefix + this.getIndex(lblIndex, labelLblCountDigits); // Next lblIndex++; break; case NumberType.CODE_RST: // Set name label.name = this.labelRstPrefix + Format.getHexString(address, 2); break; case NumberType.DATA_LBL: // Check for self.modifying code const memAttr = this.memory.getAttributeAt(address); if (memAttr & MemAttribute.CODE) { assert(memAttr & MemAttribute.CODE_FIRST, 'assignLabelNames 2'); // Yes, is self-modifying code. // Set name label.name = this.labelSelfModifyingPrefix + this.getIndex(dataSelfModifyingIndex, labelSelfModifyingCountDigits); // Next dataSelfModifyingIndex++; } else { // Normal data area. // Set name label.name = this.labelDataLblPrefix + this.getIndex(dataLblIndex, labelDataLblCountDigits); // Next dataLblIndex++; } break; } } // At the end the local labels --- // Loop through all labels (labels is sorted by address) // Local Labels: for (const [parentLabel, childLabels] of localLabels) { const localPrefix = parentLabel.name.toLowerCase(); const count = childLabels.length; const digitCount = count.toString().length; // Set names let index = 1; for (let child of childLabels) { const indexString = this.getIndex(index, digitCount); child.name = '.' + localPrefix + this.labelLocalLablePrefix; if (count > 1) child.name += indexString; index++; } } // Local Loops: for (let [parentLabel, childLabels] of localLoops) { const localPrefix = parentLabel.name.toLowerCase(); const count = childLabels.length; const digitCount = count.toString().length; // Set names let index = 1; for (let child of childLabels) { const indexString = this.getIndex(index, digitCount); child.name = '.' + localPrefix + this.labelLoopPrefix; if (count > 1) child.name += indexString; index++; } } } /** * Add/create the comments for the labels. * If a comment already exists (e.g. set by the user) it is not overwritten. */ protected addLabelComments() { // Loop through all labels (labels is sorted by address) for (const [address, label] of this.labels) { // Only for the main labels const type = label.type; if (type != NumberType.CODE_SUB && type != NumberType.CODE_RST && type != NumberType.CODE_LBL && type != NumberType.DATA_LBL) continue; // Check if comment already exists let comment = this.addressComments.get(address); if (comment) continue; // Create comment comment = this.getAddressComment(address); if (comment) this.addressComments.set(address, comment); } } /** * Returns the 3 comment lines for an address. * It first searches if there is a label at that address. * If label exists * - if there is a comment in addressComments then this * comment is returned. * - otherwise the comment for the label is generated. * If label does not exist * - the comment from addressComments is returned. * @param address The address. */ protected getAddressComment(address: number): Comment | undefined { if (this.disableCommentsInDisassembly) return undefined; let comments = this.addressComments.get(address); if (comments) return comments; return this.getLabelComments(address); } /** * Creates a human readable string telling which locations reference this address * and which locations are called (if it is a subroutine). * @param address The address. * @return The comment with statistics about the label. E.g. for * subroutines is tells the size , cyclomatic complexity, all callers and all callees. */ protected getLabelComments(address: number): Comment | undefined { const addrLabel = this.labels.get(address); if (!addrLabel) return undefined; const lineArray = new Array<string>(); const refCount = addrLabel.references.size; let line1; let line2; let line3; // Name const type = addrLabel.type; let name; switch (type) { case NumberType.CODE_SUB: name = 'Subroutine'; break; case NumberType.CODE_RST: name = 'Restart'; break; case NumberType.DATA_LBL: name = 'Data'; break; default: name = 'Label'; break; } // Aggregate output string switch (type) { case NumberType.CODE_SUB: case NumberType.CODE_RST: { // Line 2 line2 = 'Called by: '; let first = true; let recursiveFunction = false; for (const ref of addrLabel.references) { if (!first) line2 += ', '; const s = Format.getHexString(ref, 4) + 'h'; const parent = this.addressParents[ref]; if (parent) { let parName; if (parent == addrLabel) { parName = 'self'; recursiveFunction = true; } else parName = parent.name; line2 += parName + '[' + s + ']'; } else line2 += s; first = false; } // Check if anything has been output line2 += (addrLabel.references.size > 0) ? '.' : '-'; // Line 1 line1 = name; const stat = this.subroutineStatistics.get(addrLabel); if (stat) line1 += ': ' + ((recursiveFunction) ? 'Recursive, ' : '') + 'Size=' + stat.sizeInBytes + ', CC=' + stat.CyclomaticComplexity + '.'; else line1 += '.'; // Store lines lineArray.push(line1); lineArray.push(line2); // Only if "Calls:" line is wanted if (!addrLabel.isEqu) { // Line 3 line3 = 'Calls: '; first = true; const callees = new Set<DisLabel>(); for (const callee of addrLabel.calls) { callees.add(callee); } line3 += Array.from(callees).map(refLabel => refLabel.name).join(', '); // Check if anything has been output line3 += (callees.size > 0) ? '.' : '-'; lineArray.push(line3); } break; } default: { line1 = name; line1 += (refCount > 0) ? ' accessed by:' : ' not accessed.'; lineArray.push(line1); // 2nd line if (refCount > 0) { // Second line: The references const refArray = [...addrLabel.references].map(addr => { let s = Format.getHexString(addr, 4) + 'h'; const parentLabel = this.addressParents[addr]; if (parentLabel) { // Add e.g. start of subroutine s += '(in ' + parentLabel.name + ')'; } return s; }); const line2 = refArray.join(', '); lineArray.push(line2); } break; } } // For EQU labels return everything in one line. let comment = new Comment(); if (addrLabel.isEqu) { comment.inlineComment = '; ' + address.toString() + '. ' + lineArray.join(' '); } else { // Put the lines in the comments structure comment.linesBefore = lineArray.map(s => '; ' + s); } // return return comment; } /** * Reads in a file from the user that sets address labels and the comments to show in the disassembly. * @param commentsFile The file to read. Format: * ; comment1 * address: label ; comment2 * ; comments 3 * newline(s) */ public setAddressComments(commentsFile: string) { enum State { LinesBefore, lineOn, LinesAfter, }; const commentsLines = readFileSync(commentsFile).toString().split('\n'); commentsLines.push(''); // Add empty line to make sure the last comment is processed. let state = State.LinesBefore; let comment = new Comment(); let commentAddr; let commentLabelName; let lineNr = 0; for (const line of commentsLines) { lineNr++; // Read in comments "before" const match = /^\s*([^;]+)?(;.*)?(\S+)?/.exec(line)!; assert(match); const addressPart = match[1]; const commentPart = match[2]; const misc = match[3]; if (misc) { // Unexpected line throw Error('Unexpected line: "' + line + '", ' + commentsFile + ':' + lineNr + '.'); } if (!addressPart && !commentPart) { // Comment finished, line empty if (commentAddr != undefined) { // Set comment this.addressComments.set(commentAddr, comment); // Set label if (commentLabelName) { this.setLabel(commentAddr, commentLabelName, NumberType.DATA_LBL); // Data label might be changed to something else. } } // Next state state = State.LinesBefore; comment = new Comment(); commentAddr = undefined; commentLabelName = undefined; continue; } // check for state change if (addressPart) { if (state == State.LinesBefore) { // Next state state = State.lineOn; } } // add lines switch (state) { case State.LinesBefore: comment.addBefore(commentPart); break; case State.lineOn: comment.inlineComment = commentPart; // Determine address and label const match2 = /^(0x)?([0-9a-f]+)(\s+([\w\.]+))?/i.exec(addressPart); if (match2) { const addrString = match2[2]; commentAddr = parseInt(addrString, 16); commentLabelName = match2[4]; // Next state state = State.LinesAfter; } else { throw Error('Expected an address: "' + line + '", ' + commentsFile + ':' + lineNr + '.'); } break; case State.LinesAfter: if (addressPart) { throw Error('Expected "after"-comment or newline: "' + line + '", ' + commentsFile + ':' + lineNr + '.'); } comment.addAfter(match[2]); break; } } } /** * Returns all (main) labels with address and comments. */ public getMainLabels(): string { let text = ''; for (let [address, label] of this.labels) { const type = label.type; if (type != NumberType.CODE_SUB && type != NumberType.CODE_LBL && type != NumberType.CODE_RST && type != NumberType.DATA_LBL) continue; // Store address, label and comments const addrLabelLine = Format.getHexString(address, 4) + '\t' + label.name; const comment = this.getAddressComment(address); const commentLines = Comment.getLines(comment, addrLabelLine, this.disableCommentsInDisassembly); text += commentLines.join('\n'); // Next text += '\n\n'; } // Return return text; } /** * Disassemble opcodes together with label names. * Returns an array of strings which contains the disassembly. * @returns The disassembly. */ protected disassembleMemory(): Array<string> { let lines = new Array<string>(); // Check if anything to disassemble if (this.labels.size == 0) return lines; // Loop over all labels let address = -1; for (const [addr, label] of this.labels) { if (label.isEqu) continue; // Skip EQUs // If first line, print ORG if (address == -1) { // First line // Print "ORG" this.addEmptyLines(lines); let orgLine = ' '.repeat(this.clmnsBytes) + this.rightCase('ORG ') + Format.getHexString(addr) + 'h'; if (!this.disableCommentsInDisassembly) orgLine += '; ' + Format.getConversionForAddress(addr); lines.push(orgLine); } else { // Normal case. All other lines but first line. const unassignedSize = addr - address; if (unassignedSize < 0) continue; // Print new "ORG" this.addEmptyLines(lines); let orgLine = ' '.repeat(this.clmnsBytes) + this.rightCase('ORG ') + Format.getHexString(addr) + 'h'; if (!this.disableCommentsInDisassembly) orgLine += '; ' + Format.getConversionForAddress(addr); lines.push(orgLine); } // Use address address = addr; let prevMemoryAttribute = MemAttribute.DATA; let prevParent; // disassemble until unassigned memory found while (true) { //console.log('disMem: address=0x' + address.toString(16)) // Check if memory has already been disassembled let attr = this.memory.getAttributeAt(address); if (!(attr & MemAttribute.ASSIGNED)) { break; // E.g. an EQU label } // Get association of address this.resetAddEmptyLine(); const parent = this.addressParents[address]; if (parent != prevParent) { this.addEmptyLines(lines); prevParent = parent; } // Check if label needs to be added to line (print label on own line) const addrLabel = this.labels.get(address); const comment = this.addressComments.get(address); if (addrLabel) { // Add empty lines in case this is a SUB, LBL or DATA label const type = addrLabel.type; if (type == NumberType.CODE_SUB || type == NumberType.CODE_LBL || type == NumberType.DATA_LBL || type == NumberType.CODE_RST) { this.addEmptyLines(lines); } // Add label on separate line let labelLine = addrLabel.name + ':'; if (this.clmnsAddress > 0) { labelLine = Format.addSpaces(Format.getHexString(address), this.clmnsAddress) + labelLine; if (this.DBG_ADD_DEC_ADDRESS) { labelLine = Format.addSpaces(address.toString(), 5) + ' ' + labelLine; } } // Add comments const commentLines = Comment.getLines(comment, labelLine, this.disableCommentsInDisassembly); lines.push(...commentLines); } // Check if code or data should be disassembled let addAddress; let line; let commentText; if (attr & MemAttribute.CODE) { // CODE // Read opcode at address const opcode = Opcode.getOpcodeAt(this.memory, address); // Disassemble the single opcode const opCodeDescription = opcode.disassemble(this.memory); line = this.formatDisassembly(address, opcode.length, opCodeDescription.mnemonic); commentText = opCodeDescription.comment; addAddress = opcode.length; } else { // DATA if (!(prevMemoryAttribute & MemAttribute.DATA)) this.addEmptyLines(lines); // Turn memory to data memory attr |= MemAttribute.DATA; // Read memory value at address let memValue = this.memory.getValueAt(address); // Disassemble the data line let mainString = this.rightCase('DEFB ') + Format.getHexString(memValue, 2) + 'h'; commentText = Format.getVariousConversionsForByte(memValue); line = this.formatDisassembly(address, 1, mainString); // Next address addAddress = 1; } // Debug if (this.DBG_ADD_DEC_ADDRESS) { line = Format.addSpaces(address.toString(), 5) + ' ' + line; } // If not done before, add comments if (!comment || addrLabel) { // main comment already added or no comment present if (!this.disableCommentsInDisassembly && commentText && commentText.length > 0) line += '\t; ' + commentText; lines.push(line); } else { // Add comments const commentLines = Comment.getLines(comment, line, this.disableCommentsInDisassembly); lines.push(...commentLines); } // Next address address += addAddress; // Check if the next address is not assigned and put out a comment let attrEnd = this.memory.getAttributeAt(address); if (address < 0x10000) { if (!this.disableCommentsInDisassembly && !(attrEnd & MemAttribute.ASSIGNED)) { lines.push('; ...'); lines.push('; ...'); lines.push('; ...'); } } prevMemoryAttribute = attr; // Log // console.log('DISASSEMBLY: ' + lines[lines.length-1]); } } // Return return lines; } /** * Formats a disassembly string for output. * @param address The address (for conditional output of the opcode byte values) * @param size The size of the opcode. * @param mainString The opcode string, e.g. "LD HL,35152" */ protected formatDisassembly(address: number, size: number, mainString: string): string { const memory = (this.addOpcodeBytes) ? this.memory : undefined; return Format.formatDisassembly(memory, this.opcodesLowerCase, this.clmnsAddress, this.clmnsBytes, this.clmnsOpcodeFirstPart, this.clmsnOpcodeTotal, address, size, mainString); } /** * Returns the index as string digits are filled to match countDigits. * @param index The index to convert. * @param countDigits The number of digits to use. */ protected getIndex(index: number, countDigits: number) { const str = index.toString(); return '0'.repeat(countDigits - str.length) + str; } /** * Adds empty lines to the given array. * The count depends on 'numberOfLinesBetweenBlocks'. * @param lines Array to add the empty lines. */ protected addEmptyLines(lines: Array<string>) { if (this.emptyLinesWritten) return; // Already written for (let i = 0; i < this.numberOfLinesBetweenBlocks; i++) { lines.push(''); } this.emptyLinesWritten = true; } /** * Enables writing empyty lines. * Used to prohibit that empty lines are written more than once. */ protected resetAddEmptyLine() { this.emptyLinesWritten = false; } /** * Depending on 'opcodesLowerCase' the given string will be changed to lowercase. * @param s The string to convert. Must be in upper case. * @returns The same string or the lowercased string. */ protected rightCase(s: string): string { // Lowercase? if (this.opcodesLowerCase) return s.toLowerCase(); return s; } /** * Creates a reverted map from the this.labels map (<address, DisLabel>). * The created map consists of key-value pairs <name,address> * and is stored in this.revertedLabelMap. */ public createRevertedLabelMap() { this.revertedLabelMap = new Map<string, number>(); for (const [address, label] of this.labels) { this.revertedLabelMap.set(label.getName(), address); } } /** * Returns a map of chosen addresses, labels for creating the * dot graph. */ public getGraphLabels(addrString: number | string, chosenLabels?: Map<number, DisLabel>): Map<number, DisLabel> { // Crete new map if (!chosenLabels) chosenLabels = new Map<number, DisLabel>(); // Convert to number let addr; if (typeof (addrString) == 'string') { addr = this.revertedLabelMap.get(addrString); if (!addr) throw Error('Could not find "' + addrString + '" while creating graph.'); } else { // Number addr = addrString; } // Now get label const label = this.labels.get(addr); if (!label) throw Error('Could not find address for "' + addrString + '" while creating graph.'); // Check if already in map if (!chosenLabels.get(addr)) { // Save in new map chosenLabels.set(addr, label); // Also add the called sub routines for (const called of label.calls) { // Recursive const callee = called.getName(); this.getGraphLabels(callee, chosenLabels); } } // Return return chosenLabels; } /** * Returns the labels call graph in dot syntax. * Every main labels represents a bubble. * Arrows from one bubble to the other represents * calling the function. * Call 'createRevertedLabelMap' before calling this function. * @param labels The labels to print. * @param name The name of the graph. * @returns The dot graphic as text. */ public getCallGraph(labels: Map<number, DisLabel>): string { const rankSame1 = new Array<string>(); const rankSame2 = new Array<string>(); // header let text = 'digraph Callgraph {\n\n'; text += this.dotFormatString + '\n'; // Calculate size (font size) max and min const fontSizeMin = 13; const fontSizeMax = 40; //const min = this.statisticsMin.sizeInBytes; //const fontSizeFactor = (fontSizeMax-fontSizeMin) / (this.statisticsMax.sizeInBytes-min); const min = this.statisticsMin.CyclomaticComplexity; const complDiff = this.statisticsMax.CyclomaticComplexity - min const fontSizeFactor = (fontSizeMax - fontSizeMin) / ((complDiff < 8) ? 8 : complDiff); // Loop for (const [address, label] of labels) { const type = label.type; if (type != NumberType.CODE_SUB && type != NumberType.CODE_LBL && type != NumberType.CODE_RST) continue; //console.log(label.name + '(' + Format.getHexString(address) + '):') // Handle fill color (highlights) let colorString = this.dotMarkedLabels.get(address); if (!colorString) { // Now try also the label name colorString = this.dotMarkedLabels.get(label.getName()); } // Skip other labels if (label.isEqu) { // output gray label to indicate an EQU label if (!colorString) colorString = 'lightgray'; text += label.name + ' [fontsize="' + fontSizeMin + '"];\n'; const nodeName = this.nodeFormat(label.name, label.id, address, undefined, undefined, undefined); text += label.name + ' [label="' + nodeName + '"];\n'; } else { // A normal label. // Size const stats = this.subroutineStatistics.get(label)!; assert(stats); const fontSize = fontSizeMin + fontSizeFactor * (stats.CyclomaticComplexity - min); // Output text += '"' + label.name + '" [fontsize="' + Math.round(fontSize) + '"];\n'; const nodeName = this.nodeFormat(label.name, label.id, address, stats.CyclomaticComplexity, stats.sizeInBytes, stats.countOfInstructions); text += '"' + label.name + '" [label="' + nodeName + '"];\n'; //text += '"' + label.name + '" [label="' + label.name + '\\nID=' + label.id + '\\nCC=' + stats.CyclomaticComplexity + '\\n"];\n'; // List each callee only once const callees = new Set<DisLabel>(); for (const callee of label.calls) { callees.add(callee); } // Output all called labels in different color: if (label.references.size == 0 || label.type == NumberType.CODE_LBL) { //const callers = this.getCallersOf(label); if (!colorString) colorString = 'lightyellow'; if (label.references.size == 0) rankSame1.push(label.name); else rankSame2.push(label.name); } if (callees.size > 0) text += '"' + label.name + '" -> { ' + Array.from(callees).map(refLabel => '"' + refLabel.name + '"').join(' ') + ' };\n'; } // Color if (colorString) text += '"' + label.name + '" [fillcolor=' + colorString + ', style=filled];\n'; } // Do some ranking. // All labels without callers are ranked at the same level. if (rankSame1.length > 0) text += '\n{ rank=same; "' + rankSame1.join('", "') + '" };\n\n'; if (rankSame2.length > 0) text += '\n{ rank=same; "' + rankSame2.join('", "') + '" };\n\n'; // ending text += '}\n'; // return return text; } /** * Does the formatting for the node in the dot file. * @param labelName E.g. "SUB33" * @param labelId The unique number of each label. * @param address E.g. F7A9 * @param cc Cyclomatic Complexity, e.g. 3 * @param size Size in bytes. * @param instructions Number of instructions. */ protected nodeFormat(labelName: string, labelId: number, address: number, cc?: number, size?: number, instructions?: number): string { // Check if formatting is correct let text = this.nodeFormatString; try { text = text.replace(/\${label}/g, labelName); text = text.replace(/\${id}/g, labelId.toString()); text = text.replace(/\${address}/g, Format.getHexString(address, 4)); text = text.replace(/\${CC}/g, (cc) ? cc.toString() : '?'); text = text.replace(/\${size}/g, (size) ? size.toString() : '?'); text = text.replace(/\${instructions}/g, (instructions) ? instructions.toString() : '?'); } catch (e) { throw Error('Dot format string wrong: ' + e); } return text; } /** * Highlights a node (bubble) in the dot graphics. * @param addr The address (node) to highlight. * @param colorString The color used for highlighting. E.g. "yellow". */ public setDotHighlightAddress(addr: number | string, colorString: string) { this.dotMarkedLabels.set(addr, colorString); } /** * Returns a Flow-Chart for the given addresses. * Output can be used as input to graphviz. * @param startAddresses An array with the start address of the subroutines. */ public getFlowChart(startAddresses: Array<number>): string { // header let text = 'digraph FlowChart {\n\n'; // appearance text += 'node [shape=box];\n'; for (const startAddress of startAddresses) { // Start const label = this.labels.get(startAddress); const addressString = Format.getHexString(startAddress, 4); let name; if (label) name = label.name; if (!name) name += '0x' + addressString; const start = 'b' + addressString + 'start'; text += start + ' [label="' + name + '", fillcolor=lightgray, style=filled, shape=tab];\n'; text += start + ' -> b' + Format.getHexString(startAddress, 4) + ';\n'; const end = 'b' + addressString + 'end'; text += end + ' [label="end", shape=doublecircle];\n'; // Get all addresses belonging to the subroutine const addrsArray = new Array<number>(); this.getSubroutineAddresses(startAddress, addrsArray); // Now reduce array. I.e. only a coherent block will be treated as a subroutine. this.reduceSubroutineAddresses(startAddress, addrsArray); // get the text for all branches const processedAddrsArray = new Array<number>(); const bText = this.getBranchForAddress(startAddress, addrsArray, processedAddrsArray); text += bText; } // ending text += '\n}\n'; // return return text; } /** * Returns the text of one branch (or recursively more branches) * of the flowchart of one subroutine. * @param address The start address of the branch. * @param addrsArray The array that contains all addresses belonging to the subroutine. * @param processedAddrsArray At the start an empty array. Is filled with all processed addresses. */ protected getBranchForAddress(address: number, addrsArray: Array<number>, processedAddrsArray: Array<number>): string { const branch = 'b' + Format.getHexString(address, 4); let text = branch + ' [label="'; let disTexts: Array<string> = []; let opcode; do { // Add to new array processedAddrsArray.push(address); // check opcode opcode = Opcode.getOpcodeAt(this.memory, address); // Add disassembly to label text const disText = opcode.disassemble(); disTexts.push(disText.mnemonic); // Next address += opcode.length; // stop if a label is found if (this.labels.get(address)) break; } while (!(opcode.flags & OpcodeFlag.BRANCH_ADDRESS) // branch-address includes a CALL && !(opcode.flags & OpcodeFlag.RET) && !(opcode.flags & OpcodeFlag.STOP)); // finish text text += disTexts.join('\\l') + '\\l'; text += '"];\n' // Maybe branch if (opcode.flags & OpcodeFlag.BRANCH_ADDRESS) { const branchAddress = opcode.value; // Check if outside if (addrsArray.indexOf(branchAddress) >= 0) { // Inside text += branch + ' -> b' + Format.getHexString(branchAddress, 4) + ' [headport="n", tailport="e"];\n'; // Check if already disassembled if (processedAddrsArray.indexOf(branchAddress) < 0) { // No, so disassemble const textBranch = this.getBranchForAddress(branchAddress, addrsArray, processedAddrsArray); text += textBranch; } } } // Check if we need to call another branch if (!(opcode.flags & OpcodeFlag.STOP)) { // Call another branch. // Check if outside if (addrsArray.indexOf(address) >= 0) { // Inside text += branch + ' -> b' + Format.getHexString(address, 4) + ';\n'; // Check if already disassembled if (processedAddrsArray.indexOf(address) < 0) { // No, so disassemble const textBranch = this.getBranchForAddress(address, addrsArray, processedAddrsArray); text += textBranch; } } } // Check if subroutine ends here (RET or JP) if (opcode.flags & (OpcodeFlag.STOP | OpcodeFlag.RET)) { // Subroutine ends assert(addrsArray.length > 0); text += branch + ' -> b' + Format.getHexString(addrsArray[0], 4) + 'end;\n'; } // Return return text; } }
the_stack
import { Inject, Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { IEvent, IEventPublisher, EventBus, IMessageSource } from '@nestjs/cqrs'; import { ExplorerService } from '@nestjs/cqrs/dist/services/explorer.service'; import * as Long from 'long'; import { Subject } from 'rxjs'; import { v4 } from 'uuid'; import { EventData, EventStorePersistentSubscription, ResolvedEvent, EventStoreCatchUpSubscription, EventStoreSubscription as EventStoreVolatileSubscription, expectedVersion, createJsonEventData } from 'node-eventstore-client'; import { IAdapterStore } from '../adapter'; import { EventStoreOptionConfig, IEventConstructors, EventStoreSubscriptionType, EventStorePersistentSubscription as ESPersistentSubscription, EventStoreCatchupSubscription as ESCatchUpSubscription, EventStoreVolatileSubscription as ESVolatileSubscription, ExtendedCatchUpSubscription, ExtendedVolatileSubscription, ExtendedPersistentSubscription, ProvidersConstants, EventStoreModuleOptions } from '../contract'; import { EventStoreBroker } from '../brokers'; /** * @class EventStore */ @Injectable() export class EventStore implements IEventPublisher, OnModuleDestroy, OnModuleInit, IMessageSource { private logger = new Logger(this.constructor.name); private eventStore: EventStoreBroker; private store: IAdapterStore; private eventHandlers: IEventConstructors; private subject$: Subject<IEvent>; private readonly featureStream?: string; private catchupSubscriptions: Array< Promise<ExtendedCatchUpSubscription> > = []; private catchupSubscriptionsCount: number; private persistentSubscriptions: ExtendedPersistentSubscription[] = []; private persistentSubscriptionsCount: number; private volatileSubscriptions: ExtendedVolatileSubscription[] = []; private volatileSubscriptionsCount: number; constructor( @Inject(ProvidersConstants.EVENT_STORE_PROVIDER) eventStore: any, @Inject(ProvidersConstants.EVENT_STORE_CONNECTION_CONFIG_PROVIDER) configService: EventStoreModuleOptions, @Inject(ProvidersConstants.EVENT_STORE_STREAM_CONFIG_PROVIDER) esStreamConfig: EventStoreOptionConfig, private readonly explorerService: ExplorerService, private readonly eventsBus: EventBus ) { this.eventStore = eventStore; this.featureStream = esStreamConfig.featureStreamName; if (esStreamConfig.type === 'event-store') { this.store = esStreamConfig.store; } else { throw new Error('Event store type is not supported - (event-tore.ts)'); } this.addEventHandlers(esStreamConfig.eventHandlers); if (configService.type === 'event-store') { this.eventStore.connect(configService.options, configService.tcpEndpoint); const catchupSubscriptions = esStreamConfig.subscriptions.filter(sub => { return sub.type === EventStoreSubscriptionType.CatchUp; }); const persistentSubscriptions = esStreamConfig.subscriptions.filter( sub => { return sub.type === EventStoreSubscriptionType.Persistent; } ); const volatileSubscriptions = esStreamConfig.subscriptions.filter(sub => { return sub.type === EventStoreSubscriptionType.Volatile; }); this.subscribeToCatchUpSubscriptions( catchupSubscriptions as ESCatchUpSubscription[] ); this.subscribeToPersistentSubscriptions( persistentSubscriptions as ESPersistentSubscription[] ); this.subscribeToVolatileSubscriptions( volatileSubscriptions as ESVolatileSubscription[] ); } else { throw new Error('Event store type is not supported for feature - (event-tore.ts)'); } } async publish(event: IEvent, stream?: string) { if (event === undefined) { return; } if (event === null) { return; } const eventPayload: EventData = createJsonEventData( v4(), event, null, stream ); const streamId = stream ? stream : this.featureStream; try { await this.eventStore .getClient() .appendToStream(streamId, expectedVersion.any, [eventPayload]); } catch (err) { this.logger.error(err); } } async subscribeToPersistentSubscriptions( subscriptions: ESPersistentSubscription[] ) { this.persistentSubscriptionsCount = subscriptions.length; this.persistentSubscriptions = await Promise.all( subscriptions.map(async subscription => { return await this.subscribeToPersistentSubscription( subscription.stream, subscription.persistentSubscriptionName ); }) ); } async subscribeToCatchUpSubscriptions( subscriptions: ESCatchUpSubscription[] ) { this.catchupSubscriptionsCount = subscriptions.length; this.catchupSubscriptions = subscriptions.map(async subscription => { let lcp = subscription.lastCheckpoint; if (this.store) { lcp = await this.store.read(this.store.storeKey); } return this.subscribeToCatchupSubscription( subscription.stream, subscription.resolveLinkTos, lcp ); }); } async subscribeToVolatileSubscriptions( subscriptions: ESVolatileSubscription[] ) { this.volatileSubscriptionsCount = subscriptions.length; this.volatileSubscriptions = await Promise.all( subscriptions.map(async subscription => { return await this.subscribeToVolatileSubscription( subscription.stream, subscription.resolveLinkTos ); }) ); } subscribeToCatchupSubscription( stream: string, resolveLinkTos: boolean = true, lastCheckpoint: number | Long | null = 0 ): ExtendedCatchUpSubscription { this.logger.log(`Catching up and subscribing to stream ${stream}!`); try { return this.eventStore.getClient().subscribeToStreamFrom( stream, lastCheckpoint, resolveLinkTos, (sub, payload) => this.onEvent(sub, payload), subscription => this.onLiveProcessingStarted( subscription as ExtendedCatchUpSubscription ), (sub, reason, error) => this.onDropped(sub as ExtendedCatchUpSubscription, reason, error) ) as ExtendedCatchUpSubscription; } catch (err) { this.logger.error(err); } } async subscribeToVolatileSubscription( stream: string, resolveLinkTos: boolean = true ): Promise<ExtendedVolatileSubscription> { this.logger.log(`Volatile and subscribing to stream ${stream}!`); try { const resolved = (await this.eventStore.getClient().subscribeToStream( stream, resolveLinkTos, (sub, payload) => this.onEvent(sub, payload), (sub, reason, error) => this.onDropped(sub as ExtendedVolatileSubscription, reason, error) )) as ExtendedVolatileSubscription; this.logger.log('Volatile processing of EventStore events started!'); resolved.isLive = true; return resolved; } catch (err) { this.logger.error(err); } } get allCatchUpSubscriptionsLive(): boolean { const initialized = this.catchupSubscriptions.length === this.catchupSubscriptionsCount; return ( initialized && this.catchupSubscriptions.every(async subscription => { const s = await subscription; return !!s && s.isLive; }) ); } get allVolatileSubscriptionsLive(): boolean { const initialized = this.volatileSubscriptions.length === this.volatileSubscriptionsCount; return ( initialized && this.volatileSubscriptions.every(subscription => { return !!subscription && subscription.isLive; }) ); } get allPersistentSubscriptionsLive(): boolean { const initialized = this.persistentSubscriptions.length === this.persistentSubscriptionsCount; return ( initialized && this.persistentSubscriptions.every(subscription => { return !!subscription && subscription.isLive; }) ); } async subscribeToPersistentSubscription( stream: string, subscriptionName: string ): Promise<ExtendedPersistentSubscription> { try { this.logger.log(` Connecting to persistent subscription ${subscriptionName} on stream ${stream}! `); const resolved = (await this.eventStore .getClient() .connectToPersistentSubscription( stream, subscriptionName, (sub, payload) => this.onEvent(sub, payload), (sub, reason, error) => this.onDropped(sub as ExtendedPersistentSubscription, reason, error) )) as ExtendedPersistentSubscription; resolved.isLive = true; return resolved; } catch (err) { this.logger.error(err.message); } } async onEvent( _subscription: | EventStorePersistentSubscription | EventStoreCatchUpSubscription | EventStoreVolatileSubscription, payload: ResolvedEvent ) { const { event } = payload; if (!event || !event.isJson) { this.logger.error('Received event that could not be resolved!'); return; } const handler = this.eventHandlers[event.eventType]; if (!handler) { this.logger.error('Received event that could not be handled!'); return; } const rawData = JSON.parse(event.data.toString()); const data = Object.values(rawData); const eventType = event.eventType || rawData.content.eventType; if (this.eventHandlers && this.eventHandlers[eventType]) { this.subject$.next(this.eventHandlers[event.eventType](...data)); if ( this.store && _subscription.constructor.name === 'EventStoreStreamCatchUpSubscription' ) { await this.store.write( this.store.storeKey, payload.event.eventNumber.toInt() ); } } else { Logger.warn( `Event of type ${eventType} not handled`, this.constructor.name ); } } onDropped( subscription: | ExtendedPersistentSubscription | ExtendedCatchUpSubscription | ExtendedVolatileSubscription, _reason: string, error: Error ) { subscription.isLive = false; this.logger.error('onDropped => ' + error); } onLiveProcessingStarted(subscription: ExtendedCatchUpSubscription) { subscription.isLive = true; this.logger.log('Live processing of EventStore events started!'); } get isLive(): boolean { return ( this.allCatchUpSubscriptionsLive && this.allPersistentSubscriptionsLive && this.allVolatileSubscriptionsLive ); } addEventHandlers(eventHandlers: IEventConstructors) { this.eventHandlers = { ...this.eventHandlers, ...eventHandlers }; } onModuleInit(): any { this.subject$ = (this.eventsBus as any).subject$; this.bridgeEventsTo((this.eventsBus as any).subject$); this.eventsBus.publisher = this; } onModuleDestroy(): any { this.eventStore.close(); } async bridgeEventsTo<T extends IEvent>(subject: Subject<T>): Promise<any> { this.subject$ = subject; } }
the_stack
import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; import * as events from '@aws-cdk/aws-events'; import * as iam from '@aws-cdk/aws-iam'; import * as logs from '@aws-cdk/aws-logs'; import * as s3 from '@aws-cdk/aws-s3'; import * as cdk from '@aws-cdk/core'; import * as constructs from 'constructs'; import { Code, JobExecutable, JobExecutableConfig, JobType } from '.'; import { IConnection } from './connection'; import { CfnJob } from './glue.generated'; import { ISecurityConfiguration } from './security-configuration'; /** * The type of predefined worker that is allocated when a job runs. * * If you need to use a WorkerType that doesn't exist as a static member, you * can instantiate a `WorkerType` object, e.g: `WorkerType.of('other type')`. */ export class WorkerType { /** * Each worker provides 4 vCPU, 16 GB of memory and a 50GB disk, and 2 executors per worker. */ public static readonly STANDARD = new WorkerType('Standard'); /** * Each worker maps to 1 DPU (4 vCPU, 16 GB of memory, 64 GB disk), and provides 1 executor per worker. Suitable for memory-intensive jobs. */ public static readonly G_1X = new WorkerType('G.1X'); /** * Each worker maps to 2 DPU (8 vCPU, 32 GB of memory, 128 GB disk), and provides 1 executor per worker. Suitable for memory-intensive jobs. */ public static readonly G_2X = new WorkerType('G.2X'); /** * Custom worker type * @param workerType custom worker type */ public static of(workerType: string): WorkerType { return new WorkerType(workerType); } /** * The name of this WorkerType, as expected by Job resource. */ public readonly name: string; private constructor(name: string) { this.name = name; } } /** * Job states emitted by Glue to CloudWatch Events. * * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#glue-event-types for more information. */ export enum JobState { /** * State indicating job run succeeded */ SUCCEEDED = 'SUCCEEDED', /** * State indicating job run failed */ FAILED = 'FAILED', /** * State indicating job run timed out */ TIMEOUT = 'TIMEOUT', /** * State indicating job is starting */ STARTING = 'STARTING', /** * State indicating job is running */ RUNNING = 'RUNNING', /** * State indicating job is stopping */ STOPPING = 'STOPPING', /** * State indicating job stopped */ STOPPED = 'STOPPED', } /** * The Glue CloudWatch metric type. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitoring-awsglue-with-cloudwatch-metrics.html */ export enum MetricType { /** * A value at a point in time. */ GAUGE = 'gauge', /** * An aggregate number. */ COUNT = 'count', } /** * Interface representing a created or an imported {@link Job}. */ export interface IJob extends cdk.IResource, iam.IGrantable { /** * The name of the job. * @attribute */ readonly jobName: string; /** * The ARN of the job. * @attribute */ readonly jobArn: string; /** * Defines a CloudWatch event rule triggered when something happens with this job. * * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#glue-event-types */ onEvent(id: string, options?: events.OnEventOptions): events.Rule; /** * Defines a CloudWatch event rule triggered when this job moves to the input jobState. * * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#glue-event-types */ onStateChange(id: string, jobState: JobState, options?: events.OnEventOptions): events.Rule; /** * Defines a CloudWatch event rule triggered when this job moves to the SUCCEEDED state. * * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#glue-event-types */ onSuccess(id: string, options?: events.OnEventOptions): events.Rule; /** * Defines a CloudWatch event rule triggered when this job moves to the FAILED state. * * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#glue-event-types */ onFailure(id: string, options?: events.OnEventOptions): events.Rule; /** * Defines a CloudWatch event rule triggered when this job moves to the TIMEOUT state. * * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#glue-event-types */ onTimeout(id: string, options?: events.OnEventOptions): events.Rule; /** * Create a CloudWatch metric. * * @param metricName name of the metric typically prefixed with `glue.driver.`, `glue.<executorId>.` or `glue.ALL.`. * @param type the metric type. * @param props metric options. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitoring-awsglue-with-cloudwatch-metrics.html */ metric(metricName: string, type: MetricType, props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * Create a CloudWatch Metric indicating job success. */ metricSuccess(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * Create a CloudWatch Metric indicating job failure. */ metricFailure(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * Create a CloudWatch Metric indicating job timeout. */ metricTimeout(props?: cloudwatch.MetricOptions): cloudwatch.Metric; } abstract class JobBase extends cdk.Resource implements IJob { public abstract readonly jobArn: string; public abstract readonly jobName: string; public abstract readonly grantPrincipal: iam.IPrincipal; /** * Create a CloudWatch Event Rule for this Glue Job when it's in a given state * * @param id construct id * @param options event options. Note that some values are overridden if provided, these are * - eventPattern.source = ['aws.glue'] * - eventPattern.detailType = ['Glue Job State Change', 'Glue Job Run Status'] * - eventPattern.detail.jobName = [this.jobName] * * @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#glue-event-types */ public onEvent(id: string, options: events.OnEventOptions = {}): events.Rule { const rule = new events.Rule(this, id, options); rule.addTarget(options.target); rule.addEventPattern({ source: ['aws.glue'], detailType: ['Glue Job State Change', 'Glue Job Run Status'], detail: { jobName: [this.jobName], }, }); return rule; } /** * Create a CloudWatch Event Rule for the transition into the input jobState. * * @param id construct id. * @param jobState the job state. * @param options optional event options. */ public onStateChange(id: string, jobState: JobState, options: events.OnEventOptions = {}): events.Rule { const rule = this.onEvent(id, { description: `Rule triggered when Glue job ${this.jobName} is in ${jobState} state`, ...options, }); rule.addEventPattern({ detail: { state: [jobState], }, }); return rule; } /** * Create a CloudWatch Event Rule matching JobState.SUCCEEDED. * * @param id construct id. * @param options optional event options. default is {}. */ public onSuccess(id: string, options: events.OnEventOptions = {}): events.Rule { return this.onStateChange(id, JobState.SUCCEEDED, options); } /** * Return a CloudWatch Event Rule matching FAILED state. * * @param id construct id. * @param options optional event options. default is {}. */ public onFailure(id: string, options: events.OnEventOptions = {}): events.Rule { return this.onStateChange(id, JobState.FAILED, options); } /** * Return a CloudWatch Event Rule matching TIMEOUT state. * * @param id construct id. * @param options optional event options. default is {}. */ public onTimeout(id: string, options: events.OnEventOptions = {}): events.Rule { return this.onStateChange(id, JobState.TIMEOUT, options); } /** * Create a CloudWatch metric. * * @param metricName name of the metric typically prefixed with `glue.driver.`, `glue.<executorId>.` or `glue.ALL.`. * @param type the metric type. * @param props metric options. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitoring-awsglue-with-cloudwatch-metrics.html */ public metric(metricName: string, type: MetricType, props?: cloudwatch.MetricOptions): cloudwatch.Metric { return new cloudwatch.Metric({ metricName, namespace: 'Glue', dimensionsMap: { JobName: this.jobName, JobRunId: 'ALL', Type: type, }, ...props, }).attachTo(this); } /** * Return a CloudWatch Metric indicating job success. * * This metric is based on the Rule returned by no-args onSuccess() call. */ public metricSuccess(props?: cloudwatch.MetricOptions): cloudwatch.Metric { return metricRule(this.metricJobStateRule('SuccessMetricRule', JobState.SUCCEEDED), props); } /** * Return a CloudWatch Metric indicating job failure. * * This metric is based on the Rule returned by no-args onFailure() call. */ public metricFailure(props?: cloudwatch.MetricOptions): cloudwatch.Metric { return metricRule(this.metricJobStateRule('FailureMetricRule', JobState.FAILED), props); } /** * Return a CloudWatch Metric indicating job timeout. * * This metric is based on the Rule returned by no-args onTimeout() call. */ public metricTimeout(props?: cloudwatch.MetricOptions): cloudwatch.Metric { return metricRule(this.metricJobStateRule('TimeoutMetricRule', JobState.TIMEOUT), props); } /** * Creates or retrieves a singleton event rule for the input job state for use with the metric JobState methods. * * @param id construct id. * @param jobState the job state. * @private */ private metricJobStateRule(id: string, jobState: JobState): events.Rule { return this.node.tryFindChild(id) as events.Rule ?? this.onStateChange(id, jobState); } } /** * Properties for enabling Spark UI monitoring feature for Spark-based Glue jobs. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitor-spark-ui-jobs.html * @see https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html */ export interface SparkUIProps { /** * Enable Spark UI. */ readonly enabled: boolean /** * The bucket where the Glue job stores the logs. * * @default a new bucket will be created. */ readonly bucket?: s3.IBucket; /** * The path inside the bucket (objects prefix) where the Glue job stores the logs. * * @default '/' - the logs will be written at the root of the bucket */ readonly prefix?: string; } /** * The Spark UI logging location. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitor-spark-ui-jobs.html * @see https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html */ export interface SparkUILoggingLocation { /** * The bucket where the Glue job stores the logs. */ readonly bucket: s3.IBucket; /** * The path inside the bucket (objects prefix) where the Glue job stores the logs. * * @default '/' - the logs will be written at the root of the bucket */ readonly prefix?: string; } /** * Properties for enabling Continuous Logging for Glue Jobs. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitor-continuous-logging-enable.html * @see https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html */ export interface ContinuousLoggingProps { /** * Enable continouous logging. */ readonly enabled: boolean; /** * Specify a custom CloudWatch log group name. * * @default - a log group is created with name `/aws-glue/jobs/logs-v2/`. */ readonly logGroup?: logs.ILogGroup; /** * Specify a custom CloudWatch log stream prefix. * * @default - the job run ID. */ readonly logStreamPrefix?: string; /** * Filter out non-useful Apache Spark driver/executor and Apache Hadoop YARN heartbeat log messages. * * @default true */ readonly quiet?: boolean; /** * Apply the provided conversion pattern. * * This is a Log4j Conversion Pattern to customize driver and executor logs. * * @default `%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n` */ readonly conversionPattern?: string; } /** * Attributes for importing {@link Job}. */ export interface JobAttributes { /** * The name of the job. */ readonly jobName: string; /** * The IAM role assumed by Glue to run this job. * * @default - undefined */ readonly role?: iam.IRole; } /** * Construction properties for {@link Job}. */ export interface JobProps { /** * The job's executable properties. */ readonly executable: JobExecutable; /** * The name of the job. * * @default - a name is automatically generated */ readonly jobName?: string; /** * The description of the job. * * @default - no value */ readonly description?: string; /** * The number of AWS Glue data processing units (DPUs) that can be allocated when this job runs. * Cannot be used for Glue version 2.0 and later - workerType and workerCount should be used instead. * * @default - 10 when job type is Apache Spark ETL or streaming, 0.0625 when job type is Python shell */ readonly maxCapacity?: number; /** * The maximum number of times to retry this job after a job run fails. * * @default 0 */ readonly maxRetries?: number; /** * The maximum number of concurrent runs allowed for the job. * * An error is returned when this threshold is reached. The maximum value you can specify is controlled by a service limit. * * @default 1 */ readonly maxConcurrentRuns?: number; /** * The number of minutes to wait after a job run starts, before sending a job run delay notification. * * @default - no delay notifications */ readonly notifyDelayAfter?: cdk.Duration; /** * The maximum time that a job run can consume resources before it is terminated and enters TIMEOUT status. * * @default cdk.Duration.hours(48) */ readonly timeout?: cdk.Duration; /** * The type of predefined worker that is allocated when a job runs. * * @default - differs based on specific Glue version */ readonly workerType?: WorkerType; /** * The number of workers of a defined {@link WorkerType} that are allocated when a job runs. * * @default - differs based on specific Glue version/worker type */ readonly workerCount?: number; /** * The {@link Connection}s used for this job. * * Connections are used to connect to other AWS Service or resources within a VPC. * * @default [] - no connections are added to the job */ readonly connections?: IConnection[]; /** * The {@link SecurityConfiguration} to use for this job. * * @default - no security configuration. */ readonly securityConfiguration?: ISecurityConfiguration; /** * The default arguments for this job, specified as name-value pairs. * * @see https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html for a list of reserved parameters * @default - no arguments */ readonly defaultArguments?: { [key: string]: string }; /** * The tags to add to the resources on which the job runs * * @default {} - no tags */ readonly tags?: { [key: string]: string }; /** * The IAM role assumed by Glue to run this job. * * If providing a custom role, it needs to trust the Glue service principal (glue.amazonaws.com) and be granted sufficient permissions. * * @see https://docs.aws.amazon.com/glue/latest/dg/getting-started-access.html * * @default - a role is automatically generated */ readonly role?: iam.IRole; /** * Enables the collection of metrics for job profiling. * * @default - no profiling metrics emitted. * * @see `--enable-metrics` at https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html */ readonly enableProfilingMetrics? :boolean; /** * Enables the Spark UI debugging and monitoring with the specified props. * * @default - Spark UI debugging and monitoring is disabled. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitor-spark-ui-jobs.html * @see https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html */ readonly sparkUI?: SparkUIProps, /** * Enables continuous logging with the specified props. * * @default - continuous logging is disabled. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitor-continuous-logging-enable.html * @see https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html */ readonly continuousLogging?: ContinuousLoggingProps, } /** * A Glue Job. */ export class Job extends JobBase { /** * Creates a Glue Job * * @param scope The scope creating construct (usually `this`). * @param id The construct's id. * @param attrs Import attributes */ public static fromJobAttributes(scope: constructs.Construct, id: string, attrs: JobAttributes): IJob { class Import extends JobBase { public readonly jobName = attrs.jobName; public readonly jobArn = jobArn(scope, attrs.jobName); public readonly grantPrincipal = attrs.role ?? new iam.UnknownPrincipal({ resource: this }); } return new Import(scope, id); } /** * The ARN of the job. */ public readonly jobArn: string; /** * The name of the job. */ public readonly jobName: string; /** * The IAM role Glue assumes to run this job. */ public readonly role: iam.IRole; /** * The principal this Glue Job is running as. */ public readonly grantPrincipal: iam.IPrincipal; /** * The Spark UI logs location if Spark UI monitoring and debugging is enabled. * * @see https://docs.aws.amazon.com/glue/latest/dg/monitor-spark-ui-jobs.html * @see https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html */ public readonly sparkUILoggingLocation?: SparkUILoggingLocation; constructor(scope: constructs.Construct, id: string, props: JobProps) { super(scope, id, { physicalName: props.jobName, }); const executable = props.executable.bind(); this.role = props.role ?? new iam.Role(this, 'ServiceRole', { assumedBy: new iam.ServicePrincipal('glue.amazonaws.com'), managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSGlueServiceRole')], }); this.grantPrincipal = this.role; const sparkUI = props.sparkUI?.enabled ? this.setupSparkUI(executable, this.role, props.sparkUI) : undefined; this.sparkUILoggingLocation = sparkUI?.location; const continuousLoggingArgs = props.continuousLogging?.enabled ? this.setupContinuousLogging(this.role, props.continuousLogging) : {}; const profilingMetricsArgs = props.enableProfilingMetrics ? { '--enable-metrics': '' } : {}; const defaultArguments = { ...this.executableArguments(executable), ...continuousLoggingArgs, ...profilingMetricsArgs, ...sparkUI?.args, ...this.checkNoReservedArgs(props.defaultArguments), }; const jobResource = new CfnJob(this, 'Resource', { name: props.jobName, description: props.description, role: this.role.roleArn, command: { name: executable.type.name, scriptLocation: this.codeS3ObjectUrl(executable.script), pythonVersion: executable.pythonVersion, }, glueVersion: executable.glueVersion.name, workerType: props.workerType?.name, numberOfWorkers: props.workerCount, maxCapacity: props.maxCapacity, maxRetries: props.maxRetries, executionProperty: props.maxConcurrentRuns ? { maxConcurrentRuns: props.maxConcurrentRuns } : undefined, notificationProperty: props.notifyDelayAfter ? { notifyDelayAfter: props.notifyDelayAfter.toMinutes() } : undefined, timeout: props.timeout?.toMinutes(), connections: props.connections ? { connections: props.connections.map((connection) => connection.connectionName) } : undefined, securityConfiguration: props.securityConfiguration?.securityConfigurationName, tags: props.tags, defaultArguments, }); const resourceName = this.getResourceNameAttribute(jobResource.ref); this.jobArn = jobArn(this, resourceName); this.jobName = resourceName; } /** * Check no usage of reserved arguments. * * @see https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-glue-arguments.html */ private checkNoReservedArgs(defaultArguments?: { [key: string]: string }) { if (defaultArguments) { const reservedArgs = new Set(['--conf', '--debug', '--mode', '--JOB_NAME']); Object.keys(defaultArguments).forEach((arg) => { if (reservedArgs.has(arg)) { throw new Error(`The ${arg} argument is reserved by Glue. Don't set it`); } }); } return defaultArguments; } private executableArguments(config: JobExecutableConfig) { const args: { [key: string]: string } = {}; args['--job-language'] = config.language; if (config.className) { args['--class'] = config.className; } if (config.extraJars && config.extraJars?.length > 0) { args['--extra-jars'] = config.extraJars.map(code => this.codeS3ObjectUrl(code)).join(','); } if (config.extraPythonFiles && config.extraPythonFiles.length > 0) { args['--extra-py-files'] = config.extraPythonFiles.map(code => this.codeS3ObjectUrl(code)).join(','); } if (config.extraFiles && config.extraFiles.length > 0) { args['--extra-files'] = config.extraFiles.map(code => this.codeS3ObjectUrl(code)).join(','); } if (config.extraJarsFirst) { args['--user-jars-first'] = 'true'; } return args; } private setupSparkUI(executable: JobExecutableConfig, role: iam.IRole, props: SparkUIProps) { if (JobType.PYTHON_SHELL === executable.type) { throw new Error('Spark UI is not available for JobType.PYTHON_SHELL jobs'); } const bucket = props.bucket ?? new s3.Bucket(this, 'SparkUIBucket'); bucket.grantReadWrite(role); const args = { '--enable-spark-ui': 'true', '--spark-event-logs-path': bucket.s3UrlForObject(props.prefix), }; return { location: { prefix: props.prefix, bucket, }, args, }; } private setupContinuousLogging(role: iam.IRole, props: ContinuousLoggingProps) { const args: {[key: string]: string} = { '--enable-continuous-cloudwatch-log': 'true', '--enable-continuous-log-filter': (props.quiet ?? true).toString(), }; if (props.logGroup) { args['--continuous-log-logGroup'] = props.logGroup.logGroupName; props.logGroup.grantWrite(role); } if (props.logStreamPrefix) { args['--continuous-log-logStreamPrefix'] = props.logStreamPrefix; } if (props.conversionPattern) { args['--continuous-log-conversionPattern'] = props.conversionPattern; } return args; } private codeS3ObjectUrl(code: Code) { const s3Location = code.bind(this, this.role).s3Location; return `s3://${s3Location.bucketName}/${s3Location.objectKey}`; } } /** * Create a CloudWatch Metric that's based on Glue Job events * {@see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html#glue-event-types} * The metric has namespace = 'AWS/Events', metricName = 'TriggeredRules' and RuleName = rule.ruleName dimension. * * @param rule for use in setting RuleName dimension value * @param props metric properties */ function metricRule(rule: events.IRule, props?: cloudwatch.MetricOptions): cloudwatch.Metric { return new cloudwatch.Metric({ namespace: 'AWS/Events', metricName: 'TriggeredRules', dimensionsMap: { RuleName: rule.ruleName }, statistic: cloudwatch.Statistic.SUM, ...props, }).attachTo(rule); } /** * Returns the job arn * @param scope * @param jobName */ function jobArn(scope: constructs.Construct, jobName: string) : string { return cdk.Stack.of(scope).formatArn({ service: 'glue', resource: 'job', resourceName: jobName, }); }
the_stack
import { Component, OnDestroy, Injector, ChangeDetectorRef, AfterViewInit, ViewChild, isDevMode } from '@angular/core'; import { ProfileStatuses, LoginManagerService } from 'src/app/login/services/login-manager.service'; import { Subscription } from 'rxjs'; import { Submission } from 'src/app/database/models/submission.model'; import { WebsiteRegistryEntry, WebsiteRegistry, WebsiteRegistryConfig } from 'src/app/websites/registries/website.registry'; import { TypeOfSubmission } from 'src/app/utils/enums/type-of-submission.enum'; import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms'; import { LoginStatus, WebsiteStatus } from 'src/app/websites/interfaces/website-service.interface'; import { MatDialog } from '@angular/material'; import { ISubmission } from 'src/app/database/tables/submission.table'; import { DescriptionInput } from 'src/app/utils/components/description-input/description-input.component'; import { TagInput } from 'src/app/utils/components/tag-input/tag-input.component'; import { debounceTime } from 'rxjs/operators'; import { LoginProfileManagerService } from 'src/app/login/services/login-profile-manager.service'; import { ConfirmDialog } from 'src/app/utils/components/confirm-dialog/confirm-dialog.component'; import { TemplateSelectDialog } from 'src/app/templates/components/template-select-dialog/template-select-dialog.component'; import { InputDialog } from 'src/app/utils/components/input-dialog/input-dialog.component'; import { TemplateManagerService } from 'src/app/templates/services/template-manager.service'; import * as dotProp from 'dot-prop'; import { copyObject } from 'src/app/utils/helpers/copy.helper'; import { QueueInserterService } from '../../services/queue-inserter.service'; import { LoginProfile } from 'src/app/login/interfaces/login-profile'; import { SubmissionPreviewDialog } from '../../components/submission-preview-dialog/submission-preview-dialog.component'; @Component({ selector: 'base-submission-form', template: '<div></div>', }) export class BaseSubmissionForm implements AfterViewInit, OnDestroy { @ViewChild('defaultTags') defaultTags: TagInput; @ViewChild('defaultDescription') defaultDescription: DescriptionInput; protected loginStatuses: ProfileStatuses = {}; protected loginListener: Subscription = Subscription.EMPTY; protected profileListener: Subscription = Subscription.EMPTY; protected loginProfileListener: Subscription = Subscription.EMPTY; public submission: Submission; public loading: boolean = false; public hideForReload: boolean = false; public triggerWebsiteReload: boolean = true; public availableWebsites: WebsiteRegistryEntry = {}; public profiles: LoginProfile[] = []; public basicInfoForm: FormGroup; public formDataForm: FormGroup; public typeOfSubmission: TypeOfSubmission; protected _changeDetector: ChangeDetectorRef; protected dialog: MatDialog; protected _fb: FormBuilder; protected _queueInserter: QueueInserterService; protected _loginManager: LoginManagerService; protected _loginProfileManager: LoginProfileManagerService; protected _templateManager: TemplateManagerService; constructor(injector: Injector) { this._changeDetector = injector.get(ChangeDetectorRef); this.dialog = injector.get(MatDialog); this._loginManager = injector.get(LoginManagerService); this._fb = injector.get(FormBuilder); this._loginProfileManager = injector.get(LoginProfileManagerService); this._queueInserter = injector.get(QueueInserterService); this._templateManager = injector.get(TemplateManagerService); // somewhat of a duplicate that could be refactored into other listener if optimization is needed this.loginProfileListener = this._loginProfileManager.profileChanges.subscribe(profiles => { this.profiles = profiles; }); this.loginListener = this._loginManager.statusChanges.subscribe(statuses => { const oldStatuses = this.loginStatuses || {}; let updatedWebsites: string[] = []; if (this.submission.formData.loginProfile && oldStatuses[this.submission.formData.loginProfile]) { const profile = this.submission.formData.loginProfile; Object.keys(oldStatuses[profile]).forEach(key => { if (statuses[profile] && statuses[profile][key]) { const status: WebsiteStatus = statuses[profile][key]; if (status.status !== oldStatuses[profile][key].status || status.username !== oldStatuses[profile][key].username) { updatedWebsites.push(key); } } }); } this.loginStatuses = statuses; if (updatedWebsites.length) { this.triggerWebsiteReload = true; this._changeDetector.detectChanges(); this.triggerWebsiteReload = false; this._changeDetector.markForCheck(); } this._changeDetector.markForCheck(); }); } ngAfterViewInit() { // This shouldn't really occur, but it is possible on a rare case if (this.formDataForm) { this.triggerWebsiteReload = false; this.profileListener = this._loginProfileManager.profileChanges.subscribe(profiles => { const existingProfiles = profiles.map(p => p.id); if (!existingProfiles.includes(this.formDataForm.value.loginProfile)) { this.formDataForm.patchValue({ loginProfile: null }); this._changeDetector.markForCheck(); } }); if (this.submission.formData && !this.submission.formData.loginProfile && this.formDataForm.value.loginProfile) { const obj: any = copyObject(this.submission.formData); obj.loginProfile = this.formDataForm.value.loginProfile; this.submission.formData = obj; } this._changeDetector.markForCheck(); } } ngOnDestroy() { this.loginListener.unsubscribe(); this.profileListener.unsubscribe(); this.loginProfileListener.unsubscribe(); } protected _initializeFormDataForm(): void { this.formDataForm = this._fb.group({ loginProfile: [this._loginProfileManager.getDefaultProfile().id, Validators.required], defaults: this._fb.group({ description: [null], tags: [null] }) }); this.formDataForm.addControl('websites', new FormControl([], { updateOn: 'blur', validators: [Validators.required] })); this.formDataForm.addControl('excludeThumbnailWebsites', new FormControl([], { updateOn: 'blur', validators: [] })); // We want to keep all added websites through the filter so users can remove filtered ones if (this.submission.formData && this.submission.formData.websites) { this.submission.formData.websites.filter(w => !!w).forEach(website => { const config = WebsiteRegistry.getConfigForRegistry(website); if (config && this.allowWebsite(config)) this.availableWebsites[website] = config; }); } Object.keys(this.availableWebsites).forEach(website => { this.formDataForm.addControl(website, this._fb.group({ description: [], rating: [], tags: [], title: null })); }); this.formDataForm.patchValue(copyObject(this.submission.formData) || {}); this.formDataForm.controls.loginProfile.valueChanges .subscribe(() => { this.triggerWebsiteReload = true; this._changeDetector.detectChanges(); this.triggerWebsiteReload = false; this._changeDetector.detectChanges(); this._changeDetector.markForCheck(); }); // Clean up removed websites of dead form controls this.formDataForm.controls.websites.valueChanges.subscribe((websites: string[]) => { const chosenWebsites = websites || []; const resetableWebsites = Object.keys(this.availableWebsites).filter(key => !chosenWebsites.includes(key)); resetableWebsites.forEach(website => { if (this.formDataForm.get(website) && this.formDataForm.get(website).get('options')) { (<FormGroup>this.formDataForm.get(website)).removeControl('options'); } if (this.submission && this.submission.formData[website] && this.submission.formData[website].options) { delete this.submission.formData[website].options; } }); }); Object.keys(this.formDataForm.controls).forEach(key => { let keyField = key; this.formDataForm.get(key).valueChanges .pipe(debounceTime(200)) .subscribe((value) => { if (JSON.stringify((this.submission.formData || {})[keyField]) !== JSON.stringify(value)) { if (isDevMode()) { console.info(`UPDATED [${keyField}]`, (this.submission.formData || {})[keyField], value); } const copy = copyObject(this.submission.formData); copy[keyField] = copyObject(value); this._formUpdated(copy); } }); }); } protected _formUpdated(changes: any): void { this.submission.formData = changes; } protected _copySubmission(submission: ISubmission): void { if (submission.formData) this._safeLoadFormData(submission.formData); if (submission.rating && this.basicInfoForm) this.basicInfoForm.patchValue({ rating: submission.rating }); this._changeDetector.markForCheck(); } protected _safeLoadFormData(formData: any): void { const copy = copyObject(formData || {}); this.submission.formData = copy; // need to set this first due to how base-website-submission populate data this.formDataForm.patchValue(copy); } protected allowWebsite(config: WebsiteRegistryConfig): boolean { return !!config }; public getLoginProfileId(): string { return this.formDataForm.value.loginProfile; } public getWebsites(): string[] { let websites = []; if (this.formDataForm) { websites = (this.formDataForm.value.websites || []) .filter(w => !!w) .filter(w => !!this.availableWebsites[w]); } return websites; } public importTemplateField(paths: string[], event: Event): void { if (event) { event.preventDefault(); event.stopPropagation(); } this.dialog.open(TemplateSelectDialog) .afterClosed() .subscribe(template => { if (template) { for (let i = 0; i < paths.length; i++) { const path = paths[i]; if (path === 'websites') { const websites = dotProp.get(copyObject(template.data), path, []) .filter(w => this.allowWebsite(this.availableWebsites[w])); this.submission.formData = { ...this.submission.formData, websites }; } else { const newObj = { ...this.submission.formData }; dotProp.set(newObj, path, dotProp.get(copyObject(template.data), path)); this.submission.formData = newObj; } } this.formDataForm.patchValue(copyObject(this.submission.formData)); this._changeDetector.markForCheck(); this._onImport(); } }); } protected _onImport(): void {} public isLoggedIn(website: string): boolean { try { if (this.loginStatuses && this.formDataForm && this.formDataForm.value.loginProfile) { if (this.loginStatuses[this.formDataForm.value.loginProfile][website]) { return this.loginStatuses[this.formDataForm.value.loginProfile][website].status === LoginStatus.LOGGED_IN; } } } catch (e) { // Catching because electron has a weird issue here } return false; } public loadTemplate(): void { this.dialog.open(TemplateSelectDialog) .afterClosed() .subscribe(template => { if (template) { this._safeLoadFormData(template.data); } }); } public post(): void { if (this.submission.problems.length === 0) { this.dialog.open(ConfirmDialog, { data: { title: this.submission.schedule ? 'Schedule' : 'Post' } }).afterClosed() .subscribe(result => { if (result) { this._queueInserter.queue(this.submission); } }); } } public preview(): void { this.dialog.open(SubmissionPreviewDialog, { data: this.submission }); } public saveTemplate(): void { this.dialog.open(InputDialog, { data: { title: 'Save', minLength: 1, maxLength: 50 } }).afterClosed() .subscribe(templateName => { if (templateName) { this._templateManager.createTemplate(templateName.trim(), copyObject(this.formDataForm.value)); } }); } public toggleLogin(): void { loginPanel.toggle(); } }
the_stack
import Q = require('q'); import {IEntityService} from '../core/interfaces/entity-service'; import {MetaUtils} from "../core/metadata/utils"; import * as MongooseModel from './mongoose-model'; import {pathRepoMap, getModel, getEntity} from '../core/dynamic/model-entity'; import {winstonLog} from '../logging/winstonLog'; import * as Utils from './utils'; import {QueryOptions} from '../core/interfaces/queryOptions'; import {BaseModel} from "../models/baseModel"; import * as utils from '../mongoose/utils'; import { PrincipalContext } from '../security/auth/principalContext'; import * as configUtil from '../core/utils'; import {IUser} from '../tests/models/user'; import {getDbSpecifcModel} from './db'; import {Decorators} from '../core/constants'; var hash = require('object-hash'); export class MongooseService implements IEntityService { constructor() { } updateWriteCount() { if (PrincipalContext) { var count = PrincipalContext.get('cacheCount'); if (!count) { count = 0; } PrincipalContext.save('cacheCount', ++count); } } startTransaction(param?:any):Q.Promise<any>{ return Q.when(true); } commitTransaction(param?:any):Q.Promise<any>{ return Q.when(true); } rollbackTransaction(param?:any):Q.Promise<any>{ return Q.when(true); } bulkPost(repoPath: string, objArr: Array<any>, batchSize?: number): Q.Promise<any> { return MongooseModel.bulkPost(this.getModel(repoPath), objArr, batchSize); } bulkDel(repoPath: string, objArr: Array<any>): Q.Promise<any> { return MongooseModel.bulkDel(this.getModel(repoPath), objArr).then(result => { objArr.forEach(x => this.deletEntityFromCache(repoPath, CacheConstants.idCache, x._id)); return result; }); } bulkPut(repoPath: string, objArr: Array<any>, batchSize?: number, donotLoadChilds?: boolean): Q.Promise<any> { return MongooseModel.bulkPut(this.getModel(repoPath), objArr, batchSize, donotLoadChilds).then(results => { results.forEach((x: BaseModel) => { if (donotLoadChilds) { x.__partialLoaded = true; } this.setEntityIntoCache(repoPath, CacheConstants.idCache, x._id, x) }); return results; }); } bulkPatch(repoPath: string, objArr: Array<any>): Q.Promise<any> { return MongooseModel.bulkPatch(this.getModel(repoPath), objArr).then(results => { results.forEach(x => this.setEntityIntoCache(repoPath, CacheConstants.idCache, x._id, x)); return results; }); } bulkPutMany(repoPath: string, objIds: Array<any>, obj: any): Q.Promise<any> { return MongooseModel.bulkPutMany(this.getModel(repoPath), objIds, obj).then(results => { //results && results.forEach((x: BaseModel) => { // // in bulkPutMany we do not load egarLoading properties (children objects) so its partially loaded // x.__partialLoaded = true; // this.setEntityIntoCache(repoPath, CacheConstants.idCache, x._id, x); //}); return results; }); } findAll(repoPath: string): Q.Promise<any> { return MongooseModel.findAll(this.getModel(repoPath)); } findWhere(repoPath: string, query, selectedFields?: Array<string> | any, queryOptions?: QueryOptions, toLoadChilds?: boolean): Q.Promise<any> { let hashEntity = hash(JSON.stringify(query)); let cacheValueIds: Array<any> = this.getEntityFromCache(repoPath, CacheConstants.hashCache, hashEntity); if (cacheValueIds) { // get objects from cache only if previous findwhere does not cached with selectedFields let cachedValueResults = cacheValueIds.map(id => this.getEntityFromCache(repoPath, CacheConstants.idCache, id)) .filter((x: BaseModel) => x && !x.__selectedFindWhere && !x.__partialLoaded); if (cacheValueIds.length === cachedValueResults.length) { console.log("cache hit success findWhere " + repoPath + " count " + cachedValueResults.length); this.updateWriteCount(); return Q.when(cachedValueResults); } } return MongooseModel.findWhere(this.getModel(repoPath), query, selectedFields, queryOptions, toLoadChilds).then((results: Array<BaseModel>) => { results.forEach(result => { if (selectedFields && selectedFields.length > 0) { result.__selectedFindWhere = true; } // if selected fields is empty or undefined and toLoadChilds is false, then set partialLoaded true if ((!selectedFields || selectedFields.length === 0) && toLoadChilds === false) { result.__partialLoaded = true; } this.setEntityIntoCache(repoPath, CacheConstants.idCache, result._id, result); }); this.setEntityIntoCache(repoPath, CacheConstants.hashCache, hashEntity, results.map(x => x._id)); return results; }); } countWhere(repoPath: string, query): Q.Promise<any> { return MongooseModel.countWhere(this.getModel(repoPath), query); } distinctWhere(repoPath: string, query): Q.Promise<any> { return MongooseModel.countWhere(this.getModel(repoPath), query); } findOne(repoPath: string, id, donotLoadChilds?: boolean): Q.Promise<any> { let cacheValue: BaseModel = this.getEntityFromCache(repoPath, CacheConstants.idCache, id); if (cacheValue && !cacheValue.__partialLoaded && !cacheValue.__selectedFindWhere) { console.log("cache hit success findone " + repoPath); this.updateWriteCount(); return Q.when(cacheValue); } return MongooseModel.findOne(this.getModel(repoPath), id, donotLoadChilds).then((result: BaseModel) => { if (donotLoadChilds) { result.__partialLoaded = true; } this.setEntityIntoCache(repoPath, CacheConstants.idCache, id, result); return result; }); } findByField(repoPath: string, fieldName, value): Q.Promise<any> { return MongooseModel.findByField(this.getModel(repoPath), fieldName, value); } findMany(repoPath: string, ids: Array<any>, toLoadEmbeddedChilds?: boolean) { // do not cache embedded objects if (!utils.isBasonOrStringType(ids[0])) { return Q.when(ids); } let chachedValues = []; let unChachedIds = []; ids.forEach(id => { let cacheValue: BaseModel = this.getEntityFromCache(repoPath, CacheConstants.idCache, id); if (cacheValue) { if (cacheValue.__selectedFindWhere) { unChachedIds.push(id); return; } if (toLoadEmbeddedChilds && cacheValue.__partialLoaded) { unChachedIds.push(id); return; } return chachedValues.push(cacheValue); } unChachedIds.push(id); }); if (unChachedIds.length === 0) { return Q.when(chachedValues); } if (chachedValues && chachedValues.length) { console.log("cache hit success findMany " + repoPath + " count " + chachedValues.length); this.updateWriteCount(); } return MongooseModel.findMany(this.getModel(repoPath), unChachedIds, toLoadEmbeddedChilds).then((results: Array<BaseModel>) => { results.forEach(result => { if (!toLoadEmbeddedChilds) { result.__partialLoaded = true; } this.setEntityIntoCache(repoPath, CacheConstants.idCache, result._id, result); }); return chachedValues.concat(results); }); } findChild(repoPath: string, id, prop): Q.Promise<any> { return MongooseModel.findChild(this.getModel(repoPath), id, prop); } /** * case 1: all new - create main item and child separately and embed if true * case 2: some new, some update - create main item and update/create child accordingly and embed if true * @param obj */ post(repoPath: string, obj: any): Q.Promise<any> { return MongooseModel.post(this.getModel(repoPath), obj); } put(repoPath: string, id: any, obj: any): Q.Promise<any> { return MongooseModel.put(this.getModel(repoPath), id, obj).then(result => { this.setEntityIntoCache(repoPath, CacheConstants.idCache, id, result); return result; }); } del(repoPath: string, id: any): Q.Promise<any> { return MongooseModel.del(this.getModel(repoPath), id).then(result => { this.deletEntityFromCache(repoPath, CacheConstants.idCache, id); return result; }); } patch(repoPath: string, id: any, obj): Q.Promise<any> { return MongooseModel.patch(this.getModel(repoPath), id, obj).then(result => { this.setEntityIntoCache(repoPath, CacheConstants.idCache, id, result); return result; }); } getModel(repoPath: string, dynamicName?: string) { try { let model = Utils.getCurrentDBModel(pathRepoMap[repoPath].schemaName); if (model && dynamicName) { var meta = MetaUtils.getMetaData(getEntity(model.modelName), Decorators.DOCUMENT); if (meta && meta[0] && meta[0].params.dynamicName) { model = getDbSpecifcModel(dynamicName, model.schema); } } return model; } catch (e) { winstonLog.logError(`Error in getMongooseModel ${e}`); throw e; } } private getEntityFromCache(repoPath: string, param: string, id: any) { // entityCache->modelName_path->hashEntity->{key: valueObj} // ->idEntity->{key: valueObj} if (!configUtil.config().Config.isCacheEnabled) { return undefined; } let currentUser: IUser = PrincipalContext.User; if (currentUser && currentUser.entityCache && currentUser.entityCache[repoPath] && currentUser.entityCache[repoPath][param] && currentUser.entityCache[repoPath][param][id]) { // if current context view is changed then clear cache objects if (currentUser.cacheContext != currentUser.viewContext) { currentUser.cacheContext = currentUser.viewContext; currentUser.entityCache = []; return undefined; } return currentUser.entityCache[repoPath][param][id]; } return undefined; } private setEntityIntoCache(repoPath: string, entityType: string, id: any, value: any) { // entityCache->modelName_path->hashEntity->{key: valueObj} // ->idEntity->{key: valueObj} if (!configUtil.config().Config.isCacheEnabled) { return undefined; } let currentUser: IUser = PrincipalContext.User; if (!currentUser) { currentUser = <any>{}; PrincipalContext.User = currentUser; } if (!currentUser.entityCache) { currentUser.entityCache = {}; } if (!currentUser.entityCache[repoPath]) { currentUser.entityCache[repoPath] = {}; } if (!currentUser.entityCache[repoPath][entityType]) { currentUser.entityCache[repoPath][entityType] = {}; } currentUser.entityCache[repoPath][entityType][id] = value; } private deletEntityFromCache(repoPath: string, param: string, id: any) { if (!configUtil.config().Config.isCacheEnabled) { return undefined; } let currentUser: any = PrincipalContext.User; if (currentUser && currentUser.entityCache && currentUser.entityCache[repoPath] && currentUser.entityCache[repoPath][param][id]) { delete currentUser.entityCache[repoPath][param][id]; } } } export class CacheConstants { public static idCache: string = "idCache"; public static hashCache: string = "hashCache"; }
the_stack
/* * Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info. */ namespace LiteMol.Core.Geometry.LinearAlgebra { /* * This code has been modified from https://github.com/toji/gl-matrix/, * copyright (c) 2015, Brandon Jones, Colin MacKenzie IV. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: */ export type Matrix4 = number[] export type Vector3 = number[] export type Vector4 = number[] const enum EPSILON { Value = 0.000001 } export function Matrix4() { return Matrix4.zero(); } /** * Stores a 4x4 matrix in a column major (j * 4 + i indexing) format. */ export namespace Matrix4 { export function zero(): number[] { // force double backing array by 0.1. const ret = [0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; ret[0] = 0.0; return ret; } export function identity(): number[] { let out = zero(); out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = 1; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = 1; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return out; } export function fromIdentity(mat: number[]): number[] { mat[0] = 1; mat[1] = 0; mat[2] = 0; mat[3] = 0; mat[4] = 0; mat[5] = 1; mat[6] = 0; mat[7] = 0; mat[8] = 0; mat[9] = 0; mat[10] = 1; mat[11] = 0; mat[12] = 0; mat[13] = 0; mat[14] = 0; mat[15] = 1; return mat; } export function ofRows(rows: number[][]): number[] { let out = zero(), i: number, j: number, r: number[]; for (i = 0; i < 4; i++) { r = rows[i]; for (j = 0; j < 4; j++) { out[4 * j + i] = r[j]; } } return out; } export function areEqual(a: number[], b: number[], eps: number) { for (let i = 0; i < 16; i++) { if (Math.abs(a[i] - b[i]) > eps) { return false; } } return true; } export function setValue(a: number[], i: number, j: number, value: number) { a[4 * j + i] = value; } export function copy(out: number[], a: number[]) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; out[9] = a[9]; out[10] = a[10]; out[11] = a[11]; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; out[15] = a[15]; return out; } export function clone(a: number[]) { return Matrix4.copy(Matrix4.zero(), a); } export function invert(out: number[], a: number[]) { let a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, // Calculate the determinant det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null; } det = 1.0 / det; out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; return out; } export function mul(out: number[], a: number[], b: number[]) { let a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; // Cache only the current line of the second matrix let b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7]; out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11]; out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15]; out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; return out; } export function mul3(out: number[], a: number[], b: number[], c: number[]) { return mul(out, mul(out, a, b), c); } export function translate(out: number[], a: number[], v: number[]) { let x = v[0], y = v[1], z = v[2], a00: number, a01: number, a02: number, a03: number, a10: number, a11: number, a12: number, a13: number, a20: number, a21: number, a22: number, a23: number; if (a === out) { out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; } else { a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03; out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13; out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23; out[12] = a00 * x + a10 * y + a20 * z + a[12]; out[13] = a01 * x + a11 * y + a21 * z + a[13]; out[14] = a02 * x + a12 * y + a22 * z + a[14]; out[15] = a03 * x + a13 * y + a23 * z + a[15]; } return out; } export function fromTranslation(out: number[], v: number[]) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = 1; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = 1; out[11] = 0; out[12] = v[0]; out[13] = v[1]; out[14] = v[2]; out[15] = 1; return out; } export function rotate(out: number[], a: number[], rad: number, axis: number[]) { let x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, b00, b01, b02, b10, b11, b12, b20, b21, b22; if (Math.abs(len) < EPSILON.Value) { return null; } len = 1 / len; x *= len; y *= len; z *= len; s = Math.sin(rad); c = Math.cos(rad); t = 1 - c; a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3]; a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7]; a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11]; // Construct the elements of the rotation matrix b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s; b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s; b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c; // Perform rotation-specific matrix multiplication out[0] = a00 * b00 + a10 * b01 + a20 * b02; out[1] = a01 * b00 + a11 * b01 + a21 * b02; out[2] = a02 * b00 + a12 * b01 + a22 * b02; out[3] = a03 * b00 + a13 * b01 + a23 * b02; out[4] = a00 * b10 + a10 * b11 + a20 * b12; out[5] = a01 * b10 + a11 * b11 + a21 * b12; out[6] = a02 * b10 + a12 * b11 + a22 * b12; out[7] = a03 * b10 + a13 * b11 + a23 * b12; out[8] = a00 * b20 + a10 * b21 + a20 * b22; out[9] = a01 * b20 + a11 * b21 + a21 * b22; out[10] = a02 * b20 + a12 * b21 + a22 * b22; out[11] = a03 * b20 + a13 * b21 + a23 * b22; if (a !== out) { // If the source and destination differ, copy the unchanged last row out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; out[15] = a[15]; } return out; } export function fromRotation(out: number[], rad: number, axis: number[]) { let x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t; if (Math.abs(len) < EPSILON.Value) { return fromIdentity(out); } len = 1 / len; x *= len; y *= len; z *= len; s = Math.sin(rad); c = Math.cos(rad); t = 1 - c; // Perform rotation-specific matrix multiplication out[0] = x * x * t + c; out[1] = y * x * t + z * s; out[2] = z * x * t - y * s; out[3] = 0; out[4] = x * y * t - z * s; out[5] = y * y * t + c; out[6] = z * y * t + x * s; out[7] = 0; out[8] = x * z * t + y * s; out[9] = y * z * t - x * s; out[10] = z * z * t + c; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return out; } export function scale(out: number[], a: number[], v: number[]) { let x = v[0], y = v[1], z = v[2]; out[0] = a[0] * x; out[1] = a[1] * x; out[2] = a[2] * x; out[3] = a[3] * x; out[4] = a[4] * y; out[5] = a[5] * y; out[6] = a[6] * y; out[7] = a[7] * y; out[8] = a[8] * z; out[9] = a[9] * z; out[10] = a[10] * z; out[11] = a[11] * z; out[12] = a[12]; out[13] = a[13]; out[14] = a[14]; out[15] = a[15]; return out; } export function fromScaling(out: number[], v: number[]) { out[0] = v[0]; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 0; out[5] = v[1]; out[6] = 0; out[7] = 0; out[8] = 0; out[9] = 0; out[10] = v[2]; out[11] = 0; out[12] = 0; out[13] = 0; out[14] = 0; out[15] = 1; return out; } export function makeTable(m: number[]) { let ret = ''; for (let i = 0; i < 4; i++) { for (let j = 0; j < 4; j++) { ret += m[4 * j + i].toString(); if (j < 3) ret += ' '; } if (i < 3) ret += '\n'; } return ret; } export function determinant(a: number[]) { let a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32; // Calculate the determinant return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; } } export function Vector3(x?: number, y?: number, z?: number) { return Vector3.fromValues(x || 0, y || 0, z || 0); } export namespace Vector3 { export function zero() { let out = [0.1, 0.0, 0.0]; out[0] = 0; return out; } export function clone(a: number[]) { let out = zero(); out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; return out; } export function fromObj(v: { x: number, y: number, z: number }) { return fromValues(v.x, v.y, v.z); } export function toObj(v: number[]) { return { x: v[0], y: v[1], z: v[2] }; } export function fromValues(x: number, y: number, z: number) { let out = zero(); out[0] = x; out[1] = y; out[2] = z; return out; } export function set(out: number[], x: number, y: number, z: number) { out[0] = x; out[1] = y; out[2] = z; return out; } export function copy(out: number[], a: number[]) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; return out; } export function add(out: number[], a: number[], b: number[]) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; return out; } export function sub(out: number[], a: number[], b: number[]) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; return out; } export function scale(out: number[], a: number[], b: number) { out[0] = a[0] * b; out[1] = a[1] * b; out[2] = a[2] * b; return out; } export function scaleAndAdd(out: number[], a: number[], b: number[], scale: number) { out[0] = a[0] + (b[0] * scale); out[1] = a[1] + (b[1] * scale); out[2] = a[2] + (b[2] * scale); return out; } export function distance(a: number[], b: number[]) { let x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2]; return Math.sqrt(x * x + y * y + z * z); } export function squaredDistance(a: number[], b: number[]) { let x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2]; return x * x + y * y + z * z; } export function magnitude(a: number[]) { let x = a[0], y = a[1], z = a[2]; return Math.sqrt(x * x + y * y + z * z); } export function squaredMagnitude(a: number[]) { let x = a[0], y = a[1], z = a[2]; return x * x + y * y + z * z; } export function normalize(out: number[], a: number[]) { let x = a[0], y = a[1], z = a[2]; let len = x * x + y * y + z * z; if (len > 0) { len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; out[2] = a[2] * len; } return out; } export function dot(a: number[], b: number[]) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } export function cross(out: number[], a: number[], b: number[]) { let ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2]; out[0] = ay * bz - az * by; out[1] = az * bx - ax * bz; out[2] = ax * by - ay * bx; return out; } export function lerp(out: number[], a: number[], b: number[], t: number) { let ax = a[0], ay = a[1], az = a[2]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); out[2] = az + t * (b[2] - az); return out; } export function transformMat4(out: number[], a: number[], m: number[]) { let x = a[0], y = a[1], z = a[2], w = m[3] * x + m[7] * y + m[11] * z + m[15]; w = w || 1.0; out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; return out; } const angleTempA = zero(), angleTempB = zero(); export function angle(a: number[], b: number[]) { copy(angleTempA, a); copy(angleTempB, b); normalize(angleTempA, angleTempA); normalize(angleTempB, angleTempB); let cosine = dot(angleTempA, angleTempB); if (cosine > 1.0) { return 0; } else if (cosine < -1.0) { return Math.PI; } else { return Math.acos(cosine); } } const rotTemp = zero(); export function makeRotation(mat: Matrix4, a: Vector3, b: Vector3): Matrix4 { const by = angle(a, b); if (Math.abs(by) < 0.0001) { return Matrix4.fromIdentity(mat); } const axis = cross(rotTemp, a, b); const m = squaredMagnitude(axis); if (m < 0.0001) { if (Math.abs(angleTempA[0] - 1) < EPSILON.Value) set(axis, 0, 1, 0); else set(axis, 1, 0, 0); } return Matrix4.fromRotation(mat, by, axis); } } export function Vector4(x?: number, y?: number, z?: number, w?: number) { return Vector4.fromValues(x || 0, y || 0, z || 0, w || 0); } export namespace Vector4 { export function zero(): number[] { // force double backing array by 0.1. const ret = [0.1, 0, 0, 0]; ret[0] = 0.0; return ret; } export function clone(a: number[]) { let out = zero(); out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; return out; } export function fromValues(x: number, y: number, z: number, w: number) { let out = zero(); out[0] = x; out[1] = y; out[2] = z; out[3] = w; return out; } export function set(out: number[], x: number, y: number, z: number, w: number) { out[0] = x; out[1] = y; out[2] = z; out[3] = w; return out; } export function distance(a: number[], b: number[]) { let x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2], w = b[3] - a[3]; return Math.sqrt(x * x + y * y + z * z + w * w); } export function squaredDistance(a: number[], b: number[]) { let x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2], w = b[3] - a[3]; return x * x + y * y + z * z + w * w; } export function norm(a: number[]) { let x = a[0], y = a[1], z = a[2], w = a[3]; return Math.sqrt(x * x + y * y + z * z + w * w); } export function squaredNorm(a: number[]) { let x = a[0], y = a[1], z = a[2], w = a[3]; return x * x + y * y + z * z + w * w; } export function transform(out: number[], a: number[], m: number[]) { let x = a[0], y = a[1], z = a[2], w = a[3]; out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w; out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w; out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w; out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w; return out; } } }
the_stack
import { ArrayExt } from '@phosphor/algorithm'; /** * An object which manages a collection of variable sized sections. * * #### Notes * This class is an implementation detail. It is designed to manage * the variable row and column sizes for a data grid. User code will * not interact with this class directly. */ export class SectionList { /** * Construct a new section list. * * @param options - The options for initializing the list. */ constructor(options: SectionList.IOptions) { this._defaultSize = Math.max(0, Math.floor(options.defaultSize)); } /** * The total size of all sections in the list. * * #### Complexity * Constant. */ get length(): number { return this._length; } /** * The total number of sections in the list. * * #### Complexity * Constant. */ get count(): number { return this._count; } /** * Get the default size of sections in the list. * * #### Complexity * Constant. */ get defaultSize(): number { return this._defaultSize; } /** * Set the default size of sections in the list. * * #### Complexity * Linear on the number of resized sections. */ set defaultSize(value: number) { // Normalize the value. value = Math.max(0, Math.floor(value)); // Bail early if the value does not change. if (this._defaultSize === value) { return; } // Compute the delta default size. let delta = value - this._defaultSize; // Update the internal default size. this._defaultSize = value; // Update the length. this._length += delta * (this._count - this._sections.length); // Bail early if there are no modified sections. if (this._sections.length === 0) { return; } // Recompute the offsets of the modified sections. for (let i = 0, n = this._sections.length; i < n; ++i) { // Look up the previous and current modified sections. let prev = this._sections[i - 1]; let curr = this._sections[i]; // Adjust the offset for the current section. if (prev) { let count = curr.index - prev.index - 1; curr.offset = prev.offset + prev.size + count * value; } else { curr.offset = curr.index * value; } } } /** * Find the index of the section which covers the given offset. * * @param offset - The offset of the section of interest. * * @returns The index of the section which covers the given offset, * or `-1` if the offset is out of range. * * #### Complexity * Logarithmic on the number of resized sections. */ indexOf(offset: number): number { // Bail early if the offset is out of range. if (offset < 0 || offset >= this._length || this._count === 0) { return -1; } // Handle the simple case of no modified sections. if (this._sections.length === 0) { return Math.floor(offset / this._defaultSize); } // Find the modified section for the given offset. let i = ArrayExt.lowerBound(this._sections, offset, Private.offsetCmp); // Return the index of an exact match. if (i < this._sections.length && this._sections[i].offset <= offset) { return this._sections[i].index; } // Handle the case of no modified sections before the offset. if (i === 0) { return Math.floor(offset / this._defaultSize); } // Compute the index from the previous modified section. let section = this._sections[i - 1]; let span = offset - (section.offset + section.size); return section.index + Math.floor(span / this._defaultSize) + 1; } /** * Find the offset of the section at the given index. * * @param index - The index of the section of interest. * * @returns The offset of the section at the given index, or `-1` * if the index is out of range. * * #### Undefined Behavior * An `index` which is non-integral. * * #### Complexity * Logarithmic on the number of resized sections. */ offsetOf(index: number): number { // Bail early if the index is out of range. if (index < 0 || index >= this._count) { return -1; } // Handle the simple case of no modified sections. if (this._sections.length === 0) { return index * this._defaultSize; } // Find the modified section for the given index. let i = ArrayExt.lowerBound(this._sections, index, Private.indexCmp); // Return the offset of an exact match. if (i < this._sections.length && this._sections[i].index === index) { return this._sections[i].offset; } // Handle the case of no modified sections before the index. if (i === 0) { return index * this._defaultSize; } // Compute the offset from the previous modified section. let section = this._sections[i - 1]; let span = index - section.index - 1; return section.offset + section.size + span * this._defaultSize; } /** * Find the extent of the section at the given index. * * @param index - The index of the section of interest. * * @returns The extent of the section at the given index, or `-1` * if the index is out of range. * * #### Undefined Behavior * An `index` which is non-integral. * * #### Complexity * Logarithmic on the number of resized sections. */ extentOf(index: number): number { // Bail early if the index is out of range. if (index < 0 || index >= this._count) { return -1; } // Handle the simple case of no modified sections. if (this._sections.length === 0) { return (index + 1) * this._defaultSize - 1; } // Find the modified section for the given index. let i = ArrayExt.lowerBound(this._sections, index, Private.indexCmp); // Return the offset of an exact match. if (i < this._sections.length && this._sections[i].index === index) { return this._sections[i].offset + this._sections[i].size - 1; } // Handle the case of no modified sections before the index. if (i === 0) { return (index + 1) * this._defaultSize - 1; } // Compute the offset from the previous modified section. let section = this._sections[i - 1]; let span = index - section.index; return section.offset + section.size + span * this._defaultSize - 1; } /** * Find the size of the section at the given index. * * @param index - The index of the section of interest. * * @returns The size of the section at the given index, or `-1` * if the index is out of range. * * #### Undefined Behavior * An `index` which is non-integral. * * #### Complexity * Logarithmic on the number of resized sections. */ sizeOf(index: number): number { // Bail early if the index is out of range. if (index < 0 || index >= this._count) { return -1; } // Handle the simple case of no modified sections. if (this._sections.length === 0) { return this._defaultSize; } // Find the modified section for the given index. let i = ArrayExt.lowerBound(this._sections, index, Private.indexCmp); // Return the size of an exact match. if (i < this._sections.length && this._sections[i].index === index) { return this._sections[i].size; } // Return the default size for all other cases. return this._defaultSize; } /** * Resize a section in the list. * * @param index - The index of the section to resize. This method * is a no-op if this value is out of range. * * @param size - The new size of the section. This value will be * clamped to an integer `>= 0`. * * #### Undefined Behavior * An `index` which is non-integral. * * #### Complexity * Linear on the number of resized sections. */ resize(index: number, size: number): void { // Bail early if the index is out of range. if (index < 0 || index >= this._count) { return; } // Clamp the size to an integer >= 0. size = Math.max(0, Math.floor(size)); // Find the modified section for the given index. let i = ArrayExt.lowerBound(this._sections, index, Private.indexCmp); // Update or create the modified section as needed. let delta: number; if (i < this._sections.length && this._sections[i].index === index) { let section = this._sections[i]; delta = size - section.size; section.size = size; } else if (i === 0) { let offset = index * this._defaultSize; ArrayExt.insert(this._sections, i, { index, offset, size }); delta = size - this._defaultSize; } else { let section = this._sections[i - 1]; let span = index - section.index - 1; let offset = section.offset + section.size + span * this._defaultSize; ArrayExt.insert(this._sections, i, { index, offset, size }); delta = size - this._defaultSize; } // Adjust the length. this._length += delta; // Update all modified sections after the resized section. for (let j = i + 1, n = this._sections.length; j < n; ++j) { this._sections[j].offset += delta; } } /** * Insert sections into the list. * * @param index - The index at which to insert the sections. This * value will be clamped to the bounds of the list. * * @param count - The number of sections to insert. This method * is a no-op if this value is `<= 0`. * * #### Undefined Behavior * An `index` or `count` which is non-integral. * * #### Complexity * Linear on the number of resized sections. */ insert(index: number, count: number): void { // Bail early if there are no sections to insert. if (count <= 0) { return; } // Clamp the index to the bounds of the list. index = Math.max(0, Math.min(index, this._count)); // Add the new sections to the totals. let span = count * this._defaultSize; this._count += count; this._length += span; // Bail early if there are no modified sections to update. if (this._sections.length === 0) { return; } // Find the modified section for the given index. let i = ArrayExt.lowerBound(this._sections, index, Private.indexCmp); // Update all modified sections after the insert location. for (let n = this._sections.length; i < n; ++i) { let section = this._sections[i]; section.index += count; section.offset += span; } } /** * Remove sections from the list. * * @param index - The index of the first section to remove. This * method is a no-op if this value is out of range. * * @param count - The number of sections to remove. This method * is a no-op if this value is `<= 0`. * * #### Undefined Behavior * An `index` or `count` which is non-integral. * * #### Complexity * Linear on the number of resized sections. */ remove(index: number, count: number): void { // Bail early if there is nothing to remove. if (index < 0 || index >= this._count || count <= 0) { return; } // Clamp the count to the bounds of the list. count = Math.min(this._count - index, count); // Handle the simple case of no modified sections to update. if (this._sections.length === 0) { this._count -= count; this._length -= count * this._defaultSize; return; } // Handle the simple case of removing all sections. if (count === this._count) { this._length = 0; this._count = 0; this._sections.length = 0; return; } // Find the modified section for the start index. let i = ArrayExt.lowerBound(this._sections, index, Private.indexCmp); // Find the modified section for the end index. let j = ArrayExt.lowerBound(this._sections, index + count, Private.indexCmp); // Remove the relevant modified sections. let removed = this._sections.splice(i, j - i); // Compute the total removed span. let span = (count - removed.length) * this._defaultSize; for (let k = 0, n = removed.length; k < n; ++k) { span += removed[k].size; } // Adjust the totals. this._count -= count; this._length -= span; // Update all modified sections after the removed span. for (let k = i, n = this._sections.length; k < n; ++k) { let section = this._sections[k]; section.index -= count; section.offset -= span; } } /** * Move sections within the list. * * @param index - The index of the first section to move. This method * is a no-op if this value is out of range. * * @param count - The number of sections to move. This method is a * no-op if this value is `<= 0`. * * @param destination - The destination index for the first section. * This value will be clamped to the allowable range. * * #### Undefined Behavior * An `index`, `count`, or `destination` which is non-integral. * * #### Complexity * Linear on the number of moved resized sections. */ move(index: number, count: number, destination: number): void { // Bail early if there is nothing to move. if (index < 0 || index >= this._count || count <= 0) { return; } // Handle the simple case of no modified sections. if (this._sections.length === 0) { return; } // Clamp the move count to the limit. count = Math.min(count, this._count - index); // Clamp the destination index to the limit. destination = Math.min(Math.max(0, destination), this._count - count); // Bail early if there is no effective move. if (index === destination) { return; } // Compute the first affected index. let i1 = Math.min(index, destination); // Look up the first affected modified section. let k1 = ArrayExt.lowerBound(this._sections, i1, Private.indexCmp); // Bail early if there are no affected modified sections. if (k1 === this._sections.length) { return; } // Compute the last affected index. let i2 = Math.max(index + count - 1, destination + count - 1); // Look up the last affected modified section. let k2 = ArrayExt.upperBound(this._sections, i2, Private.indexCmp) - 1; // Bail early if there are no affected modified sections. if (k2 < k1) { return; } // Compute the pivot index. let pivot = destination < index ? index : index + count; // Compute the count for each side of the pivot. let count1 = pivot - i1; let count2 = i2 - pivot + 1; // Compute the span for each side of the pivot. let span1 = count1 * this._defaultSize; let span2 = count2 * this._defaultSize; // Adjust the spans for the modified sections. for (let j = k1; j <= k2; ++j) { let section = this._sections[j]; if (section.index < pivot) { span1 += section.size - this._defaultSize; } else { span2 += section.size - this._defaultSize; } } // Look up the pivot section. let k3 = ArrayExt.lowerBound(this._sections, pivot, Private.indexCmp); // Rotate the modified sections if needed. if (k1 <= k3 && k3 <= k2) { ArrayExt.rotate(this._sections, k3 - k1, k1, k2); } // Adjust the modified section indices and offsets. for (let j = k1; j <= k2; ++j) { let section = this._sections[j]; if (section.index < pivot) { section.index += count2; section.offset += span2; } else { section.index -= count1; section.offset -= span1; } } } /** * Reset all modified sections to the default size. * * #### Complexity * Constant. */ reset(): void { this._sections.length = 0; this._length = this._count * this._defaultSize; } /** * Remove all sections from the list. * * #### Complexity * Constant. */ clear(): void { this._count = 0; this._length = 0; this._sections.length = 0; } private _count = 0; private _length = 0; private _defaultSize: number; private _sections: Private.Section[] = []; } /** * The namespace for the `SectionList` class statics. */ export namespace SectionList { /** * An options object for initializing a section list. */ export interface IOptions { /** * The size of new sections added to the list. */ defaultSize: number; } } /** * The namespace for the module implementation details. */ namespace Private { /** * An object which represents a modified section. */ export type Section = { /** * The index of the section. * * This is always `>= 0`. */ index: number; /** * The offset of the section. */ offset: number; /** * The size of the section. * * This is always `>= 0`. */ size: number; }; /** * A comparison function for searching by offset. */ export function offsetCmp(section: Section, offset: number): number { if (offset < section.offset) { return 1; } if (section.offset + section.size <= offset) { return -1; } return 0; } /** * A comparison function for searching by index. */ export function indexCmp(section: Section, index: number): number { return section.index - index; } }
the_stack
// import { platform } from 'node:process' import { jest } from '@jest/globals' import { Request, Response, NextFunction } from 'express' import { agent as request } from 'supertest' import rateLimit, { LegacyStore, Store, Options, IncrementCallback, IncrementResponse, } from '../../source/index.js' import { createServer } from './helpers/create-server.js' describe('middleware test', () => { beforeEach(() => { jest.useFakeTimers('modern') }) afterEach(() => { jest.useRealTimers() jest.restoreAllMocks() }) class MockStore implements Store { initWasCalled = false incrementWasCalled = false decrementWasCalled = false resetKeyWasCalled = false resetAllWasCalled = false counter = 0 init(_options: Options): void { this.initWasCalled = true } async increment(_key: string): Promise<IncrementResponse> { this.counter += 1 this.incrementWasCalled = true return { totalHits: this.counter, resetTime: undefined } } async decrement(_key: string): Promise<void> { this.counter -= 1 this.decrementWasCalled = true } async resetKey(_key: string): Promise<void> { this.resetKeyWasCalled = true } async resetAll(): Promise<void> { this.resetAllWasCalled = true } } class MockLegacyStore implements LegacyStore { initWasCalled = false incrementWasCalled = false decrementWasCalled = false resetKeyWasCalled = false resetAllWasCalled = false counter = 0 incr(_key: string, callback: IncrementCallback) { this.counter += 1 this.incrementWasCalled = true callback(undefined, this.counter, undefined) } decrement(_key: string): void { this.counter -= 1 this.decrementWasCalled = true } resetKey(_key: string): void { this.resetKeyWasCalled = true } resetAll(): void { this.resetAllWasCalled = true } } class MockBackwardCompatibleStore implements Store, LegacyStore { initWasCalled = false incrementWasCalled = false decrementWasCalled = false resetKeyWasCalled = false resetAllWasCalled = false counter = 0 incr(_key: string, callback: IncrementCallback) { this.counter += 1 this.incrementWasCalled = true callback(undefined, this.counter, undefined) } async increment(_key: string): Promise<IncrementResponse> { this.counter += 1 this.incrementWasCalled = true return { totalHits: this.counter, resetTime: undefined } } decrement(_key: string): void { this.counter -= 1 this.decrementWasCalled = true } resetKey(_key: string): void { this.resetKeyWasCalled = true } resetAll(): void { this.resetAllWasCalled = true } } it('should not modify the options object passed', () => { const options = {} rateLimit(options) expect(options).toStrictEqual({}) }) it('should call `init` even if no requests have come in', async () => { const store = new MockStore() rateLimit({ store, }) expect(store.initWasCalled).toEqual(true) }) it('should print an error if `request.ip` is undefined', async () => { jest.spyOn(global.console, 'error').mockImplementation(() => {}) await Promise.resolve( rateLimit()( { ip: undefined } as any as Request, {} as any as Response, (() => {}) as NextFunction, ), ) expect(console.error).toBeCalled() }) it('should let the first request through', async () => { const app = createServer(rateLimit({ max: 1 })) await request(app).get('/').expect(200).expect('Hi there!') }) it('should refuse additional connections once IP has reached the max', async () => { const app = createServer( rateLimit({ max: 2, }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(200) await request(app).get('/').expect(429) }) it('should (eventually) accept new connections from a blocked IP', async () => { const app = createServer( rateLimit({ max: 2, windowMs: 50, }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(200) await request(app).get('/').expect(429) jest.advanceTimersByTime(60) await request(app).get('/').expect(200) }) it('should work repeatedly', async () => { const app = createServer( rateLimit({ max: 2, windowMs: 50, }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(200) await request(app).get('/').expect(429) jest.advanceTimersByTime(60) await request(app).get('/').expect(200) await request(app).get('/').expect(200) await request(app).get('/').expect(429) jest.advanceTimersByTime(60) await request(app).get('/').expect(200) }) it('should show the provided message instead of the default message when max connections are reached', async () => { const message = 'Enhance your calm' const app = createServer( rateLimit({ windowMs: 1000, max: 2, message, }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(200) await request(app).get('/').expect(429).expect(message) }) it('should allow the error status code to be customized', async () => { const statusCode = 420 const app = createServer( rateLimit({ max: 1, statusCode, }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(statusCode) }) it('should allow responding with a JSON message', async () => { const message = { error: { code: 'too-many-requests', message: 'Too many requests were attempted in a short span of time.', }, } const app = createServer( rateLimit({ message, max: 1, }), ) await request(app).get('/').expect(200, 'Hi there!') await request(app).get('/').expect(429, message) }) it('should use a custom handler when specified', async () => { const app = createServer( rateLimit({ max: 1, handler: (_request, response) => { response.status(420).end('Enhance your calm') }, }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(420, 'Enhance your calm') }) it('should allow custom key generators', async () => { const app = createServer( rateLimit({ max: 2, keyGenerator: (request, _response) => request.query.key as string, }), ) await request(app).get('/').query({ key: 1 }).expect(200) await request(app).get('/').query({ key: 1 }).expect(200) await request(app).get('/').query({ key: 2 }).expect(200) await request(app).get('/').query({ key: 1 }).expect(429) await request(app).get('/').query({ key: 2 }).expect(200) await request(app).get('/').query({ key: 2 }).expect(429) }) it('should allow custom skip function', async () => { const app = createServer( rateLimit({ max: 2, skip: () => true, }), ) await request(app).get('/').query({ key: 1 }).expect(200) await request(app).get('/').query({ key: 1 }).expect(200) await request(app).get('/').query({ key: 1 }).expect(200) }) it('should allow custom skip function that returns a promise', async () => { const limiter = rateLimit({ max: 2, skip: async () => { return Promise.resolve(true) }, }) const app = createServer(limiter) await request(app).get('/').query({ key: 1 }).expect(200) await request(app).get('/').query({ key: 1 }).expect(200) await request(app).get('/').query({ key: 1 }).expect(200) }) it('should allow max to be a function', async () => { const app = createServer( rateLimit({ max: () => 2, }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(200) await request(app).get('/').expect(429) }) it('should allow max to be a function that returns a promise', async () => { const app = createServer( rateLimit({ max: async () => Promise.resolve(2), }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(200) await request(app).get('/').expect(429) }) it('should calculate the remaining hits', async () => { const app = createServer( rateLimit({ max: async () => Promise.resolve(2), }), ) await request(app) .get('/') .expect(200) .expect('x-ratelimit-limit', '2') .expect('x-ratelimit-remaining', '1') .expect((response) => { if ('retry-after' in response.headers) { throw new Error( `Expected no retry-after header, got ${ response.headers['retry-after'] as string }`, ) } }) .expect(200, 'Hi there!') }) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])('should call `increment` on the store (%s store)', async (name, store) => { const app = createServer( rateLimit({ store, }), ) await request(app).get('/') expect(store.incrementWasCalled).toEqual(true) }) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])('should call `resetKey` on the store (%s store)', async (name, store) => { const limiter = rateLimit({ store, }) limiter.resetKey('key') expect(store.resetKeyWasCalled).toEqual(true) }) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should decrement hits when requests succeed and `skipSuccessfulRequests` is set to true (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipSuccessfulRequests: true, store, }), ) await request(app).get('/').expect(200) expect(store.decrementWasCalled).toEqual(true) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should not decrement hits when requests fail and `skipSuccessfulRequests` is set to true (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipSuccessfulRequests: true, store, }), ) await request(app).get('/error').expect(400) expect(store.decrementWasCalled).toEqual(false) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should decrement hits when requests succeed, `skipSuccessfulRequests` is set to true and a custom `requestWasSuccessful` method used (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipSuccessfulRequests: true, requestWasSuccessful: (_request, response) => response.statusCode === 200, store, }), ) await request(app).get('/').expect(200) expect(store.decrementWasCalled).toEqual(true) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should not decrement hits when requests fail, `skipSuccessfulRequests` is set to true and a custom `requestWasSuccessful` method used (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipSuccessfulRequests: true, requestWasSuccessful: (request, response) => { return response.statusCode === 200 }, store, }), ) await request(app).get('/error').expect(400) expect(store.decrementWasCalled).toEqual(false) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should decrement hits when requests succeed, `skipSuccessfulRequests` is set to true and a custom `requestWasSuccessful` method used (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipSuccessfulRequests: true, requestWasSuccessful: (request, _response) => request.query.success === '1', store, }), ) await request(app).get('/?success=1') expect(store.decrementWasCalled).toEqual(true) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should not decrement hits when requests fail, `skipSuccessfulRequests` is set to true and a custom `requestWasSuccessful` method used (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipSuccessfulRequests: true, requestWasSuccessful: (request, _response) => request.query.success === '1', store, }), ) await request(app).get('/?success=0') expect(store.decrementWasCalled).toEqual(false) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should decrement hits when requests fail and `skipFailedRequests` is set to true (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipFailedRequests: true, store, }), ) await request(app).get('/error').expect(400) expect(store.decrementWasCalled).toEqual(true) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should not decrement hits when requests succeed and `skipFailedRequests` is set to true (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipFailedRequests: true, store, }), ) await request(app).get('/').expect(200) expect(store.decrementWasCalled).toEqual(false) }, ) // FIXME: This test times out _sometimes_ on MacOS and Windows, so it is disabled for now /* ;(platform === 'darwin' ? it.skip : it).each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should decrement hits when response closes and `skipFailedRequests` is set to true (%s store)', async (name, store) => { jest.useRealTimers() jest.setTimeout(60_000) const app = createServer( rateLimit({ skipFailedRequests: true, store, }), ) let _resolve: () => void const connectionClosed = new Promise<void>((resolve) => { _resolve = resolve }) app.get('/hang-server', (_request, response) => { response.on('close', _resolve) }) const hangRequest = request(app).get('/hang-server').timeout(10) await expect(hangRequest).rejects.toThrow() await connectionClosed expect(store.decrementWasCalled).toEqual(true) }, ) */ it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should decrement hits when response emits an error and `skipFailedRequests` is set to true (%s store)', async (name, store) => { const app = createServer( rateLimit({ skipFailedRequests: true, store, }), ) await request(app).get('/crash') expect(store.decrementWasCalled).toEqual(true) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should decrement hits when rate limit is reached and `skipFailedRequests` is set to true (%s store)', async (name, store) => { const app = createServer( rateLimit({ max: 2, store, skipFailedRequests: true, }), ) await request(app).get('/').expect(200) await request(app).get('/').expect(200) await request(app).get('/').expect(429) expect(store.decrementWasCalled).toEqual(true) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should forward errors in the handler using `next()` (%s store)', async (name, store) => { let errorCaught = false const app = createServer( rateLimit({ max: 1, store, handler: () => { const exception = new Error('420: Enhance your calm') throw exception }, }), ) app.use( ( error: Error, _request: Request, response: Response, _next: NextFunction, ) => { errorCaught = true response.status(500).send(error.message) }, ) await request(app).get('/').expect(200) await request(app).get('/').expect(500) expect(errorCaught).toEqual(true) }, ) it.each([ ['modern', new MockStore()], ['legacy', new MockLegacyStore()], ['compat', new MockBackwardCompatibleStore()], ])( 'should forward errors in `skip()` using `next()` (%s store)', async (name, store) => { let errorCaught = false const app = createServer( rateLimit({ max: 1, store, skip: () => { const exception = new Error('420: Enhance your calm') throw exception }, }), ) app.use( ( error: Error, _request: Request, response: Response, _next: NextFunction, ) => { errorCaught = true response.status(500).send(error.message) }, ) await request(app).get('/').expect(500) expect(errorCaught).toEqual(true) }, ) it('should pass the number of hits and the limit to the next request handler in the `request.rateLimit` property', async () => { let savedRequestObject: any const saveRequestObject = ( request: Request, _response: Response, next: NextFunction, ) => { savedRequestObject = request next() } const app = createServer([ saveRequestObject, rateLimit({ legacyHeaders: false, }), ]) await request(app).get('/').expect(200) expect(savedRequestObject).toBeTruthy() expect(savedRequestObject.rateLimit).toBeTruthy() expect(savedRequestObject.rateLimit.limit).toEqual(5) expect(savedRequestObject.rateLimit.remaining).toEqual(4) savedRequestObject = undefined await request(app).get('/').expect(200) expect(savedRequestObject.rateLimit.limit).toEqual(5) expect(savedRequestObject.rateLimit.remaining).toEqual(3) }) it('should pass the number of hits and the limit to the next request handler with a custom property', async () => { let savedRequestObject: any const saveRequestObject = ( request: Request, _response: Response, next: NextFunction, ) => { savedRequestObject = request next() } const app = createServer([ saveRequestObject, rateLimit({ legacyHeaders: false, requestPropertyName: 'rateLimitInfo', }), ]) await request(app).get('/').expect(200) expect(savedRequestObject).toBeTruthy() expect(savedRequestObject.rateLimitInfo).toBeTruthy() expect(savedRequestObject.rateLimitInfo.limit).toEqual(5) expect(savedRequestObject.rateLimitInfo.remaining).toEqual(4) savedRequestObject = undefined await request(app).get('/').expect(200) expect(savedRequestObject.rateLimitInfo.limit).toEqual(5) expect(savedRequestObject.rateLimitInfo.remaining).toEqual(3) }) it('should handle two rate-limiters with different `requestPropertyNames` operating independently', async () => { const keyLimiter = rateLimit({ max: 2, requestPropertyName: 'rateLimitKey', keyGenerator: (request) => request.query.key as string, handler: (_request, response) => { response.status(420).end('Enhance your calm') }, }) const globalLimiter = rateLimit({ max: 5, requestPropertyName: 'rateLimitGlobal', keyGenerator: () => 'global', handler: (_request, response) => { response.status(429).end('Too many requests') }, }) let savedRequestObject: any const saveRequestObject = ( request: Request, _response: Response, next: NextFunction, ) => { savedRequestObject = request next() } const app = createServer([saveRequestObject, keyLimiter, globalLimiter]) await request(app).get('/').query({ key: 1 }).expect(200) expect(savedRequestObject).toBeTruthy() expect(savedRequestObject.rateLimit).toBeUndefined() expect(savedRequestObject.rateLimitKey).toBeTruthy() expect(savedRequestObject.rateLimitKey.limit).toEqual(2) expect(savedRequestObject.rateLimitKey.remaining).toEqual(1) expect(savedRequestObject.rateLimitGlobal).toBeTruthy() expect(savedRequestObject.rateLimitGlobal.limit).toEqual(5) expect(savedRequestObject.rateLimitGlobal.remaining).toEqual(4) savedRequestObject = undefined await request(app).get('/').query({ key: 2 }).expect(200) expect(savedRequestObject.rateLimitKey.remaining).toEqual(1) expect(savedRequestObject.rateLimitGlobal.remaining).toEqual(3) savedRequestObject = undefined await request(app).get('/').query({ key: 1 }).expect(200) expect(savedRequestObject.rateLimitKey.remaining).toEqual(0) expect(savedRequestObject.rateLimitGlobal.remaining).toEqual(2) savedRequestObject = undefined await request(app).get('/').query({ key: 2 }).expect(200) expect(savedRequestObject.rateLimitKey.remaining).toEqual(0) expect(savedRequestObject.rateLimitGlobal.remaining).toEqual(1) savedRequestObject = undefined await request(app) .get('/') .query({ key: 1 }) .expect(420, 'Enhance your calm') expect(savedRequestObject.rateLimitKey.remaining).toEqual(0) savedRequestObject = undefined await request(app).get('/').query({ key: 3 }).expect(200) await request(app) .get('/') .query({ key: 3 }) .expect(429, 'Too many requests') expect(savedRequestObject.rateLimitKey.remaining).toEqual(0) expect(savedRequestObject.rateLimitGlobal.remaining).toEqual(0) }) })
the_stack
import checkPosition from '../../../../utils/checkPosition' import { mainWeapon, secondaryWeapon, meleeWeapon, tempWeapon, fistsWeapon, bootsWeapon, weaponTopWrap, weaponTopWrapPropsLeftIconFirst, weaponTopWrapPropsLeftIconLast, weaponTopWrapLabel, weaponTopWrapPropsRightIconFirst, weaponTopWrapPropsRightIconLast, weaponImageWrap, weaponImage, weaponBottomWrap, weaponBottomWrapPropsLeftIcon, weaponBottomWrapPropsLeftDamage, weaponBottomWrapLabel, weaponBottomWrapLabelWrap, weaponBottomWrapPropsRightIcon, weaponBottomWrapPropsRightDamage, weaponBottomWrapLabelEternity } from '../selectors/weapons' import { TDimensionTypes, IWeaponBottomSection, IWeaponTopSection, IWeaponImage, IWeaponData, IWeaponsData } from '../../interfaces/IView' import { TPersonTypes } from '../../interfaces/IController' import { WEAPON_BOX_DIMENSIONS } from '../constants' import { WEAPON_COORDS } from '../constants/coords' import checkStyles from '../../../../utils/checkStyles' const amplifierOffset = ({ value, rowID, customShift = 0 }: { value: number; rowID: number; customShift?: number }) => { const updatedValue = value + (rowID * 97) // this is a hack for testing fists and boots weapons if (rowID === 4) { return updatedValue - 15 + customShift } return updatedValue + customShift } const checkWeaponBoxStyles = (node: any, dimType?: TDimensionTypes) => { const { width, height } = WEAPON_BOX_DIMENSIONS[dimType] || WEAPON_BOX_DIMENSIONS['regular'] checkStyles({ elemNode: node(), expectations: { width: width, height: height } }) } export const checkWeaponTopSection = (config: IWeaponTopSection) => { const { ID, userType, weaponType, label, disableAttachments, disableBlock, forceDisabled, customShiftWrap, customShiftLabel } = config const weaponTopWrapNode = () => weaponTopWrap(userType, weaponType) if (forceDisabled) { weaponTopWrapNode().should('have.length', 0) return } const wrap = () => { weaponTopWrapNode().should('have.length', 1) weaponTopWrapNode().styles('width').should('eq', '155px') checkPosition({ nodeElement: weaponTopWrapNode, leftOffset: WEAPON_COORDS[userType].topWrap.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].topWrap.topOffset, rowID: ID, customShift: customShiftWrap }) }) } const leftSection = () => { const weaponTopWrapPropsLeftIconFirstNode = () => weaponTopWrapPropsLeftIconFirst(userType, weaponType) const weaponTopWrapPropsLeftIconLastNode = () => weaponTopWrapPropsLeftIconLast(userType, weaponType) weaponTopWrapPropsLeftIconFirstNode().should('have.length', 1) checkStyles({ elemNode: weaponTopWrapPropsLeftIconFirstNode(), expectations: { width: '11px', height: '11px' } }) weaponTopWrapPropsLeftIconLastNode().should('have.length', 1) checkStyles({ elemNode: weaponTopWrapPropsLeftIconLastNode(), expectations: { width: '11px', height: '11px' } }) checkPosition({ nodeElement: weaponTopWrapPropsLeftIconFirstNode, leftOffset: WEAPON_COORDS[userType].topWrapLeftIconFirst.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].topWrapLeftIconLast.topOffset, rowID: ID }) }) checkPosition({ nodeElement: weaponTopWrapPropsLeftIconLastNode, leftOffset: WEAPON_COORDS[userType].topWrapLeftIconLast.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].topWrapLeftIconLast.topOffset, rowID: ID }) }) } const labelSection = () => { const weaponTopWrapLabelNode = () => weaponTopWrapLabel(userType, weaponType) weaponTopWrapLabelNode().should('have.length', 1) weaponTopWrapLabelNode().should('have.text', label) checkStyles({ elemNode: weaponTopWrapLabelNode(), expectations: { width: '64px', height: '16px', 'background-color': 'rgb(255, 255, 255)', 'border-top-left-radius': '0px', 'border-top-right-radius': '0px', 'border-bottom-right-radius': '5px', 'border-bottom-left-radius': '5px' } }) // if (userType === 'attacker' && ID === 3) { // console.log(WEAPON_COORDS[userType].topLabel.topOffset, 'WEAPON_COORDS[userType].topLabel.topOffset') // console.log(amplifierOffset({ value: WEAPON_COORDS[userType].topLabel.topOffset, rowID: ID }), 'AMPLIFIED!') // } checkPosition({ nodeElement: weaponTopWrapLabelNode, leftOffset: WEAPON_COORDS[userType].topLabel.leftOffset // topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].topLabel.topOffset, rowID: ID, customShift: customShiftLabel }) }) } const rightSection = () => { const weaponTopWrapPropsRightIconFirstNode = () => weaponTopWrapPropsRightIconFirst(userType, weaponType) const weaponTopWrapPropsRightIconLastNode = () => weaponTopWrapPropsRightIconLast(userType, weaponType) weaponTopWrapPropsRightIconFirstNode().should('have.length', 1) checkStyles({ elemNode: weaponTopWrapPropsRightIconFirstNode(), expectations: { width: '11px', height: '11px' } }) weaponTopWrapPropsRightIconLastNode().should('have.length', 1) checkStyles({ elemNode: weaponTopWrapPropsRightIconLastNode(), expectations: { width: '11px', height: '11px' } }) checkPosition({ nodeElement: weaponTopWrapPropsRightIconFirstNode, leftOffset: WEAPON_COORDS[userType].topWrapRightIconFirst.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].topWrapRightIconFirst.topOffset, rowID: ID }) }) checkPosition({ nodeElement: weaponTopWrapPropsRightIconLastNode, leftOffset: WEAPON_COORDS[userType].topWrapRightIconLast.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].topWrapRightIconLast.topOffset, rowID: ID }) }) } !disableBlock && wrap(); (!disableBlock && !disableAttachments) && leftSection() !disableBlock && labelSection(); (!disableBlock && !disableAttachments) && rightSection() } export const checkWeaponImage = ({ ID, userType, weaponType, customShiftWrap, customShiftImage }: IWeaponImage) => { const weaponImageWrapNode = () => weaponImageWrap(userType, weaponType) const weaponImageNode = () => weaponImage(userType, weaponType) weaponImageWrapNode().should('have.length', 1) weaponImageNode().should('have.length', 1) checkPosition({ nodeElement: weaponImageWrapNode, leftOffset: WEAPON_COORDS[userType].weaponImageWrap.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].weaponImageWrap.topOffset, rowID: ID, customShift: customShiftWrap }) }) checkPosition({ nodeElement: weaponImageNode, leftOffset: WEAPON_COORDS[userType].weaponImage.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].weaponImage.topOffset, rowID: ID, customShift: customShiftImage }) }) } export const checkWeaponBottomSection = (config: IWeaponBottomSection) => { const { ID, userType, weaponType, label, damage, accuracy, disableBlock, forceDisabled } = config const weaponBottomWrapNode = () => weaponBottomWrap(userType, weaponType) if (forceDisabled) { weaponBottomWrapNode().should('have.length', 0) return } const wrap = () => { weaponBottomWrapNode().should('have.length', 1) checkStyles({ elemNode: weaponBottomWrapNode(), expectations: { width: '155px', height: '12px' } }) checkPosition({ nodeElement: weaponBottomWrapNode, leftOffset: WEAPON_COORDS[userType].bottomWrap.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].bottomWrap.topOffset, rowID: ID }) }) } const leftSection = () => { const weaponBottomWrapPropsLeftIconFirstNode = () => weaponBottomWrapPropsLeftIcon(userType, weaponType) const weaponBottomWrapPropsLeftIconLastNode = () => weaponBottomWrapPropsLeftDamage(userType, weaponType) weaponBottomWrapPropsLeftIconFirstNode().should('have.length', 1) checkStyles({ elemNode: weaponBottomWrapPropsLeftIconFirstNode(), expectations: { width: '11px', height: '11px' } }) weaponBottomWrapPropsLeftIconLastNode().should('have.length', 1) weaponBottomWrapPropsLeftIconLastNode().should('have.text', damage) checkPosition({ nodeElement: weaponBottomWrapPropsLeftIconFirstNode, leftOffset: WEAPON_COORDS[userType].bottomWrapLeftIcon.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].bottomWrapLeftIcon.topOffset, rowID: ID }) }) checkPosition({ nodeElement: weaponBottomWrapPropsLeftIconLastNode, leftOffset: WEAPON_COORDS[userType].bottomWrapLeftIconValue.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].bottomWrapLeftIconValue.topOffset, rowID: ID }) }) } const labelSection = () => { const weaponBottomWrapLabelWrapNode = () => weaponBottomWrapLabelWrap(userType, weaponType) const weaponBottomWrapLabelNode = () => weaponBottomWrapLabel(userType, weaponType) const weaponBottomWrapLabelEternityNode = () => weaponBottomWrapLabelEternity(userType, weaponType) weaponBottomWrapLabelWrapNode().should('have.length', 1) weaponBottomWrapLabelNode().should('have.length', 1) checkStyles({ elemNode: weaponBottomWrapLabelWrapNode(), expectations: { width: '64px', height: '16px', 'background-color': 'rgb(255, 255, 255)', 'border-top-left-radius': '5px', 'border-top-right-radius': '5px', 'border-bottom-right-radius': '0px', 'border-bottom-left-radius': '0px' } }) if (label === 'infinity') { weaponBottomWrapLabelEternityNode().should('have.length', 1) } else { weaponBottomWrapLabelNode().should('have.text', label) } checkPosition({ nodeElement: weaponBottomWrapLabelWrapNode, leftOffset: WEAPON_COORDS[userType].bottomLabel.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].bottomLabel.topOffset, rowID: ID }) }) } const rightSection = () => { const weaponBottomWrapPropsRightIconNode = () => weaponBottomWrapPropsRightIcon(userType, weaponType) const weaponBottomWrapPropsRightDamageNode = () => weaponBottomWrapPropsRightDamage(userType, weaponType) weaponBottomWrapPropsRightIconNode().should('have.length', 1) checkStyles({ elemNode: weaponBottomWrapPropsRightIconNode(), expectations: { width: '11px', height: '11px' } }) weaponBottomWrapPropsRightDamageNode().should('have.length', 1) weaponBottomWrapPropsRightDamageNode().should('have.text', accuracy) checkPosition({ nodeElement: weaponBottomWrapPropsRightIconNode, leftOffset: WEAPON_COORDS[userType].bottomWrapRightIcon.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].bottomWrapRightIcon.topOffset, rowID: ID }) }) checkPosition({ nodeElement: weaponBottomWrapPropsRightDamageNode, leftOffset: WEAPON_COORDS[userType].bottomWrapRightIconValue.leftOffset, topOffset: amplifierOffset({ value: WEAPON_COORDS[userType].bottomWrapRightIconValue.topOffset, rowID: ID }) }) } !disableBlock && wrap(); (!disableBlock && damage) && leftSection() !disableBlock && labelSection(); (!disableBlock && accuracy) && rightSection() } export const checkMainWeapon = (ID: number, userType: TPersonTypes, weaponData: IWeaponData) => { const weaponNode = () => mainWeapon(userType) weaponNode().should('have.length', 1) checkWeaponBoxStyles(weaponNode) checkWeaponTopSection({ ID, userType, weaponType: 'main', label: 'Primary' }) checkWeaponImage({ ID, userType, weaponType: 'main' }) checkWeaponBottomSection({ ID, userType, weaponType: 'main', disableBlock: weaponData.disableBottomBlock, damage: weaponData.damage, label: weaponData.patrons, accuracy: weaponData.accuracy }) } export const checkSecondaryWeapon = (ID: number, userType: TPersonTypes, weaponData: IWeaponData) => { const weaponNode = () => secondaryWeapon(userType) weaponNode().should('have.length', 1) checkWeaponBoxStyles(weaponNode) checkWeaponTopSection({ ID, userType, weaponType: 'second', label: 'Secondary' }) checkWeaponImage({ ID, userType, weaponType: 'second' }) checkWeaponBottomSection({ ID, userType, weaponType: 'second', damage: weaponData.damage, label: weaponData.patrons, accuracy: weaponData.accuracy, disableBlock: weaponData.disableBottomBlock }) } export const checkMeleeWeapon = (ID: number, userType: TPersonTypes, weaponData: IWeaponData) => { const weaponNode = () => meleeWeapon(userType) weaponNode().should('have.length', 1) checkWeaponBoxStyles(weaponNode) checkWeaponTopSection({ ID, userType, weaponType: 'melee', label: 'Melee' }) checkWeaponImage({ ID, userType, weaponType: 'melee' }) checkWeaponBottomSection({ ID, userType, weaponType: 'melee', label: 'infinity', damage: weaponData.damage, accuracy: weaponData.accuracy, disableBlock: weaponData.disableBottomBlock }) } export const checkTempWeapon = (ID: number, userType: TPersonTypes) => { const weaponNode = () => tempWeapon(userType) weaponNode().should('have.length', 1) checkWeaponBoxStyles(weaponNode) checkWeaponTopSection({ ID, userType, weaponType: 'temp', label: 'Temporary', disableAttachments: true }) checkWeaponImage({ ID, userType, weaponType: 'temp' }) checkWeaponBottomSection({ ID, userType, weaponType: 'temp', disableBlock: true }) } export const checkFistsWeapon = (ID: number, userType: TPersonTypes) => { const weaponNode = () => fistsWeapon(userType) weaponNode().should('have.length', 1) checkWeaponBoxStyles(weaponNode, 'slim') checkWeaponTopSection({ ID, userType, weaponType: 'fists', forceDisabled: true }) checkWeaponImage({ ID, userType, weaponType: 'fists', customShiftWrap: 1, customShiftImage: 1 }) checkWeaponBottomSection({ ID, userType, weaponType: 'fists', forceDisabled: true }) } export const checkBootsWeapon = (ID: number, userType: TPersonTypes, isActive?: boolean) => { const weaponNode = () => bootsWeapon(userType) weaponNode().should('have.length', !isActive ? 0 : 1) if (!isActive) { return } checkWeaponBoxStyles(weaponNode, 'slim') checkWeaponTopSection({ ID, userType, weaponType: 'fists', forceDisabled: true }) checkWeaponImage({ ID, userType, weaponType: 'fists' }) checkWeaponBottomSection({ ID, userType, weaponType: 'fists', forceDisabled: true }) } export const checkWeaponBoxes = ({ userType, weaponsData }: { userType: TPersonTypes; weaponsData?: IWeaponsData }) => { cy.log(`**[START] Check Weapons: ${userType}**`) checkMainWeapon(0, userType, weaponsData.main) checkSecondaryWeapon(1, userType, weaponsData.secondary) checkMeleeWeapon(2, userType, weaponsData.melee) checkTempWeapon(3, userType) checkFistsWeapon(4, userType) checkBootsWeapon(5, userType, false) // temporary disabled cy.log(`**[END] Check Weapons: ${userType}**`) }
the_stack
import { ChartDataSectionType } from 'app/constants'; import { ChartConfig, ChartDataSectionField, ChartStyleConfig, LabelStyle, LegendStyle, } from 'app/types/ChartConfig'; import ChartDataSetDTO, { IChartDataSet, IChartDataSetRow, } from 'app/types/ChartDataSet'; import { getAutoFunnelTopPosition, getColumnRenderName, getDrillableRows, getExtraSeriesDataFormat, getExtraSeriesRowData, getGridStyle, getSeriesTooltips4Scatter, getStyles, toFormattedValue, transformToDataSet, } from 'app/utils/chartHelper'; import { init } from 'echarts'; import isEmpty from 'lodash/isEmpty'; import Chart from '../../../models/Chart'; import { ChartDrillOption } from '../../../models/ChartDrillOption'; import Config from './config'; import { Series, SeriesData } from './types'; class BasicFunnelChart extends Chart { config = Config; chart: any = null; constructor() { super( 'funnel-chart', 'viz.palette.graph.names.funnelChart', 'fsux_tubiao_loudoutu', ); this.meta.requirements = [ { group: [0, 1], aggregate: [1, 999], }, ]; } onMount(options, context): void { if (options.containerId === undefined || !context.document) { return; } this.chart = init( context.document.getElementById(options.containerId), 'default', ); this.mouseEvents?.forEach(event => { this.chart.on(event.name, event.callback); }); } onUpdated(props): void { if (!props.dataset || !props.dataset.columns || !props.config) { return; } this.chart?.clear(); if (!this.isMatchRequirement(props.config)) { return; } const newOptions = this.getOptions( props.dataset, props.config, props.drillOption, ); this.chart?.setOption(Object.assign({}, newOptions), true); } onUnMount(): void { this.chart?.dispose(); } onResize(opt: any, context): void { this.chart?.resize({ width: context?.width, height: context?.height }); } private getOptions( dataset: ChartDataSetDTO, config: ChartConfig, drillOption: ChartDrillOption, ) { const styleConfigs = config.styles || []; const dataConfigs = config.datas || []; const groupConfigs: ChartDataSectionField[] = getDrillableRows( dataConfigs, drillOption, ); const aggregateConfigs = dataConfigs .filter(c => c.type === ChartDataSectionType.AGGREGATE) .flatMap(config => config.rows || []); const infoConfigs = dataConfigs .filter(c => c.type === ChartDataSectionType.INFO) .flatMap(config => config.rows || []); const chartDataSet = transformToDataSet( dataset.rows, dataset.columns, dataConfigs, ); const dataList = !groupConfigs.length ? chartDataSet : chartDataSet?.sort( (a, b) => (b?.getCell(aggregateConfigs[0]) as any) - (a?.getCell(aggregateConfigs[0]) as any), ); const aggregateList = !groupConfigs.length ? aggregateConfigs?.sort( (a, b) => (chartDataSet?.[0]?.getCell(b) as any) - (chartDataSet?.[0]?.getCell(a) as any), ) : aggregateConfigs; const series = this.getSeries( styleConfigs, aggregateList, groupConfigs, dataList, infoConfigs, ); return { tooltip: this.getFunnelChartTooltip( groupConfigs, aggregateList, infoConfigs, ), legend: this.getLegendStyle(styleConfigs, series.sort), series, }; } private getDataItemStyle( config: ChartDataSectionField, colorConfigs: ChartDataSectionField[], chartDataSetRow: IChartDataSetRow<string>, ): { color: string | undefined } | undefined { const colorColConfig = colorConfigs?.[0]; const columnColor = config?.color?.start; if (colorColConfig) { const colorKey = chartDataSetRow.getCell(colorColConfig); const itemStyleColor = colorConfigs[0]?.color?.colors?.find( c => c.key === colorKey, ); return { color: itemStyleColor?.value, }; } else if (columnColor) { return { color: columnColor, }; } } private getLabelStyle(styles: ChartStyleConfig[]): LabelStyle { const [show, position, font, metric, conversion, arrival, percentage] = getStyles( styles, ['label'], [ 'showLabel', 'position', 'font', 'metric', 'conversion', 'arrival', 'percentage', ], ); return { show, position, ...font, formatter: params => { const { name, value, percent, data } = params; const formattedValue = toFormattedValue(value?.[0], data.format); const labels: string[] = []; if (metric) { labels.push(`${name}: ${formattedValue}`); } if (conversion && !isEmpty(data.conversion)) { labels.push(`转化率: ${data.conversion}%`); } if (arrival && !isEmpty(data.arrival)) { labels.push(`到达率: ${data.arrival}%`); } if (percentage) { labels.push(`百分比: ${percent}%`); } return labels.join('\n'); }, }; } private getLegendStyle(styles: ChartStyleConfig[], sort): LegendStyle { const [show, type, font, legendPos, height] = getStyles( styles, ['legend'], ['showLegend', 'type', 'font', 'position', 'height'], ); let positions = {}; let orient = ''; const top = getAutoFunnelTopPosition({ chart: this.chart, sort, legendPos, height, }); switch (legendPos) { case 'top': orient = 'horizontal'; positions = { top, left: 8, right: 8, height: 32 }; break; case 'bottom': orient = 'horizontal'; positions = { bottom: 8, left: 8, right: 8, height: 32 }; break; case 'left': orient = 'vertical'; positions = { left: 8, top, bottom: 24, width: 96 }; break; default: orient = 'vertical'; positions = { right: 8, top, bottom: 24, width: 96 }; break; } return { ...positions, height: height || null, show, type, orient, textStyle: font, }; } private getSeries( styles: ChartStyleConfig[], aggregateConfigs: ChartDataSectionField[], groupConfigs: ChartDataSectionField[], dataList: IChartDataSet<string>, infoConfigs: ChartDataSectionField[], ): Series { const [selectAll] = getStyles(styles, ['legend'], ['selectAll']); const [sort, funnelAlign, gap] = getStyles( styles, ['funnel'], ['sort', 'align', 'gap'], ); if (!groupConfigs.length) { const dc = dataList?.[0]; const datas: SeriesData[] = aggregateConfigs.map(aggConfig => { return { ...aggConfig, select: selectAll, value: [aggConfig] .concat(infoConfigs) .map(config => dc?.getCell(config)), name: getColumnRenderName(aggConfig), itemStyle: this.getDataItemStyle(aggConfig, groupConfigs, dc), ...getExtraSeriesRowData(dc), ...getExtraSeriesDataFormat(aggConfig?.format), }; }); return { ...getGridStyle(styles), type: 'funnel', funnelAlign, sort, gap, labelLine: { length: 10, lineStyle: { width: 1, type: 'solid', }, }, itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)', }, label: this.getLabelStyle(styles), labelLayout: { hideOverlap: true }, data: this.getFunnelSeriesData(datas), }; } const flattenedDatas = aggregateConfigs.flatMap(aggConfig => { const ormalizeSerieDatas: SeriesData[] = dataList.map(dc => { return { ...aggConfig, select: selectAll, value: aggregateConfigs .concat(infoConfigs) .map(config => dc?.getCell(config)), name: groupConfigs.map(config => dc.getCell(config)).join('-'), itemStyle: this.getDataItemStyle(aggConfig, groupConfigs, dc), ...getExtraSeriesRowData(dc), ...getExtraSeriesDataFormat(aggConfig?.format), }; }); return ormalizeSerieDatas; }); const series = { ...getGridStyle(styles), type: 'funnel', funnelAlign, sort, gap, labelLine: { length: 10, lineStyle: { width: 1, type: 'solid', }, }, itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)', }, label: this.getLabelStyle(styles), data: this.getFunnelSeriesData(flattenedDatas), }; return series; } private getFunnelSeriesData(seriesData: SeriesData[]) { const _calculateConversionAndArrivalRatio = (data, index) => { if (index) { data.conversion = this.formatPercent( (data.value?.[0] / Number(seriesData[index - 1].value?.[0])) * 100, ); data.arrival = this.formatPercent( (data.value?.[0] / Number(seriesData[0].value?.[0])) * 100, ); } return data; }; return seriesData.map(_calculateConversionAndArrivalRatio); } private formatPercent(per: number): string { const perStr = per + ''; return perStr.length - (perStr.indexOf('.') + 1) > 2 ? per.toFixed(2) : perStr; } private getFunnelChartTooltip( groupConfigs: ChartDataSectionField[], aggregateConfigs: ChartDataSectionField[], infoConfigs: ChartDataSectionField[], ): { trigger: string; formatter: (params) => string } { return { trigger: 'item', formatter(params) { const { data } = params; let tooltips: string[] = !!groupConfigs?.length ? [ `${groupConfigs?.map(gc => getColumnRenderName(gc)).join('-')}: ${ params?.name }`, ] : []; const aggTooltips = !!groupConfigs?.length ? getSeriesTooltips4Scatter( [params], aggregateConfigs.concat(infoConfigs), ) : getSeriesTooltips4Scatter([params], [data].concat(infoConfigs)); tooltips = tooltips.concat(aggTooltips); if (data.conversion) { tooltips.push(`转化率: ${data.conversion}%`); } if (data.arrival) { tooltips.push(`到达率: ${data.arrival}%`); } return tooltips.join('<br/>'); }, }; } } export default BasicFunnelChart;
the_stack
import {FieldsSelection,Observable} from '@genql/runtime' export type Scalars = { Boolean: boolean, Date: any, DateTime: any, Float: number, Hex: any, ID: string, Int: number, Json: any, Long: any, RGBAHue: any, RGBATransparency: any, RichTextAST: any, String: string, } export interface Aggregate { count: Scalars['Int'] __typename: 'Aggregate' } /** Asset system model */ export interface Asset { /** System stage field */ stage: Stage /** System Locale field */ locale: Locale /** Get the other localizations for this document */ localizations: Asset[] /** Get the document in other stages */ documentInStages: Asset[] /** The unique identifier */ id: Scalars['ID'] /** The time the document was created */ createdAt: Scalars['DateTime'] /** User that created this document */ createdBy?: User /** The time the document was updated */ updatedAt: Scalars['DateTime'] /** User that last updated this document */ updatedBy?: User /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Scalars['DateTime'] /** User that last published this document */ publishedBy?: User /** The file handle */ handle: Scalars['String'] /** The file name */ fileName: Scalars['String'] /** The height of the file */ height?: Scalars['Float'] /** The file width */ width?: Scalars['Float'] /** The file size */ size?: Scalars['Float'] /** The mime type of the file */ mimeType?: Scalars['String'] productImage: Product[] /** List of Asset versions */ history: Version[] /** Get the url for the asset with provided transformations applied. */ url: Scalars['String'] __typename: 'Asset' } /** A connection to a list of items. */ export interface AssetConnection { /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges: AssetEdge[] aggregate: Aggregate __typename: 'AssetConnection' } /** An edge in a connection. */ export interface AssetEdge { /** The item at the end of the edge. */ node: Asset /** A cursor for use in pagination. */ cursor: Scalars['String'] __typename: 'AssetEdge' } export type AssetOrderByInput = 'id_ASC' | 'id_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'publishedAt_ASC' | 'publishedAt_DESC' | 'handle_ASC' | 'handle_DESC' | 'fileName_ASC' | 'fileName_DESC' | 'height_ASC' | 'height_DESC' | 'width_ASC' | 'width_DESC' | 'size_ASC' | 'size_DESC' | 'mimeType_ASC' | 'mimeType_DESC' export interface BatchPayload { /** The number of nodes that have been affected by the Batch operation. */ count: Scalars['Long'] __typename: 'BatchPayload' } /** Representing a color value comprising of HEX, RGBA and css color values */ export interface Color { hex: Scalars['Hex'] rgba: RGBA css: Scalars['String'] __typename: 'Color' } export type DocumentFileTypes = 'jpg' | 'odp' | 'ods' | 'odt' | 'png' | 'svg' | 'txt' | 'webp' | 'docx' | 'pdf' | 'html' | 'doc' | 'xlsx' | 'xls' | 'pptx' | 'ppt' export interface DocumentVersion { id: Scalars['ID'] stage: Stage revision: Scalars['Int'] createdAt: Scalars['DateTime'] data?: Scalars['Json'] __typename: 'DocumentVersion' } export type ImageFit = 'clip' | 'crop' | 'scale' | 'max' /** Locale system enumeration */ export type Locale = 'en' | 'de' /** Representing a geolocation point with latitude and longitude */ export interface Location { latitude: Scalars['Float'] longitude: Scalars['Float'] distance: Scalars['Float'] __typename: 'Location' } export interface Mutation { /** * @deprecated Asset mutations will be overhauled soon * Create one asset */ createAsset?: Asset /** Update one asset */ updateAsset?: Asset /** Delete one asset from _all_ existing stages. Returns deleted document. */ deleteAsset?: Asset /** Upsert one asset */ upsertAsset?: Asset /** Publish one asset */ publishAsset?: Asset /** Unpublish one asset from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishAsset?: Asset /** Update many Asset documents */ updateManyAssetsConnection: AssetConnection /** Delete many Asset documents, return deleted documents */ deleteManyAssetsConnection: AssetConnection /** Publish many Asset documents */ publishManyAssetsConnection: AssetConnection /** Find many Asset documents that match criteria in specified stage and unpublish from target stages */ unpublishManyAssetsConnection: AssetConnection /** * @deprecated Please use the new paginated many mutation (updateManyAssetsConnection) * Update many assets */ updateManyAssets: BatchPayload /** * @deprecated Please use the new paginated many mutation (deleteManyAssetsConnection) * Delete many Asset documents */ deleteManyAssets: BatchPayload /** * @deprecated Please use the new paginated many mutation (publishManyAssetsConnection) * Publish many Asset documents */ publishManyAssets: BatchPayload /** * @deprecated Please use the new paginated many mutation (unpublishManyAssetsConnection) * Unpublish many Asset documents */ unpublishManyAssets: BatchPayload /** Create one product */ createProduct?: Product /** Update one product */ updateProduct?: Product /** Delete one product from _all_ existing stages. Returns deleted document. */ deleteProduct?: Product /** Upsert one product */ upsertProduct?: Product /** Publish one product */ publishProduct?: Product /** Unpublish one product from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishProduct?: Product /** Update many Product documents */ updateManyProductsConnection: ProductConnection /** Delete many Product documents, return deleted documents */ deleteManyProductsConnection: ProductConnection /** Publish many Product documents */ publishManyProductsConnection: ProductConnection /** Find many Product documents that match criteria in specified stage and unpublish from target stages */ unpublishManyProductsConnection: ProductConnection /** * @deprecated Please use the new paginated many mutation (updateManyProductsConnection) * Update many products */ updateManyProducts: BatchPayload /** * @deprecated Please use the new paginated many mutation (deleteManyProductsConnection) * Delete many Product documents */ deleteManyProducts: BatchPayload /** * @deprecated Please use the new paginated many mutation (publishManyProductsConnection) * Publish many Product documents */ publishManyProducts: BatchPayload /** * @deprecated Please use the new paginated many mutation (unpublishManyProductsConnection) * Unpublish many Product documents */ unpublishManyProducts: BatchPayload /** Create one review */ createReview?: Review /** Update one review */ updateReview?: Review /** Delete one review from _all_ existing stages. Returns deleted document. */ deleteReview?: Review /** Upsert one review */ upsertReview?: Review /** Publish one review */ publishReview?: Review /** Unpublish one review from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishReview?: Review /** Update many Review documents */ updateManyReviewsConnection: ReviewConnection /** Delete many Review documents, return deleted documents */ deleteManyReviewsConnection: ReviewConnection /** Publish many Review documents */ publishManyReviewsConnection: ReviewConnection /** Find many Review documents that match criteria in specified stage and unpublish from target stages */ unpublishManyReviewsConnection: ReviewConnection /** * @deprecated Please use the new paginated many mutation (updateManyReviewsConnection) * Update many reviews */ updateManyReviews: BatchPayload /** * @deprecated Please use the new paginated many mutation (deleteManyReviewsConnection) * Delete many Review documents */ deleteManyReviews: BatchPayload /** * @deprecated Please use the new paginated many mutation (publishManyReviewsConnection) * Publish many Review documents */ publishManyReviews: BatchPayload /** * @deprecated Please use the new paginated many mutation (unpublishManyReviewsConnection) * Unpublish many Review documents */ unpublishManyReviews: BatchPayload /** Create one vote */ createVote?: Vote /** Update one vote */ updateVote?: Vote /** Delete one vote from _all_ existing stages. Returns deleted document. */ deleteVote?: Vote /** Upsert one vote */ upsertVote?: Vote /** Publish one vote */ publishVote?: Vote /** Unpublish one vote from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishVote?: Vote /** Update many Vote documents */ updateManyVotesConnection: VoteConnection /** Delete many Vote documents, return deleted documents */ deleteManyVotesConnection: VoteConnection /** Publish many Vote documents */ publishManyVotesConnection: VoteConnection /** Find many Vote documents that match criteria in specified stage and unpublish from target stages */ unpublishManyVotesConnection: VoteConnection /** * @deprecated Please use the new paginated many mutation (updateManyVotesConnection) * Update many votes */ updateManyVotes: BatchPayload /** * @deprecated Please use the new paginated many mutation (deleteManyVotesConnection) * Delete many Vote documents */ deleteManyVotes: BatchPayload /** * @deprecated Please use the new paginated many mutation (publishManyVotesConnection) * Publish many Vote documents */ publishManyVotes: BatchPayload /** * @deprecated Please use the new paginated many mutation (unpublishManyVotesConnection) * Unpublish many Vote documents */ unpublishManyVotes: BatchPayload __typename: 'Mutation' } /** An object with an ID */ export type Node = (Asset | Product | Review | User | Vote) & { __isUnion?: true } /** Information about pagination in a connection. */ export interface PageInfo { /** When paginating forwards, are there more items? */ hasNextPage: Scalars['Boolean'] /** When paginating backwards, are there more items? */ hasPreviousPage: Scalars['Boolean'] /** When paginating backwards, the cursor to continue. */ startCursor?: Scalars['String'] /** When paginating forwards, the cursor to continue. */ endCursor?: Scalars['String'] /** Number of items in the current page. */ pageSize?: Scalars['Int'] __typename: 'PageInfo' } export interface Product { /** System stage field */ stage: Stage /** System Locale field */ locale: Locale /** Get the other localizations for this document */ localizations: Product[] /** Get the document in other stages */ documentInStages: Product[] /** The unique identifier */ id: Scalars['ID'] /** The time the document was created */ createdAt: Scalars['DateTime'] /** User that created this document */ createdBy?: User /** The time the document was updated */ updatedAt: Scalars['DateTime'] /** User that last updated this document */ updatedBy?: User /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Scalars['DateTime'] /** User that last published this document */ publishedBy?: User name: Scalars['String'] slug: Scalars['String'] description?: Scalars['String'] price: Scalars['Int'] reviews: Review[] votes: Vote[] image?: Asset content?: RichText /** List of Product versions */ history: Version[] __typename: 'Product' } /** A connection to a list of items. */ export interface ProductConnection { /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges: ProductEdge[] aggregate: Aggregate __typename: 'ProductConnection' } /** An edge in a connection. */ export interface ProductEdge { /** The item at the end of the edge. */ node: Product /** A cursor for use in pagination. */ cursor: Scalars['String'] __typename: 'ProductEdge' } export type ProductOrderByInput = 'id_ASC' | 'id_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'publishedAt_ASC' | 'publishedAt_DESC' | 'name_ASC' | 'name_DESC' | 'slug_ASC' | 'slug_DESC' | 'description_ASC' | 'description_DESC' | 'price_ASC' | 'price_DESC' export interface Query { /** Fetches an object given its ID */ node?: Node /** Retrieve multiple assets */ assets: Asset[] /** Retrieve a single asset */ asset?: Asset /** Retrieve multiple assets using the Relay connection interface */ assetsConnection: AssetConnection /** Retrieve document version */ assetVersion?: DocumentVersion /** Retrieve multiple products */ products: Product[] /** Retrieve a single product */ product?: Product /** Retrieve multiple products using the Relay connection interface */ productsConnection: ProductConnection /** Retrieve document version */ productVersion?: DocumentVersion /** Retrieve multiple reviews */ reviews: Review[] /** Retrieve a single review */ review?: Review /** Retrieve multiple reviews using the Relay connection interface */ reviewsConnection: ReviewConnection /** Retrieve document version */ reviewVersion?: DocumentVersion /** Retrieve multiple users */ users: User[] /** Retrieve a single user */ user?: User /** Retrieve multiple users using the Relay connection interface */ usersConnection: UserConnection /** Retrieve multiple votes */ votes: Vote[] /** Retrieve a single vote */ vote?: Vote /** Retrieve multiple votes using the Relay connection interface */ votesConnection: VoteConnection /** Retrieve document version */ voteVersion?: DocumentVersion __typename: 'Query' } /** Representing a RGBA color value: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb()_and_rgba() */ export interface RGBA { r: Scalars['RGBAHue'] g: Scalars['RGBAHue'] b: Scalars['RGBAHue'] a: Scalars['RGBATransparency'] __typename: 'RGBA' } export interface Review { /** System stage field */ stage: Stage /** Get the document in other stages */ documentInStages: Review[] /** The unique identifier */ id: Scalars['ID'] /** The time the document was created */ createdAt: Scalars['DateTime'] /** User that created this document */ createdBy?: User /** The time the document was updated */ updatedAt: Scalars['DateTime'] /** User that last updated this document */ updatedBy?: User /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Scalars['DateTime'] /** User that last published this document */ publishedBy?: User name?: Scalars['String'] comment: Scalars['String'] product?: Product /** List of Review versions */ history: Version[] __typename: 'Review' } /** A connection to a list of items. */ export interface ReviewConnection { /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges: ReviewEdge[] aggregate: Aggregate __typename: 'ReviewConnection' } /** An edge in a connection. */ export interface ReviewEdge { /** The item at the end of the edge. */ node: Review /** A cursor for use in pagination. */ cursor: Scalars['String'] __typename: 'ReviewEdge' } export type ReviewOrderByInput = 'id_ASC' | 'id_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'publishedAt_ASC' | 'publishedAt_DESC' | 'name_ASC' | 'name_DESC' | 'comment_ASC' | 'comment_DESC' /** Custom type representing a rich text value comprising of raw rich text ast, html, markdown and text values */ export interface RichText { /** Returns AST representation */ raw: Scalars['RichTextAST'] /** Returns HTMl representation */ html: Scalars['String'] /** Returns Markdown representation */ markdown: Scalars['String'] /** Returns plain-text contents of RichText */ text: Scalars['String'] __typename: 'RichText' } /** Stage system enumeration */ export type Stage = 'PUBLISHED' | 'DRAFT' export type SystemDateTimeFieldVariation = 'BASE' | 'LOCALIZATION' | 'COMBINED' /** User system model */ export interface User { /** System stage field */ stage: Stage /** Get the document in other stages */ documentInStages: User[] /** The unique identifier */ id: Scalars['ID'] /** The time the document was created */ createdAt: Scalars['DateTime'] /** The time the document was updated */ updatedAt: Scalars['DateTime'] /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Scalars['DateTime'] /** The username */ name: Scalars['String'] /** Profile Picture url */ picture?: Scalars['String'] /** User Kind. Can be either MEMBER, PAT or PUBLIC */ kind: UserKind /** Flag to determine if user is active or not */ isActive: Scalars['Boolean'] __typename: 'User' } /** A connection to a list of items. */ export interface UserConnection { /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges: UserEdge[] aggregate: Aggregate __typename: 'UserConnection' } /** An edge in a connection. */ export interface UserEdge { /** The item at the end of the edge. */ node: User /** A cursor for use in pagination. */ cursor: Scalars['String'] __typename: 'UserEdge' } /** System User Kind */ export type UserKind = 'MEMBER' | 'PAT' | 'PUBLIC' | 'WEBHOOK' export type UserOrderByInput = 'id_ASC' | 'id_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'publishedAt_ASC' | 'publishedAt_DESC' | 'name_ASC' | 'name_DESC' | 'picture_ASC' | 'picture_DESC' | 'kind_ASC' | 'kind_DESC' | 'isActive_ASC' | 'isActive_DESC' export interface Version { id: Scalars['ID'] stage: Stage revision: Scalars['Int'] createdAt: Scalars['DateTime'] __typename: 'Version' } export interface Vote { /** System stage field */ stage: Stage /** Get the document in other stages */ documentInStages: Vote[] /** The unique identifier */ id: Scalars['ID'] /** The time the document was created */ createdAt: Scalars['DateTime'] /** User that created this document */ createdBy?: User /** The time the document was updated */ updatedAt: Scalars['DateTime'] /** User that last updated this document */ updatedBy?: User /** The time the document was published. Null on documents in draft stage. */ publishedAt?: Scalars['DateTime'] /** User that last published this document */ publishedBy?: User product?: Product /** List of Vote versions */ history: Version[] __typename: 'Vote' } /** A connection to a list of items. */ export interface VoteConnection { /** Information to aid in pagination. */ pageInfo: PageInfo /** A list of edges. */ edges: VoteEdge[] aggregate: Aggregate __typename: 'VoteConnection' } /** An edge in a connection. */ export interface VoteEdge { /** The item at the end of the edge. */ node: Vote /** A cursor for use in pagination. */ cursor: Scalars['String'] __typename: 'VoteEdge' } export type VoteOrderByInput = 'id_ASC' | 'id_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'publishedAt_ASC' | 'publishedAt_DESC' export type _FilterKind = 'search' | 'AND' | 'OR' | 'NOT' | 'eq' | 'eq_not' | 'in' | 'not_in' | 'lt' | 'lte' | 'gt' | 'gte' | 'contains' | 'not_contains' | 'starts_with' | 'not_starts_with' | 'ends_with' | 'not_ends_with' | 'contains_all' | 'contains_some' | 'contains_none' | 'relational_single' | 'relational_every' | 'relational_some' | 'relational_none' export type _MutationInputFieldKind = 'scalar' | 'richText' | 'richTextWithEmbeds' | 'enum' | 'relation' | 'union' | 'virtual' export type _MutationKind = 'create' | 'publish' | 'unpublish' | 'update' | 'upsert' | 'delete' | 'updateMany' | 'publishMany' | 'unpublishMany' | 'deleteMany' export type _OrderDirection = 'asc' | 'desc' export type _RelationInputCardinality = 'one' | 'many' export type _RelationInputKind = 'create' | 'update' export type _RelationKind = 'regular' | 'union' export type _SystemDateTimeFieldVariation = 'base' | 'localization' | 'combined' export interface AggregateRequest{ count?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Asset system model */ export interface AssetRequest{ /** System stage field */ stage?: boolean | number /** System Locale field */ locale?: boolean | number /** Get the other localizations for this document */ localizations?: [{ /** Potential locales that should be returned */ locales: Locale[], /** Decides if the current locale should be included or not */ includeCurrent: Scalars['Boolean']},AssetRequest] /** Get the document in other stages */ documentInStages?: [{ /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']},AssetRequest] /** The unique identifier */ id?: boolean | number /** The time the document was created */ createdAt?: [{ /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}] /** User that created this document */ createdBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The time the document was updated */ updatedAt?: [{ /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}] /** User that last updated this document */ updatedBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The time the document was published. Null on documents in draft stage. */ publishedAt?: [{ /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}] /** User that last published this document */ publishedBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The file handle */ handle?: boolean | number /** The file name */ fileName?: boolean | number /** The height of the file */ height?: boolean | number /** The file width */ width?: boolean | number /** The file size */ size?: boolean | number /** The mime type of the file */ mimeType?: boolean | number productImage?: [{where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `productImage` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},ProductRequest] | ProductRequest /** List of Asset versions */ history?: [{limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)},VersionRequest] /** Get the url for the asset with provided transformations applied. */ url?: [{transformation?: (AssetTransformationInput | null)}] | boolean | number __typename?: boolean | number __scalar?: boolean | number } export interface AssetConnectInput { /** Document to connect */ where: AssetWhereUniqueInput, /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: (ConnectPositionInput | null)} /** A connection to a list of items. */ export interface AssetConnectionRequest{ /** Information to aid in pagination. */ pageInfo?: PageInfoRequest /** A list of edges. */ edges?: AssetEdgeRequest aggregate?: AggregateRequest __typename?: boolean | number __scalar?: boolean | number } export interface AssetCreateInput {createdAt?: (Scalars['DateTime'] | null),updatedAt?: (Scalars['DateTime'] | null),handle: Scalars['String'],fileName: Scalars['String'],height?: (Scalars['Float'] | null),width?: (Scalars['Float'] | null),size?: (Scalars['Float'] | null),mimeType?: (Scalars['String'] | null),productImage?: (ProductCreateManyInlineInput | null), /** Inline mutations for managing document localizations excluding the default locale */ localizations?: (AssetCreateLocalizationsInput | null)} export interface AssetCreateLocalizationDataInput {createdAt?: (Scalars['DateTime'] | null),updatedAt?: (Scalars['DateTime'] | null),handle: Scalars['String'],fileName: Scalars['String'],height?: (Scalars['Float'] | null),width?: (Scalars['Float'] | null),size?: (Scalars['Float'] | null),mimeType?: (Scalars['String'] | null)} export interface AssetCreateLocalizationInput { /** Localization input */ data: AssetCreateLocalizationDataInput,locale: Locale} export interface AssetCreateLocalizationsInput { /** Create localizations for the newly-created document */ create?: (AssetCreateLocalizationInput[] | null)} export interface AssetCreateManyInlineInput { /** Create and connect multiple existing Asset documents */ create?: (AssetCreateInput[] | null), /** Connect multiple existing Asset documents */ connect?: (AssetWhereUniqueInput[] | null)} export interface AssetCreateOneInlineInput { /** Create and connect one Asset document */ create?: (AssetCreateInput | null), /** Connect one existing Asset document */ connect?: (AssetWhereUniqueInput | null)} /** An edge in a connection. */ export interface AssetEdgeRequest{ /** The item at the end of the edge. */ node?: AssetRequest /** A cursor for use in pagination. */ cursor?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Identifies documents */ export interface AssetManyWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (AssetWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (AssetWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (AssetWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),createdBy?: (UserWhereInput | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),updatedBy?: (UserWhereInput | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),publishedBy?: (UserWhereInput | null),productImage_every?: (ProductWhereInput | null),productImage_some?: (ProductWhereInput | null),productImage_none?: (ProductWhereInput | null)} /** Transformations for Assets */ export interface AssetTransformationInput {image?: (ImageTransformationInput | null),document?: (DocumentTransformationInput | null), /** Pass true if you want to validate the passed transformation parameters */ validateOptions?: (Scalars['Boolean'] | null)} export interface AssetUpdateInput {handle?: (Scalars['String'] | null),fileName?: (Scalars['String'] | null),height?: (Scalars['Float'] | null),width?: (Scalars['Float'] | null),size?: (Scalars['Float'] | null),mimeType?: (Scalars['String'] | null),productImage?: (ProductUpdateManyInlineInput | null), /** Manage document localizations */ localizations?: (AssetUpdateLocalizationsInput | null)} export interface AssetUpdateLocalizationDataInput {handle?: (Scalars['String'] | null),fileName?: (Scalars['String'] | null),height?: (Scalars['Float'] | null),width?: (Scalars['Float'] | null),size?: (Scalars['Float'] | null),mimeType?: (Scalars['String'] | null)} export interface AssetUpdateLocalizationInput {data: AssetUpdateLocalizationDataInput,locale: Locale} export interface AssetUpdateLocalizationsInput { /** Localizations to create */ create?: (AssetCreateLocalizationInput[] | null), /** Localizations to update */ update?: (AssetUpdateLocalizationInput[] | null),upsert?: (AssetUpsertLocalizationInput[] | null), /** Localizations to delete */ delete?: (Locale[] | null)} export interface AssetUpdateManyInlineInput { /** Create and connect multiple Asset documents */ create?: (AssetCreateInput[] | null), /** Connect multiple existing Asset documents */ connect?: (AssetConnectInput[] | null), /** Override currently-connected documents with multiple existing Asset documents */ set?: (AssetWhereUniqueInput[] | null), /** Update multiple Asset documents */ update?: (AssetUpdateWithNestedWhereUniqueInput[] | null), /** Upsert multiple Asset documents */ upsert?: (AssetUpsertWithNestedWhereUniqueInput[] | null), /** Disconnect multiple Asset documents */ disconnect?: (AssetWhereUniqueInput[] | null), /** Delete multiple Asset documents */ delete?: (AssetWhereUniqueInput[] | null)} export interface AssetUpdateManyInput {fileName?: (Scalars['String'] | null),height?: (Scalars['Float'] | null),width?: (Scalars['Float'] | null),size?: (Scalars['Float'] | null),mimeType?: (Scalars['String'] | null), /** Optional updates to localizations */ localizations?: (AssetUpdateManyLocalizationsInput | null)} export interface AssetUpdateManyLocalizationDataInput {fileName?: (Scalars['String'] | null),height?: (Scalars['Float'] | null),width?: (Scalars['Float'] | null),size?: (Scalars['Float'] | null),mimeType?: (Scalars['String'] | null)} export interface AssetUpdateManyLocalizationInput {data: AssetUpdateManyLocalizationDataInput,locale: Locale} export interface AssetUpdateManyLocalizationsInput { /** Localizations to update */ update?: (AssetUpdateManyLocalizationInput[] | null)} export interface AssetUpdateManyWithNestedWhereInput { /** Document search */ where: AssetWhereInput, /** Update many input */ data: AssetUpdateManyInput} export interface AssetUpdateOneInlineInput { /** Create and connect one Asset document */ create?: (AssetCreateInput | null), /** Update single Asset document */ update?: (AssetUpdateWithNestedWhereUniqueInput | null), /** Upsert single Asset document */ upsert?: (AssetUpsertWithNestedWhereUniqueInput | null), /** Connect existing Asset document */ connect?: (AssetWhereUniqueInput | null), /** Disconnect currently connected Asset document */ disconnect?: (Scalars['Boolean'] | null), /** Delete currently connected Asset document */ delete?: (Scalars['Boolean'] | null)} export interface AssetUpdateWithNestedWhereUniqueInput { /** Unique document search */ where: AssetWhereUniqueInput, /** Document to update */ data: AssetUpdateInput} export interface AssetUpsertInput { /** Create document if it didn't exist */ create: AssetCreateInput, /** Update document if it exists */ update: AssetUpdateInput} export interface AssetUpsertLocalizationInput {update: AssetUpdateLocalizationDataInput,create: AssetCreateLocalizationDataInput,locale: Locale} export interface AssetUpsertWithNestedWhereUniqueInput { /** Unique document search */ where: AssetWhereUniqueInput, /** Upsert data */ data: AssetUpsertInput} /** Identifies documents */ export interface AssetWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (AssetWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (AssetWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (AssetWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),createdBy?: (UserWhereInput | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),updatedBy?: (UserWhereInput | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),publishedBy?: (UserWhereInput | null),handle?: (Scalars['String'] | null), /** All values that are not equal to given value. */ handle_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ handle_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ handle_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ handle_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ handle_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ handle_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ handle_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ handle_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ handle_not_ends_with?: (Scalars['String'] | null),fileName?: (Scalars['String'] | null), /** All values that are not equal to given value. */ fileName_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ fileName_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ fileName_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ fileName_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ fileName_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ fileName_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ fileName_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ fileName_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ fileName_not_ends_with?: (Scalars['String'] | null),height?: (Scalars['Float'] | null), /** All values that are not equal to given value. */ height_not?: (Scalars['Float'] | null), /** All values that are contained in given list. */ height_in?: (Scalars['Float'][] | null), /** All values that are not contained in given list. */ height_not_in?: (Scalars['Float'][] | null), /** All values less than the given value. */ height_lt?: (Scalars['Float'] | null), /** All values less than or equal the given value. */ height_lte?: (Scalars['Float'] | null), /** All values greater than the given value. */ height_gt?: (Scalars['Float'] | null), /** All values greater than or equal the given value. */ height_gte?: (Scalars['Float'] | null),width?: (Scalars['Float'] | null), /** All values that are not equal to given value. */ width_not?: (Scalars['Float'] | null), /** All values that are contained in given list. */ width_in?: (Scalars['Float'][] | null), /** All values that are not contained in given list. */ width_not_in?: (Scalars['Float'][] | null), /** All values less than the given value. */ width_lt?: (Scalars['Float'] | null), /** All values less than or equal the given value. */ width_lte?: (Scalars['Float'] | null), /** All values greater than the given value. */ width_gt?: (Scalars['Float'] | null), /** All values greater than or equal the given value. */ width_gte?: (Scalars['Float'] | null),size?: (Scalars['Float'] | null), /** All values that are not equal to given value. */ size_not?: (Scalars['Float'] | null), /** All values that are contained in given list. */ size_in?: (Scalars['Float'][] | null), /** All values that are not contained in given list. */ size_not_in?: (Scalars['Float'][] | null), /** All values less than the given value. */ size_lt?: (Scalars['Float'] | null), /** All values less than or equal the given value. */ size_lte?: (Scalars['Float'] | null), /** All values greater than the given value. */ size_gt?: (Scalars['Float'] | null), /** All values greater than or equal the given value. */ size_gte?: (Scalars['Float'] | null),mimeType?: (Scalars['String'] | null), /** All values that are not equal to given value. */ mimeType_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ mimeType_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ mimeType_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ mimeType_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ mimeType_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ mimeType_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ mimeType_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ mimeType_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ mimeType_not_ends_with?: (Scalars['String'] | null),productImage_every?: (ProductWhereInput | null),productImage_some?: (ProductWhereInput | null),productImage_none?: (ProductWhereInput | null)} /** References Asset record uniquely */ export interface AssetWhereUniqueInput {id?: (Scalars['ID'] | null)} export interface BatchPayloadRequest{ /** The number of nodes that have been affected by the Batch operation. */ count?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Representing a color value comprising of HEX, RGBA and css color values */ export interface ColorRequest{ hex?: boolean | number rgba?: RGBARequest css?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Accepts either HEX or RGBA color value. At least one of hex or rgba value should be passed. If both are passed RGBA is used. */ export interface ColorInput {hex?: (Scalars['Hex'] | null),rgba?: (RGBAInput | null)} export interface ConnectPositionInput { /** Connect document after specified document */ after?: (Scalars['ID'] | null), /** Connect document before specified document */ before?: (Scalars['ID'] | null), /** Connect document at first position */ start?: (Scalars['Boolean'] | null), /** Connect document at last position */ end?: (Scalars['Boolean'] | null)} export interface DocumentOutputInput { /** * Transforms a document into a desired file type. * See this matrix for format support: * * PDF: jpg, odp, ods, odt, png, svg, txt, and webp * DOC: docx, html, jpg, odt, pdf, png, svg, txt, and webp * DOCX: doc, html, jpg, odt, pdf, png, svg, txt, and webp * ODT: doc, docx, html, jpg, pdf, png, svg, txt, and webp * XLS: jpg, pdf, ods, png, svg, xlsx, and webp * XLSX: jpg, pdf, ods, png, svg, xls, and webp * ODS: jpg, pdf, png, xls, svg, xlsx, and webp * PPT: jpg, odp, pdf, png, svg, pptx, and webp * PPTX: jpg, odp, pdf, png, svg, ppt, and webp * ODP: jpg, pdf, png, ppt, svg, pptx, and webp * BMP: jpg, odp, ods, odt, pdf, png, svg, and webp * GIF: jpg, odp, ods, odt, pdf, png, svg, and webp * JPG: jpg, odp, ods, odt, pdf, png, svg, and webp * PNG: jpg, odp, ods, odt, pdf, png, svg, and webp * WEBP: jpg, odp, ods, odt, pdf, png, svg, and webp * TIFF: jpg, odp, ods, odt, pdf, png, svg, and webp * AI: jpg, odp, ods, odt, pdf, png, svg, and webp * PSD: jpg, odp, ods, odt, pdf, png, svg, and webp * SVG: jpg, odp, ods, odt, pdf, png, and webp * HTML: jpg, odt, pdf, svg, txt, and webp * TXT: jpg, html, odt, pdf, svg, and webp */ format?: (DocumentFileTypes | null)} /** Transformations for Documents */ export interface DocumentTransformationInput { /** Changes the output for the file. */ output?: (DocumentOutputInput | null)} export interface DocumentVersionRequest{ id?: boolean | number stage?: boolean | number revision?: boolean | number createdAt?: boolean | number data?: boolean | number __typename?: boolean | number __scalar?: boolean | number } export interface ImageResizeInput { /** The width in pixels to resize the image to. The value must be an integer from 1 to 10000. */ width?: (Scalars['Int'] | null), /** The height in pixels to resize the image to. The value must be an integer from 1 to 10000. */ height?: (Scalars['Int'] | null), /** The default value for the fit parameter is fit:clip. */ fit?: (ImageFit | null)} /** Transformations for Images */ export interface ImageTransformationInput { /** Resizes the image */ resize?: (ImageResizeInput | null)} /** Representing a geolocation point with latitude and longitude */ export interface LocationRequest{ latitude?: boolean | number longitude?: boolean | number distance?: [{from: LocationInput}] __typename?: boolean | number __scalar?: boolean | number } /** Input for a geolocation point with latitude and longitude */ export interface LocationInput {latitude: Scalars['Float'],longitude: Scalars['Float']} export interface MutationRequest{ /** * @deprecated Asset mutations will be overhauled soon * Create one asset */ createAsset?: [{data: AssetCreateInput},AssetRequest] /** Update one asset */ updateAsset?: [{where: AssetWhereUniqueInput,data: AssetUpdateInput},AssetRequest] /** Delete one asset from _all_ existing stages. Returns deleted document. */ deleteAsset?: [{ /** Document to delete */ where: AssetWhereUniqueInput},AssetRequest] /** Upsert one asset */ upsertAsset?: [{where: AssetWhereUniqueInput,upsert: AssetUpsertInput},AssetRequest] /** Publish one asset */ publishAsset?: [{ /** Document to publish */ where: AssetWhereUniqueInput, /** Optional localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is set */ withDefaultLocale?: (Scalars['Boolean'] | null), /** Publishing target stage */ to: Stage[]},AssetRequest] /** Unpublish one asset from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishAsset?: [{ /** Document to unpublish */ where: AssetWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[], /** Optional locales to unpublish. Unpublishing the default locale will completely remove the document from the selected stages */ locales?: (Locale[] | null), /** Unpublish complete document including default localization and relations from stages. Can be disabled. */ unpublishBase?: (Scalars['Boolean'] | null)},AssetRequest] /** Update many Asset documents */ updateManyAssetsConnection?: [{ /** Documents to apply update on */ where?: (AssetManyWhereInput | null), /** Updates to document content */ data: AssetUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},AssetConnectionRequest] /** Delete many Asset documents, return deleted documents */ deleteManyAssetsConnection?: [{ /** Documents to delete */ where?: (AssetManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},AssetConnectionRequest] | AssetConnectionRequest /** Publish many Asset documents */ publishManyAssetsConnection?: [{ /** Identifies documents in each stage to be published */ where?: (AssetManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)},AssetConnectionRequest] /** Find many Asset documents that match criteria in specified stage and unpublish from target stages */ unpublishManyAssetsConnection?: [{ /** Identifies documents in draft stage */ where?: (AssetManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)},AssetConnectionRequest] /** * @deprecated Please use the new paginated many mutation (updateManyAssetsConnection) * Update many assets */ updateManyAssets?: [{ /** Documents to apply update on */ where?: (AssetManyWhereInput | null), /** Updates to document content */ data: AssetUpdateManyInput},BatchPayloadRequest] /** * @deprecated Please use the new paginated many mutation (deleteManyAssetsConnection) * Delete many Asset documents */ deleteManyAssets?: [{ /** Documents to delete */ where?: (AssetManyWhereInput | null)},BatchPayloadRequest] | BatchPayloadRequest /** * @deprecated Please use the new paginated many mutation (publishManyAssetsConnection) * Publish many Asset documents */ publishManyAssets?: [{ /** Identifies documents in each stage to be published */ where?: (AssetManyWhereInput | null), /** Stages to publish documents to */ to: Stage[], /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)},BatchPayloadRequest] /** * @deprecated Please use the new paginated many mutation (unpublishManyAssetsConnection) * Unpublish many Asset documents */ unpublishManyAssets?: [{ /** Identifies documents in each stage */ where?: (AssetManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[], /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)},BatchPayloadRequest] /** Create one product */ createProduct?: [{data: ProductCreateInput},ProductRequest] /** Update one product */ updateProduct?: [{where: ProductWhereUniqueInput,data: ProductUpdateInput},ProductRequest] /** Delete one product from _all_ existing stages. Returns deleted document. */ deleteProduct?: [{ /** Document to delete */ where: ProductWhereUniqueInput},ProductRequest] /** Upsert one product */ upsertProduct?: [{where: ProductWhereUniqueInput,upsert: ProductUpsertInput},ProductRequest] /** Publish one product */ publishProduct?: [{ /** Document to publish */ where: ProductWhereUniqueInput, /** Optional localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is set */ withDefaultLocale?: (Scalars['Boolean'] | null), /** Publishing target stage */ to: Stage[]},ProductRequest] /** Unpublish one product from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishProduct?: [{ /** Document to unpublish */ where: ProductWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[], /** Optional locales to unpublish. Unpublishing the default locale will completely remove the document from the selected stages */ locales?: (Locale[] | null), /** Unpublish complete document including default localization and relations from stages. Can be disabled. */ unpublishBase?: (Scalars['Boolean'] | null)},ProductRequest] /** Update many Product documents */ updateManyProductsConnection?: [{ /** Documents to apply update on */ where?: (ProductManyWhereInput | null), /** Updates to document content */ data: ProductUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},ProductConnectionRequest] /** Delete many Product documents, return deleted documents */ deleteManyProductsConnection?: [{ /** Documents to delete */ where?: (ProductManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},ProductConnectionRequest] | ProductConnectionRequest /** Publish many Product documents */ publishManyProductsConnection?: [{ /** Identifies documents in each stage to be published */ where?: (ProductManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)},ProductConnectionRequest] /** Find many Product documents that match criteria in specified stage and unpublish from target stages */ unpublishManyProductsConnection?: [{ /** Identifies documents in draft stage */ where?: (ProductManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)},ProductConnectionRequest] /** * @deprecated Please use the new paginated many mutation (updateManyProductsConnection) * Update many products */ updateManyProducts?: [{ /** Documents to apply update on */ where?: (ProductManyWhereInput | null), /** Updates to document content */ data: ProductUpdateManyInput},BatchPayloadRequest] /** * @deprecated Please use the new paginated many mutation (deleteManyProductsConnection) * Delete many Product documents */ deleteManyProducts?: [{ /** Documents to delete */ where?: (ProductManyWhereInput | null)},BatchPayloadRequest] | BatchPayloadRequest /** * @deprecated Please use the new paginated many mutation (publishManyProductsConnection) * Publish many Product documents */ publishManyProducts?: [{ /** Identifies documents in each stage to be published */ where?: (ProductManyWhereInput | null), /** Stages to publish documents to */ to: Stage[], /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)},BatchPayloadRequest] /** * @deprecated Please use the new paginated many mutation (unpublishManyProductsConnection) * Unpublish many Product documents */ unpublishManyProducts?: [{ /** Identifies documents in each stage */ where?: (ProductManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[], /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)},BatchPayloadRequest] /** Create one review */ createReview?: [{data: ReviewCreateInput},ReviewRequest] /** Update one review */ updateReview?: [{where: ReviewWhereUniqueInput,data: ReviewUpdateInput},ReviewRequest] /** Delete one review from _all_ existing stages. Returns deleted document. */ deleteReview?: [{ /** Document to delete */ where: ReviewWhereUniqueInput},ReviewRequest] /** Upsert one review */ upsertReview?: [{where: ReviewWhereUniqueInput,upsert: ReviewUpsertInput},ReviewRequest] /** Publish one review */ publishReview?: [{ /** Document to publish */ where: ReviewWhereUniqueInput, /** Publishing target stage */ to: Stage[]},ReviewRequest] /** Unpublish one review from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishReview?: [{ /** Document to unpublish */ where: ReviewWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[]},ReviewRequest] /** Update many Review documents */ updateManyReviewsConnection?: [{ /** Documents to apply update on */ where?: (ReviewManyWhereInput | null), /** Updates to document content */ data: ReviewUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},ReviewConnectionRequest] /** Delete many Review documents, return deleted documents */ deleteManyReviewsConnection?: [{ /** Documents to delete */ where?: (ReviewManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},ReviewConnectionRequest] | ReviewConnectionRequest /** Publish many Review documents */ publishManyReviewsConnection?: [{ /** Identifies documents in each stage to be published */ where?: (ReviewManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},ReviewConnectionRequest] /** Find many Review documents that match criteria in specified stage and unpublish from target stages */ unpublishManyReviewsConnection?: [{ /** Identifies documents in draft stage */ where?: (ReviewManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},ReviewConnectionRequest] /** * @deprecated Please use the new paginated many mutation (updateManyReviewsConnection) * Update many reviews */ updateManyReviews?: [{ /** Documents to apply update on */ where?: (ReviewManyWhereInput | null), /** Updates to document content */ data: ReviewUpdateManyInput},BatchPayloadRequest] /** * @deprecated Please use the new paginated many mutation (deleteManyReviewsConnection) * Delete many Review documents */ deleteManyReviews?: [{ /** Documents to delete */ where?: (ReviewManyWhereInput | null)},BatchPayloadRequest] | BatchPayloadRequest /** * @deprecated Please use the new paginated many mutation (publishManyReviewsConnection) * Publish many Review documents */ publishManyReviews?: [{ /** Identifies documents in each stage to be published */ where?: (ReviewManyWhereInput | null), /** Stages to publish documents to */ to: Stage[]},BatchPayloadRequest] /** * @deprecated Please use the new paginated many mutation (unpublishManyReviewsConnection) * Unpublish many Review documents */ unpublishManyReviews?: [{ /** Identifies documents in each stage */ where?: (ReviewManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[]},BatchPayloadRequest] /** Create one vote */ createVote?: [{data: VoteCreateInput},VoteRequest] /** Update one vote */ updateVote?: [{where: VoteWhereUniqueInput,data: VoteUpdateInput},VoteRequest] /** Delete one vote from _all_ existing stages. Returns deleted document. */ deleteVote?: [{ /** Document to delete */ where: VoteWhereUniqueInput},VoteRequest] /** Upsert one vote */ upsertVote?: [{where: VoteWhereUniqueInput,upsert: VoteUpsertInput},VoteRequest] /** Publish one vote */ publishVote?: [{ /** Document to publish */ where: VoteWhereUniqueInput, /** Publishing target stage */ to: Stage[]},VoteRequest] /** Unpublish one vote from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishVote?: [{ /** Document to unpublish */ where: VoteWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[]},VoteRequest] /** Update many Vote documents */ updateManyVotesConnection?: [{ /** Documents to apply update on */ where?: (VoteManyWhereInput | null), /** Updates to document content */ data: VoteUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},VoteConnectionRequest] /** Delete many Vote documents, return deleted documents */ deleteManyVotesConnection?: [{ /** Documents to delete */ where?: (VoteManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},VoteConnectionRequest] | VoteConnectionRequest /** Publish many Vote documents */ publishManyVotesConnection?: [{ /** Identifies documents in each stage to be published */ where?: (VoteManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},VoteConnectionRequest] /** Find many Vote documents that match criteria in specified stage and unpublish from target stages */ unpublishManyVotesConnection?: [{ /** Identifies documents in draft stage */ where?: (VoteManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)},VoteConnectionRequest] /** * @deprecated Please use the new paginated many mutation (updateManyVotesConnection) * Update many votes */ updateManyVotes?: [{ /** Documents to apply update on */ where?: (VoteManyWhereInput | null), /** Updates to document content */ data: VoteUpdateManyInput},BatchPayloadRequest] /** * @deprecated Please use the new paginated many mutation (deleteManyVotesConnection) * Delete many Vote documents */ deleteManyVotes?: [{ /** Documents to delete */ where?: (VoteManyWhereInput | null)},BatchPayloadRequest] | BatchPayloadRequest /** * @deprecated Please use the new paginated many mutation (publishManyVotesConnection) * Publish many Vote documents */ publishManyVotes?: [{ /** Identifies documents in each stage to be published */ where?: (VoteManyWhereInput | null), /** Stages to publish documents to */ to: Stage[]},BatchPayloadRequest] /** * @deprecated Please use the new paginated many mutation (unpublishManyVotesConnection) * Unpublish many Vote documents */ unpublishManyVotes?: [{ /** Identifies documents in each stage */ where?: (VoteManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[]},BatchPayloadRequest] __typename?: boolean | number __scalar?: boolean | number } /** An object with an ID */ export interface NodeRequest{ /** The id of the object. */ id?: boolean | number /** The Stage of an object */ stage?: boolean | number on_Asset?: AssetRequest on_Product?: ProductRequest on_Review?: ReviewRequest on_User?: UserRequest on_Vote?: VoteRequest __typename?: boolean | number __scalar?: boolean | number } /** Information about pagination in a connection. */ export interface PageInfoRequest{ /** When paginating forwards, are there more items? */ hasNextPage?: boolean | number /** When paginating backwards, are there more items? */ hasPreviousPage?: boolean | number /** When paginating backwards, the cursor to continue. */ startCursor?: boolean | number /** When paginating forwards, the cursor to continue. */ endCursor?: boolean | number /** Number of items in the current page. */ pageSize?: boolean | number __typename?: boolean | number __scalar?: boolean | number } export interface ProductRequest{ /** System stage field */ stage?: boolean | number /** System Locale field */ locale?: boolean | number /** Get the other localizations for this document */ localizations?: [{ /** Potential locales that should be returned */ locales: Locale[], /** Decides if the current locale should be included or not */ includeCurrent: Scalars['Boolean']},ProductRequest] /** Get the document in other stages */ documentInStages?: [{ /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']},ProductRequest] /** The unique identifier */ id?: boolean | number /** The time the document was created */ createdAt?: [{ /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}] /** User that created this document */ createdBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The time the document was updated */ updatedAt?: [{ /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}] /** User that last updated this document */ updatedBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The time the document was published. Null on documents in draft stage. */ publishedAt?: [{ /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}] /** User that last published this document */ publishedBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest name?: boolean | number slug?: boolean | number description?: boolean | number price?: boolean | number reviews?: [{where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `reviews` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},ReviewRequest] | ReviewRequest votes?: [{where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `votes` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},VoteRequest] | VoteRequest image?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `image` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},AssetRequest] | AssetRequest content?: RichTextRequest /** List of Product versions */ history?: [{limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)},VersionRequest] __typename?: boolean | number __scalar?: boolean | number } export interface ProductConnectInput { /** Document to connect */ where: ProductWhereUniqueInput, /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: (ConnectPositionInput | null)} /** A connection to a list of items. */ export interface ProductConnectionRequest{ /** Information to aid in pagination. */ pageInfo?: PageInfoRequest /** A list of edges. */ edges?: ProductEdgeRequest aggregate?: AggregateRequest __typename?: boolean | number __scalar?: boolean | number } export interface ProductCreateInput {createdAt?: (Scalars['DateTime'] | null),updatedAt?: (Scalars['DateTime'] | null), /** name input for default locale (en) */ name: Scalars['String'],slug: Scalars['String'],description?: (Scalars['String'] | null),price: Scalars['Int'],reviews?: (ReviewCreateManyInlineInput | null),votes?: (VoteCreateManyInlineInput | null),image?: (AssetCreateOneInlineInput | null),content?: (Scalars['RichTextAST'] | null), /** Inline mutations for managing document localizations excluding the default locale */ localizations?: (ProductCreateLocalizationsInput | null)} export interface ProductCreateLocalizationDataInput {createdAt?: (Scalars['DateTime'] | null),updatedAt?: (Scalars['DateTime'] | null),name: Scalars['String']} export interface ProductCreateLocalizationInput { /** Localization input */ data: ProductCreateLocalizationDataInput,locale: Locale} export interface ProductCreateLocalizationsInput { /** Create localizations for the newly-created document */ create?: (ProductCreateLocalizationInput[] | null)} export interface ProductCreateManyInlineInput { /** Create and connect multiple existing Product documents */ create?: (ProductCreateInput[] | null), /** Connect multiple existing Product documents */ connect?: (ProductWhereUniqueInput[] | null)} export interface ProductCreateOneInlineInput { /** Create and connect one Product document */ create?: (ProductCreateInput | null), /** Connect one existing Product document */ connect?: (ProductWhereUniqueInput | null)} /** An edge in a connection. */ export interface ProductEdgeRequest{ /** The item at the end of the edge. */ node?: ProductRequest /** A cursor for use in pagination. */ cursor?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Identifies documents */ export interface ProductManyWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (ProductWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (ProductWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (ProductWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),createdBy?: (UserWhereInput | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),updatedBy?: (UserWhereInput | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),publishedBy?: (UserWhereInput | null),slug?: (Scalars['String'] | null), /** All values that are not equal to given value. */ slug_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ slug_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ slug_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ slug_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ slug_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ slug_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ slug_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ slug_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ slug_not_ends_with?: (Scalars['String'] | null),description?: (Scalars['String'] | null), /** All values that are not equal to given value. */ description_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ description_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ description_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ description_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ description_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ description_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ description_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ description_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ description_not_ends_with?: (Scalars['String'] | null),price?: (Scalars['Int'] | null), /** All values that are not equal to given value. */ price_not?: (Scalars['Int'] | null), /** All values that are contained in given list. */ price_in?: (Scalars['Int'][] | null), /** All values that are not contained in given list. */ price_not_in?: (Scalars['Int'][] | null), /** All values less than the given value. */ price_lt?: (Scalars['Int'] | null), /** All values less than or equal the given value. */ price_lte?: (Scalars['Int'] | null), /** All values greater than the given value. */ price_gt?: (Scalars['Int'] | null), /** All values greater than or equal the given value. */ price_gte?: (Scalars['Int'] | null),reviews_every?: (ReviewWhereInput | null),reviews_some?: (ReviewWhereInput | null),reviews_none?: (ReviewWhereInput | null),votes_every?: (VoteWhereInput | null),votes_some?: (VoteWhereInput | null),votes_none?: (VoteWhereInput | null),image?: (AssetWhereInput | null)} export interface ProductUpdateInput { /** name input for default locale (en) */ name?: (Scalars['String'] | null),slug?: (Scalars['String'] | null),description?: (Scalars['String'] | null),price?: (Scalars['Int'] | null),reviews?: (ReviewUpdateManyInlineInput | null),votes?: (VoteUpdateManyInlineInput | null),image?: (AssetUpdateOneInlineInput | null),content?: (Scalars['RichTextAST'] | null), /** Manage document localizations */ localizations?: (ProductUpdateLocalizationsInput | null)} export interface ProductUpdateLocalizationDataInput {name?: (Scalars['String'] | null)} export interface ProductUpdateLocalizationInput {data: ProductUpdateLocalizationDataInput,locale: Locale} export interface ProductUpdateLocalizationsInput { /** Localizations to create */ create?: (ProductCreateLocalizationInput[] | null), /** Localizations to update */ update?: (ProductUpdateLocalizationInput[] | null),upsert?: (ProductUpsertLocalizationInput[] | null), /** Localizations to delete */ delete?: (Locale[] | null)} export interface ProductUpdateManyInlineInput { /** Create and connect multiple Product documents */ create?: (ProductCreateInput[] | null), /** Connect multiple existing Product documents */ connect?: (ProductConnectInput[] | null), /** Override currently-connected documents with multiple existing Product documents */ set?: (ProductWhereUniqueInput[] | null), /** Update multiple Product documents */ update?: (ProductUpdateWithNestedWhereUniqueInput[] | null), /** Upsert multiple Product documents */ upsert?: (ProductUpsertWithNestedWhereUniqueInput[] | null), /** Disconnect multiple Product documents */ disconnect?: (ProductWhereUniqueInput[] | null), /** Delete multiple Product documents */ delete?: (ProductWhereUniqueInput[] | null)} export interface ProductUpdateManyInput { /** name input for default locale (en) */ name?: (Scalars['String'] | null),description?: (Scalars['String'] | null),price?: (Scalars['Int'] | null),content?: (Scalars['RichTextAST'] | null), /** Optional updates to localizations */ localizations?: (ProductUpdateManyLocalizationsInput | null)} export interface ProductUpdateManyLocalizationDataInput {name?: (Scalars['String'] | null)} export interface ProductUpdateManyLocalizationInput {data: ProductUpdateManyLocalizationDataInput,locale: Locale} export interface ProductUpdateManyLocalizationsInput { /** Localizations to update */ update?: (ProductUpdateManyLocalizationInput[] | null)} export interface ProductUpdateManyWithNestedWhereInput { /** Document search */ where: ProductWhereInput, /** Update many input */ data: ProductUpdateManyInput} export interface ProductUpdateOneInlineInput { /** Create and connect one Product document */ create?: (ProductCreateInput | null), /** Update single Product document */ update?: (ProductUpdateWithNestedWhereUniqueInput | null), /** Upsert single Product document */ upsert?: (ProductUpsertWithNestedWhereUniqueInput | null), /** Connect existing Product document */ connect?: (ProductWhereUniqueInput | null), /** Disconnect currently connected Product document */ disconnect?: (Scalars['Boolean'] | null), /** Delete currently connected Product document */ delete?: (Scalars['Boolean'] | null)} export interface ProductUpdateWithNestedWhereUniqueInput { /** Unique document search */ where: ProductWhereUniqueInput, /** Document to update */ data: ProductUpdateInput} export interface ProductUpsertInput { /** Create document if it didn't exist */ create: ProductCreateInput, /** Update document if it exists */ update: ProductUpdateInput} export interface ProductUpsertLocalizationInput {update: ProductUpdateLocalizationDataInput,create: ProductCreateLocalizationDataInput,locale: Locale} export interface ProductUpsertWithNestedWhereUniqueInput { /** Unique document search */ where: ProductWhereUniqueInput, /** Upsert data */ data: ProductUpsertInput} /** Identifies documents */ export interface ProductWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (ProductWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (ProductWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (ProductWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),createdBy?: (UserWhereInput | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),updatedBy?: (UserWhereInput | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),publishedBy?: (UserWhereInput | null),name?: (Scalars['String'] | null), /** All values that are not equal to given value. */ name_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ name_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ name_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ name_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ name_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ name_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ name_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ name_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ name_not_ends_with?: (Scalars['String'] | null),slug?: (Scalars['String'] | null), /** All values that are not equal to given value. */ slug_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ slug_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ slug_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ slug_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ slug_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ slug_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ slug_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ slug_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ slug_not_ends_with?: (Scalars['String'] | null),description?: (Scalars['String'] | null), /** All values that are not equal to given value. */ description_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ description_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ description_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ description_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ description_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ description_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ description_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ description_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ description_not_ends_with?: (Scalars['String'] | null),price?: (Scalars['Int'] | null), /** All values that are not equal to given value. */ price_not?: (Scalars['Int'] | null), /** All values that are contained in given list. */ price_in?: (Scalars['Int'][] | null), /** All values that are not contained in given list. */ price_not_in?: (Scalars['Int'][] | null), /** All values less than the given value. */ price_lt?: (Scalars['Int'] | null), /** All values less than or equal the given value. */ price_lte?: (Scalars['Int'] | null), /** All values greater than the given value. */ price_gt?: (Scalars['Int'] | null), /** All values greater than or equal the given value. */ price_gte?: (Scalars['Int'] | null),reviews_every?: (ReviewWhereInput | null),reviews_some?: (ReviewWhereInput | null),reviews_none?: (ReviewWhereInput | null),votes_every?: (VoteWhereInput | null),votes_some?: (VoteWhereInput | null),votes_none?: (VoteWhereInput | null),image?: (AssetWhereInput | null)} /** References Product record uniquely */ export interface ProductWhereUniqueInput {id?: (Scalars['ID'] | null),slug?: (Scalars['String'] | null)} export interface PublishLocaleInput { /** Locales to publish */ locale: Locale, /** Stages to publish selected locales to */ stages: Stage[]} export interface QueryRequest{ /** Fetches an object given its ID */ node?: [{ /** The ID of an object */ id: Scalars['ID'],stage: Stage, /** * Defines which locales should be returned. * * Note that `Node` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},NodeRequest] /** Retrieve multiple assets */ assets?: [{where?: (AssetWhereInput | null),orderBy?: (AssetOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},AssetRequest] /** Retrieve a single asset */ asset?: [{where: AssetWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},AssetRequest] /** Retrieve multiple assets using the Relay connection interface */ assetsConnection?: [{where?: (AssetWhereInput | null),orderBy?: (AssetOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},AssetConnectionRequest] /** Retrieve document version */ assetVersion?: [{where: VersionWhereInput},DocumentVersionRequest] /** Retrieve multiple products */ products?: [{where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},ProductRequest] /** Retrieve a single product */ product?: [{where: ProductWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},ProductRequest] /** Retrieve multiple products using the Relay connection interface */ productsConnection?: [{where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},ProductConnectionRequest] /** Retrieve document version */ productVersion?: [{where: VersionWhereInput},DocumentVersionRequest] /** Retrieve multiple reviews */ reviews?: [{where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},ReviewRequest] /** Retrieve a single review */ review?: [{where: ReviewWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},ReviewRequest] /** Retrieve multiple reviews using the Relay connection interface */ reviewsConnection?: [{where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},ReviewConnectionRequest] /** Retrieve document version */ reviewVersion?: [{where: VersionWhereInput},DocumentVersionRequest] /** Retrieve multiple users */ users?: [{where?: (UserWhereInput | null),orderBy?: (UserOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},UserRequest] /** Retrieve a single user */ user?: [{where: UserWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},UserRequest] /** Retrieve multiple users using the Relay connection interface */ usersConnection?: [{where?: (UserWhereInput | null),orderBy?: (UserOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},UserConnectionRequest] /** Retrieve multiple votes */ votes?: [{where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},VoteRequest] /** Retrieve a single vote */ vote?: [{where: VoteWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},VoteRequest] /** Retrieve multiple votes using the Relay connection interface */ votesConnection?: [{where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]},VoteConnectionRequest] /** Retrieve document version */ voteVersion?: [{where: VersionWhereInput},DocumentVersionRequest] __typename?: boolean | number __scalar?: boolean | number } /** Representing a RGBA color value: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb()_and_rgba() */ export interface RGBARequest{ r?: boolean | number g?: boolean | number b?: boolean | number a?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Input type representing a RGBA color value: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb()_and_rgba() */ export interface RGBAInput {r: Scalars['RGBAHue'],g: Scalars['RGBAHue'],b: Scalars['RGBAHue'],a: Scalars['RGBATransparency']} export interface ReviewRequest{ /** System stage field */ stage?: boolean | number /** Get the document in other stages */ documentInStages?: [{ /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']},ReviewRequest] /** The unique identifier */ id?: boolean | number /** The time the document was created */ createdAt?: boolean | number /** User that created this document */ createdBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The time the document was updated */ updatedAt?: boolean | number /** User that last updated this document */ updatedBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The time the document was published. Null on documents in draft stage. */ publishedAt?: boolean | number /** User that last published this document */ publishedBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest name?: boolean | number comment?: boolean | number product?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `product` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},ProductRequest] | ProductRequest /** List of Review versions */ history?: [{limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)},VersionRequest] __typename?: boolean | number __scalar?: boolean | number } export interface ReviewConnectInput { /** Document to connect */ where: ReviewWhereUniqueInput, /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: (ConnectPositionInput | null)} /** A connection to a list of items. */ export interface ReviewConnectionRequest{ /** Information to aid in pagination. */ pageInfo?: PageInfoRequest /** A list of edges. */ edges?: ReviewEdgeRequest aggregate?: AggregateRequest __typename?: boolean | number __scalar?: boolean | number } export interface ReviewCreateInput {createdAt?: (Scalars['DateTime'] | null),updatedAt?: (Scalars['DateTime'] | null),name?: (Scalars['String'] | null),comment: Scalars['String'],product?: (ProductCreateOneInlineInput | null)} export interface ReviewCreateManyInlineInput { /** Create and connect multiple existing Review documents */ create?: (ReviewCreateInput[] | null), /** Connect multiple existing Review documents */ connect?: (ReviewWhereUniqueInput[] | null)} export interface ReviewCreateOneInlineInput { /** Create and connect one Review document */ create?: (ReviewCreateInput | null), /** Connect one existing Review document */ connect?: (ReviewWhereUniqueInput | null)} /** An edge in a connection. */ export interface ReviewEdgeRequest{ /** The item at the end of the edge. */ node?: ReviewRequest /** A cursor for use in pagination. */ cursor?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Identifies documents */ export interface ReviewManyWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (ReviewWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (ReviewWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (ReviewWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),createdBy?: (UserWhereInput | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),updatedBy?: (UserWhereInput | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),publishedBy?: (UserWhereInput | null),name?: (Scalars['String'] | null), /** All values that are not equal to given value. */ name_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ name_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ name_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ name_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ name_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ name_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ name_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ name_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ name_not_ends_with?: (Scalars['String'] | null),comment?: (Scalars['String'] | null), /** All values that are not equal to given value. */ comment_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ comment_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ comment_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ comment_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ comment_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ comment_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ comment_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ comment_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ comment_not_ends_with?: (Scalars['String'] | null),product?: (ProductWhereInput | null)} export interface ReviewUpdateInput {name?: (Scalars['String'] | null),comment?: (Scalars['String'] | null),product?: (ProductUpdateOneInlineInput | null)} export interface ReviewUpdateManyInlineInput { /** Create and connect multiple Review documents */ create?: (ReviewCreateInput[] | null), /** Connect multiple existing Review documents */ connect?: (ReviewConnectInput[] | null), /** Override currently-connected documents with multiple existing Review documents */ set?: (ReviewWhereUniqueInput[] | null), /** Update multiple Review documents */ update?: (ReviewUpdateWithNestedWhereUniqueInput[] | null), /** Upsert multiple Review documents */ upsert?: (ReviewUpsertWithNestedWhereUniqueInput[] | null), /** Disconnect multiple Review documents */ disconnect?: (ReviewWhereUniqueInput[] | null), /** Delete multiple Review documents */ delete?: (ReviewWhereUniqueInput[] | null)} export interface ReviewUpdateManyInput {name?: (Scalars['String'] | null),comment?: (Scalars['String'] | null)} export interface ReviewUpdateManyWithNestedWhereInput { /** Document search */ where: ReviewWhereInput, /** Update many input */ data: ReviewUpdateManyInput} export interface ReviewUpdateOneInlineInput { /** Create and connect one Review document */ create?: (ReviewCreateInput | null), /** Update single Review document */ update?: (ReviewUpdateWithNestedWhereUniqueInput | null), /** Upsert single Review document */ upsert?: (ReviewUpsertWithNestedWhereUniqueInput | null), /** Connect existing Review document */ connect?: (ReviewWhereUniqueInput | null), /** Disconnect currently connected Review document */ disconnect?: (Scalars['Boolean'] | null), /** Delete currently connected Review document */ delete?: (Scalars['Boolean'] | null)} export interface ReviewUpdateWithNestedWhereUniqueInput { /** Unique document search */ where: ReviewWhereUniqueInput, /** Document to update */ data: ReviewUpdateInput} export interface ReviewUpsertInput { /** Create document if it didn't exist */ create: ReviewCreateInput, /** Update document if it exists */ update: ReviewUpdateInput} export interface ReviewUpsertWithNestedWhereUniqueInput { /** Unique document search */ where: ReviewWhereUniqueInput, /** Upsert data */ data: ReviewUpsertInput} /** Identifies documents */ export interface ReviewWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (ReviewWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (ReviewWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (ReviewWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),createdBy?: (UserWhereInput | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),updatedBy?: (UserWhereInput | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),publishedBy?: (UserWhereInput | null),name?: (Scalars['String'] | null), /** All values that are not equal to given value. */ name_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ name_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ name_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ name_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ name_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ name_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ name_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ name_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ name_not_ends_with?: (Scalars['String'] | null),comment?: (Scalars['String'] | null), /** All values that are not equal to given value. */ comment_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ comment_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ comment_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ comment_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ comment_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ comment_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ comment_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ comment_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ comment_not_ends_with?: (Scalars['String'] | null),product?: (ProductWhereInput | null)} /** References Review record uniquely */ export interface ReviewWhereUniqueInput {id?: (Scalars['ID'] | null)} /** Custom type representing a rich text value comprising of raw rich text ast, html, markdown and text values */ export interface RichTextRequest{ /** Returns AST representation */ raw?: boolean | number /** Returns HTMl representation */ html?: boolean | number /** Returns Markdown representation */ markdown?: boolean | number /** Returns plain-text contents of RichText */ text?: boolean | number __typename?: boolean | number __scalar?: boolean | number } export interface UnpublishLocaleInput { /** Locales to unpublish */ locale: Locale, /** Stages to unpublish selected locales from */ stages: Stage[]} /** User system model */ export interface UserRequest{ /** System stage field */ stage?: boolean | number /** Get the document in other stages */ documentInStages?: [{ /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']},UserRequest] /** The unique identifier */ id?: boolean | number /** The time the document was created */ createdAt?: boolean | number /** The time the document was updated */ updatedAt?: boolean | number /** The time the document was published. Null on documents in draft stage. */ publishedAt?: boolean | number /** The username */ name?: boolean | number /** Profile Picture url */ picture?: boolean | number /** User Kind. Can be either MEMBER, PAT or PUBLIC */ kind?: boolean | number /** Flag to determine if user is active or not */ isActive?: boolean | number __typename?: boolean | number __scalar?: boolean | number } export interface UserConnectInput { /** Document to connect */ where: UserWhereUniqueInput, /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: (ConnectPositionInput | null)} /** A connection to a list of items. */ export interface UserConnectionRequest{ /** Information to aid in pagination. */ pageInfo?: PageInfoRequest /** A list of edges. */ edges?: UserEdgeRequest aggregate?: AggregateRequest __typename?: boolean | number __scalar?: boolean | number } export interface UserCreateManyInlineInput { /** Connect multiple existing User documents */ connect?: (UserWhereUniqueInput[] | null)} export interface UserCreateOneInlineInput { /** Connect one existing User document */ connect?: (UserWhereUniqueInput | null)} /** An edge in a connection. */ export interface UserEdgeRequest{ /** The item at the end of the edge. */ node?: UserRequest /** A cursor for use in pagination. */ cursor?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Identifies documents */ export interface UserManyWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (UserWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (UserWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (UserWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),name?: (Scalars['String'] | null), /** All values that are not equal to given value. */ name_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ name_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ name_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ name_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ name_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ name_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ name_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ name_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ name_not_ends_with?: (Scalars['String'] | null),picture?: (Scalars['String'] | null), /** All values that are not equal to given value. */ picture_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ picture_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ picture_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ picture_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ picture_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ picture_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ picture_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ picture_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ picture_not_ends_with?: (Scalars['String'] | null),kind?: (UserKind | null), /** All values that are not equal to given value. */ kind_not?: (UserKind | null), /** All values that are contained in given list. */ kind_in?: (UserKind[] | null), /** All values that are not contained in given list. */ kind_not_in?: (UserKind[] | null),isActive?: (Scalars['Boolean'] | null), /** All values that are not equal to given value. */ isActive_not?: (Scalars['Boolean'] | null)} export interface UserUpdateManyInlineInput { /** Connect multiple existing User documents */ connect?: (UserConnectInput[] | null), /** Override currently-connected documents with multiple existing User documents */ set?: (UserWhereUniqueInput[] | null), /** Disconnect multiple User documents */ disconnect?: (UserWhereUniqueInput[] | null)} export interface UserUpdateOneInlineInput { /** Connect existing User document */ connect?: (UserWhereUniqueInput | null), /** Disconnect currently connected User document */ disconnect?: (Scalars['Boolean'] | null)} /** Identifies documents */ export interface UserWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (UserWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (UserWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (UserWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),name?: (Scalars['String'] | null), /** All values that are not equal to given value. */ name_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ name_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ name_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ name_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ name_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ name_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ name_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ name_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ name_not_ends_with?: (Scalars['String'] | null),picture?: (Scalars['String'] | null), /** All values that are not equal to given value. */ picture_not?: (Scalars['String'] | null), /** All values that are contained in given list. */ picture_in?: (Scalars['String'][] | null), /** All values that are not contained in given list. */ picture_not_in?: (Scalars['String'][] | null), /** All values containing the given string. */ picture_contains?: (Scalars['String'] | null), /** All values not containing the given string. */ picture_not_contains?: (Scalars['String'] | null), /** All values starting with the given string. */ picture_starts_with?: (Scalars['String'] | null), /** All values not starting with the given string. */ picture_not_starts_with?: (Scalars['String'] | null), /** All values ending with the given string. */ picture_ends_with?: (Scalars['String'] | null), /** All values not ending with the given string */ picture_not_ends_with?: (Scalars['String'] | null),kind?: (UserKind | null), /** All values that are not equal to given value. */ kind_not?: (UserKind | null), /** All values that are contained in given list. */ kind_in?: (UserKind[] | null), /** All values that are not contained in given list. */ kind_not_in?: (UserKind[] | null),isActive?: (Scalars['Boolean'] | null), /** All values that are not equal to given value. */ isActive_not?: (Scalars['Boolean'] | null)} /** References User record uniquely */ export interface UserWhereUniqueInput {id?: (Scalars['ID'] | null)} export interface VersionRequest{ id?: boolean | number stage?: boolean | number revision?: boolean | number createdAt?: boolean | number __typename?: boolean | number __scalar?: boolean | number } export interface VersionWhereInput {id: Scalars['ID'],stage: Stage,revision: Scalars['Int']} export interface VoteRequest{ /** System stage field */ stage?: boolean | number /** Get the document in other stages */ documentInStages?: [{ /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']},VoteRequest] /** The unique identifier */ id?: boolean | number /** The time the document was created */ createdAt?: boolean | number /** User that created this document */ createdBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The time the document was updated */ updatedAt?: boolean | number /** User that last updated this document */ updatedBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest /** The time the document was published. Null on documents in draft stage. */ publishedAt?: boolean | number /** User that last published this document */ publishedBy?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},UserRequest] | UserRequest product?: [{ /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `product` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)},ProductRequest] | ProductRequest /** List of Vote versions */ history?: [{limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)},VersionRequest] __typename?: boolean | number __scalar?: boolean | number } export interface VoteConnectInput { /** Document to connect */ where: VoteWhereUniqueInput, /** Allow to specify document position in list of connected documents, will default to appending at end of list */ position?: (ConnectPositionInput | null)} /** A connection to a list of items. */ export interface VoteConnectionRequest{ /** Information to aid in pagination. */ pageInfo?: PageInfoRequest /** A list of edges. */ edges?: VoteEdgeRequest aggregate?: AggregateRequest __typename?: boolean | number __scalar?: boolean | number } export interface VoteCreateInput {createdAt?: (Scalars['DateTime'] | null),updatedAt?: (Scalars['DateTime'] | null),product?: (ProductCreateOneInlineInput | null)} export interface VoteCreateManyInlineInput { /** Create and connect multiple existing Vote documents */ create?: (VoteCreateInput[] | null), /** Connect multiple existing Vote documents */ connect?: (VoteWhereUniqueInput[] | null)} export interface VoteCreateOneInlineInput { /** Create and connect one Vote document */ create?: (VoteCreateInput | null), /** Connect one existing Vote document */ connect?: (VoteWhereUniqueInput | null)} /** An edge in a connection. */ export interface VoteEdgeRequest{ /** The item at the end of the edge. */ node?: VoteRequest /** A cursor for use in pagination. */ cursor?: boolean | number __typename?: boolean | number __scalar?: boolean | number } /** Identifies documents */ export interface VoteManyWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (VoteWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (VoteWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (VoteWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),createdBy?: (UserWhereInput | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),updatedBy?: (UserWhereInput | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),publishedBy?: (UserWhereInput | null),product?: (ProductWhereInput | null)} export interface VoteUpdateInput {product?: (ProductUpdateOneInlineInput | null)} export interface VoteUpdateManyInlineInput { /** Create and connect multiple Vote documents */ create?: (VoteCreateInput[] | null), /** Connect multiple existing Vote documents */ connect?: (VoteConnectInput[] | null), /** Override currently-connected documents with multiple existing Vote documents */ set?: (VoteWhereUniqueInput[] | null), /** Update multiple Vote documents */ update?: (VoteUpdateWithNestedWhereUniqueInput[] | null), /** Upsert multiple Vote documents */ upsert?: (VoteUpsertWithNestedWhereUniqueInput[] | null), /** Disconnect multiple Vote documents */ disconnect?: (VoteWhereUniqueInput[] | null), /** Delete multiple Vote documents */ delete?: (VoteWhereUniqueInput[] | null)} export interface VoteUpdateManyInput { /** No fields in updateMany data input */ _?: (Scalars['String'] | null)} export interface VoteUpdateManyWithNestedWhereInput { /** Document search */ where: VoteWhereInput, /** Update many input */ data: VoteUpdateManyInput} export interface VoteUpdateOneInlineInput { /** Create and connect one Vote document */ create?: (VoteCreateInput | null), /** Update single Vote document */ update?: (VoteUpdateWithNestedWhereUniqueInput | null), /** Upsert single Vote document */ upsert?: (VoteUpsertWithNestedWhereUniqueInput | null), /** Connect existing Vote document */ connect?: (VoteWhereUniqueInput | null), /** Disconnect currently connected Vote document */ disconnect?: (Scalars['Boolean'] | null), /** Delete currently connected Vote document */ delete?: (Scalars['Boolean'] | null)} export interface VoteUpdateWithNestedWhereUniqueInput { /** Unique document search */ where: VoteWhereUniqueInput, /** Document to update */ data: VoteUpdateInput} export interface VoteUpsertInput { /** Create document if it didn't exist */ create: VoteCreateInput, /** Update document if it exists */ update: VoteUpdateInput} export interface VoteUpsertWithNestedWhereUniqueInput { /** Unique document search */ where: VoteWhereUniqueInput, /** Upsert data */ data: VoteUpsertInput} /** Identifies documents */ export interface VoteWhereInput { /** Contains search across all appropriate fields. */ _search?: (Scalars['String'] | null), /** Logical AND on all given filters. */ AND?: (VoteWhereInput[] | null), /** Logical OR on all given filters. */ OR?: (VoteWhereInput[] | null), /** Logical NOT on all given filters combined by AND. */ NOT?: (VoteWhereInput[] | null),id?: (Scalars['ID'] | null), /** All values that are not equal to given value. */ id_not?: (Scalars['ID'] | null), /** All values that are contained in given list. */ id_in?: (Scalars['ID'][] | null), /** All values that are not contained in given list. */ id_not_in?: (Scalars['ID'][] | null), /** All values containing the given string. */ id_contains?: (Scalars['ID'] | null), /** All values not containing the given string. */ id_not_contains?: (Scalars['ID'] | null), /** All values starting with the given string. */ id_starts_with?: (Scalars['ID'] | null), /** All values not starting with the given string. */ id_not_starts_with?: (Scalars['ID'] | null), /** All values ending with the given string. */ id_ends_with?: (Scalars['ID'] | null), /** All values not ending with the given string */ id_not_ends_with?: (Scalars['ID'] | null),createdAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ createdAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ createdAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ createdAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ createdAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ createdAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ createdAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ createdAt_gte?: (Scalars['DateTime'] | null),createdBy?: (UserWhereInput | null),updatedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ updatedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ updatedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ updatedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ updatedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ updatedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ updatedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ updatedAt_gte?: (Scalars['DateTime'] | null),updatedBy?: (UserWhereInput | null),publishedAt?: (Scalars['DateTime'] | null), /** All values that are not equal to given value. */ publishedAt_not?: (Scalars['DateTime'] | null), /** All values that are contained in given list. */ publishedAt_in?: (Scalars['DateTime'][] | null), /** All values that are not contained in given list. */ publishedAt_not_in?: (Scalars['DateTime'][] | null), /** All values less than the given value. */ publishedAt_lt?: (Scalars['DateTime'] | null), /** All values less than or equal the given value. */ publishedAt_lte?: (Scalars['DateTime'] | null), /** All values greater than the given value. */ publishedAt_gt?: (Scalars['DateTime'] | null), /** All values greater than or equal the given value. */ publishedAt_gte?: (Scalars['DateTime'] | null),publishedBy?: (UserWhereInput | null),product?: (ProductWhereInput | null)} /** References Vote record uniquely */ export interface VoteWhereUniqueInput {id?: (Scalars['ID'] | null)} const Aggregate_possibleTypes = ['Aggregate'] export const isAggregate = (obj?: { __typename?: any } | null): obj is Aggregate => { if (!obj?.__typename) throw new Error('__typename is missing in "isAggregate"') return Aggregate_possibleTypes.includes(obj.__typename) } const Asset_possibleTypes = ['Asset'] export const isAsset = (obj?: { __typename?: any } | null): obj is Asset => { if (!obj?.__typename) throw new Error('__typename is missing in "isAsset"') return Asset_possibleTypes.includes(obj.__typename) } const AssetConnection_possibleTypes = ['AssetConnection'] export const isAssetConnection = (obj?: { __typename?: any } | null): obj is AssetConnection => { if (!obj?.__typename) throw new Error('__typename is missing in "isAssetConnection"') return AssetConnection_possibleTypes.includes(obj.__typename) } const AssetEdge_possibleTypes = ['AssetEdge'] export const isAssetEdge = (obj?: { __typename?: any } | null): obj is AssetEdge => { if (!obj?.__typename) throw new Error('__typename is missing in "isAssetEdge"') return AssetEdge_possibleTypes.includes(obj.__typename) } const BatchPayload_possibleTypes = ['BatchPayload'] export const isBatchPayload = (obj?: { __typename?: any } | null): obj is BatchPayload => { if (!obj?.__typename) throw new Error('__typename is missing in "isBatchPayload"') return BatchPayload_possibleTypes.includes(obj.__typename) } const Color_possibleTypes = ['Color'] export const isColor = (obj?: { __typename?: any } | null): obj is Color => { if (!obj?.__typename) throw new Error('__typename is missing in "isColor"') return Color_possibleTypes.includes(obj.__typename) } const DocumentVersion_possibleTypes = ['DocumentVersion'] export const isDocumentVersion = (obj?: { __typename?: any } | null): obj is DocumentVersion => { if (!obj?.__typename) throw new Error('__typename is missing in "isDocumentVersion"') return DocumentVersion_possibleTypes.includes(obj.__typename) } const Location_possibleTypes = ['Location'] export const isLocation = (obj?: { __typename?: any } | null): obj is Location => { if (!obj?.__typename) throw new Error('__typename is missing in "isLocation"') return Location_possibleTypes.includes(obj.__typename) } const Mutation_possibleTypes = ['Mutation'] export const isMutation = (obj?: { __typename?: any } | null): obj is Mutation => { if (!obj?.__typename) throw new Error('__typename is missing in "isMutation"') return Mutation_possibleTypes.includes(obj.__typename) } const Node_possibleTypes = ['Asset','Product','Review','User','Vote'] export const isNode = (obj?: { __typename?: any } | null): obj is Node => { if (!obj?.__typename) throw new Error('__typename is missing in "isNode"') return Node_possibleTypes.includes(obj.__typename) } const PageInfo_possibleTypes = ['PageInfo'] export const isPageInfo = (obj?: { __typename?: any } | null): obj is PageInfo => { if (!obj?.__typename) throw new Error('__typename is missing in "isPageInfo"') return PageInfo_possibleTypes.includes(obj.__typename) } const Product_possibleTypes = ['Product'] export const isProduct = (obj?: { __typename?: any } | null): obj is Product => { if (!obj?.__typename) throw new Error('__typename is missing in "isProduct"') return Product_possibleTypes.includes(obj.__typename) } const ProductConnection_possibleTypes = ['ProductConnection'] export const isProductConnection = (obj?: { __typename?: any } | null): obj is ProductConnection => { if (!obj?.__typename) throw new Error('__typename is missing in "isProductConnection"') return ProductConnection_possibleTypes.includes(obj.__typename) } const ProductEdge_possibleTypes = ['ProductEdge'] export const isProductEdge = (obj?: { __typename?: any } | null): obj is ProductEdge => { if (!obj?.__typename) throw new Error('__typename is missing in "isProductEdge"') return ProductEdge_possibleTypes.includes(obj.__typename) } const Query_possibleTypes = ['Query'] export const isQuery = (obj?: { __typename?: any } | null): obj is Query => { if (!obj?.__typename) throw new Error('__typename is missing in "isQuery"') return Query_possibleTypes.includes(obj.__typename) } const RGBA_possibleTypes = ['RGBA'] export const isRGBA = (obj?: { __typename?: any } | null): obj is RGBA => { if (!obj?.__typename) throw new Error('__typename is missing in "isRGBA"') return RGBA_possibleTypes.includes(obj.__typename) } const Review_possibleTypes = ['Review'] export const isReview = (obj?: { __typename?: any } | null): obj is Review => { if (!obj?.__typename) throw new Error('__typename is missing in "isReview"') return Review_possibleTypes.includes(obj.__typename) } const ReviewConnection_possibleTypes = ['ReviewConnection'] export const isReviewConnection = (obj?: { __typename?: any } | null): obj is ReviewConnection => { if (!obj?.__typename) throw new Error('__typename is missing in "isReviewConnection"') return ReviewConnection_possibleTypes.includes(obj.__typename) } const ReviewEdge_possibleTypes = ['ReviewEdge'] export const isReviewEdge = (obj?: { __typename?: any } | null): obj is ReviewEdge => { if (!obj?.__typename) throw new Error('__typename is missing in "isReviewEdge"') return ReviewEdge_possibleTypes.includes(obj.__typename) } const RichText_possibleTypes = ['RichText'] export const isRichText = (obj?: { __typename?: any } | null): obj is RichText => { if (!obj?.__typename) throw new Error('__typename is missing in "isRichText"') return RichText_possibleTypes.includes(obj.__typename) } const User_possibleTypes = ['User'] export const isUser = (obj?: { __typename?: any } | null): obj is User => { if (!obj?.__typename) throw new Error('__typename is missing in "isUser"') return User_possibleTypes.includes(obj.__typename) } const UserConnection_possibleTypes = ['UserConnection'] export const isUserConnection = (obj?: { __typename?: any } | null): obj is UserConnection => { if (!obj?.__typename) throw new Error('__typename is missing in "isUserConnection"') return UserConnection_possibleTypes.includes(obj.__typename) } const UserEdge_possibleTypes = ['UserEdge'] export const isUserEdge = (obj?: { __typename?: any } | null): obj is UserEdge => { if (!obj?.__typename) throw new Error('__typename is missing in "isUserEdge"') return UserEdge_possibleTypes.includes(obj.__typename) } const Version_possibleTypes = ['Version'] export const isVersion = (obj?: { __typename?: any } | null): obj is Version => { if (!obj?.__typename) throw new Error('__typename is missing in "isVersion"') return Version_possibleTypes.includes(obj.__typename) } const Vote_possibleTypes = ['Vote'] export const isVote = (obj?: { __typename?: any } | null): obj is Vote => { if (!obj?.__typename) throw new Error('__typename is missing in "isVote"') return Vote_possibleTypes.includes(obj.__typename) } const VoteConnection_possibleTypes = ['VoteConnection'] export const isVoteConnection = (obj?: { __typename?: any } | null): obj is VoteConnection => { if (!obj?.__typename) throw new Error('__typename is missing in "isVoteConnection"') return VoteConnection_possibleTypes.includes(obj.__typename) } const VoteEdge_possibleTypes = ['VoteEdge'] export const isVoteEdge = (obj?: { __typename?: any } | null): obj is VoteEdge => { if (!obj?.__typename) throw new Error('__typename is missing in "isVoteEdge"') return VoteEdge_possibleTypes.includes(obj.__typename) } export interface AggregatePromiseChain{ count: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Promise<Scalars['Int']>}) } export interface AggregateObservableChain{ count: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Observable<Scalars['Int']>}) } /** Asset system model */ export interface AssetPromiseChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Promise<Stage>}), /** System Locale field */ locale: ({get: (request?: boolean|number, defaultValue?: Locale) => Promise<Locale>}), /** Get the other localizations for this document */ localizations: ((args: { /** Potential locales that should be returned */ locales: Locale[], /** Decides if the current locale should be included or not */ includeCurrent: Scalars['Boolean']}) => {get: <R extends AssetRequest>(request: R, defaultValue?: FieldsSelection<Asset, R>[]) => Promise<FieldsSelection<Asset, R>[]>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends AssetRequest>(request: R, defaultValue?: FieldsSelection<Asset, R>[]) => Promise<FieldsSelection<Asset, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Promise<Scalars['ID']>}), /** The time the document was created */ createdAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** User that created this document */ createdBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The time the document was updated */ updatedAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** User that last updated this document */ updatedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Promise<(Scalars['DateTime'] | undefined)>}), /** User that last published this document */ publishedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The file handle */ handle: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}), /** The file name */ fileName: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}), /** The height of the file */ height: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>}), /** The file width */ width: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>}), /** The file size */ size: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Promise<(Scalars['Float'] | undefined)>}), /** The mime type of the file */ mimeType: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>}), productImage: ((args?: {where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `productImage` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Promise<FieldsSelection<Product, R>[]>})&({get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Promise<FieldsSelection<Product, R>[]>}), /** List of Asset versions */ history: ((args: {limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)}) => {get: <R extends VersionRequest>(request: R, defaultValue?: FieldsSelection<Version, R>[]) => Promise<FieldsSelection<Version, R>[]>}), /** Get the url for the asset with provided transformations applied. */ url: ((args?: {transformation?: (AssetTransformationInput | null)}) => {get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>})&({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}) } /** Asset system model */ export interface AssetObservableChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Observable<Stage>}), /** System Locale field */ locale: ({get: (request?: boolean|number, defaultValue?: Locale) => Observable<Locale>}), /** Get the other localizations for this document */ localizations: ((args: { /** Potential locales that should be returned */ locales: Locale[], /** Decides if the current locale should be included or not */ includeCurrent: Scalars['Boolean']}) => {get: <R extends AssetRequest>(request: R, defaultValue?: FieldsSelection<Asset, R>[]) => Observable<FieldsSelection<Asset, R>[]>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends AssetRequest>(request: R, defaultValue?: FieldsSelection<Asset, R>[]) => Observable<FieldsSelection<Asset, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Observable<Scalars['ID']>}), /** The time the document was created */ createdAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** User that created this document */ createdBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The time the document was updated */ updatedAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** User that last updated this document */ updatedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Observable<(Scalars['DateTime'] | undefined)>}), /** User that last published this document */ publishedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The file handle */ handle: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}), /** The file name */ fileName: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}), /** The height of the file */ height: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>}), /** The file width */ width: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>}), /** The file size */ size: ({get: (request?: boolean|number, defaultValue?: (Scalars['Float'] | undefined)) => Observable<(Scalars['Float'] | undefined)>}), /** The mime type of the file */ mimeType: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>}), productImage: ((args?: {where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `productImage` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Observable<FieldsSelection<Product, R>[]>})&({get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Observable<FieldsSelection<Product, R>[]>}), /** List of Asset versions */ history: ((args: {limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)}) => {get: <R extends VersionRequest>(request: R, defaultValue?: FieldsSelection<Version, R>[]) => Observable<FieldsSelection<Version, R>[]>}), /** Get the url for the asset with provided transformations applied. */ url: ((args?: {transformation?: (AssetTransformationInput | null)}) => {get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>})&({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}) } /** A connection to a list of items. */ export interface AssetConnectionPromiseChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoPromiseChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Promise<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends AssetEdgeRequest>(request: R, defaultValue?: FieldsSelection<AssetEdge, R>[]) => Promise<FieldsSelection<AssetEdge, R>[]>}), aggregate: (AggregatePromiseChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Promise<FieldsSelection<Aggregate, R>>}) } /** A connection to a list of items. */ export interface AssetConnectionObservableChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoObservableChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Observable<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends AssetEdgeRequest>(request: R, defaultValue?: FieldsSelection<AssetEdge, R>[]) => Observable<FieldsSelection<AssetEdge, R>[]>}), aggregate: (AggregateObservableChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Observable<FieldsSelection<Aggregate, R>>}) } /** An edge in a connection. */ export interface AssetEdgePromiseChain{ /** The item at the end of the edge. */ node: (AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: FieldsSelection<Asset, R>) => Promise<FieldsSelection<Asset, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}) } /** An edge in a connection. */ export interface AssetEdgeObservableChain{ /** The item at the end of the edge. */ node: (AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: FieldsSelection<Asset, R>) => Observable<FieldsSelection<Asset, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}) } export interface BatchPayloadPromiseChain{ /** The number of nodes that have been affected by the Batch operation. */ count: ({get: (request?: boolean|number, defaultValue?: Scalars['Long']) => Promise<Scalars['Long']>}) } export interface BatchPayloadObservableChain{ /** The number of nodes that have been affected by the Batch operation. */ count: ({get: (request?: boolean|number, defaultValue?: Scalars['Long']) => Observable<Scalars['Long']>}) } /** Representing a color value comprising of HEX, RGBA and css color values */ export interface ColorPromiseChain{ hex: ({get: (request?: boolean|number, defaultValue?: Scalars['Hex']) => Promise<Scalars['Hex']>}), rgba: (RGBAPromiseChain & {get: <R extends RGBARequest>(request: R, defaultValue?: FieldsSelection<RGBA, R>) => Promise<FieldsSelection<RGBA, R>>}), css: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}) } /** Representing a color value comprising of HEX, RGBA and css color values */ export interface ColorObservableChain{ hex: ({get: (request?: boolean|number, defaultValue?: Scalars['Hex']) => Observable<Scalars['Hex']>}), rgba: (RGBAObservableChain & {get: <R extends RGBARequest>(request: R, defaultValue?: FieldsSelection<RGBA, R>) => Observable<FieldsSelection<RGBA, R>>}), css: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}) } export interface DocumentVersionPromiseChain{ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Promise<Scalars['ID']>}), stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Promise<Stage>}), revision: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Promise<Scalars['Int']>}), createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), data: ({get: (request?: boolean|number, defaultValue?: (Scalars['Json'] | undefined)) => Promise<(Scalars['Json'] | undefined)>}) } export interface DocumentVersionObservableChain{ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Observable<Scalars['ID']>}), stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Observable<Stage>}), revision: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Observable<Scalars['Int']>}), createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), data: ({get: (request?: boolean|number, defaultValue?: (Scalars['Json'] | undefined)) => Observable<(Scalars['Json'] | undefined)>}) } /** Representing a geolocation point with latitude and longitude */ export interface LocationPromiseChain{ latitude: ({get: (request?: boolean|number, defaultValue?: Scalars['Float']) => Promise<Scalars['Float']>}), longitude: ({get: (request?: boolean|number, defaultValue?: Scalars['Float']) => Promise<Scalars['Float']>}), distance: ((args: {from: LocationInput}) => {get: (request?: boolean|number, defaultValue?: Scalars['Float']) => Promise<Scalars['Float']>}) } /** Representing a geolocation point with latitude and longitude */ export interface LocationObservableChain{ latitude: ({get: (request?: boolean|number, defaultValue?: Scalars['Float']) => Observable<Scalars['Float']>}), longitude: ({get: (request?: boolean|number, defaultValue?: Scalars['Float']) => Observable<Scalars['Float']>}), distance: ((args: {from: LocationInput}) => {get: (request?: boolean|number, defaultValue?: Scalars['Float']) => Observable<Scalars['Float']>}) } export interface MutationPromiseChain{ /** * @deprecated Asset mutations will be overhauled soon * Create one asset */ createAsset: ((args: {data: AssetCreateInput}) => AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>}), /** Update one asset */ updateAsset: ((args: {where: AssetWhereUniqueInput,data: AssetUpdateInput}) => AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>}), /** Delete one asset from _all_ existing stages. Returns deleted document. */ deleteAsset: ((args: { /** Document to delete */ where: AssetWhereUniqueInput}) => AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>}), /** Upsert one asset */ upsertAsset: ((args: {where: AssetWhereUniqueInput,upsert: AssetUpsertInput}) => AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>}), /** Publish one asset */ publishAsset: ((args: { /** Document to publish */ where: AssetWhereUniqueInput, /** Optional localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is set */ withDefaultLocale?: (Scalars['Boolean'] | null), /** Publishing target stage */ to: Stage[]}) => AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>}), /** Unpublish one asset from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishAsset: ((args: { /** Document to unpublish */ where: AssetWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[], /** Optional locales to unpublish. Unpublishing the default locale will completely remove the document from the selected stages */ locales?: (Locale[] | null), /** Unpublish complete document including default localization and relations from stages. Can be disabled. */ unpublishBase?: (Scalars['Boolean'] | null)}) => AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>}), /** Update many Asset documents */ updateManyAssetsConnection: ((args: { /** Documents to apply update on */ where?: (AssetManyWhereInput | null), /** Updates to document content */ data: AssetUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => AssetConnectionPromiseChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Promise<FieldsSelection<AssetConnection, R>>}), /** Delete many Asset documents, return deleted documents */ deleteManyAssetsConnection: ((args?: { /** Documents to delete */ where?: (AssetManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => AssetConnectionPromiseChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Promise<FieldsSelection<AssetConnection, R>>})&(AssetConnectionPromiseChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Promise<FieldsSelection<AssetConnection, R>>}), /** Publish many Asset documents */ publishManyAssetsConnection: ((args: { /** Identifies documents in each stage to be published */ where?: (AssetManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)}) => AssetConnectionPromiseChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Promise<FieldsSelection<AssetConnection, R>>}), /** Find many Asset documents that match criteria in specified stage and unpublish from target stages */ unpublishManyAssetsConnection: ((args: { /** Identifies documents in draft stage */ where?: (AssetManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)}) => AssetConnectionPromiseChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Promise<FieldsSelection<AssetConnection, R>>}), /** * @deprecated Please use the new paginated many mutation (updateManyAssetsConnection) * Update many assets */ updateManyAssets: ((args: { /** Documents to apply update on */ where?: (AssetManyWhereInput | null), /** Updates to document content */ data: AssetUpdateManyInput}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (deleteManyAssetsConnection) * Delete many Asset documents */ deleteManyAssets: ((args?: { /** Documents to delete */ where?: (AssetManyWhereInput | null)}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>})&(BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (publishManyAssetsConnection) * Publish many Asset documents */ publishManyAssets: ((args: { /** Identifies documents in each stage to be published */ where?: (AssetManyWhereInput | null), /** Stages to publish documents to */ to: Stage[], /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (unpublishManyAssetsConnection) * Unpublish many Asset documents */ unpublishManyAssets: ((args: { /** Identifies documents in each stage */ where?: (AssetManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[], /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** Create one product */ createProduct: ((args: {data: ProductCreateInput}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** Update one product */ updateProduct: ((args: {where: ProductWhereUniqueInput,data: ProductUpdateInput}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** Delete one product from _all_ existing stages. Returns deleted document. */ deleteProduct: ((args: { /** Document to delete */ where: ProductWhereUniqueInput}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** Upsert one product */ upsertProduct: ((args: {where: ProductWhereUniqueInput,upsert: ProductUpsertInput}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** Publish one product */ publishProduct: ((args: { /** Document to publish */ where: ProductWhereUniqueInput, /** Optional localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is set */ withDefaultLocale?: (Scalars['Boolean'] | null), /** Publishing target stage */ to: Stage[]}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** Unpublish one product from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishProduct: ((args: { /** Document to unpublish */ where: ProductWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[], /** Optional locales to unpublish. Unpublishing the default locale will completely remove the document from the selected stages */ locales?: (Locale[] | null), /** Unpublish complete document including default localization and relations from stages. Can be disabled. */ unpublishBase?: (Scalars['Boolean'] | null)}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** Update many Product documents */ updateManyProductsConnection: ((args: { /** Documents to apply update on */ where?: (ProductManyWhereInput | null), /** Updates to document content */ data: ProductUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ProductConnectionPromiseChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Promise<FieldsSelection<ProductConnection, R>>}), /** Delete many Product documents, return deleted documents */ deleteManyProductsConnection: ((args?: { /** Documents to delete */ where?: (ProductManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ProductConnectionPromiseChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Promise<FieldsSelection<ProductConnection, R>>})&(ProductConnectionPromiseChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Promise<FieldsSelection<ProductConnection, R>>}), /** Publish many Product documents */ publishManyProductsConnection: ((args: { /** Identifies documents in each stage to be published */ where?: (ProductManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)}) => ProductConnectionPromiseChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Promise<FieldsSelection<ProductConnection, R>>}), /** Find many Product documents that match criteria in specified stage and unpublish from target stages */ unpublishManyProductsConnection: ((args: { /** Identifies documents in draft stage */ where?: (ProductManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)}) => ProductConnectionPromiseChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Promise<FieldsSelection<ProductConnection, R>>}), /** * @deprecated Please use the new paginated many mutation (updateManyProductsConnection) * Update many products */ updateManyProducts: ((args: { /** Documents to apply update on */ where?: (ProductManyWhereInput | null), /** Updates to document content */ data: ProductUpdateManyInput}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (deleteManyProductsConnection) * Delete many Product documents */ deleteManyProducts: ((args?: { /** Documents to delete */ where?: (ProductManyWhereInput | null)}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>})&(BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (publishManyProductsConnection) * Publish many Product documents */ publishManyProducts: ((args: { /** Identifies documents in each stage to be published */ where?: (ProductManyWhereInput | null), /** Stages to publish documents to */ to: Stage[], /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (unpublishManyProductsConnection) * Unpublish many Product documents */ unpublishManyProducts: ((args: { /** Identifies documents in each stage */ where?: (ProductManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[], /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** Create one review */ createReview: ((args: {data: ReviewCreateInput}) => ReviewPromiseChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Promise<(FieldsSelection<Review, R> | undefined)>}), /** Update one review */ updateReview: ((args: {where: ReviewWhereUniqueInput,data: ReviewUpdateInput}) => ReviewPromiseChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Promise<(FieldsSelection<Review, R> | undefined)>}), /** Delete one review from _all_ existing stages. Returns deleted document. */ deleteReview: ((args: { /** Document to delete */ where: ReviewWhereUniqueInput}) => ReviewPromiseChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Promise<(FieldsSelection<Review, R> | undefined)>}), /** Upsert one review */ upsertReview: ((args: {where: ReviewWhereUniqueInput,upsert: ReviewUpsertInput}) => ReviewPromiseChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Promise<(FieldsSelection<Review, R> | undefined)>}), /** Publish one review */ publishReview: ((args: { /** Document to publish */ where: ReviewWhereUniqueInput, /** Publishing target stage */ to: Stage[]}) => ReviewPromiseChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Promise<(FieldsSelection<Review, R> | undefined)>}), /** Unpublish one review from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishReview: ((args: { /** Document to unpublish */ where: ReviewWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[]}) => ReviewPromiseChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Promise<(FieldsSelection<Review, R> | undefined)>}), /** Update many Review documents */ updateManyReviewsConnection: ((args: { /** Documents to apply update on */ where?: (ReviewManyWhereInput | null), /** Updates to document content */ data: ReviewUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ReviewConnectionPromiseChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Promise<FieldsSelection<ReviewConnection, R>>}), /** Delete many Review documents, return deleted documents */ deleteManyReviewsConnection: ((args?: { /** Documents to delete */ where?: (ReviewManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ReviewConnectionPromiseChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Promise<FieldsSelection<ReviewConnection, R>>})&(ReviewConnectionPromiseChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Promise<FieldsSelection<ReviewConnection, R>>}), /** Publish many Review documents */ publishManyReviewsConnection: ((args: { /** Identifies documents in each stage to be published */ where?: (ReviewManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ReviewConnectionPromiseChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Promise<FieldsSelection<ReviewConnection, R>>}), /** Find many Review documents that match criteria in specified stage and unpublish from target stages */ unpublishManyReviewsConnection: ((args: { /** Identifies documents in draft stage */ where?: (ReviewManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ReviewConnectionPromiseChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Promise<FieldsSelection<ReviewConnection, R>>}), /** * @deprecated Please use the new paginated many mutation (updateManyReviewsConnection) * Update many reviews */ updateManyReviews: ((args: { /** Documents to apply update on */ where?: (ReviewManyWhereInput | null), /** Updates to document content */ data: ReviewUpdateManyInput}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (deleteManyReviewsConnection) * Delete many Review documents */ deleteManyReviews: ((args?: { /** Documents to delete */ where?: (ReviewManyWhereInput | null)}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>})&(BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (publishManyReviewsConnection) * Publish many Review documents */ publishManyReviews: ((args: { /** Identifies documents in each stage to be published */ where?: (ReviewManyWhereInput | null), /** Stages to publish documents to */ to: Stage[]}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (unpublishManyReviewsConnection) * Unpublish many Review documents */ unpublishManyReviews: ((args: { /** Identifies documents in each stage */ where?: (ReviewManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[]}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** Create one vote */ createVote: ((args: {data: VoteCreateInput}) => VotePromiseChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Promise<(FieldsSelection<Vote, R> | undefined)>}), /** Update one vote */ updateVote: ((args: {where: VoteWhereUniqueInput,data: VoteUpdateInput}) => VotePromiseChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Promise<(FieldsSelection<Vote, R> | undefined)>}), /** Delete one vote from _all_ existing stages. Returns deleted document. */ deleteVote: ((args: { /** Document to delete */ where: VoteWhereUniqueInput}) => VotePromiseChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Promise<(FieldsSelection<Vote, R> | undefined)>}), /** Upsert one vote */ upsertVote: ((args: {where: VoteWhereUniqueInput,upsert: VoteUpsertInput}) => VotePromiseChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Promise<(FieldsSelection<Vote, R> | undefined)>}), /** Publish one vote */ publishVote: ((args: { /** Document to publish */ where: VoteWhereUniqueInput, /** Publishing target stage */ to: Stage[]}) => VotePromiseChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Promise<(FieldsSelection<Vote, R> | undefined)>}), /** Unpublish one vote from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishVote: ((args: { /** Document to unpublish */ where: VoteWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[]}) => VotePromiseChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Promise<(FieldsSelection<Vote, R> | undefined)>}), /** Update many Vote documents */ updateManyVotesConnection: ((args: { /** Documents to apply update on */ where?: (VoteManyWhereInput | null), /** Updates to document content */ data: VoteUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => VoteConnectionPromiseChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Promise<FieldsSelection<VoteConnection, R>>}), /** Delete many Vote documents, return deleted documents */ deleteManyVotesConnection: ((args?: { /** Documents to delete */ where?: (VoteManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => VoteConnectionPromiseChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Promise<FieldsSelection<VoteConnection, R>>})&(VoteConnectionPromiseChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Promise<FieldsSelection<VoteConnection, R>>}), /** Publish many Vote documents */ publishManyVotesConnection: ((args: { /** Identifies documents in each stage to be published */ where?: (VoteManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => VoteConnectionPromiseChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Promise<FieldsSelection<VoteConnection, R>>}), /** Find many Vote documents that match criteria in specified stage and unpublish from target stages */ unpublishManyVotesConnection: ((args: { /** Identifies documents in draft stage */ where?: (VoteManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => VoteConnectionPromiseChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Promise<FieldsSelection<VoteConnection, R>>}), /** * @deprecated Please use the new paginated many mutation (updateManyVotesConnection) * Update many votes */ updateManyVotes: ((args: { /** Documents to apply update on */ where?: (VoteManyWhereInput | null), /** Updates to document content */ data: VoteUpdateManyInput}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (deleteManyVotesConnection) * Delete many Vote documents */ deleteManyVotes: ((args?: { /** Documents to delete */ where?: (VoteManyWhereInput | null)}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>})&(BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (publishManyVotesConnection) * Publish many Vote documents */ publishManyVotes: ((args: { /** Identifies documents in each stage to be published */ where?: (VoteManyWhereInput | null), /** Stages to publish documents to */ to: Stage[]}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (unpublishManyVotesConnection) * Unpublish many Vote documents */ unpublishManyVotes: ((args: { /** Identifies documents in each stage */ where?: (VoteManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[]}) => BatchPayloadPromiseChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Promise<FieldsSelection<BatchPayload, R>>}) } export interface MutationObservableChain{ /** * @deprecated Asset mutations will be overhauled soon * Create one asset */ createAsset: ((args: {data: AssetCreateInput}) => AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>}), /** Update one asset */ updateAsset: ((args: {where: AssetWhereUniqueInput,data: AssetUpdateInput}) => AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>}), /** Delete one asset from _all_ existing stages. Returns deleted document. */ deleteAsset: ((args: { /** Document to delete */ where: AssetWhereUniqueInput}) => AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>}), /** Upsert one asset */ upsertAsset: ((args: {where: AssetWhereUniqueInput,upsert: AssetUpsertInput}) => AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>}), /** Publish one asset */ publishAsset: ((args: { /** Document to publish */ where: AssetWhereUniqueInput, /** Optional localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is set */ withDefaultLocale?: (Scalars['Boolean'] | null), /** Publishing target stage */ to: Stage[]}) => AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>}), /** Unpublish one asset from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishAsset: ((args: { /** Document to unpublish */ where: AssetWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[], /** Optional locales to unpublish. Unpublishing the default locale will completely remove the document from the selected stages */ locales?: (Locale[] | null), /** Unpublish complete document including default localization and relations from stages. Can be disabled. */ unpublishBase?: (Scalars['Boolean'] | null)}) => AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>}), /** Update many Asset documents */ updateManyAssetsConnection: ((args: { /** Documents to apply update on */ where?: (AssetManyWhereInput | null), /** Updates to document content */ data: AssetUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => AssetConnectionObservableChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Observable<FieldsSelection<AssetConnection, R>>}), /** Delete many Asset documents, return deleted documents */ deleteManyAssetsConnection: ((args?: { /** Documents to delete */ where?: (AssetManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => AssetConnectionObservableChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Observable<FieldsSelection<AssetConnection, R>>})&(AssetConnectionObservableChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Observable<FieldsSelection<AssetConnection, R>>}), /** Publish many Asset documents */ publishManyAssetsConnection: ((args: { /** Identifies documents in each stage to be published */ where?: (AssetManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)}) => AssetConnectionObservableChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Observable<FieldsSelection<AssetConnection, R>>}), /** Find many Asset documents that match criteria in specified stage and unpublish from target stages */ unpublishManyAssetsConnection: ((args: { /** Identifies documents in draft stage */ where?: (AssetManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)}) => AssetConnectionObservableChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Observable<FieldsSelection<AssetConnection, R>>}), /** * @deprecated Please use the new paginated many mutation (updateManyAssetsConnection) * Update many assets */ updateManyAssets: ((args: { /** Documents to apply update on */ where?: (AssetManyWhereInput | null), /** Updates to document content */ data: AssetUpdateManyInput}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (deleteManyAssetsConnection) * Delete many Asset documents */ deleteManyAssets: ((args?: { /** Documents to delete */ where?: (AssetManyWhereInput | null)}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>})&(BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (publishManyAssetsConnection) * Publish many Asset documents */ publishManyAssets: ((args: { /** Identifies documents in each stage to be published */ where?: (AssetManyWhereInput | null), /** Stages to publish documents to */ to: Stage[], /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (unpublishManyAssetsConnection) * Unpublish many Asset documents */ unpublishManyAssets: ((args: { /** Identifies documents in each stage */ where?: (AssetManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[], /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** Create one product */ createProduct: ((args: {data: ProductCreateInput}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** Update one product */ updateProduct: ((args: {where: ProductWhereUniqueInput,data: ProductUpdateInput}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** Delete one product from _all_ existing stages. Returns deleted document. */ deleteProduct: ((args: { /** Document to delete */ where: ProductWhereUniqueInput}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** Upsert one product */ upsertProduct: ((args: {where: ProductWhereUniqueInput,upsert: ProductUpsertInput}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** Publish one product */ publishProduct: ((args: { /** Document to publish */ where: ProductWhereUniqueInput, /** Optional localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is set */ withDefaultLocale?: (Scalars['Boolean'] | null), /** Publishing target stage */ to: Stage[]}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** Unpublish one product from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishProduct: ((args: { /** Document to unpublish */ where: ProductWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[], /** Optional locales to unpublish. Unpublishing the default locale will completely remove the document from the selected stages */ locales?: (Locale[] | null), /** Unpublish complete document including default localization and relations from stages. Can be disabled. */ unpublishBase?: (Scalars['Boolean'] | null)}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** Update many Product documents */ updateManyProductsConnection: ((args: { /** Documents to apply update on */ where?: (ProductManyWhereInput | null), /** Updates to document content */ data: ProductUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ProductConnectionObservableChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Observable<FieldsSelection<ProductConnection, R>>}), /** Delete many Product documents, return deleted documents */ deleteManyProductsConnection: ((args?: { /** Documents to delete */ where?: (ProductManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ProductConnectionObservableChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Observable<FieldsSelection<ProductConnection, R>>})&(ProductConnectionObservableChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Observable<FieldsSelection<ProductConnection, R>>}), /** Publish many Product documents */ publishManyProductsConnection: ((args: { /** Identifies documents in each stage to be published */ where?: (ProductManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)}) => ProductConnectionObservableChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Observable<FieldsSelection<ProductConnection, R>>}), /** Find many Product documents that match criteria in specified stage and unpublish from target stages */ unpublishManyProductsConnection: ((args: { /** Identifies documents in draft stage */ where?: (ProductManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null), /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)}) => ProductConnectionObservableChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Observable<FieldsSelection<ProductConnection, R>>}), /** * @deprecated Please use the new paginated many mutation (updateManyProductsConnection) * Update many products */ updateManyProducts: ((args: { /** Documents to apply update on */ where?: (ProductManyWhereInput | null), /** Updates to document content */ data: ProductUpdateManyInput}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (deleteManyProductsConnection) * Delete many Product documents */ deleteManyProducts: ((args?: { /** Documents to delete */ where?: (ProductManyWhereInput | null)}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>})&(BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (publishManyProductsConnection) * Publish many Product documents */ publishManyProducts: ((args: { /** Identifies documents in each stage to be published */ where?: (ProductManyWhereInput | null), /** Stages to publish documents to */ to: Stage[], /** Document localizations to publish */ locales?: (Locale[] | null), /** Whether to publish the base document */ publishBase?: (Scalars['Boolean'] | null), /** Whether to include the default locale when publishBase is true */ withDefaultLocale?: (Scalars['Boolean'] | null)}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (unpublishManyProductsConnection) * Unpublish many Product documents */ unpublishManyProducts: ((args: { /** Identifies documents in each stage */ where?: (ProductManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[], /** Locales to unpublish */ locales?: (Locale[] | null), /** Whether to unpublish the base document and default localization */ unpublishBase?: (Scalars['Boolean'] | null)}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** Create one review */ createReview: ((args: {data: ReviewCreateInput}) => ReviewObservableChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Observable<(FieldsSelection<Review, R> | undefined)>}), /** Update one review */ updateReview: ((args: {where: ReviewWhereUniqueInput,data: ReviewUpdateInput}) => ReviewObservableChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Observable<(FieldsSelection<Review, R> | undefined)>}), /** Delete one review from _all_ existing stages. Returns deleted document. */ deleteReview: ((args: { /** Document to delete */ where: ReviewWhereUniqueInput}) => ReviewObservableChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Observable<(FieldsSelection<Review, R> | undefined)>}), /** Upsert one review */ upsertReview: ((args: {where: ReviewWhereUniqueInput,upsert: ReviewUpsertInput}) => ReviewObservableChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Observable<(FieldsSelection<Review, R> | undefined)>}), /** Publish one review */ publishReview: ((args: { /** Document to publish */ where: ReviewWhereUniqueInput, /** Publishing target stage */ to: Stage[]}) => ReviewObservableChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Observable<(FieldsSelection<Review, R> | undefined)>}), /** Unpublish one review from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishReview: ((args: { /** Document to unpublish */ where: ReviewWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[]}) => ReviewObservableChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Observable<(FieldsSelection<Review, R> | undefined)>}), /** Update many Review documents */ updateManyReviewsConnection: ((args: { /** Documents to apply update on */ where?: (ReviewManyWhereInput | null), /** Updates to document content */ data: ReviewUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ReviewConnectionObservableChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Observable<FieldsSelection<ReviewConnection, R>>}), /** Delete many Review documents, return deleted documents */ deleteManyReviewsConnection: ((args?: { /** Documents to delete */ where?: (ReviewManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ReviewConnectionObservableChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Observable<FieldsSelection<ReviewConnection, R>>})&(ReviewConnectionObservableChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Observable<FieldsSelection<ReviewConnection, R>>}), /** Publish many Review documents */ publishManyReviewsConnection: ((args: { /** Identifies documents in each stage to be published */ where?: (ReviewManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ReviewConnectionObservableChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Observable<FieldsSelection<ReviewConnection, R>>}), /** Find many Review documents that match criteria in specified stage and unpublish from target stages */ unpublishManyReviewsConnection: ((args: { /** Identifies documents in draft stage */ where?: (ReviewManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => ReviewConnectionObservableChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Observable<FieldsSelection<ReviewConnection, R>>}), /** * @deprecated Please use the new paginated many mutation (updateManyReviewsConnection) * Update many reviews */ updateManyReviews: ((args: { /** Documents to apply update on */ where?: (ReviewManyWhereInput | null), /** Updates to document content */ data: ReviewUpdateManyInput}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (deleteManyReviewsConnection) * Delete many Review documents */ deleteManyReviews: ((args?: { /** Documents to delete */ where?: (ReviewManyWhereInput | null)}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>})&(BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (publishManyReviewsConnection) * Publish many Review documents */ publishManyReviews: ((args: { /** Identifies documents in each stage to be published */ where?: (ReviewManyWhereInput | null), /** Stages to publish documents to */ to: Stage[]}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (unpublishManyReviewsConnection) * Unpublish many Review documents */ unpublishManyReviews: ((args: { /** Identifies documents in each stage */ where?: (ReviewManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[]}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** Create one vote */ createVote: ((args: {data: VoteCreateInput}) => VoteObservableChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Observable<(FieldsSelection<Vote, R> | undefined)>}), /** Update one vote */ updateVote: ((args: {where: VoteWhereUniqueInput,data: VoteUpdateInput}) => VoteObservableChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Observable<(FieldsSelection<Vote, R> | undefined)>}), /** Delete one vote from _all_ existing stages. Returns deleted document. */ deleteVote: ((args: { /** Document to delete */ where: VoteWhereUniqueInput}) => VoteObservableChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Observable<(FieldsSelection<Vote, R> | undefined)>}), /** Upsert one vote */ upsertVote: ((args: {where: VoteWhereUniqueInput,upsert: VoteUpsertInput}) => VoteObservableChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Observable<(FieldsSelection<Vote, R> | undefined)>}), /** Publish one vote */ publishVote: ((args: { /** Document to publish */ where: VoteWhereUniqueInput, /** Publishing target stage */ to: Stage[]}) => VoteObservableChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Observable<(FieldsSelection<Vote, R> | undefined)>}), /** Unpublish one vote from selected stages. Unpublish either the complete document with its relations, localizations and base data or specific localizations only. */ unpublishVote: ((args: { /** Document to unpublish */ where: VoteWhereUniqueInput, /** Stages to unpublish document from */ from: Stage[]}) => VoteObservableChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Observable<(FieldsSelection<Vote, R> | undefined)>}), /** Update many Vote documents */ updateManyVotesConnection: ((args: { /** Documents to apply update on */ where?: (VoteManyWhereInput | null), /** Updates to document content */ data: VoteUpdateManyInput,skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => VoteConnectionObservableChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Observable<FieldsSelection<VoteConnection, R>>}), /** Delete many Vote documents, return deleted documents */ deleteManyVotesConnection: ((args?: { /** Documents to delete */ where?: (VoteManyWhereInput | null),skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => VoteConnectionObservableChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Observable<FieldsSelection<VoteConnection, R>>})&(VoteConnectionObservableChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Observable<FieldsSelection<VoteConnection, R>>}), /** Publish many Vote documents */ publishManyVotesConnection: ((args: { /** Identifies documents in each stage to be published */ where?: (VoteManyWhereInput | null), /** Stage to find matching documents in */ from?: (Stage | null), /** Stages to publish documents to */ to: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => VoteConnectionObservableChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Observable<FieldsSelection<VoteConnection, R>>}), /** Find many Vote documents that match criteria in specified stage and unpublish from target stages */ unpublishManyVotesConnection: ((args: { /** Identifies documents in draft stage */ where?: (VoteManyWhereInput | null), /** Stage to find matching documents in */ stage?: (Stage | null), /** Stages to unpublish documents from */ from: Stage[],skip?: (Scalars['Int'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),before?: (Scalars['ID'] | null),after?: (Scalars['ID'] | null)}) => VoteConnectionObservableChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Observable<FieldsSelection<VoteConnection, R>>}), /** * @deprecated Please use the new paginated many mutation (updateManyVotesConnection) * Update many votes */ updateManyVotes: ((args: { /** Documents to apply update on */ where?: (VoteManyWhereInput | null), /** Updates to document content */ data: VoteUpdateManyInput}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (deleteManyVotesConnection) * Delete many Vote documents */ deleteManyVotes: ((args?: { /** Documents to delete */ where?: (VoteManyWhereInput | null)}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>})&(BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (publishManyVotesConnection) * Publish many Vote documents */ publishManyVotes: ((args: { /** Identifies documents in each stage to be published */ where?: (VoteManyWhereInput | null), /** Stages to publish documents to */ to: Stage[]}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}), /** * @deprecated Please use the new paginated many mutation (unpublishManyVotesConnection) * Unpublish many Vote documents */ unpublishManyVotes: ((args: { /** Identifies documents in each stage */ where?: (VoteManyWhereInput | null), /** Stages to unpublish documents from */ from: Stage[]}) => BatchPayloadObservableChain & {get: <R extends BatchPayloadRequest>(request: R, defaultValue?: FieldsSelection<BatchPayload, R>) => Observable<FieldsSelection<BatchPayload, R>>}) } /** An object with an ID */ export interface NodePromiseChain{ /** The id of the object. */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Promise<Scalars['ID']>}), /** The Stage of an object */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Promise<Stage>}) } /** An object with an ID */ export interface NodeObservableChain{ /** The id of the object. */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Observable<Scalars['ID']>}), /** The Stage of an object */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Observable<Stage>}) } /** Information about pagination in a connection. */ export interface PageInfoPromiseChain{ /** When paginating forwards, are there more items? */ hasNextPage: ({get: (request?: boolean|number, defaultValue?: Scalars['Boolean']) => Promise<Scalars['Boolean']>}), /** When paginating backwards, are there more items? */ hasPreviousPage: ({get: (request?: boolean|number, defaultValue?: Scalars['Boolean']) => Promise<Scalars['Boolean']>}), /** When paginating backwards, the cursor to continue. */ startCursor: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>}), /** When paginating forwards, the cursor to continue. */ endCursor: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>}), /** Number of items in the current page. */ pageSize: ({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Promise<(Scalars['Int'] | undefined)>}) } /** Information about pagination in a connection. */ export interface PageInfoObservableChain{ /** When paginating forwards, are there more items? */ hasNextPage: ({get: (request?: boolean|number, defaultValue?: Scalars['Boolean']) => Observable<Scalars['Boolean']>}), /** When paginating backwards, are there more items? */ hasPreviousPage: ({get: (request?: boolean|number, defaultValue?: Scalars['Boolean']) => Observable<Scalars['Boolean']>}), /** When paginating backwards, the cursor to continue. */ startCursor: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>}), /** When paginating forwards, the cursor to continue. */ endCursor: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>}), /** Number of items in the current page. */ pageSize: ({get: (request?: boolean|number, defaultValue?: (Scalars['Int'] | undefined)) => Observable<(Scalars['Int'] | undefined)>}) } export interface ProductPromiseChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Promise<Stage>}), /** System Locale field */ locale: ({get: (request?: boolean|number, defaultValue?: Locale) => Promise<Locale>}), /** Get the other localizations for this document */ localizations: ((args: { /** Potential locales that should be returned */ locales: Locale[], /** Decides if the current locale should be included or not */ includeCurrent: Scalars['Boolean']}) => {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Promise<FieldsSelection<Product, R>[]>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Promise<FieldsSelection<Product, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Promise<Scalars['ID']>}), /** The time the document was created */ createdAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** User that created this document */ createdBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The time the document was updated */ updatedAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** User that last updated this document */ updatedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Promise<(Scalars['DateTime'] | undefined)>}), /** User that last published this document */ publishedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), name: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}), slug: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}), description: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>}), price: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Promise<Scalars['Int']>}), reviews: ((args?: {where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `reviews` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => {get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>[]) => Promise<FieldsSelection<Review, R>[]>})&({get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>[]) => Promise<FieldsSelection<Review, R>[]>}), votes: ((args?: {where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `votes` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => {get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>[]) => Promise<FieldsSelection<Vote, R>[]>})&({get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>[]) => Promise<FieldsSelection<Vote, R>[]>}), image: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `image` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>})&(AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>}), content: (RichTextPromiseChain & {get: <R extends RichTextRequest>(request: R, defaultValue?: (FieldsSelection<RichText, R> | undefined)) => Promise<(FieldsSelection<RichText, R> | undefined)>}), /** List of Product versions */ history: ((args: {limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)}) => {get: <R extends VersionRequest>(request: R, defaultValue?: FieldsSelection<Version, R>[]) => Promise<FieldsSelection<Version, R>[]>}) } export interface ProductObservableChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Observable<Stage>}), /** System Locale field */ locale: ({get: (request?: boolean|number, defaultValue?: Locale) => Observable<Locale>}), /** Get the other localizations for this document */ localizations: ((args: { /** Potential locales that should be returned */ locales: Locale[], /** Decides if the current locale should be included or not */ includeCurrent: Scalars['Boolean']}) => {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Observable<FieldsSelection<Product, R>[]>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Observable<FieldsSelection<Product, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Observable<Scalars['ID']>}), /** The time the document was created */ createdAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** User that created this document */ createdBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The time the document was updated */ updatedAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** User that last updated this document */ updatedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ((args: { /** Variation of DateTime field to return, allows value from base document, current localization, or combined by returning the newer value of both */ variation: SystemDateTimeFieldVariation}) => {get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Observable<(Scalars['DateTime'] | undefined)>}), /** User that last published this document */ publishedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), name: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}), slug: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}), description: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>}), price: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Observable<Scalars['Int']>}), reviews: ((args?: {where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `reviews` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => {get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>[]) => Observable<FieldsSelection<Review, R>[]>})&({get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>[]) => Observable<FieldsSelection<Review, R>[]>}), votes: ((args?: {where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null), /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `votes` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => {get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>[]) => Observable<FieldsSelection<Vote, R>[]>})&({get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>[]) => Observable<FieldsSelection<Vote, R>[]>}), image: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `image` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>})&(AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>}), content: (RichTextObservableChain & {get: <R extends RichTextRequest>(request: R, defaultValue?: (FieldsSelection<RichText, R> | undefined)) => Observable<(FieldsSelection<RichText, R> | undefined)>}), /** List of Product versions */ history: ((args: {limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)}) => {get: <R extends VersionRequest>(request: R, defaultValue?: FieldsSelection<Version, R>[]) => Observable<FieldsSelection<Version, R>[]>}) } /** A connection to a list of items. */ export interface ProductConnectionPromiseChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoPromiseChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Promise<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends ProductEdgeRequest>(request: R, defaultValue?: FieldsSelection<ProductEdge, R>[]) => Promise<FieldsSelection<ProductEdge, R>[]>}), aggregate: (AggregatePromiseChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Promise<FieldsSelection<Aggregate, R>>}) } /** A connection to a list of items. */ export interface ProductConnectionObservableChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoObservableChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Observable<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends ProductEdgeRequest>(request: R, defaultValue?: FieldsSelection<ProductEdge, R>[]) => Observable<FieldsSelection<ProductEdge, R>[]>}), aggregate: (AggregateObservableChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Observable<FieldsSelection<Aggregate, R>>}) } /** An edge in a connection. */ export interface ProductEdgePromiseChain{ /** The item at the end of the edge. */ node: (ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>) => Promise<FieldsSelection<Product, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}) } /** An edge in a connection. */ export interface ProductEdgeObservableChain{ /** The item at the end of the edge. */ node: (ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>) => Observable<FieldsSelection<Product, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}) } export interface QueryPromiseChain{ /** Fetches an object given its ID */ node: ((args: { /** The ID of an object */ id: Scalars['ID'],stage: Stage, /** * Defines which locales should be returned. * * Note that `Node` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => NodePromiseChain & {get: <R extends NodeRequest>(request: R, defaultValue?: (FieldsSelection<Node, R> | undefined)) => Promise<(FieldsSelection<Node, R> | undefined)>}), /** Retrieve multiple assets */ assets: ((args: {where?: (AssetWhereInput | null),orderBy?: (AssetOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends AssetRequest>(request: R, defaultValue?: FieldsSelection<Asset, R>[]) => Promise<FieldsSelection<Asset, R>[]>}), /** Retrieve a single asset */ asset: ((args: {where: AssetWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => AssetPromiseChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Promise<(FieldsSelection<Asset, R> | undefined)>}), /** Retrieve multiple assets using the Relay connection interface */ assetsConnection: ((args: {where?: (AssetWhereInput | null),orderBy?: (AssetOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => AssetConnectionPromiseChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Promise<FieldsSelection<AssetConnection, R>>}), /** Retrieve document version */ assetVersion: ((args: {where: VersionWhereInput}) => DocumentVersionPromiseChain & {get: <R extends DocumentVersionRequest>(request: R, defaultValue?: (FieldsSelection<DocumentVersion, R> | undefined)) => Promise<(FieldsSelection<DocumentVersion, R> | undefined)>}), /** Retrieve multiple products */ products: ((args: {where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Promise<FieldsSelection<Product, R>[]>}), /** Retrieve a single product */ product: ((args: {where: ProductWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** Retrieve multiple products using the Relay connection interface */ productsConnection: ((args: {where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => ProductConnectionPromiseChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Promise<FieldsSelection<ProductConnection, R>>}), /** Retrieve document version */ productVersion: ((args: {where: VersionWhereInput}) => DocumentVersionPromiseChain & {get: <R extends DocumentVersionRequest>(request: R, defaultValue?: (FieldsSelection<DocumentVersion, R> | undefined)) => Promise<(FieldsSelection<DocumentVersion, R> | undefined)>}), /** Retrieve multiple reviews */ reviews: ((args: {where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>[]) => Promise<FieldsSelection<Review, R>[]>}), /** Retrieve a single review */ review: ((args: {where: ReviewWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => ReviewPromiseChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Promise<(FieldsSelection<Review, R> | undefined)>}), /** Retrieve multiple reviews using the Relay connection interface */ reviewsConnection: ((args: {where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => ReviewConnectionPromiseChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Promise<FieldsSelection<ReviewConnection, R>>}), /** Retrieve document version */ reviewVersion: ((args: {where: VersionWhereInput}) => DocumentVersionPromiseChain & {get: <R extends DocumentVersionRequest>(request: R, defaultValue?: (FieldsSelection<DocumentVersion, R> | undefined)) => Promise<(FieldsSelection<DocumentVersion, R> | undefined)>}), /** Retrieve multiple users */ users: ((args: {where?: (UserWhereInput | null),orderBy?: (UserOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends UserRequest>(request: R, defaultValue?: FieldsSelection<User, R>[]) => Promise<FieldsSelection<User, R>[]>}), /** Retrieve a single user */ user: ((args: {where: UserWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** Retrieve multiple users using the Relay connection interface */ usersConnection: ((args: {where?: (UserWhereInput | null),orderBy?: (UserOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => UserConnectionPromiseChain & {get: <R extends UserConnectionRequest>(request: R, defaultValue?: FieldsSelection<UserConnection, R>) => Promise<FieldsSelection<UserConnection, R>>}), /** Retrieve multiple votes */ votes: ((args: {where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>[]) => Promise<FieldsSelection<Vote, R>[]>}), /** Retrieve a single vote */ vote: ((args: {where: VoteWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => VotePromiseChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Promise<(FieldsSelection<Vote, R> | undefined)>}), /** Retrieve multiple votes using the Relay connection interface */ votesConnection: ((args: {where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => VoteConnectionPromiseChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Promise<FieldsSelection<VoteConnection, R>>}), /** Retrieve document version */ voteVersion: ((args: {where: VersionWhereInput}) => DocumentVersionPromiseChain & {get: <R extends DocumentVersionRequest>(request: R, defaultValue?: (FieldsSelection<DocumentVersion, R> | undefined)) => Promise<(FieldsSelection<DocumentVersion, R> | undefined)>}) } export interface QueryObservableChain{ /** Fetches an object given its ID */ node: ((args: { /** The ID of an object */ id: Scalars['ID'],stage: Stage, /** * Defines which locales should be returned. * * Note that `Node` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => NodeObservableChain & {get: <R extends NodeRequest>(request: R, defaultValue?: (FieldsSelection<Node, R> | undefined)) => Observable<(FieldsSelection<Node, R> | undefined)>}), /** Retrieve multiple assets */ assets: ((args: {where?: (AssetWhereInput | null),orderBy?: (AssetOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends AssetRequest>(request: R, defaultValue?: FieldsSelection<Asset, R>[]) => Observable<FieldsSelection<Asset, R>[]>}), /** Retrieve a single asset */ asset: ((args: {where: AssetWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => AssetObservableChain & {get: <R extends AssetRequest>(request: R, defaultValue?: (FieldsSelection<Asset, R> | undefined)) => Observable<(FieldsSelection<Asset, R> | undefined)>}), /** Retrieve multiple assets using the Relay connection interface */ assetsConnection: ((args: {where?: (AssetWhereInput | null),orderBy?: (AssetOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Asset` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => AssetConnectionObservableChain & {get: <R extends AssetConnectionRequest>(request: R, defaultValue?: FieldsSelection<AssetConnection, R>) => Observable<FieldsSelection<AssetConnection, R>>}), /** Retrieve document version */ assetVersion: ((args: {where: VersionWhereInput}) => DocumentVersionObservableChain & {get: <R extends DocumentVersionRequest>(request: R, defaultValue?: (FieldsSelection<DocumentVersion, R> | undefined)) => Observable<(FieldsSelection<DocumentVersion, R> | undefined)>}), /** Retrieve multiple products */ products: ((args: {where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends ProductRequest>(request: R, defaultValue?: FieldsSelection<Product, R>[]) => Observable<FieldsSelection<Product, R>[]>}), /** Retrieve a single product */ product: ((args: {where: ProductWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** Retrieve multiple products using the Relay connection interface */ productsConnection: ((args: {where?: (ProductWhereInput | null),orderBy?: (ProductOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Product` will be affected directly by this argument, as well as any other related models with localized fields in the query's subtree. * The first locale matching the provided list will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => ProductConnectionObservableChain & {get: <R extends ProductConnectionRequest>(request: R, defaultValue?: FieldsSelection<ProductConnection, R>) => Observable<FieldsSelection<ProductConnection, R>>}), /** Retrieve document version */ productVersion: ((args: {where: VersionWhereInput}) => DocumentVersionObservableChain & {get: <R extends DocumentVersionRequest>(request: R, defaultValue?: (FieldsSelection<DocumentVersion, R> | undefined)) => Observable<(FieldsSelection<DocumentVersion, R> | undefined)>}), /** Retrieve multiple reviews */ reviews: ((args: {where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>[]) => Observable<FieldsSelection<Review, R>[]>}), /** Retrieve a single review */ review: ((args: {where: ReviewWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => ReviewObservableChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: (FieldsSelection<Review, R> | undefined)) => Observable<(FieldsSelection<Review, R> | undefined)>}), /** Retrieve multiple reviews using the Relay connection interface */ reviewsConnection: ((args: {where?: (ReviewWhereInput | null),orderBy?: (ReviewOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Review` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => ReviewConnectionObservableChain & {get: <R extends ReviewConnectionRequest>(request: R, defaultValue?: FieldsSelection<ReviewConnection, R>) => Observable<FieldsSelection<ReviewConnection, R>>}), /** Retrieve document version */ reviewVersion: ((args: {where: VersionWhereInput}) => DocumentVersionObservableChain & {get: <R extends DocumentVersionRequest>(request: R, defaultValue?: (FieldsSelection<DocumentVersion, R> | undefined)) => Observable<(FieldsSelection<DocumentVersion, R> | undefined)>}), /** Retrieve multiple users */ users: ((args: {where?: (UserWhereInput | null),orderBy?: (UserOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends UserRequest>(request: R, defaultValue?: FieldsSelection<User, R>[]) => Observable<FieldsSelection<User, R>[]>}), /** Retrieve a single user */ user: ((args: {where: UserWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** Retrieve multiple users using the Relay connection interface */ usersConnection: ((args: {where?: (UserWhereInput | null),orderBy?: (UserOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `User` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => UserConnectionObservableChain & {get: <R extends UserConnectionRequest>(request: R, defaultValue?: FieldsSelection<UserConnection, R>) => Observable<FieldsSelection<UserConnection, R>>}), /** Retrieve multiple votes */ votes: ((args: {where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => {get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>[]) => Observable<FieldsSelection<Vote, R>[]>}), /** Retrieve a single vote */ vote: ((args: {where: VoteWhereUniqueInput,stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => VoteObservableChain & {get: <R extends VoteRequest>(request: R, defaultValue?: (FieldsSelection<Vote, R> | undefined)) => Observable<(FieldsSelection<Vote, R> | undefined)>}), /** Retrieve multiple votes using the Relay connection interface */ votesConnection: ((args: {where?: (VoteWhereInput | null),orderBy?: (VoteOrderByInput | null),skip?: (Scalars['Int'] | null),after?: (Scalars['String'] | null),before?: (Scalars['String'] | null),first?: (Scalars['Int'] | null),last?: (Scalars['Int'] | null),stage: Stage, /** * Defines which locales should be returned. * * Note that `Vote` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument may be overwritten by another locales definition in a relational child field, this will effectively use the overwritten argument for the affected query's subtree. */ locales: Locale[]}) => VoteConnectionObservableChain & {get: <R extends VoteConnectionRequest>(request: R, defaultValue?: FieldsSelection<VoteConnection, R>) => Observable<FieldsSelection<VoteConnection, R>>}), /** Retrieve document version */ voteVersion: ((args: {where: VersionWhereInput}) => DocumentVersionObservableChain & {get: <R extends DocumentVersionRequest>(request: R, defaultValue?: (FieldsSelection<DocumentVersion, R> | undefined)) => Observable<(FieldsSelection<DocumentVersion, R> | undefined)>}) } /** Representing a RGBA color value: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb()_and_rgba() */ export interface RGBAPromiseChain{ r: ({get: (request?: boolean|number, defaultValue?: Scalars['RGBAHue']) => Promise<Scalars['RGBAHue']>}), g: ({get: (request?: boolean|number, defaultValue?: Scalars['RGBAHue']) => Promise<Scalars['RGBAHue']>}), b: ({get: (request?: boolean|number, defaultValue?: Scalars['RGBAHue']) => Promise<Scalars['RGBAHue']>}), a: ({get: (request?: boolean|number, defaultValue?: Scalars['RGBATransparency']) => Promise<Scalars['RGBATransparency']>}) } /** Representing a RGBA color value: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb()_and_rgba() */ export interface RGBAObservableChain{ r: ({get: (request?: boolean|number, defaultValue?: Scalars['RGBAHue']) => Observable<Scalars['RGBAHue']>}), g: ({get: (request?: boolean|number, defaultValue?: Scalars['RGBAHue']) => Observable<Scalars['RGBAHue']>}), b: ({get: (request?: boolean|number, defaultValue?: Scalars['RGBAHue']) => Observable<Scalars['RGBAHue']>}), a: ({get: (request?: boolean|number, defaultValue?: Scalars['RGBATransparency']) => Observable<Scalars['RGBATransparency']>}) } export interface ReviewPromiseChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Promise<Stage>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>[]) => Promise<FieldsSelection<Review, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Promise<Scalars['ID']>}), /** The time the document was created */ createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** User that created this document */ createdBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The time the document was updated */ updatedAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** User that last updated this document */ updatedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ({get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Promise<(Scalars['DateTime'] | undefined)>}), /** User that last published this document */ publishedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), name: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>}), comment: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}), product: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `product` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>})&(ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** List of Review versions */ history: ((args: {limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)}) => {get: <R extends VersionRequest>(request: R, defaultValue?: FieldsSelection<Version, R>[]) => Promise<FieldsSelection<Version, R>[]>}) } export interface ReviewObservableChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Observable<Stage>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>[]) => Observable<FieldsSelection<Review, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Observable<Scalars['ID']>}), /** The time the document was created */ createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** User that created this document */ createdBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The time the document was updated */ updatedAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** User that last updated this document */ updatedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ({get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Observable<(Scalars['DateTime'] | undefined)>}), /** User that last published this document */ publishedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), name: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>}), comment: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}), product: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `product` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>})&(ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** List of Review versions */ history: ((args: {limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)}) => {get: <R extends VersionRequest>(request: R, defaultValue?: FieldsSelection<Version, R>[]) => Observable<FieldsSelection<Version, R>[]>}) } /** A connection to a list of items. */ export interface ReviewConnectionPromiseChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoPromiseChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Promise<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends ReviewEdgeRequest>(request: R, defaultValue?: FieldsSelection<ReviewEdge, R>[]) => Promise<FieldsSelection<ReviewEdge, R>[]>}), aggregate: (AggregatePromiseChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Promise<FieldsSelection<Aggregate, R>>}) } /** A connection to a list of items. */ export interface ReviewConnectionObservableChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoObservableChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Observable<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends ReviewEdgeRequest>(request: R, defaultValue?: FieldsSelection<ReviewEdge, R>[]) => Observable<FieldsSelection<ReviewEdge, R>[]>}), aggregate: (AggregateObservableChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Observable<FieldsSelection<Aggregate, R>>}) } /** An edge in a connection. */ export interface ReviewEdgePromiseChain{ /** The item at the end of the edge. */ node: (ReviewPromiseChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>) => Promise<FieldsSelection<Review, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}) } /** An edge in a connection. */ export interface ReviewEdgeObservableChain{ /** The item at the end of the edge. */ node: (ReviewObservableChain & {get: <R extends ReviewRequest>(request: R, defaultValue?: FieldsSelection<Review, R>) => Observable<FieldsSelection<Review, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}) } /** Custom type representing a rich text value comprising of raw rich text ast, html, markdown and text values */ export interface RichTextPromiseChain{ /** Returns AST representation */ raw: ({get: (request?: boolean|number, defaultValue?: Scalars['RichTextAST']) => Promise<Scalars['RichTextAST']>}), /** Returns HTMl representation */ html: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}), /** Returns Markdown representation */ markdown: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}), /** Returns plain-text contents of RichText */ text: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}) } /** Custom type representing a rich text value comprising of raw rich text ast, html, markdown and text values */ export interface RichTextObservableChain{ /** Returns AST representation */ raw: ({get: (request?: boolean|number, defaultValue?: Scalars['RichTextAST']) => Observable<Scalars['RichTextAST']>}), /** Returns HTMl representation */ html: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}), /** Returns Markdown representation */ markdown: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}), /** Returns plain-text contents of RichText */ text: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}) } /** User system model */ export interface UserPromiseChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Promise<Stage>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends UserRequest>(request: R, defaultValue?: FieldsSelection<User, R>[]) => Promise<FieldsSelection<User, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Promise<Scalars['ID']>}), /** The time the document was created */ createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** The time the document was updated */ updatedAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ({get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Promise<(Scalars['DateTime'] | undefined)>}), /** The username */ name: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}), /** Profile Picture url */ picture: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Promise<(Scalars['String'] | undefined)>}), /** User Kind. Can be either MEMBER, PAT or PUBLIC */ kind: ({get: (request?: boolean|number, defaultValue?: UserKind) => Promise<UserKind>}), /** Flag to determine if user is active or not */ isActive: ({get: (request?: boolean|number, defaultValue?: Scalars['Boolean']) => Promise<Scalars['Boolean']>}) } /** User system model */ export interface UserObservableChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Observable<Stage>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends UserRequest>(request: R, defaultValue?: FieldsSelection<User, R>[]) => Observable<FieldsSelection<User, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Observable<Scalars['ID']>}), /** The time the document was created */ createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** The time the document was updated */ updatedAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ({get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Observable<(Scalars['DateTime'] | undefined)>}), /** The username */ name: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}), /** Profile Picture url */ picture: ({get: (request?: boolean|number, defaultValue?: (Scalars['String'] | undefined)) => Observable<(Scalars['String'] | undefined)>}), /** User Kind. Can be either MEMBER, PAT or PUBLIC */ kind: ({get: (request?: boolean|number, defaultValue?: UserKind) => Observable<UserKind>}), /** Flag to determine if user is active or not */ isActive: ({get: (request?: boolean|number, defaultValue?: Scalars['Boolean']) => Observable<Scalars['Boolean']>}) } /** A connection to a list of items. */ export interface UserConnectionPromiseChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoPromiseChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Promise<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends UserEdgeRequest>(request: R, defaultValue?: FieldsSelection<UserEdge, R>[]) => Promise<FieldsSelection<UserEdge, R>[]>}), aggregate: (AggregatePromiseChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Promise<FieldsSelection<Aggregate, R>>}) } /** A connection to a list of items. */ export interface UserConnectionObservableChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoObservableChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Observable<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends UserEdgeRequest>(request: R, defaultValue?: FieldsSelection<UserEdge, R>[]) => Observable<FieldsSelection<UserEdge, R>[]>}), aggregate: (AggregateObservableChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Observable<FieldsSelection<Aggregate, R>>}) } /** An edge in a connection. */ export interface UserEdgePromiseChain{ /** The item at the end of the edge. */ node: (UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: FieldsSelection<User, R>) => Promise<FieldsSelection<User, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}) } /** An edge in a connection. */ export interface UserEdgeObservableChain{ /** The item at the end of the edge. */ node: (UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: FieldsSelection<User, R>) => Observable<FieldsSelection<User, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}) } export interface VersionPromiseChain{ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Promise<Scalars['ID']>}), stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Promise<Stage>}), revision: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Promise<Scalars['Int']>}), createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}) } export interface VersionObservableChain{ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Observable<Scalars['ID']>}), stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Observable<Stage>}), revision: ({get: (request?: boolean|number, defaultValue?: Scalars['Int']) => Observable<Scalars['Int']>}), createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}) } export interface VotePromiseChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Promise<Stage>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>[]) => Promise<FieldsSelection<Vote, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Promise<Scalars['ID']>}), /** The time the document was created */ createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** User that created this document */ createdBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The time the document was updated */ updatedAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Promise<Scalars['DateTime']>}), /** User that last updated this document */ updatedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ({get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Promise<(Scalars['DateTime'] | undefined)>}), /** User that last published this document */ publishedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>})&(UserPromiseChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Promise<(FieldsSelection<User, R> | undefined)>}), product: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `product` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>})&(ProductPromiseChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Promise<(FieldsSelection<Product, R> | undefined)>}), /** List of Vote versions */ history: ((args: {limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)}) => {get: <R extends VersionRequest>(request: R, defaultValue?: FieldsSelection<Version, R>[]) => Promise<FieldsSelection<Version, R>[]>}) } export interface VoteObservableChain{ /** System stage field */ stage: ({get: (request?: boolean|number, defaultValue?: Stage) => Observable<Stage>}), /** Get the document in other stages */ documentInStages: ((args: { /** Potential stages that should be returned */ stages: Stage[], /** Decides if the current stage should be included or not */ includeCurrent: Scalars['Boolean'], /** Decides if the documents should match the parent documents locale or should use the fallback order defined in the tree */ inheritLocale: Scalars['Boolean']}) => {get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>[]) => Observable<FieldsSelection<Vote, R>[]>}), /** The unique identifier */ id: ({get: (request?: boolean|number, defaultValue?: Scalars['ID']) => Observable<Scalars['ID']>}), /** The time the document was created */ createdAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** User that created this document */ createdBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `createdBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The time the document was updated */ updatedAt: ({get: (request?: boolean|number, defaultValue?: Scalars['DateTime']) => Observable<Scalars['DateTime']>}), /** User that last updated this document */ updatedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `updatedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), /** The time the document was published. Null on documents in draft stage. */ publishedAt: ({get: (request?: boolean|number, defaultValue?: (Scalars['DateTime'] | undefined)) => Observable<(Scalars['DateTime'] | undefined)>}), /** User that last published this document */ publishedBy: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `publishedBy` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>})&(UserObservableChain & {get: <R extends UserRequest>(request: R, defaultValue?: (FieldsSelection<User, R> | undefined)) => Observable<(FieldsSelection<User, R> | undefined)>}), product: ((args?: { /** * Allows to optionally override locale filtering behaviour in the query's subtree. * * Note that `product` is a model without localized fields and will not be affected directly by this argument, however the locales will be passed on to any relational fields in the query's subtree for filtering. * For related models with localized fields in the query's subtree, the first locale matching the provided list of locales will be returned, entries with non matching locales will be filtered out. * * This argument will overwrite any existing locale filtering defined in the query's tree for the subtree. */ locales?: (Locale[] | null)}) => ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>})&(ProductObservableChain & {get: <R extends ProductRequest>(request: R, defaultValue?: (FieldsSelection<Product, R> | undefined)) => Observable<(FieldsSelection<Product, R> | undefined)>}), /** List of Vote versions */ history: ((args: {limit: Scalars['Int'],skip: Scalars['Int'], /** This is optional and can be used to fetch the document version history for a specific stage instead of the current one */ stageOverride?: (Stage | null)}) => {get: <R extends VersionRequest>(request: R, defaultValue?: FieldsSelection<Version, R>[]) => Observable<FieldsSelection<Version, R>[]>}) } /** A connection to a list of items. */ export interface VoteConnectionPromiseChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoPromiseChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Promise<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends VoteEdgeRequest>(request: R, defaultValue?: FieldsSelection<VoteEdge, R>[]) => Promise<FieldsSelection<VoteEdge, R>[]>}), aggregate: (AggregatePromiseChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Promise<FieldsSelection<Aggregate, R>>}) } /** A connection to a list of items. */ export interface VoteConnectionObservableChain{ /** Information to aid in pagination. */ pageInfo: (PageInfoObservableChain & {get: <R extends PageInfoRequest>(request: R, defaultValue?: FieldsSelection<PageInfo, R>) => Observable<FieldsSelection<PageInfo, R>>}), /** A list of edges. */ edges: ({get: <R extends VoteEdgeRequest>(request: R, defaultValue?: FieldsSelection<VoteEdge, R>[]) => Observable<FieldsSelection<VoteEdge, R>[]>}), aggregate: (AggregateObservableChain & {get: <R extends AggregateRequest>(request: R, defaultValue?: FieldsSelection<Aggregate, R>) => Observable<FieldsSelection<Aggregate, R>>}) } /** An edge in a connection. */ export interface VoteEdgePromiseChain{ /** The item at the end of the edge. */ node: (VotePromiseChain & {get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>) => Promise<FieldsSelection<Vote, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Promise<Scalars['String']>}) } /** An edge in a connection. */ export interface VoteEdgeObservableChain{ /** The item at the end of the edge. */ node: (VoteObservableChain & {get: <R extends VoteRequest>(request: R, defaultValue?: FieldsSelection<Vote, R>) => Observable<FieldsSelection<Vote, R>>}), /** A cursor for use in pagination. */ cursor: ({get: (request?: boolean|number, defaultValue?: Scalars['String']) => Observable<Scalars['String']>}) }
the_stack
import { BrsValue, ValueKind, BrsString, BrsBoolean, BrsInvalid, Comparable } from "../BrsType"; import { BrsType, isBrsString, isBrsNumber, isBrsBoolean } from ".."; import { BrsComponent, BrsIterable } from "./BrsComponent"; import { Callable, StdlibArgument } from "../Callable"; import { Interpreter } from "../../interpreter"; import { Int32 } from "../Int32"; import { RoAssociativeArray } from "./RoAssociativeArray"; /** * Gives the order for sorting different types in a mixed array * * Mixed Arrays seem to get sorted in this order (tested with Roku OS 9.4): * * numbers in numeric order * strings in alphabetical order, * assocArrays in original order * everything else in original order */ function getTypeSortIndex(a: BrsType): number { if (isBrsNumber(a)) { return 0; } else if (isBrsString(a)) { return 1; } else if (a instanceof RoAssociativeArray) { return 2; } return 3; } /** * Sorts two BrsTypes in the order that ROku would sort them * @param originalArray A copy of the original array. Used to get the order of items * @param a * @param b * @param caseInsensitive Should strings be compared case insensitively? defaults to false * @param sortInsideTypes Should two numbers or two strings be sorted? defaults to true * @return compare value for array.sort() */ function sortCompare( originalArray: BrsType[], a: BrsType, b: BrsType, caseInsensitive: boolean = false, sortInsideTypes: boolean = true ): number { let compare = 0; if (a !== undefined && b !== undefined) { const aSortOrder = getTypeSortIndex(a); const bSortOrder = getTypeSortIndex(b); if (aSortOrder < bSortOrder) { compare = -1; } else if (bSortOrder < aSortOrder) { compare = 1; } else { // a and b have the same type if (sortInsideTypes && isBrsNumber(a)) { // two numbers are in numeric order compare = (a as Comparable).greaterThan(b).toBoolean() ? 1 : -1; } else if (sortInsideTypes && isBrsString(a)) { // two strings are in alphabetical order let aStr = a.toString(); let bStr = b.toString(); if (caseInsensitive) { aStr = aStr.toLowerCase(); bStr = bStr.toLowerCase(); } // roku does not use locale for sorting strings compare = aStr > bStr ? 1 : -1; } else { // everything else is in the same order as the original const aOriginalIndex = originalArray.indexOf(a); const bOriginalIndex = originalArray.indexOf(b); if (aOriginalIndex > -1 && bOriginalIndex > -1) { compare = aOriginalIndex - bOriginalIndex; } } } } return compare; } export class RoArray extends BrsComponent implements BrsValue, BrsIterable { readonly kind = ValueKind.Object; private elements: BrsType[]; constructor(elements: BrsType[]) { super("roArray"); this.elements = elements; this.registerMethods({ ifArray: [ this.peek, this.pop, this.push, this.shift, this.unshift, this.delete, this.count, this.clear, this.append, ], ifArrayJoin: [this.join], ifArraySort: [this.sort, this.sortBy, this.reverse], ifEnum: [this.isEmpty], }); } toString(parent?: BrsType): string { if (parent) { return "<Component: roArray>"; } return [ "<Component: roArray> =", "[", ...this.elements.map((el: BrsValue) => ` ${el.toString(this)}`), "]", ].join("\n"); } equalTo(other: BrsType) { return BrsBoolean.False; } getValue() { return this.elements; } getElements() { return this.elements.slice(); } get(index: BrsType) { switch (index.kind) { case ValueKind.Int32: return this.getElements()[index.getValue()] || BrsInvalid.Instance; case ValueKind.String: return this.getMethod(index.value) || BrsInvalid.Instance; default: throw new Error( "Array indexes must be 32-bit integers, or method names must be strings" ); } } set(index: BrsType, value: BrsType) { if (index.kind !== ValueKind.Int32) { throw new Error("Array indexes must be 32-bit integers"); } this.elements[index.getValue()] = value; return BrsInvalid.Instance; } private peek = new Callable("peek", { signature: { args: [], returns: ValueKind.Dynamic, }, impl: (interpreter: Interpreter) => { return this.elements[this.elements.length - 1] || BrsInvalid.Instance; }, }); private pop = new Callable("pop", { signature: { args: [], returns: ValueKind.Dynamic, }, impl: (interpreter: Interpreter) => { return this.elements.pop() || BrsInvalid.Instance; }, }); private push = new Callable("push", { signature: { args: [new StdlibArgument("talue", ValueKind.Dynamic)], returns: ValueKind.Void, }, impl: (interpreter: Interpreter, tvalue: BrsType) => { this.elements.push(tvalue); return BrsInvalid.Instance; }, }); private shift = new Callable("shift", { signature: { args: [], returns: ValueKind.Dynamic, }, impl: (interpreter: Interpreter) => { return this.elements.shift() || BrsInvalid.Instance; }, }); private unshift = new Callable("unshift", { signature: { args: [new StdlibArgument("tvalue", ValueKind.Dynamic)], returns: ValueKind.Void, }, impl: (interpreter: Interpreter, tvalue: BrsType) => { this.elements.unshift(tvalue); return BrsInvalid.Instance; }, }); private delete = new Callable("delete", { signature: { args: [new StdlibArgument("index", ValueKind.Int32)], returns: ValueKind.Boolean, }, impl: (interpreter: Interpreter, index: Int32) => { if (index.lessThan(new Int32(0)).toBoolean()) { return BrsBoolean.False; } let deleted = this.elements.splice(index.getValue(), 1); return BrsBoolean.from(deleted.length > 0); }, }); private count = new Callable("count", { signature: { args: [], returns: ValueKind.Int32, }, impl: (interpreter: Interpreter) => { return new Int32(this.elements.length); }, }); private clear = new Callable("clear", { signature: { args: [], returns: ValueKind.Void, }, impl: (interpreter: Interpreter) => { this.elements = []; return BrsInvalid.Instance; }, }); private append = new Callable("append", { signature: { args: [new StdlibArgument("array", ValueKind.Object)], returns: ValueKind.Void, }, impl: (interpreter: Interpreter, array: BrsComponent) => { if (!(array instanceof RoArray)) { // TODO: validate against RBI return BrsInvalid.Instance; } this.elements = [ ...this.elements, ...array.elements.filter((element) => !!element), // don't copy "holes" where no value exists ]; return BrsInvalid.Instance; }, }); // ifArrayJoin private join = new Callable("join", { signature: { args: [new StdlibArgument("separator", ValueKind.String)], returns: ValueKind.String, }, impl: (interpreter: Interpreter, separator: BrsString) => { if ( this.elements.some(function (element) { return !(element instanceof BrsString); }) ) { interpreter.stderr.write("roArray.Join: Array contains non-string value(s).\n"); return new BrsString(""); } return new BrsString(this.elements.join(separator.value)); }, }); // ifArraySort private sort = new Callable("sort", { signature: { args: [new StdlibArgument("flags", ValueKind.String, new BrsString(""))], returns: ValueKind.Void, }, impl: (interpreter: Interpreter, flags: BrsString) => { if (flags.toString().match(/([^ir])/g) != null) { interpreter.stderr.write("roArray.Sort: Flags contains invalid option(s).\n"); } else { const caseInsensitive = flags.toString().indexOf("i") > -1; const originalArrayCopy = [...this.elements]; this.elements = this.elements.sort((a, b) => { return sortCompare(originalArrayCopy, a, b, caseInsensitive); }); if (flags.toString().indexOf("r") > -1) { this.elements = this.elements.reverse(); } } return BrsInvalid.Instance; }, }); private sortBy = new Callable("sortBy", { signature: { args: [ new StdlibArgument("fieldName", ValueKind.String), new StdlibArgument("flags", ValueKind.String, new BrsString("")), ], returns: ValueKind.Void, }, impl: (interpreter: Interpreter, fieldName: BrsString, flags: BrsString) => { if (flags.toString().match(/([^ir])/g) != null) { interpreter.stderr.write("roArray.SortBy: Flags contains invalid option(s).\n"); } else { const caseInsensitive = flags.toString().indexOf("i") > -1; const originalArrayCopy = [...this.elements]; this.elements = this.elements.sort((a, b) => { let compare = 0; if (a instanceof RoAssociativeArray && b instanceof RoAssociativeArray) { const aHasField = a.elements.has(fieldName.toString().toLowerCase()); const bHasField = b.elements.has(fieldName.toString().toLowerCase()); if (aHasField && bHasField) { const valueA = a.get(fieldName); const valueB = b.get(fieldName); compare = sortCompare( originalArrayCopy, valueA, valueB, caseInsensitive ); } else if (aHasField) { // assocArray with fields come before assocArrays without compare = -1; } else if (bHasField) { // assocArray with fields come before assocArrays without compare = 1; } } else if (a !== undefined && b !== undefined) { compare = sortCompare(originalArrayCopy, a, b, false, false); } return compare; }); if (flags.toString().indexOf("r") > -1) { this.elements = this.elements.reverse(); } } return BrsInvalid.Instance; }, }); private reverse = new Callable("reverse", { signature: { args: [], returns: ValueKind.Void, }, impl: (interpreter: Interpreter, separator: BrsString) => { this.elements = this.elements.reverse(); return BrsInvalid.Instance; }, }); // ifEnum private isEmpty = new Callable("isEmpty", { signature: { args: [], returns: ValueKind.Boolean, }, impl: (interpreter: Interpreter) => { return BrsBoolean.from(this.elements.length === 0); }, }); }
the_stack
namespace KMWRecorder { //#region Defines the InputEventSpec set, used to reconstruct DOM-based events for browser-based simulation export abstract class InputEventSpec { type: "key" | "osk"; static fromJSONObject(obj: any): InputEventSpec { if(obj && obj.type) { if(obj.type == "key") { return new PhysicalInputEventSpec(obj); } else if(obj.type == "osk") { return new OSKInputEventSpec(obj); } } else { throw new SyntaxError("Error in JSON format corresponding to an InputEventSpec!"); } } toPrettyJSON(): string { // We want the default, non-spaced JSON for this class, even when otherwise adding whitespace. var str = JSON.stringify(this); return str; } } export class PhysicalInputEventSpec extends InputEventSpec { static readonly modifierCodes: { [mod:string]: number } = { "Shift":0x0001, "Control":0x0002, "Alt":0x0004, "Meta":0x0008, "CapsLock":0x0010, "NumLock":0x0020, "ScrollLock":0x0040 }; // KeyboardEvent properties type: "key" = "key"; key: string; code: string; keyCode: number; modifierSet: number; location: number; constructor(e?: PhysicalInputEventSpec) { // parameter is used to reconstruct from JSON. super(); if(e) { this.key = e.key; this.code = e.code; this.keyCode = e.keyCode; this.modifierSet = e.modifierSet; this.location = e.location; } } getModifierState(key: string): boolean { return (PhysicalInputEventSpec.modifierCodes[key] & this.modifierSet) != 0; } generateModifierString(): string { var list: string = ""; for(var key in PhysicalInputEventSpec.modifierCodes) { if(this.getModifierState(key)) { list += ((list != "" ? " " : "") + key); } } return list; } } export class OSKInputEventSpec extends InputEventSpec { type: "osk" = "osk"; keyID: string; // The parameter may be used to reconstruct the item from raw JSON. constructor(e?: OSKInputEventSpec) { super(); if(e) { this.keyID = e.keyID; } } } //#endregion export abstract class RecordedKeystroke { type: "key" | "osk"; static fromJSONObject(obj: any): RecordedKeystroke { if(obj && obj.type) { if(obj.type == "key") { return new RecordedPhysicalKeystroke(obj as RecordedPhysicalKeystroke); } else if(obj && obj.type) { return new RecordedSyntheticKeystroke(obj as RecordedSyntheticKeystroke); } } else { throw new SyntaxError("Error in JSON format corresponding to a RecordedKeystroke!"); } } toPrettyJSON(): string { // We want the default, non-spaced JSON for this class, even when otherwise adding whitespace. var str = JSON.stringify(this); return str; } /** * Returns an InputEventSpec that may be used to simulate the keystroke within a browser-based environment. */ abstract get inputEventSpec(): InputEventSpec; } export class RecordedPhysicalKeystroke extends RecordedKeystroke { // KeyboardEvent properties type: "key" = "key"; keyCode: number; // may be different from eventSpec's value b/c keymapping states: number; modifiers: number; modifierChanged: boolean; isVirtualKey: boolean; vkCode: number; // may be possible to eliminate; differences arise from mnemonics. eventSpec: PhysicalInputEventSpec; constructor(keystroke: RecordedPhysicalKeystroke) constructor(keystroke: com.keyman.text.KeyEvent, eventSpec: PhysicalInputEventSpec) constructor(keystroke: RecordedPhysicalKeystroke|com.keyman.text.KeyEvent, eventSpec?: PhysicalInputEventSpec) { super(); if(keystroke instanceof com.keyman.text.KeyEvent || typeof keystroke.type === 'undefined') { // Store what is necessary for headless event reconstruction. keystroke = keystroke as com.keyman.text.KeyEvent; this.keyCode = keystroke.Lcode; this.states = keystroke.Lstates; this.modifiers = keystroke.Lmodifiers; this.modifierChanged = !!keystroke.LmodifierChange; this.isVirtualKey = keystroke.LisVirtualKey; this.vkCode = keystroke.vkCode; // Also store the DOM-based event spec for use in integrated testing. this.eventSpec = eventSpec; } else { // It might be a raw object, from JSON. this.keyCode = keystroke.keyCode; this.states = keystroke.states; this.modifiers = keystroke.modifiers; this.modifierChanged = keystroke.modifierChanged; this.isVirtualKey = keystroke.isVirtualKey; this.vkCode = keystroke.vkCode; this.eventSpec = new PhysicalInputEventSpec(keystroke.eventSpec); // must also be reconstructed. } } get inputEventSpec(): InputEventSpec { return this.eventSpec; } } export class RecordedSyntheticKeystroke extends RecordedKeystroke { // KeyboardEvent properties type: "osk" = "osk"; keyName: string; layer: string; keyDistribution?: com.keyman.text.KeyDistribution; constructor(keystroke: RecordedSyntheticKeystroke) constructor(keystroke: com.keyman.text.KeyEvent) constructor(keystroke: RecordedSyntheticKeystroke|com.keyman.text.KeyEvent) { super(); if(keystroke instanceof com.keyman.text.KeyEvent || typeof keystroke.type === 'undefined') { keystroke = keystroke as com.keyman.text.KeyEvent; // Store what is necessary for headless event reconstruction. // Also store the DOM-based event spec for use in integrated testing. this.layer = keystroke.kbdLayer; this.keyName = keystroke.kName; this.keyDistribution = keystroke.keyDistribution; } else { // It might be a raw object, from JSON. this.layer = keystroke.layer; this.keyName = keystroke.keyName; this.keyDistribution = keystroke.keyDistribution; } } get inputEventSpec(): InputEventSpec { let eventSpec = new OSKInputEventSpec(); eventSpec.keyID = this.layer + '-' + this.keyName; return eventSpec; } } export abstract class TestSequence<KeyRecord extends RecordedKeystroke | InputEventSpec> { inputs: KeyRecord[]; output: string; msg?: string; abstract hasOSKInteraction(): boolean; test(proctor: Proctor, target?: com.keyman.text.OutputTarget): {success: boolean, result: string} { // Start with an empty OutputTarget and a fresh KeyboardProcessor. if(!target) { target = new com.keyman.text.Mock(); } proctor.before(); let result = proctor.simulateSequence(this, target); proctor.assertEquals(result, this.output, this.msg); return {success: (result == this.output), result: result}; } toPrettyJSON(): string { var str = "{ "; if(this.output) { str += "\"output\": \"" + this.output + "\", "; } str += "\"inputs\": [\n"; for(var i = 0; i < this.inputs.length; i++) { str += " " + this.inputs[i].toPrettyJSON() + ((i == this.inputs.length-1) ? "\n" : ",\n"); } if(this.msg) { str += "], \"message\": \"" + this.msg + "\" }"; } else { str += "]}"; } return str; } } export class InputEventSpecSequence extends TestSequence<InputEventSpec> { inputs: InputEventSpec[]; output: string; msg?: string; constructor(ins?: InputEventSpec[] | InputEventSpecSequence, outs?: string, msg?: string) { super(); if(ins) { if(ins instanceof Array) { this.inputs = [].concat(ins); } else { // We're constructing from existing JSON. this.inputs = []; for(var ie=0; ie < ins.inputs.length; ie++) { this.inputs.push(InputEventSpec.fromJSONObject(ins.inputs[ie])); } this.output = ins.output; this.msg = ins.msg; return; } } else { this.inputs = []; } if(outs) { this.output = outs; } if(msg) { this.msg = msg; } } addInput(event: InputEventSpec, output: string) { this.inputs.push(event); this.output = output; } hasOSKInteraction(): boolean { for(var i=0; i < this.inputs.length; i++) { if(this.inputs[i] instanceof OSKInputEventSpec) { return true; } } return false; } } export class RecordedKeystrokeSequence extends TestSequence<RecordedKeystroke> { inputs: RecordedKeystroke[]; output: string; msg?: string; constructor(ins?: RecordedKeystroke[], outs?: string, msg?: string) constructor(sequence: RecordedKeystrokeSequence) constructor(ins?: RecordedKeystroke[] | RecordedKeystrokeSequence, outs?: string, msg?: string) { super(); if(ins) { if(ins instanceof Array) { this.inputs = [].concat(ins); } else { // We're constructing from existing JSON. this.inputs = []; for(var ie=0; ie < ins.inputs.length; ie++) { this.inputs.push(RecordedKeystroke.fromJSONObject(ins.inputs[ie])); } this.output = ins.output; this.msg = ins.msg; return; } } else { this.inputs = []; } if(outs) { this.output = outs; } if(msg) { this.msg = msg; } } addInput(event: RecordedKeystroke, output: string) { this.inputs.push(event); this.output = output; } hasOSKInteraction(): boolean { for(var i=0; i < this.inputs.length; i++) { if(this.inputs[i] instanceof RecordedSyntheticKeystroke) { return true; } } return false; } } class FontStubForLanguage { family: string; source: string[]; constructor(activeStubEntry: any) { this.family = activeStubEntry.family; var src = activeStubEntry.files; if(!(src instanceof Array)) { src = [ src ]; } this.source = []; for(var i=0; i < src.length; i++) { this.source.push(activeStubEntry.path + src[i]); } } } export class LanguageStubForKeyboard { id: string; name: string; region: string; font?: FontStubForLanguage; oskFont?: FontStubForLanguage; constructor(activeStub: any) { if(activeStub.KLC) { this.id = activeStub.KLC; this.name = activeStub.KL; this.region = activeStub.KR; // Fonts. if(activeStub.KFont) { this.font = new FontStubForLanguage(activeStub.KFont); } if(activeStub.KOskFont) { this.oskFont = new FontStubForLanguage(activeStub.KOskFont); } } else { this.id = activeStub.id; this.name = activeStub.name; this.region = activeStub.region; // If we end up adding functionality to FontStubForLanguage, we'll need to properly reconstruct these. this.font = activeStub.font; this.oskFont = activeStub.oskFont; } } } export class KeyboardStub { id: string; name: string; filename: string; languages: LanguageStubForKeyboard | LanguageStubForKeyboard[]; // Constructs a stub usable with KeymanWeb's addKeyboards() API function from // the internally-tracked ActiveStub value for that keyboard. constructor(json?: KeyboardStub) { if(json) { this.id = json.id; this.name = json.name; this.filename = json.filename; if(!Array.isArray(json.languages)) { this.languages = new LanguageStubForKeyboard(json.languages); } else { this.languages = []; for(var i=0; i < json.languages.length; i++) { this.languages.push(new LanguageStubForKeyboard(json.languages[i])); } } } } getFirstLanguage() { if(this.languages instanceof LanguageStubForKeyboard) { return this.languages.id; } else { return this.languages[0].id; } } } type TARGET = 'hardware'|'desktop'|'phone'|'tablet'; type OS = 'windows'|'android'|'ios'|'macosx'|'linux'; type BROWSER = 'ie'|'chrome'|'firefox'|'safari'|'opera'; // ! no 'edge' detection in KMW! export class Constraint { target: TARGET; validOSList?: OS[]; validBrowsers?: BROWSER[]; constructor(target: TARGET|Constraint, validOSList?: OS[], validBrowsers?: BROWSER[]) { if(typeof(target) == 'string') { this.target = target; this.validOSList = validOSList; this.validBrowsers = validBrowsers; } else { var json = target; this.target = json.target; this.validOSList = json.validOSList; this.validBrowsers = json.validBrowsers; } } matchesClient(device: com.keyman.utils.DeviceSpec, usingOSK?: boolean) { // #1: Platform check. if(usingOSK === true) { if(this.target != device.formFactor) { return false; } } else if(usingOSK === false) { if(this.target != 'hardware') { return false; } } else if(this.target != device.formFactor && this.target != 'hardware') { return false; } if(this.validOSList) { if(this.validOSList.indexOf(device.OS as OS) == -1) { return false; } } if(this.validBrowsers) { if(this.validBrowsers.indexOf(device.browser as BROWSER) == -1) { return false; } } return true; } // Checks if another Constraint instance is functionally identical to this one. equals(other: Constraint) { if(this.target != other.target) { return false; } var list1 = this.validOSList ? this.validOSList : ['any']; var list2 = other.validOSList ? other.validOSList : ['any']; if(list1.sort().join(',') != list2.sort().join(',')) { return false; } list1 = this.validBrowsers ? this.validBrowsers : ['web']; list2 = other.validBrowsers ? other.validBrowsers : ['web']; if(list1.sort().join(',') != list2.sort().join(',')) { return false; } return true; } } export class TestFailure { constraint: Constraint; test: InputEventSpecSequence; result: string; constructor(constraint: Constraint, test: InputEventSpecSequence, output: string) { this.constraint = constraint; this.test = test; this.result = output; } } export interface TestSet<Sequence extends TestSequence<any>> { constraint: Constraint; addTest(seq: Sequence): void; isValidForDevice(device: com.keyman.utils.DeviceSpec, usingOSK?: boolean): boolean; test(proctor: Proctor): TestFailure[]; } /** * The core constraint-specific test set definition used for testing versions 10.0 to 13.0. */ export class EventSpecTestSet implements TestSet<InputEventSpecSequence> { constraint: Constraint; testSet: InputEventSpecSequence[]; constructor(constraint: Constraint|EventSpecTestSet) { if("target" in constraint) { this.constraint = constraint as Constraint; this.testSet = []; } else { var json = constraint as EventSpecTestSet; this.constraint = new Constraint(json.constraint); this.testSet = []; // Clone each test sequence / reconstruct from methodless JSON object. for(var i=0; i < json.testSet.length; i++) { this.testSet.push(new InputEventSpecSequence(json.testSet[i])); } } } addTest(seq: InputEventSpecSequence) { this.testSet.push(seq); } // Used to determine if the current EventSpecTestSet is applicable to be run on a device. isValidForDevice(device: com.keyman.utils.DeviceSpec, usingOSK?: boolean) { return this.constraint.matchesClient(device, usingOSK); } // Validity should be checked before calling this method. test(proctor: Proctor): TestFailure[] { var failures: TestFailure[] = []; let testSet = this.testSet; for(var i=0; i < testSet.length; i++) { var testSeq = this[i]; var simResult = testSet[i].test(proctor); if(!simResult.success) { // Failed test! failures.push(new TestFailure(this.constraint, testSeq, simResult.result)); } } return failures.length > 0 ? failures : null; } } /** * The core constraint-specific test set definition used for testing versions 10.0 to 13.0. */ export class RecordedSequenceTestSet implements TestSet<RecordedKeystrokeSequence> { constraint: Constraint; testSet: RecordedKeystrokeSequence[]; constructor(constraint: Constraint|RecordedSequenceTestSet) { if("target" in constraint) { this.constraint = constraint as Constraint; this.testSet = []; } else { var json = constraint as RecordedSequenceTestSet; this.constraint = new Constraint(json.constraint); this.testSet = []; // Clone each test sequence / reconstruct from methodless JSON object. for(var i=0; i < json.testSet.length; i++) { this.testSet.push(new RecordedKeystrokeSequence(json.testSet[i])); } } } addTest(seq: RecordedKeystrokeSequence) { this.testSet.push(seq); } // Used to determine if the current EventSpecTestSet is applicable to be run on a device. isValidForDevice(device: com.keyman.utils.DeviceSpec, usingOSK?: boolean) { return this.constraint.matchesClient(device, usingOSK); } // Validity should be checked before calling this method. test(proctor: Proctor): TestFailure[] { var failures: TestFailure[] = []; let testSet = this.testSet; for(var i=0; i < testSet.length; i++) { var testSeq = this[i]; var simResult = testSet[i].test(proctor); if(!simResult.success) { // Failed test! failures.push(new TestFailure(this.constraint, testSeq, simResult.result)); } } return failures.length > 0 ? failures : null; } toTestName(): string { let name = "constraint: for " + this.constraint.target; if(this.constraint.target == 'hardware') { name += " keyboard"; } else { name += " OSK"; } if(this.constraint.validOSList) { name += " on OS of " + JSON.stringify(this.constraint.validOSList); } if(this.constraint.validBrowsers) { name += " in browser of " + JSON.stringify(this.constraint.validBrowsers); } return name; } } export class KeyboardTest { /** * Indicates what version of KMW's recorder the spec conforms to. */ public specVersion: com.keyman.utils.Version = KeyboardTest.CURRENT_VERSION; /** * The version of KMW in which the Recorder was first written. Worked from 10.0 to 13.0 with * only backward-compatible changes and minor tweaks to conform to internal API shifts. */ public static readonly FALLBACK_VERSION = new com.keyman.utils.Version("10.0"); public static readonly CURRENT_VERSION = new com.keyman.utils.Version("14.0"); /** * The stub information to be passed into keyman.addKeyboards() in order to run the test. */ keyboard: KeyboardStub; /** * The master array of test sets, each of which specifies constraints a client must fulfill for * the tests contained therein to be valid. */ inputTestSets: TestSet<any>[]; /** * Reconstructs a KeyboardTest object from its JSON representation, restoring its methods. * @param fromJSON */ constructor(fromJSON?: string|KeyboardStub|KeyboardTest) { if(!fromJSON) { this.keyboard = null; this.inputTestSets = []; return; } else if(typeof(fromJSON) == 'string') { fromJSON = JSON.parse(fromJSON) as KeyboardTest; } else if(fromJSON instanceof KeyboardStub) { this.keyboard = fromJSON; this.inputTestSets = []; return; } if(!fromJSON.specVersion) { fromJSON.specVersion = KeyboardTest.FALLBACK_VERSION; } else { // Is serialized to a String when saved. fromJSON.specVersion = new com.keyman.utils.Version(fromJSON.specVersion as unknown as string); } this.keyboard = new KeyboardStub(fromJSON.keyboard); this.inputTestSets = []; this.specVersion = fromJSON.specVersion; if(this.specVersion.equals(KeyboardTest.FALLBACK_VERSION)) { // Top-level test spec: EventSpecTestSet, based entirely on browser events. for(var i=0; i < fromJSON.inputTestSets.length; i++) { this.inputTestSets[i] = new EventSpecTestSet(fromJSON.inputTestSets[i] as EventSpecTestSet); } } else { for(var i=0; i < fromJSON.inputTestSets.length; i++) { this.inputTestSets[i] = new RecordedSequenceTestSet(fromJSON.inputTestSets[i] as RecordedSequenceTestSet); } } } addTest(constraint: Constraint, seq: RecordedKeystrokeSequence) { if(!this.specVersion.equals(KeyboardTest.CURRENT_VERSION)) { throw new Error("The currently-loaded test was built to an outdated specification and may not be altered."); } for(var i=0; i < this.inputTestSets.length; i++) { if(this.inputTestSets[i].constraint.equals(constraint)) { this.inputTestSets[i].addTest(seq); return; } } var newSet = new RecordedSequenceTestSet(new Constraint(constraint)); this.inputTestSets.push(newSet); newSet.addTest(seq); } test(proctor: Proctor) { var setHasRun = false; var failures: TestFailure[] = []; proctor.beforeAll(); // The original test spec requires a browser environment and thus requires its own `.run` implementation. if(!(proctor.compatibleWithSuite(this))) { throw Error("Cannot perform version " + KeyboardTest.FALLBACK_VERSION + "-based testing outside of browser-based environments."); } // Otherwise, the test spec instances will know how to run in any currently-supported environment. for(var i = 0; i < this.inputTestSets.length; i++) { var testSet = this.inputTestSets[i]; if(proctor.matchesTestSet(testSet)) { var testFailures = testSet.test(proctor); if(testFailures) { failures = failures.concat(testFailures); } setHasRun = true; } } if(!setHasRun) { // The sets CAN be empty, allowing silent failure if/when we actually want that. console.warn("No test sets for this keyboard were applicable for this device!"); } // Allow the method's caller to trigger a 'fail'. if(failures.length > 0) { return failures; } else { return null; } } isEmpty() { return this.inputTestSets.length == 0; } toPrettyJSON() { return JSON.stringify(this, null, ' '); } get isLegacy(): boolean { return !this.specVersion.equals(KeyboardTest.CURRENT_VERSION); } } }
the_stack
import Chart from './chart'; import dataRange from '@src/store/dataRange'; import scale from '@src/store/scale'; import axes from '@src/store/axes'; import plot from '@src/store/plot'; import Tooltip from '@src/component/tooltip'; import Plot from '@src/component/plot'; import LineSeries from '@src/component/lineSeries'; import ScatterSeries from '@src/component/scatterSeries'; import Axis from '@src/component/axis'; import Legend from '@src/component/legend'; import DataLabels from '@src/component/dataLabels'; import AxisTitle from '@src/component/axisTitle'; import Title from '@src/component/title'; import ExportMenu from '@src/component/exportMenu'; import SelectedSeries from '@src/component/selectedSeries'; import HoveredSeries from '@src/component/hoveredSeries'; import Zoom from '@src/component/zoom'; import Background from '@src/component/background'; import NoDataText from '@src/component/noDataText'; import * as lineSeriesBrush from '@src/brushes/lineSeries'; import * as basicBrush from '@src/brushes/basic'; import * as axisBrush from '@src/brushes/axis'; import * as legendBrush from '@src/brushes/legend'; import * as labelBrush from '@src/brushes/label'; import * as exportMenuBrush from '@src/brushes/exportMenu'; import * as dataLabelBrush from '@src/brushes/dataLabel'; import * as resetButtonBrush from '@src/brushes/resetButton'; import * as scatterSeriesBrush from '@src/brushes/scatterSeries'; import { CoordinateDataType, LineScatterChartOptions, LineScatterData, ScatterSeriesInput, } from '@t/options'; import { RawSeries } from '@t/store/store'; import { LineScatterChartProps, AddSeriesDataInfo, SelectSeriesInfo } from '@t/charts'; /** * @class * @classdesc LineScatter Chart * @param {Object} props * @param {HTMLElement} props.el - The target element to create chart. * @param {Object} props.data - Data for making LineArea Chart. * @param {Array<Object>} props.data.series - Series data. * @param {Array<Object>} props.data.series.line - Line series data. Only coordinate type data is possible. * @param {Array<Object>} props.data.series.scatter - Scatter series data. * @param {Object} [props.options] - Options for making LineScatter Chart. * @param {Object} [props.options.chart] * @param {string|Object} [props.options.chart.title] - Chart title text or options. * @param {string} [props.options.chart.title.text] - Chart title text. * @param {number} [props.options.chart.title.offsetX] - Offset value to move title horizontally. * @param {number} [props.options.chart.title.offsetY] - Offset value to move title vertically. * @param {string} [props.options.chart.title.align] - Chart text align. 'left', 'right', 'center' is available. * @param {boolean|Object} [props.options.chart.animation] - Whether to use animation and duration when rendering the initial chart. * @param {number|string} [props.options.chart.width] - Chart width. 'auto' or if not write, the width of the parent container is followed. 'auto' or if not created, the width of the parent container is followed. * @param {number|string} [props.options.chart.height] - Chart height. 'auto' or if not write, the width of the parent container is followed. 'auto' or if not created, the height of the parent container is followed. * @param {Object} [props.options.series] - Write common options in the upper depth and separate options to be applied to each chart. * @param {Object} [props.options.series.line] - Options to be applied to the line chart. 'spline', 'showDot' is available. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Line Chart guide} on github. * @param {boolean} [props.options.series.selectable=false] - Whether to make selectable series or not. * @param {Object} [props.options.series.dataLabels] - Set the visibility, location, and formatting of dataLabel. For specific information, refer to the {@link https://github.com/nhn/tui.chart|DataLabels guide} on github. * @param {Object} [props.options.xAxis] * @param {string|Object} [props.options.xAxis.title] - Axis title. * @param {boolean} [props.options.xAxis.pointOnColumn=false] - Whether to move the start of the chart to the center of the column. * @param {boolean} [props.options.xAxis.rotateLabel=true] - Whether to allow axis label rotation. * @param {boolean|Object} [props.options.xAxis.date] - Whether the x axis label is of date type. Format option used for date type. Whether the x axis label is of date type. If use date type, format option used for date type. * @param {Object} [props.options.xAxis.tick] - Option to adjust tick interval. * @param {Object} [props.options.xAxis.label] - Option to adjust label interval. * @param {Object} [props.options.xAxis.scale] - Option to adjust axis minimum, maximum, step size. * @param {number} [props.options.xAxis.width] - Width of xAxis. * @param {number} [props.options.xAxis.height] - Height of xAxis. * @param {Object|Array<Object>} [props.options.yAxis] - If this option is an array type, use the secondary y axis. * @param {string|Object} [props.options.yAxis.title] - Axis title. * @param {Object} [props.options.yAxis.tick] - Option to adjust tick interval. * @param {Object} [props.options.yAxis.label] - Option to adjust label interval. * @param {Object} [props.options.yAxis.scale] - Option to adjust axis minimum, maximum, step size. * @param {number} [props.options.yAxis.width] - Width of yAxis. * @param {number} [props.options.yAxis.height] - Height of yAxis. * @param {Object} [props.options.plot] * @param {number} [props.options.plot.width] - Width of plot. * @param {number} [props.options.plot.height] - Height of plot. * @param {boolean} [props.options.plot.visible] - Whether to show plot line. * @param {Object} [props.options.legend] * @param {string} [props.options.legend.align] - Legend align. 'top', 'bottom', 'right', 'left' is available. * @param {string} [props.options.legend.showCheckbox] - Whether to show checkbox. * @param {boolean} [props.options.legend.visible] - Whether to show legend. * @param {number} [props.options.legend.width] - Width of legend. * @param {Object} [props.options.legend.item] - `width` and `overflow` options of the legend item. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Legend guide} on github. * @param {Object} [props.options.exportMenu] * @param {boolean} [props.options.exportMenu.visible] - Whether to show export menu. * @param {string} [props.options.exportMenu.filename] - File name applied when downloading. * @param {Object} [props.options.tooltip] * @param {number} [props.options.tooltip.offsetX] - Offset value to move title horizontally. * @param {number} [props.options.tooltip.offsetY] - Offset value to move title vertically. * @param {Function} [props.options.tooltip.formatter] - Function to format data value. * @param {Function} [props.options.tooltip.template] - Function to create custom template. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Tooltip guide} on github. * @param {Object} [props.options.responsive] - Rules for changing chart options. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Responsive guide} on github. * @param {boolean|Object} [props.options.responsive.animation] - Animation duration when the chart is modified. * @param {Array<Object>} [props.options.responsive.rules] - Rules for the Chart to Respond. * @param {Object} [props.options.lang] - Options for changing the text displayed on the chart or i18n languages. * @param {Object} [props.options.lang.noData] - No Data Layer Text. * @param {Object} [props.options.theme] - Chart theme options. For specific information, refer to the {@link https://github.com/nhn/tui.chart|LineScatter Chart guide} on github. * @param {Object} [props.options.theme.chart] - Chart font theme. * @param {Object} [props.options.theme.noData] - No Data Layer Text theme. * @param {Object} [props.options.theme.series] - Series theme. Each theme to be applied to the two charts should be written separately. * @param {Object} [props.options.theme.title] - Title theme. * @param {Object} [props.options.theme.xAxis] - X Axis theme. * @param {Object|Array<Object>} [props.options.theme.yAxis] - Y Axis theme. In the case of an arrangement, the first is the main axis and the second is the theme for the secondary axis. * @param {Object} [props.options.theme.legend] - Legend theme. * @param {Object} [props.options.theme.tooltip] - Tooltip theme. * @param {Object} [props.options.theme.plot] - Plot theme. * @param {Object} [props.options.theme.exportMenu] - ExportMenu theme. * @extends Chart */ export default class LineScatterChart extends Chart<LineScatterChartOptions> { constructor(props: LineScatterChartProps) { super({ el: props.el, options: props.options, series: props.data.series as RawSeries, modules: [dataRange, scale, axes, plot], }); } protected initialize() { super.initialize(); this.componentManager.add(Background); this.componentManager.add(Title); this.componentManager.add(Plot); this.componentManager.add(Legend); this.componentManager.add(LineSeries); this.componentManager.add(ScatterSeries); this.componentManager.add(Axis, { name: 'yAxis' }); this.componentManager.add(Axis, { name: 'xAxis' }); this.componentManager.add(Axis, { name: 'secondaryYAxis' }); this.componentManager.add(DataLabels); this.componentManager.add(AxisTitle, { name: 'xAxis' }); this.componentManager.add(AxisTitle, { name: 'yAxis' }); this.componentManager.add(AxisTitle, { name: 'secondaryYAxis' }); this.componentManager.add(ExportMenu, { chartEl: this.el }); this.componentManager.add(HoveredSeries); this.componentManager.add(SelectedSeries); this.componentManager.add(Tooltip, { chartEl: this.el }); this.componentManager.add(Zoom); this.componentManager.add(NoDataText); this.painter.addGroups([ basicBrush, axisBrush, lineSeriesBrush, legendBrush, labelBrush, exportMenuBrush, dataLabelBrush, resetButtonBrush, scatterSeriesBrush, ]); } /** * Add data. * @param {Array} data - Array of data to be added. * @param {string} chartType - Which type of chart to add. * @api * @example * chart.addData([{x: 10, y: 20}, {x: 30, y: 40}], 'line'); */ addData(data: CoordinateDataType[], chartType: 'line' | 'scatter') { this.animationControlFlag.updating = true; this.resetSeries(); this.store.dispatch('addData', { data, chartType }); } /** * Add series. * @param {Object} data - Data to be added. * @param {string} data.name - Series name. * @param {Array<Object>} data.data - Array of data to be added. * @param {Object} dataInfo - Which type of chart to add. * @param {Object} dataInfo.chartType - Chart type. * @api * @example * chart.addSeries( * { * name: 'newSeries', * data: [{x: 10, y: 20}, {x: 30, y: 40}], * }, * { * chartType: 'line' * }); */ addSeries(data: ScatterSeriesInput, dataInfo: AddSeriesDataInfo) { this.resetSeries(); this.store.dispatch('addSeries', { data, ...dataInfo }); } /** * Convert the chart data to new data. * @param {Object} data - Data to be set * @api * @example * chart.setData({ * series: { * line: [ * { * name: 'A', * data: [{x: 10, y: 20}, {x: 30, y: 40}], * } * ], * scatter: [ * { * name: 'B', * data: [{x: 30, y: 20}, {x: 40, y: 40}], * } * ] * } * }); */ setData(data: LineScatterData) { this.resetSeries(); this.store.dispatch('setData', data); } /** * Convert the chart options to new options. * @param {Object} options - Chart options * @api * @example * chart.setOptions({ * chart: { * width: 500, * height: 'auto', * title: 'Energy Usage', * }, * xAxis: { * title: 'Month', * date: { format: 'yy/MM' }, * }, * yAxis: { * title: 'Energy (kWh)', * }, * series: { * line: { * showDot: true, * }, * selectable: true, * }, * tooltip: { * formatter: (value) => `${value}kWh`, * }, * }); */ setOptions(options: LineScatterChartOptions) { this.resetSeries(); this.dispatchOptionsEvent('initOptions', options); } /** * Update chart options. * @param {Object} options - Chart options * @api * @example * chart.updateOptions({ * chart: { * height: 'auto', * title: 'Energy Usage', * }, * series: { * line: { * showDot: true, * }, * }, * }); */ updateOptions(options: LineScatterChartOptions) { this.resetSeries(); this.dispatchOptionsEvent('updateOptions', options); } /** * Show tooltip. * @param {Object} seriesInfo - Information of the series for the tooltip to be displayed * @param {number} seriesInfo.seriesIndex - Index of series * @param {number} seriesInfo.index - Index of data within series * @param {string} seriesInfo.chartType - Specify which chart to select. * @api * @example * chart.showTooltip({index: 1, seriesIndex: 2, chartType: 'scatter'}); */ showTooltip(seriesInfo: SelectSeriesInfo) { this.eventBus.emit('showTooltip', { ...seriesInfo, state: this.store.state }); } /** * Hide tooltip. * @api * @example * chart.hideTooltip(); */ hideTooltip() { this.eventBus.emit('hideTooltip'); } }
the_stack
import React, { useState } from 'react' import { useTranslation } from 'react-i18next' import CompensationProgressBar from 'components/CompensationProgressBar' import Button from 'widgets/Button' import CopyZone from 'widgets/CopyZone' import { calculateClaimEpochValue, ConnectionStatus, CONSTANTS, shannonToCKBFormatter, uniformTimeFormatter, getDAOCellStatus, CellStatus, epochParser, } from 'utils' import CompensationPeriodTooltip from 'components/CompensationPeriodTooltip' import styles from './daoRecordRow.module.scss' import hooks from './hooks' const { IMMATURE_EPOCHS, HOURS_PER_EPOCH } = CONSTANTS const EPOCHS_PER_DAY = 6 const getDaysAndHours = (seconds: number) => { const SECS_PER_HOUR = 3600 * 1000 const SECS_PER_DAY = 24 * SECS_PER_HOUR const days = Math.floor(seconds / SECS_PER_DAY) const hours = Math.floor((seconds - days * SECS_PER_DAY) / SECS_PER_HOUR) return { days, hours } } export interface DAORecordProps extends State.NervosDAORecord { depositEpoch: string // deposit epoch string currentEpoch: string // current epoch string withdrawCapacity: string | null // capacity that is available for withdraw connectionStatus: 'online' | 'offline' | 'connecting' // connection status onClick: React.EventHandler<React.MouseEvent> // on action button click onToggle: () => void isCollapsed?: boolean tipBlockTimestamp: number // tip block timestamp, used to calculate apc, dovetails with current epoch genesisBlockTimestamp: number | undefined // genesis block timestamp, used to calculate apc } export const DAORecord = ({ blockNumber, tipBlockTimestamp, capacity, outPoint: { txHash, index }, timestamp, genesisBlockTimestamp, depositEpoch, currentEpoch, withdrawCapacity, connectionStatus, onClick, status, isCollapsed = true, onToggle, depositInfo, withdrawInfo, unlockInfo, }: DAORecordProps) => { const [t] = useTranslation() const [withdrawEpoch, setWithdrawEpoch] = useState('') const [withdrawTimestamp, setWithdrawTimestamp] = useState('') const [apc, setApc] = useState(0) const isWithdrawn = !!withdrawInfo // update apc hooks.useUpdateApc({ depositTimestamp: +(depositInfo?.timestamp || 0), genesisBlockTimestamp: +(genesisBlockTimestamp || 0), tipBlockTimestamp, timestamp: +(timestamp || 0), setApc, }) hooks.useUpdateWithdrawEpochs({ isWithdrawn, blockNumber, setWithdrawEpoch, setWithdrawTimestamp }) const onTxRecordClick = hooks.useOnTxRecordClick() const currentEpochValue = epochParser(currentEpoch).value const depositEpochInfo = epochParser(depositEpoch) const depositEpochValue = depositEpochInfo.value const withdrawEpochValue = withdrawEpoch ? epochParser(withdrawEpoch).value : undefined const compensationEndEpochValue = calculateClaimEpochValue( epochParser(depositEpoch), epochParser(withdrawEpoch || currentEpoch) ) const leftEpochs = Math.max(compensationEndEpochValue - currentEpochValue, 0) const leftDays = (Math.round(leftEpochs / EPOCHS_PER_DAY) ?? '').toString() const compensation = BigInt(withdrawCapacity || capacity) - BigInt(capacity) const cellStatus: CellStatus = getDAOCellStatus({ unlockInfo, withdrawInfo, status, withdrawEpoch, depositEpoch, currentEpoch, }) let message = '' if (ConnectionStatus.Online === connectionStatus) { switch (cellStatus) { case CellStatus.Unlocking: { message = t('nervos-dao.compensation-period.stage-messages.unlocking') break } case CellStatus.Withdrawing: { message = t('nervos-dao.compensation-period.stage-messages.withdrawing') break } case CellStatus.Unlockable: { message = t('nervos-dao.compensation-period.stage-messages.compensation-cycle-has-ended') break } case CellStatus.Depositing: { message = t('nervos-dao.compensation-period.stage-messages.pending') break } case CellStatus.ImmatureForWithdraw: { let hours: string | number = (depositEpochValue + IMMATURE_EPOCHS - currentEpochValue) * HOURS_PER_EPOCH if (Number.isNaN(hours) || hours < 0 || hours > HOURS_PER_EPOCH * IMMATURE_EPOCHS) { hours = '--' } else { hours = hours.toFixed(1) } message = t('nervos-dao.compensation-period.stage-messages.immature-for-withdraw', { hours }) break } case CellStatus.Deposited: { message = t('nervos-dao.compensation-period.stage-messages.next-compensation-cycle', { days: leftDays || '--' }) break } case CellStatus.ImmatureForUnlock: { let hours: number | string = (compensationEndEpochValue + IMMATURE_EPOCHS - currentEpochValue) * HOURS_PER_EPOCH if (Number.isNaN(hours) || hours < 0 || hours > HOURS_PER_EPOCH * IMMATURE_EPOCHS) { hours = '--' } else { hours = hours.toFixed(1) } message = t('nervos-dao.compensation-period.stage-messages.immature-for-unlock', { hours }) break } case CellStatus.Locked: { message = t('nervos-dao.compensation-period.stage-messages.compensation-cycle-will-end', { days: leftDays || '--', }) break } default: { // ignore } } } const lockedPeriod = unlockInfo?.timestamp && depositInfo?.timestamp ? +unlockInfo?.timestamp - +depositInfo?.timestamp : undefined const compensatedPeriod = withdrawInfo?.timestamp && depositInfo?.timestamp ? +withdrawInfo?.timestamp - +depositInfo?.timestamp : undefined const isActionAvailable = connectionStatus === 'online' && [CellStatus.Deposited, CellStatus.Unlockable].includes(cellStatus) const progressOrPeriod = CellStatus.Completed === cellStatus ? ( <> {lockedPeriod ? ( <div className={styles.lockedPeriod}> <span>{`${t('nervos-dao.deposit-record.locked-period')}:`}</span> <span>{t('nervos-dao.deposit-record.days-hours', getDaysAndHours(lockedPeriod))}</span> </div> ) : null} {compensatedPeriod ? ( <div className={styles.compensatedPeriod}> <span>{`${t('nervos-dao.deposit-record.compensated-period')}:`}</span> <span>{t('nervos-dao.deposit-record.days-hours', getDaysAndHours(compensatedPeriod))}</span> </div> ) : null} </> ) : ( <> <div className={styles.stage}> <CompensationProgressBar pending={[CellStatus.Depositing, CellStatus.ImmatureForWithdraw].includes(cellStatus)} currentEpochValue={currentEpochValue} endEpochValue={compensationEndEpochValue} withdrawEpochValue={withdrawEpochValue} /> <div className={styles.tooltip}> {CellStatus.Depositing === cellStatus ? null : ( <CompensationPeriodTooltip depositEpochValue={depositEpochValue} baseEpochTimestamp={withdrawEpochValue ? +withdrawTimestamp : tipBlockTimestamp} baseEpochValue={withdrawEpochValue || currentEpochValue} endEpochValue={compensationEndEpochValue} isWithdrawn={!!withdrawEpochValue} /> )} </div> <span className={styles.message}>{message}</span> </div> <div className={styles.action}> <Button type="primary" data-tx-hash={txHash} data-index={index} onClick={onClick} disabled={!isActionAvailable} label={t(`nervos-dao.deposit-record.${isWithdrawn ? 'unlock' : 'withdraw'}-action-label`)} /> </div> </> ) let badge = ( <div> <span>{t('nervos-dao.deposit-record.deposited-at')}</span> <time>{depositInfo ? uniformTimeFormatter(+depositInfo.timestamp) : ''}</time> </div> ) if (CellStatus.Completed === cellStatus) { badge = ( <div> <span>{t('nervos-dao.deposit-record.completed-at')}</span> <time>{unlockInfo ? uniformTimeFormatter(+unlockInfo.timestamp) : ''}</time> </div> ) } else if (CellStatus.Depositing === cellStatus) { badge = ( <div> <span>{t('nervos-dao.deposit-record.deposit-pending')}</span> </div> ) } return ( <div className={styles.container} data-is-collapsed={isCollapsed}> <div className={styles.badge}>{badge}</div> <div className={styles.collapse}> <button type="button" onClick={onToggle}> <span className={styles.collapseIcon} /> </button> </div> <div className={styles.compensation}> <span> {CellStatus.Depositing !== cellStatus && compensation >= BigInt(0) ? `+${shannonToCKBFormatter(compensation.toString()).toString()} CKB` : '- CKB'} </span> </div> <CopyZone className={styles.amount} content={shannonToCKBFormatter(capacity, false, '')}> {`${shannonToCKBFormatter(capacity)} CKB`} </CopyZone> {progressOrPeriod} <div className={styles.apc}> <span>{apc ? `APC: ~${apc}%` : `APC: - %`}</span> </div> <div className={styles.transactions}> <div className={styles.title}>{t('nervos-dao.deposit-record.record')}</div> {depositInfo ? ( <button type="button" className={styles.deposited} data-tx-hash={depositInfo.txHash} data-text={t('nervos-dao.deposit-record.tx-record')} onClick={onTxRecordClick} > <span>{t('nervos-dao.deposit-record.deposited')}</span> <span>{uniformTimeFormatter(+depositInfo.timestamp)}</span> </button> ) : null} {withdrawInfo ? ( <button type="button" className={styles.withdrawn} data-tx-hash={withdrawInfo.txHash} data-text={t('nervos-dao.deposit-record.tx-record')} onClick={onTxRecordClick} > <span>{t('nervos-dao.deposit-record.withdrawn')}</span> <span>{uniformTimeFormatter(+withdrawInfo.timestamp)}</span> </button> ) : null} {unlockInfo ? ( <button type="button" className={styles.unlocked} data-tx-hash={unlockInfo.txHash} data-text={t('nervos-dao.deposit-record.tx-record')} onClick={onTxRecordClick} > <span>{t('nervos-dao.deposit-record.unlocked')}</span> <span>{uniformTimeFormatter(+unlockInfo.timestamp)}</span> </button> ) : null} </div> </div> ) } DAORecord.displayName = 'DAORecord' export default DAORecord
the_stack
import * as evm from "@connext/pure-evm-wasm"; import { Address, tidy, Balance, ERC20Abi, FullTransferState, IVectorChainReader, Result, ChainError, ChainProviders, RegisteredTransfer, TransferName, ChannelDispute, TransferState, HydratedProviders, WithdrawCommitmentJson, ETH_READER_MAX_RETRIES, ChainReaderEventMap, ChainReaderEvent, ChainReaderEvents, ChannelDisputedPayload, ChannelDefundedPayload, TransferDisputedPayload, TransferDefundedPayload, CoreChannelState, CoreTransferState, TransferDispute, } from "@connext/vector-types"; import axios from "axios"; import { encodeBalance, encodeTransferResolver, encodeTransferState } from "@connext/vector-utils"; import { BigNumber } from "@ethersproject/bignumber"; import { parseUnits } from "@ethersproject/units"; import { AddressZero, HashZero } from "@ethersproject/constants"; import { Contract } from "@ethersproject/contracts"; import { JsonRpcProvider, TransactionRequest } from "@ethersproject/providers"; import pino from "pino"; import { ChannelFactory, ChannelMastercopy, TransferDefinition, TransferRegistry, VectorChannel } from "../artifacts"; import { Evt } from "evt"; export const MIN_GAS_PRICE = parseUnits("5", "gwei"); export const BUMP_GAS_PRICE = 30; // 30% bump gas price // https://github.com/rustwasm/wasm-bindgen/issues/700#issuecomment-419708471 const execEvmBytecode = (bytecode: string, payload: string): Uint8Array => evm.exec( Uint8Array.from(Buffer.from(bytecode.replace(/^0x/, ""), "hex")), Uint8Array.from(Buffer.from(payload.replace(/^0x/, ""), "hex")), ); export class EthereumChainReader implements IVectorChainReader { private transferRegistries: Map<string, RegisteredTransfer[]> = new Map(); protected disputeEvts: { [eventName in ChainReaderEvent]: Evt<ChainReaderEventMap[eventName]> } = { [ChainReaderEvents.CHANNEL_DISPUTED]: new Evt(), [ChainReaderEvents.CHANNEL_DEFUNDED]: new Evt(), [ChainReaderEvents.TRANSFER_DISPUTED]: new Evt(), [ChainReaderEvents.TRANSFER_DEFUNDED]: new Evt(), }; private contracts: Map<string, Contract> = new Map(); constructor( public readonly chainProviders: { [chainId: string]: JsonRpcProvider }, public readonly log: pino.BaseLogger, ) {} getChainProviders(): Result<ChainProviders, ChainError> { const ret: ChainProviders = {}; Object.entries(this.chainProviders).forEach(([name, value]) => { ret[parseInt(name)] = value.connection.url; }); return Result.ok(ret); } getHydratedProviders(): Result<HydratedProviders, ChainError> { return Result.ok(this.chainProviders); } async getSyncing( chainId: number, ): Promise< Result< | boolean | { startingBlock: string; currentBlock: string; highestBlock: string; }, ChainError > > { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper< | boolean | { startingBlock: string; currentBlock: string; highestBlock: string; } >(chainId, async () => { try { const res = await provider.send("eth_syncing", []); return Result.ok(res); } catch (e) { return Result.fail(e); } }); } async getChannelDispute( channelAddress: string, chainId: number, ): Promise<Result<ChannelDispute | undefined, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } const code = await this.getCode(channelAddress, chainId); if (code.isError) { return Result.fail(code.getError()!); } if (code.getValue() === "0x" || code.getValue() === undefined) { // channel is not deployed return Result.ok(undefined); } return await this.retryWrapper<ChannelDispute | undefined>(chainId, async () => { try { const dispute = await new Contract(channelAddress, VectorChannel.abi, provider).getChannelDispute(); if (dispute.channelStateHash === HashZero) { return Result.ok(undefined); } return Result.ok({ channelStateHash: dispute.channelStateHash, nonce: dispute.nonce.toString(), merkleRoot: dispute.merkleRoot, consensusExpiry: dispute.consensusExpiry.toString(), defundExpiry: dispute.defundExpiry.toString(), }); } catch (e) { return Result.fail(e); } }); } async getRegisteredTransferByDefinition( definition: Address, transferRegistry: string, chainId: number, bytecode?: string, ): Promise<Result<RegisteredTransfer, ChainError>> { return await this.retryWrapper<RegisteredTransfer>(chainId, async () => { let registry = this.transferRegistries.get(chainId.toString())!; if (!this.transferRegistries.has(chainId.toString())) { // Registry for chain not loaded, load into memory const loadRes = await this.loadRegistry(transferRegistry, chainId, bytecode); if (loadRes.isError) { return Result.fail(loadRes.getError()!); } registry = loadRes.getValue(); } const info = registry.find((r) => r.definition === definition); if (!info) { return Result.fail( new ChainError(ChainError.reasons.TransferNotRegistered, { definition, transferRegistry, chainId, }), ); } return Result.ok(info); }); } async getRegisteredTransferByName( name: TransferName, transferRegistry: string, chainId: number, bytecode?: string, ): Promise<Result<RegisteredTransfer, ChainError>> { return await this.retryWrapper<RegisteredTransfer>(chainId, async () => { let registry = this.transferRegistries.get(chainId.toString()); if (!registry) { // Registry for chain not loaded, load into memory const loadRes = await this.loadRegistry(transferRegistry, chainId, bytecode); if (loadRes.isError) { return Result.fail(loadRes.getError()!); } registry = loadRes.getValue(); } const info = registry!.find((r) => r.name === name); if (!info) { return Result.fail( new ChainError(ChainError.reasons.TransferNotRegistered, { name, transferRegistry, chainId, }), ); } return Result.ok(info); }); } async getRegisteredTransfers( transferRegistry: string, chainId: number, bytecode?: string, ): Promise<Result<RegisteredTransfer[], ChainError>> { return await this.retryWrapper<RegisteredTransfer[]>(chainId, async () => { let registry = this.transferRegistries.get(chainId.toString()); if (!registry) { // Registry for chain not loaded, load into memory const loadRes = await this.loadRegistry(transferRegistry, chainId, bytecode); if (loadRes.isError) { return Result.fail(loadRes.getError()!); } registry = loadRes.getValue(); } return Result.ok(registry); }); } async getChannelFactoryBytecode(channelFactoryAddress: string, chainId: number): Promise<Result<string, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<string>(chainId, async () => { try { const factory = new Contract(channelFactoryAddress, ChannelFactory.abi, provider); const proxyBytecode = await factory.getProxyCreationCode(); return Result.ok(proxyBytecode); } catch (e) { return Result.fail(e); } }); } async getChannelMastercopyAddress( channelFactoryAddress: string, chainId: number, ): Promise<Result<string, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<string>(chainId, async () => { try { const factory = new Contract(channelFactoryAddress, ChannelFactory.abi, provider); const mastercopy = await factory.getMastercopy(); return Result.ok(mastercopy); } catch (e) { return Result.fail(e); } }); } async getTotalDepositedA( channelAddress: string, chainId: number, assetId: string, ): Promise<Result<BigNumber, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<BigNumber>(chainId, async () => { const code = await this.getCode(channelAddress, chainId); if (code.isError) { return Result.fail(code.getError()!); } if (code.getValue() === "0x") { // contract *must* be deployed for alice to have a balance return Result.ok(BigNumber.from(0)); } const channelContract = new Contract(channelAddress, ChannelMastercopy.abi, provider); try { const totalDepositsAlice = await channelContract.getTotalDepositsAlice(assetId); return Result.ok(totalDepositsAlice); } catch (e) { return Result.fail(e); } }); } async getTotalDepositedB( channelAddress: string, chainId: number, assetId: string, ): Promise<Result<BigNumber, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<BigNumber>(chainId, async () => { const code = await this.getCode(channelAddress, chainId); if (code.isError) { return Result.fail(code.getError()!); } if (code.getValue() === "0x") { // all balance at channel address *must* be for bob return this.getOnchainBalance(assetId, channelAddress, chainId); } const channelContract = new Contract(channelAddress, ChannelMastercopy.abi, provider); try { const totalDepositsBob = await channelContract.getTotalDepositsBob(assetId); return Result.ok(totalDepositsBob); } catch (e) { return Result.fail(e); } }); } async create( initialState: TransferState, balance: Balance, transferDefinition: string, transferRegistryAddress: string, chainId: number, bytecode?: string, ): Promise<Result<boolean, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<boolean>(chainId, async () => { // Get encoding const registryRes = await this.getRegisteredTransferByDefinition( transferDefinition, transferRegistryAddress, chainId, bytecode, ); if (registryRes.isError) { return Result.fail(registryRes.getError()!); } // Try to encode let encodedState: string; let encodedBalance: string; try { encodedState = encodeTransferState(initialState, registryRes.getValue().stateEncoding); encodedBalance = encodeBalance(balance); } catch (e) { return Result.fail(e); } const contract = new Contract(transferDefinition, TransferDefinition.abi, provider); if (bytecode) { const evmRes = this.tryEvm( contract.interface.encodeFunctionData("create", [encodedBalance, encodedState]), bytecode, ); if (!evmRes.isError) { const decoded = contract.interface.decodeFunctionResult("create", evmRes.getValue()!)[0]; return Result.ok(decoded); } } this.log.debug( { transferDefinition, }, "Calling create onchain", ); try { const valid = await contract.create(encodedBalance, encodedState); return Result.ok(valid); } catch (e) { return Result.fail(e); } }); } async resolve(transfer: FullTransferState, chainId: number, bytecode?: string): Promise<Result<Balance, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<Balance>(chainId, async () => { // Try to encode let encodedState: string; let encodedResolver: string; let encodedBalance: string; try { encodedState = encodeTransferState(transfer.transferState, transfer.transferEncodings[0]); encodedResolver = encodeTransferResolver(transfer.transferResolver!, transfer.transferEncodings[1]); encodedBalance = encodeBalance(transfer.balance); } catch (e) { return Result.fail(e); } // Use pure-evm if possible const contract = new Contract(transfer.transferDefinition, TransferDefinition.abi, provider); if (bytecode) { const evmRes = this.tryEvm( contract.interface.encodeFunctionData("resolve", [encodedBalance, encodedState, encodedResolver]), bytecode, ); if (!evmRes.isError) { const decoded = contract.interface.decodeFunctionResult("resolve", evmRes.getValue()!)[0]; return Result.ok(decoded); } } this.log.debug( { transferDefinition: transfer.transferDefinition, transferId: transfer.transferId, }, "Calling resolve onchain", ); try { const ret = await contract.resolve(encodedBalance, encodedState, encodedResolver); return Result.ok({ to: ret.to, amount: ret.amount.map((a: BigNumber) => a.toString()), }); } catch (e) { return Result.fail(e); } }); } async getChannelAddress( alice: string, bob: string, channelFactoryAddress: string, chainId: number, ): Promise<Result<string, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<string>(chainId, async () => { const channelFactory = new Contract(channelFactoryAddress, ChannelFactory.abi, provider); try { const derivedAddress = await channelFactory.getChannelAddress(alice, bob); return Result.ok(derivedAddress); } catch (e) { return Result.fail(e); } }); } async getCode(address: string, chainId: number): Promise<Result<string, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<string>(chainId, async () => { try { const code = await provider.getCode(address); return Result.ok(code); } catch (e) { return Result.fail(e); } }); } async getBlockNumber(chainId: number): Promise<Result<number, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<number>(chainId, async () => { try { const blockNumber = await provider.getBlockNumber(); return Result.ok(blockNumber); } catch (e) { return Result.fail(e); } }); } async getGasPrice(chainId: number): Promise<Result<BigNumber, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<BigNumber>(chainId, async () => { let gasPrice: BigNumber | undefined = undefined; if (chainId === 1) { try { const gasNowResponse = await axios.get(`https://www.gasnow.org/api/v3/gas/price`); const { rapid } = gasNowResponse.data; gasPrice = typeof rapid !== "undefined" ? BigNumber.from(rapid) : undefined; } catch (e) { this.log.warn({ error: e }, "Gasnow failed, using provider"); } } if (!gasPrice) { try { gasPrice = await provider.getGasPrice(); gasPrice = gasPrice.add(gasPrice.mul(BUMP_GAS_PRICE).div(100)); } catch (e) { return Result.fail(e); } } if (gasPrice.lt(MIN_GAS_PRICE)) { gasPrice = BigNumber.from(MIN_GAS_PRICE); } return Result.ok(gasPrice); }); } async estimateGas(chainId: number, transaction: TransactionRequest): Promise<Result<BigNumber, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<BigNumber>(chainId, async () => { try { const gas = await provider.estimateGas(transaction); return Result.ok(gas); } catch (e) { return Result.fail(e); } }); } async getTokenAllowance( tokenAddress: string, owner: string, spender: string, chainId: number, ): Promise<Result<BigNumber, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<BigNumber>(chainId, async () => { const erc20 = new Contract(tokenAddress, ERC20Abi, provider); try { const res = await erc20.allowance(owner, spender); return Result.ok(res); } catch (e) { return Result.fail(e); } }); } async getOnchainBalance(assetId: string, balanceOf: string, chainId: number): Promise<Result<BigNumber, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<BigNumber>(chainId, async () => { try { const onchainBalance = assetId === AddressZero ? await provider.getBalance(balanceOf) : await new Contract(assetId, ERC20Abi, provider).balanceOf(balanceOf); return Result.ok(onchainBalance); } catch (e) { return Result.fail(e); } }); } async getDecimals(assetId: string, chainId: number): Promise<Result<number, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<number>(chainId, async () => { try { const decimals = assetId === AddressZero ? 18 : await new Contract(assetId, ERC20Abi, provider).decimals(); return Result.ok(decimals); } catch (e) { return Result.fail(e); } }); } async getWithdrawalTransactionRecord( withdrawData: WithdrawCommitmentJson, channelAddress: string, chainId: number, ): Promise<Result<boolean, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return await this.retryWrapper<boolean>(chainId, async () => { // check if it was deployed const code = await this.getCode(channelAddress, chainId); if (code.isError) { return Result.fail(code.getError()!); } if (code.getValue() === "0x") { // channel must always be deployed for a withdrawal // to be submitted return Result.ok(false); } const channel = new Contract(channelAddress, VectorChannel.abi, provider); try { const record = await channel.getWithdrawalTransactionRecord({ channelAddress, assetId: withdrawData.assetId, recipient: withdrawData.recipient, amount: withdrawData.amount, nonce: withdrawData.nonce, callTo: withdrawData.callTo, callData: withdrawData.callData, }); return Result.ok(record); } catch (e) { return Result.fail(e); } }); } // // When you are checking for disputes that have happened while you were // // offline, you query the `getChannelDispute` function onchain. This will // // give you the `ChannelDispute` record, but *not* the `CoreChannelState` // // that was disputed. To find the `CoreChannelState` that was disputed, // // you need to look at the emitted event corresponding to the // // `ChannelDispute`. // async getCoreChannelState(): Promise<Result<CoreChannelState, ChainError>> { // // Get the expiry from dispute // // Find the approximate timestamp for when the dispute event was emitted // // Binary search from blocks to find which one corresponds to the timestamp // // for the emitted dispute // // Get events for that block // // Parse events + return the core channel state // } async registerChannel(channelAddress: string, chainId: number): Promise<Result<void, ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } return this.retryWrapper<void>(chainId, async () => { if (this.contracts.has(channelAddress)) { // channel is already registered return Result.ok(undefined); } // Create channel contract const contract = new Contract(channelAddress, ChannelMastercopy.abi, provider); // Create helpers to clean contract-emitted types. Ethers emits // very oddly structured types, and any uint256 is a BigNumber. // Clean that bad boi up const processCCS = (state: any): CoreChannelState => { return { channelAddress: state.channelAddress, alice: state.alice, bob: state.bob, assetIds: state.assetIds, balances: state.balances.map((balance: any) => { return { amount: balance.amount.map((a: BigNumber) => a.toString()), to: balance.to, }; }), processedDepositsA: state.processedDepositsA.map((deposit: BigNumber) => deposit.toString()), processedDepositsB: state.processedDepositsB.map((deposit: BigNumber) => deposit.toString()), defundNonces: state.defundNonces.map((nonce: BigNumber) => nonce.toString()), timeout: state.timeout.toString(), nonce: state.nonce.toNumber(), merkleRoot: state.merkleRoot, }; }; const processChannelDispute = (dispute: any): ChannelDispute => { return { channelStateHash: dispute.channelStateHash, nonce: dispute.nonce.toString(), merkleRoot: dispute.merkleRoot, consensusExpiry: dispute.consensusExpiry.toString(), defundExpiry: dispute.defundExpiry.toString(), }; }; const processCTS = (state: any): CoreTransferState => { return { channelAddress: state.channelAddress, transferId: state.transferId, transferDefinition: state.transferDefinition, initiator: state.initiator, responder: state.responder, assetId: state.assetId, balance: { amount: state.balance.amount.map((a: BigNumber) => a.toString()), to: state.balance.to, }, transferTimeout: state.transferTimeout.toString(), initialStateHash: state.initialStateHash, }; }; const processTransferDispute = (state: any, dispute: any): TransferDispute => { return { transferId: state.transferId, transferDisputeExpiry: dispute.transferDisputeExpiry.toString(), isDefunded: dispute.isDefunded, transferStateHash: dispute.transferStateHash, }; }; // Register all dispute event listeners contract.on("ChannelDisputed", async (disputer, state, dispute) => { const payload: ChannelDisputedPayload = { disputer, state: processCCS(state), dispute: processChannelDispute(dispute), }; this.disputeEvts[ChainReaderEvents.CHANNEL_DISPUTED].post(payload); }); contract.on("ChannelDefunded", async (defunder, state, dispute, assets) => { const payload: ChannelDefundedPayload = { defunder, state: processCCS(state), dispute: processChannelDispute(dispute), defundedAssets: assets, }; this.disputeEvts[ChainReaderEvents.CHANNEL_DEFUNDED].post(payload); }); contract.on("TransferDisputed", async (disputer, state, dispute) => { const payload: TransferDisputedPayload = { disputer, state: processCTS(state), dispute: processTransferDispute(state, dispute), }; this.disputeEvts[ChainReaderEvents.TRANSFER_DISPUTED].post(payload); }); contract.on( "TransferDefunded", async (defunder, state, dispute, encodedInitialState, encodedTransferResolver, balance) => { const payload: TransferDefundedPayload = { defunder, state: processCTS(state), dispute: processTransferDispute(state, dispute), encodedInitialState, encodedTransferResolver, balance: { amount: balance.amount.map((a: BigNumber) => a.toString()), to: balance.to, }, }; this.disputeEvts[ChainReaderEvents.TRANSFER_DEFUNDED].post(payload); }, ); this.contracts.set(channelAddress, contract); return Result.ok(undefined); }); } //////////////////////////// /// CHAIN READER EVENTS public on<T extends ChainReaderEvent>( event: T, callback: (payload: ChainReaderEventMap[T]) => void | Promise<void>, filter: (payload: ChainReaderEventMap[T]) => boolean = () => true, ): void { (this.disputeEvts[event].pipe(filter) as Evt<ChainReaderEventMap[T]>).attach(callback); } public once<T extends ChainReaderEvent>( event: T, callback: (payload: ChainReaderEventMap[T]) => void | Promise<void>, filter: (payload: ChainReaderEventMap[T]) => boolean = () => true, ): void { (this.disputeEvts[event].pipe(filter) as Evt<ChainReaderEventMap[T]>).attachOnce(callback); } public off<T extends ChainReaderEvent>(event?: T): void { if (event) { this.disputeEvts[event].detach(); return; } Object.values(this.disputeEvts).forEach((evt) => evt.detach()); } public waitFor<T extends ChainReaderEvent>( event: T, timeout: number, filter: (payload: ChainReaderEventMap[T]) => boolean = () => true, ): Promise<ChainReaderEventMap[T]> { return this.disputeEvts[event].pipe(filter).waitFor(timeout) as Promise<ChainReaderEventMap[T]>; } private tryEvm(encodedFunctionData: string, bytecode: string): Result<Uint8Array, Error> { try { const output = execEvmBytecode(bytecode, encodedFunctionData); return Result.ok(output); } catch (e) { this.log.debug({ error: e.message }, `Pure-evm failed`); return Result.fail(e); } } private async loadRegistry( transferRegistry: string, chainId: number, bytecode?: string, ): Promise<Result<RegisteredTransfer[], ChainError>> { const provider = this.chainProviders[chainId]; if (!provider) { return Result.fail(new ChainError(ChainError.reasons.ProviderNotFound)); } // Registry for chain not loaded, load into memory const registry = new Contract(transferRegistry, TransferRegistry.abi, provider); let registered; if (bytecode) { // Try with evm first const evm = this.tryEvm(registry.interface.encodeFunctionData("getTransferDefinitions"), bytecode); if (!evm.isError) { try { registered = registry.interface.decodeFunctionResult("getTransferDefinitions", evm.getValue()!)[0]; } catch (e) {} } } if (!registered) { try { registered = await registry.getTransferDefinitions(); } catch (e) { return Result.fail(new ChainError(e.message, { chainId, transferRegistry })); } } const cleaned = registered.map((r: RegisteredTransfer) => { return { name: r.name, definition: r.definition, stateEncoding: tidy(r.stateEncoding), resolverEncoding: tidy(r.resolverEncoding), encodedCancel: r.encodedCancel, }; }); this.transferRegistries.set(chainId.toString(), cleaned); return Result.ok(cleaned); } private async retryWrapper<T>( chainId: number, targetMethod: () => Promise<Result<T, ChainError>>, ): Promise<Result<T, ChainError>> { let res = await targetMethod(); let retries; const errors: { [attempt: number]: string | undefined } = {}; if (!res.isError) { return res; } errors[0] = res.getError()?.message; for (retries = 1; retries < ETH_READER_MAX_RETRIES; retries++) { res = await targetMethod(); if (!res.isError) { break; } errors[retries] = res.getError()?.message; } return res.isError ? Result.fail( new ChainError(`Could not execute rpc method`, { chainId, errors, }), ) : res; } }
the_stack
import G6, { ModelConfig, IGroup, Item, IPoint, ArrowConfig } from '@antv/g6'; import { isObject } from '@antv/util'; export const registerCustomItems = () => { G6.registerNode( 'card-node', { draw: (cfg: ModelConfig | undefined = {}, group: IGroup | undefined) => { let size = cfg.size || [100, 30]; if (typeof size === 'number') size = [size, size]; const style = { radius: 2, fill: '#fff', ...cfg.style }; const color = style.stroke || cfg.color || '#5B8FF9'; const r = style.radius || 0; const shape = group!.addShape('rect', { attrs: { x: 0, y: 0, width: size[0], height: size[1], stroke: color, ...style, }, name: 'main-box', draggable: true, }); // title text const title = cfg.title || cfg.label; let titleTextShape; const labelStyle = cfg.labelCfg?.style || {}; if (title) { const titleStyle = { fill: '#fff', ...labelStyle }; titleTextShape = group!.addShape('text', { attrs: { textBaseline: 'top', x: 8, y: 2, // lineHeight: 20, text: title, ...titleStyle, fill: '#fff', }, name: 'title', }); } const titleBox = titleTextShape ? titleTextShape.getBBox() : { height: size[1] / 2 }; // title rect const titleRectShape = group!.addShape('rect', { attrs: { x: 0, y: 0, width: size[0], height: titleBox.height + 4, fill: color, radius: [r, r, 0, 0], }, name: 'title-rect', draggable: true, }); titleTextShape?.toFront(); // marker let markerShape; if (cfg?.children) { markerShape = group!.addShape('marker', { attrs: { x: size[0] / 2, y: 0, r: 6, cursor: 'pointer', symbol: cfg.collapsed ? G6.Marker.expand : G6.Marker.collapse, stroke: color, lineWidth: 1, fill: '#fff', }, name: 'collapse-icon', }); } // description const description = cfg && cfg.description ? cfg.description : undefined; const titleRectBox = titleRectShape.getBBox(); let descriptionTextShape; if (description) { descriptionTextShape = group!.addShape('text', { attrs: { textBaseline: 'top', x: 8, y: titleRectBox.height + 8, text: description, ...labelStyle, }, name: `description`, }); } if (descriptionTextShape) { const desTextShapeBBox = descriptionTextShape.getBBox(); const height = titleRectBox.height + 16 + desTextShapeBBox.height; const width = size[0] > desTextShapeBBox.width + 16 ? size[0] : desTextShapeBBox.width + 16; shape.attr({ width, height }); titleRectShape?.attr('width', width); markerShape?.attr({ x: width, y: height / 2, }); } return shape; }, update: undefined, }, 'single-node', ); G6.registerNode( 'round-rect', { drawShape: (cfg: ModelConfig | undefined = {}, group: IGroup | undefined) => { let size = cfg.size || [100, 30]; if (typeof size === 'number') size = [size, size]; let style = cfg.style || {}; const color = style.stroke || cfg.color || '#5B8FF9'; const fill = style.fill || '#fff'; style = { width: size[0], height: size[1], radius: size[1] / 2, fill, lineWidth: 1.2, stroke: color, ...style, }; const rect = group!.addShape('rect', { attrs: { x: -size[0] / 2, y: -size[1] / 2, ...style, }, name: 'rect-shape', }); // circles for anchor points group!.addShape('circle', { attrs: { x: -size[0] / 2, y: 0, r: 3, fill: style.stroke, }, name: 'circle-shape', }); group!.addShape('circle', { attrs: { x: size[0] / 2, y: 0, r: 3, fill: style.stroke, }, name: 'circle-shape2', }); return rect; }, getAnchorPoints: function getAnchorPoints() { return [ [0, 0.5], [1, 0.5], ]; }, update: function update(cfg: ModelConfig = {}, item: Item) { const group = item.getContainer(); const children = group.get('children'); const node = children[0]; const circleLeft = children[1]; const circleRight = children[2]; const stroke = cfg.style?.stroke || '#5B8FF9'; if (stroke) { node.attr('stroke', stroke); circleLeft.attr('fill', stroke); circleRight.attr('fill', stroke); } }, }, 'single-node', ); G6.registerEdge( 'fund-polyline', { draw: function draw(cfg: ModelConfig | undefined = {}, group: IGroup | undefined) { const startPoint = cfg.startPoint as IPoint; const endPoint = cfg.endPoint as IPoint; const Ydiff = endPoint.y - startPoint.y; const slope = Ydiff !== 0 ? Math.min(500 / Math.abs(Ydiff), 20) : 0; const cpOffset = slope > 15 ? 0 : 16; const offset = Ydiff < 0 ? cpOffset : -cpOffset; const line1EndPoint = { x: startPoint.x + slope, y: endPoint.y + offset, }; const line2StartPoint = { x: line1EndPoint.x + cpOffset, y: endPoint.y, }; // 控制点坐标 const controlPoint = { x: ((line1EndPoint.x - startPoint.x) * (endPoint.y - startPoint.y)) / (line1EndPoint.y - startPoint.y) + startPoint.x, y: endPoint.y, }; let path = [ ['M', startPoint.x, startPoint.y], ['L', line1EndPoint.x, line1EndPoint.y], ['Q', controlPoint.x, controlPoint.y, line2StartPoint.x, line2StartPoint.y], ['L', endPoint.x, endPoint.y], ]; if (Math.abs(Ydiff) <= 5) { path = [ ['M', startPoint.x, startPoint.y], ['L', endPoint.x, endPoint.y], ]; } const { style } = cfg; const stroke = style!.stroke || (cfg?.colorMap && (cfg.colorMap as Object)[cfg.dataType as string]) ? (cfg?.colorMap as Object)[cfg?.dataType as string] : '#5B8FF9'; const endArrow: ArrowConfig | boolean = cfg.style?.endArrow || false; if (isObject(endArrow)) endArrow.fill = stroke; const line = group!.addShape('path', { attrs: { path, stroke, lineWidth: style!.lineWidth || 1.2, endArrow, }, name: 'path-shape', }); const labelLeftOffset = 0; const labelTopOffset = 8; // label let labelTextShape; const textBeginX = line2StartPoint.x + labelLeftOffset; if (cfg?.label) { labelTextShape = group!.addShape('text', { attrs: { text: cfg.label, x: textBeginX, y: endPoint.y - labelTopOffset - 2, fontSize: 14, textAlign: 'left', textBaseline: 'middle', fill: '#000', }, name: 'text-shape-label', }); } // dataType if (cfg?.dataType) { const labelTextShapeBBox = labelTextShape ? labelTextShape.getBBox() : { height: 0 }; group!.addShape('text', { attrs: { text: cfg.dataType, x: textBeginX, y: endPoint.y - labelTopOffset - labelTextShapeBBox.height - 2, fontSize: 10, textAlign: 'left', textBaseline: 'middle', fill: '#000', }, name: 'text-shape-type', }); } // subLabel if (cfg?.subLabel) { group!.addShape('text', { attrs: { text: cfg.subLabel, x: textBeginX, y: endPoint.y + labelTopOffset + 4, fontSize: 12, fontWeight: 300, textAlign: 'left', textBaseline: 'middle', fill: '#000', }, name: 'text-shape-sub-label', }); } return line; }, update: undefined, }, 'single-edge', ); G6.registerEdge('flow-line', { draw(cfg: ModelConfig | undefined = {}, group: IGroup | undefined) { const { startPoint, endPoint } = cfg; const { style = {} } = cfg; const shape = group!.addShape('path', { attrs: { stroke: style.stroke, endArrow: style.endArrow, path: [ ['M', startPoint!.x, startPoint!.y], ['L', startPoint!.x, (startPoint!.y + endPoint!.y) / 2], ['L', endPoint!.x, (startPoint!.y + endPoint!.y) / 2], ['L', endPoint!.x, endPoint!.y], ], }, }); return shape; }, }); }; export const customIconNode = (params: { enableEdit?: boolean; options?: any }) => { G6.registerNode( 'icon-node', { options: { size: [60, 20], stroke: '#91d5ff', fill: '#91d5ff', }, draw(cfg: ModelConfig | undefined = {}, group: IGroup | undefined) { // @ts-ignore const styles = this.getShapeStyle(cfg); const { labelCfg = {} } = cfg; const keyShape = group!.addShape('rect', { attrs: { ...styles, x: 0, y: 0, }, }); /** * leftIcon 格式如下: * { * style: ShapeStyle; * img: '' * } */ let style = { fill: '#e6fffb', }; let img = 'https://g.alicdn.com/cm-design/arms-trace/1.0.155/styles/armsTrace/images/TAIR.png'; if (cfg.leftIcon) { style = { ...style, ...(cfg.leftIcon as any).style }; img = (cfg.leftIcon as any).img; } group!.addShape('rect', { attrs: { x: 1, y: 1, width: 38, height: styles.height - 2, ...style, }, }); group!.addShape('image', { attrs: { x: 8, y: 8, width: 24, height: 24, img, }, name: 'image-shape', }); if (params.enableEdit) { group!.addShape('marker', { attrs: { x: styles.width / 3, y: styles.height + 6, r: 6, stroke: '#73d13d', cursor: 'pointer', symbol: G6.Marker.expand, }, name: 'add-item', }); group!.addShape('marker', { attrs: { x: (styles.width * 2) / 3, y: styles.height + 6, r: 6, stroke: '#ff4d4f', cursor: 'pointer', symbol: G6.Marker.collapse, }, name: 'remove-item', }); } if (cfg.label) { group!.addShape('text', { attrs: { ...labelCfg.style, text: cfg.label, x: styles.width / 2, y: styles.height / 1.5, }, }); } return keyShape; }, }, 'rect', ); };
the_stack
import Cascade from '../cascade/Cascade'; import Computed from '../graph/Computed'; import VirtualNode from './VirtualNode'; import ComponentNode from './ComponentNode'; import Fragment from './Fragment'; import { IVirtualNode, IVirtualNodeProps } from './IVirtualNode'; import Diff, { DiffOperation } from '../util/Diff'; import { CascadeError } from '../util/CascadeError'; // Store ComponentContext in window to prevent multiple Cascade instance problem. export interface IComponentContext { componentContexts: ComponentNode<IVirtualNodeProps>[][]; context: ComponentNode<IVirtualNodeProps>[]; } var componentContext: IComponentContext = window['$_cascade_component_context'] || {}; window['$_cascade_component_context'] = componentContext; componentContext.componentContexts = componentContext.componentContexts || []; componentContext.context = componentContext.context || undefined; export abstract class Component<T> implements IVirtualNode<T> { // TODO: Remove unused uniqueId? uniqueId: number = Math.floor(Math.random() * 1000000); props: T & IVirtualNodeProps; prevProps: T & IVirtualNodeProps; children: any; key: string | number; root: any; element: Node; context: ComponentNode<any>[]; oldContext: ComponentNode<any>[]; mounted: boolean = false; rendered: boolean = false; portal: boolean = false; constructor(props?: T & IVirtualNodeProps, children?: any[]) { this.storeProps(props, children); } storeProps(props?: T & IVirtualNodeProps, children?: any[]) { this.prevProps = this.props; this.props = props || ({} as any); this.key = this.props.key; // TODO: Remove key and ref? // if (this.props.key) { // delete this.props.key; // } this.children = children; this.afterProps(this.mounted); } build() { // Store old context this.oldContext = this.context; // Create a new context Component.pushContext(); // Render var root = this.render(); // Store the new context this.context = Component.popContext(); return root; } init() { // This should subscribe to all observables used by render. Cascade.createComputed(this, 'root', () => { Cascade.wrapContext(() => { this.beforeRender(this.mounted); }); return this.build(); }); // Only update if we are re-rendering Cascade.subscribe(this, 'root', (root: any, oldRoot: any) => { if (this.rendered) { var element = this.element; // Get namespace from current element // If element is an svg, use undefined, as it may change // Otherwise, assume the namespace comes from parent let namespace; if (element && element.nodeName !== 'svg') { let namespaceURI = element.namespaceURI; namespace = (namespaceURI && namespaceURI.endsWith('svg')) ? namespaceURI : undefined; } this.toNode(namespace, oldRoot); // Dispose of old context this.disposeContext(); if (element !== this.element) { if (element) { var parentNode = element.parentNode; if (parentNode) { if (this.element) { parentNode.replaceChild(this.element, element); } else { parentNode.removeChild(element); } } } } } else { this.rendered = true } }); } update(props?: T & IVirtualNodeProps, children?: any[]) { this.storeProps(props, children); this.rendered = false; return Cascade.update(this, 'root'); } abstract render(): any; toNode(namespace?: string, oldRoot?: any): Node { // Get root var root = Cascade.peek(this, 'root') as any; // Store old element var oldElement = this.element; var element: Node; var rootType = typeof root; var noDispose: boolean = false; // Test if we must diff. // If we have an old root, we may need to diff. if (oldRoot && typeof oldRoot === rootType) { switch (rootType) { case 'string': if (root !== oldRoot) { element = document.createTextNode(root as string); } else { element = oldElement; } break; case 'object': if (root) { if (root instanceof ComponentNode) { // Root is a Component if (root.componentConstructor === oldRoot.componentConstructor && root.key === oldRoot.key) { // Root and OldRoot are both the same Component - Diff this case if (oldRoot.component instanceof Fragment) { element = this.diffFragments(root, oldRoot, oldElement, namespace); } else { element = this.diffComponents(root, oldRoot, namespace); swapChildren(element, oldElement); } noDispose = true; } else { // Root is a different Component element = root.toNode(namespace); } } else if (root.type) { // Root is a VirtualNode if (root.type === oldRoot.type && root.key === oldRoot.key) { // Root and OldRoot are both the same VirtualNode - Diff this case root.element = oldElement; element = this.diffVirtualNodes(root, oldRoot, oldElement as HTMLElement, namespace); } else { // Root is a different VirtualNode element = root.toNode(namespace); } } else { // Root is an Object element = document.createTextNode(root.toString()); } // Ignore Null } break; case 'undefined': // Ignore Undefined break; // Number and anything else // case 'number': default: if (root !== oldRoot) { // Render to a string element = document.createTextNode(root.toString()); } else { // Root and OldRoot are the same element = oldElement; } break; } } else { switch (rootType) { case 'string': element = document.createTextNode(root as string); break; case 'object': if (root) { if (root.toNode) { element = root.toNode(namespace); } else { element = document.createTextNode(root.toString()); } } // Ignore Null break; case 'undefined': // Ignore Undefined break; // Number and anything else // case 'number': default: element = document.createTextNode(root.toString()); break; } } if (this.props && this.props.ref) { if (typeof this.props.ref === 'function') { this.props.ref(element); } else { this.props.ref.current = element; } } if (!noDispose && oldRoot && oldRoot instanceof ComponentNode) { //oldRoot.dispose(); } this.afterRender(element, this.mounted); if (!element) { element = document.createComment('Empty Component'); } this.element = element; this.rendered = true; this.mounted = true; if (this.portal) { element = document.createComment('Empty Component'); } return element; } dispose() { var computed = Cascade.getObservable(this, 'root') as Computed<any>; computed.dispose(); if (this.context) { for (var index = 0, length = this.context.length; index < length; index++) { let component = this.context[index]; component.dispose(); } } this.afterDispose(this.element); } disposeContext() { if (this.oldContext) { for (var index = 0, length = this.oldContext.length; index < length; index++) { let component = this.oldContext[index]; component.dispose(); } } } afterProps(updating: boolean) { } beforeRender(updating: boolean) { } afterRender(node: Node, updating: boolean) { } afterDispose(node: Node) { } diffFragments(newRootComponentNode: ComponentNode<IVirtualNodeProps>, oldRootComponentNode: ComponentNode<IVirtualNodeProps>, oldElement: Node, namespace: string, offsetIndex: number = 0) { var output: Node; let oldRoot: Fragment = oldRootComponentNode.component as any; oldRootComponentNode.component = undefined; newRootComponentNode.component = oldRoot as any; oldRoot.update(newRootComponentNode.props, newRootComponentNode.children); this.diffVirtualNodes(oldRoot as any, oldRoot as any, oldElement as any, namespace, offsetIndex); return oldElement; } diffComponents(newRootComponentNode: ComponentNode<IVirtualNodeProps>, oldRootComponentNode: ComponentNode<IVirtualNodeProps>, namespace: string) { // No diff necessary. We have the exact same Components if (newRootComponentNode === oldRootComponentNode) { return oldRootComponentNode.component.element; } // We have already rendered newRootComponentNode. It is likely a child Component. if (newRootComponentNode.component) { return newRootComponentNode.component.element; } var output: Node; let oldRoot = oldRootComponentNode.component; // This should never happen if (!oldRoot) { throw new Error(CascadeError.NoOldComponent); } let oldElement = oldRoot.element; oldRootComponentNode.component = undefined; newRootComponentNode.component = oldRoot; let innerOldRoot = Cascade.peekDirty(oldRoot, 'root'); let innerRoot = oldRoot.update(newRootComponentNode.props, newRootComponentNode.children); if (!innerOldRoot) { // We are replacing switch (typeof innerRoot) { case 'object': if (innerRoot) { if (innerRoot.toNode) { output = innerRoot.toNode(namespace); } else { output = document.createTextNode(innerRoot.toString()); } } break; case 'undefined': break; default: output = document.createTextNode(innerRoot.toString()); } } else { switch (typeof innerRoot) { case 'object': if (innerRoot) { // InnerRoot is not Null if (innerRoot instanceof ComponentNode) { // InnerRoot is a Component if (innerOldRoot instanceof ComponentNode && innerRoot.componentConstructor === innerOldRoot.componentConstructor && innerRoot.key === innerOldRoot.key) { // InnerRoot is the same Component as InnerOldRoot - Diff this case if (innerOldRoot.component instanceof Fragment) { output = this.diffFragments(innerRoot, innerOldRoot, oldElement, namespace); } else { output = this.diffComponents(innerRoot, innerOldRoot, namespace); swapChildren(output, oldElement); } } else { // Replace output = innerRoot.toNode(namespace); // Dispose innerOldRoot innerOldRoot.dispose(); } } else if (innerRoot instanceof VirtualNode) { if (innerOldRoot instanceof VirtualNode && innerRoot.type === innerOldRoot.type && innerRoot.key === innerOldRoot.key) { // InnerRoot is the same VirtualNode as InnerOldRoot - Diff this case output = this.diffVirtualNodes(innerRoot, innerOldRoot, oldElement as HTMLElement, namespace); } else { // Replace output = innerRoot.toNode(namespace); } } } // Ignore Null break; case 'undefined': // Ignore Undefined break; case 'string': if (innerRoot === innerOldRoot) { // InnerRoot is the same as InnerOldRoot output = oldElement; } else { // Replace output = document.createTextNode(innerRoot); } break; default: if (innerRoot === innerOldRoot) { // InnerRoot is the same as InnerOldRoot output = oldElement; } else { // Replace output = document.createTextNode(innerRoot.toString()); } } } // Call the ref for oldRoot if (oldRoot.props.ref) { if (typeof oldRoot.props.ref === 'function') { oldRoot.props.ref(output); } else { oldRoot.props.ref.current = output; } } if (oldRoot.afterRender) { oldRoot.afterRender(output, true); } if (!output) { output = document.createComment('Empty Component'); } oldRoot.element = output; if (oldRoot.portal) { output = document.createComment('Empty Component'); } return output; } diffVirtualNodes(newRoot: VirtualNode<IVirtualNodeProps>, oldRoot: VirtualNode<IVirtualNodeProps>, oldElement: HTMLElement, namespace: string, offsetIndex?: number) { // TODO: This case should not happen. if (!oldRoot || oldRoot.type !== newRoot.type) { // We are cleanly replacing oldElement = newRoot.toNode(namespace); } else if (newRoot === oldRoot) { // No diff necessary. We have the exact same VirtualNodes } else { // Old and New Roots match var diff = Diff.compare(oldRoot.children, newRoot.children, compareVirtualNodes); var propertyDiff = Diff.compareHash(oldRoot.props, newRoot.props); namespace = namespace || ((oldElement && oldElement.namespaceURI && oldElement.namespaceURI.endsWith('svg')) ? oldElement.namespaceURI : undefined) var childIndex = oldRoot.children.length - 1 + (offsetIndex || 0); for (var index = 0, length = diff.length; index < length; index++) { var diffItem = diff[index]; switch (diffItem.operation) { case DiffOperation.REMOVE: var oldChild = diffItem.item; // We need to know if oldChild is a Fragment or a Component with a root Fragment if (oldChild.component && oldChild.component.element.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { let fragmentLength = oldChild.component.getChildLength(); let fragmentIndexLength = fragmentLength + childIndex; for (let fragmentIndex = childIndex; fragmentIndex < fragmentIndexLength; fragmentIndex++) { oldElement.removeChild(oldElement.childNodes[fragmentIndex]); } childIndex -= fragmentLength; } else { oldElement.removeChild(oldElement.childNodes[childIndex]); childIndex--; } break; case DiffOperation.NONE: var newChild = diffItem.itemB; var oldChild = diffItem.item; // Diff recursively // TODO: Remove extra casts if (typeof newChild === 'object') { if (newChild instanceof ComponentNode) { if (oldChild.component instanceof Fragment) { this.diffVirtualNodes(newChild as any, oldChild, oldElement.childNodes[childIndex] as HTMLElement, namespace, childIndex); } else { let newNode = this.diffComponents(newChild, oldChild, namespace); swapChildren(newNode, oldElement.childNodes[childIndex] as HTMLElement, oldElement, childIndex); } } else if (newChild instanceof VirtualNode) { // TODO: This is the only case where we don't know if oldChild exists and has the same type as newChild. // Perhaps we should figure that out here intead of inside diffVirtualNodes. this.diffVirtualNodes(newChild as any, oldChild as any, oldElement.childNodes[childIndex] as HTMLElement, namespace); } } childIndex--; break; case DiffOperation.ADD: var newChild = diffItem.item; var newElement; // TODO: Null and Undefined should never happen switch (typeof newChild) { case 'string': newElement = document.createTextNode(newChild as string); oldElement.insertBefore(newElement, oldElement.childNodes[childIndex + 1]); break; case 'object': if (newChild) { if ((newChild as any).toNode) { newElement = (newChild as any).toNode(namespace); } else { newElement = document.createTextNode(newChild.toString()); } oldElement.insertBefore(newElement, oldElement.childNodes[childIndex + 1]); } break; // case 'undefined': // break; // Number and anything else // case 'number': default: newElement = document.createTextNode(newChild.toString()); oldElement.insertBefore(newElement, oldElement.childNodes[childIndex + 1]); break; } break; } } for (var name in propertyDiff) { if (propertyDiff.hasOwnProperty(name)) { var property = propertyDiff[name]; if (property === null) { VirtualNode.removeAttribute(oldElement, name, namespace); } else { VirtualNode.setAttribute(oldElement, name, property, namespace); } } } // Call the ref for newRoot if (newRoot.props.ref) { if (typeof newRoot.props.ref === 'function') { newRoot.props.ref(oldElement); } else { newRoot.props.ref.current = oldElement; } } } return oldElement; } getChildLength() { let root = Cascade.peekDirty(this, 'root') as any; if (root instanceof ComponentNode && root.component.getChildLength) { return root.component.getChildLength(); } else { return 1; } } static getContext() { return componentContext.context; } static pushContext() { componentContext.context = []; componentContext.componentContexts.unshift(componentContext.context); return componentContext.context; } static popContext() { var oldContext = componentContext.componentContexts.shift(); componentContext.context = componentContext.componentContexts[0]; return oldContext; } } function compareVirtualNodes(nodeA: any, nodeB: any) { var typeA = typeof nodeA; var typeB = typeof nodeB; if (typeA === typeB) { // The two are of the same type switch (typeA) { case 'object': // If nodeA and nodeB are both IVirtualNodes if (nodeA && nodeB && (nodeA as any).toNode && (nodeB as any).toNode) { if ((nodeA as IVirtualNode<IVirtualNodeProps>).key === (nodeB as IVirtualNode<IVirtualNodeProps>).key) { if (nodeA instanceof ComponentNode) { return nodeA.componentConstructor === nodeB.componentConstructor; } else { return (nodeA as VirtualNode<IVirtualNodeProps>).type === (nodeB as VirtualNode<IVirtualNodeProps>).type; } } else { return false; } } else { // This covers null return nodeA === nodeB; } // case 'undefined'; // case 'string': // case 'number': default: return nodeA === nodeB; } } else { return false; } } function swapChildren(newNode: Node, oldNode: Node, parent?: HTMLElement, index?: number) { if (newNode) { if (newNode !== oldNode) { if (oldNode && oldNode.parentNode) { oldNode.parentNode.replaceChild(newNode, oldNode); } else if (parent) { parent.insertBefore(newNode, parent.childNodes[index + 1]); } } } else { if (oldNode && oldNode.parentNode) { oldNode.parentNode.removeChild(oldNode); } } }
the_stack
import { ExtensionTypes, RequestLogicTypes } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; import Erc777StreamPaymentNetwork from '../../../../src/extensions/payment-network/erc777/stream'; import * as DataERC777StreamAddData from '../../../utils/payment-network/erc777/stream-add-data-generator'; import * as DataERC777StreamCreate from '../../../utils/payment-network/erc777/stream-create-data-generator'; import * as TestData from '../../../utils/test-data-generator'; const erc777StreamPaymentNetwork = new Erc777StreamPaymentNetwork(); /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('extensions/payment-network/erc777/stream', () => { describe('createCreationAction', () => { it('can create a create action with all parameters', () => { expect( erc777StreamPaymentNetwork.createCreationAction({ expectedFlowRate: '0x0000000000000000000000000000000000000001', expectedStartDate: '0', paymentAddress: '0x0000000000000000000000000000000000000002', refundAddress: '0x0000000000000000000000000000000000000003', salt: 'ea3bc7caf64110ca', }), ).toEqual({ action: 'create', id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC777_STREAM, parameters: { expectedFlowRate: '0x0000000000000000000000000000000000000001', expectedStartDate: '0', paymentAddress: '0x0000000000000000000000000000000000000002', refundAddress: '0x0000000000000000000000000000000000000003', salt: 'ea3bc7caf64110ca', }, version: '0.1.0', }); }); describe('createAddPaymentAddressAction', () => { it('can createAddPaymentAddressAction', () => { expect( erc777StreamPaymentNetwork.createAddPaymentAddressAction({ paymentAddress: '0x0000000000000000000000000000000000000001', }), ).toEqual({ action: ExtensionTypes.PnReferenceBased.ACTION.ADD_PAYMENT_ADDRESS, id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC777_STREAM, parameters: { paymentAddress: '0x0000000000000000000000000000000000000001', }, }); }); it('cannot createAddPaymentAddressAction with payment address not an ethereum address', () => { // 'must throw' expect(() => { erc777StreamPaymentNetwork.createAddPaymentAddressAction({ paymentAddress: 'not an ethereum address', }); }).toThrowError("paymentAddress 'not an ethereum address' is not a valid address"); }); }); describe('createAddRefundAddressAction', () => { it('can createAddRefundAddressAction', () => { expect( erc777StreamPaymentNetwork.createAddRefundAddressAction({ refundAddress: '0x0000000000000000000000000000000000000002', }), ).toEqual({ action: ExtensionTypes.PnReferenceBased.ACTION.ADD_REFUND_ADDRESS, id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC777_STREAM, parameters: { refundAddress: '0x0000000000000000000000000000000000000002', }, }); }); it('cannot createAddRefundAddressAction with payment address not an ethereum address', () => { // 'must throw' expect(() => { erc777StreamPaymentNetwork.createAddRefundAddressAction({ refundAddress: 'not an ethereum address', }); }).toThrowError("refundAddress 'not an ethereum address' is not a valid address"); }); }); describe('applyActionToExtension', () => { describe('applyActionToExtension/unknown action', () => { it('cannot applyActionToExtensions of unknown action', () => { const unknownAction = Utils.deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); unknownAction.action = 'unknown action' as any; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateCreatedEmpty.extensions, unknownAction, DataERC777StreamCreate.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('Unknown action: unknown action'); }); it('cannot applyActionToExtensions of unknown id', () => { const unknownAction = Utils.deepCopy(DataERC777StreamAddData.actionAddPaymentAddress); unknownAction.id = 'unknown id' as any; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateCreatedEmpty.extensions, unknownAction, DataERC777StreamCreate.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('The extension should be created before receiving any other action'); }); }); describe('applyActionToExtension/create', () => { it('can applyActionToExtensions of creation', () => { // 'new extension state wrong' expect( erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateNoExtensions.extensions, DataERC777StreamCreate.actionCreationFull, DataERC777StreamCreate.requestStateNoExtensions, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(DataERC777StreamCreate.extensionFullState); }); it('cannot applyActionToExtensions of creation with a previous state', () => { // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestFullStateCreated.extensions, DataERC777StreamCreate.actionCreationFull, DataERC777StreamCreate.requestFullStateCreated, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('This extension has already been created'); }); it('cannot applyActionToExtensions of creation on a non ERC777 request', () => { const requestCreatedNoExtension: RequestLogicTypes.IRequest = Utils.deepCopy( TestData.requestCreatedNoExtension, ); requestCreatedNoExtension.currency = { type: RequestLogicTypes.CURRENCY.BTC, value: 'BTC', }; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( TestData.requestCreatedNoExtension.extensions, DataERC777StreamCreate.actionCreationFull, requestCreatedNoExtension, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('This extension can be used only on ERC777 requests'); }); it('cannot applyActionToExtensions of creation with payment address not valid', () => { const testnetPaymentAddress = Utils.deepCopy(DataERC777StreamCreate.actionCreationFull); testnetPaymentAddress.parameters.paymentAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateNoExtensions.extensions, testnetPaymentAddress, DataERC777StreamCreate.requestStateNoExtensions, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError( `paymentAddress '${DataERC777StreamAddData.invalidAddress}' is not a valid address`, ); }); it('cannot applyActionToExtensions of creation with refund address not valid', () => { const testnetRefundAddress = Utils.deepCopy(DataERC777StreamCreate.actionCreationFull); testnetRefundAddress.parameters.refundAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateNoExtensions.extensions, testnetRefundAddress, DataERC777StreamCreate.requestStateNoExtensions, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError( `refundAddress '${DataERC777StreamAddData.invalidAddress}' is not a valid address`, ); }); it('keeps the version used at creation', () => { const newState = erc777StreamPaymentNetwork.applyActionToExtension( {}, { ...DataERC777StreamCreate.actionCreationFull, version: 'ABCD' }, DataERC777StreamCreate.requestStateNoExtensions, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); expect(newState[erc777StreamPaymentNetwork.extensionId].version).toBe('ABCD'); }); it('requires a version at creation', () => { expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( {}, { ...DataERC777StreamCreate.actionCreationFull, version: '' }, DataERC777StreamCreate.requestStateNoExtensions, TestData.otherIdRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('version is required at creation'); }); }); describe('applyActionToExtension/addPaymentAddress', () => { it('can applyActionToExtensions of addPaymentAddress', () => { // 'new extension state wrong' expect( erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateCreatedEmpty.extensions, DataERC777StreamAddData.actionAddPaymentAddress, DataERC777StreamCreate.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(DataERC777StreamAddData.extensionStateWithPaymentAfterCreation); }); it('cannot applyActionToExtensions of addPaymentAddress without a previous state', () => { // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateNoExtensions.extensions, DataERC777StreamAddData.actionAddPaymentAddress, DataERC777StreamCreate.requestStateNoExtensions, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addPaymentAddress without a payee', () => { const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); previousState.payee = undefined; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( previousState.extensions, DataERC777StreamAddData.actionAddPaymentAddress, previousState, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The request must have a payee`); }); it('cannot applyActionToExtensions of addPaymentAddress signed by someone else than the payee', () => { const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( previousState.extensions, DataERC777StreamAddData.actionAddPaymentAddress, previousState, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payee`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address already given', () => { // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestFullStateCreated.extensions, DataERC777StreamAddData.actionAddPaymentAddress, DataERC777StreamCreate.requestFullStateCreated, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`Payment address already given`); }); it('cannot applyActionToExtensions of addPaymentAddress with payment address not valid', () => { const testnetPaymentAddress = Utils.deepCopy( DataERC777StreamAddData.actionAddPaymentAddress, ); testnetPaymentAddress.parameters.paymentAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateCreatedEmpty.extensions, testnetPaymentAddress, DataERC777StreamCreate.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError( `paymentAddress '${DataERC777StreamAddData.invalidAddress}' is not a valid address`, ); }); }); describe('applyActionToExtension/addRefundAddress', () => { it('can applyActionToExtensions of addRefundAddress', () => { // 'new extension state wrong' expect( erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateCreatedEmpty.extensions, DataERC777StreamAddData.actionAddRefundAddress, DataERC777StreamCreate.requestStateCreatedEmpty, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ), ).toEqual(DataERC777StreamAddData.extensionStateWithRefundAfterCreation); }); it('cannot applyActionToExtensions of addRefundAddress without a previous state', () => { // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateNoExtensions.extensions, DataERC777StreamAddData.actionAddRefundAddress, DataERC777StreamCreate.requestStateNoExtensions, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The extension should be created before receiving any other action`); }); it('cannot applyActionToExtensions of addRefundAddress without a payer', () => { const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); previousState.payer = undefined; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( previousState.extensions, DataERC777StreamAddData.actionAddRefundAddress, previousState, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The request must have a payer`); }); it('cannot applyActionToExtensions of addRefundAddress signed by someone else than the payer', () => { const previousState = Utils.deepCopy(DataERC777StreamCreate.requestStateCreatedEmpty); // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( previousState.extensions, DataERC777StreamAddData.actionAddRefundAddress, previousState, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`The signer must be the payer`); }); it('cannot applyActionToExtensions of addRefundAddress with payment address already given', () => { // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestFullStateCreated.extensions, DataERC777StreamAddData.actionAddRefundAddress, DataERC777StreamCreate.requestFullStateCreated, TestData.payerRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError(`Refund address already given`); }); it('cannot applyActionToExtensions of addRefundAddress with refund address not valid', () => { const testnetPaymentAddress = Utils.deepCopy( DataERC777StreamAddData.actionAddRefundAddress, ); testnetPaymentAddress.parameters.refundAddress = DataERC777StreamAddData.invalidAddress; // 'must throw' expect(() => { erc777StreamPaymentNetwork.applyActionToExtension( DataERC777StreamCreate.requestStateCreatedEmpty.extensions, testnetPaymentAddress, DataERC777StreamCreate.requestStateCreatedEmpty, TestData.payeeRaw.identity, TestData.arbitraryTimestamp, ); }).toThrowError('refundAddress is not a valid address'); }); }); }); }); });
the_stack
import { cosmiconfigSync } from "cosmiconfig"; import { JSONPath } from "jsonpath-plus"; import path from "path"; import { EmittedAsset } from "rollup"; import { findChunk, getOutputFilenameFromChunk, isJsonFilePath, } from "../utils/helpers"; import { ChromeExtensionManifest } from "../manifest"; import { ManifestInputPlugin, ManifestInputPluginCache, ManifestInputPluginOptions, } from "../plugin-options"; import { cloneObject } from "../utils/cloneObject"; import { manifestName } from "./common/constants"; import { generateManifest } from "./generateBundle"; import { combinePerms } from "./manifest-parser/combine"; import { deriveFiles, } from "./manifest-parser/index"; import { validateManifest, ValidationErrorsArray, } from "./manifest-parser/validate"; import { reduceToRecord } from "./reduceToRecord"; import { join } from "path"; import { getAssets, getChunk } from "../utils/bundle"; import slash from "slash"; export const explorer = cosmiconfigSync("manifest", { cache: false, }); const name = "manifest-input"; const npmPkgDetails = process.env.npm_package_name && process.env.npm_package_version && process.env.npm_package_description ? { name: process.env.npm_package_name, version: process.env.npm_package_version, description: process.env.npm_package_description, } : { name: "", version: "", description: "", }; /* ============================================ */ /* MANIFEST-INPUT */ /* ============================================ */ export function manifestInput( { browserPolyfill = false, contentScriptWrapper = true, crossBrowser = false, dynamicImportWrapper = {}, extendManifest = {}, firstClassManifest = true, iifeJsonPaths = [], pkg = npmPkgDetails, publicKey, cache = { assetChanged: false, assets: [], iife: [], input: [], inputAry: [], inputObj: {}, permsHash: "", readFile: new Map<string, any>(), srcDir: null, } as ManifestInputPluginCache, } = {} as ManifestInputPluginOptions, ): ManifestInputPlugin { /* ----------- HOOKS CLOSURES START ----------- */ let manifestPath: string; /* ------------ HOOKS CLOSURES END ------------ */ /* --------------- plugin object -------------- */ return { name, browserPolyfill, crossBrowser, get srcDir() { return cache.srcDir; }, get formatMap() { return { iife: cache.iife }; }, /* ============================================ */ /* OPTIONS HOOK */ /* ============================================ */ options(options) { // Do not reload manifest without changes if (!cache.manifest) { /* ----------- LOAD AND PROCESS MANIFEST ----------- */ let inputManifestPath: string | undefined; if (Array.isArray(options.input)) { const manifestIndex = options.input.findIndex( isJsonFilePath, ); inputManifestPath = options.input[manifestIndex]; cache.inputAry = [ ...options.input.slice(0, manifestIndex), ...options.input.slice(manifestIndex + 1), ]; } else if (typeof options.input === "object") { inputManifestPath = options.input.manifest; cache.inputObj = cloneObject(options.input); delete cache.inputObj["manifest"]; } else { inputManifestPath = options.input; } if (!isJsonFilePath(inputManifestPath)) { throw new TypeError( "RollupOptions.input must be a single Chrome extension manifest.", ); } // Load content of manifest.json const configResult = explorer.load( inputManifestPath, ) as { filepath: string, config: ChromeExtensionManifest, isEmpty?: true, }; if (configResult.isEmpty) { throw new Error(`${options.input} is an empty file.`); } const { options_page, options_ui } = configResult.config; if ( options_page !== undefined && options_ui !== undefined ) { throw new Error( "options_ui and options_page cannot both be defined in manifest.json.", ); } manifestPath = configResult.filepath; if (typeof extendManifest === "function") { cache.manifest = extendManifest(configResult.config); } else if (typeof extendManifest === "object") { cache.manifest = { ...configResult.config, ...extendManifest, }; } else { cache.manifest = configResult.config; } cache.srcDir = path.dirname(manifestPath); if (firstClassManifest) { cache.iife = iifeJsonPaths .map((jsonPath) => { const result = JSONPath({ path: jsonPath, json: cache.manifest!, }); return result; }) .flat(Infinity); // Derive entry paths from manifest const { js, html, css, img, others } = deriveFiles( cache.manifest, cache.srcDir, ); // Cache derived inputs cache.input = [...cache.inputAry, ...js, ...html]; cache.assets = [ // Dedupe assets ...new Set([...css, ...img, ...others]), ]; } /* --------------- END LOAD MANIFEST --------------- */ } const finalInput = cache.input.reduce( reduceToRecord(cache.srcDir), cache.inputObj, ); return { ...options, input: finalInput }; }, /* ============================================ */ /* GENERATEBUNDLE */ /* ============================================ */ generateBundle(options, bundle) { /* ----------------- GET CHUNKS -----------------*/ const chunks = getChunk(bundle); const assets = getAssets(bundle); if (Object.keys(bundle).length === 0) { throw new Error( "The manifest must have at least one asset (html or css) or script file.", ); } try { // Clone cache.manifest if (!cache.manifest) // This is a programming error, so it should throw throw new TypeError(`cache.manifest is ${typeof cache.manifest}`); const clonedManifest = cloneObject(cache.manifest); const manifestBody: ChromeExtensionManifest = validateManifest({ description: pkg.description, ...clonedManifest, permissions: combinePerms( clonedManifest.permissions || [], ), } as ChromeExtensionManifest); const { content_scripts: cts = [], web_accessible_resources: war = [], background: { service_worker: sw = "" } = {}, } = manifestBody; /* ------------- SETUP CONTENT SCRIPTS ------------- */ manifestBody.content_scripts = cts.map( ({ js, ...rest }) => typeof js === "undefined" ? rest : { js: js .map(filename => getOutputFilenameFromChunk(join(cache.srcDir!, filename), Object.values(chunks))) .filter(filename => !!filename) .map((p) => slash(p)), ...rest, }, ); /* ------------ SETUP BACKGROUND SCRIPTS ----------- */ if (sw && manifestBody.background && manifestBody.background.service_worker) { // make background chunk output in the same directory as manifest.json const chunk = findChunk(join(cache.srcDir!, manifestBody.background.service_worker), chunks); if (chunk) { // remove original chunk delete bundle[chunk.fileName]; // change background chunk output in the same directory as manifest.json chunk.fileName = chunk.fileName.replace(/assets\//, ""); bundle[chunk.fileName] = chunk; manifestBody.background.service_worker = chunk.fileName; } } /* ------------ SETUP ASSETS IN WEB ACCESSIBLE RESOURCES ----------- */ manifestBody.web_accessible_resources = [ ...war, { resources: Object.keys(assets), matches: ["<all_urls>"] }]; /* --------- STABLE EXTENSION ID -------- */ if (publicKey) manifestBody.key = publicKey; /* ----------- OUTPUT MANIFEST.JSON ---------- */ generateManifest(this, manifestBody); } catch (error) { // Catch here because we need the validated result in scope if (error.name !== "ValidationError") throw error; const errors = error.errors as ValidationErrorsArray; if (errors) { errors.forEach((err) => { // FIXME: make a better validation error message // https://github.com/atlassian/better-ajv-errors this.warn(JSON.stringify(err, undefined, 2)); }); } this.error(error.message); } }, }; } export default manifestInput;
the_stack
import { OwnerStakeByStatus, StakeInfo, StakeStatus, StoredBalance } from '@0x/contracts-staking'; import { constants } from '@0x/contracts-test-utils'; import { BigNumber } from '@0x/utils'; import '@azure/core-asynciterator-polyfill'; import * as _ from 'lodash'; import { AssertionResult } from '../assertions/function_assertion'; import { assetProxyTransferFailedAssertion } from '../assertions/generic_assertions'; import { moveStakeNonexistentPoolAssertion, validMoveStakeAssertion } from '../assertions/moveStake'; import { validStakeAssertion } from '../assertions/stake'; import { invalidUnstakeAssertion, validUnstakeAssertion } from '../assertions/unstake'; import { invalidWithdrawDelegatorRewardsAssertion, validWithdrawDelegatorRewardsAssertion, } from '../assertions/withdrawDelegatorRewards'; import { Pseudorandom } from '../utils/pseudorandom'; import { Actor, Constructor } from './base'; export interface StakerInterface { stakeAsync: (amount: BigNumber, poolId?: string) => Promise<void>; } /** * This mixin encapsulates functionality associated with stakers within the 0x ecosystem. * This includes staking ZRX (and optionally delegating it to a specific pool). */ export function StakerMixin<TBase extends Constructor>(Base: TBase): TBase & Constructor<StakerInterface> { return class extends Base { public stake: OwnerStakeByStatus; public readonly actor: Actor; /** * The mixin pattern requires that this constructor uses `...args: any[]`, but this class * really expects a single `ActorConfig` parameter (assuming `Actor` is used as the base * class). */ constructor(...args: any[]) { // tslint:disable-next-line:no-inferred-empty-object-type super(...args); this.actor = (this as any) as Actor; this.actor.mixins.push('Staker'); this.stake = { [StakeStatus.Undelegated]: new StoredBalance(), [StakeStatus.Delegated]: { total: new StoredBalance() }, }; // Register this mixin's assertion generators this.actor.simulationActions = { ...this.actor.simulationActions, validStake: this._validStake(), invalidStake: this._invalidStake(), validUnstake: this._validUnstake(), invalidUnstake: this._invalidUnstake(), validMoveStake: this._validMoveStake(), moveStakeNonexistentPool: this._moveStakeNonexistentPool(), validWithdrawDelegatorRewards: this._validWithdrawDelegatorRewards(), invalidWithdrawDelegatorRewards: this._invalidWithdrawDelegatorRewards(), }; } /** * Stakes the given amount of ZRX. If `poolId` is provided, subsequently delegates the newly * staked ZRX with that pool. */ public async stakeAsync(amount: BigNumber, poolId?: string): Promise<void> { const { stakingWrapper } = this.actor.deployment.staking; await stakingWrapper.stake(amount).awaitTransactionSuccessAsync({ from: this.actor.address, }); if (poolId !== undefined) { await stakingWrapper .moveStake( new StakeInfo(StakeStatus.Undelegated), new StakeInfo(StakeStatus.Delegated, poolId), amount, ) .awaitTransactionSuccessAsync({ from: this.actor.address }); } } private async *_validStake(): AsyncIterableIterator<AssertionResult> { const { zrx } = this.actor.deployment.tokens; const { deployment, balanceStore } = this.actor.simulationEnvironment!; const assertion = validStakeAssertion(deployment, this.actor.simulationEnvironment!, this.stake); while (true) { await balanceStore.updateErc20BalancesAsync(); const zrxBalance = balanceStore.balances.erc20[this.actor.address][zrx.address]; const amount = Pseudorandom.integer(0, zrxBalance); yield assertion.executeAsync([amount], { from: this.actor.address }); } } private async *_invalidStake(): AsyncIterableIterator<AssertionResult> { const { zrx } = this.actor.deployment.tokens; const { deployment, balanceStore } = this.actor.simulationEnvironment!; const assertion = assetProxyTransferFailedAssertion(deployment.staking.stakingWrapper, 'stake'); while (true) { await balanceStore.updateErc20BalancesAsync(); const zrxBalance = balanceStore.balances.erc20[this.actor.address][zrx.address]; const amount = Pseudorandom.integer(zrxBalance.plus(1), constants.MAX_UINT256); yield assertion.executeAsync([amount], { from: this.actor.address }); } } private async *_validUnstake(): AsyncIterableIterator<AssertionResult> { const { stakingWrapper } = this.actor.deployment.staking; const { deployment, balanceStore } = this.actor.simulationEnvironment!; const assertion = validUnstakeAssertion(deployment, this.actor.simulationEnvironment!, this.stake); while (true) { await balanceStore.updateErc20BalancesAsync(); const undelegatedStake = await stakingWrapper .getOwnerStakeByStatus(this.actor.address, StakeStatus.Undelegated) .callAsync(); const withdrawableStake = BigNumber.min( undelegatedStake.currentEpochBalance, undelegatedStake.nextEpochBalance, ); const amount = Pseudorandom.integer(0, withdrawableStake); yield assertion.executeAsync([amount], { from: this.actor.address }); } } private async *_invalidUnstake(): AsyncIterableIterator<AssertionResult> { const { stakingWrapper } = this.actor.deployment.staking; const { deployment, balanceStore } = this.actor.simulationEnvironment!; while (true) { await balanceStore.updateErc20BalancesAsync(); const undelegatedStake = await stakingWrapper .getOwnerStakeByStatus(this.actor.address, StakeStatus.Undelegated) .callAsync(); const withdrawableStake = BigNumber.min( undelegatedStake.currentEpochBalance, undelegatedStake.nextEpochBalance, ); const assertion = invalidUnstakeAssertion(deployment, withdrawableStake); const amount = Pseudorandom.integer(withdrawableStake.plus(1), constants.MAX_UINT256); yield assertion.executeAsync([amount], { from: this.actor.address }); } } private _validMoveParams(): [StakeInfo, StakeInfo, BigNumber] { const { stakingPools, currentEpoch } = this.actor.simulationEnvironment!; // Pick a random pool that this staker has delegated to (undefined if no such pools exist) const fromPoolId = Pseudorandom.sample(Object.keys(_.omit(this.stake[StakeStatus.Delegated], ['total']))); // The `from` status must be Undelegated if the staker isn't delegated to any pools // at the moment, or if the chosen pool is unfinalized const fromStatus = fromPoolId === undefined || stakingPools[fromPoolId].lastFinalized.isLessThan(currentEpoch.minus(1)) ? StakeStatus.Undelegated : (Pseudorandom.sample( [StakeStatus.Undelegated, StakeStatus.Delegated], [0.2, 0.8], // 20% chance of `Undelegated`, 80% chance of `Delegated` ) as StakeStatus); const from = new StakeInfo(fromStatus, fromPoolId); // Pick a random pool to move the stake to const toPoolId = Pseudorandom.sample(Object.keys(stakingPools)); // The `from` status must be Undelegated if no pools exist in the simulation yet, // or if the chosen pool is unfinalized const toStatus = toPoolId === undefined || stakingPools[toPoolId].lastFinalized.isLessThan(currentEpoch.minus(1)) ? StakeStatus.Undelegated : (Pseudorandom.sample( [StakeStatus.Undelegated, StakeStatus.Delegated], [0.2, 0.8], // 20% chance of `Undelegated`, 80% chance of `Delegated` ) as StakeStatus); const to = new StakeInfo(toStatus, toPoolId); // The next epoch balance of the `from` stake is the amount that can be moved const moveableStake = from.status === StakeStatus.Undelegated ? this.stake[StakeStatus.Undelegated].nextEpochBalance : this.stake[StakeStatus.Delegated][from.poolId].nextEpochBalance; const amount = Pseudorandom.integer(0, moveableStake); return [from, to, amount]; } private async *_validMoveStake(): AsyncIterableIterator<AssertionResult> { const assertion = validMoveStakeAssertion( this.actor.deployment, this.actor.simulationEnvironment!, this.stake, ); while (true) { const [from, to, amount] = this._validMoveParams(); yield assertion.executeAsync([from, to, amount], { from: this.actor.address }); } } private async *_moveStakeNonexistentPool(): AsyncIterableIterator<AssertionResult> { while (true) { const [from, to, amount] = this._validMoveParams(); // If there is 0 moveable stake for the sampled `to` pool, we need to mutate the // `from` info, otherwise `moveStake` will just noop if (amount.isZero()) { from.poolId = Pseudorandom.hex(); // Status must be delegated and amount must be nonzero to trigger _assertStakingPoolExists from.status = StakeStatus.Delegated; const randomAmount = Pseudorandom.integer(1, constants.MAX_UINT256); const assertion = moveStakeNonexistentPoolAssertion(this.actor.deployment, from.poolId); yield assertion.executeAsync([from, to, randomAmount], { from: this.actor.address }); } else { // One or both of the `from` and `to` poolId are invalid const infoToMutate = Pseudorandom.sample([[from], [to], [from, to]]); let nonExistentPoolId; for (const info of infoToMutate!) { info.poolId = Pseudorandom.hex(); nonExistentPoolId = nonExistentPoolId || info.poolId; // Status must be delegated and amount must be nonzero to trigger _assertStakingPoolExists info.status = StakeStatus.Delegated; } const assertion = moveStakeNonexistentPoolAssertion( this.actor.deployment, nonExistentPoolId as string, ); yield assertion.executeAsync([from, to, amount], { from: this.actor.address }); } } } private async *_validWithdrawDelegatorRewards(): AsyncIterableIterator<AssertionResult | void> { const { stakingPools } = this.actor.simulationEnvironment!; const assertion = validWithdrawDelegatorRewardsAssertion( this.actor.deployment, this.actor.simulationEnvironment!, ); while (true) { const prevEpoch = this.actor.simulationEnvironment!.currentEpoch.minus(1); // Pick a finalized pool const poolId = Pseudorandom.sample( Object.keys(stakingPools).filter(id => stakingPools[id].lastFinalized.isGreaterThanOrEqualTo(prevEpoch), ), ); if (poolId === undefined) { yield; } else { yield assertion.executeAsync([poolId], { from: this.actor.address }); } } } private async *_invalidWithdrawDelegatorRewards(): AsyncIterableIterator<AssertionResult | void> { const { stakingPools } = this.actor.simulationEnvironment!; const assertion = invalidWithdrawDelegatorRewardsAssertion( this.actor.deployment, this.actor.simulationEnvironment!, ); while (true) { const prevEpoch = this.actor.simulationEnvironment!.currentEpoch.minus(1); // Pick an unfinalized pool const poolId = Pseudorandom.sample( Object.keys(stakingPools).filter(id => stakingPools[id].lastFinalized.isLessThan(prevEpoch)), ); if (poolId === undefined) { yield; } else { yield assertion.executeAsync([poolId], { from: this.actor.address }); } } } }; } export class Staker extends StakerMixin(Actor) {}
the_stack
import { css } from '@emotion/react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import classnames from 'classnames'; import includes from 'lodash.includes'; import isEmpty from 'lodash.isempty'; import remove from 'lodash.remove'; import React, { KeyboardEventHandler, MouseEventHandler, useEffect, useState, } from 'react'; import { Node, NodeChildProps, Remove, } from 'reaflow'; import { useRecoilState } from 'recoil'; import { useDebouncedCallback } from 'use-debounce'; import { Options as DebounceCallbackOptions } from 'use-debounce/lib/useDebouncedCallback'; import settings from '../../settings'; import { blockPickerMenuSelector } from '../../states/blockPickerMenuState'; import { canvasDatasetSelector } from '../../states/canvasDatasetSelector'; import { lastCreatedState } from '../../states/lastCreatedState'; import { nodesSelector } from '../../states/nodesState'; import { selectedNodesSelector } from '../../states/selectedNodesState'; import BaseNodeAdditionalData from '../../types/BaseNodeAdditionalData'; import BaseNodeComponent from '../../types/BaseNodeComponent'; import BaseNodeData from '../../types/BaseNodeData'; import { BaseNodeDefaultProps } from '../../types/BaseNodeDefaultProps'; import BaseNodeProps, { PatchCurrentNode } from '../../types/BaseNodeProps'; import BasePortData from '../../types/BasePortData'; import { CanvasDataset } from '../../types/CanvasDataset'; import { NewCanvasDatasetMutation } from '../../types/CanvasDatasetMutation'; import { GetBaseNodeDefaultPropsProps } from '../../types/GetBaseNodeDefaultProps'; import { SpecializedNodeProps } from '../../types/nodes/SpecializedNodeProps'; import NodeType from '../../types/NodeType'; import PartialBaseNodeData from '../../types/PartialBaseNodeData'; import { isYoungerThan } from '../../utils/date'; import { cloneNode, isNodeReachable, removeAndUpsertNodesThroughPorts, } from '../../utils/nodes'; import { createPort } from '../../utils/ports'; import BasePort from '../ports/BasePort'; import BasePortChild from '../ports/BasePortChild'; type Props = BaseNodeProps & { hasCloneAction?: boolean; hasDeleteAction?: boolean; baseWidth: number; baseHeight: number; patchCurrentNodeWait?: number; patchCurrentNodeOptions?: DebounceCallbackOptions; }; const fallbackBaseWidth = 200; const fallbackBaseHeight = 100; /** * Base node component. * * This component contains shared business logic common to all nodes. * It renders a Reaflow <Node> component, which contains a <foreignObject> HTML element that allows us to write advanced HTML elements within. * * The Node is rendered as SVG <rect> element. * Beware the <foreignObject> will appear "on top" of the <Node>, and thus the Node will not receive some events because they're caught by the <foreignObject>. * * XXX If you want to change the behavior of all nodes while avoid code duplication, here's the place. * * @see https://reaflow.dev/?path=/story/demos-nodes * @see https://github.com/reaviz/reaflow/issues/45 Using `foreignObject` "steals" all `Node` events (onEnter, etc.) - How to forward events when using foreignObject? * @see https://github.com/reaviz/reaflow/issues/50 `useSelection` hook `onKeyDown` event doesn't work with `foreignObject` - Multiple selection doesn't work when using a `foreignObject * @see https://github.com/reaviz/reaflow/issues/44 React select component displays/hides itself randomly (as `foreignObject`) * TODO link doc about foreignObject - awaiting https://github.com/reaviz/reaflow/pull/74 */ const BaseNode: BaseNodeComponent<Props> = (props) => { const { children, // Don't forward, overridden in this file node, // Don't forward, not expected hasCloneAction = true, // Don't forward, not expected hasDeleteAction = true, // Don't forward, not expected baseWidth, baseHeight, patchCurrentNodeWait, patchCurrentNodeOptions, queueCanvasDatasetMutation, ...nodeProps // All props that are left will be forwarded to the Node component } = props; const [blockPickerMenu, setBlockPickerMenu] = useRecoilState(blockPickerMenuSelector); const [nodes, setNodes] = useRecoilState(nodesSelector); const [canvasDataset, setCanvasDataset] = useRecoilState(canvasDatasetSelector); const { edges } = canvasDataset; const [selectedNodes, setSelectedNodes] = useRecoilState(selectedNodesSelector); const isSelected = !!selectedNodes?.find((selectedNode: string) => selectedNode === node.id); const nodeType: NodeType = node?.data?.type as NodeType; const isReachable = isNodeReachable(node, edges); const [lastCreated] = useRecoilState(lastCreatedState); const lastCreatedNode = lastCreated?.node; const lastCreatedAt = lastCreated?.at; const isLastCreatedNode = lastCreated?.node?.id === node?.id; const recentlyCreatedMaxAge = 5000; // TODO convert to settings // Used to highlight the last created node for a few seconds after it's been created, to make it easier to understand where it's located // Particularly useful to the editor when ELK changes the nodes position to avoid losing track of the node that was just created const [isRecentlyCreated, setIsRecentlyCreated] = useState<boolean>(isYoungerThan(lastCreatedAt, recentlyCreatedMaxAge)); /** * Debounces the patchCurrentNode function. * * By debouncing "patchCurrentNode", it ensures all call to "patchCurrentNode" will not trigger burst of database updates. * It's a safer default behavior, because we usually care only about the last update, not all those in between. * * This is very convenient when updating input's values and such, and help keeping good app's performances and reduces cost. * * The default behavior is to wait for 1sec and there is no timeout. * You can override the default behavior for each specialized Node component. */ const debouncedPatchCurrentNode = useDebouncedCallback( (patch: PartialBaseNodeData) => { patchCurrentNode(patch); }, patchCurrentNodeWait || settings.canvas.nodes.defaultDebounceWaitFor, // Wait for other changes to happen, if no change happen then invoke the update patchCurrentNodeOptions || {}, ); /** * Stops the highlight of the last created node when the node's age has reached max age. */ useEffect(() => { if (isRecentlyCreated) { setTimeout(() => { setIsRecentlyCreated(false); }, recentlyCreatedMaxAge + 1); } }, []); /** * Update the node's base width/height in the event the Node component base width/height would have changed. */ useEffect(() => { const patchData: Partial<BaseNodeAdditionalData> = {}; const patch: PartialBaseNodeData = { data: patchData, }; if (node?.data?.dynHeights?.baseHeight !== baseHeight) { patchData.dynHeights = { baseHeight: baseHeight, }; if (node?.data?.dynHeights?.baseHeight && node?.height) { const heightDiff = node?.data?.dynHeights?.baseHeight - baseHeight; patch.height = node?.height - heightDiff; } } if (node?.data?.dynWidths?.baseWidth !== baseWidth) { patchData.dynWidths = { baseWidth: baseWidth, }; if (node?.data?.dynWidths?.baseWidth && node?.width) { const widthDiff = node?.data?.dynWidths?.baseWidth - baseWidth; patch.width = node?.width - widthDiff; } } if (!isEmpty(patchData)) { console.log(`Current node's base width/height doesn't match component's own base width/height. Updating the current node with patch:`, patchData); patchCurrentNode(patch); } }, [ baseHeight, baseWidth, node?.height, node?.width, node?.data?.dynHeights?.baseHeight, node?.data?.dynWidths?.baseWidth, ]); /** * Patches the properties of the current node. * * Only updates the provided properties, doesn't update other properties. * Will use deep merge of properties. * * @param patch * @param stateUpdateDelay (ms) */ const patchCurrentNode: PatchCurrentNode = (patch: PartialBaseNodeData, stateUpdateDelay = 0): void => { const mutation: NewCanvasDatasetMutation = { operationType: 'patch', elementId: node?.id, elementType: 'node', changes: patch, }; console.log('Adding node patch to the queue', 'patch:', patch, 'mutation:', mutation); queueCanvasDatasetMutation(mutation, stateUpdateDelay); }; /** * Clones the current node. * * @param event */ const onNodeClone = (event: React.MouseEvent<SVGGElement, MouseEvent>) => { const clonedNode: BaseNodeData = cloneNode(node); const mutation: NewCanvasDatasetMutation = { operationType: 'add', elementId: node?.id, elementType: 'node', changes: clonedNode, }; console.log('Adding patch to the queue', 'node:', clonedNode, 'mutation:', mutation); queueCanvasDatasetMutation(mutation); }; /** * Removes the current node. * * Upsert its descendant if there were any. (auto-link all descendants to all its ascendants) * * Triggered when clicking on the "x" remove button that appears when a node is selected. * * @param event */ const onNodeRemove = (event: React.MouseEvent<SVGGElement, MouseEvent>) => { console.log('onNodeRemove', event, node); const dataset: CanvasDataset = removeAndUpsertNodesThroughPorts(nodes, edges, node); const newSelectedNodes = remove(selectedNodes, node?.id); setCanvasDataset(dataset); // Updates selected nodes to make sure we don't keep selected nodes that have been deleted setSelectedNodes(newSelectedNodes); // Hide the block picker menu. // Forces to reset the function bound to onBlockClick. Necessary when there is one or none node left. setBlockPickerMenu({ isDisplayed: false, }); }; /** * Selects the current node when clicking on it. * * XXX We're resolving the "node" ourselves, instead of relying on the 2nd argument (nodeData), * which might return null depending on where in the node the click was performed * (because of the <foreignObject> which is displayed on top of the <rect> element and might hijack mouse events). * * @param event */ const onNodeClick = (event: React.MouseEvent<SVGGElement, MouseEvent>) => { console.log(`node clicked (${node?.data?.type})`, 'node:', node); // Don't select nodes that are already selected if (!includes(selectedNodes, node?.id)) { setSelectedNodes([node.id]); } }; /** * When the mouse enters a node (on hover). * * XXX Tried to detect when entering/leaving a node, but it's hard because of foreignObject which yields a lot of false positive events * I couldn't reliably tell whether we're actually entering/leaving a node * The goal was to to update mouseEnteredState accordingly, to know which node/port are currently being hovered/entered * to bind node/ports in a reliable way when dropping an edge onto a node/port. * But, our current implementation inf "BasePort.onPortDragEnd" (which relies on the DOM) is much more reliable. * * @param event * @param node */ const onNodeEnter = (event: React.MouseEvent<SVGGElement, MouseEvent>, node: BaseNodeData) => { // console.log('onNodeEnter', event.target); // @ts-ignore // const isNode = event.target?.classList?.contains('node-svg-rect'); // if (isNode) { // // console.log('Entering node') // } }; /** * When the mouse leaves a node (leaves hover area). * * XXX Tried to detect when entering/leaving a node, but it's hard because of foreignObject which yields a lot of false positive events * I couldn't reliably tell whether we're actually entering/leaving a node * The goal was to to update mouseEnteredState accordingly, to know which node/port are currently being hovered/entered * to bind node/ports in a reliable way when dropping an edge onto a node/port. * But, our current implementation inf "BasePort.onPortDragEnd" (which relies on the DOM) is much more reliable. * * @param event * @param node */ const onNodeLeave = (event: React.MouseEvent<SVGGElement, MouseEvent>, node: BaseNodeData) => { // console.log('onNodeLeave', event.target); // console.log('containerRef?.current', containerRef?.current) // // @ts-ignore // const isChildrenOfNodeContainer = event.target?.closest('.node-container'); // // @ts-ignore // const isChildrenOfNodeRect = event.target?.closest('.node-svg-rect'); // const isNode = isChildrenOfNodeContainer || isChildrenOfNodeRect; // // if (isNode) { // console.log('Hovering node') // } }; /** * When a keyboard key is pressed/released. * * @param event * @param node */ const onKeyDown = (event: React.KeyboardEvent<SVGGElement>, node: BaseNodeData) => { console.log('onKeyDown', event, node); }; // console.log('BaseNode nodeProps', nodeProps); return ( <Node {...nodeProps} style={{ strokeWidth: 0, fill: isReachable ? 'white' : '#eaeaea', color: 'black', cursor: 'auto', }} className={classnames( `node-svg-rect node-${nodeType}-svg-rect`, )} onClick={onNodeClick} onEnter={onNodeEnter} onLeave={onNodeLeave} onKeyDown={onKeyDown} onRemove={onNodeRemove} remove={(<Remove hidden={true} />)} port={( <BasePort fromNodeId={node.id} additionalPortChildProps={{ fromNode: node, isNodeReachable: isReachable, }} PortChildComponent={BasePortChild} queueCanvasDatasetMutation={queueCanvasDatasetMutation} /> )} > { /** * Renders the foreignObject and common layout used by all nodes. * * XXX CSS styles applied here will be correctly applied to elements created in specialised node components. * * @param nodeProps */ (nodeProps: NodeChildProps) => { const { width, height, } = nodeProps; const specializedNodeProps: SpecializedNodeProps = { ...nodeProps, isSelected, isReachable, lastCreated, patchCurrentNode, patchCurrentNodeImmediately: patchCurrentNode, queueCanvasDatasetMutation, }; return ( <foreignObject id={`node-foreignObject-${node.id}`} // Used during drag & drop of edges to resolve the destination node ("toNode") className={classnames(`${nodeType}-node-container node-container`, { 'is-selected': isSelected, 'is-last-created': isLastCreatedNode, 'is-recently-created': isRecentlyCreated, })} width={width} height={height} // x={0} // Relative position from the parent Node component (aligned to top) // y={0} // Relative position from the parent Node component (aligned to left) css={css` position: relative; border: ${settings.canvas.nodes.borderWidth}px solid transparent; // Highlights the node when it's being selected &.is-selected { border: ${settings.canvas.nodes.borderWidth}px solid ${isReachable ? settings.canvas.nodes.selected.borderColor : 'orange'}; border-radius: 2px; } // Highlights the node when it's the last created node &.is-recently-created { animation: fadeIn ease-in-out 1.3s; @keyframes fadeIn { 0% { opacity: 0; box-shadow: 0px 5px 15px rgba(0, 40, 255, 1); } 35% { opacity: 0; box-shadow: 0px 5px 15px rgba(0, 40, 255, 1); } 100% { opacity: 1; box-shadow: 0px 5px 15px rgba(0, 40, 255, 0); } } } // Disabling pointer-events on top-level containers, for events to be forwarded to the underlying <rect> // Allows using events specific to the Reaflow <Node> component (onClick, onEnter, onLeave, etc.) pointer-events: none; .node, .node-header { pointer-events: none; } .node-action, .node-content { pointer-events: auto; } .node { margin: 15px; // XXX Elements within a <foreignObject> that are using the CSS "position" attribute won't be shown properly, // unless they're wrapped into a container using a "fixed" position. // Solves the display of React Select element. // See https://github.com/chakra-ui/chakra-ui/issues/3288#issuecomment-776316200 position: fixed; // Take full size of its parent, minus the margins (left/right) width: calc(100% - 30px); // Depends on above "margin" value height: calc(100% - 30px); // Depends on above "margin" value } .is-unreachable-warning { pointer-events: auto; color: orange; float: left; cursor: help; } // Applied to all textarea for all nodes .textarea { margin-top: 15px; background-color: #F1F3FF; border: ${settings.canvas.nodes.textarea.borderWidth}px solid lightgrey; border-radius: 5px; } `} // Use the same onClick/onMouseEnter/onMouseLeave handlers as the one used by the Node component, to yield the same behavior whether clicking on the <rect> or on the <foreignObject> element onClick={onNodeClick as MouseEventHandler} onMouseEnter={onNodeEnter as MouseEventHandler} onMouseLeave={onNodeLeave as MouseEventHandler} onKeyDown={onKeyDown as KeyboardEventHandler} > <div className={classnames(`${nodeType}-node node`)} > <div className={'node-actions-container'} css={css` position: absolute; display: ${isSelected ? 'flex' : 'none'}; top: -15px; right: ${(hasCloneAction ? 13 : 0) + (hasDeleteAction ? 13 : 0)}px; // Depends on how many actions needs to be displayed, currently hardcoded margin: 5px; padding: 5px; background-color: transparent; color: red; width: 5px; height: 5px; .node-action { cursor: pointer; .svg-inline--fa { margin-right: 5px; } } `} > { hasCloneAction && ( <div className={'node-action delete-action'} onClick={onNodeClone as MouseEventHandler} > <FontAwesomeIcon color="#0028FF" icon={['fas', 'clone']} /> </div> ) } { hasDeleteAction && ( <div className={'node-action delete-action'} onClick={onNodeRemove as MouseEventHandler} > <FontAwesomeIcon color="#F9694A" icon={['fas', 'trash-alt']} /> </div> ) } </div> <div className={`node-content-container ${nodeType}-content-container`} > { // Invoke the children as a function, or render the children as a component, if it's not a function // @ts-ignore typeof children === 'function' ? (children({ ...specializedNodeProps })) : children } </div> </div> </foreignObject> ); } } </Node> ); }; /** * By default, a node has 2 ports, one on the east side (left) and one on the west side (right). * * XXX The height/width properties must be set here because they're used for calculations of the port's placement. * If we change them directly in the <Port|BasePort> component, the ports will be misaligned with the node. */ BaseNode.getDefaultPorts = (): BasePortData[] => { return [ createPort({ height: settings.canvas.ports.radius, width: settings.canvas.ports.radius, alignment: 'CENTER', side: 'WEST', }), createPort({ height: settings.canvas.ports.radius, width: settings.canvas.ports.radius, alignment: 'CENTER', side: 'EAST', }), ]; }; /** * Builds the defaults properties of a node. * * Used when creating a new node. * * @param props */ BaseNode.getDefaultNodeProps = (props: GetBaseNodeDefaultPropsProps): BaseNodeDefaultProps => { const { type, baseHeight, baseWidth } = props; return { type, baseWidth: baseWidth || fallbackBaseWidth, baseHeight: baseHeight || fallbackBaseHeight, // @ts-ignore ports: BaseNode.getDefaultPorts(), // nodePadding: 10 // TODO try it (left/top/bottom/right) }; }; export default BaseNode;
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 resourcesettings_v1 { export interface Options extends GlobalOptions { version: 'v1'; } 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; } /** * Resource Settings API * * The Resource Settings API allows users to control and modify the behavior of their GCP resources (e.g., VM, firewall, Project, etc.) across the Cloud Resource Hierarchy. * * @example * ```js * const {google} = require('googleapis'); * const resourcesettings = google.resourcesettings('v1'); * ``` */ export class Resourcesettings { context: APIRequestContext; folders: Resource$Folders; organizations: Resource$Organizations; projects: Resource$Projects; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.folders = new Resource$Folders(this.context); this.organizations = new Resource$Organizations(this.context); this.projects = new Resource$Projects(this.context); } } /** * The response from ListSettings. */ export interface Schema$GoogleCloudResourcesettingsV1ListSettingsResponse { /** * Unused. A page token used to retrieve the next page. */ nextPageToken?: string | null; /** * A list of settings that are available at the specified Cloud resource. */ settings?: Schema$GoogleCloudResourcesettingsV1Setting[]; } /** * The schema for settings. */ export interface Schema$GoogleCloudResourcesettingsV1Setting { /** * Output only. The effective value of the setting at the given parent resource, evaluated based on the resource hierarchy The effective value evaluates to one of the following options, in this order. If an option is not valid or doesn't exist, then the next option is used: 1. The local setting value on the given resource: Setting.local_value 2. If one of the given resource's ancestors in the resource hierarchy have a local setting value, the local value at the nearest such ancestor. 3. The setting's default value: SettingMetadata.default_value 4. An empty value, defined as a `Value` with all fields unset. The data type of Value must always be consistent with the data type defined in Setting.metadata. */ effectiveValue?: Schema$GoogleCloudResourcesettingsV1Value; /** * A fingerprint used for optimistic concurrency. See UpdateSetting for more details. */ etag?: string | null; /** * The configured value of the setting at the given parent resource, ignoring the resource hierarchy. The data type of Value must always be consistent with the data type defined in Setting.metadata. */ localValue?: Schema$GoogleCloudResourcesettingsV1Value; /** * Output only. Metadata about a setting which is not editable by the end user. */ metadata?: Schema$GoogleCloudResourcesettingsV1SettingMetadata; /** * The resource name of the setting. Must be in one of the following forms: * `projects/{project_number\}/settings/{setting_name\}` * `folders/{folder_id\}/settings/{setting_name\}` * `organizations/{organization_id\}/settings/{setting_name\}` For example, "/projects/123/settings/gcp-enableMyFeature" */ name?: string | null; } /** * Metadata about a setting which is not editable by the end user. */ export interface Schema$GoogleCloudResourcesettingsV1SettingMetadata { /** * The data type for this setting. */ dataType?: string | null; /** * The value provided by Setting.effective_value if no setting value is explicitly set. Note: not all settings have a default value. */ defaultValue?: Schema$GoogleCloudResourcesettingsV1Value; /** * A detailed description of what this setting does. */ description?: string | null; /** * The human readable name for this setting. */ displayName?: string | null; /** * A flag indicating that values of this setting cannot be modified. See documentation for the specific setting for updates and reasons. */ readOnly?: boolean | null; } /** * The data in a setting value. */ export interface Schema$GoogleCloudResourcesettingsV1Value { /** * Defines this value as being a boolean value. */ booleanValue?: boolean | null; /** * Defines this value as being a Duration. */ durationValue?: string | null; /** * Defines this value as being a Enum. */ enumValue?: Schema$GoogleCloudResourcesettingsV1ValueEnumValue; /** * Defines this value as being a StringMap. */ stringMapValue?: Schema$GoogleCloudResourcesettingsV1ValueStringMap; /** * Defines this value as being a StringSet. */ stringSetValue?: Schema$GoogleCloudResourcesettingsV1ValueStringSet; /** * Defines this value as being a string value. */ stringValue?: string | null; } /** * A enum value that can hold any enum type setting values. Each enum type is represented by a number, this representation is stored in the definitions. */ export interface Schema$GoogleCloudResourcesettingsV1ValueEnumValue { /** * The value of this enum */ value?: string | null; } /** * A string-\>string map value that can hold a map of string keys to string values. The maximum length of each string is 200 characters and there can be a maximum of 50 key-value pairs in the map. */ export interface Schema$GoogleCloudResourcesettingsV1ValueStringMap { /** * The key-value pairs in the map */ mappings?: {[key: string]: string} | null; } /** * A string set value that can hold a set of strings. The maximum length of each string is 200 characters and there can be a maximum of 50 strings in the string set. */ export interface Schema$GoogleCloudResourcesettingsV1ValueStringSet { /** * The strings in the set */ values?: string[] | null; } export class Resource$Folders { context: APIRequestContext; settings: Resource$Folders$Settings; constructor(context: APIRequestContext) { this.context = context; this.settings = new Resource$Folders$Settings(this.context); } } export class Resource$Folders$Settings { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Returns a specified setting. Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the setting does not exist. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.folders.settings.get({ * // Required. The name of the setting to get. See Setting for naming requirements. * name: 'folders/my-folder/settings/my-setting', * // The SettingView for this request. * view: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "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$Folders$Settings$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Folders$Settings$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting>; get( params: Params$Resource$Folders$Settings$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Folders$Settings$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( params: Params$Resource$Folders$Settings$Get, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( paramsOrCallback?: | Params$Resource$Folders$Settings$Get | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Settings$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Settings$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters ); } } /** * Lists all the settings that are available on the Cloud resource `parent`. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.folders.settings.list({ * // Unused. The size of the page to be returned. * pageSize: 'placeholder-value', * // Unused. A page token used to retrieve the next page. * pageToken: 'placeholder-value', * // Required. The project, folder, or organization that is the parent resource for this setting. Must be in one of the following forms: * `projects/{project_number\}` * `projects/{project_id\}` * `folders/{folder_id\}` * `organizations/{organization_id\}` * parent: 'folders/my-folder', * // The SettingView for this request. * view: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "settings": [] * // } * } * * 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$Folders$Settings$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Folders$Settings$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>; list( params: Params$Resource$Folders$Settings$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Folders$Settings$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( params: Params$Resource$Folders$Settings$List, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Folders$Settings$List | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Settings$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Settings$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/settings').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>( parameters ); } } /** * Updates a specified setting. Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the setting does not exist. Returns a `google.rpc.Status` with `google.rpc.Code.FAILED_PRECONDITION` if the setting is flagged as read only. Returns a `google.rpc.Status` with `google.rpc.Code.ABORTED` if the etag supplied in the request does not match the persisted etag of the setting value. On success, the response will contain only `name`, `local_value` and `etag`. The `metadata` and `effective_value` cannot be updated through this API. Note: the supplied setting will perform a full overwrite of the `local_value` field. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.folders.settings.patch({ * // The resource name of the setting. Must be in one of the following forms: * `projects/{project_number\}/settings/{setting_name\}` * `folders/{folder_id\}/settings/{setting_name\}` * `organizations/{organization_id\}/settings/{setting_name\}` For example, "/projects/123/settings/gcp-enableMyFeature" * name: 'folders/my-folder/settings/my-setting', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "metadata": {}, * // "name": "my_name" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "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. */ patch( params: Params$Resource$Folders$Settings$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Folders$Settings$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting>; patch( params: Params$Resource$Folders$Settings$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Folders$Settings$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( params: Params$Resource$Folders$Settings$Patch, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( paramsOrCallback?: | Params$Resource$Folders$Settings$Patch | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Settings$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Settings$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters ); } } } export interface Params$Resource$Folders$Settings$Get extends StandardParameters { /** * Required. The name of the setting to get. See Setting for naming requirements. */ name?: string; /** * The SettingView for this request. */ view?: string; } export interface Params$Resource$Folders$Settings$List extends StandardParameters { /** * Unused. The size of the page to be returned. */ pageSize?: number; /** * Unused. A page token used to retrieve the next page. */ pageToken?: string; /** * Required. The project, folder, or organization that is the parent resource for this setting. Must be in one of the following forms: * `projects/{project_number\}` * `projects/{project_id\}` * `folders/{folder_id\}` * `organizations/{organization_id\}` */ parent?: string; /** * The SettingView for this request. */ view?: string; } export interface Params$Resource$Folders$Settings$Patch extends StandardParameters { /** * The resource name of the setting. Must be in one of the following forms: * `projects/{project_number\}/settings/{setting_name\}` * `folders/{folder_id\}/settings/{setting_name\}` * `organizations/{organization_id\}/settings/{setting_name\}` For example, "/projects/123/settings/gcp-enableMyFeature" */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudResourcesettingsV1Setting; } export class Resource$Organizations { context: APIRequestContext; settings: Resource$Organizations$Settings; constructor(context: APIRequestContext) { this.context = context; this.settings = new Resource$Organizations$Settings(this.context); } } export class Resource$Organizations$Settings { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Returns a specified setting. Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the setting does not exist. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.organizations.settings.get({ * // Required. The name of the setting to get. See Setting for naming requirements. * name: 'organizations/my-organization/settings/my-setting', * // The SettingView for this request. * view: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "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$Organizations$Settings$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Organizations$Settings$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting>; get( params: Params$Resource$Organizations$Settings$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Organizations$Settings$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( params: Params$Resource$Organizations$Settings$Get, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( paramsOrCallback?: | Params$Resource$Organizations$Settings$Get | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Settings$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Settings$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters ); } } /** * Lists all the settings that are available on the Cloud resource `parent`. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.organizations.settings.list({ * // Unused. The size of the page to be returned. * pageSize: 'placeholder-value', * // Unused. A page token used to retrieve the next page. * pageToken: 'placeholder-value', * // Required. The project, folder, or organization that is the parent resource for this setting. Must be in one of the following forms: * `projects/{project_number\}` * `projects/{project_id\}` * `folders/{folder_id\}` * `organizations/{organization_id\}` * parent: 'organizations/my-organization', * // The SettingView for this request. * view: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "settings": [] * // } * } * * 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$Organizations$Settings$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Organizations$Settings$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>; list( params: Params$Resource$Organizations$Settings$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Organizations$Settings$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( params: Params$Resource$Organizations$Settings$List, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Organizations$Settings$List | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Settings$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Settings$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/settings').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>( parameters ); } } /** * Updates a specified setting. Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the setting does not exist. Returns a `google.rpc.Status` with `google.rpc.Code.FAILED_PRECONDITION` if the setting is flagged as read only. Returns a `google.rpc.Status` with `google.rpc.Code.ABORTED` if the etag supplied in the request does not match the persisted etag of the setting value. On success, the response will contain only `name`, `local_value` and `etag`. The `metadata` and `effective_value` cannot be updated through this API. Note: the supplied setting will perform a full overwrite of the `local_value` field. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.organizations.settings.patch({ * // The resource name of the setting. Must be in one of the following forms: * `projects/{project_number\}/settings/{setting_name\}` * `folders/{folder_id\}/settings/{setting_name\}` * `organizations/{organization_id\}/settings/{setting_name\}` For example, "/projects/123/settings/gcp-enableMyFeature" * name: 'organizations/my-organization/settings/my-setting', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "metadata": {}, * // "name": "my_name" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "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. */ patch( params: Params$Resource$Organizations$Settings$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Organizations$Settings$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting>; patch( params: Params$Resource$Organizations$Settings$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Organizations$Settings$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( params: Params$Resource$Organizations$Settings$Patch, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( paramsOrCallback?: | Params$Resource$Organizations$Settings$Patch | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Settings$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Settings$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters ); } } } export interface Params$Resource$Organizations$Settings$Get extends StandardParameters { /** * Required. The name of the setting to get. See Setting for naming requirements. */ name?: string; /** * The SettingView for this request. */ view?: string; } export interface Params$Resource$Organizations$Settings$List extends StandardParameters { /** * Unused. The size of the page to be returned. */ pageSize?: number; /** * Unused. A page token used to retrieve the next page. */ pageToken?: string; /** * Required. The project, folder, or organization that is the parent resource for this setting. Must be in one of the following forms: * `projects/{project_number\}` * `projects/{project_id\}` * `folders/{folder_id\}` * `organizations/{organization_id\}` */ parent?: string; /** * The SettingView for this request. */ view?: string; } export interface Params$Resource$Organizations$Settings$Patch extends StandardParameters { /** * The resource name of the setting. Must be in one of the following forms: * `projects/{project_number\}/settings/{setting_name\}` * `folders/{folder_id\}/settings/{setting_name\}` * `organizations/{organization_id\}/settings/{setting_name\}` For example, "/projects/123/settings/gcp-enableMyFeature" */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudResourcesettingsV1Setting; } export class Resource$Projects { context: APIRequestContext; settings: Resource$Projects$Settings; constructor(context: APIRequestContext) { this.context = context; this.settings = new Resource$Projects$Settings(this.context); } } export class Resource$Projects$Settings { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Returns a specified setting. Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the setting does not exist. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.projects.settings.get({ * // Required. The name of the setting to get. See Setting for naming requirements. * name: 'projects/my-project/settings/my-setting', * // The SettingView for this request. * view: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "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$Settings$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Settings$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting>; get( params: Params$Resource$Projects$Settings$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Settings$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( params: Params$Resource$Projects$Settings$Get, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Settings$Get | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Settings$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Settings$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters ); } } /** * Lists all the settings that are available on the Cloud resource `parent`. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.projects.settings.list({ * // Unused. The size of the page to be returned. * pageSize: 'placeholder-value', * // Unused. A page token used to retrieve the next page. * pageToken: 'placeholder-value', * // Required. The project, folder, or organization that is the parent resource for this setting. Must be in one of the following forms: * `projects/{project_number\}` * `projects/{project_id\}` * `folders/{folder_id\}` * `organizations/{organization_id\}` * parent: 'projects/my-project', * // The SettingView for this request. * view: 'placeholder-value', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "settings": [] * // } * } * * 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$Settings$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Settings$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>; list( params: Params$Resource$Projects$Settings$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Settings$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( params: Params$Resource$Projects$Settings$List, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Settings$List | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Settings$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Settings$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/settings').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1ListSettingsResponse>( parameters ); } } /** * Updates a specified setting. Returns a `google.rpc.Status` with `google.rpc.Code.NOT_FOUND` if the setting does not exist. Returns a `google.rpc.Status` with `google.rpc.Code.FAILED_PRECONDITION` if the setting is flagged as read only. Returns a `google.rpc.Status` with `google.rpc.Code.ABORTED` if the etag supplied in the request does not match the persisted etag of the setting value. On success, the response will contain only `name`, `local_value` and `etag`. The `metadata` and `effective_value` cannot be updated through this API. Note: the supplied setting will perform a full overwrite of the `local_value` field. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/resourcesettings.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 resourcesettings = google.resourcesettings('v1'); * * 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 resourcesettings.projects.settings.patch({ * // The resource name of the setting. Must be in one of the following forms: * `projects/{project_number\}/settings/{setting_name\}` * `folders/{folder_id\}/settings/{setting_name\}` * `organizations/{organization_id\}/settings/{setting_name\}` For example, "/projects/123/settings/gcp-enableMyFeature" * name: 'projects/my-project/settings/my-setting', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "metadata": {}, * // "name": "my_name" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "effectiveValue": {}, * // "etag": "my_etag", * // "localValue": {}, * // "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. */ patch( params: Params$Resource$Projects$Settings$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Settings$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting>; patch( params: Params$Resource$Projects$Settings$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Settings$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting>, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( params: Params$Resource$Projects$Settings$Patch, callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( callback: BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Settings$Patch | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudResourcesettingsV1Setting> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudResourcesettingsV1Setting> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Settings$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Settings$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://resourcesettings.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudResourcesettingsV1Setting>( parameters ); } } } export interface Params$Resource$Projects$Settings$Get extends StandardParameters { /** * Required. The name of the setting to get. See Setting for naming requirements. */ name?: string; /** * The SettingView for this request. */ view?: string; } export interface Params$Resource$Projects$Settings$List extends StandardParameters { /** * Unused. The size of the page to be returned. */ pageSize?: number; /** * Unused. A page token used to retrieve the next page. */ pageToken?: string; /** * Required. The project, folder, or organization that is the parent resource for this setting. Must be in one of the following forms: * `projects/{project_number\}` * `projects/{project_id\}` * `folders/{folder_id\}` * `organizations/{organization_id\}` */ parent?: string; /** * The SettingView for this request. */ view?: string; } export interface Params$Resource$Projects$Settings$Patch extends StandardParameters { /** * The resource name of the setting. Must be in one of the following forms: * `projects/{project_number\}/settings/{setting_name\}` * `folders/{folder_id\}/settings/{setting_name\}` * `organizations/{organization_id\}/settings/{setting_name\}` For example, "/projects/123/settings/gcp-enableMyFeature" */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudResourcesettingsV1Setting; } }
the_stack
import { LogLevel } from './../../chat21-core/utils/constants'; import { Injectable } from '@angular/core'; // import { Subscription } from 'rxjs/Subscription'; import { environment } from '../../environments/environment'; // import { TranslatorService } from '../providers/translator.service'; import { DepartmentModel } from '../../models/department'; import { User } from '../../models/User'; import { ProjectModel } from '../../models/project'; import { detectIfIsMobile, convertColorToRGBA, getParameterByName, setColorFromString, avatarPlaceholder } from '../utils/utils'; import { CHANNEL_TYPE_GROUP } from '../utils/constants'; // import { TemplateBindingParseResult } from '@angular/compiler'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { ConversationModel } from '../../models/conversation'; import { ConversationComponent } from '../components/conversation-detail/conversation/conversation.component'; import { invertColor } from '../../chat21-core/utils/utils'; // import { variable } from '@angular/compiler/src/output/output_ast'; // import { storage } from 'firebase'; @Injectable() export class Globals { obsObjChanged = new BehaviorSubject<any>(null); obsIsOpen = new BehaviorSubject<boolean>(null); // obsGlobalsParameters = new BehaviorSubject<any>(null); BASE_LOCATION = 'https://widget.tiledesk.com/v2'; // POWERED_BY = '<a tabindex="-1" target="_blank" href="http://www.tiledesk.com/">Powered by <b>TileDesk</b></a>'; POWERED_BY ='<a tabindex="-1" target="_blank" href="http://www.tiledesk.com/"><span>POWERED BY</span> <img src="https://support-pre.tiledesk.com/dashboard/assets/img/logos/tiledesk-logo.svg"/></a>' DEFAULT_LOGO_CHAT = '/assets/images/tiledesk_logo_white_small.png'; WIDGET_TITLE = 'Tiledesk'; // private parameters = {}; // private default_settings; // ========= begin:: sottoscrizioni ======= // // subscriptions: Subscription[] = []; /** */ // ========= end:: sottoscrizioni ======= // // ============ BEGIN: SET FUNCTION BY UTILS ==============// getParameterByName = getParameterByName; convertColorToRGBA = convertColorToRGBA; // ============ BEGIN: SET INTERNAL PARAMETERS ==============// project = new ProjectModel(); senderId: string; tenant: string; channelType: string; default_settings: any; isMobile: boolean; isLogged: boolean; soundEnabled: boolean; BUILD_VERSION: String; filterSystemMsg: boolean; /** se è true i messaggi inviati da system non vengono visualizzati */ baseLocation: string; availableAgents: Array<User> = []; isLogout = false; /** indica se ho appena fotto il logout */ attributes: any; preChatFormJson: any; // ******* new ******** token: string; tiledeskToken: string; firebaseToken: string; lang: string; conversationsBadge: number; activeConversation: ConversationModel; public currentConversationComponent: ConversationComponent; isOpenStartRating: boolean; departments: DepartmentModel[]; departmentSelected: DepartmentModel; departmentDefault: any; isOpenMenuOptions: boolean; isOpenPrechatForm: boolean; // areAgentsAvailable = false; areAgentsAvailableText: string; availableAgentsStatus = false; // indica quando è impostato lo stato degli agenti nel subscribe signInWithCustomToken: boolean; displayEyeCatcherCard: string; firstOpen = true; departmentID = null; privacyApproved = false; startedAt = new Date(); // ============ BEGIN: LABELS ==============// LABEL_TU: string; LABEL_PLACEHOLDER: string; LABEL_START_NW_CONV: string; LABEL_FIRST_MSG: string; LABEL_FIRST_MSG_NO_AGENTS: string; LABEL_SELECT_TOPIC: string; LABEL_COMPLETE_FORM: string; LABEL_FIELD_NAME: string; LABEL_ERROR_FIELD_NAME: string; LABEL_FIELD_EMAIL: string; LABEL_ERROR_FIELD_EMAIL: string; LABEL_WRITING: string; LABEL_SEND_NEW_MESSAGE: string; AGENT_NOT_AVAILABLE: string; AGENT_AVAILABLE: string; GUEST_LABEL: string; ALL_AGENTS_OFFLINE_LABEL: string; CALLOUT_TITLE_PLACEHOLDER: string; CALLOUT_MSG_PLACEHOLDER: string; ALERT_LEAVE_CHAT: string; YES: string; NO: string; BUTTON_CLOSE_TO_ICON: string; BUTTON_EDIT_PROFILE: string; DOWNLOAD_TRANSCRIPT: string; RATE_CHAT: string; WELCOME_TITLE: string; WELCOME_MSG: string; WELCOME: string; OPTIONS: string; SOUND_ON: string; SOUND_OFF: string; LOGOUT: string; CUSTOMER_SATISFACTION: string; YOUR_OPINION_ON_OUR_CUSTOMER_SERVICE: string; YOUR_RATING: string; WRITE_YOUR_OPINION: string; SUBMIT: string; THANK_YOU_FOR_YOUR_EVALUATION: string; YOUR_RATING_HAS_BEEN_RECEIVED: string; CLOSE: string; PREV_CONVERSATIONS: string; YOU: string; SHOW_ALL_CONV: string; START_A_CONVERSATION: string; NO_CONVERSATION: string; SEE_PREVIOUS: string; WAITING_TIME_FOUND: string; WAITING_TIME_NOT_FOUND: string; CLOSED: string; LABEL_PREVIEW: string; // ============ BEGIN: EXTERNAL PARAMETERS ==============// globalsParameters: any; autoStart: boolean; startHidden: boolean; isShown: boolean; isOpen: boolean; startFromHome: boolean; projectid: string; preChatForm: boolean; align: string; calloutTimer: number; calloutTitle: string; calloutMsg: string; calloutStaus: boolean; userFullname: string; userEmail: string; widgetTitle: string; fullscreenMode: boolean; hideHeaderCloseButton: boolean; themeColor: string; themeForegroundColor: string; themeColor50: string; colorGradient: string; colorBck: string colorGradient180: string; allowTranscriptDownload: boolean; poweredBy: string; logoChat: string; welcomeTitle: string; welcomeMsg: string; recipientId: string; newConversationStart: boolean; recipientFullname: string; // userId: string; // userToken: string; marginX: string; marginY: string; launcherWidth: string; launcherHeight: string; baloonImage: string; baloonShape: string; isLogEnabled: boolean; openExternalLinkButton: boolean; hideHeaderConversationOptionsMenu: boolean; hideSettings: boolean; filterByRequester: boolean; persistence; windowContext; showWaitTime: boolean; showAvailableAgents: boolean; showLogoutOption: boolean; supportMode: boolean; online_msg: string; offline_msg: string; customAttributes: any; showAttachmentButton: boolean; showAllConversations: boolean; // privacyField: string; jwt: string; isOpenNewMessage: boolean; dynamicWaitTimeReply: boolean; // ******* new ******** logLevel: string; // ******* new ******** bubbleSentBackground: string; // ******* new ******** bubbleSentTextColor: string; // ******* new ******** bubbleReceivedBackground: string; // ******* new ******** bubbleReceivedTextColor: string; // ******* new ******** fontSize: string; // ******* new ******** fontFamily: string; // ******* new ******** buttonFontSize: string; // ******* new ******** buttonBackgroundColor: string // ******* new ******** buttonTextColor: string // ******* new ******** buttonHoverBackgroundColor: string // ******* new ******** buttonHoverTextColor: string // ******* new ******** singleConversation: boolean; // ******* new ******** nativeRating: boolean; // ******* new ******** constructor( ) { // console.log(' ---------------- 1: initDefafultParameters ---------------- '); } /** * 1: initParameters */ initDefafultParameters() { // console.log('initDefafultParameters, ', window, window.frameElement); this.globalsParameters = {}; this.filterSystemMsg = true; let wContext: any = window; // console.log('windowContext 0', wContext); if (window.frameElement && window.frameElement.getAttribute('tiledesk_context') === 'parent') { wContext = window.parent; } // console.log('windowContext 1', wContext); const windowcontextFromWindow = getParameterByName(window, 'windowcontext'); if (windowcontextFromWindow !== null && windowcontextFromWindow === 'window.parent') { wContext = window.parent; } // console.log('windowContext 2', wContext); // this.parameters['windowContext'] = windowContext; this.windowContext = wContext; // ============ BEGIN: SET EXTERNAL PARAMETERS ==============// this.baseLocation = this.BASE_LOCATION; this.autoStart = true; this.startHidden = false; /** start Authentication and startUI */ this.isShown = true; /** show/hide all widget -> js call: showAllWidget */ this.isOpen = false; /** show/hide window widget -> js call: hideAllWidget */ this.startFromHome = true; /** start from Home or Conversation */ this.isOpenPrechatForm = true; /** check open/close modal prechatform if g.preChatForm is true */ this.isOpenStartRating = false; /** show/hide all rating chat */ this.projectid = ''; /** The TileDesk project id. Find your TileDesk ProjectID in the TileDesk Dashboard under the Widget menu. */ this.preChatForm = false; /** You can require customers to enter information like name and email before sending a chat message by enabling the Pre-Chat form. Permitted values: true, false. The default value is false. */ this.align = ''; /** if it is true, the chat window is automatically open when the widget is loaded. Permitted values: true, false. Default value : false */ this.calloutTimer = -1; /** Proactively open the chat windows to increase the customer engagement. Permitted values: -1 (Disabled), 0 (Immediatly) or a positive integer value. For exmaple: 5 (After 5 seconds), 10 (After 10 seconds). */ this.calloutTitle = ''; /** title box callout */ this.calloutMsg = ''; /** stato callout (shown only first time) */ this.calloutStaus = true; /** message box callout */ this.userFullname = ''; /** userFullname: Current user fullname. Set this parameter to specify the visitor fullname. */ this.userEmail = ''; /** Current user email address. Set this parameter to specify the visitor email address. */ this.widgetTitle = ''; /** Set the widget title label shown in the widget header. Value type : string. The default value is Tiledesk. */ this.dynamicWaitTimeReply = true; /** The user can decide whether or not to share the * average response time of his team (if 'dynamicWaitTimeReply' is * false the WAITING_TIME_NOT_FOUND will always be displayed) * is set to true for backward compatibility with old projects */ this.hideHeaderCloseButton = false; /** Hide the close button in the widget header. Permitted values: true, false. The default value is false. */ this.fullscreenMode = false; /** if it is true, the chat window is open in fullscreen mode. Permitted values: true, false. Default value : false */ this.themeColor = convertColorToRGBA('#2a6ac1', 100); /** allows you to change the main widget's color (color of the header, color of the launcher button, other minor elements). Permitted values: Hex color codes, e.g. #87BC65 and RGB color codes, e.g. rgb(135,188,101) */ this.themeForegroundColor = convertColorToRGBA('#ffffff', 100); /** allows you to change text and icons' color. Permitted values: Hex color codes, e.g. #425635 and RGB color codes, e.g. rgb(66,86,53) */ this.colorBck = convertColorToRGBA('#000000', 100) /** allows you to change background color. Permitted values: Hex color codes, e.g. #425635 and RGB color codes, e.g. rgb(66,86,53) */ this.allowTranscriptDownload = false; /** allows the user to download the chat transcript. The download button appears when the chat is closed by the operator. Permitter values: true, false. Default value: false */ this.poweredBy = this.POWERED_BY; /** link nel footer widget */ this.logoChat = this.BASE_LOCATION + this.DEFAULT_LOGO_CHAT; /** url img logo */ this.marginX = '20px'; /** set margin left or rigth widget */ this.marginY = '20px'; /** set margin bottom widget */ this.launcherWidth = '60px' /** set launcher width widget */ this.launcherHeight = '60px' /** set launcher height widget */ this.baloonImage=''; /** set launcher baloon widget image: require SVG url */ this.baloonShape = '50%'; /** set launcher balon widget shape: can set corner by corner */ this.isLogEnabled = false; // this.parameters['isLogEnabled'] = false; this.openExternalLinkButton = true; /** enable to open URL in self action link button in external page from widget */ this.hideHeaderConversationOptionsMenu = false; /** enable to hide/show options menu in conversation detail header */ this.hideSettings = false; /** enable to hide/show options menu in home component */ this.filterByRequester = false; /** show conversations with conversation.attributes.requester_id == user.uid */ this.persistence = 'local'; /** set the auth persistence */ this.preChatFormJson = [{name: "userFullname", type:"text", mandatory:true, label:{ en:"User fullname", it:"Nome utente"}},{name:"userEmail", type:"text", mandatory:true, regex:"/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)+$/", label:{ en:"Email", it: "Indirizzo email"},"errorLabel":{ en:"Invalid email address", it:"Indirizzo email non valido"}}] /** set the preChatForm Json as default if preChatFormCustomFieldsEnabled is false or not exist */ this.bubbleSentBackground = convertColorToRGBA('#2a6ac1', 100); //'#62a8ea' /** set the background of bubble sent message */ this.bubbleSentTextColor = convertColorToRGBA('#ffffff', 100); //'#ffffff' /** set the text color of bubble sent message */ this.bubbleReceivedBackground= convertColorToRGBA('#f7f7f7', 100); /** set the background of bubble received message */ this.bubbleReceivedTextColor = convertColorToRGBA('#1a1a1a', 100); //#1a1a1a /** set the text color of bubble received message */ this.fontSize = '1.4em' /** set the text size of bubble messages */ this.fontFamily = "'Roboto','Google Sans', Helvetica, Arial, sans-serif'" /** set the text family of bubble messages */ this.buttonFontSize = '15px' /** set the text size of attachment-buttons */ this.buttonBackgroundColor = convertColorToRGBA('#ffffff', 100) /** set the backgroundColor of attachment-buttons */ this.buttonTextColor = convertColorToRGBA('#2a6ac1', 100) /** set the text color of attachment-buttons */ this.buttonHoverBackgroundColor = convertColorToRGBA('#2a6ac1', 100) /** set the text size of attachment-buttons */ this.buttonHoverTextColor = convertColorToRGBA('#ffffff', 100); /** set the text size of attachment-buttons */ this.singleConversation = false; /** set the single conversation mode for the widget */ this.nativeRating = true; /** set if native rating componet has to be shown */ this.showWaitTime = true; this.showAvailableAgents = true; // this.parameters['availableAgents'] = []; this.showLogoutOption = true; this.offline_msg = this.LABEL_FIRST_MSG_NO_AGENTS; this.online_msg = this.LABEL_FIRST_MSG; this.isOpenNewMessage = false; this.showAttachmentButton = true; this.showAllConversations = true; // ============ END: SET EXTERNAL PARAMETERS ==============// // ============ BEGIN: SET INTERNAL PARAMETERS ==============// this.tenant = environment.firebaseConfig.tenant; // this.parameters['tenant'] = environment.tenant; // this.parameters.push({'tenant': environment.tenant}); /** Set the widget title label shown in the widget header. Value type : string. The default value is Tiledesk. */ /** name tenant ex: tilechat */ this.channelType = CHANNEL_TYPE_GROUP; // this.parameters['channelType'] = CHANNEL_TYPE_GROUP; // this.parameters.push({'channelType': CHANNEL_TYPE_GROUP}); /** channelType: group/direct */ this.default_settings = {}; // this.parameters.push({'default_settings': '' }); /** settings for pass variables to js */ this.isMobile = false; // this.parameters['isMobile'] = false; // this.parameters.push({'isMobile': false}); /** detect is mobile : detectIfIsMobile() */ this.isLogged = false; // this.parameters['isLogged'] = false; // this.parameters.push({'isLogged': false}); /** detect is logged */ this.BUILD_VERSION = 'v.' + environment.version; // this.parameters['BUILD_VERSION'] = 'v.' + environment.version; // this.parameters.push({'BUILD_VERSION': 'v.' + environment.version}); this.filterSystemMsg = true; /** ???? scolpito in MessagingService. se è true i messaggi inviati da system non vengono visualizzati */ // this.parameters['filterSystemMsg'] = true; // this.parameters.push({'filterSystemMsg': true}); this.soundEnabled = true; // this.parameters['soundEnabled'] = true; // this.parameters.push({'soundEnabled': true}); this.conversationsBadge = 0; // this.parameters['conversationsBadge'] = 0; // this.parameters.push({'conversationsBadge': 0}); this.activeConversation = null; // this.parameters['activeConversation'] = ''; // this.parameters.push({'activeConversation': ''}); this.isOpenMenuOptions = false; // this.parameters['isOpenMenuOptions'] = false; // this.parameters.push({'isOpenMenuOptions': false}); /** open/close menu options */ this.signInWithCustomToken = false; // this.parameters['signInWithCustomToken'] = false; // this.parameters.push({'signInWithCustomToken': false}); this.displayEyeCatcherCard = 'none'; // this.parameters['displayEyeCatcherCard'] = 'none'; // this.parameters.push({'displayEyeCatcherCard': 'none'}); // ============ END: SET INTERNAL PARAMETERS ==============// this.supportMode = true; // this.parameters['supportMode'] = true; // this.parameters.push({'supportMode': true}); this.newConversationStart = true; } /** * @param attributes */ initialize() { this.createDefaultSettingsObject(); this.setParameter('isMobile', detectIfIsMobile(this.windowContext)); this.setParameter('attributes', this.attributes); this.setProjectParameters(); } /** */ public setProjectParameters() { let projectName = this.project.name; if (this.widgetTitle && this.widgetTitle !== '') { projectName = this.widgetTitle; } this.project.customization( projectName, this.logoChat, avatarPlaceholder(projectName), setColorFromString(projectName), this.welcomeTitle, this.welcomeMsg ); // console.log('this.project::::: ', this.project); } /** * 1: setDefaultSettings */ createDefaultSettingsObject() { this.default_settings = { 'tenant': this.tenant, 'recipientId': this.recipientId, 'projectid': this.projectid, 'widgetTitle': this.widgetTitle, 'poweredBy': this.poweredBy, 'userEmail': this.userEmail, //'userId': this.userId, 'userFullname': this.userFullname, 'preChatForm': this.preChatForm, 'preChatFormJson': this.preChatFormJson, 'isOpen': this.isOpen, 'channelType': this.channelType, 'lang': this.lang, 'calloutTimer': this.calloutTimer, 'calloutStaus': this.calloutStaus, 'align': this.align,'welcomeMsg': this.welcomeMsg, 'calloutTitle': this.calloutTitle, 'calloutMsg': this.calloutMsg, 'fullscreenMode': this.fullscreenMode, 'hideHeaderCloseButton': this.hideHeaderCloseButton, 'themeColor': this.themeColor, 'themeForegroundColor': this.themeForegroundColor, 'allowTranscriptDownload': this.allowTranscriptDownload, //'userToken': this.userToken, 'autoStart': this.autoStart, 'startHidden': this.startHidden, 'isShown': this.isShown, 'startFromHome': this.startFromHome, 'logoChat': this.logoChat, 'welcomeTitle': this.welcomeTitle, 'marginX': this.marginX, 'marginY': this.marginY, 'lancherWidth': this.launcherWidth, 'lancherHeight': this.launcherHeight, 'baloonImage': this.baloonImage, 'baloonShape': this.baloonShape, 'isLogEnabled': this.isLogEnabled, 'openExternalLinkButton': this.openExternalLinkButton, 'hideHeaderConversationOptionsMenu': this.hideHeaderConversationOptionsMenu, 'hideSettings': this.hideSettings,'filterByRequester': this.filterByRequester, 'persistence': this.persistence,'showWaitTime': this.showWaitTime, 'showAvailableAgents': this.showAvailableAgents, 'showLogoutOption': this.showLogoutOption, 'showAttachmentButton': this.showAttachmentButton, 'showAllConversations': this.showAllConversations, 'jwt': this.jwt, 'dynamicWaitTimeReply': this.dynamicWaitTimeReply, 'soundEnabled': this.soundEnabled, 'logLevel': this.logLevel, 'bubbleSentBackground' : this.bubbleSentBackground, 'bubbleSentTextColor': this.bubbleSentTextColor, 'bubbleReceivedBackground': this.bubbleReceivedBackground, 'bubbleReceivedTextColor': this.bubbleReceivedTextColor, 'fontSize': this.fontSize, 'fontFamily': this.fontFamily, 'buttonFontSize': this.buttonFontSize, 'buttonBackgroundColor': this.buttonBackgroundColor, 'buttonTextColor': this.buttonTextColor, 'buttonHoverBackgroundColor': this.buttonHoverBackgroundColor, 'buttonHoverTextColor': this.buttonHoverTextColor }; } setColorWithGradient() { this.themeColor50 = convertColorToRGBA(this.themeColor, 50); // this.g.themeColor + 'CC'; this.colorGradient = 'linear-gradient(' + this.themeColor + ', ' + this.themeColor50 + ')'; this.colorGradient180 = 'linear-gradient( 180grad, ' + this.themeColor + ', ' + this.themeColor50 + ')'; this.bubbleSentBackground = 'linear-gradient( 135grad, ' + this.bubbleSentBackground + ', ' + convertColorToRGBA(this.bubbleSentBackground, 80) + ')'; } /** * * @param val */ public setIsOpen(val: boolean) { // console.log('setIsOpen', val); this.isOpen = val; this.obsIsOpen.next(val); } /** * * @param key * @param val */ public setParameter(key: string, val: any, storage?: boolean) { // storage = true; this[key] = val; const obj = {'key': key, 'val': val}; if (storage === true) { this.obsObjChanged.next(obj); } } /** * * @param key * @param val */ public setAttributeParameter(key: string, val: any) { this.attributes[key] = val; this.setParameter('attributes', this.attributes, true); } /** * * @param message */ public wdLog(message: any) { if ( this.isLogEnabled && message.length > 0 ) { message.forEach(element => console.log(element)); // console.log(message.toString()); } } }
the_stack
import * as ts from '@terascope/utils'; import ipaddr from 'ipaddr.js'; import _isIP from 'is-ip'; import ip6addr from 'ip6addr'; import validateCidr from 'is-cidr'; import PhoneValidator from 'awesome-phonenumber'; import validator from 'validator'; import * as url from 'valid-url'; import { FieldType, GeoShapePoint, MACDelimiter } from '@terascope/types'; import { FQDNOptions, HashConfig, LengthConfig, PostalCodeLocale, ArgsISSNOptions, } from './interfaces'; import * as i from '../interfaces'; export const repository: i.Repository = { isBoolean: { fn: isBoolean, config: {}, primary_input_type: i.InputType.Boolean }, isBooleanLike: { fn: isBooleanLike, config: {}, primary_input_type: i.InputType.Any }, isEmail: { fn: isEmail, config: {}, primary_input_type: i.InputType.String }, isGeoJSON: { fn: isGeoJSON, config: {}, primary_input_type: i.InputType.Object }, isGeoPoint: { fn: isGeoPoint, config: {}, primary_input_type: i.InputType.String }, isGeoShapePoint: { fn: isGeoShapePoint, config: {}, primary_input_type: i.InputType.Object }, isGeoShapePolygon: { fn: isGeoShapePolygon, config: {}, primary_input_type: i.InputType.Object }, isGeoShapeMultiPolygon: { fn: isGeoShapeMultiPolygon, config: {}, primary_input_type: i.InputType.Object }, isIP: { fn: isIP, config: {}, primary_input_type: i.InputType.String }, isISDN: { fn: isISDN, config: {}, primary_input_type: i.InputType.String }, isMACAddress: { fn: isMACAddress, config: { delimiter: { type: FieldType.String, array: true } }, primary_input_type: i.InputType.String }, isNumber: { fn: isNumber, config: {}, primary_input_type: i.InputType.Number }, isInteger: { fn: isInteger, config: {}, primary_input_type: i.InputType.Number }, inNumberRange: { fn: inNumberRange, config: { min: { type: FieldType.Number }, max: { type: FieldType.Number }, inclusive: { type: FieldType.Boolean } }, primary_input_type: i.InputType.Number }, isString: { fn: isString, config: {}, primary_input_type: i.InputType.String }, isURL: { fn: isURL, config: {}, primary_input_type: i.InputType.String }, isUUID: { fn: isUUID, config: {}, primary_input_type: i.InputType.String }, contains: { fn: contains, config: { value: { type: FieldType.String } }, primary_input_type: i.InputType.Array }, equals: { fn: equals, config: { value: { type: FieldType.String } }, primary_input_type: i.InputType.Any }, isAlpha: { fn: isAlpha, config: { locale: { type: FieldType.String } }, primary_input_type: i.InputType.String }, isAlphanumeric: { fn: isAlphanumeric, config: { locale: { type: FieldType.String } }, primary_input_type: i.InputType.String }, isASCII: { fn: isASCII, config: {}, primary_input_type: i.InputType.String }, isBase64: { fn: isBase64, config: {}, primary_input_type: i.InputType.String }, isEmpty: { fn: isEmpty, config: { ignoreWhitespace: { type: FieldType.Boolean } }, primary_input_type: i.InputType.Any }, isFQDN: { fn: isFQDN, config: { requireTld: { type: FieldType.Boolean }, allowUnderscores: { type: FieldType.Boolean }, allowTrailingDot: { type: FieldType.Boolean }, }, primary_input_type: i.InputType.String }, isHash: { fn: isHash, config: { algo: { type: FieldType.String } }, primary_input_type: i.InputType.String }, isCountryCode: { fn: isCountryCode, config: {}, primary_input_type: i.InputType.String }, isISO8601: { fn: isISO8601, config: {}, primary_input_type: i.InputType.String }, isISSN: { fn: isISSN, config: { caseSensitive: { type: FieldType.Boolean }, requireHyphen: { type: FieldType.Boolean } }, primary_input_type: i.InputType.String }, isRFC3339: { fn: isRFC3339, config: {}, primary_input_type: i.InputType.String }, isJSON: { fn: isJSON, config: {}, primary_input_type: i.InputType.String }, isLength: { fn: isLength, config: { size: { type: FieldType.Number }, min: { type: FieldType.Number }, max: { type: FieldType.Number }, }, primary_input_type: i.InputType.String }, isMIMEType: { fn: isMIMEType, config: {}, primary_input_type: i.InputType.String }, isPostalCode: { fn: isPostalCode, config: { locale: { type: FieldType.String } }, primary_input_type: i.InputType.String }, isRoutableIP: { fn: isRoutableIP, config: {}, primary_input_type: i.InputType.String }, isNonRoutableIP: { fn: isNonRoutableIP, config: {}, primary_input_type: i.InputType.String }, inIPRange: { fn: inIPRange, config: { min: { type: FieldType.String }, max: { type: FieldType.String }, cidr: { type: FieldType.String } }, primary_input_type: i.InputType.String }, isCIDR: { fn: isCIDR, config: {}, primary_input_type: i.InputType.String }, exists: { fn: exists, config: {}, primary_input_type: i.InputType.Any }, guard: { fn: guard, config: {}, primary_input_type: i.InputType.Any }, isArray: { fn: isArray, config: {}, primary_input_type: i.InputType.Array }, some: { fn: some, config: { fn: { type: FieldType.String }, options: { type: FieldType.Object } }, primary_input_type: i.InputType.Array }, every: { fn: every, config: { fn: { type: FieldType.String }, options: { type: FieldType.Object } }, primary_input_type: i.InputType.Array }, }; function _lift(fn: any, input: unknown[], parentContext?: any, args?: any) { const sanitized = input.filter(ts.isNotNil); if (sanitized.length === 0) return false; return sanitized.every((data) => fn(data, parentContext, args)); } function handleArgs(fn: any) { return (data: any, _parentContext: unknown, args: any) => fn(data, args); } /** * Checks to see if input is a boolean. * If given an array, will check if all values are booleans * * @example * FieldValidator.isBoolean(false); // true * FieldValidator.isBoolean('astring'); // false * FieldValidator.isBoolean(0); // false * FieldValidator.isBoolean([true, undefined]); // true * FieldValidator.isBoolean(['true', undefined]; // false * * @param {*} input * @returns {boolean} boolean */ export function isBoolean(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isBoolean), input, _parentContext); return ts.isBoolean(input); } /** * Checks to see if input is a boolean-like value. If an given an array, it will check * to see if all values in the array are boolean-like, does NOT ignore null/undefined values * * @example * FieldValidator.isBooleanLike(); // true * FieldValidator.isBooleanLike(null); // true * FieldValidator.isBooleanLike(0); // true * FieldValidator.isBooleanLike('0'); // true * FieldValidator.isBooleanLike('false'); // true * FieldValidator.isBooleanLike('no'); // true * FieldValidator.isBooleanLike(['no', '0', null]); // true * * @param {*} input * @returns {boolean} boolean */ export function isBooleanLike(input: unknown, _parentContext?: unknown): boolean { if (isArray(input)) return input.every(ts.isBooleanLike); return ts.isBooleanLike(input); } /** * Return true if value is a valid email, or a list of valid emails * * @example * FieldValidator.isEmail('ha3ke5@pawnage.com') // true * FieldValidator.isEmail('user@blah.com/junk.junk?a=<tag value="junk"') // true * FieldValidator.isEmail('email@example.com'); // true * FieldValidator.isEmail(12345); // false * FieldValidator.isEmail(['email@example.com', 'ha3ke5@pawnage.com']); // true * * @param {*} input * @returns {boolean} boolean */ export function isEmail(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isEmail), input, _parentContext); return ts.isEmail(input); } /** * Checks to see if input is a valid geo-point, or a list of valid geo-points * excluding null/undefined values * * @example * FieldValidator.isGeoPoint('60,80'); // true * FieldValidator.isGeoPoint([80, 60]); // true * FieldValidator.isGeoPoint({ lat: 60, lon: 80 }); // true * FieldValidator.isGeoPoint({ latitude: 60, longitude: 80 }); // true * FieldValidator.isGeoPoint(['60,80', { lat: 60, lon: 80 }]); // true * FieldValidator.isGeoPoint(['60,80', 'hello']); // false * * @param {*} input * @returns {boolean} boolean */ export function isGeoPoint(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input) && !isNumberTuple(input)) { return _lift(handleArgs(ts.parseGeoPoint), input, _parentContext, false); } // TODO: check for tuple vs an array of numbers const results = ts.parseGeoPoint(input as any, false); return results != null; } /** * Checks to see if input is a valid geo-json geometry, or a list of geo-json geometries * * @example * FieldValidator.isGeoJSON('hello'); // false * * const polygon = { * type: "Polygon", * coordinates: [ * [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], * ] * }; * FieldValidator.isGeoJSON(polygon); // true * FieldValidator.isGeoJSON([polygon, { other: 'obj'}]); // false * * @param {*} input * @returns {boolean} boolean */ export function isGeoJSON(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isGeoJSON), input, _parentContext); return ts.isGeoJSON(input); } /** * Checks to see if input is a valid geo-json point, or a list of geo-json points * @example * const polygon = { * type: "Polygon", * coordinates: [ * [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], * ] * }; * * const point = { * type: 'Point', * coordinates: [12, 12] * }; * * FieldValidator.isGeoShapePoint(polygon); // false * FieldValidator.isGeoShapePoint(point); // true * FieldValidator.isGeoShapePoint([polygon, point]); // false * FieldValidator.isGeoShapePoint([point, point]); // true * * @param {JoinGeoShape} input * @returns {boolean} boolean */ export function isGeoShapePoint( input: unknown, _parentContext?: unknown ): input is GeoShapePoint; export function isGeoShapePoint( input: unknown[], _parentContext?: unknown ): input is GeoShapePoint[]; export function isGeoShapePoint( input: unknown, _parentContext?: unknown ): input is GeoShapePoint[]|GeoShapePoint { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isGeoShapePoint), input, _parentContext); return ts.isGeoShapePoint(input as any); } /** * Checks to see if input is a valid geo-json polygon or a list of geo-json polygons * @example * FieldValidator.isGeoShapePolygon(3); // false * * const polygon = { * type: 'Polygon', * coordinates: [ * [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], * ] * }; * * const point = { * type: 'Point', * coordinates: [12, 12] * }; * * FieldValidator.isGeoShapePolygon(polygon); // true * FieldValidator.isGeoShapePolygon(point); // false * FieldValidator.isGeoShapePolygon([polygon, point]); // false * FieldValidator.isGeoShapePolygon([polygon, polygon]); // true * * @param {JoinGeoShape} input * @returns {boolean} boolean */ export function isGeoShapePolygon(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isGeoShapePolygon), input, _parentContext); return ts.isGeoShapePolygon(input as any); } /** * Checks to see if input is a valid geo-json multi-polygon or a list of geo-json multi-polygons * @example * * const polygon = { * type: "Polygon", * coordinates: [ * [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], * ] * }; * * const point = { * type: 'Point', * coordinates: [12, 12] * }; * * const multiPolygon = { * type: 'MultiPolygon', * coordinates: [ * [ * [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], * ], * [ * [[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]], * ] * ] * }; * * FieldValidator.isGeoShapeMultiPolygon(polygon); // false * FieldValidator.isGeoShapeMultiPolygon(point); // false * FieldValidator.isGeoShapeMultiPolygon(multiPolygon); // true * FieldValidator.isGeoShapeMultiPolygon([multiPolygon, multiPolygon]); // true * FieldValidator.isGeoShapeMultiPolygon([multiPolygon, point]); // false * * @param {JoinGeoShape} input * @returns {boolean} boolean */ export function isGeoShapeMultiPolygon(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isGeoShapeMultiPolygon), input, _parentContext); return ts.isGeoShapeMultiPolygon(input as any); } /** * Validates that the input is an IP address, or a list of IP addresses * * @example * * FieldValidator.isIP('8.8.8.8'); // true * FieldValidator.isIP('192.172.1.18'); // true * FieldValidator.isIP('11.0.1.18'); // true * FieldValidator.isIP('2001:db8:85a3:8d3:1319:8a2e:370:7348'); // true * FieldValidator.isIP('fe80::1ff:fe23:4567:890a%eth2'); // true * FieldValidator.isIP('2001:DB8::1'); // true * FieldValidator.isIP('172.16.0.1'); // true * FieldValidator.isIP(['172.16.0.1', '11.0.1.18']); // true * * @param {*} input * @returns {boolean} boolean */ export function isIP(input: unknown, _parentContext?: unknown): input is string { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(isValidIP, input, _parentContext); return isValidIP(input); } function isValidIP(input: unknown, _parentContext?: unknown) { if (!ts.isString(input)) return false; if (!_isIP(input)) return false; return true; } /** * Validate is input is a routable IP, or a list of routable IP's * * @example * * FieldValidator.isRoutableIP('8.8.8.8'); // true * FieldValidator.isRoutableIP('2001:db8::1'); // true * FieldValidator.isRoutableIP('172.194.0.1'); // true * FieldValidator.isRoutableIP('100.127.255.250'); // false * FieldValidator.isRoutableIP('192.168.0.1'); // false * FieldValidator.isRoutableIP(['172.194.0.1', '8.8.8.8']); // true * * @param {*} input * @returns {boolean} boolean * * see: * https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml * https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml * for ip range details */ export function isRoutableIP(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(_isRoutableIP, input, _parentContext); return _isRoutableIP(input); } function _isRoutableIP(input: unknown, _parentContext?: unknown): boolean { if (!isIP(input)) return false; return !_privateIP(input); } /** * Validate is input is a non-routable IP, or a list of non-routable IP's * * @example * * FieldValidator.isNonRoutableIP('192.168.0.1'); // true * FieldValidator.isNonRoutableIP('10.16.32.210'); // true * FieldValidator.isNonRoutableIP('fc00:db8::1'); // true * FieldValidator.isNonRoutableIP('8.8.8.8'); // false * FieldValidator.isNonRoutableIP('2001:db8::1'); // false * FieldValidator.isNonRoutableIP(['10.16.32.210', '192.168.0.1']); // true * * @param {*} input * @returns { boolean } boolean * * see: * https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml * https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml * for ip range details */ export function isNonRoutableIP(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(_isNonRoutableIP, input, _parentContext); return _isNonRoutableIP(input); } function _isNonRoutableIP(input: unknown, _parentContext?: unknown): boolean { if (!isIP(input)) return false; return _privateIP(input); } function _privateIP(input: string): boolean { const parsedIp = _parseIpAddress(input); const ipRangeName = parsedIp.range(); return _inPrivateIPRange(ipRangeName) || _inRestrictedIPRange(parsedIp); } function _parseIpAddress(input: string) { const ipv4Regex = /\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b/; const parsed = ipaddr.parse(input); // if ipv6 mapped v4 then need to return the parsed ipv4 address if (parsed.kind() === 'ipv6') { const ipv4 = input.match(ipv4Regex); if (ipv4 != null && Array.isArray(ipv4)) { return ipaddr.parse(ipv4[0]); } } return parsed; } function _inPrivateIPRange(ipRange: string) { return [ 'private', 'uniqueLocal', 'loopback', 'unspecified', 'carrierGradeNat', 'linkLocal', 'reserved', 'rfc6052', 'teredo', '6to4', 'broadcast' ].includes(ipRange); } const ipv4RestrictedRanges = [ ipaddr.parseCIDR('192.31.196.0/24'), ipaddr.parseCIDR('192.52.193.0/24'), ipaddr.parseCIDR('192.175.48.0/24'), ipaddr.parseCIDR('198.18.0.0/15'), ipaddr.parseCIDR('224.0.0.0/8') ]; const ipv6RestrictedRanges = [ ipaddr.parseCIDR('64:ff9b:1::/48'), ipaddr.parseCIDR('100::/64'), ipaddr.parseCIDR('2001::/23'), ipaddr.parseCIDR('2620:4f:8000::/48') ]; function _inRestrictedIPRange(parsedIp: ipaddr.IPv4 | ipaddr.IPv6) { const rangesToCheck = parsedIp.kind() === 'ipv4' ? ipv4RestrictedRanges : ipv6RestrictedRanges; return rangesToCheck.some((ipRange) => parsedIp.match(ipRange)); } /** * Validates that input is a cidr or a list of cidr values * * @example * * FieldValidator.isCIDR('8.8.0.0/12'); // true * FieldValidator.isCIDR('2001::1234:5678/128'); // true * FieldValidator.isCIDR('8.8.8.10'); // false * FieldValidator.isCIDR(['8.8.0.0/12', '2001::1234:5678/128']); // true * * @param {*} input * @returns {boolean} boolean */ export function isCIDR(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(_isCidr, input, _parentContext); return _isCidr(input); } function _isCidr(input: unknown, _parentContext?: unknown): boolean { if (!ts.isString(input)) return false; return validateCidr(input) > 0; } /** * Validates if the input is within a given range of IP's * @example * FieldValidator.inIPRange('8.8.8.8', {}, { cidr: '8.8.8.0/24' }); // true * FieldValidator.inIPRange('fd00::b000', {}, { min: 'fd00::123', max: 'fd00::ea00' }); // true; * FieldValidator.inIPRange('8.8.8.8', {}, { cidr: '8.8.8.10/32' }); // false * * const config = { min: '8.8.8.0', max: '8.8.8.64' }; * FieldValidator.inIPRange(['8.8.8.64', '8.8.8.8'], {}, config); // true * * @param {*} input * @param {{ min?: string; max?: string; cidr?: string }} args * @returns {boolean} boolean */ export function inIPRange( input: unknown, _parentContext: unknown, args: { min?: string; max?: string; cidr?: string } ): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(_inIPRange, input, _parentContext, args); return _inIPRange(input, args); } function _inIPRange(input: unknown, args: { min?: string; max?: string; cidr?: string }) { const MIN_IPV4_IP = '0.0.0.0'; const MAX_IPV4_IP = '255.255.255.255'; const MIN_IPV6_IP = '::'; const MAX_IPV6_IP = 'ffff.ffff.ffff.ffff.ffff.ffff.ffff.ffff'; if (!isIP(input)) return false; // assign min/max IP range values if (args.cidr) { if (!isCIDR(args.cidr)) return false; return ip6addr.createCIDR(args.cidr).contains(input); } // assign upper/lower bound even if min or max is missing let { min, max } = args; if (!min) min = _isIP.v6(input) ? MIN_IPV6_IP : MIN_IPV4_IP; if (!max) max = _isIP.v6(input) ? MAX_IPV6_IP : MAX_IPV4_IP; // min and max must be valid ips, same IP type, and min < max if (!isIP(min) || !isIP(max) || _isIP.v6(min) !== _isIP.v6(max) || ip6addr.compare(max, min) === -1) { return false; } return ip6addr.createAddrRange(min, max).contains(input); } /** * Validates that the input is a valid phone number, or a list of phone numbers * * @example * FieldValidator.isISDN('46707123456'); // true * FieldValidator.isISDN('1-808-915-6800'); // true * FieldValidator.isISDN('NOT A PHONE Number'); // false * FieldValidator.isISDN(79525554602); // true * FieldValidator.isISDN(['46707123456', '1-808-915-6800']); // true * * @param {*} input * @returns {boolean} boolean */ export function isISDN(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => { const phoneNumber = new PhoneValidator(`+${data}`); return phoneNumber.isValid(); }; return _lift(fn, input, _parentContext); } const phoneNumber = new PhoneValidator(`+${input}`); return phoneNumber.isValid(); } interface MACAddressArgs { delimiter?: MACDelimiter; } /** * Validates that the input is a MacAddress, or a list of MacAddresses * * @example * FieldValidator.isMACAddress('00:1f:f3:5b:2b:1f'); // true * FieldValidator.isMACAddress('001ff35b2b1f'); // true * FieldValidator.isMACAddress('001f.f35b.2b1f',{}, { delimiter: 'dot' }); // true * * const manyDelimiters = { delimiter: 'any' } * FieldValidator.isMACAddress('00-1f-f3-5b-2b-1f', {}, manyDelimiters); // true * FieldValidator.isMACAddress(12345); // false * * // specified colon and space delimiter only * const twoDelimiters = { delimiter: 'any }; * FieldValidator.isMACAddress('00-1f-f3-5b-2b-1f', {}, twoDelimiters ); // false, * FieldValidator.isMACAddress(['001ff35b2b1f', '00:1f:f3:5b:2b:1f']); // true * * @param {*} input * @param {{delimiter}} [{ delimiter?: string}] may be set to 'colon'|'space'|'dash'|'dot'|'none' * @returns {boolean} boolean */ export function isMACAddress( input: unknown, _parentContext?: unknown, args?: MACAddressArgs ): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { return _lift(ts.isMACAddressFP(args?.delimiter), input, _parentContext); } return ts.isMACAddress(input, args?.delimiter); } /** * Will return true if number is between args provided, or that the list * of numbers are between the values * * @example * FieldValidator.inNumberRange(42, {}, { min: 0, max: 100}); // true * FieldValidator.inNumberRange([42, 11, 94], {}, { min: 0, max: 100}); // true * FieldValidator.inNumberRange([42, 11367, 94], {}, { min: 0, max: 100}); // false * FieldValidator.inNumberRange(-42, {}, { min:0 , max: 100 }); // false * FieldValidator.inNumberRange(42, {}, { min: 0, max: 42 }); // false without the inclusive option * FieldValidator.inNumberRange(42, {}, { min: 0, max: 42, inclusive: true }) // true with inclusive * * @param {number} input * @param {{ min?: number; max?: number; inclusive?: boolean }} args * @returns {boolean} boolean */ export function inNumberRange( input: unknown, _parentContext: unknown, args: { min?: number; max?: number; inclusive?: boolean } ): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { return _lift(ts.inNumberRangeFP(args), input, _parentContext); } return ts.inNumberRange(input, args); } /** * Validates that input is a number or a list of numbers * * @example * FieldValidator.isNumber(42.32); // true * FieldValidator.isNumber('NOT A Number'); // false * FieldValidator.isNumber([42.32, 245]); // true * FieldValidator.isNumber([42.32, { some: 'obj' }]); // false * FieldValidator.isNumber('1'); // false * * @param {*} input * @returns {boolean} boolean */ export function isNumber(input: unknown, _parentContext?: unknown): input is number { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isNumber), input, _parentContext); return ts.isNumber(input); } /** * Validates that input is a integer or a list of integers * * @example * FieldValidator.isInteger(42); // true * FieldValidator.isInteger(3.14); // false * FieldValidator.isInteger(Infinity); // false * FieldValidator.isInteger('1'); // false * FieldValidator.isInteger(true); //false * FieldValidator.isInteger([42, 1]); // true * FieldValidator.isInteger([42, 3.14]); // false * * @param {*} input * @returns {boolean} boolean */ export function isInteger(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isInteger), input, _parentContext); return ts.isInteger(input); } /** * Validates that input is a string or a list of strings * * @example * FieldValidator.isString('this is a string'); // true * FieldValidator.isString(true); // false * FieldValidator.isString(['hello', 'world']); // true * FieldValidator.isString(['hello', 3]); // false * FieldValidator.isString(17.343); // false * * @param {*} input */ export function isString(input: unknown, _parentContext?: unknown): input is string { if (ts.isNil(input)) return false; if (isArray(input)) return _lift(handleArgs(ts.isString), input, _parentContext); return ts.isString(input); } /** * Validates that the input is a url or a list of urls * * @example * FieldValidator.isURL('https://someurl.cc.ru.ch'); // true * FieldValidator.isURL('ftp://someurl.bom:8080?some=bar&hi=bob'); // true * FieldValidator.isURL('http://xn--fsqu00a.xn--3lr804guic'); // true * FieldValidator.isURL('http://example.com'); // true * FieldValidator.isURL('BAD-URL'); // false * FieldValidator.isURL(['http://example.com', 'http://example.com']); // true * * @param {*} input * @returns {boolean} boolean */ export function isURL(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && url.isUri(data) !== null; return _lift(fn, input, _parentContext); } return ts.isString(input) && url.isUri(input) != null; } /** * Validates that input is a UUID or a list of UUID's * * @example * FieldValidator.isUUID('0668CF8B-27F8-2F4D-4F2D-763AC7C8F68B'); // true * FieldValidator.isUUID('BAD-UUID'); // false * FieldValidator.isUUID([ * '0668CF8B-27F8-2F4D-4F2D-763AC7C8F68B', * '123e4567-e89b-82d3-f456-426655440000' * ]); // true * * @param {*} input * @returns {boolean} boolean */ export function isUUID(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isUUID(data); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isUUID(input); } /** * Validates the input contains the values specified in args, * or that the array of inputs contains the value in args * * @example * FieldValidator.contains('hello', {}, { value: 'hello' }); // true * FieldValidator.contains('hello', {}, { value: 'll' }); // true * FieldValidator.contains(['hello', 'cello'], {}, { value: 'll' }); // true * FieldValidator.contains(['hello', 'stuff'], {}, { value: 'll' }); // false * FieldValidator.contains('12345', {}, { value: '45' }); // true * * @param {*} input * @param {{ value: string }} { value } * @returns {boolean} boolean */ export function contains( input: unknown, _parentContext: unknown, args: { value: string } ): boolean { if (ts.isNil(input)) return false; if (!args.value) throw new Error('Parameter value must provided'); if (isArray(input)) { const fn = (data: any) => ts.includes(data, args.value); return _lift(fn, input, _parentContext); } return ts.includes(input, args.value); } /** * Validates that the input matches the value, of that the input array matches the value provided * * @example * FieldValidator.equals('12345', {}, { value: '12345' }); // true * FieldValidator.equals('hello', {}, { value: 'llo' }); // false * FieldValidator.equals([3, 3], { value: 3 }); // true * * @param {*} input * @param {{ value: string }} { value } * @returns {boolean} boolean */ export function equals(input: unknown, _parentContext: unknown, args: { value: string }): boolean { if (ts.isNil(input)) return false; if (!args.value) throw new Error('A value must provided with the input'); if (isArray(input)) { const fn = (data: any) => ts.isDeepEqual(data, args.value); return _lift(fn, input, _parentContext); } return ts.isDeepEqual(input, args.value); } /** * Validates that the input is alpha or a list of alpha values * * @example * FieldValidator.isAlpha('ThiSisAsTRing'); // true * FieldValidator.isAlpha('ThisiZĄĆĘŚŁ', {}, { locale: 'pl-Pl' }); // true * FieldValidator.isAlpha('1123_not-valid'); // false * FieldValidator.isAlpha(['validString', 'more']); // true * * @param {*} input * @param {{ locale: validator.AlphaLocale }} [args] * @returns {boolean} boolean */ export function isAlpha( input: unknown, _parentContext?: unknown, args?: { locale: validator.AlphaLocale } ): boolean { if (ts.isNil(input)) return false; const locale: validator.AlphaLocale = args && args.locale ? args.locale : 'en-US'; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isAlpha(data, locale); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isAlpha(input, locale); } /** * Validates that the input is alphanumeric or a list of alphanumeric values * * @example * * FieldValidator.isAlphanumeric('123validString'); // true * FieldValidator.isAlphanumeric('فڤقکگ1234', { locale: 'ku-IQ' }); // true * FieldValidator.isAlphanumeric('-- not valid'); // false * FieldValidator.isAlphanumeric(['134', 'hello']); // true * * @param {*} input * @param {{ locale: validator.AlphanumericLocale }} [args] * @returns {boolean} boolean */ export function isAlphanumeric( input: unknown, _parentContext?: unknown, args?: { locale: validator.AlphanumericLocale } ): boolean { if (ts.isNil(input)) return false; const locale: validator.AlphanumericLocale = args && args.locale ? args.locale : 'en-US'; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isAlphanumeric(data, locale); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isAlphanumeric(input, locale); } /** * Validates that the input is ascii chars or a list of ascii chars * * @example * * FieldValidator.isASCII('ascii\s__'); // true; * FieldValidator.isASCII('˜∆˙©∂ß'); // false * FieldValidator.isASCII(['some', 'words']); // true; * * @param {*} input * @returns {boolean} boolean */ export function isASCII(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isAscii(data); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isAscii(input); } /** * Validates that the input is a base64 encoded string or a list of base64 encoded strings * * @example * FieldValidator.isBase64('ZWFzdXJlLg=='); // true * FieldValidator.isBase64('not base 64'); // false\ * FieldValidator.isBase64(['ZWFzdXJlLg==', 'ZWFzdXJlLg==']); // true * * @param {*} input * @returns {boolean} boolean */ export function isBase64(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => _validBase64(data); return _lift(fn, input, _parentContext); } return _validBase64(input); } function _validBase64(input: unknown): boolean { if (ts.isString(input)) { const validatorValid = validator.isBase64(input); if (validatorValid) { const decode = Buffer.from(input, 'base64').toString('utf8'); const encode = Buffer.from(decode, 'utf8').toString('base64'); return input === encode; } } return false; } /** * Validates that the input is empty * @example * FieldValidator.isEmpty(''); // true * FieldValidator.isEmpty(undefined); // true * FieldValidator.isEmpty(null); // true * FieldValidator.isEmpty({ foo: 'bar' }); // false * FieldValidator.isEmpty({}); // true * FieldValidator.isEmpty([]); // true * FieldValidator.isEmpty(' ', {}, { ignoreWhitespace: true }); // true * * @param {*} input * @param {{ ignoreWhitespace: boolean }} [args] set to true if you want the value to be trimmed * @returns {boolean} boolean */ export function isEmpty( input: unknown, _parentContext?: unknown, args?: { ignoreWhitespace: boolean } ): boolean { let value = input; if (!isArray(value) && ts.isString(value) && args && args.ignoreWhitespace) { value = value.trim(); } return ts.isEmpty(value); } /** * Validate that the input is a valid domain name, or a list of domain names * * @example * * FieldValidator.isFQDN('example.com.uk'); // true * FieldValidator.isFQDN('notadomain'); // false * FieldValidator.isFQDN(['example.com.uk', 'google.com']); // true * * @param {*} input * @param {args} [{ require_tld = true, allow_underscores = false, allow_trailing_dot = false}] * @returns {boolean} boolean */ export function isFQDN(input: unknown, _parentContext?: unknown, args?: FQDNOptions): boolean { if (ts.isNil(input)) return false; const config = { require_tld: args?.requireTld || true, allow_underscores: args?.allowUnderscores || false, allow_trailing_dot: args?.allowTrailingDot || false }; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isFQDN(data, config); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isFQDN(input, config); } /** * Validates that the input is a hash, or a list of hashes * * @example * const md5Config = { algo: 'md5'}; * const sha256Config = { algo: 'sha256' } * const sha1Config = { algo: 'sha1' } * * FieldValidator.isHash('6201b3d1815444c87e00963fcf008c1e', {}, { algo: 'md5' }); // true * FieldValidator.isHash( * '85031b6f407e7f25cf826193338f7a4c2dc8c8b5130f5ca2c69a66d9f5107e33', * {}, * { algo: 'sha256' } * ); // true * * FieldValidator.isHash('98fc121ea4c749f2b06e4a768b92ef1c740625a0', {}, { algo: 'sha1' }); // true * FieldValidator.isHash(['6201b3d1815444c87e00963fcf008c1e', undefined], * {}, * { algo: 'md5' } * ); // true * * @param {*} input * @param {HashConfig} { algo } * @returns {boolean} boolean */ export function isHash(input: unknown, _parentContext: unknown, args: HashConfig): boolean { if (ts.isNil(input)) return false; if (args?.algo === undefined) throw new Error('Parameter property algo was not provided'); if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isHash(data, args.algo); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isHash(input, args.algo); } /** * Validates that input is a valid country code or a list of country codes * * @example * * FieldValidator.isCountryCode('IS'); // true * FieldValidator.isCountryCode('ru'); // true * FieldValidator.isCountryCode('USA'); // false * FieldValidator.isCountryCode(['IS', 'ru']); // true * * @param {*} input * @returns {boolean} boolean */ export function isCountryCode(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isISO31661Alpha2(data); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isISO31661Alpha2(input); } /** * Checks to see if input is a valid ISO8601 string dates or a list of valid dates * @example * FieldValidator.isISO8601('2020-01-01T12:03:03.494Z'); // true * FieldValidator.isISO8601('2020-01-01'); // true * FieldValidator.isISO8601('2020-01-01T12:03:03'); // true * * @param {*} input * @returns {boolean} boolean */ export function isISO8601(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isISO8601(data); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isISO8601(input); } /** * Validates that input is a valid ISSN or a list of valid ISSN * * @example * * FieldValidator.isISSN('0378-5955'); // true * FieldValidator.isISSN('03785955'); // true * FieldValidator.isISSN('0378-5955', {}, { requireHyphen: true }); // true * FieldValidator.isISSN(['0378-5955', '0000-006x']); // true * * @param {*} input * @param {ArgsISSNOptions} [{ requireHyphen?: boolean; caseSensitive?: boolean;}] * @returns {boolean} boolean */ export function isISSN(input: unknown, _parentContext?: unknown, args?: ArgsISSNOptions): boolean { if (ts.isNil(input)) return false; const config = { case_sensitive: args?.caseSensitive || false, require_hyphen: args?.requireHyphen || false }; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isISSN(data, config); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isISSN(input, config); } /** * Validates that input is a valid RFC3339 dates or a list of valid RFC3339 dates * * @example * FieldValidator.isRFC3339('2020-01-01T12:05:05.001Z'); // true * FieldValidator.isRFC3339('2020-01-01 12:05:05.001Z'); // true * FieldValidator.isRFC3339('2020-01-01T12:05:05Z'); // true * FieldValidator.isRFC3339(['2020-01-01T12:05:05Z', '2020-01-01T12:05:05.001Z']); // true * * @param {*} input * @returns {boolean} boolean */ export function isRFC3339(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isRFC3339(data); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isRFC3339(input); } /** * Validates that input is a valid JSON string or a list of valid JSON * * @example * FieldValidator.isJSON('{ "bob": "gibson" }'); // true * FieldValidator.isJSON({ bob: 'gibson' }); // false * FieldValidator.isJSON('[]'); // true * FieldValidator.isJSON('{}'); // true * FieldValidator.isJSON(['{ "bob": "gibson" }', '[]']); // true * * @param {*} input * @returns {boolean} boolean */ export function isJSON(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isJSON(data); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isJSON(input); } /** * Check to see if input is a string with given length ranges, or a list of valid string lengths * @example * FieldValidator.isLength('astring', { size: 7 }); // true * FieldValidator.isLength('astring', { min: 3, max: 10 }); // true * FieldValidator.isLength('astring', { size: 10 }); // false * FieldValidator.isLength('astring', {}, { min: 8 }); // false * FieldValidator.isLength(['astring', 'stuff', 'other'], { min: 3, max: 10 }); // true * * @param {*} input * @param {LengthConfig} { size, min, max } * @returns {boolean} boolean */ export function isLength( input: unknown, _parentContext: unknown, { size, min, max }: LengthConfig ): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => { if (size) return ts.isString(data) && data.length === size; if (min || max) return validator.isLength(data, { min, max }); return false; }; return _lift(fn, input, _parentContext); } if (isString(input)) { if (size) return input.length === size; if (min || max) return validator.isLength(input, { min, max }); } return false; } /** * Validates that input is a valid mimeType or a list of mimeTypes * * @example * * FieldValidator.isMIMEType('application/javascript'); // true * FieldValidator.isMIMEType('application/graphql'); // true * FieldValidator.isMIMEType(12345); // false * FieldValidator.isMIMEType(['application/graphql', 'application/javascript']); // true * * @param {*} input * @returns {boolean} boolean */ export function isMIMEType(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isMimeType(data); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isMimeType(input); } /** * Validates that input is a valid postal code or a list of postal codes * * @example * * FieldValidator.isPostalCode('85249'); // true * FieldValidator.isPostalCode('85249', {}, { locale: 'any' }); // true * FieldValidator.isPostalCode('85249', {}, { locale: 'ES' }); // false * FieldValidator.isPostalCode('852', {}, { locale: 'IS' }); // true * FieldValidator.isPostalCode('885 49', {}, { locale: 'SE' }); // true * FieldValidator.isPostalCode(1234567890); // false * FieldValidator.isPostalCode(['85249']); // true * * @param {*} input * @param {({ locale: 'any' | PostalCodeLocale })} { locale } * @returns {boolean} boolean */ export function isPostalCode(input: unknown, _parentContext: unknown, args: { locale: 'any' | PostalCodeLocale }): boolean { if (ts.isNil(input)) return false; if (!args?.locale) throw new Error('Invalid parameter locale, must provide an object with locale'); if (isArray(input)) { const fn = (data: any) => ts.isString(data) && validator.isPostalCode(data, args.locale); return _lift(fn, input, _parentContext); } return ts.isString(input) && validator.isPostalCode(input, args.locale); } /** * Validates that the input is a valid date or a list of valid dates * * @example * FieldValidator.isValidDate('2019-03-17T23:08:59.673Z'); // true * FieldValidator.isValidDate('2019-03-17'); // true * FieldValidator.isValidDate('2019-03-17T23:08:59'); // true * FieldValidator.isValidDate('03/17/2019'); // true * FieldValidator.isValidDate('03-17-2019'); // true * FieldValidator.isValidDate('Jan 22, 2012'); // true * FieldValidator.isValidDate('23 Jan 2012'); // true * FieldValidator.isValidDate(1552000139); // true * FieldValidator.isValidDate('1552000139'); // false * FieldValidator.isValidDate(['2019-03-17', 1552000139]); // true; * * @param {*} input * @returns {boolean} boolean */ export function isValidDate(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) return false; if (isArray(input)) { return _lift(handleArgs(ts.isValidDate), input, _parentContext); } return !ts.isBoolean(input as any) && ts.isValidDate(input); } /** * Will throw if input is null or undefined * * @example * * FieldValidator.guard({ hello: 'world' }); // true * FieldValidator.guard(); // WILL THROW * * @param {*} input * @returns {boolean} boolean */ export function guard(input: unknown, _parentContext?: unknown): boolean { if (ts.isNil(input)) throw new Error('Expected value not to be empty'); return true; } /** * Will return false if input is null or undefined * * @example * * FieldValidator.exists({ hello: 'world' }); // true * FieldValidator.exists(null); // false * * @param {*} input * @returns {boolean} boolean */ export function exists(input: unknown, _parentContext?: unknown): boolean { return ts.isNotNil(input); } /** * Validates that the input is an array * @example * FieldValidator.isArray(undefined); // false * FieldValidator.isArray([1, 2, 3]); // true * FieldValidator.isArray([]); // true * * @param {*} input * @returns {boolean} boolean */ export function isArray(input: unknown, _parentContext?: unknown): input is any[] { return ts.isArrayLike(input); } /** * Validates that the function specified returns true at least once on the list of values * * @example * * const mixedArray = ['hello', 3, { some: 'obj' }]; * FieldValidator.some(mixedArray, mixedArray, fn: 'isString' }); // true * FieldValidator.some(mixedArray, mixedArray, { fn: 'isBoolean' }); // false * * @param {*} input * @param {{ fn: string; options?: any }} { fn, options } fn is the name of method on FieldValidator * options is any other arguments necessary for that function call * @returns {boolean} boolean */ export function some( input: unknown, _parentContext: unknown, { fn, options }: { fn: string; options?: any } ): boolean { if (!isArray(input)) return false; const repoConfig = repository[fn]; if (!repoConfig) throw new Error(`No function ${fn} was found in the field validator repository`); return input.some((data: any) => repoConfig.fn(data, data, options)); } /** * Validates that the function specified returns true for every single value in the list * * @example * const mixedArray = ['hello', 3, { some: 'obj' }]; * const strArray = ['hello', 'world']; * * FieldValidator.every([mixedArray, mixedArray { fn: 'isString' }); // false * FieldValidator.every(strArray, strArray, { fn: 'isString' }); // true * * @param {*} input * @param {{ fn: string; options?: any }} { fn, options } fn is the name of method on FieldValidator * options is any other arguments necessary for that function call * @returns {boolean} boolean */ export function every( input: unknown, _parentContext: unknown, { fn, options }: { fn: string; options?: any } ): boolean { if (!isArray(input)) return false; const repoConfig = repository[fn]; if (!repoConfig) throw new Error(`No function ${fn} was found in the field validator repository`); return input.every((data: any) => repoConfig.fn(data, data, options)); } export function isNumberTuple(input: unknown, _parentContext?: unknown): boolean { if (Array.isArray(input) && input.length === 2) { return input.every(isNumber); } return false; }
the_stack
import * as ui from "../../ui"; import * as csx from "../../base/csx"; import * as React from "react"; var ReactDOM = require("react-dom"); import * as tab from "./tab"; import { server, cast } from "../../../socket/socketClient"; import * as commands from "../../commands/commands"; import * as utils from "../../../common/utils"; import * as d3 from "d3"; import * as $ from "jquery"; import * as styles from "../../styles/styles"; import * as onresize from "onresize"; import { Clipboard } from "../../components/clipboard"; import { Types } from "../../../socket/socketContract"; import { Icon } from "../../components/icon"; import * as Mousetrap from "mousetrap"; import { Robocop } from "../../components/robocop"; import * as pure from "../../../common/pure"; import * as buttons from "../../components/buttons"; import * as types from "../../../common/types"; import * as gls from "../../base/gls"; import * as typestyle from "typestyle"; type NodeDisplay = Types.NodeDisplay; let EOL = '\n'; /** * The styles */ import { inputCodeStyle, searchOptionsLabelStyle } from "../../findAndReplace"; let {inputBlackStyleBase} = styles.Input; const inputBlackClassName = typestyle.style(inputBlackStyleBase); namespace ResultsStyles { export const rootClassName = typestyle.style( csx.flex, csx.scroll as any, styles.padded1, { border: '1px solid grey', $nest: { '&:focus': { outline: 'none', border: '1px solid ' + styles.highlightColor, } } } ); export const header = csx.extend( styles.padded1, { cursor: 'default', fontSize: '1.5em', fontWeight: 'bold', color: styles.textColor, background: 'black', border: '2px solid grey', } ); export let preview = { padding: '3px', background: 'black', cursor: 'pointer', userSelect: 'text', } export let selected = { backgroundColor: styles.selectedBackgroundColor }; export const noFocusClassName = typestyle.style( { $nest: { '&:focus': { outline: 'none' } } } ) } /** * Props / State */ export interface Props extends tab.TabProps { } export interface State { completed?: boolean; results?: Types.FarmResultDetails[]; config?: Types.FarmConfig; farmResultByFilePath?: Types.FarmResultsByFilePath; /** * Results view state */ collapsedState?: { [filePath: string]: boolean }; selected?: { filePath?: string; /* If we have a filePath selected (instead of a search result) we set this to -1*/ line?: number; }; queryRegex?: RegExp; /** * Search state */ findQuery?: string; replaceQuery?: string; isRegex?: boolean; isCaseSensitive?: boolean; isFullWord?: boolean; } export class FindAndReplaceView extends ui.BaseComponent<Props, State> { constructor(props: Props) { super(props); let {protocol, filePath} = utils.getFilePathAndProtocolFromUrl(props.url); this.filePath = filePath; this.state = { completed: true, farmResultByFilePath: {}, collapsedState: {}, selected: {}, }; } filePath: string; mode: Types.ASTMode; componentDidMount() { /** * Keyboard: Focus */ this.focusOnInput(); // On initial mount as well :) this.disposible.add(commands.findAndReplace.on(this.focusOnInput)); this.disposible.add(commands.findAndReplaceMulti.on(this.focusOnInput)); /** * Keyboard: Stop */ this.disposible.add(commands.esc.on(() => { // Disabled as esc is used to focus search results as well // this.cancelAnyRunningSearch(); })); /** * Initial load && keeping it updated */ server.farmResults({}).then(res => { this.parseResults(res); }); this.disposible.add(cast.farmResultsUpdated.on(res => { this.parseResults(res); })); /** * Handle the keyboard in the search results */ let treeRoot = this.refs.results; let handlers = new Mousetrap(treeRoot); let selectFirst = () => { if (this.state.results && this.state.results.length) { this.setSelected(this.state.results[0].filePath, -1); } } handlers.bind('up', () => { // initial state if (!this.state.results || !this.state.results.length) return false; if (!this.state.selected.filePath) { selectFirst(); return false; } /** If we have an actual line go to previous or filePath */ if (this.state.selected.line !== -1) { const relevantResults = this.state.farmResultByFilePath[this.state.selected.filePath]; const indexInResults = relevantResults .map(x => x.line) .indexOf(this.state.selected.line); if (indexInResults === 0) { this.setSelected(this.state.selected.filePath, -1) } else { this.setSelected(this.state.selected.filePath, relevantResults[indexInResults - 1].line); } } /** Else go to the previous filePath (if any) (collapsed) the filePath (expanded) last child */ else { let filePaths = Object.keys(this.state.farmResultByFilePath); let filePathIndex = filePaths.indexOf(this.state.selected.filePath); if (filePathIndex === 0) return false; let previousFilePath = filePaths[filePathIndex - 1]; if (this.state.collapsedState[previousFilePath]) { this.setSelected(previousFilePath, -1); } else { let results = this.state.farmResultByFilePath[previousFilePath]; this.setSelected(previousFilePath, results[results.length - 1].line); } } return false; }); handlers.bind('down', () => { if (!this.state.results || !this.state.results.length) return false; if (!this.state.selected.filePath) { selectFirst(); return false; } /** If we are on a filePath (collaped) go to next filePath if any (expanded) go to first child */ if (this.state.selected.line === -1) { if (this.state.collapsedState[this.state.selected.filePath]) { let filePaths = Object.keys(this.state.farmResultByFilePath); let filePathIndex = filePaths.indexOf(this.state.selected.filePath); if (filePathIndex === filePaths.length - 1) return false; let nextFilePath = filePaths[filePathIndex + 1]; this.setSelected(nextFilePath, -1); } else { let results = this.state.farmResultByFilePath[this.state.selected.filePath]; this.setSelected(results[0].filePath, results[0].line); } } /** Else if last in the group go to next filePath if any, otherwise goto next sibling */ else { let results = this.state.farmResultByFilePath[this.state.selected.filePath]; let indexIntoResults = results.map(x => x.line).indexOf(this.state.selected.line); if (indexIntoResults === results.length - 1) { // Goto next filePath if any let filePaths = Object.keys(this.state.farmResultByFilePath); let filePathIndex = filePaths.indexOf(this.state.selected.filePath); if (filePathIndex === filePaths.length - 1) return false; let nextFilePath = filePaths[filePathIndex + 1]; this.setSelected(nextFilePath, -1); } else { let nextResult = results[indexIntoResults + 1]; this.setSelected(nextResult.filePath, nextResult.line); } } return false; }); handlers.bind('left', () => { /** Just select and collapse the folder irrespective of our current state */ if (!this.state.results || !this.state.results.length) return false; if (!this.state.selected.filePath) return false; this.state.collapsedState[this.state.selected.filePath] = true; this.setState({ collapsedState: this.state.collapsedState }); this.setSelected(this.state.selected.filePath, -1); return false; }); handlers.bind('right', () => { /** Expand only if a filePath root is currently selected */ if (!this.state.results || !this.state.results.length) return false; this.state.collapsedState[this.state.selected.filePath] = false; this.setState({ collapsedState: this.state.collapsedState }); return false; }); handlers.bind('enter', () => { /** Enter always takes you into the filePath */ if (!this.state.results || !this.state.results.length) return false; if (!this.state.selected.filePath) { selectFirst(); } this.openSearchResult(this.state.selected.filePath, this.state.selected.line); return false; }); // Listen to tab events const api = this.props.api; this.disposible.add(api.resize.on(this.resize)); this.disposible.add(api.focus.on(this.focus)); this.disposible.add(api.save.on(this.save)); this.disposible.add(api.close.on(this.close)); this.disposible.add(api.gotoPosition.on(this.gotoPosition)); // Listen to search tab events this.disposible.add(api.search.doSearch.on(this.search.doSearch)); this.disposible.add(api.search.hideSearch.on(this.search.hideSearch)); this.disposible.add(api.search.findNext.on(this.search.findNext)); this.disposible.add(api.search.findPrevious.on(this.search.findPrevious)); this.disposible.add(api.search.replaceNext.on(this.search.replaceNext)); this.disposible.add(api.search.replacePrevious.on(this.search.replacePrevious)); this.disposible.add(api.search.replaceAll.on(this.search.replaceAll)); } refs: { [string: string]: any; results: HTMLDivElement; find: JSX.Element; replace: JSX.Element; regex: { refs: { input: JSX.Element } }; caseInsensitive: { refs: { input: JSX.Element } }; fullWord: { refs: { input: JSX.Element } }; } findInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.find); replaceInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.replace); regexInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.regex.refs.input); caseInsensitiveInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.caseInsensitive.refs.input); fullWordInput = (): HTMLInputElement => ReactDOM.findDOMNode(this.refs.fullWord.refs.input); replaceWith = () => this.replaceInput().value; render() { let hasSearch = !!this.state.config; let rendered = ( <div className={ResultsStyles.noFocusClassName} style={csx.extend(csx.vertical, csx.flex, styles.someChildWillScroll)}> <div ref="results" tabIndex={0} className={ResultsStyles.rootClassName}> { hasSearch ? this.renderSearchResults() : <div style={ResultsStyles.header}>No Search</div> } </div> <div style={csx.extend(csx.content, styles.padded1)}> { this.renderSearchControls() } </div> </div> ); return rendered; } renderSearchControls() { return ( <div style={csx.vertical}> <div style={csx.extend(csx.horizontal, csx.center)}> <div style={csx.extend(csx.flex, csx.vertical)}> <div style={csx.extend(csx.horizontal, csx.center, styles.padded1)}> <input tabIndex={1} ref="find" placeholder="Find" className={inputBlackClassName} style={csx.extend(inputCodeStyle, csx.flex)} onKeyDown={this.findKeyDownHandler} onChange={this.findChanged} defaultValue={''} /> </div> </div> <div style={csx.content}> <div style={csx.extend(csx.horizontal, csx.aroundJustified, styles.padded1)}> <label style={csx.extend(csx.horizontal, csx.center)}> <ui.Toggle tabIndex={3} ref="regex" onChange={this.handleRegexChange} /> <span style={searchOptionsLabelStyle as any}> .* </span> </label> <label style={csx.extend(csx.horizontal, csx.center)}> <ui.Toggle tabIndex={4} ref="caseInsensitive" onChange={this.handleCaseSensitiveChange} /> <span style={searchOptionsLabelStyle as any}> Aa </span> </label> <label style={csx.extend(csx.horizontal, csx.center)}> <ui.Toggle tabIndex={5} ref="fullWord" onKeyDown={this.fullWordKeyDownHandler} onChange={this.handleFullWordChange} /> <span style={searchOptionsLabelStyle as any}> <Icon name="text-width" /> </span> </label> </div> </div> </div> <div style={styles.Tip.root}> <div> Controls: {' '}<span style={styles.Tip.keyboardShortCutStyle}>Esc</span> to focus on results {' '}<span style={styles.Tip.keyboardShortCutStyle}>Enter</span> to start/restart search {' '}<span style={styles.Tip.keyboardShortCutStyle}>Toggle 🔘 switches</span> start/restart search </div> <div> Results: {' '}<span style={styles.Tip.keyboardShortCutStyle}>Up/Down</span> to go through results {' '}<span style={styles.Tip.keyboardShortCutStyle}>Enter</span> to open a search result </div> { /* Disabled Replace as that is not the core focus of my work at the moment {' '}<span style={styles.Tip.keyboardShortCutStyle}>{commands.modName} + Enter</span> to replace {' '}<span style={styles.Tip.keyboardShortCutStyle}>{commands.modName} + Shift + Enter</span> to replace all */ } </div> </div> ); } renderSearchResults() { let filePaths = Object.keys(this.state.farmResultByFilePath); let queryRegex = this.state.queryRegex; let queryRegexStr = (this.state.queryRegex && this.state.queryRegex.toString()) || ''; queryRegexStr = queryRegexStr && ` (Query : ${queryRegexStr}) ` return ( <div style={csx.extend(csx.flex, styles.errorsPanel.main, { userSelect: 'none' })}> <div style={csx.extend(ResultsStyles.header, csx.horizontal)}> Total Results ({this.state.results.length}) { (this.state.results.length >= types.maxCountFindAndReplaceMultiResults) && <span className="hint--info hint--bottom" data-hint={`(search limited to ${types.maxCountFindAndReplaceMultiResults})`}>(+)</span> } { !this.state.completed && <span> <gls.SmallHorizontalSpace /> <buttons.ButtonBlack key="button" onClick={this.cancelAnyRunningSearch} text={"Cancel"} /> </span> } <span style={csx.flex} /> {queryRegexStr} </div> { filePaths.map((filePath, i) => { let results = this.state.farmResultByFilePath[filePath]; let selectedRoot = filePath === this.state.selected.filePath && this.state.selected.line == -1 let selectedResultLine = filePath === this.state.selected.filePath ? this.state.selected.line : -2 /* -2 means not selected */; return ( <FileResults.FileResults key={i} ref={filePath} filePath={filePath} results={results} queryRegex={this.state.queryRegex} expanded={!this.state.collapsedState[filePath]} onClickFilePath={this.toggleFilePathExpansion} openSearchResult={this.openSearchResult} selectedRoot={selectedRoot} selectedResultLine={selectedResultLine} /> ); }) } </div> ); } toggleFilePathExpansion = (filePath: string) => { this.state.collapsedState[filePath] = !this.state.collapsedState[filePath]; this.setState({ collapsedState: this.state.collapsedState, selected: { filePath, line: -1 } }); } /** * Scrolling through results */ resultRef(filePath: string) { const ref = filePath; return this.refs[ref] as FileResults.FileResults; } /** * Input Change handlers */ fullWordKeyDownHandler = (e: React.SyntheticEvent<any>) => { let {tab, shift, enter} = ui.getKeyStates(e); if (tab && !shift) { this.findInput().focus(); e.preventDefault(); return; } }; findKeyDownHandler = (e: React.SyntheticEvent<any>) => { let {tab, shift, enter, mod} = ui.getKeyStates(e); if (shift && tab) { this.fullWordInput() && this.fullWordInput().focus(); e.preventDefault(); return; } /** * Handling commit */ if (!this.state.findQuery) { return; } if (enter) { this.startSearch(); } }; findChanged = () => { let val = this.findInput().value.trim(); this.setState({ findQuery: val }); }; handleRegexChange = (e) => { let val: boolean = e.target.checked; this.setState({ isRegex: val }); this.startSearch(); } handleCaseSensitiveChange = (e) => { let val: boolean = e.target.checked; this.setState({ isCaseSensitive: val }); this.startSearch(); } handleFullWordChange = (e) => { let val: boolean = e.target.checked; this.setState({ isFullWord: val }); this.startSearch(); } /** * Sends the search query * debounced as state needs to be set before this execs */ startSearch = utils.debounce(() => { const config: Types.FarmConfig = { query: this.state.findQuery, isRegex: this.state.isRegex, isFullWord: this.state.isFullWord, isCaseSensitive: this.state.isCaseSensitive, globs: [] }; server.startFarming(config); this.setState({ // Clear previous search collapsedState: {}, selected: {}, // Set new results preemptively results: [], config, queryRegex: utils.findOptionsToQueryRegex({ query: config.query, isRegex: config.isRegex, isFullWord: config.isFullWord, isCaseSensitive: config.isCaseSensitive, }), completed: false, farmResultByFilePath: {}, }); }, 100); cancelAnyRunningSearch = () => { server.stopFarmingIfRunning({}); }; /** Parses results as they come and puts them into the state */ parseResults(response: Types.FarmNotification) { // Convert as needed // console.log(response); // DEBUG let results = response.results; let loaded: Types.FarmResultsByFilePath = utils.createMapByKey(results, result => result.filePath); let queryRegex = response.config ? utils.findOptionsToQueryRegex({ query: response.config.query, isRegex: response.config.isRegex, isFullWord: response.config.isFullWord, isCaseSensitive: response.config.isCaseSensitive, }) : null; // Finally rerender this.setState({ results: results, config: response.config, queryRegex, completed: response.completed, farmResultByFilePath: loaded }); } openSearchResult = (filePath: string, line: number) => { commands.doOpenOrFocusFile.emit({ filePath, position: { line: line - 1, ch: 0 } }); this.setSelected(filePath, line); } setSelected = (filePath: string, line: number) => { this.setState({ selected: { filePath, line } }); this.focusFilePath(filePath, line); } focusFilePath = (filePath: string, line: number) => { this.resultRef(filePath).focus(filePath, line); }; /** * TAB implementation */ resize = () => { // This layout doesn't need it } /** Allows us to focus on input on certain keystrokes instead of search results */ focusOnInput = () => setTimeout(() => this.findInput().focus(), 500); focus = () => { this.refs.results.focus(); } save = () => { } close = () => { } gotoPosition = (position: EditorPosition) => { } search = { doSearch: (options: FindOptions) => { // not needed }, hideSearch: () => { // not needed }, findNext: (options: FindOptions) => { }, findPrevious: (options: FindOptions) => { }, replaceNext: ({newText}: { newText: string }) => { }, replacePrevious: ({newText}: { newText: string }) => { }, replaceAll: ({newText}: { newText: string }) => { } } } namespace FileResults { export interface Props { filePath: string; results: Types.FarmResultDetails[]; expanded: boolean; onClickFilePath: (filePath: string) => any; openSearchResult: (filePath: string, line: number) => any; selectedRoot: boolean; selectedResultLine: number; queryRegex: RegExp; } export interface State { } export class FileResults extends React.PureComponent<Props, State>{ render() { let selectedStyle = this.props.selectedRoot ? ResultsStyles.selected : {}; return ( <div onClick={() => this.props.onClickFilePath(this.props.filePath)}> <div ref={this.props.filePath + ':' + -1} tabIndex={0} className={ResultsStyles.noFocusClassName} style={ csx.extend( selectedStyle, styles.errorsPanel.filePath, { margin: '8px 0px', padding: '3px' } ) }> {!this.props.expanded ? "+" : "-"} {this.props.filePath} ({this.props.results.length}) </div> {!this.props.expanded ? <noscript /> : this.renderResultsForFilePath(this.props.results)} </div> ); } renderResultsForFilePath = (results: Types.FarmResultDetails[]) => { return results.map((result, i) => { let selectedStyle = this.props.selectedResultLine === result.line ? ResultsStyles.selected : {}; return ( <div key={i} ref={result.filePath + ':' + result.line} tabIndex={0} className={ResultsStyles.noFocusClassName} style={ csx.extend( styles.padded1, { cursor: 'pointer', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'pre', }, selectedStyle ) } onClick={(e) => { e.stopPropagation(); this.props.openSearchResult(result.filePath, result.line) } }> {utils.padLeft((result.line).toString(), 6)} : <span style={ResultsStyles.preview}>{this.renderMatched(result.preview, this.props.queryRegex)}</span> </div> ); }) } focus(filePath: string, line: number) { let dom = this.refs[this.props.filePath + ':' + line] as HTMLDivElement; dom.scrollIntoViewIfNeeded(false); } renderMatched(preview: string, queryRegex: RegExp) { let matched = this.getMatchedSegments(preview, queryRegex); let matchedStyle = { fontWeight: 'bold' as 'bold', color: '#66d9ef' }; return matched.map((item, i) => { return <span key={i} style={item.matched ? matchedStyle : {}}>{item.str}</span>; }); } getMatchedSegments(preview: string, queryRegex: RegExp) { // A data structure which is efficient to render type MatchedSegments = { str: string, matched: boolean }[]; let result: MatchedSegments = []; var match; let previewCollectedIndex = 0; let collectUnmatched = (matchStart: number, matchLength: number) => { if (previewCollectedIndex < matchStart) { result.push({ str: preview.substring(previewCollectedIndex, matchStart), matched: false }); previewCollectedIndex = (matchStart + matchLength); } }; while (match = queryRegex.exec(preview)) { let matchStart = match.index; let matchLength = match[0].length; // let nextMatchStart = queryRegex.lastIndex; // Since we don't need it // If we have an unmatched string portion that is still not collected // Collect it :) collectUnmatched(matchStart, matchLength); result.push({ str: preview.substr(matchStart, matchLength), matched: true }); } // If we still have some string portion uncollected, collect it if (previewCollectedIndex !== preview.length) { collectUnmatched(preview.length, 0); } return result; } } }
the_stack
import { MOD_IP, MOD_UDP, MOD_UDP_SOCKET } from "../../components/rust/std_net"; export const FULL_DEMO_CODE = `// This code sends a request to a name server 1.2.3.4 and returns the resulting IP address. // When you click the Resolve button, the code here is executed and you // can see both how the message travels on the network and how it looks // internally. // Don't worry if you don't understand the code or networking details yet— // we'll go over it step-by-step on the following pages. But you can try // changing it; see if the result changes too! const DOMAIN_NAME_REQUEST: &[u8] = b"Alice"; const DNS_SERVER: &str = "1.2.3.4:53"; // address of the DNS server let socket = UdpSocket::bind("10.0.0.1:1000").expect("couldn't bind to address"); socket .send_to(DOMAIN_NAME_REQUEST, DNS_SERVER) .expect("couldn't send message"); let mut response_data_buffer = [0u8; 4]; let (size, sender) = socket .recv_from(&mut response_data_buffer) .expect("failed to receive data"); let ip_address = IpAddr::V4(Ipv4Addr::from(response_data_buffer)); return Ok(ip_address);`; const IP_HEADER_CODE = `// An IP packet can be divided into two parts: a header and a payload. // The header is where we put a destination IP address, our own address (also // known as the source address), and some more helpful information. // An IP header is just a sequence of 20 bytes. // Let's allocate an array to store our header: let mut header_data = [0u8; 20]; // Each group of bytes in the header means something, but it would have been // inconvenient to always remember that, for example, \`header_data[3..4]\` // should be interpreted as the packet size. In order to simplify this, we // use an \`Ipv4Packet\` structure which implements helper functions to work // with individual components of the header. We wrap the packet header data // into this structure: let mut ip_packet = Ipv4Packet::new(header_data); // First, let's construct our own IP address and then put it into the header // as the source address. // IP addresses are also encoded as numbers: each component of an address is // represented by a single unsigned byte (a number between 0 and 255). // As a result, an address like \`10.0.0.1\` will be represented by // 4 bytes \`[10, 0, 0, 1]\`, which also can be encoded as a single large // 32-bit number: 167772161. // We use a helper type from the Rust standard library, \`Ipv4Addr\`, which can // be constructed with \`Ipv4Addr::new\` - we put the address component bytes as // arguments, and this function does everything for us, constructing a valid // IP address. let our_own_address = Ipv4Addr::new(10, 0, 0, 1); // Finally, we can add the source address to the header: ip_packet.set_src_addr(our_own_address); // Now let's do the same thing with the destination address // (1.2.3.4 is the IP address of the name server): let name_server_address = Ipv4Addr::new(1, 2, 3, 4); ip_packet.set_dst_addr(name_server_address); // One header field that is particularly interesting to us is the protocol // identifier. It tells how the message payload should be interpreted by the // receiver. In this case, our packet payload uses UDP, which is identified by // the number 17. ip_packet.set_protocol(Protocol::Udp); // Now we also need to add some meta-information to the packet // First thing is the IP protocol version. Currently, there are two versions in // use on the Internet, versions 4 and 6. In this lesson, we have been working // with the version 4 only, so let's use it: ip_packet.set_version(4); // We also need to provide the size of the header (which we know is 20 bytes). ip_packet.set_header_len(20); // and the total size of the packet, which equals to the length of the header // plus the length of the payload (data that the packet carries). We don't have // any payload for now, so the total length will be also equal to 20 bytes. ip_packet.set_total_len(20); // Finally, we need to add a checksum to our packet. The receiver of the packet // checks it to make sure that the packet contents have not been damaged (which // can happen if you have a flaky Internet connection, for example). // If you are interested in learning more about the actual algorithm used for // checksum calculation, you can find it here: // https://en.wikipedia.org/wiki/IPv4_header_checksum ip_packet.fill_checksum(); // We can skip other header fields for now (we will cover them in the following // lessons), but if you want to play with \`Ipv4Packet\`, you can find // documentation for other available methods here: // https://docs.rs/smoltcp/0.6.0/smoltcp/wire/struct.Ipv4Packet.html return Ok(ip_packet.into_inner()); `; const UDP_HEADER_CODE = `// Let's start by constructing source and destination IP addresses. let our_own_address = Ipv4Addr::new(10, 0, 0, 1); let name_server_address = Ipv4Addr::new(1, 2, 3, 4); // We construct a UDP datagram in a similar way. // Let's allocate an array of 8 bytes to hold the header data: let udp_header_data = [0u8; 8]; // And wrap it in the \`UdpDatagram\` helper structure: let mut udp_packet = UdpDatagram::new(udp_header_data); // Let's set the source port number. // It will be used by the receiver to send a response. That is, if your program // uses port number 1000, and if you send a request to the name server on port // number 53, it will send a response to the port number 1000. udp_packet.set_src_port(1000); // Set the destination port number. We use 53 for a name server port. udp_packet.set_dst_port(53); // We also need to set a total size of the UDP datagram (the combined // length of a header and a payload). We don't send any data yet, and // we know that the header size is 8 bytes: udp_packet.set_len(8); // Lastly, the UDP header also contains its own checksum. // Why do we need another one if we have already calculated the checksum // for our IP packet? Remember that the checksum we calculated before // includes data only for the _IP header_, but not for its payload. // The checksum we calculate for UDP covers some fields of a (pseudo) // _IP header_ and the entirety of the UDP Header and Data. // If you are interested in learning more about the actual algorithm used for // checksum calculation, you can find it here: // https://en.wikipedia.org/wiki/User_Datagram_Protocol#Checksum_computation udp_packet.fill_checksum(&our_own_address, &name_server_address); // That's all we have to do for UDP! // Now let's construct an IP header which will include our UDP datagram. // This part of the code is almost the same as in the previous example. // The main difference is in the IP packet size: now that we have a // payload, the UDP datagram header, we need to add 8 bytes to the // total packet size. let mut ip_data = [0u8; 20 + 8]; // IP header size (20) + UDP datagram size (8) let mut ip_packet = Ipv4Packet::new(ip_data); ip_packet.set_version(4); ip_packet.set_protocol(Protocol::Udp); ip_packet.set_header_len(20); ip_packet.set_total_len(20 + 8); // IP header size (20) + UDP datagram size (8) ip_packet.set_src_addr(our_own_address); ip_packet.set_dst_addr(name_server_address); // Lastly, let's add our UDP datagram as the payload: ip_packet .payload_mut() .copy_from_slice(&udp_packet.into_inner()); // And calculate a checksum for our IP packet: ip_packet.fill_checksum(); // And we're done! return Ok(ip_packet.into_inner()); `; const UDP_API_CODE = `// We construct a socket by _binding_ to our IP address, 10.0.0.1 // and using the port number 1000. let socket = UdpSocket::bind("10.0.0.1:1000").expect("couldn't bind to address"); // Now we can use the \`send_to\` function which will construct UDP datagrams and // IP packets for us, including all required header fields and checksums. // We are sending a request to the name server with the address "1.2.3.4:53". // It will respond with Alice's IP address. socket .send_to(b"Alice", "1.2.3.4:53") .expect("couldn't send message"); // Now we can wait for a response from the name server. // We allocate an array to hold this response. Because we know it's only an IP // address, we need 4 bytes to hold it. let mut response_data_buffer = [0u8; 4]; socket .recv_from(&mut response_data_buffer) .expect("failed to receive data"); // Let's decode the response as an IP address. // We have used a similar function before (\`Ipv4Addr::new\`) to // construct an IP address out of four indidivual bytes. This is // the same thing, but instead of 4 separate numbers, we just // use an array of 4 numbers we have got as a response from the // name server. let ip_address = IpAddr::V4(Ipv4Addr::from(response_data_buffer)); // And we're done - just return the resulting IP address: return Ok(ip_address);`; const FINAL_TEST_CODE = `// Write your code here. // You need to send a request to a name server to get the IP address of \`Alice\`, // then send any message to \`Alice\` (use the port number 1000), and finally // return a message that Alice has sent to you in response. let mut message_from_alice = [0u8; 1024]; return Ok(message_from_alice.to_vec());`; export const initDefaultLessonState = (state) => { state.playgrounds.fullDemo.code.default = FULL_DEMO_CODE; state.playgrounds.fullDemo.code.current = FULL_DEMO_CODE; state.playgrounds.ipPackets.code.default = IP_HEADER_CODE; state.playgrounds.ipPackets.code.current = IP_HEADER_CODE; state.playgrounds.udpDatagram.code.default = UDP_HEADER_CODE; state.playgrounds.udpDatagram.code.current = UDP_HEADER_CODE; state.playgrounds.udpApi.code.default = UDP_API_CODE; state.playgrounds.udpApi.code.current = UDP_API_CODE; state.playgrounds.finalTest.code.default = FINAL_TEST_CODE; state.playgrounds.finalTest.code.current = FINAL_TEST_CODE; }; const countLines = (str) => str.split("\n").length - 1; // Tag for templates which calculates line offsets for user code. // TODO: ideally, this should be a const fn, or a preprocessor function. const rust = (strings, code) => { const lineOffset = countLines(strings[0]); return { lineOffset, code: `${strings[0]}${code}${strings[1]}`, }; }; export const wrapIpHeaderCode = (code) => { const wrappedCode = rust` use std::net::{IpAddr, Ipv4Addr}; type Result<T> = std::io::Result<T>; type Ipv4Packet = ip::Packet<[u8; 20]>; extern "C" { fn report_error(str: *const u8, str_len: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } fn code() -> Result<[u8; 20]> { ${code} } #[no_mangle] pub unsafe fn main() -> *const [u8; 20] { std::panic::set_hook(Box::new(panic_hook)); let res = code(); match res { Ok(octets) => { // We don't care about leaking memory here - this fn will be executed just once. let octets = Box::new(octets); return Box::into_raw(octets); }, Err(e) => { let msg = format!("Error: {}", e); report_error(msg.as_ptr(), msg.len()); } } return std::ptr::null(); } `; // TODO: do something better wrappedCode.code = MOD_IP + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_IP) + wrappedCode.lineOffset; return wrappedCode; }; export const wrapUdpHeaderCode = (code) => { const wrappedCode = rust` use std::net::{IpAddr, Ipv4Addr}; type Result<T> = std::io::Result<T>; type Ipv4Packet = ip::Packet<[u8; 28]>; type UdpDatagram = udp::Packet<[u8; 8]>; extern "C" { fn report_error(str: *const u8, str_len: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } fn code() -> Result<[u8; 28]> { ${code} } #[no_mangle] pub unsafe fn main() -> *const [u8; 28] { std::panic::set_hook(Box::new(panic_hook)); let res = code(); match res { Ok(octets) => { // We don't care about leaking memory here - this fn will be executed just once. let octets = Box::new(octets); return Box::into_raw(octets); }, Err(e) => { let msg = format!("Error: {}", e); report_error(msg.as_ptr(), msg.len()); } } return std::ptr::null(); } `; wrappedCode.code = MOD_IP + MOD_UDP + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_IP) + countLines(MOD_UDP) + wrappedCode.lineOffset; return wrappedCode; }; export const wrapFullDemoCode = (code) => { const wrappedCode = rust` use std::net::{SocketAddr, SocketAddrV4, IpAddr, Ipv4Addr, ToSocketAddrs}; use std::io::{Result}; extern "C" { fn report_error(str: *const u8, str_len: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } fn code() -> Result<IpAddr> { ${code} } #[no_mangle] pub unsafe fn main() -> [u8; 4] { std::panic::set_hook(Box::new(panic_hook)); let res = code(); // make sure all packets are processed for _poll in 0..4 { poll_network(); } match res { Ok(IpAddr::V4(ip_addr)) => { return ip_addr.octets(); }, Ok(res) => { let msg = format!("Unexpected result: {:?}", res); report_error(msg.as_ptr(), msg.len()); } Err(e) => { let msg = format!("Error: {}", e); report_error(msg.as_ptr(), msg.len()); } } return [0, 0, 0, 0]; } `; wrappedCode.code = MOD_UDP_SOCKET + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_UDP_SOCKET) + wrappedCode.lineOffset; return wrappedCode; }; export const wrapFinalTestCode = (code) => { const wrappedCode = rust` use std::net::{IpAddr, Ipv4Addr}; use std::io::{Result}; extern "C" { fn report_error(str: *const u8, str_len: usize); } fn panic_hook(info: &std::panic::PanicInfo) { let msg = info.to_string(); unsafe { report_error(msg.as_ptr(), msg.len()) }; } fn code() -> Result<Vec<u8>> { ${code} } #[no_mangle] pub unsafe fn main() -> usize { std::panic::set_hook(Box::new(panic_hook)); let res = code(); // make sure all packets are processed for _poll in 0..4 { poll_network(); } match res { Ok(vec) => { // put vec ptr + vec len into a box let vec_ptr = Box::into_raw(vec.into_boxed_slice()); return Box::into_raw(Box::new(vec_ptr)) as usize; }, Ok(res) => { let msg = format!("Unexpected result: {:?}", res); report_error(msg.as_ptr(), msg.len()); } Err(e) => { let msg = format!("Error: {}", e); report_error(msg.as_ptr(), msg.len()); } } return 0; } `; wrappedCode.code = MOD_UDP_SOCKET + wrappedCode.code; wrappedCode.lineOffset = countLines(MOD_UDP_SOCKET) + wrappedCode.lineOffset; return wrappedCode; };
the_stack
import * as _ from 'underscore'; import * as chai from 'chai'; import { assert } from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as path from 'path'; import * as fse from 'fs-extra'; import clone = require('lodash/clone'); import * as tmp from 'tmp-promise'; import * as winston from 'winston'; import { serialize } from 'winston/lib/winston/common'; import * as docUtils from 'app/server/lib/docUtils'; import * as log from 'app/server/lib/log'; import { getAppRoot } from 'app/server/lib/places'; chai.use(chaiAsPromised); /** * Creates a temporary file with the given contents. * @param {String} content. Data to store in the file. * @param {[Boolean]} optKeep. Optionally pass in true to keep the file from being deleted, which * is useful to see the content while debugging a test. * @returns {Promise} A promise for the path of the new file. */ export async function writeTmpFile(content: any, optKeep?: boolean) { // discardDescriptor ensures tmp module closes it. It can lead to horrible bugs to close this // descriptor yourself, since tmp also closes it on exit, and if it's a different descriptor by // that time, it can lead to a crash. See https://github.com/raszi/node-tmp/issues/168 const obj = await tmp.file({keep: optKeep, discardDescriptor: true}); await fse.writeFile(obj.path, content); return obj.path; } /** * Creates a temporary file with `numLines` of generated data, each line about 30 bytes long. * This is useful for testing operations with large files. * @param {Number} numLines. How many lines to store in the file. * @param {[Boolean]} optKeep. Optionally pass in true to keep the file from being deleted, which * is useful to see the content while debugging a test. * @returns {Promise} A promise for the path of the new file. */ export async function generateTmpFile(numLines: number, optKeep?: boolean) { // Generate a bigger data file. const data = []; for (let i = 0; i < numLines; i++) { data.push(i + " abcdefghijklmnopqrstuvwxyz\n"); } return writeTmpFile(data.join(""), optKeep); } /** * Helper class to capture log output when we want to test it. */ class CaptureTransport extends winston.Transport { private _captureFunc: (level: string, msg: string, meta: any) => void; public constructor(options: any) { super(); this._captureFunc = options.captureFunc; if (options.name) { this.name = options.name; } } public log(level: string, msg: string, meta: any, callback: () => void) { this._captureFunc(level, msg, meta); } } /** * When used inside a test suite (inside describe()), changes the log level to the given one * before tests, restoring it back afterwards. In addition, if optCaptureFunc is given, it will be * called as optCaptureFunc(level, msg) with every message logged (including those suppressed). * * This should be called at the suite level (i.e. inside describe()). */ export function setTmpLogLevel(level: string, optCaptureFunc?: (level: string, msg: string, meta: any) => void) { // If verbose is set in the environment, sabotage all reductions in logging level. // Handier than modifying the setTmpLogLevel line and then remembering to set it back // before committing. if (process.env.VERBOSE === '1') { level = 'debug'; } let prevLogLevel: string|undefined = undefined; const name = _.uniqueId('CaptureLog'); before(function() { if (this.runnable().parent?.root) { throw new Error("setTmpLogLevel should be called at suite level, not at root level"); } prevLogLevel = log.transports.file.level; log.transports.file.level = level; if (optCaptureFunc) { log.add(CaptureTransport as any, { captureFunc: optCaptureFunc, name }); // typing is off. } }); after(function() { if (optCaptureFunc) { log.remove(name); } log.transports.file.level = prevLogLevel; }); } /** * Captures debug log messages produced by callback. Suppresses ALL messages from console, and * captures those at minLevel and higher. Returns a promise for the array of "level: message" * strings. These may be tested using testUtils.assertMatchArray(). Callback may return a promise. */ export async function captureLog(minLevel: string, callback: any) { const messages: string[] = []; const prevLogLevel = log.transports.file.level; const name = _.uniqueId('CaptureLog'); function capture(level: string, msg: string, meta: any) { if ((log as any).levels[level] <= (log as any).levels[minLevel]) { // winston types are off? messages.push(level + ': ' + msg + (meta ? ' ' + serialize(meta) : '')); } } log.transports.file.level = -1 as any; // Suppress all log output. log.add(CaptureTransport as any, { captureFunc: capture, name }); // types are off. try { await callback(); } finally { log.remove(name); log.transports.file.level = prevLogLevel; } return messages; } /** * Asserts that each string of stringArray matches the corresponding regex in regexArray. */ export function assertMatchArray(stringArray: string[], regexArray: RegExp[]) { for (let i = 0; i < Math.min(stringArray.length, regexArray.length); i++) { assert.match(stringArray[i], regexArray[i]); } assert.isAtMost(stringArray.length, regexArray.length, `Unexpected strings seen: ${stringArray.slice(regexArray.length).join('\n')}`); assert.isAtLeast(stringArray.length, regexArray.length, 'Not all expected strings were seen'); } /** * Helper method for handling expected Promise rejections. * * @param {Promise} promise = the promise we are checking for errors * @param {String} errCode - Error code to check against `err.code` from the caller. * @param {RegExp} errRegexp - Regular expression to check against `err.message` from the caller. */ export function expectRejection(promise: Promise<any>, errCode: number, errRegexp: RegExp) { return promise .then(function() { assert(false, "Expected promise to return an error: " + errCode); }) .catch(function(err) { if (err.cause) { err = err.cause; } assert.strictEqual(err.code, errCode); if (errRegexp !== undefined) { assert(errRegexp.test(err.message), "Description doesn't match regexp: " + errRegexp + ' !~ ' + err.message); } }); } /** * Reads in doc actions from a test script. Used in DocStorage_Script.js and DocData.js. * This parser inserts line numbers into the step names of the test case bodies. Users of the test * script should iterate through the steps using processTestScriptSteps, which will strip out the * line numbers, and include them into any failure messages. * * @param {String} file - Input test script * @returns {Promise:Object} - Parsed test script object */ export async function readTestScript(file: string) { const fullText = await fse.readFile(file, {encoding: 'utf8'}); const allLines: string[] = []; fullText.split("\n").forEach(function(line, i) { if (line.match(/^\s*\/\//)) { allLines.push(''); } else { line = line.replace(/"(APPLY|CHECK_OUTPUT|LOAD_SAMPLE)"\s*,/, '"$1@' + (i + 1) + '",'); allLines.push(line); } }); return JSON.parse(allLines.join("\n")); } /** * For a test case step, such as ["APPLY", {actions}], checks if the step name has an encoded line * number, strips it, runs the callback with the step data, and inserts the line number into any * errors thrown by the callback. */ export async function processTestScriptSteps<T>(body: Promise<[string, T]>[], stepCallback: (step: [string, T]) => Promise<void>) { for (const promise of body) { const step = await promise; const stepName = step[0]; const lineNoPos = stepName.indexOf('@'); const lineNum = (lineNoPos === -1) ? null : stepName.slice(lineNoPos + 1); step[0] = (lineNoPos === -1) ? stepName : stepName.slice(0, lineNoPos); try { await stepCallback(step); } catch (e) { e.message = "LINE " + lineNum + ": " + e.message; throw e; } } } /** * Helper that substitutes every instance of `from` value to `to` value. Iterates down the object. */ export function deepSubstitute(obj: any, from: any, to: any): any { from = _.isArray(from) ? from : [from]; if (_.isArray(obj)) { return obj.map(el => deepSubstitute(el, from, to)); } else if (obj && typeof obj === 'object' && !_.isFunction(obj)) { return _.mapObject(obj, el => deepSubstitute(el, from, to)); } else { return from.indexOf(obj) !== -1 ? to : obj; } } export const fixturesRoot = path.resolve(getAppRoot(), 'test', 'fixtures'); export const appRoot = getAppRoot(); /** * Copy the given filename from the fixtures directory (test/fixtures) * to the storage manager root. * @param {string} alias - Optional alias that lets you rename the document on disk. */ export async function useFixtureDoc(fileName: string, storageManager: any, alias: string = fileName) { const srcPath = path.resolve(fixturesRoot, "docs", fileName); const docName = await useLocalDoc(srcPath, storageManager, alias); log.info("Using fixture %s as %s", fileName, docName + ".grist"); return docName; } /** * Copy the given filename from srcPath to the storage manager root. * @param {string} alias - Optional alias that lets you rename the document on disk. */ export async function useLocalDoc(srcPath: string, storageManager: any, alias: string = srcPath) { let docName = path.basename(alias || srcPath, ".grist"); docName = await docUtils.createNumbered( docName, "-", (name: string) => docUtils.createExclusive(storageManager.getPath(name))); await docUtils.copyFile(srcPath, storageManager.getPath(docName)); await storageManager.markAsChanged(docName); return docName; } // an helper to copy a fixtures document to destPath export async function copyFixtureDoc(docName: string, destPath: string) { const srcPath = path.resolve(fixturesRoot, 'docs', docName); await docUtils.copyFile(srcPath, destPath); } // a helper to read a fixtures document into memory export async function readFixtureDoc(docName: string) { const srcPath = path.resolve(fixturesRoot, 'docs', docName); return fse.readFile(srcPath); } // a class to store a snapshot of environment variables, can be reverted to by // calling .restore() export class EnvironmentSnapshot { private _oldEnv: NodeJS.ProcessEnv; public constructor() { this._oldEnv = clone(process.env); } // Reset environment variables. public restore() { Object.assign(process.env, this._oldEnv); for (const key of Object.keys(process.env)) { if (this._oldEnv[key] === undefined) { delete process.env[key]; } } } } export { assert };
the_stack
import { TableConstraints } from './tableConstraints'; import { ColumnConstraints } from './columnConstraints'; import { Constraint } from './constraint'; import { ConstraintType } from './constraintType'; import { RawConstraint } from './rawConstraint'; import { StringUtils } from "../stringUtils"; export class ConstraintParser { /** * Constraint name pattern */ static NAME_PATTERN = (s: string) => s.match(/CONSTRAINT\s+("[\s\S]+"|\S+)\s/i); /** * Constraint name pattern name matcher group */ static NAME_PATTERN_NAME_GROUP = 1; /** * Constraint name and definition pattern */ static CONSTRAINT_PATTERN = (s: string): string[] => s.match(/(CONSTRAINT\s+("[\s\S]+"|\S+)\s)?([\s\S]*)/i); /** * Constraint name and definition pattern name matcher group */ static CONSTRAINT_PATTERN_NAME_GROUP = 2; /** * Constraint name and definition pattern definition matcher group */ static CONSTRAINT_PATTERN_DEFINITION_GROUP = 3; /** * Get the constraints for the table SQL * @param tableSql table SQL * @return constraints */ static getConstraints(tableSql: string): TableConstraints { const constraints = new TableConstraints(); // Find the start and end of the column definitions and table // constraints let start = -1; let end = -1; if (tableSql !== null && tableSql !== undefined) { start = tableSql.indexOf('('); end = tableSql.lastIndexOf(')'); } if (start >= 0 && end >= 0) { const definitions = tableSql.substring(start + 1, end).trim(); // Parse the column definitions and table constraints, divided by // columns when not within parentheses. Create constraints when // found. let openParentheses = 0; let sqlStart = 0; for (let i = 0; i < definitions.length; i++) { let character = definitions.charAt(i); if (character === '(') { openParentheses++; } else if (character === ')') { openParentheses--; } else if (character === ',' && openParentheses === 0) { let constraintSql = definitions.substring(sqlStart, i); ConstraintParser.addConstraints(constraints, constraintSql); sqlStart = i + 1; } } if (sqlStart < definitions.length) { let constraintSql = definitions.substring(sqlStart, definitions.length); ConstraintParser.addConstraints(constraints, constraintSql); } } return constraints; } /** * Add constraints of the optional type or all constraints * @param constraints constraints to add to * @param constraintSql constraint SQL statement */ static addConstraints(constraints: TableConstraints, constraintSql: string) { const constraint = ConstraintParser.getTableConstraint(constraintSql); if (constraint !== null && constraint !== undefined) { constraints.addTableConstraint(constraint); } else { const columnConstraints = ConstraintParser.getColumnConstraints(constraintSql); if (columnConstraints.hasConstraints()) { constraints.addColumnConstraints(columnConstraints); } } } /** * Attempt to get column constraints by parsing the SQL statement * @param constraintSql constraint SQL statement * @return constraints */ static getColumnConstraints(constraintSql: string): ColumnConstraints { const parts = constraintSql.trim().split(/\s+/); const columnName = StringUtils.quoteUnwrap(parts[0]); const constraints = new ColumnConstraints(columnName); let constraintIndex = -1; let constraintType = null; for (let i = 1; i < parts.length; i++) { const part = parts[i]; if (Constraint.CONSTRAINT === part.toUpperCase()) { if (constraintType !== null && constraintType !== undefined) { constraints.addConstraint(ConstraintParser.createConstraint(parts, constraintIndex, i, constraintType)); constraintType = null; } constraintIndex = i; } else { const type = ConstraintType.getColumnType(part); if (type !== null && type !== undefined) { if (constraintType !== null && constraintType !== undefined) { constraints.addConstraint(ConstraintParser.createConstraint(parts, constraintIndex, i, constraintType)); constraintIndex = -1; } if (constraintIndex < 0) { constraintIndex = i; } constraintType = type; } } } if (constraintType !== null && constraintType !== undefined) { constraints.addConstraint(ConstraintParser.createConstraint(parts, constraintIndex, parts.length, constraintType)); } return constraints; } /** * Create a constraint from the SQL parts with the range for the type * @param parts SQL parts * @param startIndex start index (inclusive) * @param endIndex end index (exclusive) * @param type constraint type * @return constraint */ static createConstraint(parts: string[], startIndex: number, endIndex: number, type: ConstraintType): Constraint { let constraintSql = ''; for (let i = startIndex; i < endIndex; i++) { if (constraintSql.length > 0) { constraintSql = constraintSql.concat(' '); } constraintSql = constraintSql.concat(parts[i]); } const name = ConstraintParser.getName(constraintSql); return new RawConstraint(type, name, constraintSql); } /** * Attempt to get the constraint by parsing the SQL statement * @param constraintSql constraint SQL statement * @param table true to search for a table constraint, false to search for a column constraint * @return constraint or null */ static getConstraint(constraintSql: string, table: boolean): Constraint { let constraint = null; const nameAndDefinition = ConstraintParser.getNameAndDefinition(constraintSql); const definition = nameAndDefinition[1]; if (definition !== null && definition !== undefined) { const prefix = definition.split(/\s+/)[0]; let type = null; if (table) { type = ConstraintType.getTableType(prefix); } else { type = ConstraintType.getColumnType(prefix); } if (type !== null && type !== undefined) { constraint = new RawConstraint(type, nameAndDefinition[0], constraintSql.trim()); } } return constraint; } /** * Attempt to get a table constraint by parsing the SQL statement * @param constraintSql constraint SQL statement * @return constraint or null */ static getTableConstraint(constraintSql: string): Constraint { return ConstraintParser.getConstraint(constraintSql, true); } /** * Check if the SQL is a table type constraint * @param constraintSql constraint SQL statement * @return true if a table constraint */ static isTableConstraint(constraintSql: string): boolean { return ConstraintParser.getTableConstraint(constraintSql) !== null; } /** * Get the table constraint type of the constraint SQL * @param constraintSql constraint SQL * @return constraint type or null */ static getTableType(constraintSql: string): ConstraintType { let type = null; let constraint = ConstraintParser.getTableConstraint(constraintSql); if (constraint != null) { type = constraint.type; } return type; } /** * Determine if the table constraint SQL is the constraint type * @param type constraint type * @param constraintSql constraint SQL * @return true if the constraint type */ static isTableType(type: ConstraintType, constraintSql: string): boolean { let isType = false; const constraintType = ConstraintParser.getTableType(constraintSql); if (constraintType != null) { isType = type === constraintType; } return isType; } /** * Attempt to get a column constraint by parsing the SQL statement * @param constraintSql constraint SQL statement * @return constraint or null */ static getColumnConstraint(constraintSql: string): Constraint { return ConstraintParser.getConstraint(constraintSql, false); } /** * Check if the SQL is a column type constraint * @param constraintSql constraint SQL statement * @return true if a column constraint */ static isColumnConstraint(constraintSql: string): boolean { return ConstraintParser.getColumnConstraint(constraintSql) != null; } /** * Get the column constraint type of the constraint SQL * @param constraintSql constraint SQL * @return constraint type or null */ static getColumnType(constraintSql: string): ConstraintType { let type = null; const constraint = ConstraintParser.getColumnConstraint(constraintSql); if (constraint != null) { type = constraint.type; } return type; } /** * Determine if the column constraint SQL is the constraint type * @param type constraint type * @param constraintSql constraint SQL * @return true if the constraint type */ static isColumnType(type: ConstraintType, constraintSql: string): boolean { let isType = false; const constraintType = ConstraintParser.getColumnType(constraintSql); if (constraintType != null) { isType = type == constraintType; } return isType; } /** * Attempt to get a constraint by parsing the SQL statement * @param constraintSql constraint SQL statement * @return constraint or null */ static getTableOrColumnConstraint(constraintSql: string): Constraint { let constraint = ConstraintParser.getTableConstraint(constraintSql); if (constraint === null || constraint === undefined) { constraint = ConstraintParser.getColumnConstraint(constraintSql); } return constraint; } /** * Check if the SQL is a constraint * @param constraintSql constraint SQL statement * @return true if a constraint */ static isConstraint(constraintSql: string): boolean { return ConstraintParser.getTableOrColumnConstraint(constraintSql) !== null; } /** * Get the constraint type of the constraint SQL * @param constraintSql constraint SQL * @return constraint type or null */ static getType(constraintSql: string): ConstraintType { let type = null; const constraint = ConstraintParser.getTableOrColumnConstraint(constraintSql); if (constraint !== null && constraint !== undefined) { type = constraint.getType(); } return type; } /** * Determine if the constraint SQL is the constraint type * @param type constraint type * @param constraintSql constraint SQL * @return true if the constraint type */ static isType(type: ConstraintType, constraintSql: string): boolean { let isType = false; const constraintType = ConstraintParser.getType(constraintSql); if (constraintType !== null && constraintType !== undefined) { isType = type === constraintType; } return isType; } /** * Get the constraint name if it has one * @param constraintSql constraint SQL * @return constraint name or null */ static getName(constraintSql: string): string { let name = null; let matches = ConstraintParser.NAME_PATTERN(constraintSql); if (matches !== null && matches.length > ConstraintParser.NAME_PATTERN_NAME_GROUP) { name = StringUtils.quoteUnwrap(matches[ConstraintParser.NAME_PATTERN_NAME_GROUP]); } return name; } /** * Get the constraint name and remaining definition * @param constraintSql constraint SQL * @return array with name or null at index 0, definition at index 1 */ static getNameAndDefinition(constraintSql: string): string[] { let parts = [null, constraintSql]; const matches = ConstraintParser.CONSTRAINT_PATTERN(constraintSql.trim()); if (matches !== null && matches.length > ConstraintParser.CONSTRAINT_PATTERN_DEFINITION_GROUP) { let name = StringUtils.quoteUnwrap(matches[ConstraintParser.CONSTRAINT_PATTERN_NAME_GROUP]); if (name !== null && name !== undefined) { name = name.trim(); } let definition = matches[ConstraintParser.CONSTRAINT_PATTERN_DEFINITION_GROUP]; if (definition !== null && definition !== undefined) { definition = definition.trim(); } parts = [name, definition]; } return parts; } }
the_stack
import 'chrome://tab-strip.top-chrome/tab_list.js'; import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {FocusOutlineManager} from 'chrome://resources/js/cr/ui/focus_outline_manager.m.js'; import {TabElement} from 'chrome://tab-strip.top-chrome/tab.js'; import {TabGroupElement} from 'chrome://tab-strip.top-chrome/tab_group.js'; import {setScrollAnimationEnabledForTesting, TabListElement} from 'chrome://tab-strip.top-chrome/tab_list.js'; import {PageRemote, Tab} from 'chrome://tab-strip.top-chrome/tab_strip.mojom-webui.js'; import {TabsApiProxyImpl} from 'chrome://tab-strip.top-chrome/tabs_api_proxy.js'; import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks} from 'chrome://webui-test/test_util.js'; import {createTab, TestTabsApiProxy} from './test_tabs_api_proxy.js'; suite('TabList', () => { let tabList: TabListElement; let testTabsApiProxy: TestTabsApiProxy; let callbackRouter: PageRemote; const tabs: Tab[] = [ createTab({ active: true, id: 0, index: 0, title: 'Tab 1', }), createTab({ id: 1, index: 1, title: 'Tab 2', }), createTab({ active: false, id: 2, index: 2, title: 'Tab 3', }), ]; function pinTabAt(tab: Tab, index: number) { const changeInfo = {index: index, pinned: true}; const updatedTab = Object.assign({}, tab, changeInfo); callbackRouter.tabUpdated(updatedTab); } function unpinTabAt(tab: Tab, index: number) { const changeInfo = {index: index, pinned: false}; const updatedTab = Object.assign({}, tab, changeInfo); callbackRouter.tabUpdated(updatedTab); } function getUnpinnedTabs(): NodeListOf<TabElement> { return tabList.shadowRoot!.querySelectorAll('#unpinnedTabs tabstrip-tab'); } function getPinnedTabs(): NodeListOf<TabElement> { return tabList.shadowRoot!.querySelectorAll('#pinnedTabs tabstrip-tab'); } function getTabGroups(): NodeListOf<TabGroupElement> { return tabList.shadowRoot!.querySelectorAll('tabstrip-tab-group'); } function waitFor(ms: number): Promise<void> { return new Promise<void>(resolve => { setTimeout(resolve, ms); }); } function verifyTab(tab1: Tab, tab2: Tab) { assertEquals(tab1.active, tab2.active); assertDeepEquals(tab1.alertStates, tab2.alertStates); assertEquals(tab1.id, tab2.id); assertEquals(tab1.index, tab2.index); assertEquals(tab1.pinned, tab2.pinned); assertEquals(tab1.title, tab2.title); assertDeepEquals(tab1.url, tab2.url); } setup(async () => { document.documentElement.dir = 'ltr'; document.body.innerHTML = ''; document.body.style.margin = '0'; testTabsApiProxy = new TestTabsApiProxy(); testTabsApiProxy.setTabs(tabs); TabsApiProxyImpl.setInstance(testTabsApiProxy); callbackRouter = testTabsApiProxy.getCallbackRouterRemote(); testTabsApiProxy.setColors({ '--background-color': 'white', '--foreground-color': 'black', }); testTabsApiProxy.setLayout({ '--height': '100px', '--width': '150px', }); testTabsApiProxy.setVisible(true); setScrollAnimationEnabledForTesting(false); tabList = document.createElement('tabstrip-tab-list'); document.body.appendChild(tabList); await testTabsApiProxy.whenCalled('getTabs'); }); teardown(() => { testTabsApiProxy.reset(); }); test('sets theme colors on init', async () => { await testTabsApiProxy.whenCalled('getColors'); assertEquals(tabList.style.getPropertyValue('--background-color'), 'white'); assertEquals(tabList.style.getPropertyValue('--foreground-color'), 'black'); }); test('updates theme colors when theme changes', async () => { testTabsApiProxy.setColors({ '--background-color': 'pink', '--foreground-color': 'blue', }); webUIListenerCallback('theme-changed'); await testTabsApiProxy.whenCalled('getColors'); assertEquals(tabList.style.getPropertyValue('--background-color'), 'pink'); assertEquals(tabList.style.getPropertyValue('--foreground-color'), 'blue'); }); test('sets layout variables on init', async () => { await testTabsApiProxy.whenCalled('getLayout'); assertEquals(tabList.style.getPropertyValue('--height'), '100px'); assertEquals(tabList.style.getPropertyValue('--width'), '150px'); }); test('updates layout variables when layout changes', async () => { callbackRouter.layoutChanged({ '--height': '10000px', '--width': '10px', }); await flushTasks(); await testTabsApiProxy.whenCalled('getLayout'); assertEquals(tabList.style.getPropertyValue('--height'), '10000px'); assertEquals(tabList.style.getPropertyValue('--width'), '10px'); }); test('GroupVisualDataOnInit', async () => { testTabsApiProxy.reset(); testTabsApiProxy.setTabs([createTab({ active: true, groupId: 'group0', id: 0, index: 0, title: 'New tab', })]); testTabsApiProxy.setGroupVisualData({ group0: { title: 'My group', color: 'rgba(255, 0, 0, 1)', textColor: 'black', }, }); // Remove and reinsert into DOM to retrigger connectedCallback(); tabList.remove(); document.body.appendChild(tabList); await testTabsApiProxy.whenCalled('getGroupVisualData'); }); test('GroupVisualDataOnThemeChange', async () => { testTabsApiProxy.reset(); testTabsApiProxy.setGroupVisualData({ group0: { title: 'My group', color: 'rgba(255, 0, 0, 1)', textColor: 'black', }, }); webUIListenerCallback('theme-changed'); await testTabsApiProxy.whenCalled('getGroupVisualData'); }); test('calculates the correct unpinned tab width and height', async () => { callbackRouter.layoutChanged({ '--tabstrip-tab-thumbnail-height': '132px', '--tabstrip-tab-thumbnail-width': '200px', '--tabstrip-tab-title-height': '15px', }); await flushTasks(); await testTabsApiProxy.whenCalled('getLayout'); const tabListStyle = window.getComputedStyle(tabList); assertEquals( tabListStyle.getPropertyValue('--tabstrip-tab-height').trim(), 'calc(15px + 132px)'); assertEquals( tabListStyle.getPropertyValue('--tabstrip-tab-width').trim(), '200px'); }); test('creates a tab element for each tab', () => { const tabElements = getUnpinnedTabs(); assertEquals(tabs.length, tabElements.length); tabs.forEach((tab, index) => { assertEquals(tabElements[index]!.tab, tab); }); }); test( 'adds a new tab element when a tab is added in same window', async () => { const appendedTab = createTab({ active: false, id: 3, index: 3, title: 'New tab', }); callbackRouter.tabCreated(appendedTab); await flushTasks(); let tabElements = getUnpinnedTabs(); assertEquals(tabs.length + 1, tabElements.length); verifyTab(tabElements[tabs.length]!.tab, appendedTab); const prependedTab = createTab({ id: 4, index: 0, title: 'New tab', }); callbackRouter.tabCreated(prependedTab); await flushTasks(); tabElements = getUnpinnedTabs(); assertEquals(tabs.length + 2, tabElements.length); verifyTab(tabElements[0]!.tab, prependedTab); }); test('PlacesTabElement', () => { const pinnedTab = document.createElement('tabstrip-tab'); tabList.placeTabElement(pinnedTab, 0, true, undefined); assertEquals(pinnedTab, getPinnedTabs()[0]); const unpinnedUngroupedTab = document.createElement('tabstrip-tab'); tabList.placeTabElement(unpinnedUngroupedTab, 1, false, undefined); let unpinnedTabs = getUnpinnedTabs(); assertEquals(4, unpinnedTabs.length); assertEquals(unpinnedUngroupedTab, unpinnedTabs[0]); const groupedTab = document.createElement('tabstrip-tab'); tabList.placeTabElement(groupedTab, 1, false, 'group0'); unpinnedTabs = getUnpinnedTabs(); assertEquals(5, unpinnedTabs.length); assertEquals(groupedTab, unpinnedTabs[0]); assertEquals('TABSTRIP-TAB-GROUP', groupedTab.parentElement!.tagName); }); function testPlaceElementAnimationParams( element: Element, horizontalScale: number, verticalScale: number) { const animations = element.getAnimations(); assertEquals(1, animations.length); assertEquals('running', animations[0]!.playState); assertEquals(120, animations[0]!.effect!.getTiming().duration); assertEquals('ease-out', animations[0]!.effect!.getTiming().easing); const keyframes = (animations[0]!.effect as KeyframeEffect).getKeyframes(); const horizontalTabSpacingVars = '(var(--tabstrip-tab-width) + var(--tabstrip-tab-spacing))'; const verticalTabSpacingVars = '(var(--tabstrip-tab-height) + var(--tabstrip-tab-spacing))'; assertEquals(2, keyframes.length); assertEquals( `translate(calc(${horizontalScale} * ${ horizontalTabSpacingVars}), calc(${verticalScale} * ${ verticalTabSpacingVars}))`, keyframes[0]!['transform']); assertEquals('translate(0px, 0px)', keyframes[1]!['transform']); } /** * This function should be called once per test since the animations finishing * and being included in the getAnimations() calls can cause flaky tests. * @param direction, the direction the moved tab should animate. * +1 if moving right, -1 if moving left */ async function testPlaceTabElementAnimation( indexToMove: number, newIndex: number, direction: number) { await tabList.animationPromises; let unpinnedTabs = getUnpinnedTabs(); const movedTab = unpinnedTabs[indexToMove]!; tabList.placeTabElement(movedTab, newIndex, false, undefined); testPlaceElementAnimationParams( movedTab, -1 * direction * Math.abs(newIndex - indexToMove), 0); Array.from(unpinnedTabs) .filter(tabElement => tabElement !== movedTab) .forEach( tabElement => testPlaceElementAnimationParams(tabElement, direction, 0)); } test('PlaceTabElementAnimatesTabMovedTowardsStart', () => { return testPlaceTabElementAnimation(tabs.length - 1, 0, -1); }); test('PlaceTabElementAnimatesTabMovedTowardsStartRTL', () => { document.documentElement.dir = 'rtl'; return testPlaceTabElementAnimation(tabs.length - 1, 0, 1); }); test('PlaceTabElementAnimatesTabMovedTowardsEnd', () => { return testPlaceTabElementAnimation(0, tabs.length - 1, 1); }); test('PlaceTabElementAnimatesTabMovedTowardsEndRTL', () => { document.documentElement.dir = 'rtl'; return testPlaceTabElementAnimation(0, tabs.length - 1, -1); }); test('PlacePinnedTabElementAnimatesTabsWithinSameColumn', async () => { tabs.forEach(pinTabAt); await tabList.animationPromises; // Test moving a tab within the same column. If a tab is moved from index 0 // to index 2, it should move vertically down 2 places. Tabs at index 1 and // index 2 should move up 1 space. const pinnedTabs = getPinnedTabs(); tabList.placeTabElement(pinnedTabs[0]!, 2, /*pinned=*/ true); await Promise.all([ testPlaceElementAnimationParams(pinnedTabs[0]!, 0, -2), testPlaceElementAnimationParams(pinnedTabs[1]!, 0, 1), testPlaceElementAnimationParams(pinnedTabs[2]!, 0, 1), ]); }); test( 'PlacePinnedTabElementAnimatesTabsAcrossColumnsToHigherIndex', async () => { tabs.forEach(pinTabAt); for (let i = 0; i < 4; i++) { callbackRouter.tabCreated(createTab({ id: tabs.length + i, index: tabs.length + i, pinned: true, title: 'Pinned tab', })); } await flushTasks(); await tabList.animationPromises; const pinnedTabs = getPinnedTabs(); tabList.placeTabElement(pinnedTabs[2]!, 6, /*pinned=*/ true); await Promise.all([ testPlaceElementAnimationParams(pinnedTabs[2]!, -2, 2), testPlaceElementAnimationParams(pinnedTabs[3]!, 1, -2), testPlaceElementAnimationParams(pinnedTabs[4]!, 0, 1), testPlaceElementAnimationParams(pinnedTabs[5]!, 0, 1), testPlaceElementAnimationParams(pinnedTabs[6]!, 1, -2), ]); }); test( 'PlacePinnedTabElementAnimatesTabsAcrossColumnsToLowerIndex', async () => { tabs.forEach(pinTabAt); for (let i = 0; i < 4; i++) { callbackRouter.tabCreated(createTab({ id: tabs.length + i, index: tabs.length + i, pinned: true, title: 'Pinned tab', })); } await flushTasks(); await tabList.animationPromises; const pinnedTabs = getPinnedTabs(); tabList.placeTabElement(pinnedTabs[3]!, 0, /*pinned=*/ true); await Promise.all([ testPlaceElementAnimationParams(pinnedTabs[3]!, 1, 0), testPlaceElementAnimationParams(pinnedTabs[2]!, -1, 2), testPlaceElementAnimationParams(pinnedTabs[1]!, 0, -1), testPlaceElementAnimationParams(pinnedTabs[0]!, 0, -1), ]); }); test('PlacesTabGroupElement', () => { const tabGroupElement = document.createElement('tabstrip-tab-group'); tabList.placeTabGroupElement(tabGroupElement, 2); const tabGroupElements = getTabGroups(); assertEquals(1, tabGroupElements.length); assertEquals(tabGroupElement, tabGroupElements[0]); // Group was inserted at index 2, so it should come after the 2nd tab. assertEquals(getUnpinnedTabs()[1], tabGroupElement.previousElementSibling); }); async function testPlaceTabGroupElementAnimation( indexToGroup: number, newIndex: number, direction: number) { await tabList.animationPromises; // Group the tab at indexToGroup. const unpinnedTabs = getUnpinnedTabs(); const tabToGroup = unpinnedTabs[indexToGroup]!; callbackRouter.tabGroupStateChanged( tabToGroup.tab.id, indexToGroup, 'group0'); await flushTasks(); const groupElement = tabToGroup.parentElement as TabGroupElement; tabList.placeTabGroupElement(groupElement, newIndex); testPlaceElementAnimationParams( groupElement, -1 * direction * Math.abs(newIndex - indexToGroup), 0); // Test animations on all the other tabs. Array.from(getUnpinnedTabs()) .filter(tabElement => tabElement.parentElement !== groupElement) .forEach( tabElement => testPlaceElementAnimationParams(tabElement, direction, 0)); } test('PlaceTabGroupElementAnimatesTabGroupMovedTowardsStart', () => { return testPlaceTabGroupElementAnimation(tabs.length - 1, 0, -1); }); test('PlaceTabGroupElementAnimatesTabGroupMovedTowardsStartRTL', () => { document.documentElement.dir = 'rtl'; return testPlaceTabGroupElementAnimation(tabs.length - 1, 0, 1); }); test('PlaceTabGroupElementAnimatesTabGroupMovedTowardsEnd', () => { return testPlaceTabGroupElementAnimation(0, tabs.length - 1, 1); }); test('PlaceTabGroupElementAnimatesTabGroupMovedTowardsEndRTL', () => { document.documentElement.dir = 'rtl'; return testPlaceTabGroupElementAnimation(0, tabs.length - 1, -1); }); test('PlaceTabGroupElementAnimationWithMultipleTabs', async () => { await tabList.animationPromises; // Group all tabs except for the first one. const ungroupedTab = getUnpinnedTabs()[0]!; tabs.slice(1).forEach(tab => { callbackRouter.tabGroupStateChanged(tab.id, tab.index, 'group0'); }); await flushTasks(); // Move the group to index 0. const tabGroup = getTabGroups()[0]!; tabList.placeTabGroupElement(tabGroup, 0); // Both the TabElement and TabGroupElement should move by a scale of 1. testPlaceElementAnimationParams(tabGroup, 1, 0); testPlaceElementAnimationParams(ungroupedTab, -1, 0); }); test('AddNewTabGroup', async () => { const appendedTab = createTab({ groupId: 'group0', id: 3, index: 3, title: 'New tab in group', }); callbackRouter.tabCreated(appendedTab); await flushTasks(); let tabElements = getUnpinnedTabs(); assertEquals(tabs.length + 1, tabElements.length); assertEquals(getTabGroups().length, 1); assertEquals( 'TABSTRIP-TAB-GROUP', tabElements[appendedTab.index]!.parentElement!.tagName); const prependedTab = createTab({ groupId: 'group1', id: 4, index: 0, title: 'New tab', }); callbackRouter.tabCreated(prependedTab); await flushTasks(); tabElements = getUnpinnedTabs(); assertEquals(tabs.length + 2, tabElements.length); assertEquals(getTabGroups().length, 2); assertEquals( 'TABSTRIP-TAB-GROUP', tabElements[prependedTab.index]!.parentElement!.tagName); }); test('AddTabToExistingGroup', async () => { const appendedTab = createTab({ groupId: 'group0', id: 3, index: 3, title: 'New tab in group', }); callbackRouter.tabCreated(appendedTab); await flushTasks(); const appendedTabInSameGroup = createTab({ groupId: 'group0', id: 4, index: 4, title: 'New tab in same group', }); callbackRouter.tabCreated(appendedTabInSameGroup); await flushTasks(); const tabGroups = getTabGroups(); assertEquals(tabGroups.length, 1); const children = tabGroups[0]!.children as HTMLCollectionOf<TabElement>; assertEquals(children.item(0)!.tab.id, appendedTab.id); assertEquals(children.item(1)!.tab.id, appendedTabInSameGroup.id); }); // Test that the TabList does not add a non-grouped tab to a tab group at the // same index. test('HandleSingleTabBeforeGroup', async () => { const tabInGroup = createTab({ groupId: 'group0', id: 3, index: 3, title: 'New tab in group', }); callbackRouter.tabCreated(tabInGroup); await flushTasks(); const tabNotInGroup = createTab({ id: 4, index: 3, title: 'New tab not in group', }); callbackRouter.tabCreated(tabNotInGroup); await flushTasks(); const tabsContainerChildren = tabList.shadowRoot!.querySelector('#unpinnedTabs')!.children; assertEquals(tabsContainerChildren.item(3)!.tagName, 'TABSTRIP-TAB'); verifyTab((tabsContainerChildren.item(3) as TabElement).tab, tabNotInGroup); assertEquals(tabsContainerChildren.item(4)!.tagName, 'TABSTRIP-TAB-GROUP'); }); test('HandleGroupedTabBeforeDifferentGroup', async () => { const tabInOriginalGroup = tabs[1]!; callbackRouter.tabGroupStateChanged( tabInOriginalGroup.id, tabInOriginalGroup.index, 'originalGroup'); // Create another group from the tab before group A. const tabInPrecedingGroup = tabs[0]!; callbackRouter.tabGroupStateChanged( tabInPrecedingGroup.id, tabInPrecedingGroup.index, 'precedingGroup'); await flushTasks(); const tabsContainerChildren = tabList.shadowRoot!.querySelector('#unpinnedTabs')!.children; const precedingGroup = tabsContainerChildren[0] as HTMLElement; assertEquals(precedingGroup.tagName, 'TABSTRIP-TAB-GROUP'); assertEquals(precedingGroup.dataset['groupId'], 'precedingGroup'); assertEquals(precedingGroup.children.length, 1); assertEquals( (precedingGroup.children[0] as TabElement).tab.id, tabInPrecedingGroup.id); const originalGroup = tabsContainerChildren[1] as HTMLElement; assertEquals(originalGroup.tagName, 'TABSTRIP-TAB-GROUP'); assertEquals(originalGroup.dataset['groupId'], 'originalGroup'); assertEquals(originalGroup.children.length, 1); assertEquals( (originalGroup.children[0] as TabElement).tab.id, tabInOriginalGroup.id); }); test('HandleGroupedTabBeforeSameGroup', async () => { const originalTabInGroup = tabs[1]!; callbackRouter.tabGroupStateChanged( originalTabInGroup.id, originalTabInGroup.index, 'sameGroup'); // Create another group from the tab before group A. const precedingTabInGroup = tabs[0]!; callbackRouter.tabGroupStateChanged( precedingTabInGroup.id, precedingTabInGroup.index, 'sameGroup'); await flushTasks(); const tabGroups = getTabGroups(); const tabGroup = tabGroups[0]!; assertEquals(tabGroups.length, 1); assertEquals(tabGroup.dataset['groupId'], 'sameGroup'); assertEquals(tabGroup.children.length, 2); assertEquals( (tabGroup.children[0] as TabElement).tab.id, precedingTabInGroup.id); assertEquals( (tabGroup.children[1] as TabElement).tab.id, originalTabInGroup.id); }); test('removes a tab when tab is removed from current window', async () => { const tabToRemove = tabs[0]!; callbackRouter.tabRemoved(tabToRemove.id); await flushTasks(); await tabList.animationPromises; assertEquals(tabs.length - 1, getUnpinnedTabs().length); }); test('updates a tab with new tab data when a tab is updated', async () => { const tabToUpdate = tabs[0]; const changeInfo = {title: 'A new title'}; const updatedTab = Object.assign({}, tabToUpdate, changeInfo); callbackRouter.tabUpdated(updatedTab); await flushTasks(); const tabElements = getUnpinnedTabs(); verifyTab(tabElements[0]!.tab, updatedTab); }); test('updates tabs when a new tab is activated', async () => { const tabElements = getUnpinnedTabs(); // Mock activating the 2nd tab callbackRouter.tabActiveChanged(tabs[1]!.id); await flushTasks(); assertFalse(tabElements[0]!.tab.active); assertTrue(tabElements[1]!.tab.active); assertFalse(tabElements[2]!.tab.active); }); test('adds a pinned tab to its designated container', async () => { callbackRouter.tabCreated(createTab({ id: tabs.length, index: 0, title: 'New pinned tab', pinned: true, })); await flushTasks(); const pinnedTabElements = getPinnedTabs(); assertEquals(pinnedTabElements.length, 1); assertTrue(pinnedTabElements[0]!.tab.pinned); }); test('moves pinned tabs to designated containers', async () => { const tabToPin = tabs[1]!; const changeInfo = {index: 0, pinned: true}; let updatedTab = Object.assign({}, tabToPin, changeInfo); callbackRouter.tabUpdated(updatedTab); await flushTasks(); let pinnedTabElements = getPinnedTabs(); assertEquals(pinnedTabElements.length, 1); assertTrue(pinnedTabElements[0]!.tab.pinned); assertEquals(pinnedTabElements[0]!.tab.id, tabToPin.id); assertEquals(getUnpinnedTabs().length, 2); // Unpin the tab so that it's now at index 0 changeInfo.index = 0; changeInfo.pinned = false; updatedTab = Object.assign({}, updatedTab, changeInfo); callbackRouter.tabUpdated(updatedTab); await flushTasks(); const unpinnedTabElements = getUnpinnedTabs(); assertEquals(getPinnedTabs().length, 0); assertEquals(unpinnedTabElements.length, 3); assertEquals(unpinnedTabElements[0]!.tab.id, tabToPin.id); }); test('moves tab elements when tabs move', async () => { const tabElementsBeforeMove = getUnpinnedTabs(); const tabToMove = tabs[0]!; callbackRouter.tabMoved(tabToMove.id, 2, false); await flushTasks(); const tabElementsAfterMove = getUnpinnedTabs(); assertEquals(tabElementsBeforeMove[0], tabElementsAfterMove[2]); assertEquals(tabElementsBeforeMove[1], tabElementsAfterMove[0]); assertEquals(tabElementsBeforeMove[2], tabElementsAfterMove[1]); }); test('MoveExistingTabToGroup', async () => { const tabToGroup = tabs[1]!; callbackRouter.tabGroupStateChanged( tabToGroup.id, tabToGroup.index, 'group0'); await flushTasks(); let tabElements = getUnpinnedTabs(); assertEquals(tabElements.length, tabs.length); assertEquals( tabElements[tabToGroup.index]!.parentElement!.tagName, 'TABSTRIP-TAB-GROUP'); const anotherTabToGroup = tabs[2]!; callbackRouter.tabGroupStateChanged( anotherTabToGroup.id, anotherTabToGroup.index, 'group0'); await flushTasks(); tabElements = getUnpinnedTabs(); assertEquals(tabElements.length, tabs.length); assertEquals( tabElements[tabToGroup.index]!.parentElement, tabElements[anotherTabToGroup.index]!.parentElement); }); test('MoveTabGroup', async () => { const tabToGroup = tabs[1]!; callbackRouter.tabGroupStateChanged( tabToGroup.id, tabToGroup.index, 'group0'); callbackRouter.tabGroupMoved('group0', 0); await flushTasks(); const tabAtIndex0 = getUnpinnedTabs()[0]!; assertEquals(tabAtIndex0.parentElement!.tagName, 'TABSTRIP-TAB-GROUP'); assertEquals(tabAtIndex0.tab.id, tabToGroup.id); }); test('tracks and untracks thumbnails based on viewport', async () => { // Wait for slideIn animations to complete updating widths and reset // resolvers to track new calls. await tabList.animationPromises; await testTabsApiProxy.whenCalled('setThumbnailTracked'); testTabsApiProxy.reset(); const tabElements = getUnpinnedTabs(); // Update width such that at most one tab can fit in the viewport at once. tabList.style.setProperty('--tabstrip-tab-width', `${window.innerWidth}px`); // At this point, the only visible tab should be the first tab. The second // tab should fit within the rootMargin of the IntersectionObserver. The // third tab should not be intersecting. let [tabId, thumbnailTracked] = await testTabsApiProxy.whenCalled('setThumbnailTracked'); assertEquals(tabId, tabElements[2]!.tab.id); assertEquals(thumbnailTracked, false); assertEquals(testTabsApiProxy.getCallCount('setThumbnailTracked'), 1); testTabsApiProxy.reset(); // Scroll such that the second tab is now the only visible tab. At this // point, all 3 tabs should fit within the root and rootMargin of the // IntersectionObserver. Since the 3rd tab was not being tracked before, // it should be the only tab to become tracked. tabList.scrollLeft = tabElements[1]!.offsetLeft; [tabId, thumbnailTracked] = await testTabsApiProxy.whenCalled('setThumbnailTracked'); assertEquals(tabId, tabElements[2]!.tab.id); assertEquals(thumbnailTracked, true); assertEquals(testTabsApiProxy.getCallCount('setThumbnailTracked'), 1); testTabsApiProxy.reset(); // Scroll such that the third tab is now the only visible tab. At this // point, the first tab should be outside of the rootMargin of the // IntersectionObserver. tabList.scrollLeft = tabElements[2]!.offsetLeft; [tabId, thumbnailTracked] = await testTabsApiProxy.whenCalled('setThumbnailTracked'); assertEquals(tabId, tabElements[0]!.tab.id); assertEquals(thumbnailTracked, false); assertEquals(testTabsApiProxy.getCallCount('setThumbnailTracked'), 1); }); test('tracks and untracks thumbnails based on pinned state', async () => { await tabList.animationPromises; await testTabsApiProxy.whenCalled('setThumbnailTracked'); testTabsApiProxy.reset(); // Remove all other tabs to isolate the tab to test, and then wait for // each tab to get untracked as it is removed from the DOM. const tabElements = getUnpinnedTabs(); tabElements[0]!.remove(); await testTabsApiProxy.whenCalled('setThumbnailTracked'); testTabsApiProxy.reset(); tabElements[1]!.remove(); await testTabsApiProxy.whenCalled('setThumbnailTracked'); testTabsApiProxy.reset(); // Pinning the third tab should untrack thumbnails for the tab pinTabAt(tabs[2]!, 0); let [tabId, thumbnailTracked] = await testTabsApiProxy.whenCalled('setThumbnailTracked'); assertEquals(tabId, tabs[2]!.id); assertEquals(thumbnailTracked, false); testTabsApiProxy.reset(); // Unpinning the tab should re-track the thumbnails unpinTabAt(tabs[2]!, 0); [tabId, thumbnailTracked] = await testTabsApiProxy.whenCalled('setThumbnailTracked'); assertEquals(tabId, tabs[2]!.id); assertEquals(thumbnailTracked, true); }); test('should update thumbnail track status on visibilitychange', async () => { await tabList.animationPromises; await testTabsApiProxy.whenCalled('setThumbnailTracked'); testTabsApiProxy.reset(); testTabsApiProxy.setVisible(false); document.dispatchEvent(new Event('visibilitychange')); // The tab strip should force untrack thumbnails for all tabs. await testTabsApiProxy.whenCalled('setThumbnailTracked'); assertEquals( testTabsApiProxy.getCallCount('setThumbnailTracked'), tabs.length); testTabsApiProxy.reset(); // Update width such that at all tabs can fit tabList.style.setProperty( '--tabstrip-tab-width', `${window.innerWidth / tabs.length}px`); testTabsApiProxy.setVisible(true); document.dispatchEvent(new Event('visibilitychange')); await testTabsApiProxy.whenCalled('setThumbnailTracked'); assertEquals( testTabsApiProxy.getCallCount('setThumbnailTracked'), tabs.length); }); // Flaky on all platforms. https://crbug.com/1247687. test.skip('ShouldDebounceThumbnailTrackerWhenScrollingFast', async () => { // Set tab widths such that 3 tabs fit in the viewport. This should reach a // state where the first 6 thumbnails are being tracked: 3 in the viewport // and 3 within the IntersectionObserver's rootMargin. The widths need to be // full integers to avoid rounding errors. const tabsPerViewport = 3; const tabStripWidth = window.innerWidth - window.innerWidth % 3; tabList.style.width = `${tabStripWidth}px`; tabList.style.setProperty( '--tabstrip-tab-width', `${tabStripWidth / tabsPerViewport}px`); tabList.style.setProperty('--tabstrip-tab-height', '10px'); tabList.style.setProperty('--tabstrip-tab-spacing', '0px'); await tabList.animationPromises; await testTabsApiProxy.whenCalled('setThumbnailTracked'); testTabsApiProxy.reset(); // Add enough tabs for there to be 13 tabs. for (let i = 0; i < 10; i++) { callbackRouter.tabCreated(createTab({ id: tabs.length + i, index: tabs.length + i, title: `Tab ${tabs.length + i + 1}`, })); } await flushTasks(); await tabList.animationPromises; await testTabsApiProxy.whenCalled('setThumbnailTracked'); testTabsApiProxy.reset(); testTabsApiProxy.resetThumbnailRequestCounts(); // Mock 3 scroll events and end up with a scrolled state where the 10th // tab is aligned to the left. This should only evaluate to 1 set of // thumbnail updates and should most importantly skip the 6th tab. const tabElements = getUnpinnedTabs(); tabList.scrollLeft = tabElements[3]!.offsetLeft; tabList.scrollLeft = tabElements[5]!.offsetLeft; tabList.scrollLeft = tabElements[10]!.offsetLeft; assertEquals(0, testTabsApiProxy.getCallCount('setThumbnailTracked')); await waitFor(200); assertEquals(12, testTabsApiProxy.getCallCount('setThumbnailTracked')); assertEquals(0, testTabsApiProxy.getThumbnailRequestCount(6)); for (let tabId = 7; tabId < 13; tabId++) { assertEquals(1, testTabsApiProxy.getThumbnailRequestCount(tabId)); } }); test( 'focusing on tab strip with the keyboard adds a class and focuses ' + 'the first tab', async () => { callbackRouter.receivedKeyboardFocus(); await flushTasks(); assertEquals(document.activeElement, tabList); assertEquals(tabList.shadowRoot!.activeElement, getUnpinnedTabs()[0]); assertTrue(FocusOutlineManager.forDocument(document).visible); }); test('blurring the tab strip blurs the active element', async () => { // First, make sure tab strip has keyboard focus. callbackRouter.receivedKeyboardFocus(); await flushTasks(); window.dispatchEvent(new Event('blur')); assertEquals(tabList.shadowRoot!.activeElement, null); }); test('should update the ID when a tab is replaced', async () => { assertEquals(getUnpinnedTabs()[0]!.tab.id, 0); callbackRouter.tabReplaced(tabs[0]!.id, 1000); await flushTasks(); assertEquals(getUnpinnedTabs()[0]!.tab.id, 1000); }); test('has custom context menu', async () => { const event = new PointerEvent('pointerup', {clientX: 1, clientY: 2, button: 2}); document.dispatchEvent(event); const contextMenuArgs = await testTabsApiProxy.whenCalled('showBackgroundContextMenu'); assertEquals(contextMenuArgs[0], 1); assertEquals(contextMenuArgs[1], 2); }); test('scrolls to active tabs', async () => { await tabList.animationPromises; const scrollPadding = 32; const tabWidth = 200; const viewportWidth = 300; // Mock the width of each tab element. tabList.style.setProperty( '--tabstrip-tab-thumbnail-width', `${tabWidth}px`); tabList.style.setProperty('--tabstrip-tab-spacing', '0px'); const tabElements = getUnpinnedTabs(); tabElements.forEach(tabElement => { tabElement.style.width = `${tabWidth}px`; }); // Mock the scroller size such that it cannot fit only 1 tab at a time. tabList.style.setProperty( '--tabstrip-viewport-width', `${viewportWidth}px`); tabList.style.width = `${viewportWidth}px`; // Verify the scrollLeft is currently at its default state of 0, and then // send a visibilitychange event to cause a scroll. assertEquals(tabList.scrollLeft, 0); callbackRouter.tabActiveChanged(tabs[1]!.id); await flushTasks(); testTabsApiProxy.setVisible(false); document.dispatchEvent(new Event('visibilitychange')); // The 2nd tab should be off-screen to the right, so activating it should // scroll so that the element's right edge is aligned with the screen's // right edge. let activeTab = getUnpinnedTabs()[1]!; assertEquals( tabList.scrollLeft + tabList.offsetWidth, activeTab.offsetLeft + activeTab.offsetWidth + scrollPadding); // The 1st tab should be now off-screen to the left, so activating it should // scroll so that the element's left edge is aligned with the screen's // left edge. callbackRouter.tabActiveChanged(tabs[0]!.id); await flushTasks(); assertEquals(tabList.scrollLeft, 0); }); test('PreventsDraggingWhenOnlyOneTab', () => { assertFalse(tabList.shouldPreventDrag()); const tabElements = getUnpinnedTabs(); tabElements[1]!.remove(); tabElements[2]!.remove(); assertTrue(tabList.shouldPreventDrag()); }); });
the_stack
import { HeadQueueEntry, LiveAtlasArea, LiveAtlasCircle, LiveAtlasComponentConfig, LiveAtlasDimension, LiveAtlasLine, LiveAtlasMarker, LiveAtlasMarkerSet, LiveAtlasPartialComponentConfig, LiveAtlasPlayer, LiveAtlasServerConfig, LiveAtlasServerDefinition, LiveAtlasServerMessageConfig, LiveAtlasWorldDefinition } from "@/index"; import LiveAtlasMapDefinition from "@/model/LiveAtlasMapDefinition"; import {MutationTypes} from "@/store/mutation-types"; import MapProvider from "@/providers/MapProvider"; import {ActionTypes} from "@/store/action-types"; import {titleColoursRegex} from "@/util"; export default class Pl3xmapMapProvider extends MapProvider { private configurationAbort?: AbortController = undefined; private markersAbort?: AbortController = undefined; private playersAbort?: AbortController = undefined; private updatesEnabled = false; private updateTimeout: null | ReturnType<typeof setTimeout> = null; private updateTimestamp: Date = new Date(); private updateInterval: number = 3000; private worldComponents: Map<string, { components: LiveAtlasPartialComponentConfig, }> = new Map(); constructor(config: LiveAtlasServerDefinition) { super(config); } private static buildServerConfig(response: any): LiveAtlasServerConfig { return { title: (response.ui?.title || 'Pl3xmap').replace(titleColoursRegex, ''), expandUI: response.ui?.sidebar?.pinned === 'pinned', //Not used by pl3xmap defaultZoom: 1, defaultMap: undefined, defaultWorld: undefined, followMap: undefined, followZoom: undefined, }; } private static buildMessagesConfig(response: any): LiveAtlasServerMessageConfig { return { worldsHeading: response.ui?.sidebar?.world_list_label || '', playersHeading: response.ui?.sidebar?.player_list_label || '', //Not used by pl3xmap chatPlayerJoin: '', chatPlayerQuit: '', chatAnonymousJoin: '', chatAnonymousQuit: '', chatErrorNotAllowed: '', chatErrorRequiresLogin: '', chatErrorCooldown: '', } } private buildWorlds(serverResponse: any, worldResponses: any[]): Array<LiveAtlasWorldDefinition> { const worlds: Array<LiveAtlasWorldDefinition> = []; (serverResponse.worlds || []).filter((w: any) => w && !!w.name).forEach((world: any, index: number) => { const worldResponse = worldResponses[index], worldConfig: {components: LiveAtlasPartialComponentConfig } = { components: {}, }; if(worldResponse.player_tracker?.enabled) { const health = !!worldResponse.player_tracker?.nameplates?.show_health, armor = !!worldResponse.player_tracker?.nameplates?.show_armor, images = !!worldResponse.player_tracker?.nameplates?.show_heads; worldConfig.components.playerMarkers = { grayHiddenPlayers: true, hideByDefault: !!worldResponse.player_tracker?.default_hidden, layerName: worldResponse.player_tracker?.label || '', layerPriority: worldResponse.player_tracker?.priority, imageSize: images ? (health && armor ? 'large' : 'small') : 'none', showHealth: health, showArmor: armor, } } else { worldConfig.components.playerMarkers = undefined; } this.worldComponents.set(world.name, worldConfig); if(!worldResponse) { console.warn(`World ${world.name} has no matching world config. Ignoring.`); return; } let dimension: LiveAtlasDimension = 'overworld'; if(world.type === 'nether') { dimension = 'nether'; } else if(world.type === 'the_end') { dimension = 'end'; } const maps: Map<string, LiveAtlasMapDefinition> = new Map(); const w = { name: world.name || '(Unnamed world)', displayName: world.display_name || world.name, dimension, seaLevel: 0, center: {x: worldResponse.spawn.x, y: 0, z: worldResponse.spawn.z}, maps, }; maps.set('flat', Object.freeze(new LiveAtlasMapDefinition({ world: w, background: 'transparent', backgroundDay: 'transparent', backgroundNight: 'transparent', icon: world.icon ? `${this.config.pl3xmap}images/icon/${world.icon}.png` : undefined, imageFormat: 'png', name: 'flat', displayName: 'Flat', nativeZoomLevels: worldResponse.zoom.max || 1, extraZoomLevels: worldResponse.zoom.extra || 0, tileUpdateInterval: worldResponse.tiles_update_interval ? worldResponse.tiles_update_interval * 1000 : undefined, }))); worlds.push(w); }); return Array.from(worlds.values()); } private static buildComponents(response: any): LiveAtlasComponentConfig { const components: LiveAtlasComponentConfig = { coordinatesControl: undefined, linkControl: !!response.ui?.link?.enabled, layerControl: !!response.ui?.coordinates?.enabled, //Configured per-world playerMarkers: undefined, //Not configurable markers: { showLabels: false, }, playerList: { showImages: true, }, //Not used by pl3xmap chatBox: undefined, chatBalloons: false, clockControl: undefined, logoControls: [], login: false, }; if(response.ui?.coordinates?.enabled) { //Try to remove {x}/{z} placeholders are we aren't using them const label = (response.ui?.coordinates?.html || "Location: ").replace(/{x}.*{z}/gi, '').trim(), labelPlain = new DOMParser().parseFromString(label, 'text/html').body.textContent || ""; components.coordinatesControl = { showY: false, label: labelPlain, showRegion: false, showChunk: false, } } return components; } private async getMarkerSets(world: LiveAtlasWorldDefinition): Promise<Map<string, LiveAtlasMarkerSet>> { const url = `${this.config.pl3xmap}tiles/${world.name}/markers.json`; if(this.markersAbort) { this.markersAbort.abort(); } this.markersAbort = new AbortController(); const response = await Pl3xmapMapProvider.getJSON(url, this.markersAbort.signal); const sets: Map<string, LiveAtlasMarkerSet> = new Map(); if(!Array.isArray(response)) { return sets; } response.forEach(set => { if(!set || !set.id) { console.warn('Ignoring marker set without id'); return; } const id = set.id; const markers: Map<string, LiveAtlasMarker> = Object.freeze(new Map()), circles: Map<string, LiveAtlasCircle> = Object.freeze(new Map()), areas: Map<string, LiveAtlasArea> = Object.freeze(new Map()), lines: Map<string, LiveAtlasLine> = Object.freeze(new Map()); (set.markers || []).forEach((marker: any) => { switch(marker.type) { case 'icon': markers.set(`marker-${markers.size}`, Pl3xmapMapProvider.buildMarker(marker)); break; case 'polyline': lines.set(`line-${lines.size}`, Pl3xmapMapProvider.buildLine(marker)); break; case 'rectangle': areas.set(`area-${areas.size}`, Pl3xmapMapProvider.buildRectangle(marker)); break; case 'polygon': areas.set(`area-${areas.size}`, Pl3xmapMapProvider.buildArea(marker)); break; case 'circle': case 'ellipse': circles.set(`circle-${circles.size}`, Pl3xmapMapProvider.buildCircle(marker)); break; default: console.warn('Marker type ' + marker.type + ' not supported'); } }); const e = { id, label: set.name || "Unnamed set", hidden: set.hide || false, priority: set.order || 0, showLabels: false, markers, circles, areas, lines, }; sets.set(id, e); }); return sets; } private static buildMarker(marker: any): LiveAtlasMarker { return Object.seal({ location: { x: marker.point?.x || 0, y: 0, z: marker.point?.z || 0, }, dimensions: marker.size ? [marker.size.x || 16, marker.size.z || 16] : [16, 16], icon: marker.icon || "default", label: (marker.tooltip || '').trim(), isLabelHTML: true }); } private static buildRectangle(area: any): LiveAtlasArea { return Object.seal({ style: { stroke: typeof area.stroke !== 'undefined' ? !!area.stroke : true, color: area.color || '#3388ff', weight: area.weight || 3, opacity: typeof area.opacity !== 'undefined' ? area.opacity : 1, fill: typeof area.stroke !== 'undefined' ? !!area.stroke : true, fillColor: area.fillColor || area.color || '#3388ff', fillOpacity: area.fillOpacity || 0.2, fillRule: area.fillRule, }, points: [ area.points[0], {x: area.points[0].x, z: area.points[1].z}, area.points[1], {x: area.points[1].x, z: area.points[0].z}, ], outline: false, tooltipContent: area.tooltip, popupContent: area.popup, isPopupHTML: true, }); } private static buildArea(area: any): LiveAtlasArea { return Object.seal({ style: { stroke: typeof area.stroke !== 'undefined' ? !!area.stroke : true, color: area.color || '#3388ff', weight: area.weight || 3, opacity: typeof area.opacity !== 'undefined' ? area.opacity : 1, fill: typeof area.fill !== 'undefined' ? !!area.fill : true, fillColor: area.fillColor || area.color || '#3388ff', fillOpacity: area.fillOpacity || 0.2, fillRule: area.fillRule, }, points: area.points, outline: false, tooltipContent: area.tooltip, popupContent: area.popup, isPopupHTML: true, }); } private static buildLine(line: any): LiveAtlasLine { return Object.seal({ style: { stroke: typeof line.stroke !== 'undefined' ? !!line.stroke : true, color: line.color || '#3388ff', weight: line.weight || 3, opacity: typeof line.opacity !== 'undefined' ? line.opacity : 1, }, points: line.points, tooltipContent: line.tooltip, popupContent: line.popup, isPopupHTML: true, }); } private static buildCircle(circle: any): LiveAtlasCircle { return Object.seal({ location: { x: circle.center?.x || 0, y: 0, z: circle.center?.z || 0, }, radius: [circle.radiusX || circle.radius || 0, circle.radiusZ || circle.radius || 0], style: { stroke: typeof circle.stroke !== 'undefined' ? !!circle.stroke : true, color: circle.color || '#3388ff', weight: circle.weight || 3, opacity: typeof circle.opacity !== 'undefined' ? circle.opacity : 1, fill: typeof circle.stroke !== 'undefined' ? !!circle.stroke : true, fillColor: circle.fillColor || circle.color || '#3388ff', fillOpacity: circle.fillOpacity || 0.2, fillRule: circle.fillRule, }, tooltipContent: circle.tooltip, popupContent: circle.popup, isPopupHTML: true }); } async loadServerConfiguration(): Promise<void> { if(this.configurationAbort) { this.configurationAbort.abort(); } this.configurationAbort = new AbortController(); const baseUrl = this.config.pl3xmap, response = await Pl3xmapMapProvider.getJSON(`${baseUrl}tiles/settings.json`, this.configurationAbort.signal); if (response.error) { throw new Error(response.error); } const config = Pl3xmapMapProvider.buildServerConfig(response), worldNames: string[] = (response.worlds || []).filter((world: any) => world && !!world.name) .map((world: any) => world.name); const worldResponses = await Promise.all(worldNames.map(name => Pl3xmapMapProvider.getJSON(`${baseUrl}tiles/${name}/settings.json`, this.configurationAbort!.signal))); this.store.commit(MutationTypes.SET_SERVER_CONFIGURATION, config); this.store.commit(MutationTypes.SET_SERVER_MESSAGES, Pl3xmapMapProvider.buildMessagesConfig(response)); this.store.commit(MutationTypes.SET_WORLDS, this.buildWorlds(response, worldResponses)); this.store.commit(MutationTypes.SET_COMPONENTS, Pl3xmapMapProvider.buildComponents(response)); } async populateWorld(world: LiveAtlasWorldDefinition) { const markerSets = await this.getMarkerSets(world), worldConfig = this.worldComponents.get(world.name); this.store.commit(MutationTypes.SET_MARKER_SETS, markerSets); this.store.commit(MutationTypes.SET_COMPONENTS, worldConfig!.components); } private async getPlayers(): Promise<Set<LiveAtlasPlayer>> { const url = `${this.config.pl3xmap}tiles/players.json`; if(this.playersAbort) { this.playersAbort.abort(); } this.playersAbort = new AbortController(); const response = await Pl3xmapMapProvider.getJSON(url, this.playersAbort.signal), players: Set<LiveAtlasPlayer> = new Set(); (response.players || []).forEach((player: any) => { players.add({ name: (player.name || '').toLowerCase(), uuid: player.uuid, displayName: player.name || "", health: player.health || 0, armor: player.armor || 0, sort: 0, hidden: false, location: { //Add 0.5 to position in the middle of a block x: !isNaN(player.x) ? player.x + 0.5 : 0, y: 0, z: !isNaN(player.z) ? player.z + 0.5 : 0, world: player.world, } }); }); // Extra fake players for testing // for(let i = 0; i < 450; i++) { // players.add({ // name: "VIDEO GAMES " + i, // displayName: "VIDEO GAMES " + i, // health: Math.round(Math.random() * 10), // armor: Math.round(Math.random() * 10), // sort: Math.round(Math.random() * 10), // hidden: false, // location: { // x: Math.round(Math.random() * 1000) - 500, // y: 0, // z: Math.round(Math.random() * 1000) - 500, // world: "world", // } // }); // } this.store.commit(MutationTypes.SET_MAX_PLAYERS, response.max || 0); return players; } startUpdates() { this.updatesEnabled = true; this.update(); } private async update() { try { if(this.store.state.components.playerMarkers) { const players = await this.getPlayers(); this.updateTimestamp = new Date(); await this.store.dispatch(ActionTypes.SET_PLAYERS, players); } } finally { if(this.updatesEnabled) { if(this.updateTimeout) { clearTimeout(this.updateTimeout); } this.updateTimeout = setTimeout(() => this.update(), this.updateInterval); } } } stopUpdates() { this.updatesEnabled = false; if (this.updateTimeout) { clearTimeout(this.updateTimeout); } this.updateTimeout = null; } getTilesUrl(): string { return `${this.config.pl3xmap}tiles/`; } getPlayerHeadUrl(head: HeadQueueEntry): string { //TODO: Listen to config return 'https://mc-heads.net/avatar/{uuid}/16'.replace('{uuid}', head.uuid || ''); } getMarkerIconUrl(icon: string): string { return `${this.config.pl3xmap}images/icon/registered/${icon}.png`; } destroy() { super.destroy(); if(this.configurationAbort) { this.configurationAbort.abort(); } if(this.playersAbort) { this.playersAbort.abort(); } if(this.markersAbort) { this.markersAbort.abort(); } } }
the_stack
import { OrgInfo } from '@salesforce/salesforcedx-utils-vscode/out/src/cli'; import { RequestService } from '@salesforce/salesforcedx-utils-vscode/out/src/requestService'; import { expect } from 'chai'; import * as sinon from 'sinon'; import { ApexDebuggerEventType, StreamingClient, StreamingClientInfoBuilder, StreamingService } from '../../../src/core'; import childProcess = require('child_process'); describe('Debugger streaming service', () => { const mockSpawn = require('mock-spawn'); const requestService = new RequestService(); requestService.instanceUrl = 'https://www.salesforce.com'; requestService.accessToken = '123'; describe('Subscribe', () => { let service: StreamingService; let origSpawn: any; let mySpawn: any; let clientIsConnectedSpy: sinon.SinonStub; let clientSubscribeSpy: sinon.SinonStub; const orgInfo: OrgInfo = { username: 'name', devHubId: 'devHubId', id: 'id', createdBy: 'someone', createdDate: new Date().toDateString(), expirationDate: new Date().toDateString(), status: 'active', edition: 'Enterprise', orgName: 'My org', accessToken: '123', instanceUrl: 'https://wwww.salesforce.com', clientId: 'foo' }; beforeEach(() => { service = new StreamingService(); origSpawn = childProcess.spawn; mySpawn = mockSpawn(); childProcess.spawn = mySpawn; mySpawn.setDefault( mySpawn.simple( 0, `{ "status": 0, "result": ${JSON.stringify(orgInfo)}}` ) ); clientSubscribeSpy = sinon .stub(StreamingClient.prototype, 'subscribe') .returns(Promise.resolve()); }); afterEach(() => { childProcess.spawn = origSpawn; clientIsConnectedSpy.restore(); clientSubscribeSpy.restore(); }); it('Should return ready if client is connected', async () => { clientIsConnectedSpy = sinon .stub(StreamingClient.prototype, 'isConnected') .returns(true); const isStreamingConnected = await service.subscribe( 'foo', requestService, new StreamingClientInfoBuilder().build(), new StreamingClientInfoBuilder().build() ); expect(isStreamingConnected).to.equal(true); }); it('Should not return ready if client is not connected', async () => { clientIsConnectedSpy = sinon .stub(StreamingClient.prototype, 'isConnected') .returns(false); const isStreamingConnected = await service.subscribe( 'foo', requestService, new StreamingClientInfoBuilder().build(), new StreamingClientInfoBuilder().build() ); expect(isStreamingConnected).to.equal(false); }); }); describe('Disconnect', () => { let service: StreamingService; let clientDisconnectSpy: sinon.SinonStub; let clientIsConnectedSpy: sinon.SinonStub; let clientSubscribeSpy: sinon.SinonStub; beforeEach(() => { service = new StreamingService(); clientDisconnectSpy = sinon.stub(StreamingClient.prototype, 'disconnect'); clientIsConnectedSpy = sinon .stub(StreamingClient.prototype, 'isConnected') .returns(true); clientSubscribeSpy = sinon .stub(StreamingClient.prototype, 'subscribe') .returns(Promise.resolve()); }); afterEach(() => { clientDisconnectSpy.restore(); clientIsConnectedSpy.restore(); clientSubscribeSpy.restore(); }); it('Should not error out without any clients', () => { try { service.disconnect(); } catch (error) { expect.fail('Should not have thrown an exception'); } }); it('Should call streaming client disconnect', async () => { await service.subscribe( 'foo', requestService, new StreamingClientInfoBuilder().build(), new StreamingClientInfoBuilder().build() ); service.disconnect(); expect(clientDisconnectSpy.calledTwice).to.equal(true); }); }); describe('Is ready', () => { let service: StreamingService; let clientIsConnectedSpy: sinon.SinonStub; let clientSubscribeSpy: sinon.SinonStub; beforeEach(() => { service = new StreamingService(); clientSubscribeSpy = sinon .stub(StreamingClient.prototype, 'subscribe') .returns(Promise.resolve()); }); afterEach(() => { if (clientIsConnectedSpy) { clientIsConnectedSpy.restore(); } clientSubscribeSpy.restore(); }); it('Should not be ready without any clients', () => { expect(service.isReady()).to.equal(false); }); it('Should not be ready if client is not ready', async () => { clientIsConnectedSpy = sinon .stub(StreamingClient.prototype, 'isConnected') .returns(false); await service.subscribe( 'foo', requestService, new StreamingClientInfoBuilder().build(), new StreamingClientInfoBuilder().build() ); expect(service.isReady()).to.equal(false); }); it('Should be ready if client is ready', async () => { clientIsConnectedSpy = sinon .stub(StreamingClient.prototype, 'isConnected') .returns(true); await service.subscribe( 'foo', requestService, new StreamingClientInfoBuilder().build(), new StreamingClientInfoBuilder().build() ); expect(service.isReady()).to.equal(true); }); }); describe('Get client based on event type', () => { let service: StreamingService; let clientSubscribeSpy: sinon.SinonStub; let clientIsConnectedSpy: sinon.SinonStub; const systemEventClient = new StreamingClientInfoBuilder() .forChannel(StreamingService.SYSTEM_EVENT_CHANNEL) .build(); const userEventClient = new StreamingClientInfoBuilder() .forChannel(StreamingService.USER_EVENT_CHANNEL) .build(); before(async () => { service = new StreamingService(); clientSubscribeSpy = sinon .stub(StreamingClient.prototype, 'subscribe') .returns(Promise.resolve()); clientIsConnectedSpy = sinon .stub(StreamingClient.prototype, 'isConnected') .returns(true); await service.subscribe( 'foo', requestService, systemEventClient, userEventClient ); }); after(() => { clientSubscribeSpy.restore(); clientIsConnectedSpy.restore(); }); it('Should handle ApexException', () => { const client = service.getClient(ApexDebuggerEventType.ApexException)!; expect(client.getClientInfo().channel).to.equal( StreamingService.USER_EVENT_CHANNEL ); }); it('Should handle Debug', () => { const client = service.getClient(ApexDebuggerEventType.Debug)!; expect(client.getClientInfo().channel).to.equal( StreamingService.USER_EVENT_CHANNEL ); }); it('Should handle LogLine', () => { const client = service.getClient(ApexDebuggerEventType.ApexException)!; expect(client.getClientInfo().channel).to.equal( StreamingService.USER_EVENT_CHANNEL ); }); it('Should handle OrgChange', () => { const client = service.getClient(ApexDebuggerEventType.OrgChange)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle Ready', () => { const client = service.getClient(ApexDebuggerEventType.Ready)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle RequestFinished', () => { const client = service.getClient(ApexDebuggerEventType.RequestFinished)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle RequestStarted', () => { const client = service.getClient(ApexDebuggerEventType.RequestStarted)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle Resumed', () => { const client = service.getClient(ApexDebuggerEventType.Resumed)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle SessionTerminated', () => { const client = service.getClient( ApexDebuggerEventType.SessionTerminated )!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle Stopped', () => { const client = service.getClient(ApexDebuggerEventType.Stopped)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle SystemGack', () => { const client = service.getClient(ApexDebuggerEventType.SystemGack)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle SystemInfo', () => { const client = service.getClient(ApexDebuggerEventType.SystemInfo)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should handle SystemWarning', () => { const client = service.getClient(ApexDebuggerEventType.SystemWarning)!; expect(client.getClientInfo().channel).to.equal( StreamingService.SYSTEM_EVENT_CHANNEL ); }); it('Should not handle Heartbeat', () => { const client = service.getClient(ApexDebuggerEventType.HeartBeat)!; expect(client).to.equal(undefined); }); }); describe('Replay ID', () => { let service: StreamingService; let clientSubscribeSpy: sinon.SinonStub; let clientIsConnectedSpy: sinon.SinonStub; let clientSetReplayIdSpy: sinon.SinonSpy; const systemEventClient = new StreamingClientInfoBuilder() .forChannel(StreamingService.SYSTEM_EVENT_CHANNEL) .build(); const userEventClient = new StreamingClientInfoBuilder() .forChannel(StreamingService.USER_EVENT_CHANNEL) .build(); beforeEach(async () => { service = new StreamingService(); clientSubscribeSpy = sinon .stub(StreamingClient.prototype, 'subscribe') .returns(Promise.resolve()); clientIsConnectedSpy = sinon .stub(StreamingClient.prototype, 'isConnected') .returns(true); clientSetReplayIdSpy = sinon.spy( StreamingClient.prototype, 'setReplayId' ); await service.subscribe( 'foo', requestService, systemEventClient, userEventClient ); }); afterEach(() => { clientSubscribeSpy.restore(); clientIsConnectedSpy.restore(); clientSetReplayIdSpy.restore(); }); it('Should not have processed event', () => { expect( service.hasProcessedEvent(ApexDebuggerEventType.Stopped, 2) ).to.equal(false); }); it('Should have processed event', () => { service.markEventProcessed(ApexDebuggerEventType.Stopped, 2); expect( service.hasProcessedEvent(ApexDebuggerEventType.Stopped, 2) ).to.equal(true); }); it('Should have processed event if client cannot be determined', () => { expect( service.hasProcessedEvent(ApexDebuggerEventType.HeartBeat, 2) ).to.equal(true); }); it('Should not mark event processed if client cannot be determined', () => { service.markEventProcessed(ApexDebuggerEventType.HeartBeat, 2); expect(clientSetReplayIdSpy.called).to.equal(false); }); }); });
the_stack
import * as Chunk from "@effect-ts/system/Collections/Immutable/Chunk" import type * as Tp from "@effect-ts/system/Collections/Immutable/Tuple" import type { Predicate } from "@effect-ts/system/Function" import { identity, pipe } from "@effect-ts/system/Function" import type { Either } from "../../../Either" import type { Equal } from "../../../Equal" import { makeEqual } from "../../../Equal" import type { Identity } from "../../../Identity" import { makeIdentity } from "../../../Identity" import type { ChunkURI } from "../../../Modules" import * as Ord from "../../../Ord" import type { URI } from "../../../Prelude" import * as P from "../../../Prelude" import * as DSL from "../../../Prelude/DSL" import type { Show } from "../../../Show" import type { PredicateWithIndex, Separated } from "../../../Utils" export * from "@effect-ts/system/Collections/Immutable/Chunk" /** * `ForEachWithIndex`'s `forEachWithIndexF` function */ export const forEachWithIndexF = P.implementForEachWithIndexF<[URI<ChunkURI>]>()( (_) => (G) => { const succeed = DSL.succeedF(G) return (f) => (fa) => { let base = succeed(Chunk.empty<typeof _.B>()) for (let k = 0; k < fa.length; k += 1) { base = G.map( ({ tuple: [bs, b] }: Tp.Tuple<[Chunk.Chunk<typeof _.B>, typeof _.B]>) => Chunk.append_(bs, b) )(G.both(f(k, Chunk.unsafeGet_(fa, k)!))(base)) } return base } } ) /** * `ForEach`'s `forEachF` function */ export const forEachF = P.implementForEachF<[URI<ChunkURI>]>()( (_) => (G) => (f) => forEachWithIndexF(G)((_, a) => f(a)) ) /** * `ForEach`'s `forEachF` function */ export const forEachF_: P.ForeachFn_<[URI<ChunkURI>]> = (fa, G) => (f) => forEachF(G)(f)(fa) /** * `Wilt`'s `separateF` function */ export const separateF = P.implementSeparateF<[URI<ChunkURI>]>()( (_) => (G) => (f) => (x) => pipe(x, forEachF(G)(f), G.map(Chunk.partitionMap(identity))) ) /** * `Wilt`'s `separateF` function */ export const separateWithIndexF = P.implementSeparateWithIndexF<[URI<ChunkURI>]>()( (_) => (G) => (f) => (x) => pipe(x, forEachWithIndexF(G)(f), G.map(Chunk.partitionMap(identity))) ) /** * `Wither`'s `compactF` function */ export const compactF = P.implementCompactF<[URI<ChunkURI>]>()( (_) => (G) => (f) => (x) => pipe(x, forEachF(G)(f), G.map(Chunk.compact)) ) /** * `WitherWithIndex`'s `compactWithIndexF` function */ export const compactWithIndexF = P.implementCompactWithIndexF<[URI<ChunkURI>]>()( (_) => (G) => (f) => (x) => pipe(x, forEachWithIndexF(G)(f), G.map(Chunk.compact)) ) /** * Test if a value is a member of an array. Takes a `Equal<A>` as a single * argument which returns the function to use to search for a value of type `A` in * an array of type `Chunk<A>`. * * @ets_data_first elem_ */ export function elem<A>(E: Equal<A>, a: A): (as: Chunk.Chunk<A>) => boolean { return (as) => elem_(as, E, a) } /** * Test if a value is a member of an array. Takes a `Equal<A>` as a single * argument which returns the function to use to search for a value of type `A` in * an array of type `Chunk<A>`. */ export function elem_<A>(as: Chunk.Chunk<A>, E: Equal<A>, a: A): boolean { const predicate = (element: A) => E.equals(element, a) let i = 0 const len = as.length for (; i < len; i++) { if (predicate(Chunk.unsafeGet_(as, i)!)) { return true } } return false } /** * Creates an array of array values not included in the other given array using a `Equal` for equality * comparisons. The order and references of result values are determined by the first array. */ export function difference_<A>( xs: Chunk.Chunk<A>, E: Equal<A>, ys: Chunk.Chunk<A> ): Chunk.Chunk<A> { return Chunk.filter_(xs, (a) => !elem_(ys, E, a)) } /** * Creates an array of array values not included in the other given array using a `Equal` for equality * comparisons. The order and references of result values are determined by the first array. * * @ets_data_first difference_ */ export function difference<A>( E: Equal<A>, ys: Chunk.Chunk<A> ): (xs: Chunk.Chunk<A>) => Chunk.Chunk<A> { return (xs) => difference_(xs, E, ys) } /** * Derives an `Equal` over the `Chunk` of a given element type from the `Equal` of that type. The derived `Equal` defines two * arrays as equal if all elements of both arrays are compared equal pairwise with the given `E`. In case of arrays of * different lengths, the result is non equality. */ export function getEqual<A>(E: Equal<A>): Equal<Chunk.Chunk<A>> { return makeEqual((xs, ys) => xs === ys || Chunk.corresponds_(xs, ys, E.equals)) } /** * Returns a `Identity` for `Chunk<A>` */ export function getIdentity<A>() { return makeIdentity(Chunk.empty<A>(), Chunk.concat_) } /** * Returns a `Ord` for `Chunk<A>` given `Ord<A>` */ export function getOrd<A>(O: Ord.Ord<A>): Ord.Ord<Chunk.Chunk<A>> { return Ord.makeOrd((a, b) => { const aLen = a.length const bLen = b.length const len = Math.min(aLen, bLen) for (let i = 0; i < len; i++) { const ordering = O.compare(Chunk.unsafeGet_(a, i)!, Chunk.unsafeGet_(b, i)!) if (ordering !== 0) { return ordering } } return Ord.number.compare(aLen, bLen) }) } /** * Returns a `Show` for `Chunk<A>` given `Show<A>` */ export function getShow<A>(S: Show<A>): Show<Chunk.Chunk<A>> { return { show: (as) => `[${Chunk.map_(as, S.show)["|>"](Chunk.join(", "))}]` } } /** * Creates an array of unique values that are included in all given arrays using a `Eq` for equality * comparisons. The order and references of result values are determined by the first array. */ export function intersection_<A>( xs: Chunk.Chunk<A>, E: Equal<A>, ys: Chunk.Chunk<A> ): Chunk.Chunk<A> { return Chunk.filter_(xs, (a) => elem_(ys, E, a)) } /** * Creates an array of unique values that are included in all given arrays using a `Eq` for equality * comparisons. The order and references of result values are determined by the first array. * * @ets_data_first intersection_ */ export function intersection<A>( E: Equal<A>, ys: Chunk.Chunk<A> ): (xs: Chunk.Chunk<A>) => Chunk.Chunk<A> { return (xs) => intersection_(xs, E, ys) } /** * Fold Identity with a mapping function */ export function foldMap<M>( M: Identity<M> ): <A>(f: (a: A) => M) => (fa: Chunk.Chunk<A>) => M { return (f) => foldMapWithIndex(M)((_, a) => f(a)) } /** * Fold Identity with a mapping function */ export function foldMap_<M, A>(fa: Chunk.Chunk<A>, M: Identity<M>, f: (a: A) => M): M { return foldMapWithIndex_(fa, M, (_, a) => f(a)) } /** * Fold Identity with a mapping function that consider also the index */ export function foldMapWithIndex<M>( M: Identity<M> ): <A>(f: (i: number, a: A) => M) => (fa: Chunk.Chunk<A>) => M { return (f) => (fa) => foldMapWithIndex_(fa, M, f) } /** * Fold Identity with a mapping function that consider also the index */ export function foldMapWithIndex_<M, A>( fa: Chunk.Chunk<A>, M: Identity<M>, f: (i: number, a: A) => M ): M { return Chunk.reduce_(Chunk.zipWithIndex(fa), M.identity, (b, { tuple: [a, i] }) => M.combine(b, f(i, a)) ) } /** * Sort the elements of an array in increasing order * * @ets_data_first sort_ */ export function sort<A>(O: Ord.Ord<A>): (as: Chunk.Chunk<A>) => Chunk.Chunk<A> { return (as) => sort_(as, O) } /** * Sort the elements of an array in increasing order */ export function sort_<A>(as: Chunk.Chunk<A>, O: Ord.Ord<A>): Chunk.Chunk<A> { return Chunk.from([...Chunk.toArray(as)].sort((x, y) => O.compare(x, y))) } /** * Sort the elements of an array in increasing order, where elements are compared using first `ords[0]`, * then `ords[1]`, then `ords[2]`, etc... * * @ets_data_first sortBy_ */ export function sortBy<A>( ords: Array<Ord.Ord<A>> ): (as: Chunk.Chunk<A>) => Chunk.Chunk<A> { return (as) => sortBy_(as, ords) } /** * Sort the elements of an array in increasing order, where elements are compared using first `ords[0]`, * then `ords[1]`, then `ords[2]`, etc... */ export function sortBy_<A>( as: Chunk.Chunk<A>, ords: Array<Ord.Ord<A>> ): Chunk.Chunk<A> { const M = Ord.getIdentity<A>() return sort_( as, ords.reduce((x, y) => M.combine(x, y), M.identity) ) } /** * Creates an array of unique values, in order, from all given arrays using a `Equal` for equality comparisons */ export function union_<A>( xs: Chunk.Chunk<A>, E: Equal<A>, ys: Chunk.Chunk<A> ): Chunk.Chunk<A> { return Chunk.concat_( xs, Chunk.filter_(ys, (a) => !elem_(xs, E, a)) ) } /** * Creates an array of unique values, in order, from all given arrays using a `Equal` for equality comparisons * * @ets_data_first union_ */ export function union<A>( E: Equal<A>, ys: Chunk.Chunk<A> ): (xs: Chunk.Chunk<A>) => Chunk.Chunk<A> { return (xs) => union_(xs, E, ys) } /** * Remove duplicates from an array, keeping the first occurrence of an element. */ export function uniq_<A>(as: Chunk.Chunk<A>, E: Equal<A>): Chunk.Chunk<A> { let r: Chunk.Chunk<A> = Chunk.empty() const len = as.length let i = 0 for (; i < len; i++) { const a = as[i]! if (!elem_(r, E, a)) { r = Chunk.append_(r, a) } } return len === r.length ? as : r } /** * Remove duplicates from an array, keeping the first occurrence of an element. * * @ets_data_first uniq_ */ export function uniq<A>(E: Equal<A>): (as: Chunk.Chunk<A>) => Chunk.Chunk<A> { return (as) => uniq_(as, E) } /** * Separate elements based on a apredicate * * @ets_data_first partition_ */ export function partition<A>(predicate: Predicate<A>) { return (fa: Chunk.Chunk<A>): Separated<Chunk.Chunk<A>, Chunk.Chunk<A>> => partitionWithIndex((_, a: A) => predicate(a))(fa) } /** * Separate elements based on a apredicate */ export function partition_<A>( fa: Chunk.Chunk<A>, predicate: Predicate<A> ): Separated<Chunk.Chunk<A>, Chunk.Chunk<A>> { return partitionWithIndex((_, a: A) => predicate(a))(fa) } /** * Separate elements based on a map function that also carry the index */ export function partitionMapWithIndex_<A, B, C>( fa: Chunk.Chunk<A>, f: (i: number, a: A) => Either<B, C> ): Separated<Chunk.Chunk<B>, Chunk.Chunk<C>> { const left: Array<B> = [] const right: Array<C> = [] for (let i = 0; i < fa.length; i++) { const e = f(i, Chunk.unsafeGet_(fa, i)!) if (e._tag === "Left") { left.push(e.left) } else { right.push(e.right) } } return { left: Chunk.from(left), right: Chunk.from(right) } } /** * Separate elements based on a map function that also carry the index * * @ets_data_first partitionMapWithIndex_ */ export function partitionMapWithIndex<A, B, C>(f: (i: number, a: A) => Either<B, C>) { return (fa: Chunk.Chunk<A>): Separated<Chunk.Chunk<B>, Chunk.Chunk<C>> => partitionMapWithIndex_(fa, f) } /** * Separate elements based on a predicate that also carry the index * * @ets_data_first partitionWithIndex */ export function partitionWithIndex<A>( predicateWithIndex: PredicateWithIndex<number, A> ) { return (fa: Chunk.Chunk<A>): Separated<Chunk.Chunk<A>, Chunk.Chunk<A>> => partitionWithIndex_(fa, predicateWithIndex) } /** * Separate elements based on a predicate that also carry the index */ export function partitionWithIndex_<A>( fa: Chunk.Chunk<A>, predicateWithIndex: PredicateWithIndex<number, A> ): Separated<Chunk.Chunk<A>, Chunk.Chunk<A>> { const left: Array<A> = [] const right: Array<A> = [] for (let i = 0; i < fa.length; i++) { const a = Chunk.unsafeGet_(fa, i)! if (predicateWithIndex(i, a)) { right.push(a) } else { left.push(a) } } return { left: Chunk.from(left), right: Chunk.from(right) } }
the_stack
import { Component, OnInit, ViewEncapsulation, AfterViewInit, } from '@angular/core'; import { Helpers } from '../../../../helpers'; import { ScriptLoaderService } from '../../../../_services/script-loader.service'; declare let $: any; @Component({ selector: 'app-index', templateUrl: './index.component.html', }) export class IndexComponent implements OnInit, AfterViewInit { services: any[] = []; modalData: any = { url: '', encryptStatus: 'OK', }; modalUrl: string = ''; datatable: any; // services: any[] = [ // { // serviceName: 'API网关', // author: '金炳', // createTime: '1天前', // }, // { // serviceName: 'Spring Boot Admin监控中心', // author: '强强', // createTime: '6天前', // }, // { // serviceName: '邮件报警中心', // author: 'Anoyi', // createTime: '11天前', // }, // { // serviceName: '日志服务中心', // author: 'FangOba', // createTime: '16天前', // }, // { // serviceName: 'Rancher平台', // author: '金炳', // createTime: '21天前', // }, // { // serviceName: 'Eureka服务注册与发现中心', // author: '翟永超', // createTime: '30天前', // }, // { // serviceName: 'API网关', // author: '金炳', // createTime: '1天前', // }, // { // serviceName: 'Spring Boot Admin监控中心', // author: '强强', // createTime: '6天前', // }, // { // serviceName: '邮件报警中心', // author: 'Anoyi', // createTime: '11天前', // }, // { // serviceName: '日志服务中心', // author: 'FangOba', // createTime: '16天前', // }, // { // serviceName: 'Rancher平台', // author: '金炳', // createTime: '21天前', // }, // { // serviceName: 'Eureka服务注册与发现中心', // author: '翟永超', // createTime: '30天前', // }, // ] constructor(private _script: ScriptLoaderService) { } ngOnInit() { } ngAfterViewInit() { this._script.loadScripts('app-index', ['assets/app/js/dashboard.js']); this.dataTableInit(); } dataTableInit() { var options = { data: { type: 'remote', source: { read: { url: '/xhr/dashboard/envSummary', method: 'GET', params: {}, map: function(raw) { // sample data mapping var dataSet = raw; if (typeof raw.data !== 'undefined') { dataSet = raw.data; } return dataSet; }, }, }, pageSize: 10, saveState: { cookie: true, webstorage: true, }, serverPaging: false, serverFiltering: false, serverSorting: false, autoColumns: false, }, layout: { theme: 'default', class: 'm-datatable--brand', scroll: false, height: null, footer: false, header: true, smoothScroll: { scrollbarShown: false, }, spinner: { overlayColor: '#000000', opacity: 0, type: 'loader', state: 'brand', message: true, }, icons: { sort: { asc: 'la la-arrow-up', desc: 'la la-arrow-down' }, pagination: { next: 'la la-angle-right', prev: 'la la-angle-left', first: 'la la-angle-double-left', last: 'la la-angle-double-right', more: 'la la-ellipsis-h', }, rowDetail: { expand: 'fa fa-caret-down', collapse: 'fa fa-caret-right', }, }, }, sortable: true, pagination: true, search: { // enable trigger search by keyup enter onEnter: false, // input text for search input: $('#generalSearch'), // search delay in milliseconds delay: 200, }, rows: { callback: function() { }, // auto hide columns, if rows overflow. work on non locked columns autoHide: false, }, // columns definition columns: [ { field: 'name', title: '环境名称', sortable: 'asc', filterable: false, responsive: { visible: 'lg' }, template: '{{name}}', }, { field: 'configServers', title: '配置中心状态', sortable: 'asc', filterable: false, responsive: { visible: 'lg' }, template: function(row) { let envs = ''; envs = row.configServers.reduce((total, item) => { return total + item.encryptStatus === 'OK' ? `<span class="m-badge m-badge--success m-badge--wide" style="margin-right: 15px;" data-url="${ item.url }" data-id="${row.id}"> </span>` : `<span class="m-badge m-badge--danger m-badge--wide" style="margin-right: 15px;" data-url="${ item.url }" data-id="${row.id}"> </span>`; }, envs); return envs; }, }, { field: 'params', title: '环境参数项', sortable: 'asc', filterable: false, responsive: { visible: 'lg' }, template: '{{params}}', }, { field: 'projects', title: '部署项目数', sortable: false, overflow: 'visible', template: '{{projects}}', }, ], toolbar: { layout: ['pagination', 'info'], placement: ['bottom'], //'top', 'bottom' items: { pagination: { type: 'default', pages: { desktop: { layout: 'default', pagesNumber: 6, }, tablet: { layout: 'default', pagesNumber: 3, }, mobile: { layout: 'compact', }, }, navigation: { prev: true, next: true, first: true, last: true, }, pageSizeSelect: [10, 20, 30, 50, 100], }, info: true, }, }, translate: { records: { processing: '正在获取环境列表', noRecords: '当前还没有配置环境', }, toolbar: { pagination: { items: { default: { first: '首页', prev: '上一页', next: '下一页', last: '末页', more: '更多页', input: 'Page number', select: '请选择每页显示数量', }, info: '显示第 {{start}} - {{end}} 条记录,总共 {{total}} 条', }, }, }, }, }; let self = this; this.datatable = (<any>$('#m_datatable')).mDatatable(options); $('#m_datatable').on('click', '.m-badge', event => { let url = $(event.target).attr('data-url'); let id = $(event.target).attr('data-id'); self.showConfigServer(id, url); }); } showConfigServer(id, url) { let allData = this.datatable.getColumn(0).originalDataSet; let result = allData.filter(item => { if (item.id == id) { return true; } else { return false; } }); this.modalData = result[0].configServers.filter(item => { if (item.url === url) { return true; } else { return false; } })[0]; $('#m_modal_1').modal('show'); } }
the_stack
// tslint:disable:no-unused-expression max-func-body-length promise-function-async max-line-length no-unnecessary-class // tslint:disable:no-non-null-assertion object-literal-key-quotes variable-name import * as assert from "assert"; import { CaseInsensitiveMap, Histogram } from "../extension.bundle"; import { IPartialDeploymentTemplate } from "./support/diagnostics"; import { parseTemplate } from "./support/parseTemplate"; suite("ResourceUsage (schema.stats telemetry)", () => { async function testGetResourceUsage( template: IPartialDeploymentTemplate | string, expectedResourceCounts: { [key: string]: number }, expectedInvalidResourceCounts?: { [key: string]: number }, expectedInvalidVersionCounts?: { [key: string]: number } ): Promise<void> { const dt = parseTemplate(template); const availableResourceTypesAndVersions = new CaseInsensitiveMap<string, string[]>(); availableResourceTypesAndVersions.set("Microsoft.Network/virtualNetworks", ["2016-08-01", "2018-10-01", "2019-08-01"]); availableResourceTypesAndVersions.set("Microsoft.Resources/deployments", ["2020-10-01"]); const [resourceUsage, invalidResourceCounts, invalidVersionCounts] = dt.getResourceUsage(availableResourceTypesAndVersions); const expectedResourceCountsHistogram = new Histogram(); for (let propName of Object.getOwnPropertyNames(expectedResourceCounts)) { expectedResourceCountsHistogram.add(propName, expectedResourceCounts[propName]); } assert.deepStrictEqual(resourceUsage, expectedResourceCountsHistogram); if (expectedInvalidResourceCounts) { const expectedInvalidResourceCountsHistogram = new Histogram(); for (let propName of Object.getOwnPropertyNames(expectedInvalidResourceCounts)) { expectedInvalidResourceCountsHistogram.add(propName, expectedInvalidResourceCounts[propName]); } assert.deepStrictEqual(invalidResourceCounts, expectedInvalidResourceCountsHistogram); } if (expectedInvalidVersionCounts) { const expectedInvalidVersionCountsHistogram = new Histogram(); for (let propName of Object.getOwnPropertyNames(expectedInvalidVersionCounts)) { expectedInvalidVersionCountsHistogram.add(propName, expectedInvalidVersionCounts[propName]); } assert.deepStrictEqual(invalidVersionCounts, expectedInvalidVersionCountsHistogram); } } test("Simple resources", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "name": "[parameters('virtualMachineName')]", "type": "Microsoft.Compute/virtualMachines", "apiVersion": "2016-04-30-preview", "location": "[parameters('location')]", "dependsOn": [ "[concat('Microsoft.Network/networkInterfaces/', parameters('networkInterfaceName'))]", "[concat('Microsoft.Compute/availabilitySets/', parameters('availabilitySetName'))]", "[concat('Microsoft.Storage/storageAccounts/', parameters('diagnosticsStorageAccountName'))]" ] }, { "name": "[concat(parameters('virtualMachineName'),'/', variables('diagnosticsExtensionName'))]", "type": "Microsoft.Compute/virtualMachines/extensions", "apiVersion": "2017-03-30", "location": "[parameters('location')]", "dependsOn": [ "[concat('Microsoft.Compute/virtualMachines/', parameters('virtualMachineName'))]" ] } ] }; await testGetResourceUsage(template, { "microsoft.compute/virtualmachines@2016-04-30-preview": 1, "microsoft.compute/virtualmachines/extensions@2017-03-30": 1 }); }); test("Multiple uses of resources, same version", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "name": "[parameters('virtualMachineName')]", "type": "Microsoft.Compute/virtualMachines", "apiVersion": "2016-04-30-preview", "location": "[parameters('location')]", "dependsOn": [ "[concat('Microsoft.Network/networkInterfaces/', parameters('networkInterfaceName'))]", "[concat('Microsoft.Compute/availabilitySets/', parameters('availabilitySetName'))]", "[concat('Microsoft.Storage/storageAccounts/', parameters('diagnosticsStorageAccountName'))]" ] }, { "type": "Microsoft.Compute/virtualMachines", "name": "[parameters('virtualMachineName')]", "apiVersion": "2016-04-30-preview" } ] }; await testGetResourceUsage(template, { "microsoft.compute/virtualmachines@2016-04-30-preview": 2 }); }); test("Multiple uses of resources, case insensitive", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "name": "[parameters('virtualMachineName')]", "type": "Microsoft.Compute/virtualMachines", "apiVersion": "2016-04-30-preview", "location": "[parameters('location')]", "dependsOn": [ "[concat('Microsoft.Network/networkInterfaces/', parameters('networkInterfaceName'))]", "[concat('Microsoft.Compute/availabilitySets/', parameters('availabilitySetName'))]", "[concat('Microsoft.Storage/storageAccounts/', parameters('diagnosticsStorageAccountName'))]" ] }, { "type": "Microsoft.Compute/VIRTUALMACHINES", "name": "[parameters('virtualMachineName')]", "apiVersion": "2016-04-30-PREVIEW" } ] }; await testGetResourceUsage(template, { "microsoft.compute/virtualmachines@2016-04-30-preview": 2 }); }); test("case insensitive keys", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "name": "[parameters('virtualMachineName')]", "TYPE": "Microsoft.Compute/virtualMachines", "APIVERSION": "2016-04-30-preview" } ] }; await testGetResourceUsage(template, { "microsoft.compute/virtualmachines@2016-04-30-preview": 1 }); }); test("Multiple uses of resources, different version", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "name": "[parameters('virtualMachineName')]", "type": "Microsoft.Compute/virtualMachines", "apiVersion": "2016-04-30-preview", "location": "[parameters('location')]", "dependsOn": [ "[concat('Microsoft.Network/networkInterfaces/', parameters('networkInterfaceName'))]", "[concat('Microsoft.Compute/availabilitySets/', parameters('availabilitySetName'))]", "[concat('Microsoft.Storage/storageAccounts/', parameters('diagnosticsStorageAccountName'))]" ] }, { "type": "Microsoft.Compute/VIRTUALMACHINES", "name": "[parameters('virtualMachineName')]", "apiVersion": "2016-04-30" } ] }; await testGetResourceUsage(template, { "microsoft.compute/virtualmachines@2016-04-30-preview": 1, "microsoft.compute/virtualmachines@2016-04-30": 1 }); }); test("Child resources", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "apiVersion": "2018-10-01", "type": "Microsoft.Network/virtualNetworks", "name": "VNet1", "location": "[parameters('location')]", "properties": { "addressSpace": { "addressPrefixes": [ "10.0.0.0/16" ] } }, "resources": [ { "apiVersion": "2018-10-02", "type": "subnets", "location": "[parameters('location')]", "name": "Subnet1", "dependsOn": [ "VNet1" ], "properties": { "addressPrefix": "10.0.0.0/24" } } ] } ] }; await testGetResourceUsage(template, { "microsoft.network/virtualnetworks@2018-10-01": 1, "subnets@2018-10-02[parent=microsoft.network/virtualnetworks@2018-10-01]": 1 }); }); test("Deep child resources", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "apiVersion": "2018-10-01", "type": "Microsoft.Network/virtualNetworks", "name": "VNet1", "location": "[parameters('location')]", "properties": { "addressSpace": { "addressPrefixes": [ "10.0.0.0/16" ] } }, "resources": [ { "apiVersion": "2018-10-02", "type": "subnets", "location": "[parameters('location')]", "name": "Subnet1", "dependsOn": [ "VNet1" ], "properties": { "addressPrefix": "10.0.0.0/24" }, "resources": [ { "apiVersion": "123", "type": "whatever" } ] } ] }, { "apiVersion": "2018-10-01", "type": "Microsoft.Network/virtualNetworks", "name": "VNet1", "location": "[parameters('location')]", "properties": { "addressSpace": { "addressPrefixes": [ "10.0.0.0/16" ] } } }, { "apiVersion": "123", "type": "whatever" }] }; await testGetResourceUsage(template, { "microsoft.network/virtualnetworks@2018-10-01": 2, "subnets@2018-10-02[parent=microsoft.network/virtualnetworks@2018-10-01]": 1, "whatever@123[parent=subnets@2018-10-02]": 1, "whatever@123": 1 }); }); test("resource type is expression", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "name": "[parameters('virtualMachineName')]", "TYPE": "[parameters('resourceType')]", "APIVERSION": "2016-04-30-preview" } ] }; await testGetResourceUsage(template, { "[expression]@2016-04-30-preview": 1 }); }); test("apiVersion is expression", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "apiVersion": "[concat(variables('apiVersion),'-preview')]", "type": "Microsoft.Network/virtualNetworks" } ] }; await testGetResourceUsage(template, { "microsoft.network/virtualnetworks@[expression]": 1 }); }); test("apiVersion is multi-line expression", async () => { const template = `{ "resources": [ { "apiVersion": "[concat (variables('apiVersion),'-preview')]", "type": "Microsoft.Network/virtualNetworks" } ] }`; await testGetResourceUsage(template, { "microsoft.network/virtualnetworks@[expression]": 1 }); }); test("apiVersion is missing, no apiProfile specified)", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "type": "Microsoft.Network/virtualNetworks" } ] }; await testGetResourceUsage(template, { "microsoft.network/virtualnetworks@(profile=none)": 1 }); }); test("apiVersion is missing, apiProfile specified)", async () => { const template: IPartialDeploymentTemplate = { apiProfile: "myProfile", resources: [ { "type": "Microsoft.Network/virtualNetworks" } ] }; await testGetResourceUsage(template, { "microsoft.network/virtualnetworks@(profile=myprofile)": 1 }); }); test("Invalid resource types and apiVersions)", async () => { const template: IPartialDeploymentTemplate = { resources: [ { "apiVersion": "2018-10-01", "type": "Microsoft.Network/virtualNetworks", }, { "apiVersion": "2018-10-01", "type": "Microsoft.Network/virtualNetworks", }, // Invalid api version { "apiVersion": "2018-10-99", "type": "Microsoft.Network/virtualNetworks" }, { "apiVersion": "2018-10-99", "type": "Microsoft.Network/virtualNetworks" }, // Invalid type { "apiVersion": "2018-10-01", "type": "Microsoft.Network/virtualNetworkies", }, { "apiVersion": "2018-10-01", "type": "Microsoft.Network/virtualNetworkies", }, { "apiVersion": "2018-10-01", "type": "Microsoft.Network/virtualNetworkies", } ] }; await testGetResourceUsage( template, { "microsoft.network/virtualnetworks@2018-10-01": 2, "microsoft.network/virtualnetworkies@2018-10-01": 3, "microsoft.network/virtualnetworks@2018-10-99": 2, }, { "microsoft.network/virtualnetworkies@2018-10-01": 3 }, { "microsoft.network/virtualnetworks@2018-10-99": 2 } ); }); });
the_stack
'use strict'; import assert = require('assert'); import events = require('events'); import util = require('util'); import blpapi = require('blpapi'); import Promise = require('bluebird'); import debug = require('debug'); import _ = require('lodash'); // LOGGING var trace = debug('blpapi-wrapper:trace'); var log = debug('blpapi-wrapper:debug'); // PUBLIC TYPES export interface IRequestCallback { (err: Error, data?: any, isFinal?: boolean): void; } export class Subscription extends events.EventEmitter { security: string; fields: string[]; options: any = null; constructor(security: string, fields: string[], options?: any) { super(); this.security = security; this.fields = fields; if (3 === arguments.length) { this.options = options; } } private toJSON(): Object { var result: { security: string; fields: string[]; options?: any; } = { security: this.security, fields: this.fields }; if (null !== this.options) { result.options = this.options; } return result; } } export class BlpApiError implements Error { // STATIC DATA static NAME: string = 'BlpApiError'; // DATA data: any; name: string; message: string; constructor(data: any) { this.data = data; this.name = BlpApiError.NAME; // Subscription errors have a description, other errors have a message. this.message = data.reason.message || data.reason.description; } } // CONSTANTS var EVENT_TYPE = { RESPONSE: 'RESPONSE' , PARTIAL_RESPONSE: 'PARTIAL_RESPONSE' }; // Mapping of request types to response names to listen for. // The strings are taken from section A of the BLPAPI Developer's Guide, and are organized by // service. var REQUEST_TO_RESPONSE_MAP: { [index: string]: string; } = { // //blp/refdata 'HistoricalDataRequest': 'HistoricalDataResponse', 'IntraDayTickRequest': 'IntraDayTickResponse', 'IntraDayBarRequest': 'IntraDayBarResponse', 'ReferenceDataRequest': 'ReferenceDataResponse', 'PortfolioDataRequest': 'PortfolioDataResponse', 'BeqsRequest': 'BeqsResponse', // //blp/apiflds 'FieldInfoRequest': 'fieldResponse', 'FieldSearchRequest': 'fieldResponse', 'CategorizedFieldSearchRequest': 'categorizedFieldResponse', // //blp/instruments 'instrumentListRequest': 'InstrumentListResponse', 'curveListRequest': 'CurveListResponse', 'govtListRequest': 'GovtListResponse', // //blp/tasvc 'studyRequest': 'studyResponse', // //blp/apiauth 'AuthorizationRequest': 'AuthorizationResponse', 'AuthorizationTokenRequest': 'AuthorizationTokenResponse' }; // Mapping of service URIs to the event names to listen to when subscribed to these services. var SERVICE_TO_SUBSCRIPTION_EVENTS_MAP: { [uri: string]: string[]; } = { '//blp/mktdata': ['MarketDataEvents'], '//blp/mktvwap': ['MarketDataEvents'], '//blp/mktbar': ['MarketBarStart', 'MarketBarUpdate', 'MarketBarEnd'], '//blp/pagedata': ['PageUpdate'] }; // ANONYMOUS FUNCTIONS function isObjectEmpty(obj: Object): boolean { return (0 === Object.getOwnPropertyNames(obj).length); } function securityToService(security: string): string { var serviceRegex = /^\/\/blp\/[a-z]+/; var match = serviceRegex.exec(security); // XXX: note that we shoud probably capture what the default service is to use when // reading in the session options. However, when not specified, it is // '//blp/mktdata'. return match ? match[0] : '//blp/mktdata'; } function subscriptionsToServices(subscriptions: Subscription[]): string[] { return _.chain(subscriptions).map((s: Subscription): string => { return securityToService(s.security); }).uniq().value(); } export class Session extends events.EventEmitter { //ATTRIBUTES // TypeScript compiler needs this to allow "this['property-string']" type of access [index: string]: any; // DATA private session: blpapi.Session; private eventListeners: {[index: string]: {[index: number]: Function}} = {}; private requests: {[index: string]: IRequestCallback} = {}; private subscriptions: {[index: string]: Subscription} = {}; private services: {[index: string]: Promise<void>} = {}; private correlatorId: number = 0; private stopped: Promise<void> = null; // PRIVATE MANIPULATORS private nextCorrelatorId(): number { return this.correlatorId++; } private listen(eventName: string, expectedId: number, handler: Function): void { if (!(eventName in this.eventListeners)) { trace('Listener added: ' + eventName); this.session.on(eventName, ((eventName: string, m: any): void => { var correlatorId = m.correlations[0].value; assert(correlatorId in this.eventListeners[eventName], 'correlation id does not exist: ' + correlatorId); this.eventListeners[eventName][correlatorId](m); }).bind(this, eventName)); this.eventListeners[eventName] = {}; } this.eventListeners[eventName][expectedId] = handler; } private unlisten(eventName: string, correlatorId: number): void { delete this.eventListeners[eventName][correlatorId]; if (isObjectEmpty(this.eventListeners[eventName])) { trace('Listener removed: ' + eventName); this.session.removeAllListeners(eventName); delete this.eventListeners[eventName]; } } private openService(uri: string): Promise<void> { var thenable = this.services[uri] = this.services[uri] || new Promise<void>((resolve: Function, reject: Function): void => { trace('Opening service: ' + uri); var openServiceId = this.nextCorrelatorId(); this.session.openService(uri, openServiceId); this.listen('ServiceOpened', openServiceId, (ev: any): void => { log('Service opened: ' + uri); trace(ev); this.unlisten('ServiceOpened', openServiceId); this.unlisten('ServiceOpenFailure', openServiceId); resolve(); }); this.listen('ServiceOpenFailure', openServiceId, (ev: any): void => { log('Service open failure' + uri); trace(ev); this.unlisten('ServiceOpened', openServiceId); this.unlisten('ServiceOpenFailure', openServiceId); delete this.services[uri]; reject(new BlpApiError(ev.data)); }); }).bind(this); // end 'new Promise' return thenable; } private requestHandler(cb: IRequestCallback, m: any): void { var eventType = m.eventType; var isFinal = (EVENT_TYPE.RESPONSE === eventType); log(util.format('Response: %s|%d|%s', m.messageType, m.correlations[0].value, eventType)); trace(m); cb(null, m.data, isFinal); if (isFinal) { var correlatorId = m.correlations[0].value; var messageType = m.messageType; delete this.requests[correlatorId]; this.unlisten(messageType, correlatorId); } } private sessionTerminatedHandler(ev: any): void { log('Session terminating'); trace(ev); _([{prop: 'eventListeners', cleanupFn: (eventName: string): void => { this.session.removeAllListeners(eventName); }}, {prop: 'requests', cleanupFn: (k: string): void => { this.requests[k](new Error('session terminated')); }}, {prop: 'subscriptions', cleanupFn: (k: string): void => { this.subscriptions[k].emit('error', new Error('session terminated')); }} ]).forEach((table: {prop: string; cleanupFn: (s: string) => void}): void => { Object.getOwnPropertyNames(this[table.prop]).forEach((key: string): void => { table.cleanupFn(key); }); this[table.prop] = null; }); if (!this.stopped) { this.stopped = Promise.resolve(); } // tear down the session this.session.destroy(); this.session = null; // emit event to any listeners this.emit('SessionTerminated', ev.data); log('Session terminated'); } private doRequest(uri: string, requestName: string, request: any, execute: (correlatorId: number) => void, callback: IRequestCallback): void { this.validateSession(); var correlatorId = this.nextCorrelatorId(); this.requests[correlatorId] = callback; this.openService(uri).then((): void => { log(util.format('Request: %s|%d', requestName, correlatorId)); trace(request); execute(correlatorId); assert(requestName in REQUEST_TO_RESPONSE_MAP, util.format('Request, %s, not handled', requestName)); this.listen(REQUEST_TO_RESPONSE_MAP[requestName], correlatorId, this.requestHandler.bind(this, callback)); }).catch((ex: Error): void => { delete this.requests[correlatorId]; callback(ex); }); } // PRIVATE ACCESSORS private validateSession(): void { if (this.stopped) { throw new Error('session terminated'); } } // CREATORS constructor(opts: blpapi.SessionOpts) { super(); this.session = new blpapi.Session(opts); this.session.once('SessionTerminated', this.sessionTerminatedHandler.bind(this)); log('Session created'); trace(opts); this.setMaxListeners(0); // Remove max listener limit } // MANIPULATORS start(cb?: (err: any, value: any) => void): Promise<void> { this.validateSession(); return new Promise<void>((resolve: Function, reject: Function): void => { trace('Starting session'); this.session.start(); var listener = (listenerName: string, handler: Function, ev: any): void => { this.session.removeAllListeners(listenerName); handler(ev.data); }; this.session.once('SessionStarted', listener.bind(this, 'SessionStartupFailure', (data: any): void => { log('Session started'); trace(data); resolve(); })); this.session.once('SessionStartupFailure', listener.bind(this, 'SessionStarted', (data: any): void => { log('Session start failure'); trace(data); reject(new BlpApiError(data)); })); }).nodeify(cb); } stop(cb?: (err: any, value: any) => void): Promise<void> { return this.stopped = this.stopped || new Promise<void>((resolve: Function, reject: Function): void => { log('Stopping session'); this.session.stop(); this.session.once('SessionTerminated', (ev: any): void => { resolve(); }); }).nodeify(cb); } request(uri: string, requestName: string, request: any, identity: blpapi.Identity, callback: IRequestCallback): void { var executeRequest = (correlatorId: number): void => { this.session.request(uri, requestName, request, correlatorId, identity); }; this.doRequest(uri, requestName, request, executeRequest, callback); } authorize(cb?: (err: any, value: any) => void): Promise<void> { return new Promise<void>((resolve: () => void, reject: (err: Error) => void): void => { var callback = (err: Error, data?: any, isFinal?: boolean): void => { if (err) { reject(err); } else if (isFinal) { resolve(); } }; this.doRequest('//blp/apiauth', // uri 'AuthorizationRequest', // requestName null, // request this.session.authorize.bind(this.session, '//blp/apiauth'), callback); }).nodeify(cb); } authorizeUser(request: any, cb?: (err: any, value: any) => void): Promise<blpapi.Identity> { return new Promise<blpapi.Identity>((resolve: (identity: blpapi.Identity) => void, reject: (err: Error) => void): void => { var identity: blpapi.Identity = null; function callback(err: Error, data?: any, isFinal?: boolean): void { if (err) { reject(err); } else { if (data.hasOwnProperty('identity')) { identity = data.identity; } if (isFinal) { if (identity) { resolve(identity); } else { reject(new BlpApiError(data)); } } } } this.doRequest('//blp/apiauth', // uri 'AuthorizationRequest', // requestName request, this.session.authorizeUser.bind(this.session, request), callback); }).nodeify(cb); } subscribe(subscriptions: Subscription[], identity: blpapi.Identity, cb?: (err: any) => void): Promise<void> { this.validateSession(); _.forEach(subscriptions, (s: Subscription, i: number): void => { // XXX: O(N) - not critical but note to use ES6 Map in the future var cid = _.findKey(this.subscriptions, (other: Subscription): boolean => { return s === other; }); if (undefined !== cid) { throw new Error('Subscription already exists for index ' + i); } }); var subs = _.map(subscriptions, (s: Subscription): blpapi.Subscription => { var cid = this.nextCorrelatorId(); // XXX: yes, this is a side-effect of map, but it is needed for performance // reasons until ES6 Map is available this.subscriptions[cid] = s; var result: blpapi.Subscription = { security: s.security, correlation: cid, fields: s.fields }; if ('options' in s) { result.options = s.options; } return result; }); return Promise.all(_.map(subscriptionsToServices(subscriptions), (uri: string): Promise<void> => { return this.openService(uri); })).then((): void => { log('Subscribing to: ' + JSON.stringify(subscriptions)); this.session.subscribe(subs, identity); _.forEach(subs, (s: blpapi.Subscription): void => { var uri = securityToService(s.security); var cid = s.correlation; var userSubscription = this.subscriptions[cid]; assert(uri in SERVICE_TO_SUBSCRIPTION_EVENTS_MAP, util.format('Service, %s, not handled', uri)); var events = SERVICE_TO_SUBSCRIPTION_EVENTS_MAP[uri]; events.forEach((event: string): void => { log('listening on event: ' + event + ' for cid: ' + cid); this.listen(event, cid, (m: any): void => { userSubscription.emit('data', m.data, s); }); }); }); }).catch((ex: Error): void => { _.forEach(subs, (s: blpapi.Subscription): void => { var cid = s.correlation; delete this.subscriptions[cid]; }); throw ex; }).nodeify(cb); } unsubscribe(subscriptions: Subscription[]): void { this.validateSession(); log('Unsubscribing: ' + JSON.stringify(subscriptions)); _.forEach(subscriptions, (s: Subscription, i: number): void => { // XXX: O(N) - not critical but note to use ES6 Map in the future var cid = _.findKey(this.subscriptions, (other: Subscription): boolean => { return s === other; }); if (undefined === cid) { throw new Error('Subscription not found at index ' + i); } }); var cids = _.map(subscriptions, (s: Subscription): number => { // XXX: O(N) - not critical but note to use ES6 Map in the future var cid = _.findKey(this.subscriptions, (other: Subscription): boolean => { return s === other; }); return _.parseInt(cid); }); var subs = _.map(cids, (cid: number): blpapi.Subscription => { return <blpapi.Subscription>{ security: ' ', correlation: cid, fields: [] }; }); this.session.unsubscribe(subs); _.forEach(cids, (cid: number): void => { process.nextTick((): void => { this.subscriptions[cid].emit('end'); delete this.subscriptions[cid]; }); // unlisten for events var service = securityToService(this.subscriptions[cid].security); assert(service in SERVICE_TO_SUBSCRIPTION_EVENTS_MAP, util.format('Service, %s, not handled', service)); var events = SERVICE_TO_SUBSCRIPTION_EVENTS_MAP[service]; _.forEach(events, (e: string): void => { this.unlisten(e, cid); }); }); } }
the_stack
import { Component, ElementRef, ViewChild } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import kebabCase from 'lodash-es/kebabCase'; import { Dashboard } from '../../model/dashboard'; import { DashboardsService } from '../../services/dashboards.service'; import { SlackService } from '../../services/slack.service'; import { TextsService } from '../../services/texts.service'; import { ConfigService } from '../../services/config.service'; import { DragulaService } from 'ng2-dragula'; import { COMMA, ENTER, SPACE } from '@angular/cdk/keycodes'; import { MatAutocompleteSelectedEvent, MatAutocomplete } from '@angular/material/autocomplete'; import { MatChipInputEvent } from '@angular/material/chips'; import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs'; import { map, startWith } from 'rxjs/operators'; @Component({ selector: 'new-and-edit-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss'], providers: [ DashboardsService, SlackService, TextsService, ConfigService, DragulaService ] }) export class FormComponent { backToDashboard: boolean; dashboard: Dashboard; slackChannels: { keys?: string[], values?: any }; slack: { clientId?: string, clientSecret?: string } = {}; edit: boolean = false; columnsUpdated: boolean = false; temp: { displayName?: string, logoUrl?: string, applications?: string, boards?: string, programIncrement?: string, codeRepos?: string, adminUsers?: string[], gitRepos?: string, analyticViews?: string, operationViews?: string, infraCost?: boolean, aggregatedDashboards?: string[], teamMembers?: string[], lastVersion?: string, slackTeam?: string, urlAlerts?: string, urlAlertsAuthorization?: string } = {}; errorMessage: string; slackError: string; url: string; icon: { error?: string; success?: boolean } = {}; texts: { loaded?: boolean } = { loaded: false }; categories?: { display?: string, value?: string }[]; marketsStatsDays: number; dashboardList: string[] = []; readonly separatorKeysCodes: number[] = [ENTER, COMMA, SPACE]; // Autocomplete Aggregated Dashboard List dashboardFilteredList: Observable<string[]>; aggregatedDashboardsCtrl = new FormControl(); @ViewChild('aggregatedDashboardsInput') aggregatedDashboardsInput: ElementRef<HTMLInputElement>; @ViewChild('auto') matAutocomplete: MatAutocomplete; readonly MAX_COLUMNS = 5; constructor( private dashboardsService: DashboardsService, private configService: ConfigService, private textsService: TextsService, private slackService: SlackService, private router: Router, private route: ActivatedRoute, private dragulaService: DragulaService ) {} ngOnInit(): void { this.backToDashboard = this.route.snapshot.queryParams.backToDashboard === 'true'; this.categories = this.configService.getConfig('categories'); let id = this.route.snapshot.params['id']; if (id) { this.edit = true; this.dashboardsService.getDashboard(id).subscribe( dashboard => this.setDashboard(dashboard), error => this.errorMessage = this._formatError(error) ); } else { this.setDashboard(new Dashboard()); } this.textsService.getTexts().subscribe( texts => { this.texts = texts; this.texts.loaded = true; }, error => this.errorMessage = this._formatError(error) ); this.dashboardsService.getDashboards().subscribe(dashboards => { this.dashboardList = dashboards.map(dashboard => dashboard.name); }); this.dragulaService.createGroup('columns', { revertOnSpill: true, accepts: function(el, target, source) { if (target.classList.contains('dashboard-cols-template')) { var elements = target.getElementsByClassName('dashboard-cols-module'); var total_size = 0; for (var i = 0; i < elements.length; i++) { total_size += Number(elements[i].getAttribute('size')); if (total_size > 4) { return false; } } } return true; } }); } private setDashboard(dashboard: Dashboard) { if (!dashboard.displayName) { dashboard.displayName = dashboard.name; } this.dashboard = dashboard; this.temp.displayName = this.dashboard.displayName ? this.dashboard.displayName : ''; this.temp.logoUrl = this.dashboard.logoUrl ? this.dashboard.logoUrl : ''; this.temp.boards = this.dashboard.boards ? this.dashboard.boards.join(',') : ''; this.temp.programIncrement = this.dashboard.programIncrement ? this.dashboard.programIncrement : ''; this.temp.applications = this.dashboard.applications ? this.dashboard.applications.join(',') : ''; this.temp.codeRepos = this.dashboard.codeRepos ? this.dashboard.codeRepos.join(',') : ''; this.temp.adminUsers = this.dashboard.adminUsers ? this.dashboard.adminUsers : []; this.temp.gitRepos = this.dashboard.gitRepos ? this.dashboard.gitRepos.join(',') : ''; this.temp.aggregatedDashboards = this.dashboard.aggregatedDashboards ? this.dashboard.aggregatedDashboards : []; this.dashboardFilteredList = this.aggregatedDashboardsCtrl.valueChanges.pipe( startWith(null), map((dashboard: string | null) => this._filter( dashboard, this.dashboardList, this.temp.aggregatedDashboards ) ) ); this.temp.analyticViews = this.dashboard.analyticViews ? this.dashboard.analyticViews.join(',') : ''; this.temp.operationViews = this.dashboard.operationViews ? this.dashboard.operationViews.join(',') : ''; this.temp.infraCost = this.dashboard.infraCost || false; this.temp.teamMembers = this.dashboard.teamMembers ? this.dashboard.teamMembers : []; this.temp.lastVersion = this.dashboard.lastVersion ? this.dashboard.lastVersion : ''; this.temp.slackTeam = this.dashboard.slackTeam ? this.dashboard.slackTeam : ''; if (this.temp.slackTeam !== '') { this.updateSlackChannels(); } this.temp.urlAlerts = this.dashboard.urlAlerts ? this.dashboard.urlAlerts : ''; this.temp.urlAlertsAuthorization = this.dashboard.urlAlertsAuthorization ? this.dashboard.urlAlertsAuthorization : ''; } private mirrorTempValues() { this.dashboard.displayName = this.temp.displayName.length ? this.temp.displayName.trim() : undefined; this.dashboard.logoUrl = this.temp.logoUrl.length ? this.temp.logoUrl.trim() : undefined; this.dashboard.boards = this.temp.boards.length ? this.temp.boards.split(',') : undefined; this.dashboard.programIncrement = this.temp.programIncrement.length ? this.temp.programIncrement : undefined; this.dashboard.applications = this.temp.applications.length ? this.temp.applications.split(',').map(e => e.trim()) : undefined; this.dashboard.codeRepos = this.temp.codeRepos.length ? this.temp.codeRepos.split(',').map(e => e.trim()) : undefined; this.dashboard.adminUsers = this.temp.adminUsers.length ? this.temp.adminUsers.map(e => e.split('@')[0].trim()) : undefined; this.dashboard.gitRepos = this.temp.gitRepos.length ? this.temp.gitRepos.split(',').map(e => e.trim()) : undefined; this.dashboard.aggregatedDashboards = this.temp.aggregatedDashboards.length ? this.temp.aggregatedDashboards : undefined; this.dashboard.analyticViews = this.temp.analyticViews.length ? this.temp.analyticViews.split(',').map(e => e.trim()) : undefined; this.dashboard.operationViews = this.temp.operationViews.length ? this.temp.operationViews.split(',').map(e => e.trim()) : undefined; this.dashboard.infraCost = this.temp.infraCost || false; this.dashboard.teamMembers = this.temp.teamMembers.length ? this.temp.teamMembers.map(e => e.split('@')[0].trim()) : undefined; this.dashboard.lastVersion = this.temp.lastVersion.length ? this.temp.lastVersion.trim() : undefined; this.dashboard.slackTeam = this.temp.slackTeam.length ? this.temp.slackTeam.trim() : undefined; this.dashboard.urlAlerts = this.temp.urlAlerts.length ? this.temp.urlAlerts.trim() : undefined; this.dashboard.urlAlertsAuthorization = this.temp.urlAlertsAuthorization .length ? this.temp.urlAlertsAuthorization.trim() : undefined; if (!this.edit) { this.dashboard.name = kebabCase(this.dashboard.displayName); } } back(): void { if(this.backToDashboard) { document.location.href = this.configService.getConfig('MIRRORGATE_DASHBOARD_URL') + '?board=' + encodeURIComponent(this.dashboard.name); } else { this.router.navigate(['/list']); } } private updateColumns() { if ( this.columnsUpdated || !this.dashboard || !this.dashboard.columns || !document.getElementById('columns') ) { return; } this.columnsUpdated = true; this.dashboard.columns.forEach((column, index) => { let column_element = document.getElementById(`col${index + 1}`); column.forEach(id => { let module_element = document.getElementById(id); column_element.appendChild(module_element); }); }); } private updateSlackChannels(): void { this.slackService.getChannels(this.dashboard).subscribe( channels => this.slackChannels = { keys: Object.keys(channels), values: channels }, error => this.errorMessage = this._formatError(error) ); } private setSlackToken(token: string): void { this.slackError = undefined; this.dashboard.slackToken = token; this.updateSlackChannels(); } onSave(): void { this.mirrorTempValues(); document.getElementById('dynamicDashboardConfiguration') && this.saveColumns(this.dashboard); this.dashboardsService.saveDashboard(this.dashboard, this.edit).subscribe( dashboard => { if (dashboard) { this.dashboard = dashboard; this.back(); } }, error => this.errorMessage = this._formatError(error) ); } private saveColumns(dashboard: Dashboard) { dashboard.columns = []; for (let i = 0; i < this.MAX_COLUMNS; i++) { this.dashboard.columns[i] = []; Array.from(document.getElementById(`col${i + 1}`).children).forEach( el => this.dashboard.columns[i][this.dashboard.columns[i].length] = el.id ); } } signSlack(): void { this.slackService.signSlack( this.dashboard.slackTeam, this.slack.clientId, this.slack.clientSecret ) .then(token => this.setSlackToken(token)) .catch(error => this.slackError = this._formatError(error)); } uploadImage(event) { this.icon = {}; let fileList: FileList = event.target.files; if (fileList.length > 0) { let file: File = fileList[0]; this.dashboardsService.uploadImage(this.dashboard, file).subscribe( () => { this.icon.success = true; this.icon.error = undefined; this.dashboard.logoUrl = '#UPLOADED#'; }, error => { this.icon.success = false; this.icon.error = error.error; } ); } } ngAfterViewChecked() { this.updateColumns(); } addTag(event: MatChipInputEvent, array: string[], control: FormControl, matAutocomplete: MatAutocomplete): void { if (!matAutocomplete || matAutocomplete.isOpen) { this._addTag(event.value, array, event.input, control); } } removeTag(element: any, array: string[]): void { const index = array.indexOf(element); if (index >= 0) { array.splice(index, 1); } } selectedTag(event: MatAutocompleteSelectedEvent, array: string [], input: any, control: FormControl): void { this._addTag(event.option.value, array, input, control) } private _addTag(value: string, array: string[], input: any, control: FormControl): void { if (input) { input.value = ''; } if (control) { control.setValue(null); } if (array.indexOf(value) >= 0) { return; } if ((value || '').trim()) { array.push(value.trim()); } } private _filter(value: string | null, origin: string[], dest: string[]): string[] { let filteredList = origin.filter(e => dest.indexOf(e.trim()) < 0) return value ? filteredList.filter(e => e.indexOf(value.trim()) === 0) : filteredList; } moveTag(event: CdkDragDrop<String[]>, array: string[]) { moveItemInArray(array, event.previousIndex, event.currentIndex); } private _formatError(error: any) { return error.message || error.error && error.error.message || error.error || error } }
the_stack
import { LogLevel, PUSH_ENGINE_FIREBASE, PUSH_ENGINE_MQTT } from './../chat21-core/utils/constants'; import { CustomLogger } from 'src/chat21-core/providers/logger/customLogger'; import { NgModule, ErrorHandler, APP_INITIALIZER } from '@angular/core'; import { RouteReuseStrategy } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { ActivatedRoute } from '@angular/router'; import { TranslateLoader, TranslateModule, TranslatePipe } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { HttpClient, HttpClientModule } from '@angular/common/http'; import { Keyboard } from '@ionic-native/keyboard/ngx'; import { NgxLinkifyjsModule } from 'ngx-linkifyjs'; import { Chooser } from '@ionic-native/chooser/ngx'; import { LoggerModule, NGXLogger, NgxLoggerLevel } from "ngx-logger"; // COMPONENTS import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; // CONFIG import { environment } from '../environments/environment'; import { CHAT_ENGINE_MQTT, CHAT_ENGINE_FIREBASE, UPLOAD_ENGINE_NATIVE } from '../chat21-core/utils/constants'; // SERVICES import { AppConfigProvider } from './services/app-config'; import { EventsService } from './services/events-service'; // ABSTRACT SERVICES import { MessagingAuthService } from 'src/chat21-core/providers/abstract/messagingAuth.service'; import { ConversationHandlerBuilderService } from 'src/chat21-core/providers/abstract/conversation-handler-builder.service'; import { ConversationsHandlerService } from 'src/chat21-core/providers/abstract/conversations-handler.service'; import { ArchivedConversationsHandlerService } from 'src/chat21-core/providers/abstract/archivedconversations-handler.service'; import { ConversationHandlerService } from 'src/chat21-core/providers/abstract/conversation-handler.service'; import { TypingService } from 'src/chat21-core/providers/abstract/typing.service'; import { PresenceService } from 'src/chat21-core/providers/abstract/presence.service'; import { ImageRepoService } from 'src/chat21-core/providers/abstract/image-repo.service'; import { UploadService } from 'src/chat21-core/providers/abstract/upload.service'; import { GroupsHandlerService } from 'src/chat21-core/providers/abstract/groups-handler.service'; import { NotificationsService } from 'src/chat21-core/providers/abstract/notifications.service'; import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service'; // FIREBASE import { FirebaseInitService } from 'src/chat21-core/providers/firebase/firebase-init-service'; import { FirebaseAuthService } from 'src/chat21-core/providers/firebase/firebase-auth-service'; import { FirebaseConversationHandlerBuilderService } from 'src/chat21-core/providers/firebase/firebase-conversation-handler-builder.service'; import { FirebaseConversationsHandler } from 'src/chat21-core/providers/firebase/firebase-conversations-handler'; import { FirebaseArchivedConversationsHandler } from 'src/chat21-core/providers/firebase/firebase-archivedconversations-handler'; import { FirebaseConversationHandler } from 'src/chat21-core/providers/firebase/firebase-conversation-handler'; import { FirebaseTypingService } from 'src/chat21-core/providers/firebase/firebase-typing.service'; import { FirebasePresenceService } from 'src/chat21-core/providers/firebase/firebase-presence.service'; import { FirebaseImageRepoService } from 'src/chat21-core/providers/firebase/firebase-image-repo'; import { FirebaseUploadService } from 'src/chat21-core/providers/firebase/firebase-upload.service'; import { FirebaseGroupsHandler } from 'src/chat21-core/providers/firebase/firebase-groups-handler'; import { FirebaseNotifications } from 'src/chat21-core/providers/firebase/firebase-notifications'; // MQTT import { Chat21Service } from 'src/chat21-core/providers/mqtt/chat-service'; import { MQTTAuthService } from 'src/chat21-core/providers/mqtt/mqtt-auth-service'; import { MQTTConversationHandlerBuilderService } from 'src/chat21-core/providers/mqtt/mqtt-conversation-handler-builder.service'; import { MQTTArchivedConversationsHandler } from 'src/chat21-core/providers/mqtt/mqtt-archivedconversations-handler'; import { MQTTConversationsHandler } from 'src/chat21-core/providers/mqtt/mqtt-conversations-handler'; import { MQTTConversationHandler } from 'src/chat21-core/providers/mqtt/mqtt-conversation-handler'; import { MQTTTypingService } from 'src/chat21-core/providers/mqtt/mqtt-typing.service'; import { MQTTPresenceService } from 'src/chat21-core/providers/mqtt/mqtt-presence.service'; import { MQTTGroupsHandler } from '../chat21-core/providers/mqtt/mqtt-groups-handler'; import { MQTTNotifications } from 'src/chat21-core/providers/mqtt/mqtt-notifications'; //NATIVE import { NativeUploadService } from 'src/chat21-core/providers/native/native-upload-service'; import { NativeImageRepoService } from './../chat21-core/providers/native/native-image-repo'; //LOGGER SERVICES import { LocalSessionStorage } from 'src/chat21-core/providers/localSessionStorage'; //APP_STORAGE import { AppStorageService } from 'src/chat21-core/providers/abstract/app-storage.service'; // PAGES import { ConversationListPageModule } from './pages/conversations-list/conversations-list.module'; import { ConversationDetailPageModule } from './pages/conversation-detail/conversation-detail.module'; import { LoginPageModule } from './pages/authentication/login/login.module'; import { LoaderPreviewPageModule } from './pages/loader-preview/loader-preview.module'; // UTILS import { ScrollbarThemeModule } from './utils/scrollbar-theme.directive'; import { SharedModule } from 'src/app/shared/shared.module'; import { ConversationInfoModule } from 'src/app/components/conversation-info/conversation-info.module'; // Directives import { TooltipModule } from 'ng2-tooltip-directive'; import { LoggerInstance } from 'src/chat21-core/providers/logger/loggerInstance'; import { Network } from '@ionic-native/network/ngx'; import { ConnectionService } from 'ng-connection-service'; // FACTORIES export function createTranslateLoader(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/', '.json'); } export function authenticationFactory(http: HttpClient, appConfig: AppConfigProvider, chat21Service: Chat21Service, appSorage: AppStorageService, network: Network, connectionService:ConnectionService) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { chat21Service.config = config.chat21Config; chat21Service.initChat(); const auth = new MQTTAuthService(http, chat21Service, appSorage); auth.setBaseUrl(appConfig.getConfig().apiUrl) return auth } else { FirebaseInitService.initFirebase(config.firebaseConfig) // console.log('[APP-MOD] FirebaseInitService config ', config) const auth = new FirebaseAuthService(http, network, connectionService); auth.setBaseUrl(config.apiUrl) return auth } } export function conversationsHandlerFactory(chat21Service: Chat21Service, httpClient: HttpClient, appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTConversationsHandler(chat21Service); } else { return new FirebaseConversationsHandler(httpClient, appConfig); } } export function archivedConversationsHandlerFactory(chat21Service: Chat21Service, appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTArchivedConversationsHandler(chat21Service); } else { return new FirebaseArchivedConversationsHandler(); } } export function conversationHandlerBuilderFactory(chat21Service: Chat21Service, appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTConversationHandlerBuilderService(chat21Service); } else { return new FirebaseConversationHandlerBuilderService(); } } export function conversationHandlerFactory(chat21Service: Chat21Service, appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTConversationHandler(chat21Service, false); } else { return new FirebaseConversationHandler(false); } } export function groupsHandlerFactory(http: HttpClient, chat21Service: Chat21Service, appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTGroupsHandler(chat21Service) } else { return new FirebaseGroupsHandler(http, appConfig); } } export function typingFactory(appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTTypingService(); } else { return new FirebaseTypingService(); } } export function presenceFactory(appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.chatEngine === CHAT_ENGINE_MQTT) { return new MQTTPresenceService(); } else { return new FirebasePresenceService(); } } export function imageRepoFactory(appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.uploadEngine === UPLOAD_ENGINE_NATIVE) { const imageService = new NativeImageRepoService() imageService.setImageBaseUrl(config.baseImageUrl) return imageService } else { const imageService = new FirebaseImageRepoService(); FirebaseInitService.initFirebase(config.firebaseConfig) imageService.setImageBaseUrl(config.baseImageUrl) return imageService } } export function uploadFactory(http: HttpClient, appConfig: AppConfigProvider, appStorage: AppStorageService) { const config = appConfig.getConfig() if (config.uploadEngine === UPLOAD_ENGINE_NATIVE) { const nativeUploadService = new NativeUploadService(http, appStorage) nativeUploadService.setBaseUrl(config.apiUrl) return nativeUploadService } else { return new FirebaseUploadService(); } } export function notificationsServiceFactory(appConfig: AppConfigProvider) { const config = appConfig.getConfig() if (config.pushEngine === PUSH_ENGINE_FIREBASE) { return new FirebaseNotifications(); } else if (config.pushEngine === PUSH_ENGINE_MQTT) { return new MQTTNotifications(); } else { return; } } const appInitializerFn = (appConfig: AppConfigProvider, logger: NGXLogger) => { return () => { let customLogger = new CustomLogger(logger) LoggerInstance.setInstance(customLogger) if (environment.remoteConfig) { return appConfig.loadAppConfig(); } }; }; @NgModule({ declarations: [ AppComponent, ], entryComponents: [ ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule, LoginPageModule, ConversationListPageModule, ConversationDetailPageModule, TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: (createTranslateLoader), deps: [HttpClient] } }), LoggerModule.forRoot({ level: NgxLoggerLevel.DEBUG, serverLogLevel: NgxLoggerLevel.ERROR, timestampFormat: 'HH:mm:ss.SSS', enableSourceMaps: false, colorScheme: ['purple', 'yellow', 'gray', 'gray', 'red', 'red', 'red'], serverLoggingUrl: 'https://tiledesk-server-pre.herokuapp.com/logs' }), ScrollbarThemeModule, SharedModule, ConversationInfoModule, NgxLinkifyjsModule.forRoot(), LoaderPreviewPageModule ], bootstrap: [AppComponent], providers: [ AppConfigProvider, // https://juristr.com/blog/2018/01/ng-app-runtime-config/ { provide: APP_INITIALIZER, useFactory: appInitializerFn, multi: true, deps: [AppConfigProvider, NGXLogger] }, { provide: MessagingAuthService, useFactory: authenticationFactory, deps: [HttpClient, AppConfigProvider, Chat21Service, AppStorageService, Network, ConnectionService] }, { provide: PresenceService, useFactory: presenceFactory, deps: [AppConfigProvider] }, { provide: TypingService, useFactory: typingFactory, deps: [AppConfigProvider] }, { provide: UploadService, useFactory: uploadFactory, deps: [HttpClient, AppConfigProvider, AppStorageService] }, { provide: ConversationsHandlerService, useFactory: conversationsHandlerFactory, deps: [Chat21Service, HttpClient, AppConfigProvider] }, { provide: ArchivedConversationsHandlerService, useFactory: archivedConversationsHandlerFactory, deps: [Chat21Service, AppConfigProvider] }, { provide: ConversationHandlerService, useFactory: conversationHandlerFactory, deps: [Chat21Service, AppConfigProvider] }, { provide: GroupsHandlerService, useFactory: groupsHandlerFactory, deps: [HttpClient, Chat21Service, AppConfigProvider] }, { provide: ImageRepoService, useFactory: imageRepoFactory, deps: [AppConfigProvider] }, { provide: ConversationHandlerBuilderService, useFactory: conversationHandlerBuilderFactory, deps: [Chat21Service, AppConfigProvider] }, { provide: NotificationsService, useFactory: notificationsServiceFactory, deps: [AppConfigProvider] }, { provide: AppStorageService, useClass: LocalSessionStorage }, StatusBar, SplashScreen, Keyboard, Network, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, EventsService, Chooser, Chat21Service, ] }) export class AppModule { }
the_stack
import { RequestParams, Role, Roles, UserPayload, UserRequest, UserSignupRequest } from '@compito/api-interfaces'; import { BadRequestException, ForbiddenException, HttpException, Injectable, InternalServerErrorException, NotFoundException, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Prisma } from '@prisma/client'; import { AppMetadata, AuthenticationClient, ManagementClient, SignUpUserData, UserMetadata } from 'auth0'; import { compareSync, hashSync } from 'bcrypt'; import * as cuid from 'cuid'; import { JwtPayload, verify } from 'jsonwebtoken'; import { kebabCase } from 'voca'; import { AuthService } from '../auth/auth.service'; import { CompitoLoggerService } from '../core/utils/logger.service'; import { getUserDetails } from '../core/utils/payload.util'; import { parseQuery } from '../core/utils/query-parse.util'; import { PrismaService } from '../prisma.service'; import { USER_BASIC_DETAILS } from '../task/task.config'; @Injectable() export class UserService { private logger = this.compitoLogger.getLogger('USER'); managementClient: ManagementClient<AppMetadata, UserMetadata>; authClient: AuthenticationClient; constructor( private config: ConfigService, private prisma: PrismaService, private auth: AuthService, private compitoLogger: CompitoLoggerService, ) { this.managementClient = this.auth.management; this.authClient = this.auth.auth; } async getUserDetails(sessionToken: string) { try { const secret = this.config.get('SESSION_TOKEN_SECRET'); const token: JwtPayload = verify(sessionToken, secret) as any; if (!token) { this.logger.error('getUserDetails', 'Invalid session token'); throw new ForbiddenException('Session not valid. Please login again!'); } const [user, userInvite] = await this.prisma.$transaction([ this.prisma.user.findUnique({ where: { id: token.userId, }, select: { email: true, orgs: { select: { id: true, name: true, }, }, projects: { select: { id: true, name: true, orgId: true, }, }, roles: { select: { orgId: true, role: { select: { name: true, label: true, permissions: true, }, }, }, }, }, }), this.prisma.userInvite.findMany({ where: { email: token.email, }, select: { id: true, }, }), ]); if (!user) { this.logger.error('getUserDetails', 'User not found'); throw new NotFoundException('User not found'); } const { orgs = [], projects = [], roles = [] } = user; const projectIds = projects.map(({ id }) => id); const inviteIds = userInvite.map(({ id }) => id); const rolesData = roles.reduce((acc, { role, orgId }) => { return { ...acc, [orgId]: role, }; }, {}); if (token.org) { if (orgs.findIndex(({ id }) => id === token.org) < 0) { this.logger.error('getUserDetails', 'User is not part of the selected org'); throw new ForbiddenException('No access to org'); } const projectsPartOfOrg = projects.filter((project) => project?.orgId === token.org).map(({ id }) => id); const org = orgs.find(({ id }) => id === token.org); return { org, projects: projectsPartOfOrg, role: rolesData[token.org], }; } return { orgs, projects: projectIds, invites: inviteIds, roles: rolesData, partOfMultipleOrgs: orgs.length > 1, pendingInvites: inviteIds.length > 0, }; } catch (error) { if (error instanceof HttpException) { throw error; } this.logger.error('getUserDetails', 'Failed to fetch user details'); throw new InternalServerErrorException('Failed to fetch user details'); } } async getOnboardingDetails(sessionToken: string) { try { const secret = this.config.get('SESSION_TOKEN_SECRET'); if (!secret) { throw new Error('Please provide the Session Token Secret'); } const token: JwtPayload = verify(sessionToken, secret) as JwtPayload; if (!token) { throw new ForbiddenException('Session not valid. Please login again!'); } const [user, userInvite] = await this.prisma.$transaction([ this.prisma.user.findUnique({ where: { id: token.userId, }, select: { ...USER_BASIC_DETAILS, orgs: { select: { id: true, name: true, createdBy: { select: { firstName: true, lastName: true, image: true, email: true, }, }, updatedAt: true, }, }, roles: { select: { orgId: true, role: { select: { name: true, permissions: true, }, }, }, }, }, }), this.prisma.userInvite.findMany({ where: { email: token.email, }, select: { id: true, email: true, role: { select: { label: true, }, }, org: { select: { id: true, name: true, }, }, invitedBy: { select: USER_BASIC_DETAILS, }, createdAt: true, }, }), ]); if (!user) { throw new NotFoundException('User not found'); } const { orgs = [], ...rest } = user; return { ...rest, orgs, invites: userInvite, }; } catch (error) { if (error?.name === 'TokenExpiredError') { throw new BadRequestException('Session expired, Please login again!'); } throw new InternalServerErrorException('Failed to onboard details for user'); } } async getUserOrgsAndInvites(userId: string, sessionToken: string) { try { const secret = this.config.get('SESSION_TOKEN_SECRET'); if (!secret) { throw new Error('Please provide the Session Token Secret'); } const token = verify(sessionToken, secret); if (!token) { throw new ForbiddenException('Session not valid. Please login again!'); } const user = await this.prisma.user.findUnique({ where: { id: userId, }, select: { orgs: { select: { id: true, name: true, }, }, }, }); if (!user) { throw new NotFoundException('User not found'); } return user; } catch (error) { throw new InternalServerErrorException('Failed to fetch user orgs'); } } async getUsersInvites(user: UserPayload) { try { const { email } = getUserDetails(user); return await this.prisma.userInvite.findMany({ where: { email, }, select: { id: true, email: true, role: { select: { name: true, label: true, id: true, }, }, invitedBy: { select: USER_BASIC_DETAILS, }, org: { select: { name: true, }, }, }, }); } catch (error) { this.logger.error('getUserInvites', 'Failed to fetch user invites', error); throw new InternalServerErrorException('Failed to get invites'); } } async signup(data: UserSignupRequest) { const connection = this.config.get('AUTH0_DB'); if (!connection) { throw new Error('Please provide the auth DB name'); } let role: Role; try { role = await this.prisma.role.findFirst({ where: { name: 'super-admin', }, rejectOnNotFound: true, }); } catch (error) { this.logger.error('signup', 'Roles not configured', error); throw new InternalServerErrorException('Failed to create user!'); } const { email, firstName, lastName, org, password } = data; const createUserAndOrg = async () => { try { const userId = cuid(); const orgId = cuid(); const [, user] = await this.prisma.$transaction([ this.prisma.user.create({ data: { id: userId, firstName, lastName, email, password: hashSync(password, 10), verified: false, blocked: false, orgs: { create: { id: orgId, name: org, slug: `${kebabCase(org)}-${cuid()}`, createdBy: { connect: { id: userId }, }, }, }, }, select: { id: true, }, }), this.prisma.user.update({ where: { id: userId, }, data: { roles: { create: { orgId: orgId, roleId: role.id, }, }, }, select: { id: true, orgs: { select: { id: true, }, }, roles: { select: { id: true, orgId: true, role: { select: { name: true, id: true, }, }, }, }, }, }), ]); return { user, orgId: user.orgs[0].id }; } catch (error) { this.logger.error('signup', 'Failed to create user and in DB', error); throw new InternalServerErrorException('Failed to create user'); } }; const deleteUserFromLocal = async (userId: string) => { try { await this.prisma.user.delete({ where: { id: userId, }, }); } catch (error) { this.logger.error('signup', 'Failed to remove user from DB on failure', error); throw new InternalServerErrorException('Something went wrong'); } }; const createUserInAuth0 = async ( userId: string, orgId: string, rolesData: Record<string, { name: string; id: string }>, ) => { try { const auth0UserData: SignUpUserData = { family_name: lastName, given_name: firstName, password, email, connection, user_metadata: { server_signup: 'true', orgs: JSON.stringify([orgId]), userId: userId, roles: JSON.stringify(rolesData), }, }; return await this.authClient.database.signUp(auth0UserData); } catch (error) { await deleteUserFromLocal(userId); this.logger.error('signup', 'Failed to create user in Auth0', error); throw new InternalServerErrorException('Failed to signup'); } }; const userSaved = await createUserAndOrg(); const roles = userSaved.user.roles.reduce((acc, curr) => { return { ...acc, [curr.orgId]: curr.role, }; }, {}); return createUserInAuth0(userSaved.user.id, userSaved.orgId, roles); } async findAll(query: RequestParams, user: UserPayload) { const { org, role, userId } = getUserDetails(user); let whereCondition: Prisma.UserWhereInput = {}; switch (role.name) { /** * 1. Users of the specified Org that are part of projects he/she is a member of */ case 'user': { let projects = []; try { const userData = await this.prisma.user.findUnique({ where: { id: userId, }, select: { projects: { select: { id: true, }, }, }, }); projects = userData.projects.map(({ id }) => id); } catch (error) { this.logger.error('findAll', 'Failed to fetch user details', error); throw new InternalServerErrorException('Failed to fetch users'); } whereCondition = { ...whereCondition, AND: [ { orgs: { some: { id: org.id, }, }, }, { projects: { some: { id: { in: projects, }, }, }, }, ], }; } break; /** * Super admin, Org Admin and Project Admin can see all the users of his org */ default: whereCondition = { ...whereCondition, orgs: { some: { id: org.id, }, }, }; break; } const { skip, limit } = parseQuery(query); try { const count$ = this.prisma.user.count({ where: whereCondition }); const userSelectFields = { ...USER_BASIC_DETAILS, createdAt: true, updatedAt: true, roles: { where: { orgId: org.id, }, select: { role: { select: { id: true, label: true, name: true, }, }, }, }, orgs: { select: { id: true, name: true } }, }; const orgs$ = this.prisma.user.findMany({ where: whereCondition, skip, take: limit, select: userSelectFields, }); const [payload, count] = await Promise.all([orgs$, count$]); return { payload, meta: { count, }, }; } catch (error) { this.logger.error('fetchAll', 'Failed to fetch users', error); throw new InternalServerErrorException(); } } async find(id: string, user: UserPayload) { const { org, role, projects } = getUserDetails(user); let whereCondition: Prisma.UserWhereInput = { id, }; switch (role.name) { /** * 1. Users of the specified Org that are part of projects he/she is a member of */ case 'user': { whereCondition = { ...whereCondition, AND: [ { orgs: { some: { id: org.id, }, }, }, { projects: { some: { id: { in: projects ?? [], }, }, }, }, ], }; } break; /** * Super admin, Org Admin and Project Admin can see all the users of his org */ default: whereCondition = { ...whereCondition, orgs: { some: { id: org.id, }, }, }; break; } try { const userData = await this.prisma.user.findFirst({ where: whereCondition, select: { ...USER_BASIC_DETAILS, createdAt: true, updatedAt: true, orgs: { select: { id: true, name: true } } }, }); if (!userData) { this.logger.error('findOne', 'User not found'); throw new NotFoundException('User not found'); } return userData; } catch (error) { this.logger.error('findOne', 'Failed to fetch user', error); throw new InternalServerErrorException(); } } async updateUser(id: string, data: Partial<UserRequest>, user: UserPayload) { const { userId } = getUserDetails(user); if (id !== userId) { this.logger.error('update', 'Cannot update other user data'); throw new ForbiddenException('Not enough permissions to update the user details'); } const { password, newPassword, orgId, email, roleId, ...rest } = data; let dataToUpdate: Prisma.UserUpdateInput = { ...rest }; if (password !== null && newPassword !== null) { if (password === newPassword) { this.logger.error('update', 'New password cannot be the same as current password'); throw new BadRequestException('New password cannot be the same as your current password!'); } try { const userData = await this.prisma.user.findUnique({ where: { id, }, rejectOnNotFound: true, select: { email: true, password: true, }, }); const passwordMatched = compareSync(password, userData.password); if (!passwordMatched) { this.logger.error('update', `Current password doesn't match`); throw new ForbiddenException(`Current password doesn't match`); } const passwordUpdatedInAuth0 = this.updateUserPasswordInAuth0(userData.email, newPassword); if (passwordUpdatedInAuth0 instanceof Error) { throw passwordUpdatedInAuth0; } dataToUpdate = { ...dataToUpdate, password: hashSync(newPassword, 10), }; } catch (error) { if (error?.name === 'NotFoundError') { this.logger.error('update', 'User not found', error); throw new NotFoundException('User not found'); } this.logger.error('update', 'Failed in find user and validate password stage', error); throw new InternalServerErrorException('Something went wrong!'); } } try { return await this.prisma.user.update({ where: { id, }, data: dataToUpdate, select: USER_BASIC_DETAILS, }); } catch (error) { this.logger.error('findOne', 'Failed to fetch user', error); throw new InternalServerErrorException('Failed to update user'); } } async updateUserRole(id: string, roleId: string, user: UserPayload) { const { role, org } = getUserDetails(user); let userData; switch (role.name as Roles) { case 'super-admin': case 'org-admin': case 'admin': { try { userData = await this.prisma.user.findUnique({ where: { id }, select: { orgs: { select: { id: true, }, }, roles: { where: { orgId: org.id, }, }, }, rejectOnNotFound: true, }); if (userData.orgs.findIndex((item) => item?.id === org.id) < 0) { throw new ForbiddenException('Not enough permissions to update the role'); } if (userData.roles?.length === 0) { this.logger.error('updateRole', `User doesn't have proper roles configured`); throw new InternalServerErrorException('Something went wrong.'); } } catch (error) { if (error?.name === 'NotFoundError') { this.logger.error('updateRole', 'User not found', error); throw new NotFoundException('Invite not found'); } throw new InternalServerErrorException(); } break; } default: this.logger.error('updateRole', `User doesn't have authority to update user role`); throw new ForbiddenException('Not enough permissions to update the user details'); } try { const userSelectFields = { ...USER_BASIC_DETAILS, createdAt: true, updatedAt: true, roles: { where: { orgId: org.id, }, select: { role: { select: { id: true, label: true, }, }, }, }, orgs: { select: { id: true, name: true } }, }; return await this.prisma.user.update({ where: { id, }, data: { roles: { update: { where: { id: userData.roles[0].id, }, data: { roleId: roleId, }, }, }, }, select: userSelectFields, }); } catch (error) { this.logger.error('updateRole', 'Failed to update role', error); throw new InternalServerErrorException('Failed to update role'); } } async deleteUser(id: string, user: UserPayload) { const { role, org } = getUserDetails(user); let userData; try { userData = await this.prisma.user.findUnique({ where: { id }, select: { orgs: { select: { id: true, }, }, roles: { where: { orgId: org.id, }, select: { role: { select: { name: true, }, }, }, }, }, rejectOnNotFound: true, }); } catch (error) { if (error?.name === 'NotFoundError') { this.logger.error('delete', 'User not found', error); throw new NotFoundException(); } this.logger.error('delete', 'Failed to delete user', error); throw new InternalServerErrorException('Failed to remove user'); } switch (role.name) { case 'super-admin': { try { return await this.prisma.user.update({ where: { id, }, data: { orgs: { disconnect: { id: org.id, }, }, }, select: USER_BASIC_DETAILS, }); } catch (error) { this.logger.error('delete', 'Failed to remove user', error); throw new InternalServerErrorException('Failed to remove user'); } } case 'admin': { try { const userInAdminOrg = userData.orgs.findIndex(({ id: orgId }) => org === orgId) >= 0; if (!userInAdminOrg) { this.logger.error('delete', 'Admin user is not part of the org, cannot remove user'); throw new ForbiddenException('Not enough permissions'); } return await this.prisma.user.update({ where: { id, }, data: { orgs: { disconnect: { id: org.id, }, }, }, select: USER_BASIC_DETAILS, }); } catch (error) { this.logger.error('delete', 'Failed to remove user', error); throw new InternalServerErrorException('Failed to remove user'); } } default: this.logger.error('delete', 'User with normal role cannot remove user'); throw new ForbiddenException('Not enough permissions'); } } private updateUserPasswordInAuth0 = async (email: string, password: string) => { try { const user = await this.managementClient.getUsersByEmail(email); const connection = this.config.get('AUTH0_DB'); if (user?.length > 0) { const userId = user[0].user_id; await this.managementClient.updateUser( { id: userId, }, { password, connection, }, ); return true; } else { this.logger.error('updatePassword', 'User not found in Auth0 database'); return new BadRequestException('User not found'); } } catch (error) { this.logger.error('updatePassword', 'Something went wrong while updating password in Auth0', error); return new InternalServerErrorException(); } }; }
the_stack
"use strict"; import * as React from "react"; import * as ReactDOM from "react-dom"; import LobbyItem from "./components"; import RoleSelection from "./roleSelection"; declare let SimpleBar: any; type Message = Array<{ text: string; color: string; backgroundColor: string }>; enum States { NOTASSIGNEDGAME = "NOT ASSIGNED GAME", INGAMEWAITING = "IN GAME WAITING", INGAMEPLAYING = "IN GAME PLAYING", GAMEENDED = "GAME ENDED", } class LeaveGameButton { public action: () => void = () => { }; constructor() { } setinPlayClick() { $("#leaveGame").off("click"); this.action = function () { $("#leaveGameModal").modal("show"); }; $("#leaveGame").click(this.action); } setNotInPlayClick() { $("#leaveGame").off("click"); this.action = function () { console.log(user.inGame); if (!user.inGame) { transitionFromGameToLobby(); user.socket.emit("leaveGame"); user.restart(); } }; $("#leaveGame").click(this.action); } } let leaveGameButton = new LeaveGameButton(); export class User { private _state: States = States.NOTASSIGNEDGAME; public socket = io(); public now = 0; public time = 0; public warn = -1; public gameClicked = false; public registered = false; public canVote = false; public username: string = ""; constructor() { this.socket = io(); this.now = 0; this.time = 0; this.warn = -1; this.gameClicked = false; this.registered = false; this.canVote = false; setInterval(this.updateTime.bind(this), 1000); } get inGame() { return this.state == States.INGAMEPLAYING; } isState(state: States) { return this.state == state; } set state(inputState) { if (inputState == States.INGAMEPLAYING) { leaveGameButton.setinPlayClick(); } this._state = inputState; } get state() { return this._state; } restart() { transitionFromGameToLobby(); this.state = States.NOTASSIGNEDGAME; this.registered = false; this.now = 0; this.time = 0; this.warn = -1; $("#playerNames").empty(); $("#playerNames").append('<li class="gameli">Players:</li>'); $("#roleNames").empty(); $("#gameClock").text("Time: 00:00"); $("#gameClock").css("color", "#cecece"); $("#roleNames").append('<li class="gameli">Roles:</li>'); $("#chatbox").empty(); $("#leaveGame").off("click"); leaveGameButton.setNotInPlayClick(); //clear the gallows gallows.reset(); } //convert number of seconds into minute:second format convertTime(duration: number) { let seconds = Math.floor((duration / 1000) % 60); let minutes = Math.floor((duration / (1000 * 60)) % 60); let minuteString = minutes < 10 ? `0${minutes}` : `${minutes}`; let secondString = seconds < 10 ? `0${seconds}` : `${seconds}`; return minuteString + ":" + secondString; } updateTime() { if (this.time > 0) { this.time -= Date.now() - user.now; this.now = Date.now(); if (this.time < 0) { this.time = 0; $("#gameClock").css("color", "#cecece"); this.warn = -1; } $("#gameClock").text("Time: " + this.convertTime(user.time)); if (this.time <= this.warn && this.time >= 0) { $("#gameClock").css("color", "#ff1b1b"); } } else { $("#gameClock").text("Time: " + this.convertTime(0)); } } register() { this.registered = true; } } export const user = new User(); //ReactDOM.render(<RoleSelection user={user} />, $("#roleSelection")[0]); function lobbyItemClick(item: HTMLElement) { user.gameClicked = true; if (user.isState(States.NOTASSIGNEDGAME)) { transitionFromLobbyToGame($(item).attr("name")); } else { transitionFromLobbyToGame(); } location.hash = "3"; if ($(item).attr("inPlay") == "false") { if (user.isState(States.NOTASSIGNEDGAME)) { $("#chatbox").empty(); $("#playerNames").empty(); removeAllPlayers(); $("#playerNames").append("<li class='gameli'>Players:</li>"); let usernameList = $( ".lobbyItem[uid=" + $(item).attr("uid") + "] .username", ); for (let i = 0; i < usernameList.length; i++) { appendMessage( [ { text: $(usernameList[i]).text(), color: $(usernameList[i]).css("color"), }, ], "#playerNames", ); addPlayer($(usernameList[i]).text()); } user.socket.emit("gameClick", $(item).attr("uid")); user.state = States.INGAMEWAITING; } } else { if (user.isState(States.NOTASSIGNEDGAME)) { $("#playerNames").empty(); removeAllPlayers(); $("#playerNames").append("<li class='gameli'>Players:</li>"); let usernameList = $( ".lobbyItem[uid=" + $(item).attr("uid") + "] .username", ); for (let i = 0; i < usernameList.length; i++) { appendMessage( [ { text: $(usernameList[i]).text(), color: $(usernameList[i]).css("color"), }, ], "#playerNames", ); addPlayer($(usernameList[i]).text()); } appendMessage( [ { text: "This game has already started, please join a different one.", }, ], "#chatbox", "#950d0d", ); } } } user.socket.on("canVote", () => { user.canVote = true; }); user.socket.on("cannotVote", () => { user.canVote = false; }); let notificationSound: HTMLAudioElement = new Audio( "assets/sounds/162464__kastenfrosch__message.mp3", ); notificationSound.volume = 0.2; let newPlayerSound: HTMLAudioElement = new Audio( "assets/sounds/162476__kastenfrosch__gotitem.mp3", ); newPlayerSound.volume = 0.1; let lostPlayerSound: HTMLAudioElement = new Audio( "assets/sounds/162465__kastenfrosch__lostitem.mp3", ); lostPlayerSound.volume = 0.1; //BODGE (needs neatening up): //Safari only permits audio playback if the user has previously interacted with the UI //Even if this code were to run on other browsers, it should have no effect $(document).on("click", function () { //mute and play all the sound effects once notificationSound.muted = true; newPlayerSound.muted = true; lostPlayerSound.muted = true; notificationSound.play(); newPlayerSound.play(); lostPlayerSound.play(); //unmute each sound effect once they have finished playing once notificationSound.onended = function () { if (notificationSound) { notificationSound.muted = false; notificationSound.onended = () => { }; } }; newPlayerSound.onended = function () { newPlayerSound.muted = false; newPlayerSound.onended = () => { }; }; lostPlayerSound.onended = function () { lostPlayerSound.muted = false; lostPlayerSound.onended = () => { }; }; $(document).off("click"); }); function isClientScrolledDown() { return ( Math.abs( $("#inner")[0].scrollTop + $("#inner")[0].clientHeight - $("#inner")[0].scrollHeight, ) <= 10 ); } function addPlayerToLobbyList(username: string) { $("#lobbyList").append("<li>" + username + "</li>"); } function removePlayerFromLobbyList(username: string) { $("#lobbyList li") .filter(function () { return $(this).text() === username; }) .remove(); } function appendMessage( msg: Array<{ text: string; color?: string; backgroundColor?: string; italic?: boolean; }>, target: string, backgroundColor?: string, ) { //test if client scrolled down let scrollDown = isClientScrolledDown(); //we add a span within an li let newMessageLi = $("<li class='gameli'></li>"); for (let i = 0; i < msg.length; i++) { let messageSpan = $("<span></span>"); $(messageSpan).text(msg[i].text); let textColor = "#cecece"; if (msg[i].color) { textColor = msg[i].color as string; } $(messageSpan).css("color", textColor); if (msg[i].backgroundColor) { $(messageSpan).css("background-color", msg[i].backgroundColor as string); } if (msg[i].italic == true) { $(messageSpan).css("font-style", "italic"); } $(newMessageLi).append($(messageSpan)); } if (backgroundColor) { $(newMessageLi).css("background-color", backgroundColor); } $(target).append(newMessageLi); //only scroll down if the client was scrolled down before the message arrived if (scrollDown && target == "#chatbox") { $("#inner")[0].scrollTop = $("#inner")[0].scrollHeight - $("#inner")[0].clientHeight; } } function removeMessage(msg: string, target: string) { $(target + " li") .filter(function () { return $(this).text() === msg; }) .remove(); } function lineThroughPlayer(msg: string, color: string) { $("#playerNames li span") .filter(function () { return $(this).text() === msg; }) .css("color", color); $("#playerNames li span") .filter(function () { return $(this).text() === msg; }) .css("text-decoration", "line-through"); } let lobbyChatListContainerSimpleBar = new SimpleBar( $("#lobbyChatListContainer")[0], ); $(function () { //if navigator is not online, display a message warning that the user has disconnected if ($("#lobbyItemList .lobbyItem").length == 0) { ReactDOM.render( <p id="emptyLobbyItemPrompt" style={{ textAlign: "center", marginTop: "20px", fontStyle: "italic", fontSize: "1.1em", }} > Create a new game to play </p>, $("#lobbyItemList")[0], ); } $("#registerBox").focus(); leaveGameButton.setNotInPlayClick(); $("#lobbyChatForm").submit(() => { console.log("active"); if ($("#lobbyChatInput").val() != "") { user.socket.emit("lobbyMessage", $("#lobbyChatInput").val()); $("#lobbyChatInput").val(""); } return false; }); user.socket.on("reloadClient", function () { console.log("client receipt"); if (document.hidden) { location.reload(); } }); $("#leaveGameForm").submit(function () { user.socket.emit("leaveGame"); }); user.socket.on("transitionToLobby", function () { transitionFromLandingToLobby(); }); user.socket.on("transitionToGame", function ( name: string, uid: string, inPlay: boolean, ) { transitionFromLandingToGame(name, uid, inPlay); }); user.socket.on("message", function (message: Message, textColor: string) { appendMessage(message, "#chatbox", textColor); }); user.socket.on("headerTextMessage", function (standardArray: Message) { let out = []; for (let i = 0; i < standardArray.length; i++) { out.push( new StandardMainText(standardArray[i].text, standardArray[i].color), ); } if (mainText) { mainText.push(out); } }); user.socket.on("restart", function () { user.restart(); }); user.socket.on("registered", function (username: string) { transitionFromLandingToLobby(); user.register(); user.username = username; leaveGameButton.setNotInPlayClick(); }); user.socket.on("clear", function () { $("ul").empty(); }); user.socket.on("setTitle", function (title: string) { $(document).attr("title", title); }); user.socket.on("notify", function () { notificationSound.play(); }); user.socket.on("removeGameFromLobby", function (uid: string) { $("#container .lobbyItem[uid=" + uid + "]").remove(); if ($("#lobbyItemList .lobbyItem").length == 0) { ReactDOM.render( <p id="emptyLobbyItemPrompt" style={{ textAlign: "center", marginTop: "20px", fontStyle: "italic", fontSize: "1.1em", }} > Create a new game to play </p>, $("#lobbyItemList")[0], ); } }); user.socket.on("addNewGameToLobby", function ( name: string, type: string, uid: string, ) { $("#emptyLobbyItemPrompt").css("display", "none"); let div = document.createElement("div"); div.className = "lobbyItemReactContainer"; $("#container .simplebar-content #lobbyItemList").prepend(div); ReactDOM.render( <LobbyItem name={name} type={type} uid={uid} ranked={false} />, $("#container .simplebar-content .lobbyItemReactContainer:first")[0], ); $(".lobbyItem").off("click"); $(".lobbyItem").click(function () { lobbyItemClick(this); }); }); user.socket.on("newGame", function () { user.state = States.INGAMEPLAYING; }); user.socket.on("endChat", function () { console.log("active"); user.state = States.GAMEENDED; leaveGameButton.setNotInPlayClick(); }); user.socket.on("sound", function (sound: string) { if (sound == "NEWGAME") { notificationSound.play(); } else if (sound == "NEWPLAYER") { newPlayerSound.play(); } else if (sound == "LOSTPLAYER") { lostPlayerSound.play(); } }); user.socket.on("registrationError", function (error: string) { $( '<p style="color:red;font-size:18px;margin-top:15px;">Invalid: ' + error + "</p>", ) .hide() .appendTo("#errors") .fadeIn(100); }); $("document").resize(function () { }); user.socket.on("lobbyMessage", function (msg: Message) { appendMessage(msg, "#lobbyChatList"); if ( Math.abs( $("#lobbyChatListContainer")[0].scrollTop + $("#lobbyChatListContainer")[0].clientHeight - $("#lobbyChatListContainer")[0].scrollHeight, ) <= 100 ) { $("#lobbyChatListContainer")[0].scrollTop = $( "#lobbyChatListContainer", )[0].scrollHeight; } }); //adds text to the username + role line of the client user.socket.on("ownInfoSend", (name: string, role: string, color: string) => { $("#nameAndRole").html( `<span>${name} -</span><span style="color:${color};"> ${role}</span>`, ); }); user.socket.on("rightMessage", function (msg: Message) { appendMessage(msg, "#playerNames"); addPlayer(msg[0].text); }); user.socket.on("leftMessage", function (msg: Message) { appendMessage(msg, "#roleNames"); }); user.socket.on("removeRight", function (msg: string) { removeMessage(msg, "#playerNames"); removeMessage(" " + msg, "#playerNames"); console.log("active: " + msg); removePlayer(msg); removePlayer(" " + msg); }); user.socket.on("removeLeft", function (msg: string) { removeMessage(msg, "#roleNames"); }); user.socket.on("lineThroughPlayer", function (msg: string, color: string) { lineThroughPlayer(msg, color); lineThroughPlayer(" " + msg, color); }); user.socket.on("markAsDead", function (msg: string) { markAsDead(msg); markAsDead(" " + msg); lineThroughPlayer(msg, "red"); lineThroughPlayer(" " + msg, "red"); }); window.addEventListener("offline", function (e) { console.log("disconnected - show player warning"); $("#offlineWarning").css("display", "block"); }); user.socket.on("setTime", function (time: number, warn: number) { if (time > 0) { $("#gameClock").text("Time: " + user.convertTime(time)); } $("#gameClock").css("color", "#cecece"); user.now = Date.now(); user.time = time; user.warn = warn; }); $(".lobbyItem").off("click"); $(".lobbyItem").click(function () { lobbyItemClick(this); }); user.socket.on("getAllRolesForSelection", function ( rolesArray: Array<{ color: string; name: string; }>, ) { console.log(rolesArray); for (let roles of rolesArray) { $("#allRolesForGameType").append( '<button class="ui ' + roles.color + ' button">' + roles.name + "</button>", ); } }); user.socket.on("updateGame", function ( name: string, playerNames: Array<string>, playerColors: Array<string>, number: number, inPlay: boolean, ) { if (inPlay) { $("#container div[uid=" + number.toString() + "] p:first span:last").html( "IN PLAY", ); $("#container div[uid=" + number.toString() + "]").attr("inPlay", "true"); } else { $("#container div[uid=" + number.toString() + "] p:first span:last").html( "OPEN", ); $("#container div[uid=" + number.toString() + "]").attr( "inPlay", "false", ); } let div = $( "#container div[uid=" + number.toString() + "] p:last span:first", ); div.empty(); for (let i = 0; i < playerNames.length; i++) { if (i == 0) { div.append( '<span class="username" style="color:' + playerColors[i] + '">' + playerNames[i], ); } else { div.append("<span>,"); div.append( '<span class="username" style="color:' + playerColors[i] + '"> ' + playerNames[i], ); } } }); user.socket.on("addPlayerToLobbyList", function (username: string) { addPlayerToLobbyList(username); }); user.socket.on("removePlayerFromLobbyList", function (username: string) { removePlayerFromLobbyList(username); }); //removes player from game list user.socket.on("removePlayerFromGameList", function ( name: string, game: string, ) { let spanList = $("#container div[uid=" + game + "] p:last span:first span"); for (let i = 0; i < spanList.length; i++) { if ( $(spanList[i]).text() == name || $(spanList[i]).text() == " " + name ) { //remove the separating comma if it exists if (i != spanList.length - 1) { $(spanList[i + 1]).remove(); } if (i == spanList.length - 1 && i > 0) { $(spanList[i - 1]).remove(); } $(spanList[i]).remove(); break; } } }); user.socket.on("addPlayerToGameList", function ( name: string, color: string, game: string, ) { let div = $("#container div[uid=" + game + "] p:last span:first"); let spanList = $("#container div[uid=" + game + "] p:last .username"); if (spanList.length == 0) { div.append('<span class="username" style="color:' + color + '">' + name); } else { div.append("<span>,"); div.append('<span class="username" style="color:' + color + '"> ' + name); } }); user.socket.on("markGameStatusInLobby", function ( game: string, status: string, ) { if (status == "OPEN") { $("#container div[uid=" + game + "]").attr("inplay", "false"); } else if (status == "IN PLAY") { $("#container div[uid=" + game + "]").attr("inplay", "true"); } $("#container div[uid=" + game + "] p:first span:last").html(status); if (status == "OPEN") { //clear out the player list as the game has ended $("#container div[uid=" + game + "] p:last span:first").empty(); } }); window.onhashchange = function () { if (location.hash == "") { location.hash = "2"; } else if (location.hash == "#3" && user.gameClicked) { transitionFromLobbyToGame(); } else if (location.hash == "#2") { if (!user.isState(States.INGAMEWAITING)) { user.restart(); } else { transitionFromGameToLobby(); } } }; $("#registerForm").submit(function () { if ($("#registerBox").val() != "") { $("#errors").empty(); user.socket.emit("message", $("#registerBox").val()); $("#registerBox").val(""); } }); $("#viewLobby").click(() => { transitionFromGameToLobby(); }); }); function transitionFromLandingToLobby() { $("#landingPage").fadeOut(200, function () { $("#lobbyContainer").fadeIn(200); location.hash = "#2"; //scroll down the lobby chat $("#lobbyChatListContainer")[0].scrollTop = $( "#lobbyChatListContainer", )[0].scrollHeight; }); } //only use when the player has created a new tab //and should connect to the game they were previously in function transitionFromLandingToGame( gameName: string, uid: string, inGame: boolean, ) { console.log(inGame); $("#landingPage").fadeOut("fast", function () { $("#playerNames").empty(); $("#playerNames").append("<li class='gameli'>Players:</li>"); let usernameList = $(".lobbyItem[uid=" + uid + "] .username"); for (let i = 0; i < usernameList.length; i++) { appendMessage( [ { text: $(usernameList[i]).text(), color: $(usernameList[i]).css("color"), }, ], "#playerNames", ); addPlayer($(usernameList[i]).text()); } user.gameClicked = true; if (inGame) { user.state = States.INGAMEPLAYING; user.register(); $("#topLevel").fadeIn(200); if (gameName) { $("#mainGameName").text(gameName); resize(); } //scroll down the game chatbox $("#inner")[0].scrollTop = $("#inner")[0].scrollHeight - $("#inner")[0].clientHeight; $("#topLevel")[0].scrollTop = 0; $("#msg").focus(); } else { user.state = States.INGAMEWAITING; user.register(); $("#topLevel").fadeIn(200); if (gameName) { $("#mainGameName").text(gameName); resize(); } //scroll down the game chatbox $("#inner")[0].scrollTop = $("#inner")[0].scrollHeight - $("#inner")[0].clientHeight; $("#topLevel")[0].scrollTop = 0; $("#msg").focus(); } }); } function transitionFromLobbyToGame(gameName?: string) { $("#landingPage").fadeOut("fast", function () { $("#lobbyContainer").fadeOut(200, function () { $("#topLevel").fadeIn(200); resize(); }); if (gameName) { $("#mainGameName").text(gameName); } $("#topLevel")[0].scrollTop = 0; $("#msg").focus(); }); } function transitionFromGameToLobby() { $("#landingPage").fadeOut("fast", function () { $("#topLevel").fadeOut(200, function () { $("#lobbyContainer").fadeIn(200); //scroll down the lobby chat $("#lobbyChatListContainer")[0].scrollTop = $( "#lobbyChatListContainer", )[0].scrollHeight; }); $("#lobbyContainer")[0].scrollTop = 0; }); } /* Copyright 2017-2018 James V. Craster Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ "use strict"; import * as WebFont from "webfontloader"; import * as PIXI from "pixi.js"; export let mainText: StandardMainTextList | undefined = undefined; let WebFontConfig = { custom: { families: ["Mercutio"], urls: ["/css/main.css"], }, }; WebFont.load({ custom: { families: ["Mercutio"], }, active: function () { mainText = new StandardMainTextList(); }, }); export class StandardMainText { public object: PIXI.Text; constructor(text: string, color: string) { if (color == undefined) { this.object = new PIXI.Text(text, { fontFamily: "Mercutio", fontSize: 512, fill: 0xffffff, align: "center", }); } else { color = color.substr(1); color = "0x" + color; this.object = new PIXI.Text(text, { fontFamily: "Mercutio", fontSize: 512, fill: parseInt(color), align: "center", }); } this.object.scale.x = 0.125; this.object.scale.y = 0.125; } } class StandardMainTextList { public container: PIXI.Container; public fadeOutTimeout: NodeJS.Timer | undefined = undefined; public textShownDuration: number = 2500; public queue: Array<Array<StandardMainText>>; constructor(textArray?: Array<StandardMainText>) { this.container = new PIXI.Container(); app.stage.addChild(this.container); this.textShownDuration = 2500; this.queue = []; if (textArray != undefined) { this.push(textArray); } } clear() { this.container.removeChildren(); } push(textArray: Array<StandardMainText>) { this.queue.unshift(textArray); //if this is the only element in the queue, then render it now if (this.queue.length == 1) { this.render(this.queue[this.queue.length - 1]); } } render(textArray: Array<StandardMainText>) { if (this.fadeOutTimeout) { clearInterval(this.fadeOutTimeout); } this.clear(); this.container.alpha = 1; let point = 0; for (let i = 0; i < textArray.length; i++) { textArray[i].object.x = point; this.container.addChild(textArray[i].object); point += textArray[i].object.width; } this.reposition(); //render the next one after a delay this.fadeOutTimeout = setTimeout(() => { let fadingAnimation = setInterval(() => { this.container.alpha = this.container.alpha * 0.8; //if transparent enough to be invisible, stop fading out and show next text if (this.container.alpha < 0.01) { this.container.alpha = 0; clearInterval(fadingAnimation); this.queue.pop(); if (this.queue.length != 0) { this.render(this.queue[this.queue.length - 1]); } } }, 10); }, this.textShownDuration); } //called on window resize in addition to when rerendering happens reposition() { this.container.x = Math.floor(app.renderer.width / 2) - this.container.width / 2; this.container.y = 25; } } //set scaling to work well with pixel art PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; let app = new PIXI.Application(800, 600, { backgroundColor: 0x2d2d2d, }); const playerTexture = PIXI.Texture.fromImage( "assets/sprites/swordplayerbreathing/sprite_0.png", ); const playerTexture2 = PIXI.Texture.fromImage( "assets/sprites/swordplayerbreathing/sprite_1.png", ); const playerTextureSelected = PIXI.Texture.fromImage( "assets/sprites/swordplayerbreathing/sprite_0_selected.png", ); const playerTextureSelected2 = PIXI.Texture.fromImage( "assets/sprites/swordplayerbreathing/sprite_1_selected.png", ); const graveTexture = PIXI.Texture.fromImage("assets/sprites/grave.png"); let players: Array<Player> = []; //@ts-ignore window.players = players; const stoneBlockTexture = PIXI.Texture.fromImage("assets/sprites/stoneblock.png"); const stoneBlockContainer = new PIXI.Container(); app.stage.addChild(stoneBlockContainer); class StoneBlock { public sprite: PIXI.Sprite = new PIXI.Sprite(stoneBlockTexture); constructor(x: number, y: number) { this.sprite.pivot.x = 0.5; this.sprite.pivot.y = 0.5; this.sprite.x = x; this.sprite.y = y; this.sprite.scale.x = 2; this.sprite.scale.y = 2; this.sprite.anchor.set(0.5, 0.5); stoneBlockContainer.addChild(this.sprite); } } let level = 11; for (let y = 0; y < level; y++) { if (y < 6) { for (let x = -y; x < y; x++) { let stoneblock = new StoneBlock(x * 64, y * 64); } } else { for (let x = y - 11; x < 11 - y; x++) { let stoneblock = new StoneBlock(x * 64, y * 64); } } } stoneBlockContainer.pivot.y = stoneBlockContainer.height / 2; app.stage.interactive = true; app.stage.on("pointerdown", () => { if (user.inGame) { for (let i = 0; i < players.length; i++) { //assume that the player is unvoting let unvoted = true; //test if this mousedown has changed anything (to guard against repeat presses) let active = false; if (!players[i].selected && players[i].votedFor) { players[i].votedFor = false; active = true; if ((players[i].sprite.texture = playerTextureSelected)) { players[i].sprite.texture = playerTexture; } else { players[i].sprite.texture = playerTexture2; } } for (let j = 0; j < players.length; j++) { if (players[j].votedFor) { unvoted = false; } } if (unvoted && active && user.canVote) { user.socket.emit("message", "/unvote"); } } } }); user.socket.on("cancelVoteEffect", function () { cancelVote(); }); user.socket.on("selectPlayer", function (username: string) { selectPlayer(username.trim()); }); user.socket.on("finalVerdict", function () { $("#guiltyButtons").show(); }); user.socket.on("endVerdict", function () { $("#guiltyButtons").hide(); }); $("#guiltyButton").on("click", function () { user.socket.emit("message", "/guilty"); }); $("#innocentButton").on("click", function () { user.socket.emit("message", "/innocent"); }); function cancelVote() { for (let i = 0; i < players.length; i++) { players[i].votedFor = false; } } let firstTimeSelectingPlayer = true; let firstTimeSelectingInterval: NodeJS.Timer | undefined = undefined; let firstTimeNumberOfRuns = 0; export function markAsDead(username: string) { for (let i = 0; i < players.length; i++) { if (players[i].username == username) { players[i].disappear(); } } } function selectPlayer(username: string) { //calling selectPlayer straight away the first time causes a bug //because not all of the players have been added yet. if (firstTimeSelectingPlayer) { firstTimeSelectingInterval = setInterval(() => { for (let i = 0; i < players.length; i++) { if (players[i].username == username) { players[i].votedFor = true; firstTimeSelectingPlayer = false; if (firstTimeSelectingInterval) { clearInterval(firstTimeSelectingInterval); } players[i].select(); } } //stop running loop after 10 seconds if no match found firstTimeNumberOfRuns++; if (firstTimeNumberOfRuns > 100 && firstTimeSelectingInterval) { clearInterval(firstTimeSelectingInterval); } }, 100); } else { cancelVote(); for (let i = 0; i < players.length; i++) { if (players[i].username == username) { players[i].votedFor = true; } } } } class Player { public sprite: PIXI.Sprite; public usernameText: PIXI.Text; public graveSprite: PIXI.Sprite; public selected: boolean; public votedFor: boolean; public breatheAnimation: number | undefined; public frameCount: number; constructor(public username: string) { this.sprite = new PIXI.Sprite(playerTexture); this.sprite.anchor.set(0.5, 0.5); this.sprite.interactive = true; this.selected = false; this.votedFor = false; this.breatheAnimation = undefined; this.frameCount = 0; this.graveSprite = new PIXI.Sprite(graveTexture); this.sprite.on("pointerover", () => { this.selected = true; if (this.sprite.texture == playerTexture) { this.sprite.texture = playerTextureSelected; } else { this.sprite.texture = playerTextureSelected2; } }); this.sprite.on("pointerout", () => { this.selected = false; if (this.sprite.texture == playerTextureSelected && !this.votedFor) { this.sprite.texture = playerTexture; } else if (!this.votedFor) { this.sprite.texture = playerTexture2; } }); this.sprite.on("pointerdown", () => { if (user.inGame && user.canVote && !this.votedFor) { user.socket.emit("message", "/vote " + username.trim()); for (let i = 0; i < players.length; i++) { players[i].votedFor = false; if (players[i] != this) { if ((players[i].sprite.texture = playerTextureSelected)) { players[i].sprite.texture = playerTexture; } else { players[i].sprite.texture = playerTexture2; } } } this.votedFor = true; } }); let usernameColor = 0xffffff; this.frameCount = 0; app.stage.addChild(this.sprite); this.username = username.trim(); this.usernameText = new PIXI.Text(username, { fontFamily: "Mercutio", fontSize: 128, fill: usernameColor, align: "center", }); this.usernameText.scale.x = 0.25; this.usernameText.scale.y = 0.25; this.usernameText.x = Math.floor(this.sprite.x); this.usernameText.y = Math.floor(this.sprite.y - 45); this.usernameText.anchor.set(0.5, 0.5); app.stage.addChild(this.usernameText); this.breatheAnimation = window.setInterval(this.breathe.bind(this), 1500); } breathe() { if (this.frameCount % 2 == 0) { if (this.selected || this.votedFor) { this.sprite.texture = playerTextureSelected; } else { this.sprite.texture = playerTexture; } } else { if (this.selected || this.votedFor) { this.sprite.texture = playerTextureSelected2; } else { this.sprite.texture = playerTexture2; } } this.frameCount++; } setPos(x: number, y: number) { this.sprite.x = Math.floor(x); this.sprite.y = Math.floor(y); this.usernameText.x = Math.floor(x); this.usernameText.y = Math.floor(y - 45); if (this.graveSprite) { this.graveSprite.x = Math.floor(x); this.graveSprite.y = Math.floor(y); } } destructor() { app.stage.removeChild(this.sprite); app.stage.removeChild(this.usernameText); app.stage.removeChild(this.graveSprite); } //could more accurately be called 'die' disappear() { this.sprite.visible = false; this.graveSprite.anchor.set(0.5, 0.5); this.graveSprite.scale.x = 2; this.graveSprite.scale.y = 2; app.stage.addChild(this.graveSprite); resize(); } select() { if (this.sprite.texture == playerTexture) { this.sprite.texture = playerTextureSelected; } else { this.sprite.texture = playerTextureSelected2; } } } let gallowsTexture = PIXI.Texture.fromImage("assets/sprites/gallows.png"); let gallowsHangingAnimation: Array<PIXI.Texture> = []; gallowsHangingAnimation.push( PIXI.Texture.fromImage("assets/sprites/swordplayerhanging/sprite_hanging0.png"), ); gallowsHangingAnimation.push( PIXI.Texture.fromImage("assets/sprites/swordplayerhanging/sprite_hanging1.png"), ); gallowsHangingAnimation.push( PIXI.Texture.fromImage("assets/sprites/swordplayerhanging/sprite_hanging2.png"), ); gallowsHangingAnimation.push( PIXI.Texture.fromImage("assets/sprites/swordplayerhanging/sprite_hanging3.png"), ); class Gallows { public sprite: PIXI.Sprite; public counter: number = 0; public hangingInterval: NodeJS.Timer | undefined = undefined; constructor() { this.sprite = new PIXI.Sprite(gallowsTexture); this.sprite.anchor.set(0.5, 0.5); this.sprite.scale.x = 2; this.sprite.scale.y = 2; this.sprite.x = Math.floor(app.renderer.width / 2); this.sprite.y = Math.floor(app.renderer.height / 2) - 50; } hang() { this.sprite.texture = gallowsHangingAnimation[0]; this.sprite.scale.x = 1; this.sprite.scale.y = 1; this.counter = 0; this.hangingInterval = setInterval(() => { this.counter++; this.sprite.texture = gallowsHangingAnimation[this.counter]; if (this.counter == 3 && this.hangingInterval) { clearInterval(this.hangingInterval); } }, 25); } reset() { this.sprite.texture = gallowsTexture; this.sprite.scale.x = 2; this.sprite.scale.y = 2; } } export let gallows = new Gallows(); user.socket.on("hang", function (usernames: Array<string>) { //make invisible all those players who username matches one on the list for (let i = 0; i < players.length; i++) { for (let j = 0; j < usernames.length; j++) { if (players[i].username == usernames[j]) { players[i].sprite.visible = false; //players[i].usernameText.visible = false; } } } //hanging animation gallows.hang(); }); user.socket.on("resetGallows", function () { gallows.reset(); }); export function removeAllPlayers() { for (let i = 0; i < players.length; i++) { players[i].destructor(); } players = []; resize(); } export function removePlayer(username: string) { for (let i = 0; i < players.length; i++) { if (players[i].username == username) { players[i].destructor(); players.splice(i, 1); resize(); } } } export function addPlayer(username: string) { players.push(new Player(username)); if (mainText) { app.stage.removeChild(mainText.container); app.stage.addChild(mainText.container); } resize(); } export function resize() { const parent = app.view.parentNode; app.renderer.resize( (parent as Element).clientWidth, (parent as Element).clientHeight, ); if (mainText) { mainText.reposition(); } gallows.sprite.x = Math.floor(app.renderer.width / 2); gallows.sprite.y = Math.floor(app.renderer.height / 2) - 10; let positions: Array<Array<number>> = []; if (players.length <= 10) { positions = distributeInCircle(players.length, 190); } else { positions = distributeInCircle(players.length, 210); } for (let i = 0; i < players.length; i++) { players[i].setPos( gallows.sprite.x + positions[i][0], gallows.sprite.y + positions[i][1] + 20, ); if (positions[i][0] > 1) { players[i].sprite.scale.x = -1; } else { players[i].sprite.scale.x = 1; } } stoneBlockContainer.position.x = gallows.sprite.position.x + 33; stoneBlockContainer.position.y = gallows.sprite.position.y - 33; } function distributeInCircle(number: number, radius: number) { let positions = []; let angle = (2 * Math.PI) / number; for (let i = 0; i < number; i++) { positions.push([ radius * Math.sin(angle * i), radius * Math.cos(angle * i), ]); } return positions; } $(window).resize(resize); app.stage.addChild(gallows.sprite); $("#canvasContainer").append(app.view);
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 SnowDeviceManagement extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: SnowDeviceManagement.Types.ClientConfiguration) config: Config & SnowDeviceManagement.Types.ClientConfiguration; /** * Sends a cancel request for a specified task. You can cancel a task only if it's still in a QUEUED state. Tasks that are already running can't be cancelled. A task might still run if it's processed from the queue before the CancelTask operation changes the task's state. */ cancelTask(params: SnowDeviceManagement.Types.CancelTaskInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.CancelTaskOutput) => void): Request<SnowDeviceManagement.Types.CancelTaskOutput, AWSError>; /** * Sends a cancel request for a specified task. You can cancel a task only if it's still in a QUEUED state. Tasks that are already running can't be cancelled. A task might still run if it's processed from the queue before the CancelTask operation changes the task's state. */ cancelTask(callback?: (err: AWSError, data: SnowDeviceManagement.Types.CancelTaskOutput) => void): Request<SnowDeviceManagement.Types.CancelTaskOutput, AWSError>; /** * Instructs one or more devices to start a task, such as unlocking or rebooting. */ createTask(params: SnowDeviceManagement.Types.CreateTaskInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.CreateTaskOutput) => void): Request<SnowDeviceManagement.Types.CreateTaskOutput, AWSError>; /** * Instructs one or more devices to start a task, such as unlocking or rebooting. */ createTask(callback?: (err: AWSError, data: SnowDeviceManagement.Types.CreateTaskOutput) => void): Request<SnowDeviceManagement.Types.CreateTaskOutput, AWSError>; /** * Checks device-specific information, such as the device type, software version, IP addresses, and lock status. */ describeDevice(params: SnowDeviceManagement.Types.DescribeDeviceInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.DescribeDeviceOutput) => void): Request<SnowDeviceManagement.Types.DescribeDeviceOutput, AWSError>; /** * Checks device-specific information, such as the device type, software version, IP addresses, and lock status. */ describeDevice(callback?: (err: AWSError, data: SnowDeviceManagement.Types.DescribeDeviceOutput) => void): Request<SnowDeviceManagement.Types.DescribeDeviceOutput, AWSError>; /** * Checks the current state of the Amazon EC2 instances. The output is similar to describeDevice, but the results are sourced from the device cache in the Amazon Web Services Cloud and include a subset of the available fields. */ describeDeviceEc2Instances(params: SnowDeviceManagement.Types.DescribeDeviceEc2Input, callback?: (err: AWSError, data: SnowDeviceManagement.Types.DescribeDeviceEc2Output) => void): Request<SnowDeviceManagement.Types.DescribeDeviceEc2Output, AWSError>; /** * Checks the current state of the Amazon EC2 instances. The output is similar to describeDevice, but the results are sourced from the device cache in the Amazon Web Services Cloud and include a subset of the available fields. */ describeDeviceEc2Instances(callback?: (err: AWSError, data: SnowDeviceManagement.Types.DescribeDeviceEc2Output) => void): Request<SnowDeviceManagement.Types.DescribeDeviceEc2Output, AWSError>; /** * Checks the status of a remote task running on one or more target devices. */ describeExecution(params: SnowDeviceManagement.Types.DescribeExecutionInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.DescribeExecutionOutput) => void): Request<SnowDeviceManagement.Types.DescribeExecutionOutput, AWSError>; /** * Checks the status of a remote task running on one or more target devices. */ describeExecution(callback?: (err: AWSError, data: SnowDeviceManagement.Types.DescribeExecutionOutput) => void): Request<SnowDeviceManagement.Types.DescribeExecutionOutput, AWSError>; /** * Checks the metadata for a given task on a device. */ describeTask(params: SnowDeviceManagement.Types.DescribeTaskInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.DescribeTaskOutput) => void): Request<SnowDeviceManagement.Types.DescribeTaskOutput, AWSError>; /** * Checks the metadata for a given task on a device. */ describeTask(callback?: (err: AWSError, data: SnowDeviceManagement.Types.DescribeTaskOutput) => void): Request<SnowDeviceManagement.Types.DescribeTaskOutput, AWSError>; /** * Returns a list of the Amazon Web Services resources available for a device. Currently, Amazon EC2 instances are the only supported resource type. */ listDeviceResources(params: SnowDeviceManagement.Types.ListDeviceResourcesInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListDeviceResourcesOutput) => void): Request<SnowDeviceManagement.Types.ListDeviceResourcesOutput, AWSError>; /** * Returns a list of the Amazon Web Services resources available for a device. Currently, Amazon EC2 instances are the only supported resource type. */ listDeviceResources(callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListDeviceResourcesOutput) => void): Request<SnowDeviceManagement.Types.ListDeviceResourcesOutput, AWSError>; /** * Returns a list of all devices on your Amazon Web Services account that have Amazon Web Services Snow Device Management enabled in the Amazon Web Services Region where the command is run. */ listDevices(params: SnowDeviceManagement.Types.ListDevicesInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListDevicesOutput) => void): Request<SnowDeviceManagement.Types.ListDevicesOutput, AWSError>; /** * Returns a list of all devices on your Amazon Web Services account that have Amazon Web Services Snow Device Management enabled in the Amazon Web Services Region where the command is run. */ listDevices(callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListDevicesOutput) => void): Request<SnowDeviceManagement.Types.ListDevicesOutput, AWSError>; /** * Returns the status of tasks for one or more target devices. */ listExecutions(params: SnowDeviceManagement.Types.ListExecutionsInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListExecutionsOutput) => void): Request<SnowDeviceManagement.Types.ListExecutionsOutput, AWSError>; /** * Returns the status of tasks for one or more target devices. */ listExecutions(callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListExecutionsOutput) => void): Request<SnowDeviceManagement.Types.ListExecutionsOutput, AWSError>; /** * Returns a list of tags for a managed device or task. */ listTagsForResource(params: SnowDeviceManagement.Types.ListTagsForResourceInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListTagsForResourceOutput) => void): Request<SnowDeviceManagement.Types.ListTagsForResourceOutput, AWSError>; /** * Returns a list of tags for a managed device or task. */ listTagsForResource(callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListTagsForResourceOutput) => void): Request<SnowDeviceManagement.Types.ListTagsForResourceOutput, AWSError>; /** * Returns a list of tasks that can be filtered by state. */ listTasks(params: SnowDeviceManagement.Types.ListTasksInput, callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListTasksOutput) => void): Request<SnowDeviceManagement.Types.ListTasksOutput, AWSError>; /** * Returns a list of tasks that can be filtered by state. */ listTasks(callback?: (err: AWSError, data: SnowDeviceManagement.Types.ListTasksOutput) => void): Request<SnowDeviceManagement.Types.ListTasksOutput, AWSError>; /** * Adds or replaces tags on a device or task. */ tagResource(params: SnowDeviceManagement.Types.TagResourceInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Adds or replaces tags on a device or task. */ tagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes a tag from a device or task. */ untagResource(params: SnowDeviceManagement.Types.UntagResourceInput, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes a tag from a device or task. */ untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; } declare namespace SnowDeviceManagement { export type AttachmentStatus = "ATTACHING"|"ATTACHED"|"DETACHING"|"DETACHED"|string; export type Boolean = boolean; export interface CancelTaskInput { /** * The ID of the task that you are attempting to cancel. You can retrieve a task ID by using the ListTasks operation. */ taskId: TaskId; } export interface CancelTaskOutput { /** * The ID of the task that you are attempting to cancel. */ taskId?: String; } export interface Capacity { /** * The amount of capacity available for use on the device. */ available?: Long; /** * The name of the type of capacity, such as memory. */ name?: CapacityNameString; /** * The total capacity on the device. */ total?: Long; /** * The unit of measure for the type of capacity. */ unit?: CapacityUnitString; /** * The amount of capacity used on the device. */ used?: Long; } export type CapacityList = Capacity[]; export type CapacityNameString = string; export type CapacityUnitString = string; export interface Command { /** * Reboots the device. */ reboot?: Reboot; /** * Unlocks the device. */ unlock?: Unlock; } export interface CpuOptions { /** * The number of cores that the CPU can use. */ coreCount?: Integer; /** * The number of threads per core in the CPU. */ threadsPerCore?: Integer; } export interface CreateTaskInput { /** * A token ensuring that the action is called only once with the specified details. */ clientToken?: IdempotencyToken; /** * The task to be performed. Only one task is executed on a device at a time. */ command: Command; /** * A description of the task and its targets. */ description?: TaskDescriptionString; /** * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways, such as by purpose, owner, or environment. */ tags?: TagMap; /** * A list of managed device IDs. */ targets: TargetList; } export interface CreateTaskOutput { /** * The Amazon Resource Name (ARN) of the task that you created. */ taskArn?: String; /** * The ID of the task that you created. */ taskId?: String; } export interface DescribeDeviceEc2Input { /** * A list of instance IDs associated with the managed device. */ instanceIds: InstanceIdsList; /** * The ID of the managed device. */ managedDeviceId: ManagedDeviceId; } export interface DescribeDeviceEc2Output { /** * A list of structures containing information about each instance. */ instances?: InstanceSummaryList; } export interface DescribeDeviceInput { /** * The ID of the device that you are checking the information of. */ managedDeviceId: ManagedDeviceId; } export interface DescribeDeviceOutput { /** * The ID of the job used when ordering the device. */ associatedWithJob?: String; /** * The hardware specifications of the device. */ deviceCapacities?: CapacityList; /** * The current state of the device. */ deviceState?: UnlockState; /** * The type of Amazon Web Services Snow Family device. */ deviceType?: String; /** * When the device last contacted the Amazon Web Services Cloud. Indicates that the device is online. */ lastReachedOutAt?: Timestamp; /** * When the device last pushed an update to the Amazon Web Services Cloud. Indicates when the device cache was refreshed. */ lastUpdatedAt?: Timestamp; /** * The Amazon Resource Name (ARN) of the device. */ managedDeviceArn?: String; /** * The ID of the device that you checked the information for. */ managedDeviceId?: ManagedDeviceId; /** * The network interfaces available on the device. */ physicalNetworkInterfaces?: PhysicalNetworkInterfaceList; /** * The software installed on the device. */ software?: SoftwareInformation; /** * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways, such as by purpose, owner, or environment. */ tags?: TagMap; } export interface DescribeExecutionInput { /** * The ID of the managed device. */ managedDeviceId: ManagedDeviceId; /** * The ID of the task that the action is describing. */ taskId: TaskId; } export interface DescribeExecutionOutput { /** * The ID of the execution. */ executionId?: ExecutionId; /** * When the status of the execution was last updated. */ lastUpdatedAt?: Timestamp; /** * The ID of the managed device that the task is being executed on. */ managedDeviceId?: ManagedDeviceId; /** * When the execution began. */ startedAt?: Timestamp; /** * The current state of the execution. */ state?: ExecutionState; /** * The ID of the task being executed on the device. */ taskId?: TaskId; } export interface DescribeTaskInput { /** * The ID of the task to be described. */ taskId: TaskId; } export interface DescribeTaskOutput { /** * When the task was completed. */ completedAt?: Timestamp; /** * When the CreateTask operation was called. */ createdAt?: Timestamp; /** * The description provided of the task and managed devices. */ description?: TaskDescriptionString; /** * When the state of the task was last updated. */ lastUpdatedAt?: Timestamp; /** * The current state of the task. */ state?: TaskState; /** * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways, such as by purpose, owner, or environment. */ tags?: TagMap; /** * The managed devices that the task was sent to. */ targets?: TargetList; /** * The Amazon Resource Name (ARN) of the task. */ taskArn?: String; /** * The ID of the task. */ taskId?: String; } export interface DeviceSummary { /** * The ID of the job used to order the device. */ associatedWithJob?: String; /** * The Amazon Resource Name (ARN) of the device. */ managedDeviceArn?: String; /** * The ID of the device. */ managedDeviceId?: ManagedDeviceId; /** * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways, such as by purpose, owner, or environment. */ tags?: TagMap; } export type DeviceSummaryList = DeviceSummary[]; export interface EbsInstanceBlockDevice { /** * When the attachment was initiated. */ attachTime?: Timestamp; /** * A value that indicates whether the volume is deleted on instance termination. */ deleteOnTermination?: Boolean; /** * The attachment state. */ status?: AttachmentStatus; /** * The ID of the Amazon EBS volume. */ volumeId?: String; } export type ExecutionId = string; export type ExecutionState = "QUEUED"|"IN_PROGRESS"|"CANCELED"|"FAILED"|"SUCCEEDED"|"REJECTED"|"TIMED_OUT"|string; export interface ExecutionSummary { /** * The ID of the execution. */ executionId?: ExecutionId; /** * The ID of the managed device that the task is being executed on. */ managedDeviceId?: ManagedDeviceId; /** * The state of the execution. */ state?: ExecutionState; /** * The ID of the task. */ taskId?: TaskId; } export type ExecutionSummaryList = ExecutionSummary[]; export type IdempotencyToken = string; export interface Instance { /** * The Amazon Machine Image (AMI) launch index, which you can use to find this instance in the launch group. */ amiLaunchIndex?: Integer; /** * Any block device mapping entries for the instance. */ blockDeviceMappings?: InstanceBlockDeviceMappingList; /** * The CPU options for the instance. */ cpuOptions?: CpuOptions; /** * When the instance was created. */ createdAt?: Timestamp; /** * The ID of the AMI used to launch the instance. */ imageId?: String; /** * The ID of the instance. */ instanceId?: String; /** * The instance type. */ instanceType?: String; /** * The private IPv4 address assigned to the instance. */ privateIpAddress?: String; /** * The public IPv4 address assigned to the instance. */ publicIpAddress?: String; /** * The device name of the root device volume (for example, /dev/sda1). */ rootDeviceName?: String; /** * The security groups for the instance. */ securityGroups?: SecurityGroupIdentifierList; state?: InstanceState; /** * When the instance was last updated. */ updatedAt?: Timestamp; } export interface InstanceBlockDeviceMapping { /** * The block device name. */ deviceName?: String; /** * The parameters used to automatically set up Amazon Elastic Block Store (Amazon EBS) volumes when the instance is launched. */ ebs?: EbsInstanceBlockDevice; } export type InstanceBlockDeviceMappingList = InstanceBlockDeviceMapping[]; export type InstanceIdsList = String[]; export interface InstanceState { /** * The state of the instance as a 16-bit unsigned integer. The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values between 256 and 65,535. These numerical values are used for internal purposes and should be ignored. The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values between 0 and 255. The valid values for the instance state code are all in the range of the low byte. These values are: 0 : pending 16 : running 32 : shutting-down 48 : terminated 64 : stopping 80 : stopped You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in decimal. */ code?: Integer; /** * The current state of the instance. */ name?: InstanceStateName; } export type InstanceStateName = "PENDING"|"RUNNING"|"SHUTTING_DOWN"|"TERMINATED"|"STOPPING"|"STOPPED"|string; export interface InstanceSummary { /** * A structure containing details about the instance. */ instance?: Instance; /** * When the instance summary was last updated. */ lastUpdatedAt?: Timestamp; } export type InstanceSummaryList = InstanceSummary[]; export type Integer = number; export type IpAddressAssignment = "DHCP"|"STATIC"|string; export type JobId = string; export interface ListDeviceResourcesInput { /** * The ID of the managed device that you are listing the resources of. */ managedDeviceId: ManagedDeviceId; /** * The maximum number of resources per page. */ maxResults?: MaxResults; /** * A pagination token to continue to the next page of results. */ nextToken?: NextToken; /** * A structure used to filter the results by type of resource. */ type?: ListDeviceResourcesInputTypeString; } export type ListDeviceResourcesInputTypeString = string; export interface ListDeviceResourcesOutput { /** * A pagination token to continue to the next page of results. */ nextToken?: NextToken; /** * A structure defining the resource's type, Amazon Resource Name (ARN), and ID. */ resources?: ResourceSummaryList; } export interface ListDevicesInput { /** * The ID of the job used to order the device. */ jobId?: JobId; /** * The maximum number of devices to list per page. */ maxResults?: MaxResults; /** * A pagination token to continue to the next page of results. */ nextToken?: NextToken; } export interface ListDevicesOutput { /** * A list of device structures that contain information about the device. */ devices?: DeviceSummaryList; /** * A pagination token to continue to the next page of devices. */ nextToken?: NextToken; } export interface ListExecutionsInput { /** * The maximum number of tasks to list per page. */ maxResults?: MaxResults; /** * A pagination token to continue to the next page of tasks. */ nextToken?: NextToken; /** * A structure used to filter the tasks by their current state. */ state?: ExecutionState; /** * The ID of the task. */ taskId: TaskId; } export interface ListExecutionsOutput { /** * A list of executions. Each execution contains the task ID, the device that the task is executing on, the execution ID, and the status of the execution. */ executions?: ExecutionSummaryList; /** * A pagination token to continue to the next page of executions. */ nextToken?: NextToken; } export interface ListTagsForResourceInput { /** * The Amazon Resource Name (ARN) of the device or task. */ resourceArn: String; } export interface ListTagsForResourceOutput { /** * The list of tags for the device or task. */ tags?: TagMap; } export interface ListTasksInput { /** * The maximum number of tasks per page. */ maxResults?: MaxResults; /** * A pagination token to continue to the next page of tasks. */ nextToken?: NextToken; /** * A structure used to filter the list of tasks. */ state?: TaskState; } export interface ListTasksOutput { /** * A pagination token to continue to the next page of tasks. */ nextToken?: NextToken; /** * A list of task structures containing details about each task. */ tasks?: TaskSummaryList; } export type Long = number; export type ManagedDeviceId = string; export type MaxResults = number; export type NextToken = string; export type PhysicalConnectorType = "RJ45"|"SFP_PLUS"|"QSFP"|"RJ45_2"|"WIFI"|string; export interface PhysicalNetworkInterface { /** * The default gateway of the device. */ defaultGateway?: String; /** * The IP address of the device. */ ipAddress?: String; /** * A value that describes whether the IP address is dynamic or persistent. */ ipAddressAssignment?: IpAddressAssignment; /** * The MAC address of the device. */ macAddress?: String; /** * The netmask used to divide the IP address into subnets. */ netmask?: String; /** * The physical connector type. */ physicalConnectorType?: PhysicalConnectorType; /** * The physical network interface ID. */ physicalNetworkInterfaceId?: String; } export type PhysicalNetworkInterfaceList = PhysicalNetworkInterface[]; export interface Reboot { } export interface ResourceSummary { /** * The Amazon Resource Name (ARN) of the resource. */ arn?: String; /** * The ID of the resource. */ id?: String; /** * The resource type. */ resourceType: String; } export type ResourceSummaryList = ResourceSummary[]; export interface SecurityGroupIdentifier { /** * The security group ID. */ groupId?: String; /** * The security group name. */ groupName?: String; } export type SecurityGroupIdentifierList = SecurityGroupIdentifier[]; export interface SoftwareInformation { /** * The state of the software that is installed or that is being installed on the device. */ installState?: String; /** * The version of the software currently installed on the device. */ installedVersion?: String; /** * The version of the software being installed on the device. */ installingVersion?: String; } export type String = string; export type TagKeys = String[]; export type TagMap = {[key: string]: String}; export interface TagResourceInput { /** * The Amazon Resource Name (ARN) of the device or task. */ resourceArn: String; /** * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways, such as by purpose, owner, or environment. */ tags: TagMap; } export type TargetList = String[]; export type TaskDescriptionString = string; export type TaskId = string; export type TaskState = "IN_PROGRESS"|"CANCELED"|"COMPLETED"|string; export interface TaskSummary { /** * The state of the task assigned to one or many devices. */ state?: TaskState; /** * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways, such as by purpose, owner, or environment. */ tags?: TagMap; /** * The Amazon Resource Name (ARN) of the task. */ taskArn?: String; /** * The task ID. */ taskId: TaskId; } export type TaskSummaryList = TaskSummary[]; export type Timestamp = Date; export interface Unlock { } export type UnlockState = "UNLOCKED"|"LOCKED"|"UNLOCKING"|string; export interface UntagResourceInput { /** * The Amazon Resource Name (ARN) of the device or task. */ resourceArn: String; /** * Optional metadata that you assign to a resource. You can use tags to categorize a resource in different ways, such as by purpose, owner, or environment. */ tagKeys: TagKeys; } /** * 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 = "2021-08-04"|"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 SnowDeviceManagement client. */ export import Types = SnowDeviceManagement; } export = SnowDeviceManagement;
the_stack
import * as jsonx from '.'; import * as _jsonxUtils from './utils'; import mochaJSDOM from 'jsdom-global'; import chai from 'chai'; import sinon from 'sinon'; import React from 'react'; import ReactTestUtils from 'react-dom/test-utils'; // ES6 import ReactDOM from 'react-dom'; import ReactDOMElements from 'react-dom-factories'; import { expect } from 'chai'; import { JSDOM, } from 'jsdom'; chai.use(require('sinon-chai')); // import 'mocha-sinon'; const sampleJSONX = { component: 'div', props: { id: 'generatedJSONX', className: 'jsonx', bigNum: 1430931039, smallNum: 0.425, falsey: false, truthy: true, }, children: 'some div', }; describe('jsonx utils', function () { describe('displayComponent', () => { const displayComponent = _jsonxUtils.displayComponent; it('should display by default return true', () => { expect(displayComponent()).to.be.true; }); it('should display if left !== null||undefined', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['falsey', ], operation:'exists', },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: null, },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.false; }); it('should display if left === null||undefined', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy',], operation:'dne', },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['falsey', ], operation:'undefined', },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: null, operation:'null', },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.false; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.false //@ts-ignore; expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.true; }); it('should display if left == right', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'eq', right:['truthy', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'==', right:['falsey', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'eq', right:1, },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.false //@ts-ignore; expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.true; }); it('should display if left === right', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'seq', right:['truthy', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'===', right:['falsey', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'seq', right:1, },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.false //@ts-ignore; expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.false; }); it('should display if left != right', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'dneq', right:['truthy', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'!=', right:['falsey', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'dneq', right:1, },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.false; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.true; }); it('should display if left !== right', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'dnseq', right:['truthy', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'!==', right:['falsey', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'dnseq', right:1, },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.false; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.true; }); it('should display if left > right', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['bigNum', ], operation:'gt', right:['smallNum', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['smallNum', ], operation:'>', right:['bigNum', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['smallNum', ], operation:'gt', right:['smallNum', ], },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.false //@ts-ignore; expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.false; }); it('should display if left >= right', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['bigNum', ], operation:'gte', right:['smallNum', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['smallNum', ], operation:'>=', right:['bigNum', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['smallNum', ], operation:'gte', right:['smallNum', ], },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.false //@ts-ignore; expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.true; }); it('should display if left < right', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['bigNum', ], operation:'<', right:['smallNum', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['smallNum', ], operation:'lt', right:['bigNum', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['smallNum', ], operation:'lt', right:['smallNum', ], },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.false; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.false; }); it('should display if left <= right', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['bigNum', ], operation:'lte', right:['smallNum', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['smallNum', ], operation:'<=', right:['bigNum', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['smallNum', ], operation:'lte', right:['smallNum', ], },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.false; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.true; }); it('should display if multiple comprisons are true', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'eq', right:['truthy', ], }, { left: ['smallNum', ], operation:'==', right:['smallNum', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonprops: [{ left: ['truthy', ], operation:'eq', right:['falsey', ], }, { left: ['smallNum', ], operation:'eq', right:['smallNum', ], },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.false; }); it('should display if one or more using comparisonorprops comprisons are true', () => { const testJSONX = Object.assign({}, sampleJSONX, { comparisonorprops:true, comparisonprops: [{ left: ['truthy', ], operation:'eq', right:['truthy', ], }, { left: ['smallNum', ], operation:'==', right:['smallNum', ], },], }); const testJSONX2 = Object.assign({}, sampleJSONX, { comparisonorprops:true, comparisonprops: [{ left: ['truthy', ], operation:'eq', right:['falsey', ], }, { left: ['smallNum', ], operation:'eq', right:['smallNum', ], },], }); const testJSONX3 = Object.assign({}, sampleJSONX, { comparisonorprops:true, comparisonprops: [{ left: ['truthy', ], operation:'eq', right:['falsey', ], }, { left: ['bigNum', ], operation:'eq', right:['smallNum', ], },], }); //@ts-ignore expect(displayComponent({ jsonx: testJSONX, props: testJSONX.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX2, props: testJSONX2.props, })).to.be.true; //@ts-ignore expect(displayComponent({ jsonx: testJSONX3, props: testJSONX3.props, })).to.be.false; }); }); describe('getAdvancedBinding', () => { const getAdvancedBinding = _jsonxUtils.getAdvancedBinding; it('should return true if browser supports deep nesting', function () { const window = { navigator: { userAgent: 'Webkit', }, }; expect(getAdvancedBinding.call({ window, })).to.be.true; }); it('should return false on all versions of IE/Trident', function () { const window = { navigator: { userAgent: 'Trident', }, }; expect(getAdvancedBinding.call({ window, })).to.be.false; }); it('should return false on old Android Browser', function () { const window = { navigator: { userAgent: 'Mozilla/5.0 (Linux; U; Android 1.5; de-de; HTC Magic Build/CRB17) AppleWebKit/528.5 (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1', }, }; expect(getAdvancedBinding.call({ window, })).to.be.false; }); it('should return false on old Chrome Browser', function () { const window = { navigator: { userAgent: 'Mozilla/5.0 (Linux; Android 4.1.2; GT-I9300 Build/JZO54K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36', }, }; expect(getAdvancedBinding.call({ window, })).to.be.false; }); it('should return false unknown browser', function () { expect(getAdvancedBinding.call({window:{} })).to.be.false; }); }); describe('traverse', () => { const testObj = { user: { name: 'jsonx', description: 'react withouth javascript', }, stats: { logins: 102, comments: 3, }, authentication: 'OAuth2', }; const traverse = _jsonxUtils.traverse; it('should return properties from an object from the array of paths', () => { const testVals = { auth: ['authentication', ], username: ['user', 'name', ], }; expect( traverse(testVals, testObj)).to.eql({ auth:testObj.authentication, username:testObj.user.name, }); }); it('should return the entire object if no paths provided', () => { const testVals = { wholeObj: [], }; expect( traverse(testVals, testObj)).to.eql({ wholeObj:testObj, }); }); it('should return undefined if paths are invalid', () => { const testVals = { emptyObj: ['invalid', 'path',], }; expect( traverse(testVals, testObj)).to.eql({ emptyObj:undefined, }); }); it('should throw an error if paths are not an array of strings or numeric indexes', () => { const testVals = { emptyObj: () => undefined, }; //@ts-ignore expect(traverse.bind(null, testVals, testObj)).to.throw(Error); }); }); describe('validateJSONX', () => { const validateJSONX = _jsonxUtils.validateJSONX; it('should return true if JSONX is valid', ()=> { expect(validateJSONX(sampleJSONX)).to.be.true; }); it('should return string and warn of invalid JSONX props', () => { const invalidKeys = { incorrect: true, extra: true, }; const invalidKeyJSONX = Object.assign({}, sampleJSONX, invalidKeys); const validationTest = validateJSONX(invalidKeyJSONX); expect(validationTest).to.be.a('string').and.to.be.ok; expect(validationTest).to.eql(`Warning: Invalid Keys [${Object.keys(invalidKeys).join()}]`); }); it('should throw a syntax error if JSONX is missing a component', () => { const validationTest = validateJSONX.bind({}); expect(validationTest).to.throw('Missing React Component'); expect(validationTest).to.throw(SyntaxError); }); it('should throw multiple errors if returnAllErrors is true', () => { const validationTest = validateJSONX( { props: [], }, true); //@ts-ignore expect(validationTest).to.be.an('array'); //@ts-ignore expect(validationTest[ 0 ]).to.be.an('error'); }); it('should throw a type error if JSONX props is not an object, props.children or props._children', () => { const badPropTest1 = validateJSONX.bind(null, { component:'div', props:{ children:{}, }, }); expect(validateJSONX.bind(null, { component:'div', props:'bad', })).to.throw(TypeError); expect(validateJSONX.bind(null, { component:'div', props:[], })).to.throw(TypeError); expect(badPropTest1).to.throw(TypeError); expect(validateJSONX.bind(null, { component: 'div', props: { _children: {}, }, })).to.throw(TypeError); }); it('should throw a type error if JSONX children is not an array or JSONX docs or a string', () => { //@ts-ignore expect(validateJSONX.bind(null, { component:'div', children:{}, })).to.throw(TypeError); }); it('should validate child objects', () => { const jsonxObj = { component: 'div', children: [ { props:'this is missing a component', }, { component: 'p', children: {}, asyncprops:'', }, ], }; //@ts-ignore const childrenErrors = validateJSONX(jsonxObj, true); //@ts-ignore expect(childrenErrors).to.be.an('array'); //@ts-ignore expect(childrenErrors[ 0 ]).to.be.an('error'); }); //@ts-ignore it('should validate dynamic props[asyncprops,resourceprops,thisprops,windowprops]', () => { const jsonxObj = { component: 'myComponent', asyncprops: '[]', resourceprops: '[]', thisprops: { notStrings: [undefined, {}, ], }, windowprops: { title:['navigator', 'userAgent', ], }, }; //@ts-ignore const dynamicerrors = validateJSONX(jsonxObj, true); expect(dynamicerrors).to.be.an('array'); //@ts-ignore expect(dynamicerrors.length).to.eql(7); //@ts-ignore expect(dynamicerrors[ 0 ]).to.be.an('error'); }); it('should validate eval props[__dangerouslyEvalProps,__dangerouslyBindEvalProps]', () => { const jsonxObj = { component: 'myComponent', __dangerouslyEvalProps: 'badobj', }; const jsonxObj2 = { component: 'myComponent', __dangerouslyEvalProps: { testJS:'()=>true', testJS1:'3', }, }; //@ts-ignore const evalError = validateJSONX(jsonxObj, true); const evalError2 = validateJSONX(jsonxObj2); //@ts-ignore expect(evalError[ 0 ]).to.be.an('error'); expect(evalError2).to.be.true; // console.log({ evalError3 }); // expect(dynamicerrors).to.be.an('array'); // expect(dynamicerrors.length).to.eql(4); // expect(dynamicerrors[ 0 ]).to.be.an('error'); }); it('should validate __dangerouslyEvalProps javascript', () => { const jsonxObj3 = { component: 'myComponent', __dangerouslyEvalProps: { testJS: '(=>true', }, }; //@ts-ignore const evalError3 = validateJSONX(jsonxObj3, true); //@ts-ignore expect(evalError3[ 0 ]).to.be.an('error'); }); it('should validate __dangerouslyBindEvalProps as a function that can be bound javascript', () => { const jsonxObj4 = { component: 'myComponent', __dangerouslyBindEvalProps: { testJS1: '{}', }, }; //@ts-ignore const evalError4 = validateJSONX(jsonxObj4, true); //@ts-ignore expect(evalError4[ 0 ]).to.be.an('error'); }); it('should validate __dangerouslyInsertComponents are valid JSONX objects', () => { const jsonxObj = { component: 'myComponent', __dangerouslyInsertComponents: { testComponent: { component_missing: 'nodiv', props: {}, }, }, }; const evalError = validateJSONX(jsonxObj, true); //@ts-ignore expect(evalError[ 0 ]).to.be.an('error'); }); it('should validate __functionProps are valid function strings', () => { const jsonxObj = { component: 'myComponent', __functionProps: { invalidFunc: { isString: {}, }, }, }; const jsonxObj2 = { component: 'myComponent', __functionProps: 'should be an obj', }; const jsonxObjValid = { component: 'myComponent', __functionProps: { goodFunc:'func:this.someFunc', }, }; //@ts-ignore const evalError = validateJSONX(jsonxObj, true); //@ts-ignore const evalError2 = validateJSONX(jsonxObj2, true); const validTest = validateJSONX(jsonxObjValid); //@ts-ignore expect(evalError[0]).to.be.an('error'); //@ts-ignore expect(evalError2[ 0 ]).to.be.an('error'); expect(validTest).to.be.true; }); it('should validate __windowComponentProps is an object', () => { const jsonxObj = { component: 'myComponent', __windowComponentProps: 'should be an obj', }; const jsonxObjValid = { component: 'myComponent', __windowComponentProps: { goodProps:'ok', }, }; const evalError = validateJSONX(jsonxObj, true); const validTest = validateJSONX(jsonxObjValid); //@ts-ignore expect(evalError[ 0 ]).to.be.an('error'); expect(validTest).to.be.true; }); it('should validate __windowComponents are valid function strings', () => { const jsonxObj = { component: 'myComponent', __windowComponents: { invalidFunc: { isString: {}, }, }, }; const jsonxObj2 = { component: 'myComponent', __windowComponents: 'should be an obj', }; const jsonxObjValid = { component: 'myComponent', __windowComponents: { goodFunc:'func:this.someFunc', }, }; const evalError = validateJSONX(jsonxObj, true); const evalError2 = validateJSONX(jsonxObj2, true); const validTest = validateJSONX(jsonxObjValid); //@ts-ignore expect(evalError[0]).to.be.an('error'); //@ts-ignore expect(evalError2[ 0 ]).to.be.an('error'); expect(validTest).to.be.true; }); it('should validate comparisonorprops is boolean', () => { const jsonxObj = { component: 'myComponent', comparisonorprops: 'should be an obj', }; const jsonxObjValid = { component: 'myComponent', comparisonorprops: true, }; //@ts-ignore const evalError = validateJSONX(jsonxObj, true); //@ts-ignore const validTest = validateJSONX(jsonxObjValid); //@ts-ignore expect(evalError[ 0 ]).to.be.an('error'); expect(validTest).to.be.true; }); it('should validate comparisonprops is an array of comaprisons', () => { const jsonxObj = { component: 'myComponent', comparisonprops: 'should be an array', }; const jsonxObjValid = { component: 'myComponent', comparisonprops: [], }; const jsonxObjin1 = { component: 'myComponent', comparisonprops: [{},], }; const jsonxObjin2 = { component: 'myComponent', comparisonprops: [() => { },], }; //@ts-ignore const evalError = validateJSONX(jsonxObj, true); //@ts-ignore const evalError1 = validateJSONX(jsonxObjin1, true); //@ts-ignore const evalError2 = validateJSONX(jsonxObjin2, true); //@ts-ignore const validTest = validateJSONX(jsonxObjValid); //@ts-ignore expect(evalError[0]).to.be.an('error'); //@ts-ignore expect(evalError1[0]).to.be.an('error'); //@ts-ignore expect(evalError2[ 0 ]).to.be.an('error'); expect(validTest).to.be.true; }); it('should validate passprops is boolean', () => { const jsonxObj = { component: 'myComponent', passprops: 'should be an obj', }; const jsonxObjValid = { component: 'myComponent', passprops: true, }; //@ts-ignore const evalError = validateJSONX(jsonxObj, true); const validTest = validateJSONX(jsonxObjValid); //@ts-ignore expect(evalError[ 0 ]).to.be.an('error'); expect(validTest).to.be.true; }); }); describe('validSimpleJSONXSyntax', () => { const validSimpleJSONXSyntax = _jsonxUtils.validSimpleJSONXSyntax; it('should invalidate shorthard simple syntax', () => { const validShorthand = { component:'p', }; const invalidShorthand2 = { component: 'p', props: { style: { background:'red', }, }, }; const invalidShorthand3 = { component: 'p', props:'hey', }; const invalidShorthand4 = { component: 'p', props: { style: { background:'red', }, }, children:'hey', }; const validShorthand5 = { children:'p', }; const validShorthand6 = { anything:'p', }; const invalidShorthand7 = { anything: { component: 'p', }, }; expect(validSimpleJSONXSyntax(validShorthand)).to.be.true; expect(validSimpleJSONXSyntax(invalidShorthand2)).to.be.false; expect(validSimpleJSONXSyntax(invalidShorthand3)).to.be.false; expect(validSimpleJSONXSyntax(invalidShorthand4)).to.be.false; expect(validSimpleJSONXSyntax(validShorthand5)).to.be.true; expect(validSimpleJSONXSyntax(validShorthand6)).to.be.true; expect(validSimpleJSONXSyntax(invalidShorthand7)).to.be.false; }); it('should validate shorthard simple syntax', () => { const validShorthand = { p:{}, }; const validShorthand2 = { p: { props: { style: { background:'red', }, }, }, }; const validShorthand3 = { p: { props:'hey', }, }; const validShorthand4 = { p: { props: { style: { background:'red', }, }, children:'hey', }, }; const validShorthand5 = { children: { children:'p', }, }; expect(validSimpleJSONXSyntax(validShorthand)).to.be.true; expect(validSimpleJSONXSyntax(validShorthand2)).to.be.true; expect(validSimpleJSONXSyntax(validShorthand3)).to.be.true; expect(validSimpleJSONXSyntax(validShorthand4)).to.be.true; expect(validSimpleJSONXSyntax(validShorthand5)).to.be.true; }); }); describe('simpleJSONXSyntax', () => { const simpleJSONXSyntax = _jsonxUtils.simpleJSONXSyntax; it('should return valid JSONX from simple JSONX syntax', () => { const validShorthand = { p:{}, }; const validShorthand2 = { p: { props: { style: { background:'red', }, }, }, }; const validShorthand3 = { p: { props:'hey', }, }; const validShorthand4 = { div: { props: { style: { background:'red', }, }, children: [ { p: { children: 'hey', }, }, ], }, }; const validShorthand5 = { children: { children:'p', }, }; const transformedSimpleSyntaxValid = _jsonxUtils.validateJSONX(simpleJSONXSyntax(validShorthand), true); const transformedSimpleSyntaxValid2 = _jsonxUtils.validateJSONX(simpleJSONXSyntax(validShorthand2), true); const transformedSimpleSyntaxValid3 = _jsonxUtils.validateJSONX(simpleJSONXSyntax(validShorthand3), true); const transformedSimpleSyntaxValid4 = _jsonxUtils.validateJSONX(simpleJSONXSyntax(validShorthand4), true); const transformedSimpleSyntaxValid5 = _jsonxUtils.validateJSONX(simpleJSONXSyntax(validShorthand5), true); expect((transformedSimpleSyntaxValid)).to.be.true; expect((transformedSimpleSyntaxValid2)).to.be.true; //@ts-ignore expect((transformedSimpleSyntaxValid3[0])).to.be.an('error'); //@ts-ignore expect((transformedSimpleSyntaxValid4[0])).to.be.true; expect((transformedSimpleSyntaxValid5)).to.be.true; }); it('should produce equivalent JSONX', () => { const sampleJSONX = { component: 'div', props: { id: 'generatedJSONX', className: 'jsonx', }, asyncprops: { test:['ok', 'cool',], }, children: [ { component: 'p', props: { style: { color: 'red', fontWeight: 'bold', }, }, children: 'hello world', }, ], }; const simpleJSONX = { div: { props: { id: 'generatedJSONX', className: 'jsonx', }, asyncprops: { test:['ok', 'cool',], }, children: [ { p: { props: { style: { color: 'red', fontWeight: 'bold', }, }, children: 'hello world', }, }, ], }, }; const transformedJSONXSTRING = simpleJSONXSyntax(simpleJSONX).toString(); const JSONXSTRING = sampleJSONX.toString(); expect(transformedJSONXSTRING).to.eql(JSONXSTRING); }); }); describe('getSimplifiedJSONX', () => { const getSimplifiedJSONX = _jsonxUtils.getSimplifiedJSONX; const simpleJSONX = { div: { props: { id: 'generatedJSONX', className: 'jsonx', }, asyncprops: { test:['ok', 'cool',], }, children: [ { p: { props: { style: { color: 'red', fontWeight: 'bold', }, }, children: 'hello world', }, }, ], }, }; const sampleJSONX = { component: 'div', props: { id: 'generatedJSONX', className: 'jsonx', }, asyncprops: { test:['ok', 'cool',], }, children: [ { component: 'p', props: { style: { color: 'red', fontWeight: 'bold', }, }, children: 'hello world', }, ], }; it('should produce equivalent SimpleJSONX', () => { const transformedJSONXSTRING = getSimplifiedJSONX(sampleJSONX).toString(); const JSONXSTRING = simpleJSONX.toString(); expect(transformedJSONXSTRING).to.eql(JSONXSTRING); }); it('should return SimpleJSONX if already simple', () => { expect(simpleJSONX).to.eql(getSimplifiedJSONX(simpleJSONX)); }); }); });
the_stack
module android.text { import Canvas = android.graphics.Canvas; import Paint = android.graphics.Paint; import FontMetricsInt = android.graphics.Paint.FontMetricsInt; import RectF = android.graphics.RectF; import CharacterStyle = android.text.style.CharacterStyle; import MetricAffectingSpan = android.text.style.MetricAffectingSpan; import ReplacementSpan = android.text.style.ReplacementSpan; import Log = android.util.Log; import Spanned = android.text.Spanned; import SpanSet = android.text.SpanSet; import TextPaint = android.text.TextPaint; import TextUtils = android.text.TextUtils; import Layout = android.text.Layout; window.addEventListener('AndroidUILoadFinish', ()=>{ eval('Layout = android.text.Layout;');//real import now }); /** * Represents a line of styled text, for measuring in visual order and * for rendering. * * <p>Get a new instance using obtain(), and when finished with it, return it * to the pool using recycle(). * * <p>Call set to prepare the instance for use, then either draw, measure, * metrics, or caretToLeftRightOf. * * @hide */ export class TextLine { private static DEBUG:boolean = false; private mPaint:TextPaint; private mText:String; private mStart:number = 0; private mLen:number = 0; private mDir:number = 0; private mDirections:Layout.Directions; private mHasTabs:boolean; private mTabs:Layout.TabStops; private mChars:String; private mCharsValid:boolean; private mSpanned:Spanned; private mWorkPaint:TextPaint = new TextPaint(); private mMetricAffectingSpanSpanSet:SpanSet<MetricAffectingSpan> = new SpanSet<MetricAffectingSpan>(MetricAffectingSpan.type); private mCharacterStyleSpanSet:SpanSet<CharacterStyle> = new SpanSet<CharacterStyle>(CharacterStyle.type); private mReplacementSpanSpanSet:SpanSet<ReplacementSpan> = new SpanSet<ReplacementSpan>(ReplacementSpan.type); private static sCached:TextLine[] = new Array<TextLine>(3); /** * Returns a new TextLine from the shared pool. * * @return an uninitialized TextLine */ static obtain():TextLine { let tl:TextLine; { for (let i:number = TextLine.sCached.length; --i >= 0; ) { if (TextLine.sCached[i] != null) { tl = TextLine.sCached[i]; TextLine.sCached[i] = null; return tl; } } } tl = new TextLine(); if (TextLine.DEBUG) { Log.v("TLINE", "new: " + tl); } return tl; } /** * Puts a TextLine back into the shared pool. Do not use this TextLine once * it has been returned. * @param tl the textLine * @return null, as a convenience from clearing references to the provided * TextLine */ static recycle(tl:TextLine):TextLine { tl.mText = null; tl.mPaint = null; tl.mDirections = null; tl.mMetricAffectingSpanSpanSet.recycle(); tl.mCharacterStyleSpanSet.recycle(); tl.mReplacementSpanSpanSet.recycle(); { for (let i:number = 0; i < TextLine.sCached.length; ++i) { if (TextLine.sCached[i] == null) { TextLine.sCached[i] = tl; break; } } } return null; } /** * Initializes a TextLine and prepares it for use. * * @param paint the base paint for the line * @param text the text, can be Styled * @param start the start of the line relative to the text * @param limit the limit of the line relative to the text * @param dir the paragraph direction of this line * @param directions the directions information of this line * @param hasTabs true if the line might contain tabs or emoji * @param tabStops the tabStops. Can be null. */ set(paint:TextPaint, text:String, start:number, limit:number, dir:number, directions:Layout.Directions, hasTabs:boolean, tabStops:Layout.TabStops):void { this.mPaint = paint; this.mText = text; this.mStart = start; this.mLen = limit - start; this.mDir = dir; this.mDirections = directions; if (this.mDirections == null) { throw Error(`new IllegalArgumentException("Directions cannot be null")`); } this.mHasTabs = hasTabs; this.mSpanned = null; let hasReplacement:boolean = false; if (Spanned.isImplements(text)) { this.mSpanned = <Spanned> text; this.mReplacementSpanSpanSet.init(this.mSpanned, start, limit); hasReplacement = this.mReplacementSpanSpanSet.numberOfSpans > 0; } this.mCharsValid = hasReplacement || hasTabs || directions != Layout.DIRS_ALL_LEFT_TO_RIGHT; if (this.mCharsValid) { //if (this.mChars == null || this.mChars.length < this.mLen) { // this.mChars = new Array<char>(ArrayUtils.idealCharArraySize(this.mLen)); //} //TextUtils.getChars(text, start, limit, this.mChars, 0); this.mChars = text; if (hasReplacement) { // Handle these all at once so we don't have to do it as we go. // Replace the first character of each replacement run with the // object-replacement character and the remainder with zero width // non-break space aka BOM. Cursor movement code skips these // zero-width characters. let chars = this.mChars.split(''); for (let i:number = start, inext:number; i < limit; i = inext) { inext = this.mReplacementSpanSpanSet.getNextTransition(i, limit); if (this.mReplacementSpanSpanSet.hasSpansIntersecting(i, inext)) { // transition into a span chars[i - start] = ''; for (let j:number = i - start + 1, e:number = inext - start; j < e; ++j) { // used as ZWNBS, marks positions to skip chars[j] = ''; } } } this.mChars = chars.join(''); } } this.mTabs = tabStops; } /** * Renders the TextLine. * * @param c the canvas to render on * @param x the leading margin position * @param top the top of the line * @param y the baseline * @param bottom the bottom of the line */ draw(c:Canvas, x:number, top:number, y:number, bottom:number):void { if (!this.mHasTabs) { if (this.mDirections == Layout.DIRS_ALL_LEFT_TO_RIGHT) { this.drawRun(c, 0, this.mLen, false, x, top, y, bottom, false); return; } if (this.mDirections == Layout.DIRS_ALL_RIGHT_TO_LEFT) { this.drawRun(c, 0, this.mLen, true, x, top, y, bottom, false); return; } } let h:number = 0; let runs:number[] = this.mDirections.mDirections; let emojiRect:RectF = null; let lastRunIndex:number = runs.length - 2; for (let i:number = 0; i < runs.length; i += 2) { let runStart:number = runs[i]; let runLimit:number = runStart + (runs[i + 1] & Layout.RUN_LENGTH_MASK); if (runLimit > this.mLen) { runLimit = this.mLen; } let runIsRtl:boolean = (runs[i + 1] & Layout.RUN_RTL_FLAG) != 0; let segstart:number = runStart; for (let j:number = this.mHasTabs ? runStart : runLimit; j <= runLimit; j++) { let codept:number = 0; //let bm:Bitmap = null; if (this.mHasTabs && j < runLimit) { codept = this.mChars.codePointAt(j); if (codept >= 0xd800 && codept < 0xdc00 && j + 1 < runLimit) { codept = this.mChars.codePointAt(j); //if (codept >= Layout.MIN_EMOJI && codept <= Layout.MAX_EMOJI) { // bm = Layout.EMOJI_FACTORY.getBitmapFromAndroidPua(codept); //} else if (codept > 0xffff) { ++j; continue; } } } if (j == runLimit || codept == '\t'.codePointAt(0) //|| bm != null ) { h += this.drawRun(c, segstart, j, runIsRtl, x + h, top, y, bottom, i != lastRunIndex || j != this.mLen); if (codept == '\t'.codePointAt(0)) { h = this.mDir * this.nextTab(h * this.mDir); } //else if (bm != null) { // let bmAscent:number = this.ascent(j); // let bitmapHeight:number = bm.getHeight(); // let scale:number = -bmAscent / bitmapHeight; // let width:number = bm.getWidth() * scale; // if (emojiRect == null) { // emojiRect = new RectF(); // } // emojiRect.set(x + h, y + bmAscent, x + h + width, y); // c.drawBitmap(bm, null, emojiRect, this.mPaint); // h += width; // j++; //} segstart = j + 1; } } } } /** * Returns metrics information for the entire line. * * @param fmi receives font metrics information, can be null * @return the signed width of the line */ metrics(fmi:FontMetricsInt):number { return this.measure(this.mLen, false, fmi); } /** * Returns information about a position on the line. * * @param offset the line-relative character offset, between 0 and the * line length, inclusive * @param trailing true to measure the trailing edge of the character * before offset, false to measure the leading edge of the character * at offset. * @param fmi receives metrics information about the requested * character, can be null. * @return the signed offset from the leading margin to the requested * character edge. */ measure(offset:number, trailing:boolean, fmi:FontMetricsInt):number { let target:number = trailing ? offset - 1 : offset; if (target < 0) { return 0; } let h:number = 0; if (!this.mHasTabs) { if (this.mDirections == Layout.DIRS_ALL_LEFT_TO_RIGHT) { return this.measureRun(0, offset, this.mLen, false, fmi); } if (this.mDirections == Layout.DIRS_ALL_RIGHT_TO_LEFT) { return this.measureRun(0, offset, this.mLen, true, fmi); } } let chars = this.mChars; let runs:number[] = this.mDirections.mDirections; for (let i:number = 0; i < runs.length; i += 2) { let runStart:number = runs[i]; let runLimit:number = runStart + (runs[i + 1] & Layout.RUN_LENGTH_MASK); if (runLimit > this.mLen) { runLimit = this.mLen; } let runIsRtl:boolean = (runs[i + 1] & Layout.RUN_RTL_FLAG) != 0; let segstart:number = runStart; for (let j:number = this.mHasTabs ? runStart : runLimit; j <= runLimit; j++) { let codept:number = 0; //let bm:Bitmap = null; if (this.mHasTabs && j < runLimit) { codept = chars.codePointAt(j); if (codept >= 0xd800 && codept < 0xdc00 && j + 1 < runLimit) { codept = chars.codePointAt(j); //if (codept >= Layout.MIN_EMOJI && codept <= Layout.MAX_EMOJI) { // bm = Layout.EMOJI_FACTORY.getBitmapFromAndroidPua(codept); //} else if (codept > 0xffff) { ++j; continue; } } } if (j == runLimit || codept == '\t'.codePointAt(0) //|| bm != null ) { let inSegment:boolean = target >= segstart && target < j; let advance:boolean = (this.mDir == Layout.DIR_RIGHT_TO_LEFT) == runIsRtl; if (inSegment && advance) { return h += this.measureRun(segstart, offset, j, runIsRtl, fmi); } let w:number = this.measureRun(segstart, j, j, runIsRtl, fmi); h += advance ? w : -w; if (inSegment) { return h += this.measureRun(segstart, offset, j, runIsRtl, null); } if (codept == '\t'.codePointAt(0)) { if (offset == j) { return h; } h = this.mDir * this.nextTab(h * this.mDir); if (target == j) { return h; } } //if (bm != null) { // let bmAscent:number = this.ascent(j); // let wid:number = bm.getWidth() * -bmAscent / bm.getHeight(); // h += this.mDir * wid; // j++; //} segstart = j + 1; } } } return h; } /** * Draws a unidirectional (but possibly multi-styled) run of text. * * * @param c the canvas to draw on * @param start the line-relative start * @param limit the line-relative limit * @param runIsRtl true if the run is right-to-left * @param x the position of the run that is closest to the leading margin * @param top the top of the line * @param y the baseline * @param bottom the bottom of the line * @param needWidth true if the width value is required. * @return the signed width of the run, based on the paragraph direction. * Only valid if needWidth is true. */ private drawRun(c:Canvas, start:number, limit:number, runIsRtl:boolean, x:number, top:number, y:number, bottom:number, needWidth:boolean):number { if ((this.mDir == Layout.DIR_LEFT_TO_RIGHT) == runIsRtl) { let w:number = -this.measureRun(start, limit, limit, runIsRtl, null); this.handleRun(start, limit, limit, runIsRtl, c, x + w, top, y, bottom, null, false); return w; } return this.handleRun(start, limit, limit, runIsRtl, c, x, top, y, bottom, null, needWidth); } /** * Measures a unidirectional (but possibly multi-styled) run of text. * * * @param start the line-relative start of the run * @param offset the offset to measure to, between start and limit inclusive * @param limit the line-relative limit of the run * @param runIsRtl true if the run is right-to-left * @param fmi receives metrics information about the requested * run, can be null. * @return the signed width from the start of the run to the leading edge * of the character at offset, based on the run (not paragraph) direction */ private measureRun(start:number, offset:number, limit:number, runIsRtl:boolean, fmi:FontMetricsInt):number { return this.handleRun(start, offset, limit, runIsRtl, null, 0, 0, 0, 0, fmi, true); } /** * Walk the cursor through this line, skipping conjuncts and * zero-width characters. * * <p>This function cannot properly walk the cursor off the ends of the line * since it does not know about any shaping on the previous/following line * that might affect the cursor position. Callers must either avoid these * situations or handle the result specially. * * @param cursor the starting position of the cursor, between 0 and the * length of the line, inclusive * @param toLeft true if the caret is moving to the left. * @return the new offset. If it is less than 0 or greater than the length * of the line, the previous/following line should be examined to get the * actual offset. */ getOffsetToLeftRightOf(cursor:number, toLeft:boolean):number { // 1) The caret marks the leading edge of a character. The character // logically before it might be on a different level, and the active caret // position is on the character at the lower level. If that character // was the previous character, the caret is on its trailing edge. // 2) Take this character/edge and move it in the indicated direction. // This gives you a new character and a new edge. // 3) This position is between two visually adjacent characters. One of // these might be at a lower level. The active position is on the // character at the lower level. // 4) If the active position is on the trailing edge of the character, // the new caret position is the following logical character, else it // is the character. let lineStart:number = 0; let lineEnd:number = this.mLen; let paraIsRtl:boolean = this.mDir == -1; let runs:number[] = this.mDirections.mDirections; let runIndex:number, runLevel:number = 0, runStart:number = lineStart, runLimit:number = lineEnd, newCaret:number = -1; let trailing:boolean = false; if (cursor == lineStart) { runIndex = -2; } else if (cursor == lineEnd) { runIndex = runs.length; } else { // the active caret. for (runIndex = 0; runIndex < runs.length; runIndex += 2) { runStart = lineStart + runs[runIndex]; if (cursor >= runStart) { runLimit = runStart + (runs[runIndex + 1] & Layout.RUN_LENGTH_MASK); if (runLimit > lineEnd) { runLimit = lineEnd; } if (cursor < runLimit) { runLevel = (runs[runIndex + 1] >>> Layout.RUN_LEVEL_SHIFT) & Layout.RUN_LEVEL_MASK; if (cursor == runStart) { // The caret is on a run boundary, see if we should // use the position on the trailing edge of the previous // logical character instead. let prevRunIndex:number, prevRunLevel:number, prevRunStart:number, prevRunLimit:number; let pos:number = cursor - 1; for (prevRunIndex = 0; prevRunIndex < runs.length; prevRunIndex += 2) { prevRunStart = lineStart + runs[prevRunIndex]; if (pos >= prevRunStart) { prevRunLimit = prevRunStart + (runs[prevRunIndex + 1] & Layout.RUN_LENGTH_MASK); if (prevRunLimit > lineEnd) { prevRunLimit = lineEnd; } if (pos < prevRunLimit) { prevRunLevel = (runs[prevRunIndex + 1] >>> Layout.RUN_LEVEL_SHIFT) & Layout.RUN_LEVEL_MASK; if (prevRunLevel < runLevel) { // Start from logically previous character. runIndex = prevRunIndex; runLevel = prevRunLevel; runStart = prevRunStart; runLimit = prevRunLimit; trailing = true; break; } } } } } break; } } } // we are at a run boundary so we skip the below test. if (runIndex != runs.length) { let runIsRtl:boolean = (runLevel & 0x1) != 0; let advance:boolean = toLeft == runIsRtl; if (cursor != (advance ? runLimit : runStart) || advance != trailing) { // Moving within or into the run, so we can move logically. newCaret = this.getOffsetBeforeAfter(runIndex, runStart, runLimit, runIsRtl, cursor, advance); // position already so we're finished. if (newCaret != (advance ? runLimit : runStart)) { return newCaret; } } } } // another run boundary. while (true) { let advance:boolean = toLeft == paraIsRtl; let otherRunIndex:number = runIndex + (advance ? 2 : -2); if (otherRunIndex >= 0 && otherRunIndex < runs.length) { let otherRunStart:number = lineStart + runs[otherRunIndex]; let otherRunLimit:number = otherRunStart + (runs[otherRunIndex + 1] & Layout.RUN_LENGTH_MASK); if (otherRunLimit > lineEnd) { otherRunLimit = lineEnd; } let otherRunLevel:number = (runs[otherRunIndex + 1] >>> Layout.RUN_LEVEL_SHIFT) & Layout.RUN_LEVEL_MASK; let otherRunIsRtl:boolean = (otherRunLevel & 1) != 0; advance = toLeft == otherRunIsRtl; if (newCaret == -1) { newCaret = this.getOffsetBeforeAfter(otherRunIndex, otherRunStart, otherRunLimit, otherRunIsRtl, advance ? otherRunStart : otherRunLimit, advance); if (newCaret == (advance ? otherRunLimit : otherRunStart)) { // Crossed and ended up at a new boundary, // repeat a second and final time. runIndex = otherRunIndex; runLevel = otherRunLevel; continue; } break; } // The new caret is at a boundary. if (otherRunLevel < runLevel) { // The strong character is in the other run. newCaret = advance ? otherRunStart : otherRunLimit; } break; } if (newCaret == -1) { // We're walking off the end of the line. The paragraph // level is always equal to or lower than any internal level, so // the boundaries get the strong caret. newCaret = advance ? this.mLen + 1 : -1; break; } // the lineStart. if (newCaret <= lineEnd) { newCaret = advance ? lineEnd : lineStart; } break; } return newCaret; } /** * Returns the next valid offset within this directional run, skipping * conjuncts and zero-width characters. This should not be called to walk * off the end of the line, since the returned values might not be valid * on neighboring lines. If the returned offset is less than zero or * greater than the line length, the offset should be recomputed on the * preceding or following line, respectively. * * @param runIndex the run index * @param runStart the start of the run * @param runLimit the limit of the run * @param runIsRtl true if the run is right-to-left * @param offset the offset * @param after true if the new offset should logically follow the provided * offset * @return the new offset */ private getOffsetBeforeAfter(runIndex:number, runStart:number, runLimit:number, runIsRtl:boolean, offset:number, after:boolean):number { if (runIndex < 0 || offset == (after ? this.mLen : 0)) { // return accurate values. These are a guess. if (after) { return TextUtils.getOffsetAfter(this.mText, offset + this.mStart) - this.mStart; } return TextUtils.getOffsetBefore(this.mText, offset + this.mStart) - this.mStart; } let wp:TextPaint = this.mWorkPaint; wp.set(this.mPaint); let spanStart:number = runStart; let spanLimit:number; if (this.mSpanned == null) { spanLimit = runLimit; } else { let target:number = after ? offset + 1 : offset; let limit:number = this.mStart + runLimit; while (true) { spanLimit = this.mSpanned.nextSpanTransition(this.mStart + spanStart, limit, MetricAffectingSpan.type) - this.mStart; if (spanLimit >= target) { break; } spanStart = spanLimit; } let spans:MetricAffectingSpan[] = this.mSpanned.getSpans<MetricAffectingSpan>(this.mStart + spanStart, this.mStart + spanLimit, MetricAffectingSpan.type); spans = TextUtils.removeEmptySpans(spans, this.mSpanned, MetricAffectingSpan.type); if (spans.length > 0) { let replacement:ReplacementSpan = null; for (let j:number = 0; j < spans.length; j++) { let span:MetricAffectingSpan = spans[j]; if (span instanceof ReplacementSpan) { replacement = <ReplacementSpan> span; } else { span.updateMeasureState(wp); } } if (replacement != null) { // the start or end of this span. return after ? spanLimit : spanStart; } } } let flags:number = runIsRtl ? Paint.DIRECTION_RTL : Paint.DIRECTION_LTR; let cursorOpt:number = after ? Paint.CURSOR_AFTER : Paint.CURSOR_BEFORE; if (this.mCharsValid) { return wp.getTextRunCursor_len(this.mChars.toString(), spanStart, spanLimit - spanStart, flags, offset, cursorOpt); } else { return wp.getTextRunCursor_end(this.mText.toString(), this.mStart + spanStart, this.mStart + spanLimit, flags, this.mStart + offset, cursorOpt) - this.mStart; } } /** * @param wp */ private static expandMetricsFromPaint(fmi:FontMetricsInt, wp:TextPaint):void { const previousTop:number = fmi.top; const previousAscent:number = fmi.ascent; const previousDescent:number = fmi.descent; const previousBottom:number = fmi.bottom; const previousLeading:number = fmi.leading; wp.getFontMetricsInt(fmi); TextLine.updateMetrics(fmi, previousTop, previousAscent, previousDescent, previousBottom, previousLeading); } static updateMetrics(fmi:FontMetricsInt, previousTop:number, previousAscent:number, previousDescent:number, previousBottom:number, previousLeading:number):void { fmi.top = Math.min(fmi.top, previousTop); fmi.ascent = Math.min(fmi.ascent, previousAscent); fmi.descent = Math.max(fmi.descent, previousDescent); fmi.bottom = Math.max(fmi.bottom, previousBottom); fmi.leading = Math.max(fmi.leading, previousLeading); } /** * Utility function for measuring and rendering text. The text must * not include a tab or emoji. * * @param wp the working paint * @param start the start of the text * @param end the end of the text * @param runIsRtl true if the run is right-to-left * @param c the canvas, can be null if rendering is not needed * @param x the edge of the run closest to the leading margin * @param top the top of the line * @param y the baseline * @param bottom the bottom of the line * @param fmi receives metrics information, can be null * @param needWidth true if the width of the run is needed * @return the signed width of the run based on the run direction; only * valid if needWidth is true */ private handleText(wp:TextPaint, start:number, end:number, contextStart:number, contextEnd:number, runIsRtl:boolean, c:Canvas, x:number, top:number, y:number, bottom:number, fmi:FontMetricsInt, needWidth:boolean):number { // Get metrics first (even for empty strings or "0" width runs) if (fmi != null) { TextLine.expandMetricsFromPaint(fmi, wp); } let runLen:number = end - start; // No need to do anything if the run width is "0" if (runLen == 0) { return 0; } let ret:number = 0; let contextLen:number = contextEnd - contextStart; if (needWidth || (c != null && (wp.bgColor != 0 || wp.underlineColor != 0 || runIsRtl))) { let flags:number = runIsRtl ? Paint.DIRECTION_RTL : Paint.DIRECTION_LTR; if (this.mCharsValid) { ret = wp.getTextRunAdvances_count(this.mChars.toString(), start, runLen, contextStart, contextLen, flags, null, 0); } else { let delta:number = this.mStart; ret = wp.getTextRunAdvances_end(this.mText.toString(), delta + start, delta + end, delta + contextStart, delta + contextEnd, flags, null, 0); } } if (c != null) { if (runIsRtl) { x -= ret; } if (wp.bgColor != 0) { let previousColor:number = wp.getColor(); let previousStyle:Paint.Style = wp.getStyle(); wp.setColor(wp.bgColor); wp.setStyle(Paint.Style.FILL); c.drawRect(x, top, x + ret, bottom, wp); wp.setStyle(previousStyle); wp.setColor(previousColor); } if (wp.underlineColor != 0) { // kStdUnderline_Offset = 1/9, defined in SkTextFormatParams.h let underlineTop:number = y + wp.baselineShift + (1.0 / 9.0) * wp.getTextSize(); let previousColor:number = wp.getColor(); let previousStyle:Paint.Style = wp.getStyle(); let previousAntiAlias:boolean = wp.isAntiAlias(); wp.setStyle(Paint.Style.FILL); wp.setAntiAlias(true); wp.setColor(wp.underlineColor); c.drawRect(x, underlineTop, x + ret, underlineTop + wp.underlineThickness, wp); wp.setStyle(previousStyle); wp.setColor(previousColor); wp.setAntiAlias(previousAntiAlias); } this.drawTextRun(c, wp, start, end, contextStart, contextEnd, runIsRtl, x, y + wp.baselineShift); } return runIsRtl ? -ret : ret; } /** * Utility function for measuring and rendering a replacement. * * * @param replacement the replacement * @param wp the work paint * @param start the start of the run * @param limit the limit of the run * @param runIsRtl true if the run is right-to-left * @param c the canvas, can be null if not rendering * @param x the edge of the replacement closest to the leading margin * @param top the top of the line * @param y the baseline * @param bottom the bottom of the line * @param fmi receives metrics information, can be null * @param needWidth true if the width of the replacement is needed * @return the signed width of the run based on the run direction; only * valid if needWidth is true */ private handleReplacement(replacement:ReplacementSpan, wp:TextPaint, start:number, limit:number, runIsRtl:boolean, c:Canvas, x:number, top:number, y:number, bottom:number, fmi:FontMetricsInt, needWidth:boolean):number { let ret:number = 0; let textStart:number = this.mStart + start; let textLimit:number = this.mStart + limit; if (needWidth || (c != null && runIsRtl)) { let previousTop:number = 0; let previousAscent:number = 0; let previousDescent:number = 0; let previousBottom:number = 0; let previousLeading:number = 0; let needUpdateMetrics:boolean = (fmi != null); if (needUpdateMetrics) { previousTop = fmi.top; previousAscent = fmi.ascent; previousDescent = fmi.descent; previousBottom = fmi.bottom; previousLeading = fmi.leading; } ret = replacement.getSize(wp, this.mText, textStart, textLimit, fmi); if (needUpdateMetrics) { TextLine.updateMetrics(fmi, previousTop, previousAscent, previousDescent, previousBottom, previousLeading); } } if (c != null) { if (runIsRtl) { x -= ret; } replacement.draw(c, this.mText, textStart, textLimit, x, top, y, bottom, wp); } return runIsRtl ? -ret : ret; } /** * Utility function for handling a unidirectional run. The run must not * contain tabs or emoji but can contain styles. * * * @param start the line-relative start of the run * @param measureLimit the offset to measure to, between start and limit inclusive * @param limit the limit of the run * @param runIsRtl true if the run is right-to-left * @param c the canvas, can be null * @param x the end of the run closest to the leading margin * @param top the top of the line * @param y the baseline * @param bottom the bottom of the line * @param fmi receives metrics information, can be null * @param needWidth true if the width is required * @return the signed width of the run based on the run direction; only * valid if needWidth is true */ private handleRun(start:number, measureLimit:number, limit:number, runIsRtl:boolean, c:Canvas, x:number, top:number, y:number, bottom:number, fmi:FontMetricsInt, needWidth:boolean):number { // Case of an empty line, make sure we update fmi according to mPaint if (start == measureLimit) { let wp:TextPaint = this.mWorkPaint; wp.set(this.mPaint); if (fmi != null) { TextLine.expandMetricsFromPaint(fmi, wp); } return 0; } if (this.mSpanned == null) { let wp:TextPaint = this.mWorkPaint; wp.set(this.mPaint); const mlimit:number = measureLimit; return this.handleText(wp, start, mlimit, start, limit, runIsRtl, c, x, top, y, bottom, fmi, needWidth || mlimit < measureLimit); } this.mMetricAffectingSpanSpanSet.init(this.mSpanned, this.mStart + start, this.mStart + limit); this.mCharacterStyleSpanSet.init(this.mSpanned, this.mStart + start, this.mStart + limit); // Shaping needs to take into account context up to metric boundaries, // but rendering needs to take into account character style boundaries. // So we iterate through metric runs to get metric bounds, // then within each metric run iterate through character style runs // for the run bounds. const originalX:number = x; for (let i:number = start, inext:number; i < measureLimit; i = inext) { let wp:TextPaint = this.mWorkPaint; wp.set(this.mPaint); inext = this.mMetricAffectingSpanSpanSet.getNextTransition(this.mStart + i, this.mStart + limit) - this.mStart; let mlimit:number = Math.min(inext, measureLimit); let replacement:ReplacementSpan = null; for (let j:number = 0; j < this.mMetricAffectingSpanSpanSet.numberOfSpans; j++) { // empty by construction. This special case in getSpans() explains the >= & <= tests if ((this.mMetricAffectingSpanSpanSet.spanStarts[j] >= this.mStart + mlimit) || (this.mMetricAffectingSpanSpanSet.spanEnds[j] <= this.mStart + i)) continue; let span:MetricAffectingSpan = this.mMetricAffectingSpanSpanSet.spans[j]; if (span instanceof ReplacementSpan) { replacement = <ReplacementSpan> span; } else { // We might have a replacement that uses the draw // state, otherwise measure state would suffice. span.updateDrawState(wp); } } if (replacement != null) { x += this.handleReplacement(replacement, wp, i, mlimit, runIsRtl, c, x, top, y, bottom, fmi, needWidth || mlimit < measureLimit); continue; } for (let j:number = i, jnext:number; j < mlimit; j = jnext) { jnext = this.mCharacterStyleSpanSet.getNextTransition(this.mStart + j, this.mStart + mlimit) - this.mStart; wp.set(this.mPaint); for (let k:number = 0; k < this.mCharacterStyleSpanSet.numberOfSpans; k++) { // Intentionally using >= and <= as explained above if ((this.mCharacterStyleSpanSet.spanStarts[k] >= this.mStart + jnext) || (this.mCharacterStyleSpanSet.spanEnds[k] <= this.mStart + j)) continue; let span:CharacterStyle = this.mCharacterStyleSpanSet.spans[k]; span.updateDrawState(wp); } x += this.handleText(wp, j, jnext, i, inext, runIsRtl, c, x, top, y, bottom, fmi, needWidth || jnext < measureLimit); } } return x - originalX; } /** * Render a text run with the set-up paint. * * @param c the canvas * @param wp the paint used to render the text * @param start the start of the run * @param end the end of the run * @param contextStart the start of context for the run * @param contextEnd the end of the context for the run * @param runIsRtl true if the run is right-to-left * @param x the x position of the left edge of the run * @param y the baseline of the run */ private drawTextRun(c:Canvas, wp:TextPaint, start:number, end:number, contextStart:number, contextEnd:number, runIsRtl:boolean, x:number, y:number):void { let flags:number = runIsRtl ? Canvas.DIRECTION_RTL : Canvas.DIRECTION_LTR; if (this.mCharsValid) { let count:number = end - start; let contextCount:number = contextEnd - contextStart; c.drawTextRun_count(this.mChars.toString(), start, count, contextStart, contextCount, x, y, flags, wp); } else { let delta:number = this.mStart; c.drawTextRun_end(this.mText.toString(), delta + start, delta + end, delta + contextStart, delta + contextEnd, x, y, flags, wp); } } /** * Returns the ascent of the text at start. This is used for scaling * emoji. * * @param pos the line-relative position * @return the ascent of the text at start */ ascent(pos:number):number { if (this.mSpanned == null) { return this.mPaint.ascent(); } pos += this.mStart; let spans:MetricAffectingSpan[] = this.mSpanned.getSpans<MetricAffectingSpan>(pos, pos + 1, MetricAffectingSpan.type); if (spans.length == 0) { return this.mPaint.ascent(); } let wp:TextPaint = this.mWorkPaint; wp.set(this.mPaint); for (let span of spans) { span.updateMeasureState(wp); } return wp.ascent(); } /** * Returns the next tab position. * * @param h the (unsigned) offset from the leading margin * @return the (unsigned) tab position after this offset */ nextTab(h:number):number { if (this.mTabs != null) { return this.mTabs.nextTab(h); } return Layout.TabStops.nextDefaultStop(h, TextLine.TAB_INCREMENT); } private static TAB_INCREMENT:number = 20; } }
the_stack
// Oracledb Client // ------- import _ from '../../deps/lodash@4.17.15/index.js'; const each = _.each; const flatten = _.flatten; const isEmpty = _.isEmpty; const isString = _.isString; const map = _.map; const values = _.values; import inherits from '../../deps/inherits@2.0.4/inherits.js'; import QueryCompiler from './query/compiler.js'; import ColumnCompiler from './schema/columncompiler.js'; import { BlobHelper } from './utils.js'; import Utils from './utils.js'; const ReturningHelper = Utils.ReturningHelper; const isConnectionError = Utils.isConnectionError; import stream from '../../deps/@jspm/core@1.1.0/nodelibs/stream.js'; import { promisify } from '../../deps/@jspm/core@1.1.0/nodelibs/util.js'; import Transaction from './transaction.js'; import Client_Oracle from '../oracle/index.js'; import Oracle_Formatter from '../oracle/formatter.js'; function Client_Oracledb() { Client_Oracle.apply(this, arguments); // Node.js only have 4 background threads by default, oracledb needs one by connection if (this.driver) { process.env.UV_THREADPOOL_SIZE = process.env.UV_THREADPOOL_SIZE || 1; process.env.UV_THREADPOOL_SIZE = parseInt(process.env.UV_THREADPOOL_SIZE) + this.driver.poolMax; } } inherits(Client_Oracledb, Client_Oracle); Client_Oracledb.prototype.driverName = 'oracledb'; Client_Oracledb.prototype._driver = function () { const client = this; const oracledb = require('oracledb'); client.fetchAsString = []; if (this.config.fetchAsString && Array.isArray(this.config.fetchAsString)) { this.config.fetchAsString.forEach(function (type) { if (!isString(type)) return; type = type.toUpperCase(); if (oracledb[type]) { if ( type !== 'NUMBER' && type !== 'DATE' && type !== 'CLOB' && type !== 'BUFFER' ) { this.logger.warn( 'Only "date", "number", "clob" and "buffer" are supported for fetchAsString' ); } client.fetchAsString.push(oracledb[type]); } }); } return oracledb; }; Client_Oracledb.prototype.queryCompiler = function () { return new QueryCompiler(this, ...arguments); }; Client_Oracledb.prototype.columnCompiler = function () { return new ColumnCompiler(this, ...arguments); }; Client_Oracledb.prototype.formatter = function () { return new Oracledb_Formatter(this, ...arguments); }; Client_Oracledb.prototype.transaction = function () { return new Transaction(this, ...arguments); }; Client_Oracledb.prototype.prepBindings = function (bindings) { return map(bindings, (value) => { if (value instanceof BlobHelper && this.driver) { return { type: this.driver.BLOB, dir: this.driver.BIND_OUT }; // Returning helper always use ROWID as string } else if (value instanceof ReturningHelper && this.driver) { return { type: this.driver.STRING, dir: this.driver.BIND_OUT }; } else if (typeof value === 'boolean') { return value ? 1 : 0; } return value; }); }; // Get a raw connection, called by the `pool` whenever a new // connection needs to be added to the pool. Client_Oracledb.prototype.acquireRawConnection = function () { const client = this; const asyncConnection = new Promise(function (resolver, rejecter) { // If external authentication don't have to worry about username/password and // if not need to set the username and password const oracleDbConfig = client.connectionSettings.externalAuth ? { externalAuth: client.connectionSettings.externalAuth } : { user: client.connectionSettings.user, password: client.connectionSettings.password, }; // In the case of external authentication connection string will be given oracleDbConfig.connectString = client.connectionSettings.connectString || client.connectionSettings.host + '/' + client.connectionSettings.database; if (client.connectionSettings.prefetchRowCount) { oracleDbConfig.prefetchRows = client.connectionSettings.prefetchRowCount; } if (client.connectionSettings.stmtCacheSize !== undefined) { oracleDbConfig.stmtCacheSize = client.connectionSettings.stmtCacheSize; } client.driver.fetchAsString = client.fetchAsString; client.driver.getConnection(oracleDbConfig, function (err, connection) { if (err) { return rejecter(err); } connection.commitAsync = function () { return new Promise((commitResolve, commitReject) => { this.commit(function (err) { if (err) { return commitReject(err); } commitResolve(); }); }); }; connection.rollbackAsync = function () { return new Promise((rollbackResolve, rollbackReject) => { this.rollback(function (err) { if (err) { return rollbackReject(err); } rollbackResolve(); }); }); }; const fetchAsync = promisify(function (sql, bindParams, options, cb) { options = options || {}; options.outFormat = client.driver.OUT_FORMAT_OBJECT || client.driver.OBJECT; if (!options.outFormat) { throw new Error('not found oracledb.outFormat constants'); } if (options.resultSet) { connection.execute(sql, bindParams || [], options, function ( err, result ) { if (err) { if (isConnectionError(err)) { connection.close().catch(function (err) {}); connection.__knex__disposed = err; } return cb(err); } const fetchResult = { rows: [], resultSet: result.resultSet }; const numRows = 100; const fetchRowsFromRS = function (connection, resultSet, numRows) { resultSet.getRows(numRows, function (err, rows) { if (err) { if (isConnectionError(err)) { connection.close().catch(function (err) {}); connection.__knex__disposed = err; } resultSet.close(function () { return cb(err); }); } else if (rows.length === 0) { return cb(null, fetchResult); } else if (rows.length > 0) { if (rows.length === numRows) { fetchResult.rows = fetchResult.rows.concat(rows); fetchRowsFromRS(connection, resultSet, numRows); } else { fetchResult.rows = fetchResult.rows.concat(rows); return cb(null, fetchResult); } } }); }; fetchRowsFromRS(connection, result.resultSet, numRows); }); } else { connection.execute(sql, bindParams || [], options, function ( err, result ) { if (err) { // dispose the connection on connection error if (isConnectionError(err)) { connection.close().catch(function (err) {}); connection.__knex__disposed = err; } return cb(err); } return cb(null, result); }); } }); connection.executeAsync = function (sql, bindParams, options) { // Read all lob return fetchAsync(sql, bindParams, options).then(async (results) => { const closeResultSet = () => { return results.resultSet ? promisify(results.resultSet.close).call(results.resultSet) : Promise.resolve(); }; // Collect LOBs to read const lobs = []; if (results.rows) { if (Array.isArray(results.rows)) { for (let i = 0; i < results.rows.length; i++) { // Iterate through the rows const row = results.rows[i]; for (const column in row) { if (row[column] instanceof stream.Readable) { lobs.push({ index: i, key: column, stream: row[column] }); } } } } } try { for (const lob of lobs) { // todo should be fetchAsString/fetchAsBuffer polyfill only results.rows[lob.index][lob.key] = await lobProcessing( lob.stream ); } } catch (e) { await closeResultSet().catch(() => {}); throw e; } await closeResultSet(); return results; }); }; resolver(connection); }); }); return asyncConnection; }; // Used to explicitly close a connection, called internally by the pool // when a connection times out or the pool is shutdown. Client_Oracledb.prototype.destroyRawConnection = function (connection) { return connection.release(); }; // Runs the query on the specified connection, providing the bindings // and any other necessary prep work. Client_Oracledb.prototype._query = function (connection, obj) { if (!obj.sql) throw new Error('The query is empty'); const options = { autoCommit: false }; if (obj.method === 'select') { options.resultSet = true; } return connection .executeAsync(obj.sql, obj.bindings, options) .then(async function (response) { // Flatten outBinds let outBinds = flatten(response.outBinds); obj.response = response.rows || []; obj.rowsAffected = response.rows ? response.rows.rowsAffected : response.rowsAffected; //added for outBind parameter if (obj.method === 'raw' && outBinds.length > 0) { return { response: outBinds, }; } if (obj.method === 'update') { const modifiedRowsCount = obj.rowsAffected.length || obj.rowsAffected; const updatedObjOutBinding = []; const updatedOutBinds = []; const updateOutBinds = (i) => function (value, index) { const OutBindsOffset = index * modifiedRowsCount; updatedOutBinds.push(outBinds[i + OutBindsOffset]); }; for (let i = 0; i < modifiedRowsCount; i++) { updatedObjOutBinding.push(obj.outBinding[0]); each(obj.outBinding[0], updateOutBinds(i)); } outBinds = updatedOutBinds; obj.outBinding = updatedObjOutBinding; } if (!obj.returning && outBinds.length === 0) { if (!connection.isTransaction) { await connection.commitAsync(); } return obj; } const rowIds = []; let offset = 0; for (let line = 0; line < obj.outBinding.length; line++) { const ret = obj.outBinding[line]; offset = offset + (obj.outBinding[line - 1] ? obj.outBinding[line - 1].length : 0); for (let index = 0; index < ret.length; index++) { const out = ret[index]; await new Promise(function (bindResolver, bindRejecter) { if (out instanceof BlobHelper) { const blob = outBinds[index + offset]; if (out.returning) { obj.response[line] = obj.response[line] || {}; obj.response[line][out.columnName] = out.value; } blob.on('error', function (err) { bindRejecter(err); }); blob.on('finish', function () { bindResolver(); }); blob.write(out.value); blob.end(); } else if (obj.outBinding[line][index] === 'ROWID') { rowIds.push(outBinds[index + offset]); bindResolver(); } else { obj.response[line] = obj.response[line] || {}; obj.response[line][out] = outBinds[index + offset]; bindResolver(); } }); } } if (connection.isTransaction) { return obj; } await connection.commitAsync(); if (obj.returningSql) { const response = await connection.executeAsync( obj.returningSql(), rowIds, { resultSet: true } ); obj.response = response.rows; } return obj; }); }; /** * @param stream * @param {'string' | 'buffer'} type */ function readStream(stream, type) { return new Promise((resolve, reject) => { let data = type === 'string' ? '' : Buffer.alloc(0); stream.on('error', function (err) { reject(err); }); stream.on('data', function (chunk) { if (type === 'string') { data += chunk; } else { data = Buffer.concat([data, chunk]); } }); stream.on('end', function () { resolve(data); }); }); } // Process the response as returned from the query. Client_Oracledb.prototype.processResponse = function (obj, runner) { let response = obj.response; const method = obj.method; if (obj.output) { return obj.output.call(runner, response); } switch (method) { case 'select': case 'pluck': case 'first': if (obj.method === 'pluck') { response = map(response, obj.pluck); } return obj.method === 'first' ? response[0] : response; case 'insert': case 'del': case 'update': case 'counter': if (obj.returning && !isEmpty(obj.returning)) { if (obj.returning.length === 1 && obj.returning[0] !== '*') { return flatten(map(response, values)); } return response; } else if (obj.rowsAffected !== undefined) { return obj.rowsAffected; } else { return 1; } default: return response; } }; const lobProcessing = function (stream) { const oracledb = require('oracledb'); /** * @type 'string' | 'buffer' */ let type; if (stream.type) { // v1.2-v4 if (stream.type === oracledb.BLOB) { type = 'buffer'; } else if (stream.type === oracledb.CLOB) { type = 'string'; } } else if (stream.iLob) { // v1 if (stream.iLob.type === oracledb.CLOB) { type = 'string'; } else if (stream.iLob.type === oracledb.BLOB) { type = 'buffer'; } } else { throw new Error('Unrecognized oracledb lob stream type'); } if (type === 'string') { stream.setEncoding('utf-8'); } return readStream(stream, type); }; class Oracledb_Formatter extends Oracle_Formatter { // Checks whether a value is a function... if it is, we compile it // otherwise we check whether it's a raw parameter(value) { if (typeof value === 'function') { return this.outputQuery(this.compileCallback(value), true); } else if (value instanceof BlobHelper) { return 'EMPTY_BLOB()'; } return this.unwrapRaw(value, true) || '?'; } } export default Client_Oracledb;
the_stack
import { LOCALE_ID } from '@angular/core'; import { inject, TestBed, waitForAsync } from '@angular/core/testing'; import { DateAdapter, MC_DATE_LOCALE } from '@ptsecurity/cdk/datetime'; import * as moment from 'moment'; // tslint:disable-next-line:no-duplicate-imports import { MC_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateModule } from './index'; import { MomentDateAdapter } from './moment-date-adapter'; // tslint:disable:one-variable-per-declaration const JAN = 0, FEB = 1, MAR = 2, DEC = 11; describe('MomentDateAdapter', () => { let adapter: MomentDateAdapter; let assertValidDate: (d: moment.Moment | null, valid: boolean) => void; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MomentDateModule] }).compileComponents(); })); beforeEach(inject([DateAdapter], (dateAdapter: MomentDateAdapter) => { moment.locale('en'); adapter = dateAdapter; adapter.setLocale('en'); assertValidDate = (d: moment.Moment | null, valid: boolean) => { expect(adapter.isDateInstance(d)).not.toBeNull(`Expected ${d} to be a date instance`); expect(adapter.isValid(d!)).toBe( valid, `Expected ${d} to be ${valid ? 'valid' : 'invalid'}, but was ${valid ? 'invalid' : 'valid'}` ); }; })); it('should get year', () => { expect(adapter.getYear(moment([2017, JAN, 1]))).toBe(2017); }); it('should get month', () => { expect(adapter.getMonth(moment([2017, JAN, 1]))).toBe(0); }); it('should get date', () => { expect(adapter.getDate(moment([2017, JAN, 1]))).toBe(1); }); it('should get day of week', () => { expect(adapter.getDayOfWeek(moment([2017, JAN, 1]))).toBe(0); }); it('should get same day of week in a locale with a different first day of the week', () => { adapter.setLocale('fr'); expect(adapter.getDayOfWeek(moment([2017, JAN, 1]))).toBe(0); }); it('should get long month names', () => { expect(adapter.getMonthNames('long')).toEqual([ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]); }); it('should get short month names ru', () => { adapter.setLocale('ru'); expect(adapter.getMonthNames('short')).toEqual([ 'янв', 'фев', 'март', 'апр', 'май', 'июнь', 'июль', 'авг', 'сен', 'окт', 'ноя', 'дек' ]); }); it('should get long month names en', () => { adapter.setLocale('en'); expect(adapter.getMonthNames('short')).toEqual([ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]); }); it('should get date names', () => { expect(adapter.getDateNames()).toEqual([ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31' ]); }); it('should get date names in a different locale', () => { adapter.setLocale('ar-AE'); expect(adapter.getDateNames()).toEqual([ '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩', '١٠', '١١', '١٢', '١٣', '١٤', '١٥', '١٦', '١٧', '١٨', '١٩', '٢٠', '٢١', '٢٢', '٢٣', '٢٤', '٢٥', '٢٦', '٢٧', '٢٨', '٢٩', '٣٠', '٣١' ]); }); it('should get date names in a different locale', () => { adapter.setLocale('ru'); expect(adapter.getDateNames()).toEqual([ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31' ]); }); it('should get long day of week names for ru', () => { adapter.setLocale('ru'); expect(adapter.getDayOfWeekNames('long')).toEqual([ 'Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота' ]); }); it('should get day of week names for en', () => { adapter.setLocale('en'); expect(adapter.getDayOfWeekNames('long')).toEqual([ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]); expect(adapter.getDayOfWeekNames('short')).toEqual([ 'Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa' ]); expect(adapter.getDayOfWeekNames('narrow')).toEqual([ 'S', 'M', 'T', 'W', 'T', 'F', 'S' ]); }); it('should get day of week names in a different locale', () => { adapter.setLocale('ja-JP'); expect(adapter.getDayOfWeekNames('long')).toEqual([ '日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日' ]); }); it('should get day of week names in a different locale', () => { adapter.setLocale('ru'); expect(adapter.getDayOfWeekNames('long')).toEqual([ 'Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота' ]); expect(adapter.getDayOfWeekNames('short')).toEqual([ 'Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ]); expect(adapter.getDayOfWeekNames('narrow')).toEqual([ 'В', 'П', 'В', 'С', 'Ч', 'П', 'С' ]); }); it('should get year name', () => { expect(adapter.getYearName(moment([2017, JAN, 1]))).toBe('2017'); }); it('should get year name in a different locale', () => { adapter.setLocale('ar-AE'); expect(adapter.getYearName(moment([2017, JAN, 1]))).toBe('٢٠١٧'); }); it('should get first day of week in a different locale', () => { adapter.setLocale('fr'); expect(adapter.getFirstDayOfWeek()).toBe(1); }); it('should get first day of week for ru', () => { adapter.setLocale('ru'); expect(adapter.getFirstDayOfWeek()).toBe(1); }); it('should create Moment date', () => { expect(adapter.createDate(2017, JAN, 1).format()) .toEqual(moment([2017, JAN, 1]).format()); }); it('should not create Moment date with month over/under-flow', () => { expect(() => adapter.createDate(2017, DEC + 1, 1)).toThrow(); expect(() => adapter.createDate(2017, JAN - 1, 1)).toThrow(); }); it('should not create Moment date with date over/under-flow', () => { expect(() => adapter.createDate(2017, JAN, 32)).toThrow(); expect(() => adapter.createDate(2017, JAN, 0)).toThrow(); }); it('should create Moment date with low year number', () => { expect(adapter.createDate(-1, JAN, 1).year()).toBe(-1); expect(adapter.createDate(0, JAN, 1).year()).toBe(0); expect(adapter.createDate(50, JAN, 1).year()).toBe(50); expect(adapter.createDate(99, JAN, 1).year()).toBe(99); expect(adapter.createDate(100, JAN, 1).year()).toBe(100); }); it('should not create Moment date in utc format', () => { expect(adapter.createDate(2017, JAN, 5).isUTC()).toEqual(false); }); it('should get today\'s date', () => { expect(adapter.sameDate(adapter.today(), moment())) .toBe(true, 'should be equal to today\'s date'); }); it('should parse string according to given format', () => { expect(adapter.parse('1/2/2017', 'MM/DD/YYYY')!.format()) .toEqual(moment([2017, JAN, 2]).format()); expect(adapter.parse('1/2/2017', 'DD/MM/YYYY')!.format()) .toEqual(moment([2017, FEB, 1]).format()); }); it('should parse number', () => { const timestamp = new Date().getTime(); expect(adapter.parse(timestamp, 'MM/DD/YYYY')!.format()).toEqual(moment(timestamp).format()); }); it('should parse invalid value as invalid', () => { const d = adapter.parse('hello', 'MM/DD/YYYY'); expect(d).not.toBeNull(); expect(adapter.isDateInstance(d)) .toBe(true, 'Expected string to have been fed through Date.parse'); expect(adapter.isValid(d as moment.Moment)) .toBe(false, 'Expected to parse as "invalid date" object'); }); it('should format date according to given format', () => { expect(adapter.format(moment([2017, JAN, 2]), 'MM/DD/YYYY')).toEqual('01/02/2017'); expect(adapter.format(moment([2017, JAN, 2]), 'DD/MM/YYYY')).toEqual('02/01/2017'); }); it('should throw when attempting to format invalid date', () => { expect(() => adapter.format(moment(NaN), 'MM/DD/YYYY')) .toThrowError(/MomentDateAdapter: Cannot format invalid date\./); }); it('should add years', () => { expect(adapter.addCalendarYears(moment([2017, JAN, 1]), 1).format()) .toEqual(moment([2018, JAN, 1]).format()); expect(adapter.addCalendarYears(moment([2017, JAN, 1]), -1).format()) .toEqual(moment([2016, JAN, 1]).format()); }); it('should respect leap years when adding years', () => { expect(adapter.addCalendarYears(moment([2016, FEB, 29]), 1).format()) .toEqual(moment([2017, FEB, 28]).format()); expect(adapter.addCalendarYears(moment([2016, FEB, 29]), -1).format()) .toEqual(moment([2015, FEB, 28]).format()); }); it('should add months', () => { expect(adapter.addCalendarMonths(moment([2017, JAN, 1]), 1).format()) .toEqual(moment([2017, FEB, 1]).format()); expect(adapter.addCalendarMonths(moment([2017, JAN, 1]), -1).format()) .toEqual(moment([2016, DEC, 1]).format()); }); it('should respect month length differences when adding months', () => { expect(adapter.addCalendarMonths(moment([2017, JAN, 31]), 1).format()) .toEqual(moment([2017, FEB, 28]).format()); expect(adapter.addCalendarMonths(moment([2017, MAR, 31]), -1).format()) .toEqual(moment([2017, FEB, 28]).format()); }); it('should add days', () => { expect(adapter.addCalendarDays(moment([2017, JAN, 1]), 1).format()) .toEqual(moment([2017, JAN, 2]).format()); expect(adapter.addCalendarDays(moment([2017, JAN, 1]), -1).format()) .toEqual(moment([2016, DEC, 31]).format()); }); it('should clone', () => { const date = moment([2017, JAN, 1]); expect(adapter.clone(date).format()).toEqual(date.format()); expect(adapter.clone(date)).not.toBe(date); }); it('should compare dates', () => { expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, JAN, 2]))).toBeLessThan(0); expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, FEB, 1]))).toBeLessThan(0); expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2018, JAN, 1]))).toBeLessThan(0); expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, JAN, 1]))).toBe(0); expect(adapter.compareDate(moment([2018, JAN, 1]), moment([2017, JAN, 1]))).toBeGreaterThan(0); expect(adapter.compareDate(moment([2017, FEB, 1]), moment([2017, JAN, 1]))).toBeGreaterThan(0); expect(adapter.compareDate(moment([2017, JAN, 2]), moment([2017, JAN, 1]))).toBeGreaterThan(0); }); it('should clamp date at lower bound', () => { expect(adapter.clampDate( moment([2017, JAN, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1]))) .toEqual(moment([2018, JAN, 1])); }); it('should clamp date at upper bound', () => { expect(adapter.clampDate( moment([2020, JAN, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1]))) .toEqual(moment([2019, JAN, 1])); }); it('should clamp date already within bounds', () => { expect(adapter.clampDate( moment([2018, FEB, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1]))) .toEqual(moment([2018, FEB, 1])); }); it('should count today as a valid date instance', () => { const d = moment(); expect(adapter.isValid(d)).toBe(true); expect(adapter.isDateInstance(d)).toBe(true); }); it('should count an invalid date as an invalid date instance', () => { const d = moment(NaN); expect(adapter.isValid(d)).toBe(false); expect(adapter.isDateInstance(d)).toBe(true); }); it('should count a string as not a date instance', () => { const d = '1/1/2019'; expect(adapter.isDateInstance(d)).toBe(false); }); it('should create valid dates from valid ISO strings', () => { assertValidDate(adapter.deserialize('1985-04-12T23:20:50.52Z'), true); assertValidDate(adapter.deserialize('1996-12-19T16:39:57-08:00'), true); assertValidDate(adapter.deserialize('1937-01-01T12:00:27.87+00:20'), true); assertValidDate(adapter.deserialize('1990-13-31T23:59:00Z'), false); assertValidDate(adapter.deserialize('1/1/2017'), false); expect(adapter.deserialize('')).toBeNull(); expect(adapter.deserialize(null)).toBeNull(); assertValidDate(adapter.deserialize(new Date()), true); assertValidDate(adapter.deserialize(new Date(NaN)), false); assertValidDate(adapter.deserialize(moment()), true); assertValidDate(adapter.deserialize(moment.invalid()), false); }); it('should clone the date when deserializing a Moment date', () => { const date = moment([2017, JAN, 1]); expect(adapter.deserialize(date)!.format()).toEqual(date.format()); expect(adapter.deserialize(date)).not.toBe(date); }); it('should deserialize dates with the correct locale', () => { adapter.setLocale('ja'); expect(adapter.deserialize('1985-04-12T23:20:50.52Z')!.locale()).toBe('ja'); expect(adapter.deserialize(new Date())!.locale()).toBe('ja'); expect(adapter.deserialize(moment())!.locale()).toBe('ja'); }); it('should create an invalid date', () => { assertValidDate(adapter.invalid(), false); }); it('setLocale should not modify global moment locale', () => { expect(moment.locale()).toBe('en'); adapter.setLocale('ja-JP'); expect(moment.locale()).toBe('en'); }); it('returned Moments should have correct locale', () => { adapter.setLocale('ja-JP'); expect(adapter.createDate(2017, JAN, 1).locale()).toBe('ja'); expect(adapter.today().locale()).toBe('ja'); expect(adapter.clone(moment()).locale()).toBe('ja'); expect(adapter.parse('1/1/2017', 'MM/DD/YYYY')!.locale()).toBe('ja'); expect(adapter.addCalendarDays(moment(), 1).locale()).toBe('ja'); expect(adapter.addCalendarMonths(moment(), 1).locale()).toBe('ja'); expect(adapter.addCalendarYears(moment(), 1).locale()).toBe('ja'); }); }); describe('MomentDateAdapter findDateFormat = true', () => { let adapter: MomentDateAdapter; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MomentDateModule], providers: [{ provide: MC_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {findDateFormat: true} }] }).compileComponents(); })); beforeEach(inject([DateAdapter], (dateAdapter: MomentDateAdapter) => { moment.locale('en'); adapter = dateAdapter; adapter.setLocale('en'); })); it('should parse ISO', () => { adapter.setLocale('ru'); const utcDate = new Date(2019, 5, 3, 14, 50, 30); utcDate.setMinutes(utcDate.getMinutes() - utcDate.getTimezoneOffset()); expect(adapter.parse('2019-06-03T14:50:30.000Z', '')!.toDate()) .toEqual(utcDate); }); it('should parse dashed date', () => { adapter.setLocale('ru'); // finishing year expect(adapter.parse('03-06-2019', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); expect(adapter.parse('03-06-19', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); // leading year expect(adapter.parse('2019-06-03', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); adapter.setLocale('en'); // finishing year expect(adapter.parse('03-06-2019', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); // short year expect(adapter.parse('03-06-19', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); // leading year expect(adapter.parse('2019-06-03', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); }); it('should parse slashed date', () => { adapter.setLocale('ru'); expect(adapter.parse('03/06/2019', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); // short year expect(adapter.parse('03/06/19', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); adapter.setLocale('en'); // US by default expect(adapter.parse('03/06/2019', '')!.toDate()) .toEqual(new Date(2019, 2, 6)); // short year expect(adapter.parse('03/06/19', '')!.toDate()) .toEqual(new Date(2019, 2, 6)); // month order guessing expect(adapter.parse('23/06/2019', '')!.toDate()) .toEqual(new Date(2019, 5, 23)); }); it('should parse doted date', () => { adapter.setLocale('ru'); expect(adapter.parse('03.06.2019', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); expect(adapter.parse('03.06.19', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); adapter.setLocale('en'); expect(adapter.parse('03.06.2019', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); expect(adapter.parse('03.06.19', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); }); it('should parse long formatted date', () => { adapter.setLocale('ru'); expect(adapter.parse('3 июня 2019', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); expect(adapter.parse('6 фев 2019', '')!.toDate()) .toEqual(new Date(2019, 1, 6)); adapter.setLocale('en'); expect(adapter.parse('June 3rd 2019', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); expect(adapter.parse('Feb 6th 2019', '')!.toDate()) .toEqual(new Date(2019, 1, 6)); expect(adapter.parse('3 June 2019', '')!.toDate()) .toEqual(new Date(2019, 5, 3)); expect(adapter.parse('6 Feb 2019', '')!.toDate()) .toEqual(new Date(2019, 1, 6)); }); it('should parse unix timestamp', () => { adapter.setLocale('ru'); const utcDate = new Date(2019, 5, 3, 14, 50, 30); utcDate.setMinutes(utcDate.getMinutes() - utcDate.getTimezoneOffset()); expect(adapter.parse('1559573430', '')!.toDate()) .toEqual(utcDate); }); }); describe('MomentDateAdapter with MC_DATE_LOCALE override', () => { let adapter: MomentDateAdapter; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MomentDateModule ], providers: [{ provide: MC_DATE_LOCALE, useValue: 'ja-JP' }] }).compileComponents(); })); beforeEach(inject([DateAdapter], (d: MomentDateAdapter) => { adapter = d; })); it('should take the default locale id from the MC_DATE_LOCALE injection token', () => { expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('2017年1月2日'); }); }); describe('MomentDateAdapter with LOCALE_ID override', () => { let adapter: MomentDateAdapter; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MomentDateModule], providers: [{ provide: LOCALE_ID, useValue: 'fr' }] }).compileComponents(); })); beforeEach(inject([DateAdapter], (d: MomentDateAdapter) => { adapter = d; })); it('should cascade locale id from the LOCALE_ID injection token to MC_DATE_LOCALE', () => { expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('2 janv. 2017'); }); }); describe('MomentDateAdapter with MC_MOMENT_DATE_ADAPTER_OPTIONS override', () => { let adapter: MomentDateAdapter; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MomentDateModule], providers: [{ provide: MC_MOMENT_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true} }] }).compileComponents(); })); beforeEach(inject([DateAdapter], (d: MomentDateAdapter) => { adapter = d; })); describe('use UTC', () => { it('should create Moment date in UTC', () => { expect(adapter.createDate(2017, JAN, 5).isUTC()).toBe(true); }); it('should create today in UTC', () => { expect(adapter.today().isUTC()).toBe(true); }); it('should parse dates to UTC', () => { expect(adapter.parse('1/2/2017', 'MM/DD/YYYY')!.isUTC()).toBe(true); }); it('should return UTC date when deserializing', () => { expect(adapter.deserialize('1985-04-12T23:20:50.52Z')!.isUTC()).toBe(true); }); }); });
the_stack
const { stdout, stderr } = Deno; import { encode } from 'https://deno.land/std@0.63.0/encoding/utf8.ts'; import { dim, red } from 'https://deno.land/std@0.63.0/fmt/colors.ts'; import { parseFlags } from '../../flags/lib/flags.ts'; import { IFlagArgument, IFlagOptions, IFlagsResult, IFlagValue, IFlagValueHandler, IFlagValueType, ITypeHandler } from '../../flags/lib/types.ts'; import { fill } from '../../flags/lib/utils.ts'; import format from '../../x/format.ts'; import { BooleanType } from '../types/boolean.ts'; import { NumberType } from '../types/number.ts'; import { StringType } from '../types/string.ts'; import { Type } from '../types/type.ts'; import { ArgumentsParser } from './arguments-parser.ts'; import { HelpGenerator } from './help-generator.ts'; import { IAction, IArgumentDetails, ICommandOption, ICompleteHandler, ICompleteOptions, ICompleteSettings, IDescription, IEnvVariable, IEnvVarOption, IExample, IOption, IParseResult, ITypeMap, ITypeOption, ITypeSettings } from './types.ts'; const permissions: any = ( Deno as any ).permissions; const envPermissionStatus: any = permissions && permissions.query && await permissions.query( { name: 'env' } ); const hasEnvPermissions: boolean = !!envPermissionStatus && envPermissionStatus.state === 'granted'; interface IDefaultOption<O = any, A extends Array<any> = any> { flags: string; desc?: string opts?: ICommandOption<O, A>; } /** * Base command implementation without pre configured command's and option's. */ export class Command<O = any, A extends Array<any> = any> { private types: ITypeMap = new Map<string, ITypeSettings>( [ [ 'string', { name: 'string', handler: new StringType() } ], [ 'number', { name: 'number', handler: new NumberType() } ], [ 'boolean', { name: 'boolean', handler: new BooleanType() } ] ] ); private rawArgs: string[] = []; private literalArgs: string[] = []; // @TODO: get script name: https://github.com/denoland/deno/pull/5034 // private name: string = location.pathname.split( '/' ).pop() as string; private _name: string = 'COMMAND'; private _parent?: Command; private _globalParent?: Command; private ver: string = '0.0.0'; private desc: IDescription = ''; private fn?: IAction<O, A>; private options: IOption<O, A>[] = []; private commands: Map<string, Command> = new Map(); private examples: IExample[] = []; private envVars: IEnvVariable[] = []; private aliases: string[] = []; private completions: Map<string, ICompleteSettings> = new Map(); private cmd: Command = this; private argsDefinition?: string; private isExecutable: boolean = false; private throwOnError: boolean = false; private _allowEmpty: boolean = true; private _stopEarly: boolean = false; private defaultCommand?: string; private _useRawArgs: boolean = false; private args: IArgumentDetails[] = []; private isHidden: boolean = false; private isGlobal: boolean = false; private hasDefaults: Boolean = false; private _versionOption?: IDefaultOption<O, A> | false; private _helpOption?: IDefaultOption<O, A> | false; public versionOption( flags: string | false, desc?: string, opts?: IAction<O, A> | ICommandOption<O, A> ): this { this._versionOption = flags === false ? flags : { flags, desc, opts: typeof opts === 'function' ? { action: opts } : opts }; return this; } public helpOption( flags: string | false, desc?: string, opts?: IAction<O, A> | ICommandOption<O, A> ): this { this._helpOption = flags === false ? flags : { flags, desc, opts: typeof opts === 'function' ? { action: opts } : opts }; return this; } /** * Add new sub-command. */ public command( nameAndArguments: string, cmd?: Command | string, override?: boolean ): this { let executableDescription: string | undefined; if ( typeof cmd === 'string' ) { executableDescription = cmd; cmd = undefined; } const result = ArgumentsParser.splitArguments( nameAndArguments ); const name: string | undefined = result.args.shift(); const aliases: string[] = result.args; if ( !name ) { throw this.error( new Error( 'Missing command name.' ) ); } if ( this.getBaseCommand( name, true ) ) { if ( !override ) { throw this.error( new Error( `Duplicate command: ${ name }` ) ); } this.removeCommand( name ); } const subCommand = ( cmd || new Command() ).reset(); subCommand._name = name; subCommand._parent = this; if ( executableDescription ) { subCommand.isExecutable = true; subCommand.description( executableDescription ); } if ( result.typeDefinition ) { subCommand.arguments( result.typeDefinition ); } // if ( name === '*' && !subCommand.isExecutable ) { // subCommand.isExecutable = true; // } aliases.forEach( alias => subCommand.aliases.push( alias ) ); this.commands.set( name, subCommand ); this.select( name ); return this; } // public static async exists( name: string ) { // // const proc = Deno.run( { // cmd: [ 'sh', '-c', 'compgen -c' ], // stdout: 'piped', // stderr: 'piped' // } ); // const output: Uint8Array = await proc.output(); // const commands = new TextDecoder().decode( output ) // .trim() // .split( '\n' ); // // return commands.indexOf( name ) !== -1; // } /** * Add new command alias. * * @param alias Alias name */ public alias( alias: string ): this { if ( this.cmd === this ) { throw this.error( new Error( `Failed to add alias '${ alias }'. No sub command selected.` ) ); } if ( this.cmd.aliases.indexOf( alias ) !== -1 ) { throw this.error( new Error( `Duplicate alias: ${ alias }` ) ); } this.cmd.aliases.push( alias ); return this; } /** * Reset internal command reference to main command. */ public reset(): this { return this.cmd = this; } /** * Reset internal command reference to child command with given name. * * @param name Sub-command name. */ public select( name: string ): this { const cmd = this.getBaseCommand( name, true ); if ( !cmd ) { throw this.error( new Error( `Sub-command not found: ${ name }` ) ); } this.cmd = cmd; return this; } /******************************************************************************** **** SUB HANDLER *************************************************************** ********************************************************************************/ /** * Get or set command name. */ public name( name: string ): this { this.cmd._name = name; return this; } /** * Set command version. * * @param version Semantic version string. */ public version( version: string ): this { this.cmd.ver = version; return this; } /** * Set command description. * * @param description Short command description. */ public description( description: IDescription ): this { this.cmd.desc = description; return this; } /** * Hide command from help, completions, etc. */ public hidden(): this { this.cmd.isHidden = true; return this; } /** * Make command globally available. */ public global(): this { this.cmd.isGlobal = true; return this; } /** * Set command arguments. * * @param args Define required and optional commands like: <requiredArg:string> [optionalArg: number] [...restArgs:string] */ public arguments( args: string ): this { this.cmd.argsDefinition = args; return this; } /** * Set command handler. * * @param fn Callback method. */ public action( fn: IAction<O, A> ): this { this.cmd.fn = fn; return this; } /** * Don't throw an error if the command was called without arguments. * * @param allowEmpty */ public allowEmpty( allowEmpty: boolean = true ): this { this.cmd._allowEmpty = allowEmpty; return this; } /** * If enabled, all arguments starting from the first non option argument will be interpreted as raw argument. * * For example: * `command --debug-level warning server --port 80` * * Will result in: * - options: `{debugLevel: 'warning'}` * - args: `['server', '--port', '80']` * * @param stopEarly */ public stopEarly( stopEarly: boolean = true ): this { this.cmd._stopEarly = stopEarly; return this; } /** * Disable parsing arguments. If enabled the raw arguments will be passed to the action handler. * This has no effect for parent or child commands. Only for the command on which this method was called. */ public useRawArgs( useRawArgs: boolean = true ): this { this.cmd._useRawArgs = useRawArgs; return this; } /** * Set default command. The default command will be called if no action handler is registered. */ public default( name: string ): this { this.cmd.defaultCommand = name; return this; } /** * Register command specific custom type. */ public type( name: string, handler: Type<any> | ITypeHandler<any>, options?: ITypeOption ): this { if ( this.cmd.types.get( name ) && !options?.override ) { throw this.error( new Error( `Type '${ name }' already exists.` ) ); } this.cmd.types.set( name, { ...options, name, handler } ); if ( handler instanceof Type && typeof handler.complete !== 'undefined' ) { this.complete( name, ( cmd: Command, parent?: Command ) => handler.complete?.( cmd, parent ) || [], options ); } return this; } /** * Register command specific custom type. */ public complete( name: string, complete: ICompleteHandler, options?: ICompleteOptions ): this { if ( this.cmd.completions.has( name ) && !options?.override ) { throw this.error( new Error( `Completion '${ name }' already exists.` ) ); } this.cmd.completions.set( name, { name, complete, ...options } ); return this; } /** * Throw error's instead of calling `Deno.exit()` to handle error's manually. * This has no effect for parent commands. Only for the command on which this method was called and all child commands. */ public throwErrors(): this { this.cmd.throwOnError = true; return this; } protected shouldThrowErrors(): boolean { return this.cmd.throwOnError || !!this.cmd._parent?.shouldThrowErrors(); } public getCompletions() { return this.getGlobalCompletions().concat( this.getBaseCompletions() ); } public getBaseCompletions(): ICompleteSettings[] { return Array.from( this.completions.values() ); } public getGlobalCompletions(): ICompleteSettings[] { const getCompletions = ( cmd: Command | undefined, completions: ICompleteSettings[] = [], names: string[] = [] ): ICompleteSettings[] => { if ( cmd ) { if ( cmd.completions.size ) { cmd.completions.forEach( ( completion: ICompleteSettings ) => { if ( completion.global && !this.completions.has( completion.name ) && names.indexOf( completion.name ) === -1 ) { names.push( completion.name ); completions.push( completion ); } } ); } return getCompletions( cmd._parent, completions, names ); } return completions; }; return getCompletions( this._parent ); } public getCompletion( name: string ) { return this.getBaseCompletion( name ) ?? this.getGlobalCompletion( name ); } public getBaseCompletion( name: string ): ICompleteSettings | undefined { return this.completions.get( name ); } public getGlobalCompletion( name: string ): ICompleteSettings | undefined { if ( !this._parent ) { return; } let completion: ICompleteSettings | undefined = this._parent.getBaseCompletion( name ); if ( !completion?.global ) { return this._parent.getGlobalCompletion( name ); } return completion; } /** * Add new option (flag). * * @param flags Flags string like: -h, --help, --manual <requiredArg:string> [optionalArg: number] [...restArgs:string] * @param desc Flag description. * @param opts Flag options or custom handler for processing flag value. */ public option( flags: string, desc: string, opts?: ICommandOption | IFlagValueHandler ): this { if ( typeof opts === 'function' ) { return this.option( flags, desc, { value: opts } ); } const result = ArgumentsParser.splitArguments( flags ); const args: IArgumentDetails[] = result.typeDefinition ? ArgumentsParser.parseArgumentsDefinition( result.typeDefinition ) : []; const option: IOption = { name: '', description: desc, args, flags: result.args.join( ', ' ), typeDefinition: result.typeDefinition, ...opts }; if ( option.separator ) { for ( const arg of args ) { if ( arg.list ) { arg.separator = option.separator; } } } for ( const part of result.args ) { const arg = part.trim(); const isLong = /^--/.test( arg ); const name = isLong ? arg.slice( 2 ) : arg.slice( 1 ); if ( option.name === name || option.aliases && ~option.aliases.indexOf( name ) ) { throw this.error( new Error( `Duplicate command name: ${ name }` ) ); } if ( !option.name && isLong ) { option.name = name; } else if ( !option.aliases ) { option.aliases = [ name ]; } else { option.aliases.push( name ); } if ( this.cmd.getBaseOption( name, true ) ) { if ( opts?.override ) { this.removeOption( name ); } else { throw this.error( new Error( `Duplicate option name: ${ name }` ) ); } } } if ( option.prepend ) { this.cmd.options.unshift( option ); } else { this.cmd.options.push( option ); } return this; } /** * Add new command example. * * @param name Name of the example. * @param description The content of the example. */ public example( name: string, description: string ): this { if ( this.cmd.hasExample( name ) ) { throw this.error( new Error( 'Example already exists.' ) ); } this.cmd.examples.push( { name, description } ); return this; } /** * Add new environment variable. * * @param name Name of the environment variable. * @param description The description of the environment variable. * @param options Environment variable options. */ public env( name: string, description: string, options?: IEnvVarOption ): this { const result = ArgumentsParser.splitArguments( name ); if ( !result.typeDefinition ) { result.typeDefinition = '<value:boolean>'; } if ( result.args.some( envName => this.cmd.getBaseEnvVar( envName, true ) ) ) { throw this.error( new Error( `Environment variable already exists: ${ name }` ) ); } const details: IArgumentDetails[] = ArgumentsParser.parseArgumentsDefinition( result.typeDefinition ); if ( details.length > 1 ) { throw this.error( new Error( `An environment variable can only have one value but got: ${ name }` ) ); } else if ( details.length && details[ 0 ].optionalValue ) { throw this.error( new Error( `An environment variable can not have an optional value but '${ name }' is defined as optional.` ) ); } else if ( details.length && details[ 0 ].variadic ) { throw this.error( new Error( `An environment variable can not have an variadic value but '${ name }' is defined as variadic.` ) ); } this.cmd.envVars.push( { names: result.args, description, type: details[ 0 ].type, details: details.shift() as IArgumentDetails, ...options } ); return this; } /******************************************************************************** **** MAIN HANDLER ************************************************************** ********************************************************************************/ /** * Parse command line arguments and execute matched command. * * @param args Command line args to parse. Ex: `cmd.parse( Deno.args )` * @param dry Execute command after parsed. */ public async parse( args: string[] = Deno.args, dry?: boolean ): Promise<IParseResult<O, A>> { this.reset() .registerDefaults(); this.rawArgs = args; const subCommand = this.rawArgs.length > 0 && this.getCommand( this.rawArgs[ 0 ], true ); if ( subCommand ) { subCommand._globalParent = this; return await subCommand.parse( this.rawArgs.slice( 1 ), dry ); } if ( this.isExecutable ) { if ( !dry ) { await this.executeExecutable( this.rawArgs ); } return { options: {} as O, args: this.rawArgs as any as A, cmd: this, literal: this.literalArgs }; } else if ( this._useRawArgs ) { if ( dry ) { return { options: {} as O, args: this.rawArgs as any as A, cmd: this, literal: this.literalArgs }; } return await this.execute( {} as O, ...this.rawArgs as A ); } else { const { flags, unknown, literal } = this.parseFlags( this.rawArgs ); this.literalArgs = literal; const params = this.parseArguments( unknown, flags ); this.validateEnvVars(); if ( dry ) { return { options: flags, args: params as any as A, cmd: this, literal: this.literalArgs }; } return await this.execute( flags, ...params ); } } private registerDefaults(): this { if ( this.getParent() || this.hasDefaults ) { return this; } this.hasDefaults = true; this.reset(); if ( this._versionOption !== false ) { this.option( this._versionOption?.flags || '-V, --version', this._versionOption?.desc || 'Show the version number for this program.', Object.assign( { standalone: true, prepend: true, action: async function ( this: Command ) { await Deno.stdout.writeSync( encode( this.getVersion() + '\n' ) ); Deno.exit( 0 ); } }, this._versionOption?.opts ?? {} ) ); } if ( this._helpOption !== false ) { this.option( this._helpOption?.flags || '-h, --help', this._helpOption?.desc || 'Show this help.', Object.assign( { standalone: true, global: true, prepend: true, action: function ( this: Command ) { this.help(); Deno.exit( 0 ); } }, this._helpOption?.opts ?? {} ) ); } return this; }; /** * Execute command. * * @param options A map of options. * @param args Command arguments. */ protected async execute( options: O, ...args: A ): Promise<IParseResult<O, A>> { const actionOption = this.findActionFlag( options ); if ( actionOption && actionOption.action ) { await actionOption.action.call( this, options, ...args ); return { options, args: args as any as A, cmd: this, literal: this.literalArgs }; } if ( this.fn ) { try { await this.fn( options, ...args ); } catch ( e ) { throw this.error( e ); } } else if ( this.defaultCommand ) { const cmd = this.getCommand( this.defaultCommand, true ); if ( !cmd ) { throw this.error( new Error( `Default command '${ this.defaultCommand }' not found.` ) ); } cmd._globalParent = this; try { await cmd.execute( options, ...args ); } catch ( e ) { throw this.error( e ); } } return { options, args: args as any as A, cmd: this, literal: this.literalArgs }; } /** * Execute external sub-command. * * @param args Raw command line arguments. */ protected async executeExecutable( args: string[] ) { const [ main, ...names ] = this.getPath().split( ' ' ); names.unshift( main.replace( /\.ts$/, '' ) ); const executable = names.join( '-' ); try { // @TODO: create getEnv() method which should return all known environment variables and pass it to Deno.run({env}) await Deno.run( { cmd: [ executable, ...args ] } ); return; } catch ( e ) { if ( !e.message.match( /No such file or directory/ ) ) { throw e; } } try { await Deno.run( { cmd: [ executable + '.ts', ...args ] } ); return; } catch ( e ) { if ( !e.message.match( /No such file or directory/ ) ) { throw e; } } throw this.error( new Error( `Sub-command executable not found: ${ executable }${ dim( '(.ts)' ) }` ) ); } /** * Parse command line args. * * @param args Command line args. */ protected parseFlags( args: string[] ): IFlagsResult<O> { try { return parseFlags<O>( args, { stopEarly: this._stopEarly, // knownFlaks, allowEmpty: this._allowEmpty, flags: this.getOptions( true ), parse: ( type: string, option: IFlagOptions, arg: IFlagArgument, nextValue: string ) => this.parseType( type, option, arg, nextValue ) } ); } catch ( e ) { throw this.error( e ); } } protected parseType( name: string, option: IFlagOptions, arg: IFlagArgument, nextValue: string ): any { const type: ITypeSettings | undefined = this.getType( name ); if ( !type ) { throw this.error( new Error( `No type registered with name: ${ name }` ) ); } // @TODO: pass only name & value to .parse() method return type.handler instanceof Type ? type.handler.parse( option, arg, nextValue ) : type.handler( option, arg, nextValue ); } /** * Validate environment variables. */ protected validateEnvVars() { const envVars = this.getEnvVars( true ); if ( !envVars.length ) { return; } if ( hasEnvPermissions ) { envVars.forEach( ( env: IEnvVariable ) => { const name = env.names.find( name => !!Deno.env.get( name ) ); if ( name ) { const value: string | undefined = Deno.env.get( name ); try { // @TODO: optimize handling for environment variable error message: parseFlag & parseEnv ? this.parseType( env.type, { name }, env, value || '' ); } catch ( e ) { throw new Error( `Environment variable '${ name }' must be of type ${ env.type } but got: ${ value }` ); } } } ); } } /** * Match commands and arguments from command line arguments. */ protected parseArguments( args: string[], flags: O ): A { const params: IFlagValue[] = []; // remove array reference args = args.slice( 0 ); if ( !this.hasArguments() ) { if ( args.length ) { if ( this.hasCommands( true ) ) { throw this.error( new Error( `Unknown command: ${ args.join( ' ' ) }` ) ); } else { throw this.error( new Error( `No arguments allowed for command: ${ this._name }` ) ); } } } else { if ( !args.length ) { const required = this.getArguments() .filter( expectedArg => !expectedArg.optionalValue ) .map( expectedArg => expectedArg.name ); if ( required.length ) { const flagNames: string[] = Object.keys( flags ); const hasStandaloneOption: boolean = !!flagNames.find( name => this.getOption( name, true )?.standalone ); if ( !hasStandaloneOption ) { throw this.error( new Error( 'Missing argument(s): ' + required.join( ', ' ) ) ); } } return params as A; } for ( const expectedArg of this.getArguments() ) { if ( !expectedArg.optionalValue && !args.length ) { throw this.error( new Error( `Missing argument: ${ expectedArg.name }` ) ); } let arg: IFlagValue; if ( expectedArg.variadic ) { arg = args.splice( 0, args.length ) as IFlagValueType[]; } else { arg = args.shift() as IFlagValue; } if ( arg ) { params.push( arg ); } } if ( args.length ) { throw this.error( new Error( `To many arguments: ${ args.join( ' ' ) }` ) ); } } return params as A; } /** * Execute help command if help flag is set. * * @param flags Command options. */ protected findActionFlag( flags: O ): IOption | undefined { const flagNames = Object.keys( flags ); for ( const flag of flagNames ) { const option = this.getOption( flag, true ); if ( option?.action ) { return option; } } return; } /******************************************************************************** **** GETTER ******************************************************************** ********************************************************************************/ /** * Get command name. */ public getName(): string { return this._name; } /** * Get parent command. */ public getParent(): Command | undefined { return this._parent; } /** * Get parent command from global executed command. * Be sure, to call this method only inside an action handler. Unless this or any child command was executed, * this method returns always undefined. */ public getGlobalParent(): Command | undefined { return this._globalParent; } /** * Get main command. */ public getMainCommand(): Command { return this._parent?.getMainCommand() ?? this; } /** * Get command name aliases. */ public getAliases(): string[] { return this.aliases; } /** * Get full command path of all parent command names's and current command name. */ public getPath(): string { return this._parent ? this._parent.getPath() + ' ' + this._name : this._name; } /** * Get arguments definition. */ public getArgsDefinition(): string | undefined { return this.argsDefinition; } /** * Get argument. */ public getArgument( name: string ): IArgumentDetails | undefined { return this.getArguments().find( arg => arg.name === name ); } /** * Get arguments. */ public getArguments(): IArgumentDetails[] { if ( !this.args.length && this.argsDefinition ) { this.args = ArgumentsParser.parseArgumentsDefinition( this.argsDefinition ); } return this.args; } /** * Check if command has arguments. */ public hasArguments() { return !!this.argsDefinition; } /** * Get command version. */ public getVersion(): string { return this.ver || ( this._parent?.getVersion() ?? '' ); } /** * Get command description. */ public getDescription(): string { // call description method only once return typeof this.desc === 'function' ? this.desc = this.desc() : this.desc; } public getShortDescription(): string { return this.getDescription() .trim() .split( '\n' ) .shift() as string; } /** * Checks whether the command has options or not. */ public hasOptions( hidden?: boolean ): boolean { return this.getOptions( hidden ).length > 0; } public getOptions( hidden?: boolean ): IOption[] { return this.getGlobalOptions( hidden ).concat( this.getBaseOptions( hidden ) ); } public getBaseOptions( hidden?: boolean ): IOption[] { if ( !this.options.length ) { return []; } return hidden ? this.options.slice( 0 ) : this.options.filter( opt => !opt.hidden ); } public getGlobalOptions( hidden?: boolean ): IOption[] { const getOptions = ( cmd: Command | undefined, options: IOption[] = [], names: string[] = [] ): IOption[] => { if ( cmd ) { if ( cmd.options.length ) { cmd.options.forEach( ( option: IOption ) => { if ( option.global && !this.options.find( opt => opt.name === option.name ) && names.indexOf( option.name ) === -1 && ( hidden || !option.hidden ) ) { names.push( option.name ); options.push( option ); } } ); } return getOptions( cmd._parent, options, names ); } return options; }; return getOptions( this._parent ); } /** * Checks whether the command has an option with given name or not. * * @param name Name of the option. Must be in param-case. * @param hidden Include hidden options. */ public hasOption( name: string, hidden?: boolean ): boolean { return !!this.getOption( name, hidden ); } /** * Get option by name. * * @param name Name of the option. Must be in param-case. * @param hidden Include hidden options. */ public getOption( name: string, hidden?: boolean ): IOption | undefined { return this.getBaseOption( name, hidden ) ?? this.getGlobalOption( name, hidden ); } /** * Get base option by name. * * @param name Name of the option. Must be in param-case. * @param hidden Include hidden options. */ public getBaseOption( name: string, hidden?: boolean ): IOption | undefined { const option = this.options.find( option => option.name === name ); return option && ( hidden || !option.hidden ) ? option : undefined; } /** * Get global option from parent command's by name. * * @param name Name of the option. Must be in param-case. * @param hidden Include hidden options. */ public getGlobalOption( name: string, hidden?: boolean ): IOption | undefined { if ( !this._parent ) { return; } let option: IOption | undefined = this._parent.getBaseOption( name, hidden ); if ( !option || !option.global ) { return this._parent.getGlobalOption( name, hidden ); } return option; } /** * Remove option by name. * * @param name Name of the option. Must be in param-case. */ public removeOption( name: string ): IOption | undefined { const index = this.options.findIndex( option => option.name === name ); if ( index === -1 ) { return; } return this.options.splice( index, 1 )[ 0 ]; } /** * Checks whether the command has sub-commands or not. */ public hasCommands( hidden?: boolean ): boolean { return this.getCommands( hidden ).length > 0; } /** * Get sub-commands. */ public getCommands( hidden?: boolean ): Command[] { return this.getGlobalCommands( hidden ).concat( this.getBaseCommands( hidden ) ); } public getBaseCommands( hidden?: boolean ): Command[] { const commands = Array.from( this.commands.values() ); return hidden ? commands : commands.filter( cmd => !cmd.isHidden ); } public getGlobalCommands( hidden?: boolean ): Command[] { const getCommands = ( cmd: Command | undefined, commands: Command[] = [], names: string[] = [] ): Command[] => { if ( cmd ) { if ( cmd.commands.size ) { cmd.commands.forEach( ( cmd: Command ) => { if ( cmd.isGlobal && this !== cmd && !this.commands.has( cmd._name ) && names.indexOf( cmd._name ) === -1 && ( hidden || !cmd.isHidden ) ) { names.push( cmd._name ); commands.push( cmd ); } } ); } return getCommands( cmd._parent, commands, names ); } return commands; }; return getCommands( this._parent ); } /** * Checks whether the command has a sub-command with given name or not. * * @param name Name of the command. * @param hidden Include hidden commands. */ public hasCommand( name: string, hidden?: boolean ): boolean { return !!this.getCommand( name, hidden ); } /** * Get sub-command with given name. * * @param name Name of the sub-command. * @param hidden Include hidden commands. */ public getCommand<O = any>( name: string, hidden?: boolean ): Command<O> | undefined { return this.getBaseCommand( name, hidden ) ?? this.getGlobalCommand( name, hidden ); } public getBaseCommand<O = any>( name: string, hidden?: boolean ): Command<O> | undefined { let cmd: Command | undefined = this.commands.get( name ); return cmd && ( hidden || !cmd.isHidden ) ? cmd : undefined; } public getGlobalCommand<O = any>( name: string, hidden?: boolean ): Command<O> | undefined { if ( !this._parent ) { return; } let cmd: Command | undefined = this._parent.getBaseCommand( name, hidden ); if ( !cmd?.isGlobal ) { return this._parent.getGlobalCommand( name, hidden ); } return cmd; } /** * Remove sub-command with given name. * * @param name Name of the command. */ public removeCommand<O = any>( name: string ): Command<O> | undefined { const command = this.getBaseCommand( name, true ); if ( command ) { this.commands.delete( name ); } return command; } public getTypes(): ITypeSettings[] { return this.getGlobalTypes().concat( this.getBaseTypes() ); } public getBaseTypes(): ITypeSettings[] { return Array.from( this.types.values() ); } public getGlobalTypes(): ITypeSettings[] { const getTypes = ( cmd: Command | undefined, types: ITypeSettings[] = [], names: string[] = [] ): ITypeSettings[] => { if ( cmd ) { if ( cmd.types.size ) { cmd.types.forEach( ( type: ITypeSettings ) => { if ( type.global && !this.types.has( type.name ) && names.indexOf( type.name ) === -1 ) { names.push( type.name ); types.push( type ); } } ); } return getTypes( cmd._parent, types, names ); } return types; }; return getTypes( this._parent ); } protected getType( name: string ): ITypeSettings | undefined { return this.getBaseType( name ) ?? this.getGlobalType( name ); } protected getBaseType( name: string ): ITypeSettings | undefined { return this.types.get( name ); } protected getGlobalType( name: string ): ITypeSettings | undefined { if ( !this._parent ) { return; } let cmd: ITypeSettings | undefined = this._parent.getBaseType( name ); if ( !cmd?.global ) { return this._parent.getGlobalType( name ); } return cmd; } /** * Checks whether the command has environment variables or not. */ public hasEnvVars( hidden?: boolean ): boolean { return this.getEnvVars( hidden ).length > 0; } /** * Get environment variables. */ public getEnvVars( hidden?: boolean ): IEnvVariable[] { return this.getGlobalEnvVars( hidden ).concat( this.getBaseEnvVars( hidden ) ); } public getBaseEnvVars( hidden?: boolean ): IEnvVariable[] { if ( !this.envVars.length ) { return []; } return hidden ? this.envVars.slice( 0 ) : this.envVars.filter( env => !env.hidden ); } public getGlobalEnvVars( hidden?: boolean ): IEnvVariable[] { const getEnvVars = ( cmd: Command | undefined, envVars: IEnvVariable[] = [], names: string[] = [] ): IEnvVariable[] => { if ( cmd ) { if ( cmd.envVars.length ) { cmd.envVars.forEach( ( envVar: IEnvVariable ) => { if ( envVar.global && !this.envVars.find( env => env.names[ 0 ] === envVar.names[ 0 ] ) && names.indexOf( envVar.names[ 0 ] ) === -1 && ( hidden || !envVar.hidden ) ) { names.push( envVar.names[ 0 ] ); envVars.push( envVar ); } } ); } return getEnvVars( cmd._parent, envVars, names ); } return envVars; }; return getEnvVars( this._parent ); } /** * Checks whether the command has an environment variable with given name or not. * * @param name Name of the environment variable. * @param hidden Include hidden environment variable. */ public hasEnvVar( name: string, hidden?: boolean ): boolean { return !!this.getEnvVar( name, hidden ); } /** * Get environment variable with given name. * * @param name Name of the environment variable. * @param hidden Include hidden environment variable. */ public getEnvVar( name: string, hidden?: boolean ): IEnvVariable | undefined { return this.getBaseEnvVar( name, hidden ) ?? this.getGlobalEnvVar( name, hidden ); } public getBaseEnvVar( name: string, hidden?: boolean ): IEnvVariable | undefined { const envVar: IEnvVariable | undefined = this.envVars.find( env => env.names.indexOf( name ) !== -1 ); return envVar && ( hidden || !envVar.hidden ) ? envVar : undefined; } public getGlobalEnvVar( name: string, hidden?: boolean ): IEnvVariable | undefined { if ( !this._parent ) { return; } let envVar: IEnvVariable | undefined = this._parent.getBaseEnvVar( name, hidden ); if ( !envVar?.global ) { return this._parent.getGlobalEnvVar( name, hidden ); } return envVar; } /** * Checks whether the command has examples or not. */ public hasExamples(): boolean { return this.examples.length > 0; } /** * Get examples. */ public getExamples(): IExample[] { return this.examples; } /** * Checks whether the command has an example with given name or not. * * @param name Name of the example. */ public hasExample( name: string ): boolean { return !!this.getExample( name ); } /** * Get example with given name. * * @param name Name of the example. */ public getExample( name: string ): IExample | undefined { return this.examples.find( example => example.name === name ); } public getRawArgs(): string[] { return this.rawArgs; } public getLiteralArgs(): string[] { return this.literalArgs; } /******************************************************************************** **** HELPER ******************************************************************** ********************************************************************************/ /** * Write line to stdout without line break. * * @param args Data to write to stdout. */ public write( ...args: any[] ) { stdout.writeSync( encode( fill( 2 ) + format( ...args ) ) ); } /** * Write line to stderr without line break. * * @param args Data to write to stdout. */ public writeError( ...args: any[] ) { stderr.writeSync( encode( fill( 2 ) + red( format( `[ERROR:${ this._name }]`, ...args ) ) ) ); } /** * Write line to stdout. * * @param args Data to write to stdout. */ public log( ...args: any[] ) { this.write( ...args, '\n' ); } /** * Write line to stderr. * * @param args Data to write to stderr. */ public logError( ...args: any[] ) { this.writeError( ...args, '\n' ); } /** * Handle error. If `.throwErrors()` was called all error's will be thrown, otherwise `Deno.exit(1)` will be called. * * @param error Error to handle. * @param showHelp Show help. */ public error( error: Error, showHelp: boolean = true ): Error { if ( this.shouldThrowErrors() ) { return error; } const CLIFFY_DEBUG: boolean = hasEnvPermissions ? !!Deno.env.get( 'CLIFFY_DEBUG' ) : false; showHelp && this.help(); this.logError( CLIFFY_DEBUG ? error : error.message ); this.log(); Deno.exit( 1 ); } /** * Output generated help without exiting. */ public help() { Deno.stdout.writeSync( encode( this.getHelp() ) ); } /** * Get generated help. */ public getHelp(): string { this.registerDefaults(); return HelpGenerator.generate( this ); } }
the_stack
import { Injectable } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; import jsPDF from 'jspdf'; import autoTable, { CellHookData, Styles } from 'jspdf-autotable'; import { BehaviorSubject } from 'rxjs'; import { CreatePdfRequest, CreatePdfResponse, ScoredItem, SocialMediaItem, Tweet, } from '../common-types'; import { googleSans } from './google-sans-font'; import { OauthApiService } from './oauth_api.service'; const TWITTER = 'Twitter'; // See https://stackoverflow.com/questions/66590691/typescript-type-string-is-not-assignable-to-type-numeric-2-digit-in-d // for the rationale behind the "as const" declarations below. // Exclude milliseconds from date formatting since it can make the tests flaky. const DATE_FORMAT_OPTIONS = { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', } as const; // Exclude hours and minutes since colons can't be in file names. const TITLE_DATE_FORMAT_OPTIONS = { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric', } as const; // Regex matching Extended Pictographic Unicode characters. // https://stackoverflow.com/questions/64389323/why-do-unicode-emoji-property-escapes-match-numbers const EMOJI_REGEX = /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/gu; // Interface for data used to fill in the PDF Report Table, each // string[] in displayedRowText is a separate row in the Report // Table. Each element in displayedRowText corresponds to a cell in // the table and the cell text has an associated hiddenLink. interface ReportTableBodyContent { displayedRowText: string[][]; hiddenLinks: Map<string, string>; } const TABLE_ACCENT_COLOR = '#A54167'; const BORDER_COLUMN = ''; // Used to style border between columns. const DISPLAYED_COLUMNS_TWITTER: string[] = [ 'Comment', 'Image', 'Hashtags', 'Author', 'Time Posted', 'Tweet ID', BORDER_COLUMN, 'Toxicity', 'Severe Toxicity', 'Insult', 'Profanity', 'Threat', 'Identity Attack', BORDER_COLUMN, 'Retweets', 'Likes', 'Comments', ]; const COLUMN_STYLES_TWITTER: { [key: string]: Partial<Styles>; } = { 0: { cellWidth: 50 }, 1: { cellWidth: 12 }, 2: { cellWidth: 17 }, 3: { cellWidth: 23 }, 4: { cellWidth: 23 }, 5: { cellWidth: 17 }, 6: { cellWidth: 1, fillColor: TABLE_ACCENT_COLOR }, 7: { cellWidth: 14, halign: 'center' }, 8: { cellWidth: 14, halign: 'center' }, 9: { cellWidth: 14, halign: 'center' }, 10: { cellWidth: 14, halign: 'center' }, 11: { cellWidth: 14, halign: 'center' }, 12: { cellWidth: 14, halign: 'center' }, 13: { cellWidth: 1, fillColor: TABLE_ACCENT_COLOR }, 14: { cellWidth: 14, halign: 'center' }, 15: { cellWidth: 14, halign: 'center' }, 16: { cellWidth: 14, halign: 'center' }, 17: { cellWidth: 14, halign: 'center' }, }; // Passing undefined for the locale uses the user's default locale. // See https://stackoverflow.com/a/31873738 export const DEFAULT_LOCALE = undefined; export function formatAttributeScore(score?: number): string { if (score === undefined) { return '-'; } else { return `${Math.round(score * 100)}`; } } export function formatCount(count?: number): string { if (count === undefined || isNaN(count)) { return '0'; } else { return `${count}`; } } // Given a ISO 8601 date (like '2020-11-10T17:44:51.000Z') format it // as 'MM/DD/YY at 00:00 AM/PM' export function getTimePosted(createdTime?: string): string { if (!createdTime) { return '-'; } const date = new Date(createdTime); return `${date.toLocaleDateString('en-US', { day: 'numeric', month: 'numeric', year: '2-digit', })} at ${date .toLocaleDateString('en-US', { hour: '2-digit', minute: '2-digit' }) .slice(12)}`; } export function getAuthorUrl(url?: string): string { return url || ''; } export function formatHashtags(item: Tweet): string { // In some languages tweets are being truncated after 140 characters instead // of 280, and in this case the extended_tweet has the full tweet information // including all hashtags. // https://docs.tweepy.org/en/latest/extended_tweets.html const hashtags = item.truncated ? item.extended_tweet?.entities.hashtags : item.entities?.hashtags; return hashtags?.length ? hashtags.map(item => `#${item.text}`).join(', ') : '-'; } @Injectable({ providedIn: 'root', }) export class PdfService { displayedColumns: string[] = []; platform = ''; date = ''; username = ''; initialRequest: CreatePdfRequest<SocialMediaItem> = { entries: [], reportReasons: [], context: '', }; private onCreatePdfRequestSource: BehaviorSubject< CreatePdfRequest<SocialMediaItem> > = new BehaviorSubject(this.initialRequest); onCreatePdfRequest = this.onCreatePdfRequestSource.asObservable(); constructor( private readonly oauthApiService: OauthApiService, private sanitizer: DomSanitizer ) { this.username = this.getUsername(); this.date = new Date().toLocaleDateString( DEFAULT_LOCALE, DATE_FORMAT_OPTIONS ); } private getUsername(): string { const twitterCredentials = this.oauthApiService.getTwitterCredentials(); if (!twitterCredentials) { throw new Error('Twitter credentials not found'); } if ( twitterCredentials.additionalUserInfo && twitterCredentials.additionalUserInfo.username ) { return twitterCredentials.additionalUserInfo.username; } else { throw new Error('Twitter credentials found, but no username is present'); } } /** * Updates the createPdfObservable with new Report Data to be used to create * a PDF. */ updateCreatePdfSource(request: CreatePdfRequest<SocialMediaItem>) { request.date = this.date; request.platform = TWITTER; this.platform = request.platform; this.displayedColumns = DISPLAYED_COLUMNS_TWITTER; request.username = this.username; this.onCreatePdfRequestSource.next(request); } /** * Returns the file name of the created PDF Report. */ private getTitle(): string { const date = new Date().toLocaleDateString( DEFAULT_LOCALE, TITLE_DATE_FORMAT_OPTIONS ); return ( `${this.username}'s Harassment Report From ${date} ` + `[Content Warning- Toxic Language]` ); } /** * Returns text with emojis replaced by a placeholder. */ getTextWithoutEmojis(text?: string): string { if (!text) { return ''; } return text.replace(EMOJI_REGEX, '[emoji]'); } /** * Formats Tweet into the text for a row in the table. */ private getDisplayedRowTextTwitter(entry: ScoredItem<Tweet>): string[] { return [ entry.item.text, entry.item.hasImage ? 'Yes' : 'No', entry.item ? formatHashtags(entry.item) : '-', entry.item.authorName || 'missing author name', getTimePosted(String(entry.item.date)), entry.item.id_str, BORDER_COLUMN, formatAttributeScore(entry.scores.TOXICITY), formatAttributeScore(entry.scores.SEVERE_TOXICITY), formatAttributeScore(entry.scores.INSULT), formatAttributeScore(entry.scores.PROFANITY), formatAttributeScore(entry.scores.THREAT), formatAttributeScore(entry.scores.IDENTITY_ATTACK), BORDER_COLUMN, formatCount(entry.item.retweet_count), formatCount(entry.item.favorite_count), formatCount(entry.item.reply_count), ]; } /** * Formats ScoredItem into text to display for a row in the table. */ private getDisplayedRowText(entry: ScoredItem<Tweet>): string[] { return this.getDisplayedRowTextTwitter(entry); } private addLinks( data: CellHookData, doc: jsPDF, hiddenLinks: Map<string, string> ) { if (data.section !== 'body') { return; } // data.cell.raw can be a string, number, true, string[], // HTMLTableCellElement, or CellDef. if (typeof data.cell.raw === 'string') { const cellText = data.cell.raw as string; if (hiddenLinks.has(cellText)) { doc.link(data.cell.x, data.cell.y, data.cell.width, data.cell.height, { url: hiddenLinks.get(cellText), }); } } } /** * Gets the URLs for a Tweet entry. */ private getHiddenLinksTwitter( entries: Array<ScoredItem<Tweet>> ): Map<string, string> { // For Twitter the only links are for the author's profile page // and the URL of the Tweet, all other URLs are empty. const hiddenLinks = new Map(); for (const entry of entries) { if (entry.item.authorName) { hiddenLinks.set( entry.item.authorName, getAuthorUrl(entry.item.authorUrl) ); } hiddenLinks.set(entry.item.id_str, entry.item.url || ''); } return hiddenLinks; } /** * Adds the custom fonts to jsPDF. */ private addCustomFont(doc: jsPDF) { // Default text used, without this the character spacing is buggy // from the font in ReportPDF being converted to jsPDF's default. doc.addFileToVFS('MyFont.ttf', googleSans); doc.addFont('MyFont.ttf', 'Google Sans', 'normal'); doc.setFont('Google Sans'); } /** * Removes emojis from text and author field. */ removeEmojisFromEntries( entries: Array<ScoredItem<SocialMediaItem>> ): Array<ScoredItem<SocialMediaItem>> { for (const entry of entries) { entry.item.text = this.getTextWithoutEmojis(entry.item.text || ''); entry.item.authorName = this.getTextWithoutEmojis( entry.item.authorName || '' ); } return entries; } /** * Converts the request entries to format that can be used to create a table. */ getTableBodyContent(): ReportTableBodyContent { let entries = this.onCreatePdfRequestSource.value.entries; entries = this.removeEmojisFromEntries(entries); const displayedRowText = new Array(entries.length); const hiddenLinks = this.getHiddenLinksTwitter( entries as Array<ScoredItem<Tweet>> ); for (let i = 0; i < entries.length; i++) { displayedRowText[i] = this.getDisplayedRowText( entries[i] as ScoredItem<Tweet> ); } return { displayedRowText, hiddenLinks }; } /** * Adds the Report Details to the PDF. */ private addReportTable(tableBodyContent: ReportTableBodyContent, doc: jsPDF) { const columnStyles = COLUMN_STYLES_TWITTER; const displayedRowText = tableBodyContent.displayedRowText; doc.addPage(); doc.addImage('pdf_table_header.png', 'PNG', 14, 10, 270, 23); autoTable(doc, { theme: 'grid', // Shift the table down on the first page so the inserted image isn't covered. startY: 30, headStyles: { fontSize: 7, fillColor: TABLE_ACCENT_COLOR, valign: 'middle', halign: 'center', }, // For each of the columns in displayedColumns set the width, // vertically center the number columns, and style the empty columns as // colored lines. columnStyles, head: [this.displayedColumns], body: displayedRowText, didDrawCell: data => { this.addLinks(data, doc, tableBodyContent.hiddenLinks); }, }); } /** * Process the entire PDF into a downloadable format. */ private async finalizePdf(doc: jsPDF): Promise<CreatePdfResponse> { const blobPdf = new Blob([doc.output('blob')], { type: 'application/pdf', }); const url = this.sanitizer.bypassSecurityTrustUrl( window.URL.createObjectURL(blobPdf) ); const title = this.getTitle(); const buffer = await blobPdf.arrayBuffer(); return { title, safeUrl: url, buffer, }; } /** * Creates a PDF file with a downloadable URL and a title. */ async createPdf(reportPdfElement: HTMLElement): Promise<CreatePdfResponse> { // Format the entries so they can be used by jspdf-autotable. const tableBodyContent: ReportTableBodyContent = this.getTableBodyContent(); // Initialize JSPDF // 'mm' (millimeter) is the unit and 'a4' is the format of a standard // 8"x11" sheet of paper. const doc = new jsPDF('landscape', 'mm', 'a4'); this.addCustomFont(doc); // Create the PDF using the HTML from the ReportPDF component for the first // page and the data from the request for the table. const reportPdfElementSummary = reportPdfElement.querySelector( '.report-summary' ) as HTMLElement; // Scaling factor for the Report Summary on the first page. const scale = 0.24; const response: Promise<CreatePdfResponse> = new Promise(resolve => doc.html(reportPdfElementSummary, { html2canvas: { scale }, callback: renderedDoc => { this.addReportTable(tableBodyContent, renderedDoc); resolve(this.finalizePdf(renderedDoc)); }, }) ); return response; } }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface Operations { /** * @summary Lists all of the available operations. * * Lists all the available operations provided by Service Fabric SeaBreeze * resource provider. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * @summary Lists all of the available operations. * * Lists all the available operations provided by Service Fabric SeaBreeze * resource provider. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * @summary Lists all of the available operations. * * Lists all the available operations provided by Service Fabric SeaBreeze * resource provider. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * @summary Lists all of the available operations. * * Lists all the available operations provided by Service Fabric SeaBreeze * resource provider. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; } /** * @class * Secret * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface Secret { /** * @summary Creates or updates a secret resource. * * Creates a secret resource with the specified name, description and * properties. If a secret resource with the same name exists, then it is * updated with the specified description and properties. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {object} secretResourceDescription Description for creating a secret * resource. * * @param {object} secretResourceDescription.properties Describes the * properties of a secret resource. * * @param {string} [secretResourceDescription.properties.description] User * readable description of the secret. * * @param {string} [secretResourceDescription.properties.contentType] The type * of the content stored in the secret value. The value of this property is * opaque to Service Fabric. Once set, the value of this property cannot be * changed. * * @param {string} secretResourceDescription.properties.kind Polymorphic * Discriminator * * @param {object} [secretResourceDescription.tags] Resource tags. * * @param {string} secretResourceDescription.location The geo-location where * the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, secretResourceName: string, secretResourceDescription: models.SecretResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretResourceDescription>>; /** * @summary Creates or updates a secret resource. * * Creates a secret resource with the specified name, description and * properties. If a secret resource with the same name exists, then it is * updated with the specified description and properties. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {object} secretResourceDescription Description for creating a secret * resource. * * @param {object} secretResourceDescription.properties Describes the * properties of a secret resource. * * @param {string} [secretResourceDescription.properties.description] User * readable description of the secret. * * @param {string} [secretResourceDescription.properties.contentType] The type * of the content stored in the secret value. The value of this property is * opaque to Service Fabric. Once set, the value of this property cannot be * changed. * * @param {string} secretResourceDescription.properties.kind Polymorphic * Discriminator * * @param {object} [secretResourceDescription.tags] Resource tags. * * @param {string} secretResourceDescription.location The geo-location where * the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link SecretResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, secretResourceName: string, secretResourceDescription: models.SecretResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretResourceDescription>; create(resourceGroupName: string, secretResourceName: string, secretResourceDescription: models.SecretResourceDescription, callback: ServiceCallback<models.SecretResourceDescription>): void; create(resourceGroupName: string, secretResourceName: string, secretResourceDescription: models.SecretResourceDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretResourceDescription>): void; /** * @summary Gets the secret resource with the given name. * * Gets the information about the secret resource with the given name. The * information include the description and other properties of the secret. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, secretResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretResourceDescription>>; /** * @summary Gets the secret resource with the given name. * * Gets the information about the secret resource with the given name. The * information include the description and other properties of the secret. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link SecretResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, secretResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretResourceDescription>; get(resourceGroupName: string, secretResourceName: string, callback: ServiceCallback<models.SecretResourceDescription>): void; get(resourceGroupName: string, secretResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretResourceDescription>): void; /** * @summary Deletes the secret resource. * * Deletes the secret resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, secretResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the secret resource. * * Deletes the secret resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, secretResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, secretResourceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, secretResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets all the secret resources in a given resource group. * * Gets the information about all secret resources in a given resource group. * The information include the description and other properties of the Secret. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretResourceDescriptionList>>; /** * @summary Gets all the secret resources in a given resource group. * * Gets the information about all secret resources in a given resource group. * The information include the description and other properties of the Secret. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link SecretResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretResourceDescriptionList>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.SecretResourceDescriptionList>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretResourceDescriptionList>): void; /** * @summary Gets all the secret resources in a given subscription. * * Gets the information about all secret resources in a given resource group. * The information include the description and other properties of the secret. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretResourceDescriptionList>>; /** * @summary Gets all the secret resources in a given subscription. * * Gets the information about all secret resources in a given resource group. * The information include the description and other properties of the secret. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link SecretResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretResourceDescriptionList>; listBySubscription(callback: ServiceCallback<models.SecretResourceDescriptionList>): void; listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretResourceDescriptionList>): void; /** * @summary Gets all the secret resources in a given resource group. * * Gets the information about all secret resources in a given resource group. * The information include the description and other properties of the Secret. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretResourceDescriptionList>>; /** * @summary Gets all the secret resources in a given resource group. * * Gets the information about all secret resources in a given resource group. * The information include the description and other properties of the Secret. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link SecretResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretResourceDescriptionList>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.SecretResourceDescriptionList>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretResourceDescriptionList>): void; /** * @summary Gets all the secret resources in a given subscription. * * Gets the information about all secret resources in a given resource group. * The information include the description and other properties of the secret. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretResourceDescriptionList>>; /** * @summary Gets all the secret resources in a given subscription. * * Gets the information about all secret resources in a given resource group. * The information include the description and other properties of the secret. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link SecretResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretResourceDescriptionList>; listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.SecretResourceDescriptionList>): void; listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretResourceDescriptionList>): void; } /** * @class * SecretValueOperations * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface SecretValueOperations { /** * @summary Adds the specified value as a new version of the specified secret * resource. * * Creates a new value of the specified secret resource. The name of the value * is typically the version identifier. Once created the value cannot be * changed. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {string} secretValueResourceName The name of the secret resource * value which is typically the version identifier for the value. * * @param {object} secretValueResourceDescription Description for creating a * value of a secret resource. * * @param {string} [secretValueResourceDescription.value] The actual value of * the secret. * * @param {object} [secretValueResourceDescription.tags] Resource tags. * * @param {string} secretValueResourceDescription.location The geo-location * where the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretValueResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, secretValueResourceDescription: models.SecretValueResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretValueResourceDescription>>; /** * @summary Adds the specified value as a new version of the specified secret * resource. * * Creates a new value of the specified secret resource. The name of the value * is typically the version identifier. Once created the value cannot be * changed. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {string} secretValueResourceName The name of the secret resource * value which is typically the version identifier for the value. * * @param {object} secretValueResourceDescription Description for creating a * value of a secret resource. * * @param {string} [secretValueResourceDescription.value] The actual value of * the secret. * * @param {object} [secretValueResourceDescription.tags] Resource tags. * * @param {string} secretValueResourceDescription.location The geo-location * where the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretValueResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretValueResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link SecretValueResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, secretValueResourceDescription: models.SecretValueResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretValueResourceDescription>; create(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, secretValueResourceDescription: models.SecretValueResourceDescription, callback: ServiceCallback<models.SecretValueResourceDescription>): void; create(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, secretValueResourceDescription: models.SecretValueResourceDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretValueResourceDescription>): void; /** * @summary Gets the specified secret value resource. * * Get the information about the specified named secret value resources. The * information does not include the actual value of the secret. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {string} secretValueResourceName The name of the secret resource * value which is typically the version identifier for the value. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretValueResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretValueResourceDescription>>; /** * @summary Gets the specified secret value resource. * * Get the information about the specified named secret value resources. The * information does not include the actual value of the secret. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {string} secretValueResourceName The name of the secret resource * value which is typically the version identifier for the value. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretValueResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretValueResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link SecretValueResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretValueResourceDescription>; get(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, callback: ServiceCallback<models.SecretValueResourceDescription>): void; get(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretValueResourceDescription>): void; /** * @summary Deletes the specified value of the named secret resource. * * Deletes the secret value resource identified by the name. The name of the * resource is typically the version associated with that value. Deletion will * fail if the specified value is in use. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {string} secretValueResourceName The name of the secret resource * value which is typically the version identifier for the value. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the specified value of the named secret resource. * * Deletes the secret value resource identified by the name. The name of the * resource is typically the version associated with that value. Deletion will * fail if the specified value is in use. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {string} secretValueResourceName The name of the secret resource * value which is typically the version identifier for the value. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary List names of all values of the the specified secret resource. * * Gets information about all secret value resources of the specified secret * resource. The information includes the names of the secret value resources, * but not the actual values. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretValueResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, secretResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretValueResourceDescriptionList>>; /** * @summary List names of all values of the the specified secret resource. * * Gets information about all secret value resources of the specified secret * resource. The information includes the names of the secret value resources, * but not the actual values. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretValueResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretValueResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link SecretValueResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, secretResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretValueResourceDescriptionList>; list(resourceGroupName: string, secretResourceName: string, callback: ServiceCallback<models.SecretValueResourceDescriptionList>): void; list(resourceGroupName: string, secretResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretValueResourceDescriptionList>): void; /** * @summary Lists the specified value of the secret resource. * * Lists the decrypted value of the specified named value of the secret * resource. This is a privileged operation. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {string} secretValueResourceName The name of the secret resource * value which is typically the version identifier for the value. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretValue>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listValueWithHttpOperationResponse(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretValue>>; /** * @summary Lists the specified value of the secret resource. * * Lists the decrypted value of the specified named value of the secret * resource. This is a privileged operation. * * @param {string} resourceGroupName Azure resource group name * * @param {string} secretResourceName The name of the secret resource. * * @param {string} secretValueResourceName The name of the secret resource * value which is typically the version identifier for the value. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretValue} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretValue} [result] - The deserialized result object if an error did not occur. * See {@link SecretValue} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listValue(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretValue>; listValue(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, callback: ServiceCallback<models.SecretValue>): void; listValue(resourceGroupName: string, secretResourceName: string, secretValueResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretValue>): void; /** * @summary List names of all values of the the specified secret resource. * * Gets information about all secret value resources of the specified secret * resource. The information includes the names of the secret value resources, * but not the actual values. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SecretValueResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SecretValueResourceDescriptionList>>; /** * @summary List names of all values of the the specified secret resource. * * Gets information about all secret value resources of the specified secret * resource. The information includes the names of the secret value resources, * but not the actual values. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SecretValueResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SecretValueResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link SecretValueResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SecretValueResourceDescriptionList>; listNext(nextPageLink: string, callback: ServiceCallback<models.SecretValueResourceDescriptionList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SecretValueResourceDescriptionList>): void; } /** * @class * Volume * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface Volume { /** * @summary Creates or updates a volume resource. * * Creates a volume resource with the specified name, description and * properties. If a volume resource with the same name exists, then it is * updated with the specified description and properties. * * @param {string} resourceGroupName Azure resource group name * * @param {string} volumeResourceName The identity of the volume. * * @param {object} volumeResourceDescription Description for creating a Volume * resource. * * @param {string} [volumeResourceDescription.description] User readable * description of the volume. * * @param {object} [volumeResourceDescription.azureFileParameters] This type * describes a volume provided by an Azure Files file share. * * @param {string} volumeResourceDescription.azureFileParameters.accountName * Name of the Azure storage account for the File Share. * * @param {string} [volumeResourceDescription.azureFileParameters.accountKey] * Access key of the Azure storage account for the File Share. * * @param {string} volumeResourceDescription.azureFileParameters.shareName Name * of the Azure Files file share that provides storage for the volume. * * @param {object} [volumeResourceDescription.tags] Resource tags. * * @param {string} volumeResourceDescription.location The geo-location where * the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, volumeResourceName: string, volumeResourceDescription: models.VolumeResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeResourceDescription>>; /** * @summary Creates or updates a volume resource. * * Creates a volume resource with the specified name, description and * properties. If a volume resource with the same name exists, then it is * updated with the specified description and properties. * * @param {string} resourceGroupName Azure resource group name * * @param {string} volumeResourceName The identity of the volume. * * @param {object} volumeResourceDescription Description for creating a Volume * resource. * * @param {string} [volumeResourceDescription.description] User readable * description of the volume. * * @param {object} [volumeResourceDescription.azureFileParameters] This type * describes a volume provided by an Azure Files file share. * * @param {string} volumeResourceDescription.azureFileParameters.accountName * Name of the Azure storage account for the File Share. * * @param {string} [volumeResourceDescription.azureFileParameters.accountKey] * Access key of the Azure storage account for the File Share. * * @param {string} volumeResourceDescription.azureFileParameters.shareName Name * of the Azure Files file share that provides storage for the volume. * * @param {object} [volumeResourceDescription.tags] Resource tags. * * @param {string} volumeResourceDescription.location The geo-location where * the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link VolumeResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, volumeResourceName: string, volumeResourceDescription: models.VolumeResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeResourceDescription>; create(resourceGroupName: string, volumeResourceName: string, volumeResourceDescription: models.VolumeResourceDescription, callback: ServiceCallback<models.VolumeResourceDescription>): void; create(resourceGroupName: string, volumeResourceName: string, volumeResourceDescription: models.VolumeResourceDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeResourceDescription>): void; /** * @summary Gets the volume resource with the given name. * * Gets the information about the volume resource with the given name. The * information include the description and other properties of the volume. * * @param {string} resourceGroupName Azure resource group name * * @param {string} volumeResourceName The identity of the volume. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, volumeResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeResourceDescription>>; /** * @summary Gets the volume resource with the given name. * * Gets the information about the volume resource with the given name. The * information include the description and other properties of the volume. * * @param {string} resourceGroupName Azure resource group name * * @param {string} volumeResourceName The identity of the volume. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link VolumeResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, volumeResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeResourceDescription>; get(resourceGroupName: string, volumeResourceName: string, callback: ServiceCallback<models.VolumeResourceDescription>): void; get(resourceGroupName: string, volumeResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeResourceDescription>): void; /** * @summary Deletes the volume resource. * * Deletes the volume resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} volumeResourceName The identity of the volume. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, volumeResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the volume resource. * * Deletes the volume resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} volumeResourceName The identity of the volume. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, volumeResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, volumeResourceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, volumeResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets all the volume resources in a given resource group. * * Gets the information about all volume resources in a given resource group. * The information include the description and other properties of the Volume. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeResourceDescriptionList>>; /** * @summary Gets all the volume resources in a given resource group. * * Gets the information about all volume resources in a given resource group. * The information include the description and other properties of the Volume. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link VolumeResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeResourceDescriptionList>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.VolumeResourceDescriptionList>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeResourceDescriptionList>): void; /** * @summary Gets all the volume resources in a given subscription. * * Gets the information about all volume resources in a given resource group. * The information include the description and other properties of the volume. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeResourceDescriptionList>>; /** * @summary Gets all the volume resources in a given subscription. * * Gets the information about all volume resources in a given resource group. * The information include the description and other properties of the volume. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link VolumeResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeResourceDescriptionList>; listBySubscription(callback: ServiceCallback<models.VolumeResourceDescriptionList>): void; listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeResourceDescriptionList>): void; /** * @summary Gets all the volume resources in a given resource group. * * Gets the information about all volume resources in a given resource group. * The information include the description and other properties of the Volume. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeResourceDescriptionList>>; /** * @summary Gets all the volume resources in a given resource group. * * Gets the information about all volume resources in a given resource group. * The information include the description and other properties of the Volume. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link VolumeResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeResourceDescriptionList>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.VolumeResourceDescriptionList>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeResourceDescriptionList>): void; /** * @summary Gets all the volume resources in a given subscription. * * Gets the information about all volume resources in a given resource group. * The information include the description and other properties of the volume. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<VolumeResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.VolumeResourceDescriptionList>>; /** * @summary Gets all the volume resources in a given subscription. * * Gets the information about all volume resources in a given resource group. * The information include the description and other properties of the volume. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {VolumeResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {VolumeResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link VolumeResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.VolumeResourceDescriptionList>; listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.VolumeResourceDescriptionList>): void; listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.VolumeResourceDescriptionList>): void; } /** * @class * Network * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface Network { /** * @summary Creates or updates a network resource. * * Creates a network resource with the specified name, description and * properties. If a network resource with the same name exists, then it is * updated with the specified description and properties. * * @param {string} resourceGroupName Azure resource group name * * @param {string} networkResourceName The identity of the network. * * @param {object} networkResourceDescription Description for creating a * Network resource. * * @param {object} networkResourceDescription.properties Describes properties * of a network resource. * * @param {string} [networkResourceDescription.properties.description] User * readable description of the network. * * @param {string} networkResourceDescription.properties.kind Polymorphic * Discriminator * * @param {object} [networkResourceDescription.tags] Resource tags. * * @param {string} networkResourceDescription.location The geo-location where * the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, networkResourceName: string, networkResourceDescription: models.NetworkResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkResourceDescription>>; /** * @summary Creates or updates a network resource. * * Creates a network resource with the specified name, description and * properties. If a network resource with the same name exists, then it is * updated with the specified description and properties. * * @param {string} resourceGroupName Azure resource group name * * @param {string} networkResourceName The identity of the network. * * @param {object} networkResourceDescription Description for creating a * Network resource. * * @param {object} networkResourceDescription.properties Describes properties * of a network resource. * * @param {string} [networkResourceDescription.properties.description] User * readable description of the network. * * @param {string} networkResourceDescription.properties.kind Polymorphic * Discriminator * * @param {object} [networkResourceDescription.tags] Resource tags. * * @param {string} networkResourceDescription.location The geo-location where * the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link NetworkResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, networkResourceName: string, networkResourceDescription: models.NetworkResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkResourceDescription>; create(resourceGroupName: string, networkResourceName: string, networkResourceDescription: models.NetworkResourceDescription, callback: ServiceCallback<models.NetworkResourceDescription>): void; create(resourceGroupName: string, networkResourceName: string, networkResourceDescription: models.NetworkResourceDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkResourceDescription>): void; /** * @summary Gets the network resource with the given name. * * Gets the information about the network resource with the given name. The * information include the description and other properties of the network. * * @param {string} resourceGroupName Azure resource group name * * @param {string} networkResourceName The identity of the network. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, networkResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkResourceDescription>>; /** * @summary Gets the network resource with the given name. * * Gets the information about the network resource with the given name. The * information include the description and other properties of the network. * * @param {string} resourceGroupName Azure resource group name * * @param {string} networkResourceName The identity of the network. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link NetworkResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, networkResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkResourceDescription>; get(resourceGroupName: string, networkResourceName: string, callback: ServiceCallback<models.NetworkResourceDescription>): void; get(resourceGroupName: string, networkResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkResourceDescription>): void; /** * @summary Deletes the network resource. * * Deletes the network resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} networkResourceName The identity of the network. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, networkResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the network resource. * * Deletes the network resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} networkResourceName The identity of the network. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, networkResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, networkResourceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, networkResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets all the network resources in a given resource group. * * Gets the information about all network resources in a given resource group. * The information include the description and other properties of the Network. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkResourceDescriptionList>>; /** * @summary Gets all the network resources in a given resource group. * * Gets the information about all network resources in a given resource group. * The information include the description and other properties of the Network. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link NetworkResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkResourceDescriptionList>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.NetworkResourceDescriptionList>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkResourceDescriptionList>): void; /** * @summary Gets all the network resources in a given subscription. * * Gets the information about all network resources in a given resource group. * The information include the description and other properties of the network. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkResourceDescriptionList>>; /** * @summary Gets all the network resources in a given subscription. * * Gets the information about all network resources in a given resource group. * The information include the description and other properties of the network. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link NetworkResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkResourceDescriptionList>; listBySubscription(callback: ServiceCallback<models.NetworkResourceDescriptionList>): void; listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkResourceDescriptionList>): void; /** * @summary Gets all the network resources in a given resource group. * * Gets the information about all network resources in a given resource group. * The information include the description and other properties of the Network. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkResourceDescriptionList>>; /** * @summary Gets all the network resources in a given resource group. * * Gets the information about all network resources in a given resource group. * The information include the description and other properties of the Network. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link NetworkResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkResourceDescriptionList>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.NetworkResourceDescriptionList>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkResourceDescriptionList>): void; /** * @summary Gets all the network resources in a given subscription. * * Gets the information about all network resources in a given resource group. * The information include the description and other properties of the network. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<NetworkResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.NetworkResourceDescriptionList>>; /** * @summary Gets all the network resources in a given subscription. * * Gets the information about all network resources in a given resource group. * The information include the description and other properties of the network. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {NetworkResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {NetworkResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link NetworkResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.NetworkResourceDescriptionList>; listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.NetworkResourceDescriptionList>): void; listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.NetworkResourceDescriptionList>): void; } /** * @class * Gateway * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface Gateway { /** * @summary Creates or updates a gateway resource. * * Creates a gateway resource with the specified name, description and * properties. If a gateway resource with the same name exists, then it is * updated with the specified description and properties. Use gateway resources * to create a gateway for public connectivity for services within your * application. * * @param {string} resourceGroupName Azure resource group name * * @param {string} gatewayResourceName The identity of the gateway. * * @param {object} gatewayResourceDescription Description for creating a * Gateway resource. * * @param {string} [gatewayResourceDescription.description] User readable * description of the gateway. * * @param {object} gatewayResourceDescription.sourceNetwork Network the gateway * should listen on for requests. * * @param {object} gatewayResourceDescription.destinationNetwork Network that * the Application is using. * * @param {string} [gatewayResourceDescription.destinationNetwork.name] Name of * the network * * @param {array} [gatewayResourceDescription.destinationNetwork.endpointRefs] * A list of endpoints that are exposed on this network. * * @param {array} [gatewayResourceDescription.tcp] Configuration for tcp * connectivity for this gateway. * * @param {array} [gatewayResourceDescription.http] Configuration for http * connectivity for this gateway. * * @param {object} [gatewayResourceDescription.tags] Resource tags. * * @param {string} gatewayResourceDescription.location The geo-location where * the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, gatewayResourceName: string, gatewayResourceDescription: models.GatewayResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResourceDescription>>; /** * @summary Creates or updates a gateway resource. * * Creates a gateway resource with the specified name, description and * properties. If a gateway resource with the same name exists, then it is * updated with the specified description and properties. Use gateway resources * to create a gateway for public connectivity for services within your * application. * * @param {string} resourceGroupName Azure resource group name * * @param {string} gatewayResourceName The identity of the gateway. * * @param {object} gatewayResourceDescription Description for creating a * Gateway resource. * * @param {string} [gatewayResourceDescription.description] User readable * description of the gateway. * * @param {object} gatewayResourceDescription.sourceNetwork Network the gateway * should listen on for requests. * * @param {object} gatewayResourceDescription.destinationNetwork Network that * the Application is using. * * @param {string} [gatewayResourceDescription.destinationNetwork.name] Name of * the network * * @param {array} [gatewayResourceDescription.destinationNetwork.endpointRefs] * A list of endpoints that are exposed on this network. * * @param {array} [gatewayResourceDescription.tcp] Configuration for tcp * connectivity for this gateway. * * @param {array} [gatewayResourceDescription.http] Configuration for http * connectivity for this gateway. * * @param {object} [gatewayResourceDescription.tags] Resource tags. * * @param {string} gatewayResourceDescription.location The geo-location where * the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, gatewayResourceName: string, gatewayResourceDescription: models.GatewayResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResourceDescription>; create(resourceGroupName: string, gatewayResourceName: string, gatewayResourceDescription: models.GatewayResourceDescription, callback: ServiceCallback<models.GatewayResourceDescription>): void; create(resourceGroupName: string, gatewayResourceName: string, gatewayResourceDescription: models.GatewayResourceDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResourceDescription>): void; /** * @summary Gets the gateway resource with the given name. * * Gets the information about the gateway resource with the given name. The * information include the description and other properties of the gateway. * * @param {string} resourceGroupName Azure resource group name * * @param {string} gatewayResourceName The identity of the gateway. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, gatewayResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResourceDescription>>; /** * @summary Gets the gateway resource with the given name. * * Gets the information about the gateway resource with the given name. The * information include the description and other properties of the gateway. * * @param {string} resourceGroupName Azure resource group name * * @param {string} gatewayResourceName The identity of the gateway. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, gatewayResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResourceDescription>; get(resourceGroupName: string, gatewayResourceName: string, callback: ServiceCallback<models.GatewayResourceDescription>): void; get(resourceGroupName: string, gatewayResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResourceDescription>): void; /** * @summary Deletes the gateway resource. * * Deletes the gateway resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} gatewayResourceName The identity of the gateway. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, gatewayResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the gateway resource. * * Deletes the gateway resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} gatewayResourceName The identity of the gateway. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, gatewayResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, gatewayResourceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, gatewayResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets all the gateway resources in a given resource group. * * Gets the information about all gateway resources in a given resource group. * The information include the description and other properties of the Gateway. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResourceDescriptionList>>; /** * @summary Gets all the gateway resources in a given resource group. * * Gets the information about all gateway resources in a given resource group. * The information include the description and other properties of the Gateway. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResourceDescriptionList>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.GatewayResourceDescriptionList>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResourceDescriptionList>): void; /** * @summary Gets all the gateway resources in a given subscription. * * Gets the information about all gateway resources in a given resource group. * The information include the description and other properties of the gateway. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResourceDescriptionList>>; /** * @summary Gets all the gateway resources in a given subscription. * * Gets the information about all gateway resources in a given resource group. * The information include the description and other properties of the gateway. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResourceDescriptionList>; listBySubscription(callback: ServiceCallback<models.GatewayResourceDescriptionList>): void; listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResourceDescriptionList>): void; /** * @summary Gets all the gateway resources in a given resource group. * * Gets the information about all gateway resources in a given resource group. * The information include the description and other properties of the Gateway. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResourceDescriptionList>>; /** * @summary Gets all the gateway resources in a given resource group. * * Gets the information about all gateway resources in a given resource group. * The information include the description and other properties of the Gateway. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResourceDescriptionList>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.GatewayResourceDescriptionList>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResourceDescriptionList>): void; /** * @summary Gets all the gateway resources in a given subscription. * * Gets the information about all gateway resources in a given resource group. * The information include the description and other properties of the gateway. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<GatewayResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.GatewayResourceDescriptionList>>; /** * @summary Gets all the gateway resources in a given subscription. * * Gets the information about all gateway resources in a given resource group. * The information include the description and other properties of the gateway. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {GatewayResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {GatewayResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link GatewayResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.GatewayResourceDescriptionList>; listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.GatewayResourceDescriptionList>): void; listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.GatewayResourceDescriptionList>): void; } /** * @class * Application * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface Application { /** * @summary Creates or updates an application resource. * * Creates an application resource with the specified name, description and * properties. If an application resource with the same name exists, then it is * updated with the specified description and properties. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {object} applicationResourceDescription Description for creating a * Application resource. * * @param {string} [applicationResourceDescription.description] User readable * description of the application. * * @param {array} [applicationResourceDescription.services] Describes the * services in the application. This property is used to create or modify * services of the application. On get only the name of the service is * returned. The service description can be obtained by querying for the * service resource. * * @param {object} [applicationResourceDescription.diagnostics] Describes the * diagnostics definition and usage for an application resource. * * @param {array} [applicationResourceDescription.diagnostics.sinks] List of * supported sinks that can be referenced. * * @param {boolean} [applicationResourceDescription.diagnostics.enabled] Status * of whether or not sinks are enabled. * * @param {array} [applicationResourceDescription.diagnostics.defaultSinkRefs] * The sinks to be used if diagnostics is enabled. Sink choices can be * overridden at the service and code package level. * * @param {string} [applicationResourceDescription.debugParams] Internal - used * by Visual Studio to setup the debugging session on the local development * environment. * * @param {object} [applicationResourceDescription.tags] Resource tags. * * @param {string} applicationResourceDescription.location The geo-location * where the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ApplicationResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, applicationResourceName: string, applicationResourceDescription: models.ApplicationResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationResourceDescription>>; /** * @summary Creates or updates an application resource. * * Creates an application resource with the specified name, description and * properties. If an application resource with the same name exists, then it is * updated with the specified description and properties. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {object} applicationResourceDescription Description for creating a * Application resource. * * @param {string} [applicationResourceDescription.description] User readable * description of the application. * * @param {array} [applicationResourceDescription.services] Describes the * services in the application. This property is used to create or modify * services of the application. On get only the name of the service is * returned. The service description can be obtained by querying for the * service resource. * * @param {object} [applicationResourceDescription.diagnostics] Describes the * diagnostics definition and usage for an application resource. * * @param {array} [applicationResourceDescription.diagnostics.sinks] List of * supported sinks that can be referenced. * * @param {boolean} [applicationResourceDescription.diagnostics.enabled] Status * of whether or not sinks are enabled. * * @param {array} [applicationResourceDescription.diagnostics.defaultSinkRefs] * The sinks to be used if diagnostics is enabled. Sink choices can be * overridden at the service and code package level. * * @param {string} [applicationResourceDescription.debugParams] Internal - used * by Visual Studio to setup the debugging session on the local development * environment. * * @param {object} [applicationResourceDescription.tags] Resource tags. * * @param {string} applicationResourceDescription.location The geo-location * where the resource lives * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ApplicationResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ApplicationResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link ApplicationResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, applicationResourceName: string, applicationResourceDescription: models.ApplicationResourceDescription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationResourceDescription>; create(resourceGroupName: string, applicationResourceName: string, applicationResourceDescription: models.ApplicationResourceDescription, callback: ServiceCallback<models.ApplicationResourceDescription>): void; create(resourceGroupName: string, applicationResourceName: string, applicationResourceDescription: models.ApplicationResourceDescription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationResourceDescription>): void; /** * @summary Gets the application resource with the given name. * * Gets the information about the application resource with the given name. The * information include the description and other properties of the application. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ApplicationResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, applicationResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationResourceDescription>>; /** * @summary Gets the application resource with the given name. * * Gets the information about the application resource with the given name. The * information include the description and other properties of the application. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ApplicationResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ApplicationResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link ApplicationResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, applicationResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationResourceDescription>; get(resourceGroupName: string, applicationResourceName: string, callback: ServiceCallback<models.ApplicationResourceDescription>): void; get(resourceGroupName: string, applicationResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationResourceDescription>): void; /** * @summary Deletes the application resource. * * Deletes the application resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, applicationResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * @summary Deletes the application resource. * * Deletes the application resource identified by the name. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, applicationResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, applicationResourceName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, applicationResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * @summary Gets all the application resources in a given resource group. * * Gets the information about all application resources in a given resource * group. The information include the description and other properties of the * Application. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ApplicationResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationResourceDescriptionList>>; /** * @summary Gets all the application resources in a given resource group. * * Gets the information about all application resources in a given resource * group. The information include the description and other properties of the * Application. * * @param {string} resourceGroupName Azure resource group name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ApplicationResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ApplicationResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link ApplicationResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationResourceDescriptionList>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.ApplicationResourceDescriptionList>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationResourceDescriptionList>): void; /** * @summary Gets all the application resources in a given subscription. * * Gets the information about all application resources in a given resource * group. The information include the description and other properties of the * application. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ApplicationResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationResourceDescriptionList>>; /** * @summary Gets all the application resources in a given subscription. * * Gets the information about all application resources in a given resource * group. The information include the description and other properties of the * application. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ApplicationResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ApplicationResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link ApplicationResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationResourceDescriptionList>; listBySubscription(callback: ServiceCallback<models.ApplicationResourceDescriptionList>): void; listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationResourceDescriptionList>): void; /** * @summary Gets all the application resources in a given resource group. * * Gets the information about all application resources in a given resource * group. The information include the description and other properties of the * Application. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ApplicationResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationResourceDescriptionList>>; /** * @summary Gets all the application resources in a given resource group. * * Gets the information about all application resources in a given resource * group. The information include the description and other properties of the * Application. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ApplicationResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ApplicationResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link ApplicationResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationResourceDescriptionList>; listByResourceGroupNext(nextPageLink: string, callback: ServiceCallback<models.ApplicationResourceDescriptionList>): void; listByResourceGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationResourceDescriptionList>): void; /** * @summary Gets all the application resources in a given subscription. * * Gets the information about all application resources in a given resource * group. The information include the description and other properties of the * application. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ApplicationResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ApplicationResourceDescriptionList>>; /** * @summary Gets all the application resources in a given subscription. * * Gets the information about all application resources in a given resource * group. The information include the description and other properties of the * application. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ApplicationResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ApplicationResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link ApplicationResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscriptionNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ApplicationResourceDescriptionList>; listBySubscriptionNext(nextPageLink: string, callback: ServiceCallback<models.ApplicationResourceDescriptionList>): void; listBySubscriptionNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ApplicationResourceDescriptionList>): void; } /** * @class * Service * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface Service { /** * @summary Gets the service resource with the given name. * * Gets the information about the service resource with the given name. The * information include the description and other properties of the service. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {string} serviceResourceName The identity of the service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ServiceResourceDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceResourceDescription>>; /** * @summary Gets the service resource with the given name. * * Gets the information about the service resource with the given name. The * information include the description and other properties of the service. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {string} serviceResourceName The identity of the service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ServiceResourceDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ServiceResourceDescription} [result] - The deserialized result object if an error did not occur. * See {@link ServiceResourceDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceResourceDescription>; get(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, callback: ServiceCallback<models.ServiceResourceDescription>): void; get(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceResourceDescription>): void; /** * @summary Lists all the service resources. * * Gets the information about all services of an application resource. The * information include the description and other properties of the Service. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ServiceResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, applicationResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceResourceDescriptionList>>; /** * @summary Lists all the service resources. * * Gets the information about all services of an application resource. The * information include the description and other properties of the Service. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ServiceResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ServiceResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link ServiceResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, applicationResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceResourceDescriptionList>; list(resourceGroupName: string, applicationResourceName: string, callback: ServiceCallback<models.ServiceResourceDescriptionList>): void; list(resourceGroupName: string, applicationResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceResourceDescriptionList>): void; /** * @summary Lists all the service resources. * * Gets the information about all services of an application resource. The * information include the description and other properties of the Service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ServiceResourceDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceResourceDescriptionList>>; /** * @summary Lists all the service resources. * * Gets the information about all services of an application resource. The * information include the description and other properties of the Service. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ServiceResourceDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ServiceResourceDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link ServiceResourceDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceResourceDescriptionList>; listNext(nextPageLink: string, callback: ServiceCallback<models.ServiceResourceDescriptionList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceResourceDescriptionList>): void; } /** * @class * ServiceReplica * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface ServiceReplica { /** * @summary Gets the given replica of the service of an application. * * Gets the information about the service replica with the given name. The * information include the description and other properties of the service * replica. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {string} serviceResourceName The identity of the service. * * @param {string} replicaName Service Fabric replica name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ServiceReplicaDescription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, replicaName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceReplicaDescription>>; /** * @summary Gets the given replica of the service of an application. * * Gets the information about the service replica with the given name. The * information include the description and other properties of the service * replica. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {string} serviceResourceName The identity of the service. * * @param {string} replicaName Service Fabric replica name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ServiceReplicaDescription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ServiceReplicaDescription} [result] - The deserialized result object if an error did not occur. * See {@link ServiceReplicaDescription} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, replicaName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceReplicaDescription>; get(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, replicaName: string, callback: ServiceCallback<models.ServiceReplicaDescription>): void; get(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, replicaName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceReplicaDescription>): void; /** * @summary Gets replicas of a given service. * * Gets the information about all replicas of a given service of an * application. The information includes the runtime properties of the replica * instance. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {string} serviceResourceName The identity of the service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ServiceReplicaDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceReplicaDescriptionList>>; /** * @summary Gets replicas of a given service. * * Gets the information about all replicas of a given service of an * application. The information includes the runtime properties of the replica * instance. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {string} serviceResourceName The identity of the service. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ServiceReplicaDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ServiceReplicaDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link ServiceReplicaDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceReplicaDescriptionList>; list(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, callback: ServiceCallback<models.ServiceReplicaDescriptionList>): void; list(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceReplicaDescriptionList>): void; /** * @summary Gets replicas of a given service. * * Gets the information about all replicas of a given service of an * application. The information includes the runtime properties of the replica * instance. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ServiceReplicaDescriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ServiceReplicaDescriptionList>>; /** * @summary Gets replicas of a given service. * * Gets the information about all replicas of a given service of an * application. The information includes the runtime properties of the replica * instance. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ServiceReplicaDescriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ServiceReplicaDescriptionList} [result] - The deserialized result object if an error did not occur. * See {@link ServiceReplicaDescriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ServiceReplicaDescriptionList>; listNext(nextPageLink: string, callback: ServiceCallback<models.ServiceReplicaDescriptionList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ServiceReplicaDescriptionList>): void; } /** * @class * CodePackage * __NOTE__: An instance of this class is automatically created for an * instance of the ServiceFabricMeshManagementClient. */ export interface CodePackage { /** * @summary Gets the logs from the container. * * Gets the logs for the container of the specified code package of the service * replica. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {string} serviceResourceName The identity of the service. * * @param {string} replicaName Service Fabric replica name. * * @param {string} codePackageName The name of code package of the service. * * @param {object} [options] Optional Parameters. * * @param {number} [options.tail] Number of lines to show from the end of the * logs. Default is 100. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ContainerLogs>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getContainerLogsWithHttpOperationResponse(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, replicaName: string, codePackageName: string, options?: { tail? : number, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ContainerLogs>>; /** * @summary Gets the logs from the container. * * Gets the logs for the container of the specified code package of the service * replica. * * @param {string} resourceGroupName Azure resource group name * * @param {string} applicationResourceName The identity of the application. * * @param {string} serviceResourceName The identity of the service. * * @param {string} replicaName Service Fabric replica name. * * @param {string} codePackageName The name of code package of the service. * * @param {object} [options] Optional Parameters. * * @param {number} [options.tail] Number of lines to show from the end of the * logs. Default is 100. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ContainerLogs} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ContainerLogs} [result] - The deserialized result object if an error did not occur. * See {@link ContainerLogs} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getContainerLogs(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, replicaName: string, codePackageName: string, options?: { tail? : number, customHeaders? : { [headerName: string]: string; } }): Promise<models.ContainerLogs>; getContainerLogs(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, replicaName: string, codePackageName: string, callback: ServiceCallback<models.ContainerLogs>): void; getContainerLogs(resourceGroupName: string, applicationResourceName: string, serviceResourceName: string, replicaName: string, codePackageName: string, options: { tail? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ContainerLogs>): void; }
the_stack
module Fayde { export class FENode extends UINode implements Providers.IStyleHolder, Providers.IImplicitStyleHolder { _LocalStyle: Style; _ImplicitStyles: Style[]; _StyleMask: number; XObject: FrameworkElement; constructor(xobj: FrameworkElement) { super(xobj); var lu = this.LayoutUpdater; lu.tree.setTemplateApplier(() => { var error = new BError(); var result = this.ApplyTemplateWithError(error); if (error.Message) error.ThrowException(); return result; }); lu.setSizeUpdater({ setActualWidth (value: number) { xobj.SetCurrentValue(FrameworkElement.ActualWidthProperty, value); }, setActualHeight (value: number) { xobj.SetCurrentValue(FrameworkElement.ActualHeightProperty, value); }, onSizeChanged (oldSize: minerva.Size, newSize: minerva.Size) { xobj.SizeChanged.raise(xobj, new SizeChangedEventArgs(oldSize, newSize)); } }); } SubtreeNode: XamlNode; SetSubtreeNode(subtreeNode: XamlNode, error: BError): boolean { if (this.SubtreeNode) { this.SubtreeNode.Detach(); this.SubtreeNode = null; } if (subtreeNode && !subtreeNode.AttachTo(this, error)) return false; this.SubtreeNode = subtreeNode; return true; } GetInheritedEnumerator(): nullstone.IEnumerator<DONode> { return this.GetVisualTreeEnumerator(); } GetVisualTreeEnumerator(): nullstone.IEnumerator<FENode> { var walker = this.LayoutUpdater.tree.walk(); return { current: undefined, moveNext: function() { if (!walker.step()) return false; this.current = walker.current.getAttachedValue("$node"); return true; } }; } SetIsLoaded(value: boolean) { if (this.IsLoaded === value) return; this.IsLoaded = value; this.OnIsLoadedChanged(value); } OnIsLoadedChanged(newIsLoaded: boolean) { var xobj = this.XObject; var res = xobj.Resources; if (!newIsLoaded) { Providers.ImplicitStyleBroker.Clear(xobj, Providers.StyleMask.VisualTree); xobj.Unloaded.raise(xobj, new RoutedEventArgs()); //TODO: Should we set is loaded on resources that are FrameworkElements? } else { Providers.ImplicitStyleBroker.Set(xobj, Providers.StyleMask.All); } for (var en = this.GetVisualTreeEnumerator(); en.moveNext();) { en.current.SetIsLoaded(newIsLoaded); } if (newIsLoaded) { //TODO: Should we set is loaded on resources that are FrameworkElements? xobj.Loaded.raise(xobj, new RoutedEventArgs()); this.InvokeLoaded(); //LOOKS USELESS: //Providers.DataContextStore.EmitDataContextChanged(xobj); } } InvokeLoaded() { } AttachVisualChild(uie: UIElement, error: BError): boolean { this.OnVisualChildAttached(uie); if (!this.SetSubtreeNode(uie.XamlNode, error)) return false; uie.XamlNode.SetIsLoaded(this.IsLoaded); return true; } DetachVisualChild(uie: UIElement, error: BError) { if (!this.SetSubtreeNode(null, error)) return false; this.OnVisualChildDetached(uie); uie.XamlNode.SetIsLoaded(false); return true; } ApplyTemplateWithError(error: BError): boolean { if (this.SubtreeNode) return false; var result = this.DoApplyTemplateWithError(error); var xobj = this.XObject; if (result) xobj.OnApplyTemplate(); xobj.TemplateApplied.raise(xobj, null); return result; } DoApplyTemplateWithError(error: BError): boolean { return false; } FinishApplyTemplateWithError(uie: UIElement, error: BError): boolean { if (!uie || error.Message) return false; this.AttachVisualChild(uie, error); return error.Message == null; } UpdateLayout() { console.warn("FENode.UpdateLayout not implemented"); } static DetachFromVisualParent (xobj: UIElement) { var vpNode = <FENode>xobj.XamlNode.VisualParentNode; if (vpNode instanceof FENode) { var err = new BError(); vpNode.DetachVisualChild(xobj, err); if (err.Message) err.ThrowException(); } } } export class FrameworkElement extends UIElement implements IResourcable, Providers.IIsPropertyInheritable { XamlNode: FENode; CreateNode(): FENode { return new FENode(this); } static ActualHeightProperty = DependencyProperty.RegisterReadOnly("ActualHeight", () => Number, FrameworkElement); static ActualWidthProperty = DependencyProperty.RegisterReadOnly("ActualWidth", () => Number, FrameworkElement); static CursorProperty = DependencyProperty.Register("Cursor", () => new Enum(CursorType), FrameworkElement, CursorType.Default); static FlowDirectionProperty = InheritableOwner.FlowDirectionProperty.ExtendTo(FrameworkElement); static HeightProperty = DependencyProperty.Register("Height", () => Length, FrameworkElement, NaN); static HorizontalAlignmentProperty = DependencyProperty.Register("HorizontalAlignment", () => new Enum(HorizontalAlignment), FrameworkElement, HorizontalAlignment.Stretch); static LanguageProperty = InheritableOwner.LanguageProperty.ExtendTo(FrameworkElement); static MarginProperty = DependencyProperty.RegisterCore("Margin", () => Thickness, FrameworkElement); static MaxHeightProperty = DependencyProperty.Register("MaxHeight", () => Number, FrameworkElement, Number.POSITIVE_INFINITY); static MaxWidthProperty = DependencyProperty.Register("MaxWidth", () => Number, FrameworkElement, Number.POSITIVE_INFINITY); static MinHeightProperty = DependencyProperty.Register("MinHeight", () => Number, FrameworkElement, 0.0); static MinWidthProperty = DependencyProperty.Register("MinWidth", () => Number, FrameworkElement, 0.0); static StyleProperty = DependencyProperty.Register("Style", () => Style, FrameworkElement, undefined, (dobj, args) => Providers.LocalStyleBroker.Set(<FrameworkElement>dobj, args.NewValue)); static VerticalAlignmentProperty = DependencyProperty.Register("VerticalAlignment", () => new Enum(VerticalAlignment), FrameworkElement, VerticalAlignment.Stretch); static WidthProperty = DependencyProperty.Register("Width", () => Length, FrameworkElement, NaN); static ResourcesProperty = DependencyProperty.Register("Resources", () => ResourceDictionary, FrameworkElement); static DefaultStyleKeyProperty = DependencyProperty.Register("DefaultStyleKey", () => Function, FrameworkElement); IsInheritable(propd: DependencyProperty): boolean { if (propd === FrameworkElement.FlowDirectionProperty) return true; if (propd === FrameworkElement.LanguageProperty) return true; return super.IsInheritable(propd); } ActualHeight: number; ActualWidth: number; FlowDirection: FlowDirection; Height: number; HorizontalAlignment: HorizontalAlignment; Language: string; Margin: Thickness; MaxWidth: number; MaxHeight: number; MinWidth: number; MinHeight: number; Style: Style; VerticalAlignment: VerticalAlignment; Width: number; Resources: ResourceDictionary; DefaultStyleKey: Function; SizeChanged = new RoutedEvent<RoutedEventArgs>(); Loaded = new RoutedEvent<RoutedEventArgs>(); Unloaded = new RoutedEvent<RoutedEventArgs>(); LayoutUpdated = new nullstone.Event<nullstone.IEventArgs>(); OnApplyTemplate() { } TemplateApplied = new nullstone.Event<nullstone.IEventArgs>(); OnBindingValidationError (args: Validation.ValidationErrorEventArgs) { this.BindingValidationError.raise(this, args); } BindingValidationError = new nullstone.Event<Validation.ValidationErrorEventArgs>(); UpdateLayout() { this.XamlNode.UpdateLayout(); } } Fayde.CoreLibrary.add(FrameworkElement); FrameworkElement.ActualWidthProperty.Store = Providers.ActualSizeStore.Instance; FrameworkElement.ActualHeightProperty.Store = Providers.ActualSizeStore.Instance; FrameworkElement.ResourcesProperty.Store = Providers.ResourcesStore.Instance; module reactions { UIReaction<number>(FrameworkElement.WidthProperty, minerva.core.reactTo.width, false); UIReaction<number>(FrameworkElement.HeightProperty, minerva.core.reactTo.height, false); UIReaction<number>(FrameworkElement.MaxWidthProperty, minerva.core.reactTo.maxWidth, false); UIReaction<number>(FrameworkElement.MaxHeightProperty, minerva.core.reactTo.maxHeight, false); UIReaction<number>(FrameworkElement.MinWidthProperty, minerva.core.reactTo.minWidth, false); UIReaction<number>(FrameworkElement.MinHeightProperty, minerva.core.reactTo.minHeight, false); UIReaction<Thickness>(FrameworkElement.MarginProperty, minerva.core.reactTo.margin, false, minerva.Thickness.copyTo); UIReaction<minerva.HorizontalAlignment>(FrameworkElement.HorizontalAlignmentProperty, minerva.core.reactTo.horizontalAlignment, false); UIReaction<minerva.VerticalAlignment>(FrameworkElement.VerticalAlignmentProperty, minerva.core.reactTo.verticalAlignment, false); } }
the_stack
import async from 'async'; import { HttpResponse, RecognizedString } from 'uWebSockets.js'; import { PusherApiMessage } from './message'; import { Server } from './server'; import { Utils } from './utils'; import { Log } from './log'; const v8 = require('v8'); export interface ChannelResponse { subscription_count: number; user_count?: number; occupied: boolean; } export interface MessageCheckError { message: string; code: number; } export class HttpHandler { /** * Initialize the HTTP handler. */ constructor(protected server: Server) { // } ready(res: HttpResponse) { this.attachMiddleware(res, [ this.corsMiddleware, ]).then(res => { if (this.server.closing) { this.serverErrorResponse(res, 'The server is closing. Choose another server. :)'); } else { this.send(res, 'OK'); } }); } healthCheck(res: HttpResponse) { this.attachMiddleware(res, [ this.corsMiddleware, ]).then(res => { this.send(res, 'OK'); }); } usage(res: HttpResponse) { this.attachMiddleware(res, [ this.corsMiddleware, ]).then(res => { let { rss, heapTotal, external, arrayBuffers, } = process.memoryUsage(); let totalSize = v8.getHeapStatistics().total_available_size; let usedSize = rss + heapTotal + external + arrayBuffers; let freeSize = totalSize - usedSize; let percentUsage = (usedSize / totalSize) * 100; return this.sendJson(res, { memory: { free: freeSize, used: usedSize, total: totalSize, percent: percentUsage, }, }); }); } metrics(res: HttpResponse) { this.attachMiddleware(res, [ this.corsMiddleware, ]).then(res => { let handleError = err => { this.serverErrorResponse(res, 'A server error has occurred.'); } if (res.query.json) { this.server.metricsManager .getMetricsAsJson() .then(metrics => { this.sendJson(res, metrics); }) .catch(handleError); } else { this.server.metricsManager .getMetricsAsPlaintext() .then(metrics => { this.send(res, metrics); }) .catch(handleError); } }); } channels(res: HttpResponse) { this.attachMiddleware(res, [ this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.readRateLimitingMiddleware, ]).then(res => { this.server.adapter.getChannels(res.params.appId).then(channels => { let response: { [channel: string]: ChannelResponse } = [...channels].reduce((channels, [channel, connections]) => { if (connections.size === 0) { return channels; } channels[channel] = { subscription_count: connections.size, occupied: true, }; return channels; }, {}); return response; }).catch(err => { Log.error(err); return this.serverErrorResponse(res, 'A server error has occurred.'); }).then(channels => { let broadcastMessage = { channels }; this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage); this.sendJson(res, broadcastMessage); }); }); } channel(res: HttpResponse) { this.attachMiddleware(res, [ this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.readRateLimitingMiddleware, ]).then(res => { let response: ChannelResponse; this.server.adapter.getChannelSocketsCount(res.params.appId, res.params.channel).then(socketsCount => { response = { subscription_count: socketsCount, occupied: socketsCount > 0, }; // For presence channels, attach an user_count. // Avoid extra call to get channel members if there are no sockets. if (res.params.channel.startsWith('presence-')) { response.user_count = 0; if (response.subscription_count > 0) { this.server.adapter.getChannelMembersCount(res.params.appId, res.params.channel).then(membersCount => { let broadcastMessage = { ...response, ...{ user_count: membersCount, }, }; this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage); this.sendJson(res, broadcastMessage); }).catch(err => { Log.error(err); return this.serverErrorResponse(res, 'A server error has occurred.'); }); return; } } this.server.metricsManager.markApiMessage(res.params.appId, {}, response); return this.sendJson(res, response); }).catch(err => { Log.error(err); return this.serverErrorResponse(res, 'A server error has occurred.'); }); }); } channelUsers(res: HttpResponse) { this.attachMiddleware(res, [ this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.readRateLimitingMiddleware, ]).then(res => { if (!res.params.channel.startsWith('presence-')) { return this.badResponse(res, 'The channel must be a presence channel.'); } this.server.adapter.getChannelMembers(res.params.appId, res.params.channel).then(members => { let broadcastMessage = { users: [...members].map(([user_id, ]) => ({ id: user_id })), }; this.server.metricsManager.markApiMessage(res.params.appId, {}, broadcastMessage); this.sendJson(res, broadcastMessage); }); }); } events(res: HttpResponse) { this.attachMiddleware(res, [ this.jsonBodyMiddleware, this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.broadcastEventRateLimitingMiddleware, ]).then(res => { this.checkMessageToBroadcast(res.body as PusherApiMessage).then(message => { this.broadcastMessage(message, res.app.id); this.sendJson(res, { ok: true }); }).catch(error => { if (error.code === 400) { this.badResponse(res, error.message); } else if (error.code === 413) { this.entityTooLargeResponse(res, error.message); } }); }); } batchEvents(res: HttpResponse) { this.attachMiddleware(res, [ this.jsonBodyMiddleware, this.corsMiddleware, this.appMiddleware, this.authMiddleware, this.broadcastBatchEventsRateLimitingMiddleware, ]).then(res => { let batch = res.body.batch as PusherApiMessage[]; // Make sure the batch size is not too big. if (batch.length > this.server.options.eventLimits.maxBatchSize) { return this.badResponse(res, `Cannot batch-send more than ${this.server.options.eventLimits.maxBatchSize} messages at once`); } Promise.all(batch.map(message => this.checkMessageToBroadcast(message))).then(messages => { messages.forEach(message => this.broadcastMessage(message, res.app.id)); this.sendJson(res, { ok: true }); }).catch((error: MessageCheckError) => { if (error.code === 400) { this.badResponse(res, error.message); } else if (error.code === 413) { this.entityTooLargeResponse(res, error.message); } }); }); } protected checkMessageToBroadcast(message: PusherApiMessage): Promise<PusherApiMessage> { return new Promise((resolve, reject) => { if ( (!message.channels && !message.channel) || !message.name || !message.data ) { return reject({ message: 'The received data is incorrect', code: 400, }); } let channels: string[] = message.channels || [message.channel]; message.channels = channels; // Make sure the channels length is not too big. if (channels.length > this.server.options.eventLimits.maxChannelsAtOnce) { return reject({ message: `Cannot broadcast to more than ${this.server.options.eventLimits.maxChannelsAtOnce} channels at once`, code: 400, }); } // Make sure the event name length is not too big. if (message.name.length > this.server.options.eventLimits.maxNameLength) { return reject({ message: `Event name is too long. Maximum allowed size is ${this.server.options.eventLimits.maxNameLength}.`, code: 400, }); } let payloadSizeInKb = Utils.dataToKilobytes(message.data); // Make sure the total payload of the message body is not too big. if (payloadSizeInKb > parseFloat(this.server.options.eventLimits.maxPayloadInKb as string)) { return reject({ message: `The event data should be less than ${this.server.options.eventLimits.maxPayloadInKb} KB.`, code: 413, }); } resolve(message); }); } protected broadcastMessage(message: PusherApiMessage, appId: string): void { message.channels.forEach(channel => { this.server.adapter.send(appId, channel, JSON.stringify({ event: message.name, channel, data: message.data, }), message.socket_id); }); this.server.metricsManager.markApiMessage(appId, message, { ok: true }); } notFound(res: HttpResponse) { //Send status before any headers. res.writeStatus('404 Not Found'); this.attachMiddleware(res, [ this.corsMiddleware, ]).then(res => { this.send(res, '', '404 Not Found'); }); } protected badResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 400 }, '400 Invalid Request'); } protected notFoundResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 404 }, '404 Not Found'); } protected unauthorizedResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 401 }, '401 Unauthorized'); } protected entityTooLargeResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 413 }, '413 Payload Too Large'); } protected tooManyRequestsResponse(res: HttpResponse) { return this.sendJson(res, { error: 'Too many requests.', code: 429 }, '429 Too Many Requests'); } protected serverErrorResponse(res: HttpResponse, error: string) { return this.sendJson(res, { error, code: 500 }, '500 Internal Server Error'); } protected jsonBodyMiddleware(res: HttpResponse, next: CallableFunction): any { this.readJson(res, (body, rawBody) => { res.body = body; res.rawBody = rawBody; let requestSizeInMb = Utils.dataToMegabytes(rawBody); if (requestSizeInMb > this.server.options.httpApi.requestLimitInMb) { return this.entityTooLargeResponse(res, 'The payload size is too big.'); } next(null, res); }, err => { return this.badResponse(res, 'The received data is incorrect.'); }); } protected corsMiddleware(res: HttpResponse, next: CallableFunction): any { res.writeHeader('Access-Control-Allow-Origin', this.server.options.cors.origin.join(', ')); res.writeHeader('Access-Control-Allow-Methods', this.server.options.cors.methods.join(', ')); res.writeHeader('Access-Control-Allow-Headers', this.server.options.cors.allowedHeaders.join(', ')); next(null, res); } protected appMiddleware(res: HttpResponse, next: CallableFunction): any { return this.server.appManager.findById(res.params.appId).then(validApp => { if (!validApp) { return this.notFoundResponse(res, `The app ${res.params.appId} could not be found.`); } res.app = validApp; next(null, res); }); } protected authMiddleware(res: HttpResponse, next: CallableFunction): any { this.signatureIsValid(res).then(valid => { if (valid) { return next(null, res); } return this.unauthorizedResponse(res, 'The secret authentication failed'); }); } protected readRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any { this.server.rateLimiter.consumeReadRequestsPoints(1, res.app).then(response => { if (response.canContinue) { for (let header in response.headers) { res.writeHeader(header, '' + response.headers[header]); } return next(null, res); } this.tooManyRequestsResponse(res); }); } protected broadcastEventRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any { let channels = res.body.channels || [res.body.channel]; this.server.rateLimiter.consumeBackendEventPoints(Math.max(channels.length, 1), res.app).then(response => { if (response.canContinue) { for (let header in response.headers) { res.writeHeader(header, '' + response.headers[header]); } return next(null, res); } this.tooManyRequestsResponse(res); }); } protected broadcastBatchEventsRateLimitingMiddleware(res: HttpResponse, next: CallableFunction): any { let rateLimiterPoints = res.body.batch.reduce((rateLimiterPoints, event) => { let channels: string[] = event.channels || [event.channel]; return rateLimiterPoints += channels.length; }, 0); this.server.rateLimiter.consumeBackendEventPoints(rateLimiterPoints, res.app).then(response => { if (response.canContinue) { for (let header in response.headers) { res.writeHeader(header, '' + response.headers[header]); } return next(null, res); } this.tooManyRequestsResponse(res); }); } protected attachMiddleware(res: HttpResponse, functions: any[]): Promise<HttpResponse> { return new Promise((resolve, reject) => { let waterfallInit = callback => callback(null, res); let abortHandlerMiddleware = (res, callback) => { res.onAborted(() => { Log.warning({ message: 'Aborted request.', res }); this.serverErrorResponse(res, 'Aborted request.'); }); callback(null, res); }; async.waterfall([ waterfallInit.bind(this), abortHandlerMiddleware.bind(this), ...functions.map(fn => fn.bind(this)), ], (err, res) => { if (err) { this.serverErrorResponse(res, 'A server error has occurred.'); Log.error(err); return reject({ res, err }); } resolve(res); }); }); } /** * Read the JSON content of a request. */ protected readJson(res: HttpResponse, cb: CallableFunction, err: any) { let buffer; let loggingAction = (payload) => { if (this.server.options.debug) { Log.httpTitle('⚡ HTTP Payload received'); Log.http(payload); } }; res.onData((ab, isLast) => { let chunk = Buffer.from(ab); if (isLast) { let json = {}; let raw = '{}'; if (buffer) { try { // @ts-ignore json = JSON.parse(Buffer.concat([buffer, chunk])); } catch (e) { // } try { raw = Buffer.concat([buffer, chunk]).toString(); } catch (e) { // } cb(json, raw); loggingAction(json); } else { try { // @ts-ignore json = JSON.parse(chunk); raw = chunk.toString(); } catch (e) { // } cb(json, raw); loggingAction(json); } } else { if (buffer) { buffer = Buffer.concat([buffer, chunk]); } else { buffer = Buffer.concat([chunk]); } } }); res.onAborted(err); } /** * Check is an incoming request can access the api. */ protected signatureIsValid(res: HttpResponse): Promise<boolean> { return this.getSignedToken(res).then(token => { return token === res.query.auth_signature; }); } protected sendJson(res: HttpResponse, data: any, status: RecognizedString = '200 OK') { return res.writeStatus(status) .writeHeader('Content-Type', 'application/json') // TODO: Remove after uWS19.4 // @ts-ignore Remove after uWS 19.4 release .end(JSON.stringify(data), true); } protected send(res: HttpResponse, data: RecognizedString, status: RecognizedString = '200 OK') { return res.writeStatus(status) // TODO: Remove after uWS19.4 // @ts-ignore Remove after uWS 19.4 release .end(data, true); } /** * Get the signed token from the given request. */ protected getSignedToken(res: HttpResponse): Promise<string> { return Promise.resolve(res.app.signingTokenFromRequest(res)); } }
the_stack
* @module Polyface */ import { ConstructCurveBetweenCurves } from "../curve/ConstructCurveBetweenCurves"; import { AnyCurve, AnyRegion } from "../curve/CurveChain"; import { CurveChain, CurveCollection } from "../curve/CurveCollection"; import { CurveFactory } from "../curve/CurveFactory"; import { CurvePrimitive } from "../curve/CurvePrimitive"; import { GeometryQuery } from "../curve/GeometryQuery"; import { LineString3d } from "../curve/LineString3d"; import { ParityRegion } from "../curve/ParityRegion"; import { CylindricalRangeQuery } from "../curve/Query/CylindricalRange"; import { StrokeCountSection } from "../curve/Query/StrokeCountChain"; import { StrokeOptions } from "../curve/StrokeOptions"; import { AxisOrder, Geometry } from "../Geometry"; import { BarycentricTriangle } from "../geometry3d/BarycentricTriangle"; import { BilinearPatch } from "../geometry3d/BilinearPatch"; import { FrameBuilder } from "../geometry3d/FrameBuilder"; import { NullGeometryHandler, UVSurface } from "../geometry3d/GeometryHandler"; import { GrowableFloat64Array } from "../geometry3d/GrowableFloat64Array"; import { GrowableXYArray } from "../geometry3d/GrowableXYArray"; import { GrowableXYZArray } from "../geometry3d/GrowableXYZArray"; import { IndexedXYZCollection } from "../geometry3d/IndexedXYZCollection"; import { Matrix3d } from "../geometry3d/Matrix3d"; import { Plane3dByOriginAndVectors } from "../geometry3d/Plane3dByOriginAndVectors"; import { Point2d } from "../geometry3d/Point2dVector2d"; import { Point3dArrayCarrier } from "../geometry3d/Point3dArrayCarrier"; import { Point3d, Vector3d, XYZ } from "../geometry3d/Point3dVector3d"; import { PolygonOps } from "../geometry3d/PolygonOps"; import { Range1d, Range3d } from "../geometry3d/Range"; import { Segment1d } from "../geometry3d/Segment1d"; import { Transform } from "../geometry3d/Transform"; import { UVSurfaceOps } from "../geometry3d/UVSurfaceOps"; import { Box } from "../solid/Box"; import { Cone } from "../solid/Cone"; import { LinearSweep } from "../solid/LinearSweep"; import { RotationalSweep } from "../solid/RotationalSweep"; import { RuledSweep } from "../solid/RuledSweep"; import { Sphere } from "../solid/Sphere"; import { SweepContour } from "../solid/SweepContour"; import { TorusPipe } from "../solid/TorusPipe"; import { HalfEdge, HalfEdgeGraph, HalfEdgeToBooleanFunction } from "../topology/Graph"; import { Triangulator } from "../topology/Triangulation"; import { BoxTopology } from "./BoxTopology"; import { GreedyTriangulationBetweenLineStrings } from "./GreedyTriangulationBetweenLineStrings"; import { IndexedPolyface, PolyfaceVisitor } from "./Polyface"; /* eslint-disable @typescript-eslint/naming-convention, @typescript-eslint/prefer-for-of */ /** * A FacetSector * * initially holds coordinate data for a place where xyz and sectionDerivative are known * * normal is computed as a deferred step using an edge to adjacent place on ruled surface * * indices are set up even later. */ class FacetSector { public xyz: Point3d; public xyzIndex: number; public normal?: Vector3d; public normalIndex: number; public uv?: Point2d; public uvIndex: number; public sectionDerivative?: Vector3d; public constructor(needNormal: boolean = false, needUV: boolean = false, needSectionDerivative: boolean = false) { this.xyz = Point3d.create(); this.normalIndex = -1; this.uvIndex = -1; this.xyzIndex = -1; if (needNormal) { this.normal = Vector3d.create(); } if (needUV) { this.uv = Point2d.create(); this.uvIndex = -1; } if (needSectionDerivative) { this.sectionDerivative = Vector3d.create(); } } /** copy contents (not pointers) from source * * ASSUME all fields defined in this are defined int the source (undefined check only needed on this) */ public copyContentsFrom(other: FacetSector) { this.xyz.setFromPoint3d(other.xyz); this.xyzIndex = other.xyzIndex; if (this.normal) this.normal.setFromVector3d(other.normal!); this.normalIndex = other.normalIndex; if (this.uv) this.uv.setFrom(other.uv); this.uvIndex = other.uvIndex; if (this.sectionDerivative) this.sectionDerivative.setFrom(other.sectionDerivative); } /** access xyz, derivative from given arrays. * * ASSUME corresponding defined conditions * * xyz and derivative are set. * * index fields for updated data are cleared to -1. */ public loadIndexedPointAndDerivativeCoordinatesFromPackedArrays(i: number, packedXYZ: GrowableXYZArray, packedDerivatives?: GrowableXYZArray, fractions?: GrowableFloat64Array, v?: number) { packedXYZ.getPoint3dAtCheckedPointIndex(i, this.xyz); if (fractions && v !== undefined) this.uv = Point2d.create(fractions.atUncheckedIndex(i), v); this.xyzIndex = -1; this.normalIndex = -1; this.uvIndex = -1; if (this.sectionDerivative !== undefined && packedDerivatives !== undefined) packedDerivatives.getVector3dAtCheckedVectorIndex(i, this.sectionDerivative); } private static suppressSmallUnitVectorComponents(uvw: XYZ) { const tol = 1.0e-15; if (Math.abs(uvw.x) < tol) uvw.x = 0.0; if (Math.abs(uvw.y) < tol) uvw.y = 0.0; if (Math.abs(uvw.z) < tol) uvw.z = 0.0; } private static _edgeVector: Vector3d = Vector3d.create(); /** * given two sectors with xyz and sectionDerivative (u derivative) * use the edge from A to B as v direction in-surface derivative. * compute cross products (and normalize) * @param sectorA "lower" sector * @param sectorB "upper" sector * */ public static computeNormalsAlongRuleLine(sectorA: FacetSector, sectorB: FacetSector) { // We expect that if sectionDerivative is defined so is normal. // (If not, the cross product calls will generate normals that are never used .. not good, garbage collector will clean up.) if (sectorA.sectionDerivative && sectorB.sectionDerivative) { const vectorAB = FacetSector._edgeVector; Vector3d.createStartEnd(sectorA.xyz, sectorB.xyz, vectorAB); sectorA.sectionDerivative.crossProduct(vectorAB, sectorA.normal); sectorB.sectionDerivative.crossProduct(vectorAB, sectorB.normal); sectorA.normal!.normalizeInPlace(); sectorB.normal!.normalizeInPlace(); FacetSector.suppressSmallUnitVectorComponents(sectorA.normal!); FacetSector.suppressSmallUnitVectorComponents(sectorB.normal!); } } } /** * * * Simple construction for strongly typed GeometryQuery objects: * * * Create a builder with `builder = PolyfaceBuilder.create()` * * Add GeometryQuery objects: * * * `builder.addGeometryQuery(g: GeometryQuery)` * * `builder.addCone(cone: Cone)` * * `builder.addTorusPipe(surface: TorusPipe)` * * `builder.addLinearSweepLineStrings(surface: LinearSweep)` * * `builder.addRotationalSweep(surface: RotationalSweep)` * * `builder.addLinearSweep(surface: LinearSweep)` * * `builder.addRuledSweep(surface: RuledSweep)` * * `builder.addSphere(sphere: Sphere)` * * `builder.addBox(box: Box)` * * `builder.addIndexedPolyface(polyface)` * * Extract with `builder.claimPolyface (true)` * * * Simple construction for ephemeral constructive data: * * * Create a builder with `builder = PolyfaceBuilder.create()` * * Add from fragmentary data: * * `builder.addBetweenLineStrings (linestringA, linestringB, addClosure)` * * `builder.addBetweenTransformedLineStrings (curves, transformA, transformB, addClosure)` * * `builder.addBetweenStroked (curveA, curveB)` * * `builder.addLinearSweepLineStrings (contour, vector)` * * `builder.addPolygon (points, numPointsToUse)` * * `builder.addTransformedUnitBox (transform)` * * `builder.addTriangleFan (conePoint, linestring, toggleOrientation)` * * `builder.addTrianglesInUncheckedPolygon (linestring, toggle)` * * `builder.addUVGridBody(surface,numU, numV, createFanInCaps)` * * `builder.addGraph(Graph, acceptFaceFunction)` * * Extract with `builder.claimPolyface(true)` * * * Low-level detail construction -- direct use of indices * * Create a builder with `builder = PolyfaceBuilder.create()` * * Add GeometryQuery objects * * `builder.findOrAddPoint(point)` * * `builder.findOrAddPointInLineString (linestring, index)` * * `builder.findOrAddTransformedPointInLineString(linestring, index, transform)` * * `builder.findOrAddPointXYZ(x,y,z)` * * `builder.addTriangle (point0, point1, point2)` * * `builder.addQuad (point0, point1, point2, point3)` * * `builder.addOneBasedPointIndex (index)` * @public */ export class PolyfaceBuilder extends NullGeometryHandler { private _polyface: IndexedPolyface; private _options: StrokeOptions; /** return (pointer to) the `StrokeOptions` in use by the builder. */ public get options(): StrokeOptions { return this._options; } // State data that affects the current construction. private _reversed: boolean; /** Ask if this builder is reversing vertex order as loops are received. */ public get reversedFlag(): boolean { return this._reversed; } /** extract the polyface. */ public claimPolyface(compress: boolean = true): IndexedPolyface { if (compress) this._polyface.data.compress(); return this._polyface; } /** Toggle (reverse) the flag controlling orientation flips for newly added facets. */ public toggleReversedFacetFlag() { this._reversed = !this._reversed; } private constructor(options?: StrokeOptions) { super(); this._options = options ? options : StrokeOptions.createForFacets(); this._polyface = IndexedPolyface.create(this._options.needNormals, this._options.needParams, this._options.needColors, this._options.needTwoSided); this._reversed = false; } /** * Create a builder with given StrokeOptions * @param options StrokeOptions (captured) */ public static create(options?: StrokeOptions): PolyfaceBuilder { return new PolyfaceBuilder(options); } /** add facets for a transformed unit box. */ public addTransformedUnitBox(transform: Transform) { this.addTransformedRangeMesh(transform, Range3d.createXYZXYZ(0, 0, 0, 1, 1, 1)); } /** add facets for a transformed unit box. * * for each face in the order of BoxTopology.cornerIndexCCW, faceSelector[i]===false skips that facet. */ public addTransformedRangeMesh(transform: Transform, range: Range3d, faceSelector?: boolean[]) { const pointIndex0 = this._polyface.data.pointCount; // these will have sequential indices starting at pointIndex0 . . . const points = range.corners(); for (const p of points) this._polyface.addPoint(transform.multiplyPoint3d(p)); let faceCounter = 0; for (const facet of BoxTopology.cornerIndexCCW) { if (!faceSelector || (faceCounter < faceSelector.length && faceSelector[faceCounter])) { for (const pointIndex of facet) this._polyface.addPointIndex(pointIndex0 + pointIndex); this._polyface.terminateFacet(); } faceCounter++; } } /** Add triangles from points[0] to each far edge. * @param ls linestring with point coordinates * @param toggle if true, wrap the triangle creation in toggleReversedFacetFlag. */ public addTriangleFan(conePoint: Point3d, ls: LineString3d, toggle: boolean): void { const n = ls.numPoints(); if (n > 2) { if (toggle) this.toggleReversedFacetFlag(); const index0 = this.findOrAddPoint(conePoint); let index1 = this.findOrAddPointInLineString(ls, 0)!; let index2 = 0; for (let i = 1; i < n; i++) { index2 = this.findOrAddPointInLineString(ls, i)!; this.addIndexedTrianglePointIndexes(index0, index1, index2); index1 = index2; } if (toggle) this.toggleReversedFacetFlag(); } } /** Add triangles from points[0] to each far edge * * Assume the polygon is convex. * * i.e. simple triangulation from point0 * * i.e. simple cross products give a good normal. * @param ls linestring with point coordinates * @param reverse if true, wrap the triangle creation in toggleReversedFacetFlag. */ public addTrianglesInUncheckedConvexPolygon(ls: LineString3d, toggle: boolean): void { const n = ls.numPoints(); if (n > 2) { if (toggle) this.toggleReversedFacetFlag(); let normal; let normalIndex; if (this._options.needNormals) { normal = ls.quickUnitNormal(PolyfaceBuilder._workVectorFindOrAdd)!; if (toggle) normal.scaleInPlace(-1.0); normalIndex = this._polyface.addNormal(normal); } const needParams = this._options.needParams; const packedUV = needParams ? ls.packedUVParams : undefined; let paramIndex0 = -1; let paramIndex1 = -1; let paramIndex2 = -1; if (packedUV) { paramIndex0 = this.findOrAddParamInGrowableXYArray(packedUV, 0)!; paramIndex1 = this.findOrAddParamInGrowableXYArray(packedUV, 1)!; } const pointIndex0 = this.findOrAddPointInLineString(ls, 0)!; let pointIndex1 = this.findOrAddPointInLineString(ls, 1)!; let pointIndex2 = 0; let numEdge = n; if (ls.isPhysicallyClosed) numEdge--; for (let i = 2; i < numEdge; i++, pointIndex1 = pointIndex2, paramIndex1 = paramIndex2) { pointIndex2 = this.findOrAddPointInLineString(ls, i)!; this.addIndexedTrianglePointIndexes(pointIndex0, pointIndex1, pointIndex2, false); if (normalIndex !== undefined) this.addIndexedTriangleNormalIndexes(normalIndex, normalIndex, normalIndex); if (packedUV) { paramIndex2 = this.findOrAddParamInGrowableXYArray(packedUV, i)!; this.addIndexedTriangleParamIndexes(paramIndex0, paramIndex1, paramIndex2); } this._polyface.terminateFacet(); } if (toggle) this.toggleReversedFacetFlag(); } } /** * Announce point coordinates. The implementation is free to either create a new point or (if known) return index of a prior point with the same coordinates. */ public findOrAddPoint(xyz: Point3d): number { return this._polyface.addPoint(xyz); } /** * Announce point coordinates. The implementation is free to either create a new param or (if known) return index of a prior param with the same coordinates. */ public findOrAddParamXY(x: number, y: number): number { return this._polyface.addParamUV(x, y); } private static _workPointFindOrAddA = Point3d.create(); private static _workVectorFindOrAdd = Vector3d.create(); private static _workUVFindOrAdd = Point2d.create(); /** * Announce point coordinates. The implementation is free to either create a new point or (if known) return index of a prior point with the same coordinates. * @returns Returns the point index in the Polyface. * @param index Index of the point in the linestring. */ public findOrAddPointInLineString(ls: LineString3d, index: number, transform?: Transform, priorIndex?: number): number | undefined { const q = ls.pointAt(index, PolyfaceBuilder._workPointFindOrAddA); if (q) { if (transform) transform.multiplyPoint3d(q, q); return this._polyface.addPoint(q, priorIndex); } return undefined; } /** * Announce point coordinates. The implementation is free to either create a new point or (if known) return index of a prior point with the same coordinates. * @returns Returns the point index in the Polyface. * @param index Index of the point in the linestring. */ public findOrAddPointInGrowableXYZArray(xyz: GrowableXYZArray, index: number, transform?: Transform, priorIndex?: number): number | undefined { const q = xyz.getPoint3dAtCheckedPointIndex(index, PolyfaceBuilder._workPointFindOrAddA); if (q) { if (transform) transform.multiplyPoint3d(q, q); return this._polyface.addPoint(q, priorIndex); } return undefined; } /** * Announce point coordinates. The implementation is free to either create a new point or (if known) return index of a prior point with the same coordinates. * @returns Returns the point index in the Polyface. * @param index Index of the point in the linestring. */ public findOrAddNormalInGrowableXYZArray(xyz: GrowableXYZArray, index: number, transform?: Transform, priorIndex?: number): number | undefined { const q = xyz.getVector3dAtCheckedVectorIndex(index, PolyfaceBuilder._workVectorFindOrAdd); if (q) { if (transform) transform.multiplyVector(q, q); return this._polyface.addNormal(q, priorIndex); } return undefined; } /** * Announce param coordinates. The implementation is free to either create a new param or (if known) return index of a prior point with the same coordinates. * @returns Returns the point index in the Polyface. * @param index Index of the param in the linestring. */ public findOrAddParamInGrowableXYArray(data: GrowableXYArray, index: number): number | undefined { if (!data) return undefined; const q = data.getPoint2dAtUncheckedPointIndex(index, PolyfaceBuilder._workUVFindOrAdd); if (q) { return this._polyface.addParam(q); } return undefined; } /** * Announce param coordinates, taking u from ls.fractions and v from parameter. The implementation is free to either create a new param or (if known) return index of a prior point with the same coordinates. * @returns Returns the point index in the Polyface. * @param index Index of the point in the linestring. */ public findOrAddParamInLineString(ls: LineString3d, index: number, v: number, priorIndexA?: number, priorIndexB?: number): number | undefined { const u = (ls.fractions && index < ls.fractions.length) ? ls.fractions.atUncheckedIndex(index) : index / ls.points.length; return this._polyface.addParamUV(u, v, priorIndexA, priorIndexB); } /** * Announce normal coordinates found at index in the surfaceNormal array stored on the linestring * @returns Returns the point index in the Polyface. * @param index Index of the point in the linestring. * @param priorIndex possible prior normal index to reuse */ public findOrAddNormalInLineString(ls: LineString3d, index: number, transform?: Transform, priorIndexA?: number, priorIndexB?: number): number | undefined { const linestringNormals = ls.packedSurfaceNormals; if (linestringNormals) { const q = linestringNormals.getVector3dAtCheckedVectorIndex(index, PolyfaceBuilder._workVectorFindOrAdd); if (q) { if (transform) transform.multiplyVector(q, q); return this._polyface.addNormal(q, priorIndexA, priorIndexB); } } return undefined; } /** * Announce point coordinates. The implementation is free to either create a new point or (if known) return index of a prior point with the same coordinates. */ public findOrAddPointXYZ(x: number, y: number, z: number): number { return this._polyface.addPointXYZ(x, y, z); } /** Returns a transform who can be applied to points on a triangular facet in order to obtain UV parameters. */ private getUVTransformForTriangleFacet(pointA: Point3d, pointB: Point3d, pointC: Point3d): Transform | undefined { const vectorAB = pointA.vectorTo(pointB); const vectorAC = pointA.vectorTo(pointC); const unitAxes = Matrix3d.createRigidFromColumns(vectorAB, vectorAC, AxisOrder.XYZ); const localToWorld = Transform.createOriginAndMatrix(pointA, unitAxes); return localToWorld.inverse(); } /** Returns the normal to a triangular facet. */ private getNormalForTriangularFacet(pointA: Point3d, pointB: Point3d, pointC: Point3d): Vector3d { const vectorAB = pointA.vectorTo(pointB); const vectorAC = pointA.vectorTo(pointC); let normal = vectorAB.crossProduct(vectorAC).normalize(); normal = normal ? normal : Vector3d.create(); return normal; } // ###: Consider case where normals will be reversed and point through the other end of the facet /** * Add a quad to the polyface given its points in order around the edges. * Optionally provide params and the plane normal, otherwise they will be calculated without reference data. * Optionally mark this quad as the last piece of a face in this polyface. */ public addQuadFacet(points: Point3d[] | GrowableXYZArray, params?: Point2d[], normals?: Vector3d[]) { if (points instanceof GrowableXYZArray) points = points.getPoint3dArray(); // If params and/or normals are needed, calculate them first const needParams = this.options.needParams; const needNormals = this.options.needNormals; let param0: Point2d, param1: Point2d, param2: Point2d, param3: Point2d; let normal0: Vector3d, normal1: Vector3d, normal2: Vector3d, normal3: Vector3d; if (needParams) { if (params !== undefined && params.length > 3) { param0 = params[0]; param1 = params[1]; param2 = params[2]; param3 = params[3]; } else { const paramTransform = this.getUVTransformForTriangleFacet(points[0], points[1], points[2]); if (paramTransform === undefined) { param0 = param1 = param2 = param3 = Point2d.createZero(); } else { param0 = Point2d.createFrom(paramTransform.multiplyPoint3d(points[0])); param1 = Point2d.createFrom(paramTransform.multiplyPoint3d(points[1])); param2 = Point2d.createFrom(paramTransform.multiplyPoint3d(points[2])); param3 = Point2d.createFrom(paramTransform.multiplyPoint3d(points[3])); } } } if (needNormals) { if (normals !== undefined && normals.length > 3) { normal0 = normals[0]; normal1 = normals[1]; normal2 = normals[2]; normal3 = normals[3]; } else { normal0 = this.getNormalForTriangularFacet(points[0], points[1], points[2]); normal1 = this.getNormalForTriangularFacet(points[0], points[1], points[2]); normal2 = this.getNormalForTriangularFacet(points[0], points[1], points[2]); normal3 = this.getNormalForTriangularFacet(points[0], points[1], points[2]); } } if (this._options.shouldTriangulate) { // Add as two triangles, with a diagonal along the shortest distance const vectorAC = points[0].vectorTo(points[2]); const vectorBD = points[1].vectorTo(points[3]); // Note: We pass along any values for normals or params that we calculated if (vectorAC.magnitude() >= vectorBD.magnitude()) { this.addTriangleFacet([points[0], points[1], points[2]], needParams ? [param0!, param1!, param2!] : undefined, needNormals ? [normal0!, normal1!, normal2!] : undefined); this.addTriangleFacet([points[0], points[2], points[3]], needParams ? [param0!, param2!, param3!] : undefined, needNormals ? [normal0!, normal2!, normal3!] : undefined); } else { this.addTriangleFacet([points[0], points[1], points[3]], needParams ? [param0!, param1!, param3!] : undefined, needNormals ? [normal0!, normal1!, normal3!] : undefined); this.addTriangleFacet([points[1], points[2], points[3]], needParams ? [param1!, param2!, param3!] : undefined, needNormals ? [normal1!, normal2!, normal3!] : undefined); } return; } let idx0, idx1, idx2, idx3; // Add params if needed if (needParams) { idx0 = this._polyface.addParam(param0!); idx1 = this._polyface.addParam(param1!); idx2 = this._polyface.addParam(param2!); idx3 = this._polyface.addParam(param3!); this.addIndexedQuadParamIndexes(idx0, idx1, idx3, idx2); } // Add normals if needed if (needNormals) { idx0 = this._polyface.addNormal(normal0!); idx1 = this._polyface.addNormal(normal1!); idx2 = this._polyface.addNormal(normal2!); idx3 = this._polyface.addNormal(normal3!); this.addIndexedQuadNormalIndexes(idx0, idx1, idx3, idx2); } // Add point and point indexes last (terminates the facet) idx0 = this.findOrAddPoint(points[0]); idx1 = this.findOrAddPoint(points[1]); idx2 = this.findOrAddPoint(points[2]); idx3 = this.findOrAddPoint(points[3]); this.addIndexedQuadPointIndexes(idx0, idx1, idx3, idx2); } /** Announce a single quad facet's point indexes. * * * The actual quad may be reversed or triangulated based on builder setup. * * indexA0 and indexA1 are in the forward order at the "A" end of the quad * * indexB0 and indexB1 are in the forward order at the "B" end of the quad. */ private addIndexedQuadPointIndexes(indexA0: number, indexA1: number, indexB0: number, indexB1: number, terminate: boolean = true) { if (this._reversed) { this._polyface.addPointIndex(indexA0); this._polyface.addPointIndex(indexB0); this._polyface.addPointIndex(indexB1); this._polyface.addPointIndex(indexA1); } else { this._polyface.addPointIndex(indexA0); this._polyface.addPointIndex(indexA1); this._polyface.addPointIndex(indexB1); this._polyface.addPointIndex(indexB0); } if (terminate) this._polyface.terminateFacet(); } /** For a single quad facet, add the indexes of the corresponding param points. */ private addIndexedQuadParamIndexes(indexA0: number, indexA1: number, indexB0: number, indexB1: number) { if (this._reversed) { this._polyface.addParamIndex(indexA0); this._polyface.addParamIndex(indexB0); this._polyface.addParamIndex(indexB1); this._polyface.addParamIndex(indexA1); } else { this._polyface.addParamIndex(indexA0); this._polyface.addParamIndex(indexA1); this._polyface.addParamIndex(indexB1); this._polyface.addParamIndex(indexB0); } } /** For a single quad facet, add the indexes of the corresponding normal vectors. */ private addIndexedQuadNormalIndexes(indexA0: number, indexA1: number, indexB0: number, indexB1: number) { if (this._reversed) { this._polyface.addNormalIndex(indexA0); this._polyface.addNormalIndex(indexB0); this._polyface.addNormalIndex(indexB1); this._polyface.addNormalIndex(indexA1); } else { this._polyface.addNormalIndex(indexA0); this._polyface.addNormalIndex(indexA1); this._polyface.addNormalIndex(indexB1); this._polyface.addNormalIndex(indexB0); } } // ### TODO: Consider case where normals will be reversed and point through the other end of the facet /** * Add a triangle to the polyface given its points in order around the edges. * * Optionally provide params and triangle normals, otherwise they will be calculated without reference data. */ public addTriangleFacet(points: Point3d[] | GrowableXYZArray, params?: Point2d[], normals?: Vector3d[]) { if (points.length < 3) return; let idx0: number; let idx1: number; let idx2: number; let point0, point1, point2; if (points instanceof GrowableXYZArray) { point0 = points.getPoint3dAtCheckedPointIndex(0)!; point1 = points.getPoint3dAtCheckedPointIndex(1)!; point2 = points.getPoint3dAtCheckedPointIndex(2)!; } else { point0 = points[0]; point1 = points[1]; point2 = points[2]; } // Add params if needed if (this._options.needParams) { if (params && params.length >= 3) { // Params were given idx0 = this._polyface.addParam(params[0]); idx1 = this._polyface.addParam(params[1]); idx2 = this._polyface.addParam(params[2]); } else { // Compute params const paramTransform = this.getUVTransformForTriangleFacet(point0, point1, point2); idx0 = this._polyface.addParam(Point2d.createFrom(paramTransform ? paramTransform.multiplyPoint3d(point0) : undefined)); idx1 = this._polyface.addParam(Point2d.createFrom(paramTransform ? paramTransform.multiplyPoint3d(point1) : undefined)); idx2 = this._polyface.addParam(Point2d.createFrom(paramTransform ? paramTransform.multiplyPoint3d(point1) : undefined)); } this.addIndexedTriangleParamIndexes(idx0, idx1, idx2); } // Add normals if needed if (this._options.needNormals) { if (normals !== undefined && normals.length > 2) { // Normals were given idx0 = this._polyface.addNormal(normals[0]); idx1 = this._polyface.addNormal(normals[1]); idx2 = this._polyface.addNormal(normals[2]); } else { // Compute normals const normal = this.getNormalForTriangularFacet(point0, point1, point2); idx0 = this._polyface.addNormal(normal); idx1 = this._polyface.addNormal(normal); idx2 = this._polyface.addNormal(normal); } this.addIndexedTriangleNormalIndexes(idx0, idx1, idx2); } // Add point and point indexes last (terminates the facet) idx0 = this.findOrAddPoint(point0); idx1 = this.findOrAddPoint(point1); idx2 = this.findOrAddPoint(point2); this.addIndexedTrianglePointIndexes(idx0, idx1, idx2); } /** Announce a single triangle facet's point indexes. * * * The actual quad may be reversed or triangulated based on builder setup. */ private addIndexedTrianglePointIndexes(indexA: number, indexB: number, indexC: number, terminateFacet: boolean = true) { if (!this._reversed) { this._polyface.addPointIndex(indexA); this._polyface.addPointIndex(indexB); this._polyface.addPointIndex(indexC); } else { this._polyface.addPointIndex(indexA); this._polyface.addPointIndex(indexC); this._polyface.addPointIndex(indexB); } if (terminateFacet) this._polyface.terminateFacet(); } /** For a single triangle facet, add the indexes of the corresponding params. */ private addIndexedTriangleParamIndexes(indexA: number, indexB: number, indexC: number) { if (!this._reversed) { this._polyface.addParamIndex(indexA); this._polyface.addParamIndex(indexB); this._polyface.addParamIndex(indexC); } else { this._polyface.addParamIndex(indexA); this._polyface.addParamIndex(indexC); this._polyface.addParamIndex(indexB); } } /** For a single triangle facet, add the indexes of the corresponding params. */ private addIndexedTriangleNormalIndexes(indexA: number, indexB: number, indexC: number) { if (!this._reversed) { this._polyface.addNormalIndex(indexA); this._polyface.addNormalIndex(indexB); this._polyface.addNormalIndex(indexC); } else { this._polyface.addNormalIndex(indexA); this._polyface.addNormalIndex(indexC); this._polyface.addNormalIndex(indexB); } } /** Find or add xyzIndex and normalIndex for coordinates in the sector. */ private setSectorIndices(sector: FacetSector) { sector.xyzIndex = this.findOrAddPoint(sector.xyz); if (sector.normal) sector.normalIndex = this._polyface.addNormal(sector.normal); if (sector.uv) sector.uvIndex = this._polyface.addParam(sector.uv); } private addSectorQuadA01B01(sectorA0: FacetSector, sectorA1: FacetSector, sectorB0: FacetSector, sectorB1: FacetSector) { if (sectorA0.xyz.isAlmostEqual(sectorA1.xyz) && sectorB0.xyz.isAlmostEqual(sectorB1.xyz)) { // ignore null quad !! } else { if (this._options.needNormals) this.addIndexedQuadNormalIndexes(sectorA0.normalIndex, sectorA1.normalIndex, sectorB0.normalIndex, sectorB1.normalIndex); if (this._options.needParams) this.addIndexedQuadParamIndexes(sectorA0.uvIndex, sectorA1.uvIndex, sectorB0.uvIndex, sectorB1.uvIndex); this.addIndexedQuadPointIndexes(sectorA0.xyzIndex, sectorA1.xyzIndex, sectorB0.xyzIndex, sectorB1.xyzIndex); this._polyface.terminateFacet(); } } /** Add facets between lineStrings with matched point counts. * * surface normals are computed from (a) curve tangents in the linestrings and (b)rule line between linestrings. * * Facets are announced to addIndexedQuad. * * addIndexedQuad is free to apply reversal or triangulation options. */ public addBetweenLineStringsWithRuleEdgeNormals(lineStringA: LineString3d, vA: number, lineStringB: LineString3d, vB: number, addClosure: boolean = false) { const pointA = lineStringA.packedPoints; const pointB = lineStringB.packedPoints; const derivativeA = lineStringA.packedDerivatives; const derivativeB = lineStringB.packedDerivatives; const fractionA = lineStringA.fractions; const fractionB = lineStringB.fractions; const needNormals = this._options.needNormals; const needParams = this._options.needParams; const sectorA0 = new FacetSector(needNormals, needParams, needNormals); const sectorA1 = new FacetSector(needNormals, needParams, needNormals); const sectorB0 = new FacetSector(needNormals, needParams, needNormals); const sectorB1 = new FacetSector(needNormals, needParams, needNormals); const sectorA00 = new FacetSector(needNormals, needParams, needNormals); const sectorB00 = new FacetSector(needNormals, needParams, needNormals); const numPoints = pointA.length; if (numPoints < 2 || numPoints !== pointB.length) return; sectorA0.loadIndexedPointAndDerivativeCoordinatesFromPackedArrays(0, pointA, derivativeA, fractionA, vA); sectorB0.loadIndexedPointAndDerivativeCoordinatesFromPackedArrays(0, pointB, derivativeB, fractionB, vB); if (needNormals) FacetSector.computeNormalsAlongRuleLine(sectorA0, sectorB0); this.setSectorIndices(sectorA0); this.setSectorIndices(sectorB0); sectorA00.copyContentsFrom(sectorA0); sectorB00.copyContentsFrom(sectorB0); for (let i = 1; i < numPoints; i++) { sectorA1.loadIndexedPointAndDerivativeCoordinatesFromPackedArrays(i, pointA, derivativeA, fractionA, vA); sectorB1.loadIndexedPointAndDerivativeCoordinatesFromPackedArrays(i, pointB, derivativeA, fractionB, vB); FacetSector.computeNormalsAlongRuleLine(sectorA1, sectorB1); this.setSectorIndices(sectorA1); this.setSectorIndices(sectorB1); // create the facet ... this.addSectorQuadA01B01(sectorA0, sectorA1, sectorB0, sectorB1); sectorA0.copyContentsFrom(sectorA1); sectorB0.copyContentsFrom(sectorB1); } if (addClosure) this.addSectorQuadA01B01(sectorA0, sectorA00, sectorB0, sectorB00); } /** Add facets between lineStrings with matched point counts. * * point indices pre-stored * * normal indices pre-stored * * uv indices pre-stored */ public addBetweenLineStringsWithStoredIndices(lineStringA: LineString3d, lineStringB: LineString3d) { const pointA = lineStringA.pointIndices!; const pointB = lineStringB.pointIndices!; let normalA: GrowableFloat64Array | undefined = lineStringA.normalIndices; let normalB: GrowableFloat64Array | undefined = lineStringB.normalIndices; if (!this._options.needNormals) { normalA = undefined; normalB = undefined; } let paramA: GrowableFloat64Array | undefined = lineStringA.paramIndices; let paramB: GrowableFloat64Array | undefined = lineStringB.paramIndices; if (!this._options.needParams) { paramA = undefined; paramB = undefined; } const numPoints = pointA.length; for (let i = 1; i < numPoints; i++) { if (pointA.atUncheckedIndex(i - 1) !== pointA.atUncheckedIndex(i) || pointB.atUncheckedIndex(i - 1) !== pointB.atUncheckedIndex(i)) { this.addIndexedQuadPointIndexes(pointA.atUncheckedIndex(i - 1), pointA.atUncheckedIndex(i), pointB.atUncheckedIndex(i - 1), pointB.atUncheckedIndex(i)); if (normalA && normalB) this.addIndexedQuadNormalIndexes(normalA.atUncheckedIndex(i - 1), normalA.atUncheckedIndex(i), normalB.atUncheckedIndex(i - 1), normalB.atUncheckedIndex(i)); if (paramA && paramB) this.addIndexedQuadParamIndexes(paramA.atUncheckedIndex(i - 1), paramA.atUncheckedIndex(i), paramB.atUncheckedIndex(i - 1), paramB.atUncheckedIndex(i)); this._polyface.terminateFacet(); } } } /** Add facets between lineStrings with matched point counts. * * * Facets are announced to addIndexedQuad. * * addIndexedQuad is free to apply reversal or triangulation options. */ public addBetweenTransformedLineStrings(curves: AnyCurve, transformA: Transform, transformB: Transform, addClosure: boolean = false) { if (curves instanceof LineString3d) { const pointA = curves.points; const numPoints = pointA.length; let indexA0 = this.findOrAddPointInLineString(curves, 0, transformA)!; let indexB0 = this.findOrAddPointInLineString(curves, 0, transformB)!; const indexA00 = indexA0; const indexB00 = indexB0; let indexA1 = 0; let indexB1 = 0; for (let i = 1; i < numPoints; i++) { indexA1 = this.findOrAddPointInLineString(curves, i, transformA)!; indexB1 = this.findOrAddPointInLineString(curves, i, transformB)!; this.addIndexedQuadPointIndexes(indexA0, indexA1, indexB0, indexB1); indexA0 = indexA1; indexB0 = indexB1; } if (addClosure) this.addIndexedQuadPointIndexes(indexA0, indexA00, indexB0, indexB00); } else { const children = curves.children; // just send the children individually -- final s will fix things?? if (children) for (const c of children) { this.addBetweenTransformedLineStrings(c as AnyCurve, transformA, transformB); } } } private addBetweenStrokeSetPair(dataA: AnyCurve, vA: number, dataB: AnyCurve, vB: number) { if (dataA instanceof LineString3d && dataB instanceof LineString3d) { this.addBetweenLineStringsWithRuleEdgeNormals(dataA, vA, dataB, vB, false); } else if (dataA instanceof ParityRegion && dataB instanceof ParityRegion) { if (dataA.children.length === dataB.children.length) { for (let i = 0; i < dataA.children.length; i++) { this.addBetweenStrokeSetPair(dataA.children[i], vA, dataB.children[i], vB); } } } else if (dataA instanceof CurveChain && dataB instanceof CurveChain) { const chainA = dataA.children; const chainB = dataB.children; if (chainA.length === chainB.length) { for (let i = 0; i < chainA.length; i++) { const cpA = chainA[i]; const cpB = chainB[i]; if (cpA instanceof LineString3d && cpB instanceof LineString3d) { this.addBetweenLineStringsWithRuleEdgeNormals(cpA, vA, cpB, vB); } } } } } /** * Add facets from a Cone */ public addCone(cone: Cone) { // ensure identical stroke counts at each end . . . let strokeCount = 16; if (this._options) strokeCount = this._options.applyTolerancesToArc(cone.getMaxRadius()); let axisStrokeCount = 1; const lineStringA = cone.strokeConstantVSection(0.0, strokeCount, this._options); const lineStringB = cone.strokeConstantVSection(1.0, strokeCount, this._options); if (this._options) { const vDistanceRange = GrowableXYZArray.distanceRangeBetweenCorrespondingPoints(lineStringA.packedPoints, lineStringB.packedPoints); axisStrokeCount = this._options.applyMaxEdgeLength(1, vDistanceRange.low); } const sizes = cone.maxIsoParametricDistance(); this.addUVGridBody(cone, strokeCount, axisStrokeCount, Segment1d.create(0, sizes.x), Segment1d.create(0, sizes.y)); this.endFace(); if (cone.capped) { if (!Geometry.isSmallMetricDistance(cone.getRadiusA())) { this.addTrianglesInUncheckedConvexPolygon(lineStringA, true); // lower triangles flip this.endFace(); } if (!Geometry.isSmallMetricDistance(cone.getRadiusB())) { this.addTrianglesInUncheckedConvexPolygon(lineStringB, false); // upper triangles to not flip. this.endFace(); } } } /** * Add facets for a TorusPipe. */ public addTorusPipe(surface: TorusPipe, phiStrokeCount?: number, thetaStrokeCount?: number) { const thetaFraction = surface.getThetaFraction(); const numU = Geometry.clamp(Geometry.resolveNumber(phiStrokeCount, 8), 4, 64); const numV = Geometry.clamp( Geometry.resolveNumber(thetaStrokeCount, Math.ceil(16 * thetaFraction)), 2, 64); this.toggleReversedFacetFlag(); const sizes = surface.maxIsoParametricDistance(); this.addUVGridBody(surface, numU, numV, Segment1d.create(0, sizes.x), Segment1d.create(0, sizes.y)); this.toggleReversedFacetFlag(); if (surface.capped && thetaFraction < 1.0) { const centerFrame = surface.getConstructiveFrame()!; const minorRadius = surface.getMinorRadius(); const majorRadius = surface.getMajorRadius(); const a = 2 * minorRadius; const r0 = majorRadius - minorRadius; const r1 = majorRadius + minorRadius; const z0 = -minorRadius; const cap0ToLocal = Transform.createRowValues( a, 0, 0, r0, 0, 0, -1, 0, 0, a, 0, z0); const cap0ToWorld = centerFrame.multiplyTransformTransform(cap0ToLocal); const worldToCap0 = cap0ToWorld.inverse(); if (worldToCap0) { const ls0 = UVSurfaceOps.createLinestringOnUVLine(surface, 0, 0, 1, 0, numU, false, true); ls0.computeUVFromXYZTransform(worldToCap0); this.addTrianglesInUncheckedConvexPolygon(ls0, false); } const thetaRadians = surface.getSweepAngle().radians; const cc = Math.cos(thetaRadians); const ss = Math.sin(thetaRadians); const cap1ToLocal = Transform.createRowValues( -cc * a, 0, -ss, r1 * cc, -ss * a, 0, cc, r1 * ss, 0, a, 0, z0); const cap1ToWorld = centerFrame.multiplyTransformTransform(cap1ToLocal); const worldToCap1 = cap1ToWorld.inverse(); if (worldToCap1) { const ls1 = UVSurfaceOps.createLinestringOnUVLine(surface, 1, 1, 0, 1, numU, false, true); ls1.computeUVFromXYZTransform(worldToCap1); this.addTrianglesInUncheckedConvexPolygon(ls1, false); } } } /** * Add point data (no params, normals) for linestrings. * * This recurses through curve chains (loops and paths) * * linestrings are swept * * All other curve types are ignored. * @param vector sweep vector * @param contour contour which contains only linestrings */ public addLinearSweepLineStringsXYZOnly(contour: AnyCurve, vector: Vector3d) { if (contour instanceof LineString3d) { let pointA = Point3d.create(); let pointB = Point3d.create(); let indexA0 = 0; let indexA1 = 0; let indexB0 = 0; let indexB1 = 0; const n = contour.numPoints(); for (let i = 0; i < n; i++) { pointA = contour.pointAt(i, pointA)!; pointB = pointA.plus(vector, pointB); indexA1 = this.findOrAddPoint(pointA); indexB1 = this.findOrAddPoint(pointB); if (i > 0) { this.addIndexedQuadPointIndexes(indexA0, indexA1, indexB0, indexB1); } indexA0 = indexA1; indexB0 = indexB1; } } else if (contour instanceof CurveChain) { for (const ls of contour.children) { this.addLinearSweepLineStringsXYZOnly(ls, vector); } } } /** * Construct facets for a rotational sweep. */ public addRotationalSweep(surface: RotationalSweep) { const contour = surface.getCurves(); const section0 = StrokeCountSection.createForParityRegionOrChain(contour, this._options); const baseStrokes = section0.getStrokes(); const axis = surface.cloneAxisRay(); const perpendicularVector = CylindricalRangeQuery.computeMaxVectorFromRay(axis, baseStrokes); const swingVector = axis.direction.crossProduct(perpendicularVector); if (this._options.needNormals) CylindricalRangeQuery.buildRotationalNormalsInLineStrings(baseStrokes, axis, swingVector); const maxDistance = perpendicularVector.magnitude(); const maxPath = Math.abs(maxDistance * surface.getSweep().radians); let numStep = StrokeOptions.applyAngleTol(this._options, 1, surface.getSweep().radians, undefined); numStep = StrokeOptions.applyMaxEdgeLength(this._options, numStep, maxPath); for (let i = 1; i <= numStep; i++) { const transformA = surface.getFractionalRotationTransform((i - 1) / numStep); const transformB = surface.getFractionalRotationTransform(i / numStep); this.addBetweenRotatedStrokeSets(baseStrokes, transformA, i - 1, transformB, i); } if (surface.capped) { const capContour = surface.getSweepContourRef(); capContour.purgeFacets(); capContour.emitFacets(this, true, undefined); // final loop pass left transformA at end .. capContour.emitFacets(this, false, surface.getFractionalRotationTransform(1.0)); } } /** * Construct facets for any planar region */ public addTriangulatedRegion(region: AnyRegion) { const contour = SweepContour.createForLinearSweep(region); if (contour) contour.emitFacets(this, true, undefined); } /** * * Recursively visit all children of data. * * At each primitive, invoke the computeStrokeCountForOptions method, with options from the builder. * @param data */ public applyStrokeCountsToCurvePrimitives(data: AnyCurve | GeometryQuery) { const options = this._options; if (data instanceof CurvePrimitive) { data.computeStrokeCountForOptions(options); } else if (data instanceof CurveCollection) { const children = data.children; if (children) for (const child of children) { this.applyStrokeCountsToCurvePrimitives(child); } } } private addBetweenStrokeSetsWithRuledNormals(stroke0: AnyCurve, stroke1: AnyCurve, numVEdge: number) { const strokeSets = [stroke0]; const fractions = [0.0]; for (let vIndex = 1; vIndex < numVEdge; vIndex++) { const vFraction = vIndex / numVEdge; const strokeA = ConstructCurveBetweenCurves.interpolateBetween(stroke0, vIndex / numVEdge, stroke1) as AnyCurve; strokeSets.push(strokeA); fractions.push(vFraction); } strokeSets.push(stroke1); fractions.push(1.0); for (let vIndex = 0; vIndex < numVEdge; vIndex++) { this.addBetweenStrokeSetPair(strokeSets[vIndex], fractions[vIndex], strokeSets[vIndex + 1], fractions[vIndex + 1]); } } private createIndicesInLineString(ls: LineString3d, vParam: number, transform?: Transform) { const n = ls.numPoints(); { const pointIndices = ls.ensureEmptyPointIndices(); const index0 = this.findOrAddPointInLineString(ls, 0, transform); pointIndices.push(index0!); if (n > 1) { let indexA = index0; let indexB; for (let i = 1; i + 1 < n; i++) { indexB = this.findOrAddPointInLineString(ls, i, transform, indexA); pointIndices.push(indexB!); indexA = indexB; } // assume last point can only repeat back to zero ... indexB = this.findOrAddPointInLineString(ls, n - 1, transform, index0); pointIndices.push(indexB!); } } if (this._options.needNormals && ls.packedSurfaceNormals !== undefined) { const normalIndices = ls.ensureEmptyNormalIndices(); const normalIndex0 = this.findOrAddNormalInLineString(ls, 0, transform); normalIndices.push(normalIndex0!); let normalIndexA = normalIndex0; let normalIndexB; if (n > 1) { for (let i = 1; i + 1 < n; i++) { normalIndexB = this.findOrAddNormalInLineString(ls, i, transform, normalIndexA); normalIndices.push(normalIndexB!); normalIndexA = normalIndexB; } // assume last point can only repeat back to zero ... normalIndexB = this.findOrAddNormalInLineString(ls, n - 1, transform, normalIndex0, normalIndexA); normalIndices.push(normalIndexB!); } } if (this._options.needParams && ls.packedUVParams !== undefined) { const uvIndices = ls.ensureEmptyUVIndices(); const uvIndex0 = this.findOrAddParamInLineString(ls, 0, vParam); uvIndices.push(uvIndex0!); let uvIndexA = uvIndex0; let uvIndexB; if (n > 1) { for (let i = 1; i + 1 < n; i++) { uvIndexB = this.findOrAddParamInLineString(ls, i, vParam, uvIndexA); uvIndices.push(uvIndexB!); uvIndexA = uvIndexB; } // assume last point can only repeat back to zero ... uvIndexB = this.findOrAddParamInLineString(ls, n - 1, vParam, uvIndexA, uvIndex0); uvIndices.push(uvIndexB!); } } } private addBetweenRotatedStrokeSets(stroke0: AnyCurve, transformA: Transform, vA: number, transformB: Transform, vB: number) { if (stroke0 instanceof LineString3d) { const strokeA = stroke0.cloneTransformed(transformA) as LineString3d; this.createIndicesInLineString(strokeA, vA); const strokeB = stroke0.cloneTransformed(transformB) as LineString3d; this.createIndicesInLineString(strokeB, vB); this.addBetweenLineStringsWithStoredIndices(strokeA, strokeB); } else if (stroke0 instanceof ParityRegion) { for (let i = 0; i < stroke0.children.length; i++) { // eslint-disable-line @typescript-eslint/prefer-for-of this.addBetweenRotatedStrokeSets(stroke0.children[i], transformA, vA, transformB, vB); } } else if (stroke0 instanceof CurveChain) { const chainA = stroke0.children; for (let i = 0; i < chainA.length; i++) { // eslint-disable-line @typescript-eslint/prefer-for-of const cpA = chainA[i]; if (cpA instanceof LineString3d) { this.addBetweenRotatedStrokeSets(cpA, transformA, vA, transformB, vB); } } } } /** * * Add facets from * * The swept contour * * each cap. */ public addLinearSweep(surface: LinearSweep) { const contour = surface.getCurvesRef(); const section0 = StrokeCountSection.createForParityRegionOrChain(contour, this._options); const stroke0 = section0.getStrokes(); const sweepVector = surface.cloneSweepVector(); const sweepTransform = Transform.createTranslation(sweepVector); const stroke1 = stroke0.cloneTransformed(sweepTransform) as AnyCurve; const numVEdge = this._options.applyMaxEdgeLength(1, sweepVector.magnitude()); this.addBetweenStrokeSetsWithRuledNormals(stroke0, stroke1, numVEdge); if (surface.capped && contour.isAnyRegionType) { const contourA = surface.getSweepContourRef(); contourA.purgeFacets(); contourA.emitFacets(this, true, undefined); contourA.emitFacets(this, false, sweepTransform); } } /** * Add facets from a ruled sweep. */ public addRuledSweep(surface: RuledSweep): boolean { const contours = surface.sweepContoursRef(); let stroke0: AnyCurve | undefined; let stroke1: AnyCurve; const sectionMaps = []; for (let i = 0; i < contours.length; i++) { // eslint-disable-line @typescript-eslint/prefer-for-of sectionMaps.push(StrokeCountSection.createForParityRegionOrChain(contours[i].curves, this._options)); } if (StrokeCountSection.enforceStrokeCountCompatibility(sectionMaps)) { StrokeCountSection.enforceCompatibleDistanceSums(sectionMaps); for (let i = 0; i < contours.length; i++) { stroke1 = sectionMaps[i].getStrokes(); if (!stroke1) stroke1 = contours[i].curves.cloneStroked(); if (i > 0 && stroke0 && stroke1) { const distanceRange = Range1d.createNull(); if (StrokeCountSection.extendDistanceRangeBetweenStrokes(stroke0, stroke1, distanceRange) && !distanceRange.isNull) { const numVEdge = this._options.applyMaxEdgeLength(1, distanceRange.high); this.addBetweenStrokeSetsWithRuledNormals(stroke0, stroke1, numVEdge); } } stroke0 = stroke1; } } if (surface.capped && contours[0].curves.isAnyRegionType) { contours[0].purgeFacets(); contours[0].emitFacets(this, true, undefined); contours[contours.length - 1].purgeFacets(); contours[contours.length - 1].emitFacets(this, false, undefined); } return true; } /** * Add facets from a Sphere */ public addSphere(sphere: Sphere, strokeCount?: number) { let numStrokeTheta = strokeCount ? strokeCount : this.options.applyTolerancesToArc(sphere.maxAxisRadius()); if (Geometry.isOdd(numStrokeTheta)) numStrokeTheta += 1; const numStrokePhi = Geometry.clampToStartEnd(Math.abs(numStrokeTheta * sphere.latitudeSweepFraction), 1, Math.ceil(numStrokeTheta * 0.5)); const lineStringA = sphere.strokeConstantVSection(0.0, numStrokeTheta, this._options); if (sphere.capped && !Geometry.isSmallMetricDistance(lineStringA.quickLength())) { this.addTrianglesInUncheckedConvexPolygon(lineStringA, true); // lower triangles flip this.endFace(); } const sizes = sphere.maxIsoParametricDistance(); this.addUVGridBody(sphere, numStrokeTheta, numStrokePhi, Segment1d.create(0, sizes.x), Segment1d.create(0, sizes.y)); this.endFace(); const lineStringB = sphere.strokeConstantVSection(1.0, numStrokeTheta, this._options); if (sphere.capped && !Geometry.isSmallMetricDistance(lineStringB.quickLength())) { this.addTrianglesInUncheckedConvexPolygon(lineStringB, false); // upper triangles do not flip this.endFace(); } } /** * Add facets from a Box */ public addBox(box: Box) { const corners = box.getCorners(); const xLength = Geometry.maxXY(box.getBaseX(), box.getBaseX()); const yLength = Geometry.maxXY(box.getBaseY(), box.getTopY()); let zLength = 0.0; for (let i = 0; i < 4; i++) { zLength = Geometry.maxXY(zLength, corners[i].distance(corners[i + 4])); } const numX = this._options.applyMaxEdgeLength(1, xLength); const numY = this._options.applyMaxEdgeLength(1, yLength); const numZ = this._options.applyMaxEdgeLength(1, zLength); // Wrap the 4 out-of-plane faces as a single parameters space with "distance" advancing in x then y then negative x then negative y ... const uParamRange = Segment1d.create(0, xLength); const vParamRange = Segment1d.create(0, zLength); this.addUVGridBody(BilinearPatch.create(corners[0], corners[1], corners[4], corners[5]), numX, numZ, uParamRange, vParamRange); uParamRange.shift(xLength); this.addUVGridBody(BilinearPatch.create(corners[1], corners[3], corners[5], corners[7]), numY, numZ, uParamRange, vParamRange); uParamRange.shift(yLength); this.addUVGridBody(BilinearPatch.create(corners[3], corners[2], corners[7], corners[6]), numX, numZ, uParamRange, vParamRange); uParamRange.shift(xLength); this.addUVGridBody(BilinearPatch.create(corners[2], corners[0], corners[6], corners[4]), numY, numZ, uParamRange, vParamRange); // finally end that wraparound face !! this.endFace(); if (box.capped) { uParamRange.set(0.0, xLength); vParamRange.set(0.0, yLength); this.addUVGridBody(BilinearPatch.create(corners[4], corners[5], corners[6], corners[7]), numX, numY, uParamRange, vParamRange); this.endFace(); uParamRange.set(0.0, xLength); vParamRange.set(0.0, yLength); this.addUVGridBody(BilinearPatch.create(corners[2], corners[3], corners[0], corners[1]), numX, numY, uParamRange, vParamRange); this.endFace(); } } /** Add a polygon to the evolving facets. * * * Add points to the polyface * * indices are added (in reverse order if indicated by the builder state) * @param points array of points. This may contain extra points not to be used in the polygon * @param numPointsToUse number of points to use. */ public addPolygon(points: Point3d[], numPointsToUse?: number) { // don't use trailing points that match start point. if (numPointsToUse === undefined) numPointsToUse = points.length; while (numPointsToUse > 1 && points[numPointsToUse - 1].isAlmostEqual(points[0])) numPointsToUse--; let index = 0; if (!this._reversed) { for (let i = 0; i < numPointsToUse; i++) { index = this.findOrAddPoint(points[i]); this._polyface.addPointIndex(index); } } else { for (let i = numPointsToUse; --i >= 0;) { index = this.findOrAddPoint(points[i]); this._polyface.addPointIndex(index); } } this._polyface.terminateFacet(); } /** Add a polygon to the evolving facets. * * * Add points to the polyface * * indices are added (in reverse order if indicated by the builder state) * * Arrays with 2 or fewer points are ignored. * @param points array of points. Trailing closure points are ignored. */ public addPolygonGrowableXYZArray(points: GrowableXYZArray) { // don't use trailing points that match start point. let numPointsToUse = points.length; while (numPointsToUse > 2 && Geometry.isSmallMetricDistance(points.distanceIndexIndex(0, numPointsToUse - 1)!)) numPointsToUse--; // strip trailing duplicates while (numPointsToUse > 2 && Geometry.isSmallMetricDistance(points.distanceIndexIndex(numPointsToUse - 2, numPointsToUse - 1)!)) numPointsToUse--; // ignore triangles for which the height is less than smallMetricDistance times length // sum of edge lengths is twice the perimeter. If it is flat that's twice the largest base dimension. // cross product magnitude is twice the area. if (numPointsToUse === 3) { const cross = points.crossProductIndexIndexIndex(0, 1, 2)!; const q = cross.magnitude(); const p = points.distanceIndexIndex(0, 1)! + points.distanceIndexIndex(0, 2)! + points.distanceIndexIndex(1, 2)!; if (q < Geometry.smallMetricDistance * p) numPointsToUse = 0; } if (numPointsToUse > 2) { let index = 0; if (!this._reversed) { for (let i = 0; i < numPointsToUse; i++) { index = this.findOrAddPointInGrowableXYZArray(points, i)!; this._polyface.addPointIndex(index); } } else { for (let i = numPointsToUse; --i >= 0;) { index = this.findOrAddPointInGrowableXYZArray(points, i)!; this._polyface.addPointIndex(index); } } this._polyface.terminateFacet(); } } /** Add a polygon to the evolving facets. * * * Add points to the polyface * * indices are added (in reverse order if indicated by the builder state) * @param normals array of points. This may contain extra points not to be used in the polygon * @param numPointsToUse number of points to use. */ public addFacetFromGrowableArrays(points: GrowableXYZArray, normals: GrowableXYZArray | undefined, params: GrowableXYArray | undefined, colors: number[] | undefined) { // don't use trailing points that match start point. let numPointsToUse = points.length; while (numPointsToUse > 1 && Geometry.isSmallMetricDistance(points.distanceIndexIndex(0, numPointsToUse - 1)!)) numPointsToUse--; let index = 0; if (normals && normals.length < numPointsToUse) normals = undefined; if (params && params.length < numPointsToUse) params = undefined; if (colors && colors.length < numPointsToUse) colors = undefined; if (!this._reversed) { for (let i = 0; i < numPointsToUse; i++) { index = this.findOrAddPointInGrowableXYZArray(points, i)!; this._polyface.addPointIndex(index); if (normals) { index = this.findOrAddNormalInGrowableXYZArray(normals, i)!; this._polyface.addNormalIndex(index); } if (params) { index = this.findOrAddParamInGrowableXYArray(params, i)!; this._polyface.addParamIndex(index); } if (colors) { index = this._polyface.addColor(colors[i]); this._polyface.addColorIndex(index); } } } else { for (let i = numPointsToUse; --i >= 0;) { index = this.findOrAddPointInGrowableXYZArray(points, i)!; this._polyface.addPointIndex(index); if (normals) { index = this.findOrAddNormalInGrowableXYZArray(normals, i)!; this._polyface.addNormalIndex(index); } if (params) { index = this.findOrAddParamInGrowableXYArray(params, i)!; this._polyface.addParamIndex(index); } if (colors) { index = this._polyface.addColor(colors[i]); this._polyface.addColorIndex(index); } } } this._polyface.terminateFacet(); } /** Add the current visitor facet to the evolving polyface. * * indices are added (in reverse order if indicated by the builder state) */ public addFacetFromVisitor(visitor: PolyfaceVisitor) { this.addFacetFromGrowableArrays(visitor.point, visitor.normal, visitor.param, visitor.color); } /** Add a polyface, with optional reverse and transform. */ public addIndexedPolyface(source: IndexedPolyface, reversed: boolean, transform?: Transform) { this._polyface.addIndexedPolyface(source, reversed, transform); } /** * Produce a new FacetFaceData for all terminated facets since construction of the previous face. * Each facet number/index is mapped to the FacetFaceData through the faceToFaceData array. * Returns true if successful, and false otherwise. */ public endFace(): boolean { return this._polyface.setNewFaceData(); } /** Double dispatch handler for Cone */ public override handleCone(g: Cone): any { return this.addCone(g); } /** Double dispatch handler for TorusPipe */ public override handleTorusPipe(g: TorusPipe): any { return this.addTorusPipe(g); } /** Double dispatch handler for Sphere */ public override handleSphere(g: Sphere): any { return this.addSphere(g); } /** Double dispatch handler for Box */ public override handleBox(g: Box): any { return this.addBox(g); } /** Double dispatch handler for LinearSweep */ public override handleLinearSweep(g: LinearSweep): any { return this.addLinearSweep(g); } /** Double dispatch handler for RotationalSweep */ public override handleRotationalSweep(g: RotationalSweep): any { return this.addRotationalSweep(g); } /** Double dispatch handler for RuledSweep */ public override handleRuledSweep(g: RuledSweep): any { return this.addRuledSweep(g); } /** add facets for a GeometryQuery object. This is double dispatch through `dispatchToGeometryHandler(this)` */ public addGeometryQuery(g: GeometryQuery) { g.dispatchToGeometryHandler(this); } /** * * * Visit all faces * * Test each face with f(node) for any node on the face. * * For each face that passes, pass its coordinates to the builder. * * Rely on the builder's compress step to find common vertex coordinates * @internal */ public addGraph(graph: HalfEdgeGraph, needParams: boolean, acceptFaceFunction: HalfEdgeToBooleanFunction = HalfEdge.testNodeMaskNotExterior, isEdgeVisibleFunction: HalfEdgeToBooleanFunction | undefined = HalfEdge.testMateMaskExterior) { let index = 0; const needNormals = this._options.needNormals; let normalIndex = 0; if (needNormals) normalIndex = this._polyface.addNormalXYZ(0, 0, 1); // big assumption !!!! someday check if that's where the facets actually are!! graph.announceFaceLoops( (_graph: HalfEdgeGraph, seed: HalfEdge) => { if (acceptFaceFunction(seed) && seed.countEdgesAroundFace() > 2) { let node = seed; do { index = this.findOrAddPointXYZ(node.x, node.y, node.z); this._polyface.addPointIndex(index, isEdgeVisibleFunction === undefined ? true : isEdgeVisibleFunction(node)); if (needParams) { index = this.findOrAddParamXY(node.x, node.y); this._polyface.addParamIndex(index); } if (needNormals) { this._polyface.addNormalIndex(normalIndex); } node = node.faceSuccessor; } while (node !== seed); this._polyface.terminateFacet(); } return true; }); } /** * * * For each node in `faces` * * add all of its vertices to the polyface * * add point indices to form a new facet. * * (Note: no normal or param indices are added) * * terminate the facet * @internal */ public addGraphFaces(_graph: HalfEdgeGraph, faces: HalfEdge[]) { let index = 0; for (const seed of faces) { let node = seed; do { index = this.findOrAddPointXYZ(node.x, node.y, node.z); this._polyface.addPointIndex(index); node = node.faceSuccessor; } while (node !== seed); this._polyface.terminateFacet(); } } /** Create a polyface containing the faces of a HalfEdgeGraph, with test function to filter faces. * @internal */ public static graphToPolyface(graph: HalfEdgeGraph, options?: StrokeOptions, acceptFaceFunction: HalfEdgeToBooleanFunction = HalfEdge.testNodeMaskNotExterior): IndexedPolyface { const builder = PolyfaceBuilder.create(options); builder.addGraph(graph, builder.options.needParams, acceptFaceFunction); builder.endFace(); return builder.claimPolyface(); } /** Create a polyface containing an array of faces of a HalfEdgeGraph, with test function to filter faces. * @internal */ public static graphFacesToPolyface(graph: HalfEdgeGraph, faces: HalfEdge[]): IndexedPolyface { const builder = PolyfaceBuilder.create(); builder.addGraphFaces(graph, faces); builder.endFace(); return builder.claimPolyface(); } /** Create a polyface containing triangles in a (space) polygon. * * The polyface contains only coordinate data (no params or normals). */ public static polygonToTriangulatedPolyface(points: Point3d[], localToWorld?: Transform): IndexedPolyface | undefined { if (!localToWorld) localToWorld = FrameBuilder.createFrameWithCCWPolygon(points); if (localToWorld) { const localPoints = localToWorld.multiplyInversePoint3dArray(points)!; const areaXY = PolygonOps.areaXY(localPoints); if (areaXY < 0.0) localPoints.reverse(); const graph = Triangulator.createTriangulatedGraphFromSingleLoop(localPoints); if (graph) { const polyface = this.graphToPolyface(graph); polyface.tryTransformInPlace(localToWorld); return polyface; } } return undefined; } /** * Given arrays of coordinates for multiple facets. * * pointArray[i] is an array of 3 or 4 points * * paramArray[i] is an array of matching number of params * * normalArray[i] is an array of matching number of normals. * @param pointArray array of arrays of point coordinates * @param paramArray array of arrays of uv parameters * @param normalArray array of arrays of normals * @param endFace if true, call this.endFace after adding all the facets. */ public addCoordinateFacets(pointArray: Point3d[][], paramArray?: Point2d[][], normalArray?: Vector3d[][], endFace: boolean = false) { for (let i = 0; i < pointArray.length; i++) { const params = paramArray ? paramArray[i] : undefined; const normals = normalArray ? normalArray[i] : undefined; if (pointArray[i].length === 3) this.addTriangleFacet(pointArray[i], params, normals); else if (pointArray[i].length === 4) this.addQuadFacet(pointArray[i], params, normals); } if (endFace) this.endFace(); } /** * * Evaluate `(numU + 1) * (numV + 1)` grid points (in 0..1 in both u and v) on a surface. * * Add the facets for `numU * numV` quads. * * uv params are the 0..1 fractions. * * normals are cross products of u and v direction partial derivatives. * @param surface * @param numU number of intervals (edges) in the u direction. (Number of points is `numU + 1`) * @param numV number of intervals (edges) in the v direction. (Number of points is `numV + 1`) * @param uMap optional mapping from u fraction to parameter space (such as texture) * @param vMap optional mapping from v fraction to parameter space (such as texture) */ public addUVGridBody(surface: UVSurface, numU: number, numV: number, uMap?: Segment1d, vMap?: Segment1d) { let xyzIndex0 = new GrowableFloat64Array(numU); let xyzIndex1 = new GrowableFloat64Array(numU); let paramIndex0: GrowableFloat64Array | undefined; let paramIndex1: GrowableFloat64Array | undefined; let normalIndex0: GrowableFloat64Array | undefined; let normalIndex1: GrowableFloat64Array | undefined; const reverse = this._reversed; const needNormals = this.options.needNormals; if (needNormals) { normalIndex0 = new GrowableFloat64Array(numU); normalIndex1 = new GrowableFloat64Array(numU); } const needParams = this.options.needParams; if (needParams) { paramIndex0 = new GrowableFloat64Array(numU); paramIndex1 = new GrowableFloat64Array(numU); } let indexSwap; xyzIndex0.ensureCapacity(numU); xyzIndex1.ensureCapacity(numU); const uv = Point2d.create(); const normal = Vector3d.create(); const du = 1.0 / numU; const dv = 1.0 / numV; const plane = Plane3dByOriginAndVectors.createXYPlane(); for (let v = 0; v <= numV; v++) { // evaluate new points .... xyzIndex1.clear(); if (needNormals) normalIndex1!.clear(); if (needParams) paramIndex1!.clear(); for (let u = 0; u <= numU; u++) { const uFrac = u * du; const vFrac = v * dv; surface.uvFractionToPointAndTangents(uFrac, vFrac, plane); xyzIndex1.push(this._polyface.addPoint(plane.origin)); if (needNormals) { plane.vectorU.crossProduct(plane.vectorV, normal); normal.normalizeInPlace(); if (reverse) normal.scaleInPlace(-1.0); normalIndex1!.push(this._polyface.addNormal(normal)); } if (needParams) paramIndex1!.push(this._polyface.addParam(Point2d.create( uMap ? uMap.fractionToPoint(uFrac) : uFrac, vMap ? vMap.fractionToPoint(vFrac) : vFrac, uv))); } if (v > 0) { for (let u = 0; u < numU; u++) { if (!this._options.shouldTriangulate) { this.addIndexedQuadPointIndexes( xyzIndex0.atUncheckedIndex(u), xyzIndex0.atUncheckedIndex(u + 1), xyzIndex1.atUncheckedIndex(u), xyzIndex1.atUncheckedIndex(u + 1), false); if (needNormals) this.addIndexedQuadNormalIndexes( normalIndex0!.atUncheckedIndex(u), normalIndex0!.atUncheckedIndex(u + 1), normalIndex1!.atUncheckedIndex(u), normalIndex1!.atUncheckedIndex(u + 1)); if (needParams) this.addIndexedQuadParamIndexes( paramIndex0!.atUncheckedIndex(u), paramIndex0!.atUncheckedIndex(u + 1), paramIndex1!.atUncheckedIndex(u), paramIndex1!.atUncheckedIndex(u + 1)); this._polyface.terminateFacet(); } else { this.addIndexedTrianglePointIndexes( xyzIndex0.atUncheckedIndex(u), xyzIndex0.atUncheckedIndex(u + 1), xyzIndex1.atUncheckedIndex(u), false); if (needNormals) this.addIndexedTriangleNormalIndexes( normalIndex0!.atUncheckedIndex(u), normalIndex0!.atUncheckedIndex(u + 1), normalIndex1!.atUncheckedIndex(u)); if (needParams) this.addIndexedTriangleParamIndexes( paramIndex0!.atUncheckedIndex(u), paramIndex0!.atUncheckedIndex(u + 1), paramIndex1!.atUncheckedIndex(u)); this._polyface.terminateFacet(); this.addIndexedTrianglePointIndexes( xyzIndex1.atUncheckedIndex(u), xyzIndex0.atUncheckedIndex(u + 1), xyzIndex1.atUncheckedIndex(u + 1), false); if (needNormals) this.addIndexedTriangleNormalIndexes( normalIndex1!.atUncheckedIndex(u), normalIndex0!.atUncheckedIndex(u + 1), normalIndex1!.atUncheckedIndex(u + 1)); if (needParams) this.addIndexedTriangleParamIndexes( paramIndex1!.atUncheckedIndex(u), paramIndex0!.atUncheckedIndex(u + 1), paramIndex1!.atUncheckedIndex(u + 1)); this._polyface.terminateFacet(); } } } indexSwap = xyzIndex1; xyzIndex1 = xyzIndex0; xyzIndex0 = indexSwap; if (needParams) { indexSwap = paramIndex1; paramIndex1 = paramIndex0; paramIndex0 = indexSwap; } if (needNormals) { indexSwap = normalIndex1; normalIndex1 = normalIndex0; normalIndex0 = indexSwap; } } xyzIndex0.clear(); xyzIndex1.clear(); } /** * Triangulate the points as viewed in xy. * @param points */ public static pointsToTriangulatedPolyface(points: Point3d[]): IndexedPolyface | undefined { const graph = Triangulator.createTriangulatedGraphFromPoints(points); if (graph) return PolyfaceBuilder.graphToPolyface(graph); return undefined; } /** Create (and add to the builder) triangles that bridge the gap between two linestrings. * * Each triangle will have 1 vertex on one of the linestrings and 2 on the other * * Choice of triangles is heuristic, hence does not have a unique solution. * * Logic to choice among the various possible triangle orders prefers * * Make near-coplanar facets * * make facets with good aspect ratio. * * This is exercised with a limited number of lookahead points, i.e. greedy to make first-available decision. * @param pointsA points of first linestring. * @param pointsB points of second linestring. */ public addGreedyTriangulationBetweenLineStrings(pointsA: Point3d[] | LineString3d | IndexedXYZCollection, pointsB: Point3d[] | LineString3d | IndexedXYZCollection) { const context = GreedyTriangulationBetweenLineStrings.createContext(); context.emitTriangles( resolveToIndexedXYZCollectionOrCarrier(pointsA), resolveToIndexedXYZCollectionOrCarrier(pointsB), (triangle: BarycentricTriangle) => { this.addTriangleFacet(triangle.points); }); } private addMiteredPipesFromPoints(centerline: IndexedXYZCollection, radius: number, numFacetAround: number = 12) { const sections = CurveFactory.createMiteredPipeSections(centerline, radius); const pointA0 = Point3d.create(); const pointA1 = Point3d.create(); const pointB0 = Point3d.create(); const pointB1 = Point3d.create(); if (numFacetAround < 3) numFacetAround = 3; const df = 1.0 / numFacetAround; for (let i = 1; i < sections.length; i++) { const arcA = sections[i - 1]; const arcB = sections[i]; arcA.fractionToPoint(0.0, pointA0); arcB.fractionToPoint(0.0, pointB0); for (let k = 1; k <= numFacetAround; k++, pointA0.setFromPoint3d(pointA1), pointB0.setFromPoint3d(pointB1)) { const f = k * df; arcA.fractionToPoint(f, pointA1); arcB.fractionToPoint(f, pointB1); this.addQuadFacet([pointA0, pointB0, pointB1, pointA1]); } } } public addMiteredPipes(centerline: IndexedXYZCollection | Point3d[] | CurvePrimitive, radius: number, numFacetAround: number = 12) { if (Array.isArray(centerline)) { this.addMiteredPipesFromPoints(new Point3dArrayCarrier(centerline), radius, numFacetAround); } else if (centerline instanceof GrowableXYZArray) { this.addMiteredPipesFromPoints(centerline, radius, numFacetAround); } else if (centerline instanceof IndexedXYZCollection) { this.addMiteredPipesFromPoints(centerline, radius, numFacetAround); } else if (centerline instanceof LineString3d) { this.addMiteredPipesFromPoints(centerline.packedPoints, radius, numFacetAround); } else if (centerline instanceof GeometryQuery) { const linestring = LineString3d.create(); centerline.emitStrokes(linestring); this.addMiteredPipesFromPoints(linestring.packedPoints, radius, numFacetAround); } } } function resolveToIndexedXYZCollectionOrCarrier(points: Point3d[] | LineString3d | IndexedXYZCollection): IndexedXYZCollection { if (Array.isArray(points)) return new Point3dArrayCarrier(points); if (points instanceof LineString3d) return points.packedPoints; return points; }
the_stack
import {Component, ElementRef, Injector, OnInit, ViewChild} from '@angular/core'; import {PeriodData} from '@common/value/period.data.value'; import {PeriodComponent} from '@common/component/period/period.component'; import {AbstractUserManagementComponent} from '../../abstract.user-management.component'; import {Alert} from '@common/util/alert.util'; import {isUndefined} from 'util'; import {ActivatedRoute} from '@angular/router'; import * as _ from 'lodash'; declare let moment: any; const defaultSort = 'createdTime,desc'; @Component({ selector: 'app-user-management-approval', templateUrl: './user-management-approval.component.html' }) export class UserManagementApprovalComponent extends AbstractUserManagementComponent implements OnInit { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // date private _filterDate: PeriodData; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 사용자 리스트 public userList: any; // 상태 public statusId = 'requested,rejected'; // date public selectedDate: PeriodData; // 검색어 public searchKeyword: string; // Reject modal open/close public isRejectModalOpen: boolean = false; // Approve modal open/close public isApproveModalOpen: boolean = false; // 선택된 유저 public selectedUser: string; // 정렬 public selectedContentSort: Order = new Order(); // Reject modal 에서 reject reason 을 쓰지 않았을 떄 error msg show / hide public isErrorMsgShow: boolean = false; // Reject modal 에서 거절 사유 public rejectReason: string; // period component @ViewChild(PeriodComponent) public periodComponent: PeriodComponent; public initialPeriodData: PeriodData; // 검색 파라메터 private _searchParams: { [key: string]: string }; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(protected elementRef: ElementRef, private activatedRoute: ActivatedRoute, protected injector: Injector, ) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // Init public ngOnInit() { // Init super.ngOnInit(); this.init(); // 파라메터 조회 this.subscriptions.push( this.activatedRoute.queryParams.subscribe(params => { if (!_.isEmpty(params)) { const page = params['page']; (this.isNullOrUndefined(page)) || (this.page.page = page); const sort = params['sort']; if (!this.isNullOrUndefined(sort)) { const sortInfo = decodeURIComponent(sort).split(','); this.selectedContentSort.key = sortInfo[0]; this.selectedContentSort.sort = sortInfo[1]; } const size = params['size']; (this.isNullOrUndefined(size)) || (this.page.size = size); // Status const status = params['status']; (this.isNullOrUndefined(status)) || (this.statusId = status); // 검색어 const searchText = params['nameContains']; (this.isNullOrUndefined(searchText)) || (this.searchKeyword = searchText); const from = params['from']; const to = params['to']; this._filterDate = new PeriodData(); this._filterDate.type = 'ALL'; if (!this.isNullOrUndefined(from) && !this.isNullOrUndefined(to)) { this._filterDate.startDate = from; this._filterDate.endDate = to; this._filterDate.type = params['type']; this._filterDate.startDateStr = decodeURIComponent(from); this._filterDate.endDateStr = decodeURIComponent(to); this.initialPeriodData = this._filterDate; this.safelyDetectChanges(); } } // 퍼미션 스키마 조회 this.getUsers(); }) ); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * init 메소드 */ public init() { // 정렬 초기화 this.selectedContentSort = new Order(); this.selectedContentSort.key = 'createdTime'; this.selectedContentSort.sort = 'desc'; } /** * 가입 요청일자 변경시 * @param data 날짜 */ public onFilterDate(data: PeriodData) { // 페이지 초기화 this.page.page = 0; this.selectedDate = data; // 페이지 재 조회 this.reloadPage(); } /** * 가입 요청자 리스트 불러오기 */ public getUsers(): void { this.loadingShow(); this.userList = []; const params = this.setParam(); this.membersService.getMemberApprovalList(params).then((result) => { this.loadingHide(); this._searchParams = params; this.pageResult = result.page; this.userList = result['_embedded'] ? this.userList.concat(result['_embedded'].users) : []; }).catch((error) => { this.loadingHide(); Alert.warning(error.details); }); } /** * status change * @param status all, rejected, pending */ public changeStatus(status?: string) { if (status) { // 페이지 초기화 this.statusId = status; this.reloadPage(); } } /** * 페이지 변경 * @param data */ public changePage(data: { page: number, size: number }) { if (data) { this.page.page = data.page; this.page.size = data.size; // 재조회 this.reloadPage(false); } } // function - changePag /** * 검색하기 * @param event 키보드 이벤트 */ public searchUser(event) { if (13 === event.keyCode || 27 === event.keyCode) { if (27 === event.keyCode) { this.searchKeyword = ''; } this.reloadPage(); } } /** * Refresh filters */ public refreshFilters() { this.changeStatus('requested,rejected'); this.page.sort = defaultSort; this.searchKeyword = ''; this.selectedDate = null; this.periodComponent.setAll(); this.reloadPage(); } /** * Change User status * @param status REJECT or APPROVE * @param username */ public changeUserStatus(status: string, username: string) { if ('REJECT' === status) { this.selectedUser = username; this.rejectReason = undefined; this.isErrorMsgShow = false; this.isRejectModalOpen = true; } else if ('APPROVE' === status) { this.isApproveModalOpen = true; this.selectedUser = username; } } // function - changeUserStatus /** * 반려 모달 닫기 */ public closeRejectModal() { this.selectedUser = undefined; this.rejectReason = undefined; this.isErrorMsgShow = false; this.isRejectModalOpen = false; } // function - closeRejectModal /** * Reject button click 시 */ public rejectUser() { if (isUndefined(this.rejectReason) || this.rejectReason.trim() === '') { this.isErrorMsgShow = true; return; } else { const params = {}; params['message'] = this.rejectReason; this.loadingShow(); this.membersService.rejectUser(this.selectedUser, params).then((result) => { this.selectedUser = ''; console.log('rejected --> ', result); this.isRejectModalOpen = false; this.loadingHide(); this.reloadPage(); }).catch((err) => { this.selectedUser = ''; this.loadingHide(); Alert.warning(err.details); }) } } // function - rejectUser /** * 승인 모달에서 확인 클릭시 */ public approveUser() { this.loadingShow(); this.membersService.approveUser(this.selectedUser).then(() => { this.isApproveModalOpen = false; this.loadingHide(); this.reloadPage(); Alert.success(this.translateService.instant('msg.approval.alert.approved')); }).catch((err) => { this.loadingHide(); Alert.warning(err.details); }) } /** * 정렬 바꿈 * @param key 어떤 컬럼을 정렬 할 지 */ public sortList(key: string) { // 초기화 this.selectedContentSort.sort = this.selectedContentSort.key !== key ? 'default' : this.selectedContentSort.sort; // 정렬 정보 저장 this.selectedContentSort.key = key; if (this.selectedContentSort.key === key) { // asc, desc switch (this.selectedContentSort.sort) { case 'asc': this.selectedContentSort.sort = 'desc'; break; case 'desc': this.selectedContentSort.sort = 'asc'; break; case 'default': this.selectedContentSort.sort = 'desc'; break; } } // 데이터소스 리스트 조회 this.reloadPage(); } public clearSearchKeyword() { this.searchKeyword = ''; this.reloadPage(); } // function - clearSrchText /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 페이지를 새로 불러온다. * @param {boolean} isFirstPage */ public reloadPage(isFirstPage: boolean = true) { (isFirstPage) && (this.page.page = 0); this._searchParams = this.setParam(); this.router.navigate( [this.router.url.replace(/\?.*/gi, '')], {queryParams: this._searchParams, replaceUrl: true} ).then(); } // function - reloadPage /** * Set parameter for api */ private setParam(): any { let result: object; // 페이지, 사이즈 설정 result = { size: this.page.size, page: this.page.page, pseudoParam: (new Date()).getTime() }; result['status'] = this.statusId; // 정렬 if (this.selectedContentSort.sort !== 'default') { result['sort'] = this.selectedContentSort.key + ',' + this.selectedContentSort.sort; } // nameContains if (this.searchKeyword) { result['nameContains'] = this.searchKeyword; } // date result['type'] = 'ALL'; if (this.selectedDate && this.selectedDate.type !== 'ALL') { result['searchDateBy'] = this.selectedDate.dateType; result['type'] = this.selectedDate.type; if (this.selectedDate.startDateStr) { result['from'] = moment(this.selectedDate.startDateStr).subtract(9, 'hours').format('YYYY-MM-DDTHH:mm:ss.sss') + 'Z'; } result['to'] = moment(this.selectedDate.endDateStr).subtract(9, 'hours').format('YYYY-MM-DDTHH:mm:ss.sss') + 'Z'; } return result; } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ } class Order { key: string = 'createdTime'; sort: string = 'default'; }
the_stack
import * as actionTypes from "@nteract/actions"; import { CellId, createFrozenMediaBundle, createImmutableOutput, deleteCell, emptyCodeCell, emptyMarkdownCell, emptyNotebook, ImmutableCell, ImmutableCodeCell, ImmutableNotebook, ImmutableOutput, insertCellAfter, insertCellAt, makeCodeCell, makeMarkdownCell, makeRawCell, markCellDeleting, markCellNotDeleting, OnDiskDisplayData, OnDiskExecuteResult, OnDiskOutput, OnDiskStreamOutput, } from "@nteract/commutable"; import { UpdateDisplayDataContent } from "@nteract/messaging"; import { DocumentRecordProps, makeDocumentRecord, NotebookModel, PayloadMessage, } from "@nteract/types"; import { escapeCarriageReturnSafe } from "escape-carriage"; import { fromJS, List, Map, RecordOf, Set } from "immutable"; import has from "lodash.has"; import { v4 as uuid } from "uuid"; type KeyPath = List<string | number>; type KeyPaths = List<KeyPath>; /** * An output can be a stream of data that does not arrive at a single time. This * function handles the different types of outputs and accumulates the data * into a reduced output. * * @param {Object} outputs - Kernel output messages * @param {Object} output - Outputted to be reduced into list of outputs * @return {List<Object>} updated-outputs - Outputs + Output */ export function reduceOutputs( outputs: List<ImmutableOutput> = List(), output: OnDiskOutput ): List<ImmutableOutput> { // Find the last output to see if it's a stream type // If we don't find one, default to null const last = outputs.last(null); if (!last || !last.output_type) { return outputs.push(createImmutableOutput(output)); } if (output.output_type !== "stream" || last.output_type !== "stream") { // If the last output type or the incoming output type isn't a stream // we just add it to the outputs // This is kind of like a "break" between streams if we get error, // display_data, execute_result, etc. return outputs.push(createImmutableOutput(output)); } const streamOutput: OnDiskStreamOutput = output; if (typeof streamOutput.name === "undefined") { return outputs.push(createImmutableOutput(streamOutput)); } function appendText(text: string): string { if (typeof streamOutput.text === "string") { return escapeCarriageReturnSafe(text + streamOutput.text); } return text; } // Invariant: size > 0, outputs.last() exists if (last.name === streamOutput.name) { return outputs.updateIn([outputs.size - 1, "text"], appendText); } // Check if there's a separate stream to merge with const nextToLast = outputs.butLast().last(null); if ( nextToLast && nextToLast.output_type === "stream" && nextToLast.name === streamOutput.name ) { return outputs.updateIn([outputs.size - 2, "text"], appendText); } // If nothing else matched, just append it return outputs.push(createImmutableOutput(streamOutput)); } export function cleanCellTransient( state: NotebookModel, id: string ): RecordOf<DocumentRecordProps> { // Clear out key paths that should no longer be referenced return state .setIn(["cellPagers", id], List()) .updateIn( ["transient", "keyPathsForDisplays"], (kpfd: Map<string, KeyPaths>) => (kpfd || Map()).map((keyPaths: KeyPaths) => keyPaths.filter((keyPath: KeyPath) => keyPath.get(2) !== id) ) ) .setIn(["transient", "cellMap", id], Map()); } function setNotebookCheckpoint( state: NotebookModel ): RecordOf<DocumentRecordProps> { // Use the current version of the notebook document return state.set("savedNotebook", state.get("notebook")); } function focusCell( state: NotebookModel, action: actionTypes.FocusCell ): RecordOf<DocumentRecordProps> { return state.set("cellFocused", action.payload.id); } function clearOutputs( state: NotebookModel, action: actionTypes.ClearOutputs ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } const type = state.getIn(["notebook", "cellMap", id, "cell_type"]); const cleanedState = cleanCellTransient(state, id); if (type === "code") { return cleanedState .setIn(["notebook", "cellMap", id, "outputs"], List()) .setIn(["notebook", "cellMap", id, "execution_count"], null) .setIn(["cellPrompts", id], List()); } return cleanedState; } function toggleTagInCell( state: NotebookModel, action: actionTypes.ToggleTagInCell ): RecordOf<DocumentRecordProps> { const { id, tag } = action.payload; return state.updateIn( ["notebook", "cellMap", id, "metadata", "tags"], (tags) => { if (tags) { return tags.has(tag) ? tags.remove(tag) : tags.add(tag); } else { return Set([tag]); } } ); } function clearAllOutputs( state: NotebookModel, action: actionTypes.ClearAllOutputs | actionTypes.RestartKernel ): RecordOf<DocumentRecordProps> { // If we get a restart kernel action that said to clear outputs, we'll // handle it if ( action.type === actionTypes.RESTART_KERNEL && action.payload.outputHandling !== "Clear All" ) { return state; } // For every cell, clear the outputs and execution counts const cellMap = state .getIn(["notebook", "cellMap"]) // NOTE: My kingdom for a mergeMap .map((cell: ImmutableCell) => { if ((cell as any).get("cell_type") === "code") { return (cell as ImmutableCodeCell).merge({ outputs: List(), execution_count: null, }); } return cell; }); // Clear all the transient data too const transient = Map({ keyPathsForDisplays: Map(), cellMap: cellMap.map(() => Map()), }); return state .setIn(["notebook", "cellMap"], cellMap) .set("transient", transient) .set("cellPrompts", Map()); } type UpdatableOutputContent = | OnDiskExecuteResult | OnDiskDisplayData | UpdateDisplayDataContent; // Utility function used in two reducers below function updateAllDisplaysWithID( state: NotebookModel, content: UpdatableOutputContent ): NotebookModel { if (!content || !content.transient || !content.transient.display_id) { return state; } const keyPaths: KeyPaths = state.getIn([ "transient", "keyPathsForDisplays", content.transient.display_id, ]) || List(); const updateOutput = (output: any) => { if (output) { // We already have something here, don't change the other fields return output.merge({ data: createFrozenMediaBundle(content.data), metadata: fromJS(content.metadata || {}), }); } else if (content.output_type === "update_display_data") { // Nothing here and we have no valid output, just create a basic output return { data: createFrozenMediaBundle(content.data), metadata: fromJS(content.metadata || {}), output_type: "display_data", }; } else { // Nothing here, but we have a valid output return createImmutableOutput(content); } }; const updateOneDisplay = (currState: NotebookModel, keyPath: KeyPath) => currState.updateIn(keyPath, updateOutput); return keyPaths.reduce(updateOneDisplay, state); } function appendOutput( state: NotebookModel, action: actionTypes.AppendOutput ): RecordOf<DocumentRecordProps> { const output = action.payload.output; const cellId = action.payload.id; /** * If it is not a display_data or execute_result with * a display_id, then treat it as a normal output and don't * add its index to the keyPaths. */ if ( (output.output_type !== "execute_result" && output.output_type !== "display_data") || !has(output, "transient.display_id") ) { return state.updateIn( ["notebook", "cellMap", cellId, "outputs"], (outputs: List<ImmutableOutput>): List<ImmutableOutput> => reduceOutputs(outputs, output) ); } // We now have a display_data that includes a transient display_id // output: { // data: { 'text/html': '<b>woo</b>' } // metadata: {} // transient: { display_id: '12312' } // } // We now have a display to track const displayID = output.transient!.display_id; if (!displayID || typeof displayID !== "string") { return state; } // Every time we see a display id we're going to capture the keypath // to the output // Determine the next output index const outputIndex = state .getIn(["notebook", "cellMap", cellId, "outputs"]) .count(); // Construct the path to the output for updating later const keyPath: KeyPath = List([ "notebook", "cellMap", cellId, "outputs", outputIndex, ]); const keyPaths: KeyPaths = ( state // Extract the current list of keypaths for this displayID .getIn(["transient", "keyPathsForDisplays", displayID]) || List() ) // Append our current output's keyPath .push(keyPath); return updateAllDisplaysWithID( state.setIn(["transient", "keyPathsForDisplays", displayID], keyPaths), output ); } function updateDisplay( state: NotebookModel, action: actionTypes.UpdateDisplay ): RecordOf<DocumentRecordProps> { return updateAllDisplaysWithID(state, action.payload.content); } function focusNextCell( state: NotebookModel, action: actionTypes.FocusNextCell ): RecordOf<DocumentRecordProps> { const cellOrder = state.getIn(["notebook", "cellOrder"]); const id = action.payload.id ? action.payload.id : state.get("cellFocused"); // If for some reason we neither have an ID here or a focused cell, we just // keep the state consistent if (!id) { return state; } const curIndex = cellOrder.findIndex((foundId: CellId) => id === foundId); const curCellType = state.getIn(["notebook", "cellMap", id, "cell_type"]); const nextIndex = curIndex + 1; // When at the end, create a new cell if (nextIndex >= cellOrder.size) { if (!action.payload.createCellIfUndefined) { return state; } const cellId: string = uuid(); const cell = curCellType === "code" ? emptyCodeCell : emptyMarkdownCell; const notebook: ImmutableNotebook = state.get("notebook"); return state .set("cellFocused", cellId) .set("notebook", insertCellAt(notebook, cell, cellId, nextIndex)); } // When in the middle of the notebook document, move to the next cell return state.set("cellFocused", cellOrder.get(nextIndex)); } function focusPreviousCell( state: NotebookModel, action: actionTypes.FocusPreviousCell ): RecordOf<DocumentRecordProps> { const cellOrder = state.getIn(["notebook", "cellOrder"]); const curIndex = cellOrder.findIndex( (id: CellId) => id === action.payload.id ); const nextIndex = Math.max(0, curIndex - 1); return state.set("cellFocused", cellOrder.get(nextIndex)); } function focusCellEditor( state: NotebookModel, action: actionTypes.FocusCellEditor ): RecordOf<DocumentRecordProps> { return state.set("editorFocused", action.payload.id); } function focusNextCellEditor( state: NotebookModel, action: actionTypes.FocusNextCellEditor ): RecordOf<DocumentRecordProps> { const cellOrder: List<CellId> = state.getIn(["notebook", "cellOrder"]); const id = action.payload.id ? action.payload.id : state.get("editorFocused"); // If for some reason we neither have an ID here or a focused editor, we just // keep the state consistent if (!id) { return state; } const curIndex = cellOrder.findIndex((foundId: CellId) => id === foundId); const nextIndex = curIndex + 1; return state.set("editorFocused", cellOrder.get(nextIndex)); } function focusPreviousCellEditor( state: NotebookModel, action: actionTypes.FocusPreviousCellEditor ): RecordOf<DocumentRecordProps> { const cellOrder: List<CellId> = state.getIn(["notebook", "cellOrder"]); const curIndex = cellOrder.findIndex( (id: CellId) => id === action.payload.id ); const nextIndex = Math.max(0, curIndex - 1); return state.set("editorFocused", cellOrder.get(nextIndex)); } function moveCell( state: NotebookModel, action: actionTypes.MoveCell ): RecordOf<DocumentRecordProps> { return state.updateIn( ["notebook", "cellOrder"], (cellOrder: List<CellId>) => { const oldIndex = cellOrder.findIndex( (id: string) => id === action.payload.id ); const newIndex = cellOrder.findIndex( (id: string) => id === action.payload.destinationId ) + (action.payload.above ? 0 : 1); if (oldIndex === newIndex) { return cellOrder; } return cellOrder .splice(oldIndex, 1) .splice(newIndex - (oldIndex < newIndex ? 1 : 0), 0, action.payload.id); } ); } function markCellAsDeleting( state: NotebookModel, action: actionTypes.MarkCellAsDeleting ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } return state.update("notebook", (notebook: ImmutableNotebook) => markCellDeleting(notebook, id) ); } function unmarkCellAsDeleting( state: NotebookModel, action: actionTypes.UnmarkCellAsDeleting ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } return state.update("notebook", (notebook: ImmutableNotebook) => markCellNotDeleting(notebook, id) ); } function deleteCellFromState( state: NotebookModel, action: actionTypes.DeleteCell ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } return cleanCellTransient( state.update("notebook", (notebook: ImmutableNotebook) => deleteCell(notebook, id) ), id ); } function createCellBelow( state: NotebookModel, action: actionTypes.CreateCellBelow ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } const { cellType } = action.payload; let cell: ImmutableCell = cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell; if (action.payload.cell) { cell = action.payload.cell; } const cellId = uuid(); return state.update("notebook", (notebook: ImmutableNotebook) => { const index = notebook.get("cellOrder", List()).indexOf(id) + 1; return insertCellAt(notebook, cell, cellId, index); }); } function createCellAbove( state: NotebookModel, action: actionTypes.CreateCellAbove ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } const { cellType } = action.payload; let cell: ImmutableCell = cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell; if (action.payload.cell) { cell = action.payload.cell; } const cellId = uuid(); return state.update("notebook", (notebook: ImmutableNotebook) => { const cellOrder: List<CellId> = notebook.get("cellOrder", List()); const index = cellOrder.indexOf(id); return insertCellAt(notebook, cell, cellId, index); }); } function createCellAppend( state: NotebookModel, action: actionTypes.CreateCellAppend ): RecordOf<DocumentRecordProps> { const { cellType } = action.payload; const notebook: ImmutableNotebook = state.get("notebook"); const cellOrder: List<CellId> = notebook.get("cellOrder", List()); const cell: ImmutableCell = cellType === "markdown" ? emptyMarkdownCell : emptyCodeCell; const index = cellOrder.count(); const cellId = uuid(); return state.set("notebook", insertCellAt(notebook, cell, cellId, index)); } function acceptPayloadMessage( state: NotebookModel, action: actionTypes.AcceptPayloadMessage ): NotebookModel { const id: string = action.payload.id; const payload: PayloadMessage = action.payload.payload; if (payload.source === "page") { // append pager return state.updateIn(["cellPagers", id], (l) => (l || List()).push(payload.data) ); } else if (payload.source === "set_next_input") { if (payload.replace) { // this payload is sent in IPython when you use %load // and is intended to replace cell source return state.setIn(["notebook", "cellMap", id, "source"], payload.text); } else { // create the next cell // FIXME: This is a weird pattern. We're basically faking a dispatch here // inside a reducer and then appending to the result. I think that both of // these reducers should just handle the original action. return createCellBelow(state, { type: actionTypes.CREATE_CELL_BELOW, payload: { cellType: "code", cell: emptyCodeCell.setIn("source", payload.text || ""), id, contentRef: action.payload.contentRef, }, }); } } // If the payload is unsupported, just return the current state return state; } function setInCell( state: NotebookModel, action: actionTypes.SetInCell<string> ): RecordOf<DocumentRecordProps> { return state.setIn( ["notebook", "cellMap", action.payload.id].concat(action.payload.path), action.payload.value ); } function toggleCellOutputVisibility( state: NotebookModel, action: actionTypes.ToggleCellOutputVisibility ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } return state.setIn( ["notebook", "cellMap", id, "metadata", "jupyter", "outputs_hidden"], !state.getIn([ "notebook", "cellMap", id, "metadata", "jupyter", "outputs_hidden", ]) ); } function unhideAll( state: NotebookModel, action: actionTypes.UnhideAll ): RecordOf<DocumentRecordProps> { const { outputHidden, inputHidden } = action.payload; let metadataMixin = Map<string, boolean>(); if (outputHidden !== undefined) { metadataMixin = metadataMixin.set("outputs_hidden", outputHidden); } if (inputHidden !== undefined) { metadataMixin = metadataMixin.set("source_hidden", inputHidden); } return state.updateIn(["notebook", "cellMap"], (cellMap) => cellMap.map((cell: ImmutableCell) => { if ((cell as any).get("cell_type") === "code") { return cell.mergeIn(["metadata", "jupyter"], metadataMixin); } return cell; }) ); } function toggleCellInputVisibility( state: NotebookModel, action: actionTypes.ToggleCellInputVisibility ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } return state.setIn( ["notebook", "cellMap", id, "metadata", "jupyter", "source_hidden"], !state.getIn([ "notebook", "cellMap", id, "metadata", "jupyter", "source_hidden", ]) ); } function updateCellStatus( state: NotebookModel, action: actionTypes.UpdateCellStatus ): RecordOf<DocumentRecordProps> { const { id, status } = action.payload; return state.setIn(["transient", "cellMap", id, "status"], status); } function updateOutputMetadata( state: NotebookModel, action: actionTypes.UpdateOutputMetadata ): RecordOf<DocumentRecordProps> { const { id, metadata, index, mediaType } = action.payload; const currentOutputs = state.getIn(["notebook", "cellMap", id, "outputs"]); const updatedOutputs = currentOutputs.update(index, (item: any) => item.set( "metadata", fromJS({ [mediaType]: metadata, }) ) ); return state.setIn(["notebook", "cellMap", id, "outputs"], updatedOutputs); } function setLanguageInfo( state: NotebookModel, action: actionTypes.SetLanguageInfo ): RecordOf<DocumentRecordProps> { const langInfo = fromJS(action.payload.langInfo); return state.setIn(["notebook", "metadata", "language_info"], langInfo); } function setKernelMetadata( state: NotebookModel, action: actionTypes.SetKernelMetadata ): RecordOf<DocumentRecordProps> { const { kernelInfo } = action.payload; if (kernelInfo) { return state .setIn( ["notebook", "metadata", "kernelspec"], fromJS({ name: kernelInfo.name, language: kernelInfo.language, display_name: kernelInfo.displayName, }) ) .setIn(["notebook", "metadata", "kernel_info", "name"], kernelInfo.name); } return state; } function overwriteMetadataField( state: NotebookModel, action: actionTypes.OverwriteMetadataField ): RecordOf<DocumentRecordProps> { const { field, value } = action.payload; return state.setIn(["notebook", "metadata", field], fromJS(value)); } function deleteMetadataField( state: NotebookModel, action: actionTypes.DeleteMetadataField ): RecordOf<DocumentRecordProps> { const { field } = action.payload; return state.deleteIn(["notebook", "metadata", field]); } function copyCell( state: NotebookModel, action: actionTypes.CopyCell ): RecordOf<DocumentRecordProps> { const id = action.payload.id || state.cellFocused; const cell = state.getIn(["notebook", "cellMap", id]); if (!cell) { return state; } return state.set("copied", cell); } function cutCell( state: NotebookModel, action: actionTypes.CutCell ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } const cell = state.getIn(["notebook", "cellMap", id]); if (!cell) { return state; } // FIXME: If the cell that was cut was the focused cell, focus the cell below return state .set("copied", cell) .update("notebook", (notebook: ImmutableNotebook) => deleteCell(notebook, id) ); } function pasteCell(state: NotebookModel): RecordOf<DocumentRecordProps> { const copiedCell = state.get("copied"); const pasteAfter = state.cellFocused; if (!copiedCell || !pasteAfter) { return state; } // Create a new cell with `id` that will come after the currently focused cell // using the contents of the originally copied cell const id = uuid(); return state.update("notebook", (notebook: ImmutableNotebook) => insertCellAfter(notebook, copiedCell, id, pasteAfter) ); } function changeCellType( state: NotebookModel, action: actionTypes.ChangeCellType ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } const { to } = action.payload; const cell = state.getIn(["notebook", "cellMap", id]); const from = cell.cell_type; // NOOP, since we're already that cell type if (from === to) { return state; } let nextState = state; // from === "code" if (from === "code") { nextState = cleanCellTransient( state .deleteIn(["notebook", "cellMap", id, "execution_count"]) .deleteIn(["notebook", "cellMap", id, "outputs"]), id ); } switch (to) { case "code": return nextState.setIn( ["notebook", "cellMap", id], makeCodeCell({ source: cell.source, }) ); case "markdown": return nextState.setIn( ["notebook", "cellMap", id], makeMarkdownCell({ source: cell.source, }) ); case "raw": return nextState.setIn( ["notebook", "cellMap", id], makeRawCell({ source: cell.source, }) ); } // If we didn't match on the `to`, we should change nothing as we don't implement // other cell types (as there aren't any) return state; } function toggleOutputExpansion( state: NotebookModel, action: actionTypes.ToggleCellExpansion ): RecordOf<DocumentRecordProps> { const id = action.payload.id ? action.payload.id : state.cellFocused; if (!id) { return state; } return state.updateIn( ["notebook", "cellMap"], (cells: Map<CellId, ImmutableCell>) => { const scrolled = cells.getIn([id, "metadata", "scrolled"]); const isCurrentlyScrolled = scrolled !== false; return cells.setIn( [id, "metadata", "scrolled"], !isCurrentlyScrolled ) } ); } function promptInputRequest( state: NotebookModel, action: actionTypes.PromptInputRequest ): RecordOf<DocumentRecordProps> { const { id, password, prompt } = action.payload; return state.updateIn(["cellPrompts", id], (prompts) => prompts.push({ prompt, password, }) ); } function interruptKernelSuccessful( state: NotebookModel, action: actionTypes.InterruptKernelSuccessful ): RecordOf<DocumentRecordProps> { return state.updateIn(["transient", "cellMap"], (cells) => cells.map((cell: Map<string, string>) => { if (cell.get("status") === "queued" || cell.get("status") === "running") { return cell.set("status", ""); } return cell; }) ); } type DocumentAction = | actionTypes.ToggleTagInCell | actionTypes.FocusPreviousCellEditor | actionTypes.FocusPreviousCell | actionTypes.FocusNextCellEditor | actionTypes.FocusNextCell | actionTypes.FocusCellEditor | actionTypes.FocusCell | actionTypes.ClearOutputs | actionTypes.AppendOutput | actionTypes.UpdateDisplay | actionTypes.MoveCell | actionTypes.MarkCellAsDeleting | actionTypes.UnmarkCellAsDeleting | actionTypes.DeleteCell | actionTypes.CreateCellBelow | actionTypes.CreateCellAbove | actionTypes.CreateCellAppend | actionTypes.ToggleCellOutputVisibility | actionTypes.ToggleCellInputVisibility | actionTypes.UpdateCellStatus | actionTypes.UpdateOutputMetadata | actionTypes.SetLanguageInfo | actionTypes.SetKernelMetadata | actionTypes.OverwriteMetadataField | actionTypes.DeleteMetadataField | actionTypes.CopyCell | actionTypes.CutCell | actionTypes.PasteCell | actionTypes.ChangeCellType | actionTypes.ToggleCellExpansion | actionTypes.AcceptPayloadMessage | actionTypes.SendExecuteRequest | actionTypes.SaveFulfilled | actionTypes.RestartKernel | actionTypes.ClearAllOutputs | actionTypes.SetInCell<any> | actionTypes.UnhideAll | actionTypes.PromptInputRequest | actionTypes.InterruptKernelSuccessful; const defaultDocument: NotebookModel = makeDocumentRecord({ notebook: emptyNotebook, }); export function notebook( state: NotebookModel = defaultDocument, action: DocumentAction ): RecordOf<DocumentRecordProps> { switch (action.type) { case actionTypes.TOGGLE_TAG_IN_CELL: return toggleTagInCell(state, action); case actionTypes.SAVE_FULFILLED: return setNotebookCheckpoint(state); case actionTypes.FOCUS_CELL: return focusCell(state, action); case actionTypes.CLEAR_OUTPUTS: return clearOutputs(state, action); case actionTypes.CLEAR_ALL_OUTPUTS: case actionTypes.RESTART_KERNEL: return clearAllOutputs(state, action); case actionTypes.APPEND_OUTPUT: return appendOutput(state, action); case actionTypes.UPDATE_DISPLAY: return updateDisplay(state, action); case actionTypes.FOCUS_NEXT_CELL: return focusNextCell(state, action); case actionTypes.FOCUS_PREVIOUS_CELL: return focusPreviousCell(state, action); case actionTypes.FOCUS_CELL_EDITOR: return focusCellEditor(state, action); case actionTypes.FOCUS_NEXT_CELL_EDITOR: return focusNextCellEditor(state, action); case actionTypes.FOCUS_PREVIOUS_CELL_EDITOR: return focusPreviousCellEditor(state, action); case actionTypes.SET_IN_CELL: return setInCell(state, action); case actionTypes.MOVE_CELL: return moveCell(state, action); case actionTypes.MARK_CELL_AS_DELETING: return markCellAsDeleting(state, action); case actionTypes.UNMARK_CELL_AS_DELETING: return unmarkCellAsDeleting(state, action); case actionTypes.DELETE_CELL: return deleteCellFromState(state, action); case actionTypes.CREATE_CELL_BELOW: return createCellBelow(state, action); case actionTypes.CREATE_CELL_ABOVE: return createCellAbove(state, action); case actionTypes.CREATE_CELL_APPEND: return createCellAppend(state, action); case actionTypes.TOGGLE_CELL_OUTPUT_VISIBILITY: return toggleCellOutputVisibility(state, action); case actionTypes.TOGGLE_CELL_INPUT_VISIBILITY: return toggleCellInputVisibility(state, action); case actionTypes.ACCEPT_PAYLOAD_MESSAGE: return acceptPayloadMessage(state, action); case actionTypes.UPDATE_CELL_STATUS: return updateCellStatus(state, action); case actionTypes.UPDATE_OUTPUT_METADATA: return updateOutputMetadata(state, action); case actionTypes.SET_LANGUAGE_INFO: return setLanguageInfo(state, action); case actionTypes.SET_KERNEL_METADATA: return setKernelMetadata(state, action); case actionTypes.OVERWRITE_METADATA_FIELD: return overwriteMetadataField(state, action); case actionTypes.DELETE_METADATA_FIELD: return deleteMetadataField(state, action); case actionTypes.COPY_CELL: return copyCell(state, action); case actionTypes.CUT_CELL: return cutCell(state, action); case actionTypes.PASTE_CELL: return pasteCell(state); case actionTypes.CHANGE_CELL_TYPE: return changeCellType(state, action); case actionTypes.TOGGLE_OUTPUT_EXPANSION: return toggleOutputExpansion(state, action); case actionTypes.UNHIDE_ALL: return unhideAll(state, action); case actionTypes.PROMPT_INPUT_REQUEST: return promptInputRequest(state, action); case actionTypes.INTERRUPT_KERNEL_SUCCESSFUL: return interruptKernelSuccessful(state, action); default: return state; } }
the_stack
import Node from '../node/Node'; import ShadowRoot from '../shadow-root/ShadowRoot'; import Attr from '../../attribute/Attr'; import DOMRect from './DOMRect'; import Range from './Range'; import ClassList from './ClassList'; import QuerySelector from '../../query-selector/QuerySelector'; import SelectorItem from '../../query-selector/SelectorItem'; import MutationRecord from '../../mutation-observer/MutationRecord'; import MutationTypeEnum from '../../mutation-observer/MutationTypeEnum'; import NamespaceURI from '../../config/NamespaceURI'; import XMLParser from '../../xml-parser/XMLParser'; import XMLSerializer from '../../xml-serializer/XMLSerializer'; import ChildNodeUtility from '../child-node/ChildNodeUtility'; import ParentNodeUtility from '../parent-node/ParentNodeUtility'; import NonDocumentChildNodeUtility from '../child-node/NonDocumentChildNodeUtility'; import IElement from './IElement'; import DOMException from '../../exception/DOMException'; import IShadowRoot from '../shadow-root/IShadowRoot'; import INode from '../node/INode'; import IDocument from '../document/IDocument'; import IHTMLCollection from './IHTMLCollection'; import INodeList from '../node/INodeList'; import HTMLCollectionFactory from './HTMLCollectionFactory'; import { TInsertAdjacentPositions } from './IElement'; import IText from '../text/IText'; /** * Element. */ export default class Element extends Node implements IElement { // ObservedAttributes should only be called once by CustomElementRegistry (see #117) // CustomElementRegistry will therefore populate _observedAttributes when CustomElementRegistry.define() is called public static _observedAttributes: string[]; public static observedAttributes: string[]; public tagName: string = null; public nodeType = Node.ELEMENT_NODE; public shadowRoot: IShadowRoot = null; public readonly classList = new ClassList(this); public scrollTop = 0; public scrollLeft = 0; public children: IHTMLCollection<IElement> = HTMLCollectionFactory.create(); public _attributes: { [k: string]: Attr } = {}; public readonly namespaceURI: string = null; /** * Returns ID. * * @returns ID. */ public get id(): string { return this.getAttribute('id') || ''; } /** * Sets ID. * * @param id ID. */ public set id(id: string) { this.setAttribute('id', id); } /** * Returns class name. * * @returns Class name. */ public get className(): string { return this.getAttribute('class') || ''; } /** * Sets class name. * * @param className Class name. */ public set className(className: string) { this.setAttribute('class', className); } /** * Node name. * * @returns Node name. */ public get nodeName(): string { return this.tagName; } /** * Local name. * * @returns Local name. */ public get localName(): string { return this.tagName.toLowerCase(); } /** * Previous element sibling. * * @returns Element. */ public get previousElementSibling(): IElement { return NonDocumentChildNodeUtility.previousElementSibling(this); } /** * Next element sibling. * * @returns Element. */ public get nextElementSibling(): IElement { return NonDocumentChildNodeUtility.nextElementSibling(this); } /** * Get text value of children. * * @returns Text content. */ public get textContent(): string { let result = ''; for (const childNode of this.childNodes) { if (childNode.nodeType === Node.ELEMENT_NODE || childNode.nodeType === Node.TEXT_NODE) { result += childNode.textContent; } } return result; } /** * Sets text content. * * @param textContent Text content. */ public set textContent(textContent: string) { for (const child of this.childNodes.slice()) { this.removeChild(child); } this.appendChild(this.ownerDocument.createTextNode(textContent)); } /** * Returns inner HTML. * * @returns HTML. */ public get innerHTML(): string { const xmlSerializer = new XMLSerializer(); let xml = ''; for (const node of this.childNodes) { xml += xmlSerializer.serializeToString(node); } return xml; } /** * Sets inner HTML. * * @param html HTML. */ public set innerHTML(html: string) { for (const child of this.childNodes.slice()) { this.removeChild(child); } for (const node of XMLParser.parse(this.ownerDocument, html).childNodes.slice()) { this.appendChild(node); } } /** * Returns outer HTML. * * @returns HTML. */ public get outerHTML(): string { return new XMLSerializer().serializeToString(this); } /** * Returns outer HTML. * * @param html HTML. */ public set outerHTML(html: string) { this.replaceWith(html); } /** * Returns attributes. * * @returns Attributes. */ public get attributes(): { [k: string]: Attr | number } { const attributes = Object.values(this._attributes); return Object.assign({}, this._attributes, attributes, { length: attributes.length }); } /** * First element child. * * @returns Element. */ public get firstElementChild(): IElement { return this.children ? this.children[0] || null : null; } /** * Last element child. * * @returns Element. */ public get lastElementChild(): IElement { return this.children ? this.children[this.children.length - 1] || null : null; } /** * Last element child. * * @returns Element. */ public get childElementCount(): number { return this.children.length; } /** * Attribute changed callback. * * @param name Name. * @param oldValue Old value. * @param newValue New value. */ public attributeChangedCallback?(name: string, oldValue: string, newValue: string): void; /** * Clones a node. * * @override * @param [deep=false] "true" to clone deep. * @returns Cloned node. */ public cloneNode(deep = false): IElement { const clone = <Element | IElement>super.cloneNode(deep); for (const key of Object.keys(this._attributes)) { const attr = Object.assign(new Attr(), this._attributes[key]); (<IElement>attr.ownerElement) = clone; (<Element>clone)._attributes[key] = attr; } if (deep) { for (const node of clone.childNodes) { if (node.nodeType === Node.ELEMENT_NODE) { clone.children.push(<IElement>node); } } } (<string>clone.tagName) = this.tagName; clone.scrollLeft = this.scrollLeft; clone.scrollTop = this.scrollTop; (<string>clone.namespaceURI) = this.namespaceURI; return <IElement>clone; } /** * Append a child node to childNodes. * * @override * @param node Node to append. * @returns Appended node. */ public appendChild(node: INode): INode { // If the type is DocumentFragment, then the child nodes of if it should be moved instead of the actual node. // See: https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment if (node.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { if (node.parentNode && node.parentNode['children']) { const index = node.parentNode['children'].indexOf(node); if (index !== -1) { node.parentNode['children'].splice(index, 1); } } if (node !== this && node.nodeType === Node.ELEMENT_NODE) { this.children.push(<IElement>node); } } return super.appendChild(node); } /** * Remove Child element from childNodes array. * * @override * @param node Node to remove. */ public removeChild(node: INode): INode { if (node.nodeType === Node.ELEMENT_NODE) { const index = this.children.indexOf(<IElement>node); if (index !== -1) { this.children.splice(index, 1); } } return super.removeChild(node); } /** * Removes the node from its parent. */ public remove(): void { ChildNodeUtility.remove(this); } /** * Inserts a node before another. * * @override * @param newNode Node to insert. * @param [referenceNode] Node to insert before. * @returns Inserted node. */ public insertBefore(newNode: INode, referenceNode?: INode): INode { const returnValue = super.insertBefore(newNode, referenceNode); // If the type is DocumentFragment, then the child nodes of if it should be moved instead of the actual node. // See: https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment if (newNode.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) { if (newNode.parentNode && newNode.parentNode['children']) { const index = newNode.parentNode['children'].indexOf(newNode); if (index !== -1) { newNode.parentNode['children'].splice(index, 1); } } this.children.length = 0; for (const node of this.childNodes) { if (node.nodeType === Node.ELEMENT_NODE) { this.children.push(<IElement>node); } } } return returnValue; } /** * The Node.replaceWith() method replaces this Node in the children list of its parent with a set of Node or DOMString objects. * * @param nodes List of Node or DOMString. */ public replaceWith(...nodes: (INode | string)[]): void { ChildNodeUtility.replaceWith(this, ...nodes); } /** * Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just before this ChildNode. DOMString objects are inserted as equivalent Text nodes. * * @param nodes List of Node or DOMString. */ public before(...nodes: (string | INode)[]): void { ChildNodeUtility.before(this, ...nodes); } /** * Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent, just after this ChildNode. DOMString objects are inserted as equivalent Text nodes. * * @param nodes List of Node or DOMString. */ public after(...nodes: (string | INode)[]): void { ChildNodeUtility.after(this, ...nodes); } /** * Inserts a set of Node objects or DOMString objects after the last child of the ParentNode. DOMString objects are inserted as equivalent Text nodes. * * @param nodes List of Node or DOMString. */ public append(...nodes: (string | INode)[]): void { ParentNodeUtility.append(this, ...nodes); } /** * Inserts a set of Node objects or DOMString objects before the first child of the ParentNode. DOMString objects are inserted as equivalent Text nodes. * * @param nodes List of Node or DOMString. */ public prepend(...nodes: (string | INode)[]): void { ParentNodeUtility.prepend(this, ...nodes); } /** * Replaces the existing children of a node with a specified new set of children. * * @param nodes List of Node or DOMString. */ public replaceChildren(...nodes: (string | INode)[]): void { ParentNodeUtility.replaceChildren(this, ...nodes); } /** * Inserts a node to the given position. * * @param position Position to insert element. * @param element Node to insert. * @returns Inserted node or null if couldn't insert. */ public insertAdjacentElement(position: TInsertAdjacentPositions, element: INode): INode | null { if (position === 'beforebegin') { if (!this.parentElement) { return null; } this.parentElement.insertBefore(element, this); } else if (position === 'afterbegin') { this.insertBefore(element, this.firstChild); } else if (position === 'beforeend') { this.appendChild(element); } else if (position === 'afterend') { if (!this.parentElement) { return null; } this.parentElement.insertBefore(element, this.nextSibling); } return element; } /** * Inserts an HTML string to the given position. * * @param position Position to insert text. * @param text HTML string to insert. */ public insertAdjacentHTML(position: TInsertAdjacentPositions, text: string): void { for (const node of XMLParser.parse(this.ownerDocument, text).childNodes.slice()) { this.insertAdjacentElement(position, node); } } /** * Inserts text to the given position. * * @param position Position to insert text. * @param text String to insert. */ public insertAdjacentText(position: TInsertAdjacentPositions, text: string): void { const textNode = <IText>this.ownerDocument.createTextNode(text); this.insertAdjacentElement(position, textNode); } /** * Sets an attribute. * * @param name Name. * @param value Value. */ public setAttribute(name: string, value: string): void { const attribute = this.ownerDocument.createAttributeNS(null, name); attribute.value = String(value); this.setAttributeNode(attribute); } /** * Sets a namespace attribute. * * @param namespaceURI Namespace URI. * @param name Name. * @param value Value. */ public setAttributeNS(namespaceURI: string, name: string, value: string): void { const attribute = this.ownerDocument.createAttributeNS(namespaceURI, name); attribute.value = String(value); this.setAttributeNode(attribute); } /** * Returns attribute names. * * @returns Attribute names. */ public getAttributeNames(): string[] { return Object.keys(this._attributes); } /** * Returns attribute value. * * @param name Name. */ public getAttribute(name: string): string { const attribute = this.getAttributeNode(name); if (attribute) { return attribute.value; } return null; } /** * Returns namespace attribute value. * * @param namespace Namespace URI. * @param localName Local name. */ public getAttributeNS(namespace: string, localName: string): string { const attribute = this.getAttributeNodeNS(namespace, localName); if (attribute) { return attribute.value; } return null; } /** * Returns a boolean value indicating whether the specified element has the attribute or not. * * @param name Attribute name. * @returns True if attribute exists, false otherwise. */ public hasAttribute(name: string): boolean { return !!this.getAttributeNode(name); } /** * Returns a boolean value indicating whether the specified element has the namespace attribute or not. * * @param namespace Namespace URI. * @param localName Local name. * @returns True if attribute exists, false otherwise. */ public hasAttributeNS(namespace: string, localName: string): boolean { for (const name of Object.keys(this._attributes)) { const attribute = this._attributes[name]; if (attribute.namespaceURI === namespace && attribute.localName === localName) { return true; } } return false; } /** * Returns "true" if the element has attributes. * * @returns "true" if the element has attributes. */ public hasAttributes(): boolean { return Object.keys(this._attributes).length > 0; } /** * Removes an attribute. * * @param name Name. */ public removeAttribute(name: string): void { const attribute = this._attributes[this._getAttributeName(name)]; if (attribute) { this.removeAttributeNode(attribute); } } /** * Removes a namespace attribute. * * @param namespace Namespace URI. * @param localName Local name. */ public removeAttributeNS(namespace: string, localName: string): void { for (const name of Object.keys(this._attributes)) { const attribute = this._attributes[name]; if (attribute.namespaceURI === namespace && attribute.localName === localName) { this.removeAttribute(attribute.name); } } } /** * Attaches a shadow root. * * @param _shadowRootInit Shadow root init. * @param shadowRootInit * @param shadowRootInit.mode * @returns Shadow root. */ public attachShadow(shadowRootInit: { mode: string }): IShadowRoot { if (this.shadowRoot) { throw new DOMException('Shadow root has already been attached.'); } (<IShadowRoot>this.shadowRoot) = new ShadowRoot(); (<IDocument>this.shadowRoot.ownerDocument) = this.ownerDocument; (<Element>this.shadowRoot.host) = this; (<string>this.shadowRoot.mode) = shadowRootInit.mode; this.shadowRoot.isConnected = this.isConnected; return this.shadowRoot; } /** * Converts to string. * * @returns String. */ public toString(): string { return this.outerHTML; } /** * Returns the size of an element and its position relative to the viewport. * * @returns DOM rect. */ public getBoundingClientRect(): DOMRect { return new DOMRect(); } /** * Returns a range. * * @returns Range. */ public createTextRange(): Range { return new Range(); } /** * The matches() method checks to see if the Element would be selected by the provided selectorString. * * @param selector Selector. * @returns "true" if matching. */ public matches(selector: string): boolean { return new SelectorItem(selector).match(this); } /** * Query CSS selector to find matching nodes. * * @param selector CSS selector. * @returns Matching elements. */ public querySelectorAll(selector: string): INodeList<IElement> { return QuerySelector.querySelectorAll(this, selector); } /** * Query CSS Selector to find matching node. * * @param selector CSS selector. * @returns Matching element. */ public querySelector(selector: string): IElement { return QuerySelector.querySelector(this, selector); } /** * Returns an elements by class name. * * @param className Tag name. * @returns Matching element. */ public getElementsByClassName(className: string): IHTMLCollection<IElement> { return ParentNodeUtility.getElementsByClassName(this, className); } /** * Returns an elements by tag name. * * @param tagName Tag name. * @returns Matching element. */ public getElementsByTagName(tagName: string): IHTMLCollection<IElement> { return ParentNodeUtility.getElementsByTagName(this, tagName); } /** * Returns an elements by tag name and namespace. * * @param namespaceURI Namespace URI. * @param tagName Tag name. * @returns Matching element. */ public getElementsByTagNameNS(namespaceURI: string, tagName: string): IHTMLCollection<IElement> { return ParentNodeUtility.getElementsByTagNameNS(this, namespaceURI, tagName); } /** * The setAttributeNode() method adds a new Attr node to the specified element. * * @param attribute Attribute. * @returns Replaced attribute. */ public setAttributeNode(attribute: Attr): Attr { const name = this._getAttributeName(attribute.name); const replacedAttribute = this._attributes[name]; const oldValue = replacedAttribute ? replacedAttribute.value : null; attribute.name = name; (<IElement>attribute.ownerElement) = this; (<IDocument>attribute.ownerDocument) = this.ownerDocument; this._attributes[name] = attribute; if ( this.attributeChangedCallback && (<typeof Element>this.constructor)._observedAttributes && (<typeof Element>this.constructor)._observedAttributes.includes(name) ) { this.attributeChangedCallback(name, oldValue, attribute.value); } // MutationObserver if (this._observers.length > 0) { for (const observer of this._observers) { if ( observer.options.attributes && (!observer.options.attributeFilter || observer.options.attributeFilter.includes(name)) ) { const record = new MutationRecord(); record.type = MutationTypeEnum.attributes; record.attributeName = name; record.oldValue = observer.options.attributeOldValue ? oldValue : null; observer.callback([record]); } } } return replacedAttribute || null; } /** * The setAttributeNodeNS() method adds a new Attr node to the specified element. * * @param attribute Attribute. * @returns Replaced attribute. */ public setAttributeNodeNS(attribute: Attr): Attr { return this.setAttributeNode(attribute); } /** * Returns an Attr node. * * @param name Name. * @returns Replaced attribute. */ public getAttributeNode(name: string): Attr { return this._attributes[this._getAttributeName(name)] || null; } /** * Returns a namespaced Attr node. * * @param namespace Namespace. * @param name Name. * @returns Replaced attribute. */ public getAttributeNodeNS(namespace: string, name: string): Attr { const attributeName = this._getAttributeName(name); for (const name of Object.keys(this._attributes)) { const attribute = this._attributes[name]; if (attribute.namespaceURI === namespace && attribute.localName === attributeName) { return attribute; } } return null; } /** * Removes an Attr node. * * @param attribute Attribute. */ public removeAttributeNode(attribute: Attr): void { delete this._attributes[attribute.name]; if ( this.attributeChangedCallback && (<typeof Element>this.constructor)._observedAttributes && (<typeof Element>this.constructor)._observedAttributes.includes(attribute.name) ) { this.attributeChangedCallback(attribute.name, attribute.value, null); } // MutationObserver if (this._observers.length > 0) { for (const observer of this._observers) { if ( observer.options.attributes && (!observer.options.attributeFilter || observer.options.attributeFilter.includes(attribute.name)) ) { const record = new MutationRecord(); record.type = MutationTypeEnum.attributes; record.attributeName = attribute.name; record.oldValue = observer.options.attributeOldValue ? attribute.value : null; observer.callback([record]); } } } } /** * Removes an Attr node. * * @param attribute Attribute. */ public removeAttributeNodeNS(attribute: Attr): void { this.removeAttributeNode(attribute); } /** * Scrolls to a particular set of coordinates. * * @param x X position or options object. * @param y Y position. */ public scroll(x: { top?: number; left?: number; behavior?: string } | number, y?: number): void { if (typeof x === 'object') { if (x.behavior === 'smooth') { this.ownerDocument.defaultView.setTimeout(() => { if (x.top !== undefined) { (<number>this.scrollTop) = x.top; } if (x.left !== undefined) { (<number>this.scrollLeft) = x.left; } }); } else { if (x.top !== undefined) { (<number>this.scrollTop) = x.top; } if (x.left !== undefined) { (<number>this.scrollLeft) = x.left; } } } else if (x !== undefined && y !== undefined) { (<number>this.scrollLeft) = x; (<number>this.scrollTop) = y; } } /** * Scrolls to a particular set of coordinates. * * @param x X position or options object. * @param y Y position. */ public scrollTo( x: { top?: number; left?: number; behavior?: string } | number, y?: number ): void { this.scroll(x, y); } /** * Returns attribute name. * * @param name Name. * @returns Attribute name based on namespace. */ protected _getAttributeName(name): string { if (this.namespaceURI === NamespaceURI.svg) { return name; } return name.toLowerCase(); } }
the_stack
import { AfterContentChecked, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, EventEmitter, forwardRef, Host, HostListener, Inject, Input, OnDestroy, Optional, Output, QueryList, Self, SkipSelf, ViewChildren, ViewEncapsulation } from '@angular/core'; import { NgControl, NgForm } from '@angular/forms'; import { FocusKeyManager } from '@angular/cdk/a11y'; import { DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW, UP_ARROW } from '@angular/cdk/keycodes'; import { distinctUntilChanged, takeUntil } from 'rxjs/operators'; import { Subject } from 'rxjs'; import { FormField, FormFieldControl, InLineLayoutCollectionBaseInput, RESPONSIVE_BREAKPOINTS_CONFIG, ResponsiveBreakPointConfig, ResponsiveBreakpointsService } from '@fundamental-ngx/platform/shared'; import { RadioButtonComponent } from './radio/radio.component'; /** * Radio group implementation based on the * https://github.com/SAP/fundamental-ngx/wiki/Platform:-RadioGroup-Technical-Design * documents. * */ // Increasing integer for generating unique ids for radio components. let nextUniqueId = 0; @Component({ selector: 'fdp-radio-group', templateUrl: './radio-group.component.html', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [{ provide: FormFieldControl, useExisting: forwardRef(() => RadioGroupComponent), multi: true }] }) export class RadioGroupComponent extends InLineLayoutCollectionBaseInput implements AfterViewInit, AfterContentChecked, OnDestroy { /** Value of selected radio button */ @Input('selected') get value(): any { return super.getValue(); } set value(newValue: any) { super.setValue(newValue); } /** * To Display Radio buttons in a line */ @Input() get isInline(): boolean { return this._isInline; } set isInline(inline: boolean) { this._isInline = inline; this._cd.markForCheck(); } /** @hidden */ private _isInline: boolean; /** * None value radio button created */ @Input() hasNoValue = false; /** * Label for None value radio button */ @Input() noValueLabel = 'None'; /** Children radio buttons part of Group radio button, passed as content */ @ContentChildren(RadioButtonComponent) contentRadioButtons: QueryList<RadioButtonComponent>; /** Children radio buttons part of Group radio button, created from list of values */ @ViewChildren(RadioButtonComponent) viewRadioButtons: QueryList<RadioButtonComponent>; /** Selected radio button change event raised */ @Output() change: EventEmitter<RadioButtonComponent> = new EventEmitter<RadioButtonComponent>(); /** @hidden */ private _activeItemSet = false; /** The currently selected radio button. Should match value. */ private _selected: RadioButtonComponent | null = null; private destroy$ = new Subject<boolean>(); // FocusKeyManager instance private keyboardEventsManager: FocusKeyManager<RadioButtonComponent>; constructor( protected _cd: ChangeDetectorRef, readonly _responsiveBreakpointsService: ResponsiveBreakpointsService, @Optional() @Self() ngControl: NgControl, @Optional() @SkipSelf() ngForm: NgForm, @Optional() @SkipSelf() @Host() formField: FormField, @Optional() @SkipSelf() @Host() formControl: FormFieldControl<any>, @Optional() @Inject(RESPONSIVE_BREAKPOINTS_CONFIG) readonly _defaultResponsiveBreakPointConfig: ResponsiveBreakPointConfig ) { super( _cd, _responsiveBreakpointsService, ngControl, ngForm, formField, formControl, _defaultResponsiveBreakPointConfig ); this.id = `radio-group-${nextUniqueId++}`; // subscribe to _inlineCurrentValue in inline-layout-collection-base-input this._inlineCurrentValue .pipe(distinctUntilChanged()) .subscribe((currentInline) => (this.isInline = currentInline)); } /** * Control Value Accessor */ writeValue(value: any): void { if (value) { super.writeValue(value); } } /** * Access display value for objects, acts as checkbox label. */ public getDisplayValue(item: any): string { return this.displayValue(item); } /** * Access lookup value for objects, acts as checkbox value. */ public getLookupValue(item: any): string { return this.lookupValue(item); } /** * Called on button click for view radio button, created from list of values * @param event */ public selected(event: RadioButtonComponent): void { this._selectedValueChanged(event); } /** * @hidden Selecting default button as provided as input */ ngAfterContentChecked(): void { if (!this._validateRadioButtons()) { throw new Error('fdp-radio-button-group must contain a fdp-radio-button'); } this.contentRadioButtons.forEach((button) => (button.state = this.state)); this._cd.markForCheck(); } /** * Initialize properties once fd-radio-buttons are available. * This allows us to propagate relevant attributes to associated buttons. */ ngAfterViewInit(): void { setTimeout(() => { this._initialSetup(this.contentRadioButtons); this._initialSetup(this.viewRadioButtons); }); super.ngAfterViewInit(); } /** * @hidden * Destroys event subscription. */ ngOnDestroy(): void { this.destroy$.next(true); this.destroy$.complete(); } /** @hidden */ public getListItemDisabledValue(item: RadioGroupComponent['list'][number]): boolean { return this.disabled || typeof item === 'string' ? this.disabled : item.disabled; } /** @hidden */ @HostListener('keydown', ['$event']) public handleKeydown(event: KeyboardEvent): void { event.stopImmediatePropagation(); if (this.keyboardEventsManager) { // sets Active item. so arrow key starts after the active item. // Need to do only once, when one radio is already selected if (this._selected && !this._activeItemSet) { this.keyboardEventsManager.setActiveItem(this._selected); this._activeItemSet = true; } if ( event.keyCode === DOWN_ARROW || event.keyCode === UP_ARROW || event.keyCode === LEFT_ARROW || event.keyCode === RIGHT_ARROW ) { // passing the event to key manager so we get a change fired this.keyboardEventsManager.onKeydown(event); } } } private _initialSetup(radioButtons: QueryList<RadioButtonComponent>): void { if (radioButtons && radioButtons.length > 0) { let firstEnabledButtonIndex = -1; this.keyboardEventsManager = new FocusKeyManager(radioButtons).withWrap().withHorizontalOrientation('ltr'); radioButtons.forEach((button, i) => { if (this.list) { button.state = this.state; } else { this._setProperties(button); } this._selectUnselect(button); // finding first enabled button to set tabIndex=0 if (!button.disabled && !this._disabled && firstEnabledButtonIndex < 0) { firstEnabledButtonIndex = i; } button.checked.pipe(takeUntil(this.destroy$)).subscribe((ev) => this._selectedValueChanged(ev)); }); // accessibility requirement if (!this._selected && radioButtons && firstEnabledButtonIndex > -1) { radioButtons.toArray()[firstEnabledButtonIndex].setTabIndex(0); } this.onChange(this.value); } } /** * Selects given button, if value matches * @param button */ private _selectUnselect(button: RadioButtonComponent): void { if (button.value === this.value) { // selected button if (this._selected !== button) { this._selected = button; } if (!button.isChecked) { button.select(); } } } /** Called every time a radio button is clicked, In content child as well as viewchild */ private _selectedValueChanged(button: RadioButtonComponent): void { this.onTouched(); if (this._selected !== button) { this.resetTabIndex(button); if (this._selected) { this._selected.unselect(); } this._selected = button; button.select(); } this.value = button.value; this.change.emit(button); this.onChange(this.value); } /** resets tabIndex for first radio in radio group. for accessibility tabIndex was set */ private resetTabIndex(selectedRadio: RadioButtonComponent): void { if (this.viewRadioButtons || this.contentRadioButtons) { const radios = this.viewRadioButtons.length ? this.viewRadioButtons : this.contentRadioButtons; radios.forEach((radio) => { if (radio !== selectedRadio && radio.tabIndex === 0) { radio.tabIndex = -1; } }); } } /** * * @param button Set initial values, used while content children creation */ private _setProperties(button: RadioButtonComponent): void { if (button) { button.name = this.name; button.contentDensity = this.contentDensity; button.state = this.state; button.disabled = button.disabled ? button.disabled : this._disabled; } } /** * Make sure we have expected child. */ private _validateRadioButtons(): boolean { return ( this.contentRadioButtons.filter((item) => !(item instanceof RadioButtonComponent || item['renderer'])) .length === 0 ); } }
the_stack
import * as log from "./log"; import { Delivery } from "rhea-promise"; import { ApplicationTokenCredentials, DeviceTokenCredentials, UserTokenCredentials, MSITokenCredentials } from "ms-rest-azure"; import { MessagingError, DataTransformer, TokenProvider, EventHubConnectionConfig, AadTokenProvider } from "@azure/amqp-common"; import { OnMessage, OnError } from "./eventHubReceiver"; import { EventData } from "./eventData"; import { ConnectionContext } from "./connectionContext"; import { EventHubPartitionRuntimeInformation, EventHubRuntimeInformation } from "./managementClient"; import { EventPosition } from "./eventPosition"; import { EventHubSender } from "./eventHubSender"; import { StreamingReceiver, ReceiveHandler } from "./streamingReceiver"; import { BatchingReceiver } from "./batchingReceiver"; import { IotHubClient } from "./iothub/iothubClient"; /** * Describes the options that one can set while receiving messages. * @interface ReceiveOptions */ export interface ReceiveOptions { /** * @property {string} [name] The name of the receiver. If not provided then we will set a GUID by default. */ name?: string; /** * @property {object} [eventPosition] The starting event position at which to start receiving messages. * This is used to filter messages for the EventHub Receiver. */ eventPosition?: EventPosition; /** * @property {string} [consumerGroup] The consumer group to which the receiver wants to connect to. * If not provided then it will be connected to "$default" consumer group. */ consumerGroup?: string; /** * @property {number} [prefetchCount] The upper limit of events this receiver will actively receive * regardless of whether a receive operation is pending. Defaults to 1000. */ prefetchCount?: number; /** * @property {number} [epoch] The epoch value that this receiver is currently using for partition ownership. */ epoch?: number; /** * @property {string} [identifier] The receiver identifier that uniqely identifies the receiver. */ identifier?: string; /** * @property {boolean} [enableReceiverRuntimeMetric] A value indicating whether the runtime metric of a receiver is enabled. */ enableReceiverRuntimeMetric?: boolean; } /** * Describes the base client options. * @interface ClientOptionsBase */ export interface ClientOptionsBase { /** * @property {DataTransformer} [dataTransformer] The data transformer that will be used to encode * and decode the sent and received messages respectively. If not provided then we will use the * DefaultDataTransformer. The default transformer should handle majority of the cases. This * option needs to be used only for specialized scenarios. */ dataTransformer?: DataTransformer; /** * @property {string} [userAgent] The user agent that needs to be appended to the built in * user agent string. */ userAgent?: string; } /** * Describes the options that can be provided while creating the EventHub Client. * @interface ClientOptions */ export interface ClientOptions extends ClientOptionsBase { /** * @property {TokenProvider} [tokenProvider] - The token provider that provides the token for authentication. * Default value: SasTokenProvider. */ tokenProvider?: TokenProvider; } /** * @class EventHubClient * Describes the EventHub client. */ export class EventHubClient { /** * @property {string} [connectionId] The amqp connection id that uniquely identifies the connection within a process. */ connectionId?: string; /** * @property {string} eventhubName The name of the Eventhub. * @readonly */ get eventhubName(): string { return this._context.config.entityPath!; } /** * @property {ConnectionContext} _context Describes the amqp connection context for the eventhub client. * @private */ private _context: ConnectionContext; /** * Instantiates a client pointing to the Event Hub given by this configuration. * * @constructor * @param {EventHubConnectionConfig} config - The connection configuration to create the EventHub Client. * @param {ClientOptions} options - The optional parameters that can be provided to the EventHub * Client constructor. */ constructor(config: EventHubConnectionConfig, options?: ClientOptions) { if (!options) options = {}; this._context = ConnectionContext.create(config, options); } /** * Closes the AMQP connection to the Event Hub for this client, * returning a promise that will be resolved when disconnection is completed. * @returns {Promise<void>} Promise<void> */ async close(): Promise<void> { try { if (this._context.connection.isOpen()) { // Close all the senders. for (const senderName of Object.keys(this._context.senders)) { await this._context.senders[senderName].close(); } // Close all the receivers. for (const receiverName of Object.keys(this._context.receivers)) { await this._context.receivers[receiverName].close(); } // Close the cbs session; await this._context.cbsSession.close(); // Close the management session await this._context.managementSession!.close(); await this._context.connection.close(); this._context.wasConnectionCloseCalled = true; log.client("Closed the amqp connection '%s' on the client.", this._context.connectionId); } } catch (err) { const msg = `An error occurred while closing the connection "${this._context.connectionId}": ${JSON.stringify(err)}`; log.error(msg); throw new Error(msg); } } /** * Sends the given message to the EventHub. * * @param {any} data Message to send. Will be sent as UTF8-encoded JSON string. * @param {string|number} [partitionId] Partition ID to which the event data needs to be sent. This should only be specified * if you intend to send the event to a specific partition. When not specified EventHub will store the messages in a round-robin * fashion amongst the different partitions in the EventHub. * * @returns {Promise<Delivery>} Promise<Delivery> */ async send(data: EventData, partitionId?: string | number): Promise<Delivery> { const sender = EventHubSender.create(this._context, partitionId); return sender.send(data); } /** * Send a batch of EventData to the EventHub. The "message_annotations", "application_properties" and "properties" * of the first message will be set as that of the envelope (batch message). * * @param {Array<EventData>} datas An array of EventData objects to be sent in a Batch message. * @param {string|number} [partitionId] Partition ID to which the event data needs to be sent. This should only be specified * if you intend to send the event to a specific partition. When not specified EventHub will store the messages in a round-robin * fashion amongst the different partitions in the EventHub. * * @return {Promise<Delivery>} Promise<Delivery> */ async sendBatch(datas: EventData[], partitionId?: string | number): Promise<Delivery> { const sender = EventHubSender.create(this._context, partitionId); return sender.sendBatch(datas); } /** * Starts the receiver by establishing an AMQP session and an AMQP receiver link on the session. Messages will be passed to * the provided onMessage handler and error will be passed to the provided onError handler. * * @param {string|number} partitionId Partition ID from which to receive. * @param {OnMessage} onMessage The message handler to receive event data objects. * @param {OnError} onError The error handler to receive an error that occurs * while receiving messages. * @param {ReceiveOptions} [options] Options for how you'd like to receive messages. * * @returns {ReceiveHandler} ReceiveHandler - An object that provides a mechanism to stop receiving more messages. */ receive(partitionId: string | number, onMessage: OnMessage, onError: OnError, options?: ReceiveOptions): ReceiveHandler { if (typeof partitionId !== "string" && typeof partitionId !== "number") { throw new Error("'partitionId' is a required parameter and must be of type: 'string' | 'number'."); } const sReceiver = StreamingReceiver.create(this._context, partitionId, options); this._context.receivers[sReceiver.name] = sReceiver; return sReceiver.receive(onMessage, onError); } /** * Receives a batch of EventData objects from an EventHub partition for a given count and a given max wait time in seconds, whichever * happens first. This method can be used directly after creating the receiver object and **MUST NOT** be used along with the `start()` method. * * @param {string|number} partitionId Partition ID from which to receive. * @param {number} maxMessageCount The maximum message count. Must be a value greater than 0. * @param {number} [maxWaitTimeInSeconds] The maximum wait time in seconds for which the Receiver should wait * to receiver the said amount of messages. If not provided, it defaults to 60 seconds. * @param {ReceiveOptions} [options] Options for how you'd like to receive messages. * * @returns {Promise<Array<EventData>>} Promise<Array<EventData>>. */ async receiveBatch(partitionId: string | number, maxMessageCount: number, maxWaitTimeInSeconds?: number, options?: ReceiveOptions): Promise<EventData[]> { if (typeof partitionId !== "string" && typeof partitionId !== "number") { throw new Error("'partitionId' is a required parameter and must be of type: 'string' | 'number'."); } const bReceiver = BatchingReceiver.create(this._context, partitionId, options); this._context.receivers[bReceiver.name] = bReceiver; let error: MessagingError | undefined; let result: EventData[] = []; try { result = await bReceiver.receive(maxMessageCount, maxWaitTimeInSeconds); } catch (err) { error = err; log.error("[%s] Receiver '%s', an error occurred while receiving %d messages for %d max time:\n %O", this._context.connectionId, bReceiver.name, maxMessageCount, maxWaitTimeInSeconds, err); } try { await bReceiver.close(); } catch (err) { // do nothing about it. } if (error) { throw error; } return result; } /** * Provides the eventhub runtime information. * @returns {Promise<EventHubRuntimeInformation>} A promise that resolves with EventHubRuntimeInformation. */ async getHubRuntimeInformation(): Promise<EventHubRuntimeInformation> { try { return await this._context.managementSession!.getHubRuntimeInformation(); } catch (err) { log.error("An error occurred while getting the hub runtime information: %O", err); throw err; } } /** * Provides an array of partitionIds. * @returns {Promise<Array<string>>} A promise that resolves with an Array of strings. */ async getPartitionIds(): Promise<Array<string>> { try { const runtimeInfo = await this.getHubRuntimeInformation(); return runtimeInfo.partitionIds; } catch (err) { log.error("An error occurred while getting the partition ids: %O", err); throw err; } } /** * Provides information about the specified partition. * @param {(string|number)} partitionId Partition ID for which partition information is required. * @returns {Promise<EventHubPartitionRuntimeInformation>} A promise that resoloves with EventHubPartitionRuntimeInformation. */ async getPartitionInformation(partitionId: string | number): Promise<EventHubPartitionRuntimeInformation> { if (typeof partitionId !== "string" && typeof partitionId !== "number") { throw new Error("'partitionId' is a required parameter and must be of type: 'string' | 'number'."); } try { return await this._context.managementSession!.getPartitionInformation(partitionId); } catch (err) { log.error("An error occurred while getting the partition information: %O", err); throw err; } } /** * Creates an EventHub Client from connection string. * @param {string} connectionString - Connection string of the form 'Endpoint=sb://my-servicebus-namespace.servicebus.windows.net/;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key' * @param {string} [path] - EventHub path of the form 'my-event-hub-name' * @param {ClientOptions} [options] Options that can be provided during client creation. * @returns {EventHubClient} - An instance of the eventhub client. */ static createFromConnectionString(connectionString: string, path?: string, options?: ClientOptions): EventHubClient { if (!connectionString || (connectionString && typeof connectionString !== "string")) { throw new Error("'connectionString' is a required parameter and must be of type: 'string'."); } const config = EventHubConnectionConfig.create(connectionString, path); if (!config.entityPath) { throw new Error(`Either the connectionString must have "EntityPath=<path-to-entity>" or ` + `you must provide "path", while creating the client`); } return new EventHubClient(config, options); } /** * Creates an EventHub Client from connection string. * @param {string} iothubConnectionString - Connection string of the form 'HostName=iot-host-name;SharedAccessKeyName=my-SA-name;SharedAccessKey=my-SA-key' * @param {ClientOptions} [options] Options that can be provided during client creation. * @returns {Promise<EventHubClient>} - Promise<EventHubClient>. */ static async createFromIotHubConnectionString(iothubConnectionString: string, options?: ClientOptions): Promise<EventHubClient> { if (!iothubConnectionString || (iothubConnectionString && typeof iothubConnectionString !== "string")) { throw new Error("'connectionString' is a required parameter and must be of type: 'string'."); } const connectionString = await new IotHubClient(iothubConnectionString).getEventHubConnectionString(); return EventHubClient.createFromConnectionString(connectionString, undefined, options); } /** * Creates an EventHub Client from a generic token provider. * @param {string} host - Fully qualified domain name for Event Hubs. Most likely, * <yournamespace>.servicebus.windows.net * @param {string} entityPath - EventHub path of the form 'my-event-hub-name' * @param {TokenProvider} tokenProvider - Your token provider that implements the TokenProvider interface. * @param {ClientOptionsBase} options - The options that can be provided during client creation. * @returns {EventHubClient} An instance of the Eventhub client. */ static createFromTokenProvider( host: string, entityPath: string, tokenProvider: TokenProvider, options?: ClientOptionsBase): EventHubClient { if (!host || (host && typeof host !== "string")) { throw new Error("'host' is a required parameter and must be of type: 'string'."); } if (!entityPath || (entityPath && typeof entityPath !== "string")) { throw new Error("'entityPath' is a required parameter and must be of type: 'string'."); } if (!tokenProvider || (tokenProvider && typeof tokenProvider !== "object")) { throw new Error("'tokenProvider' is a required parameter and must be of type: 'object'."); } if (!host.endsWith("/")) host += "/"; const connectionString = `Endpoint=sb://${host};SharedAccessKeyName=defaultKeyName;` + `SharedAccessKey=defaultKeyValue`; if (!options) options = {}; const clientOptions: ClientOptions = options; clientOptions.tokenProvider = tokenProvider; return EventHubClient.createFromConnectionString(connectionString, entityPath, clientOptions); } /** * Creates an EventHub Client from AADTokenCredentials. * @param {string} host - Fully qualified domain name for Event Hubs. Most likely, * <yournamespace>.servicebus.windows.net * @param {string} entityPath - EventHub path of the form 'my-event-hub-name' * @param {TokenCredentials} credentials - The AAD Token credentials. It can be one of the following: * ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials | MSITokenCredentials. * @param {ClientOptionsBase} options - The options that can be provided during client creation. * @returns {EventHubClient} An instance of the Eventhub client. */ static createFromAadTokenCredentials( host: string, entityPath: string, credentials: ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials | MSITokenCredentials, options?: ClientOptionsBase): EventHubClient { if (!credentials || (credentials && typeof credentials !== "object")) { throw new Error("'credentials' is a required parameter and must be an instance of " + "ApplicationTokenCredentials | UserTokenCredentials | DeviceTokenCredentials | " + "MSITokenCredentials."); } const tokenProvider = new AadTokenProvider(credentials); return EventHubClient.createFromTokenProvider(host, entityPath, tokenProvider, options); } }
the_stack
import React from 'react'; import ReactDOM from 'react-dom'; import * as d3 from '../libs/d3'; // Components import {Tooltip} from "@grafana/ui" import {Icon} from "../components/Icon"; import {GroupProbeTooltip} from "../components/GroupProbeTooltip"; import {PieBoundingRect} from "../components/PieBoundingRect"; // Services import {getGroupSpec, getProbeSpec} from "../i18n/en"; import {calculateTopTicks} from './topticks'; import {getEventsSrv} from "../services/EventsSrv"; import {getTimeRangeSrv} from "../services/TimeRangeSrv"; import {availabilityPercent} from "../util/humanSeconds"; import {Episode, LegacySettings, StatusRange} from 'app/services/DatasetSrv'; import {Dataset} from 'app/services/Dataset'; // Groups layout from https://bl.ocks.org/Andrew-Reid/960819e98873bbaf035bbf6bd2774b40 // Pie from https://observablehq.com/@d3/donut-chart // Tooltip https://bl.ocks.org/d3noob/a22c42db65eb00d4e369 // Text alignment https://bl.ocks.org/emmasaunders/0016ee0a2cab25a643ee9bd4855d3464 // Format numbers https://github.com/d3/d3-format // Settings const pieBoxWidth = 60; // const pieSpace = 15; // const pieInnerRadius = 0.67; // const legendWidth = 250; // const topTicksHeight = 30; // const leftPadding = 30; // const rightPadding = 30; // let width = leftPadding + legendWidth + (12 * (pieBoxWidth + pieSpace) + pieSpace) + rightPadding; // let height = topTicksHeight + 5 * (pieBoxWidth + pieSpace) + pieSpace; //let root = d3.select("#graph") // .attr("width", width) // .attr("height", height) // .attr("viewBox", [0, 0, width, height]); export function renderGraphTable(dataset: Dataset, settings: LegacySettings) { let root = d3.select('#graph'); // Always recreate everything root.selectAll("*").remove(); root.append("div") .attr("class", "top-ticks") .append("div") .attr("class", "top-tick-left") .append("div") .attr("class", "top-tick-left-spacer") updateTicks(dataset, settings); let graphTable = root.append("div") .attr("class", "graph-table") let groups = graphTable.selectAll(".graph-row") .data(settings.groupProbes); // each group is a table row, so translate "g" element to proper y position let groupsEnter = groups.enter() .append("div") .attr("data-group-id", d => d.group) .attr("data-probe-id", d => d.probe) .attr("class", "graph-row") // Labels for group and probes. groupsEnter.each(function (item) { let rowEl = d3.select(this); let cellEl = rowEl .append("div") .attr("class", "graph-cell graph-labels"); if (item.probe === "__total__") { // total is always visible rowEl.classed("graph-row-visible", true); // add open/close icon // fas - fontawesome icon // fa-fw - fixed width https://fontawesome.com/how-to-use/on-the-web/styling/fixed-width-icons // fa-** - icon name // caret-right - closed icon for group // caret-down - opened icon for group cellEl.append("i") .attr("class", "fas fa-fw fa-caret-right group-icon") // Add label const { title: groupTitle } = getGroupSpec(item.group) cellEl.append("span") .text(groupTitle) .attr("class", "group-label") cellEl.on('click', function (d) { // TODO add visibility indicator to request probes data without additional clicks when change intervals. let probeRows = d3.selectAll(`#graph div[data-group-id=${item.group}].graph-row`); // invert expanded let expanded = !settings.groupState[item.group].expanded; settings.groupState[item.group].expanded = expanded; getTimeRangeSrv().onExpandGroup(item.group, expanded); probeRows.each(function () { let rowEl = d3.select(this) let probeId = rowEl.attr('data-probe-id'); if (probeId === "__total__") { return } rowEl.classed("graph-row-hidden", !rowEl.classed("graph-row-hidden")); rowEl.classed("graph-row-visible", !rowEl.classed("graph-row-visible")); }) // toggle icon let iconEl = cellEl.select(".group-icon svg[data-fa-i2svg]") iconEl.classed("fa-caret-down", settings.groupState[item.group].expanded); iconEl.classed("fa-caret-right", !settings.groupState[item.group].expanded); // trigger event to re-render graph if (!settings.groupState[item.group]["probe-data-loaded"]) { getEventsSrv().fireEvent("UpdateGroupProbes", { group: item.group }) } }); } else { rowEl.classed("graph-row-hidden", true); rowEl.classed(`row-${item.type}`, true); rowEl.classed(`row-probe`, true); // Add label const { title: probeTitle } = getProbeSpec(item.group, item.probe) cellEl.append("span") .text(probeTitle) .attr("class", "probe-label") } let infoEl = cellEl.append("div") .attr("class", "group-probe-info") ReactDOM.render( <Tooltip content={<GroupProbeTooltip groupName={item.group} probeName={item.probe} />} placement="right-start"> <Icon name="fa-info-circle" className="group-probe-info" /> </Tooltip> , infoEl.node() ) }); // Each row has empty cell to define initial height for empty rows groupsEnter.append("div") //.text("Data for group '" + group + "'") .attr("class", "graph-cell cell-data") .append("svg") .attr("width", pieBoxWidth) .attr("height", pieBoxWidth) } export function updateTicks(dataset: Dataset, settings: LegacySettings) { let root = d3.select("#graph div.top-ticks") // Always recreate top ticks root.selectAll("div.top-tick").remove(); const topTicks = calculateTopTicks(dataset, settings); topTicks.forEach((tick) => root.append("div") .attr("data-timeslot", tick.ts) .attr("class", "top-tick") .append("span") .text(tick.text) ); // 'Total' label root.append("div") .attr("class", "top-tick total-tick") .append("span") .text("Total"); } export function renderGroupData(_: Dataset, settings: any, group: string, data: StatusRange) { let rowEl = d3.select(`#graph div[data-group-id=${group}][data-probe-id="__total__"]`); rowEl.selectAll(".cell-data").remove(); if (!data["statuses"] || !data["statuses"][group]["__total__"]) { console.log("Bad group data", data); } data["statuses"][group]["__total__"].forEach(function (item, i) { let cell = rowEl.append("div") //.text("Data for group '" + group + "'") .attr("class", "graph-cell cell-data"); const viewBox = [0, 0, pieBoxWidth, pieBoxWidth].join(" ") let svg = cell.append("svg") .attr("width", pieBoxWidth) .attr("height", pieBoxWidth) .attr("viewBox", viewBox); drawOnePie(svg, settings, item, "group") }) let piesCount = data["statuses"][group]["__total__"].length; // add empty boxes into probe rows to prevent stripe background on expand let rows = d3.selectAll(`#graph div[data-group-id=${group}].graph-row`); rows.each(function (item: any) { if (item.probe === "__total__") { return } let rowEl = d3.select(this); rowEl.selectAll(".cell-data").remove(); for (let i = 0; i < piesCount; i++) { rowEl.append("div") .attr("class", "graph-cell cell-data") .append("svg") .attr("width", pieBoxWidth) .attr("height", pieBoxWidth) } }) } export function renderGroupProbesData(settings: LegacySettings, group: string, data: StatusRange) { let root = d3.select("#graph"); let statuses = data["statuses"] for (const group in statuses) { if (!statuses.hasOwnProperty(group)) { continue } let probes = statuses[group]; for (const probe in probes) { if (!probes.hasOwnProperty(probe)) { continue } let rowEl = root.select(`div[data-group-id=${group}][data-probe-id=${probe}]`); rowEl.selectAll(".cell-data").remove(); let cellCount = probes[probe].length; probes[probe].forEach(function (item, i) { const cell = rowEl.append("div") .attr("class", "graph-cell cell-data"); if (i === 0) { cell.classed("first-in-row", true); } if (i === cellCount - 1) { cell.classed("last-in-row", true); } const viewBox = [0, 0, pieBoxWidth, pieBoxWidth].join(" ") const svg = cell.append("svg") .attr("width", pieBoxWidth) .attr("height", pieBoxWidth) .attr("viewBox", viewBox); drawOnePie(svg, settings, item, "probe") }) } } } // pie for each "g" const pie = d3.pie() .padAngle(0) .sort(null) .value(x => x.valueOf()); const arcs = { "group": function () { const radius = pieBoxWidth / 2; return d3.arc().innerRadius(0).outerRadius(radius - 1); }(), "probe": function () { const radius = pieBoxWidth * 0.8 / 2; return d3.arc().innerRadius(0).outerRadius(radius - 1); }(), }; function toPieData(d: Episode): Array<{ name: string, valueOf(): number }> { const fields = ["up", "down", "muted", "unknown", "nodata"] const listedTimers: Array<{ name: string, valueOf(): number }> = [] for (const [field, value] of Object.entries(d)) { if (!fields.includes(field)) { continue } listedTimers.push({ name: field, valueOf: () => +(value), }); } return listedTimers } function drawOnePie(root: any, settings: LegacySettings, episode: Episode, pieType: "group" | "probe") { const halfWidth = pieBoxWidth / 2 const pieRoot = root.append("g") .attr("class", "statusPie") .attr("height", pieBoxWidth) .attr("width", pieBoxWidth) .attr("transform", () => `translate(${halfWidth},${halfWidth})`) pieRoot.selectAll("path") .data(pie(toPieData(episode))) .join("path") .attr("class", (d: { data: { name: string; }; }) => "pie-seg-" + d.data.name) .attr("d", arcs[pieType]) .append("title") .text((d: { data: { name: string; valueOf(): number }; }) => `${d.data.name}: ${d.data.valueOf().toLocaleString()}`); // Add text with availability percents pieRoot.append("text") .text(availabilityPercent(+episode.up, +episode.down, +episode.muted, 2)) .attr("class", `pie-text-${pieType}`); // Add a transparent rectangle to use // as a bounding box for click events and for tooltip hover events. const boundingRectRoot = pieRoot.append("g") const onClick = () => getTimeRangeSrv().drillDownStep(+episode.ts) ReactDOM.render( <PieBoundingRect size={pieBoxWidth} episode={episode} onClick={onClick}/>, boundingRectRoot.node() ) }
the_stack
* @module @morgan-stanley/desktopjs-openfin */ import { registerContainer, ContainerWindow, PersistedWindowLayout, Rectangle, Container, WebContainerBase, ScreenManager, Display, Point, ObjectTransform, PropertyMap, NotificationOptions, ContainerNotification, TrayIconDetails, MenuItem, Guid, MessageBus, MessageBusSubscription, MessageBusOptions, EventArgs, GlobalShortcutManager, WindowEventArgs } from "@morgan-stanley/desktopjs"; registerContainer("OpenFin", { condition: () => typeof window !== "undefined" && "fin" in window && "desktop" in (<any>window).fin, create: (options) => <any>new OpenFinContainer(null, null, options) }); const windowEventMap = { move: "bounds-changing", resize: "bounds-changing", close: "closing", focus: "focused", blur: "blurred", maximize: "maximized", minimize: "minimized", restore: "restored" }; /** * @augments ContainerWindow */ export class OpenFinContainerWindow extends ContainerWindow { public constructor(wrap: any) { super(wrap); } public get id(): string { return this.name; // Reuse name since it is the unique identifier } public get name(): string { return this.innerWindow.name; } public load(url: string, options?: any): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.navigate(url, resolve, reject); }); } public focus(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.focus(resolve, reject); }); } public show(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.show(resolve, reject); }); } public hide(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.hide(resolve, reject); }); } public close(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.close(false, resolve, reject); }); } public minimize(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.minimize(resolve, reject); }); } public maximize(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.maximize(resolve, reject); }); } public restore(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.restore(resolve, reject); }); } public isShowing(): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { this.innerWindow.isShowing(resolve, reject); }); } public getSnapshot(): Promise<string> { return new Promise<string>((resolve, reject) => { this.innerWindow.getSnapshot( (snapshot) => resolve("data:image/png;base64," + snapshot), (reason) => reject(reason) ); }); } public getBounds(): Promise<Rectangle> { return new Promise<Rectangle>((resolve, reject) => { this.innerWindow.getBounds( bounds => resolve(new Rectangle(bounds.left, bounds.top, bounds.width, bounds.height)), reject); }); } public flash(enable: boolean, options?: any): Promise<void> { return new Promise<void>((resolve, reject) => { if (enable) { this.innerWindow.flash(options, resolve, reject); } else { this.innerWindow.stopFlashing(resolve, reject); } }); } public getParent(): Promise<ContainerWindow> { return Promise.resolve(null); } public setParent(parent: ContainerWindow): Promise<void> { return new Promise<void>((resolve, reject) => { resolve(); }); } public setBounds(bounds: Rectangle): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.setBounds(bounds.x, bounds.y, bounds.width, bounds.height, resolve, reject); }); } public get allowGrouping() { return true; } public getGroup(): Promise<ContainerWindow[]> { return new Promise<ContainerWindow[]>((resolve, reject) => { this.innerWindow.getGroup(windows => { resolve(windows.map(window => new OpenFinContainerWindow(window))); }, reject); }); } public joinGroup(target: ContainerWindow): Promise<void> { if (!target || target.id === this.id) { return Promise.resolve(); } return new Promise<void>((resolve, reject) => { this.innerWindow.joinGroup(target.innerWindow, () => { ContainerWindow.emit("window-joinGroup", { name: "window-joinGroup", windowId: this.id, targetWindowId: target.id } ); resolve(); }, reject); }); } public leaveGroup(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.leaveGroup(() => { ContainerWindow.emit("window-leaveGroup", { name: "window-leaveGroup", windowId: this.id } ); resolve(); }, reject); }); } public bringToFront(): Promise<void> { return new Promise<void>((resolve, reject) => { this.innerWindow.bringToFront(resolve, reject); }); } public getOptions(): Promise<any> { return new Promise<any>((resolve, reject) => { this.innerWindow.getOptions(options => resolve(options.customData ? JSON.parse(options.customData) : undefined), reject); }); } public getState(): Promise<any> { return new Promise<any>(resolve => { (this.nativeWindow && (<any>this.nativeWindow).getState) ? resolve((<any>this.nativeWindow).getState()) : resolve(undefined); }); } public setState(state: any): Promise<void> { return new Promise<void>(resolve => { if (this.nativeWindow && (<any>this.nativeWindow).setState) { (<any>this.nativeWindow).setState(state); } resolve(); }).then(() => { this.emit("state-changed", <EventArgs> { name: "state-changed", sender: this, state: state }); ContainerWindow.emit("state-changed", <WindowEventArgs> { name: "state-changed", windowId: this.id, state: state } ); }); } protected attachListener(eventName: string, listener: (...args: any[]) => void): void { if (eventName === "beforeunload") { this.innerWindow.addEventListener("close-requested", (e) => { const args = new EventArgs(this, "beforeunload", e); listener(args); if (typeof args.returnValue === "undefined") { this.innerWindow.close(true); } }); } else { this.innerWindow.addEventListener(windowEventMap[eventName] || eventName, listener); } } protected wrapListener(eventName: string, listener: (event: EventArgs) => void): (event: EventArgs) => void { // Split OpenFin bounds-changed event to separate resize/move events if (eventName === "resize") { return (event) => { if ((<any>event).changeType >= 1) { listener(new EventArgs(this, eventName, event)); } }; } else if (eventName === "move") { return (event) => { if ((<any>event).changeType === 0) { listener(new EventArgs(this, eventName, event)); } }; } else { return super.wrapListener(eventName, listener); } } protected detachListener(eventName: string, listener: (...args: any[]) => void): any { this.innerWindow.removeEventListener(windowEventMap[eventName] || eventName, listener); } public get nativeWindow(): Window { return this.innerWindow.getNativeWindow(); } } /** * @augments MessageBus */ export class OpenFinMessageBus implements MessageBus { private bus: any; private uuid: string; public constructor(bus: any, uuid: string) { this.bus = bus; this.uuid = uuid; } public subscribe<T>(topic: string, listener: (event: any, message: T) => void, options?: MessageBusOptions): Promise<MessageBusSubscription> { return new Promise<MessageBusSubscription>((resolve, reject) => { const subscription: MessageBusSubscription = new MessageBusSubscription(topic, (message: any, uuid: string, name: string) => { listener( /* Event */ { topic: topic }, message); }, options); this.bus.subscribe(options && options.uuid || "*", // senderUuid options && options.name || undefined, // name subscription.topic, // topic subscription.listener, // listener () => resolve(subscription), // callback reject); // errorCallback }); } public unsubscribe(subscription: MessageBusSubscription): Promise<void> { const { topic, listener, options } = subscription; return new Promise<void>((resolve, reject) => { this.bus.unsubscribe(options && options.uuid || "*", // senderUuid options && options.name || undefined, // name topic, // topic listener, // listener resolve, // callback reject); // errorCallback }); } public publish<T>(topic: string, message: T, options?: MessageBusOptions): Promise<void> { return new Promise<void>((resolve, reject) => { // If publisher has targets defined, use OpenFin send vs broadcast publish // If name is specified but not uuid, assume the user wants current app uuid if ((options && options.uuid) || (options && options.name)) { this.bus.send(options.uuid || this.uuid, // destinationUuid options.name || undefined, // name topic, // topic message, // message resolve, // callback reject); // errorCallback } else { this.bus.publish(topic, // topic message, // message resolve, // callback reject); // errorCallback } }); } } /** * @extends WebContainerBase */ export class OpenFinContainer extends WebContainerBase { private desktop: any; private mainWindow: OpenFinContainerWindow; private menuItemRef: MenuItem[]; // Offsets for tray icon mouse click to not show over icon private static readonly trayIconMenuLeftOffset: number = 4; private static readonly trayIconMenuTopOffset: number = 23; private static readonly notificationGuid: string = "A21B62E0-16B1-4B10-8BE3-BBB6B489D862"; /** * Gets or sets whether to replace the native web Notification API with OpenFin notifications. * @type {boolean} * @default true */ public static replaceNotificationApi: boolean = true; public static readonly windowOptionsMap: PropertyMap = { x: { target: "defaultLeft" }, y: { target: "defaultTop" }, height: { target: "defaultHeight" }, width: { target: "defaultWidth" }, taskbar: { target: "showTaskbarIcon" }, center: { target: "defaultCentered" }, show: { target: "autoShow" } }; public windowOptionsMap: PropertyMap = OpenFinContainer.windowOptionsMap; public static readonly notificationOptionsMap: PropertyMap = { body: { target: "message" } }; public notificationOptionsMap: PropertyMap = OpenFinContainer.notificationOptionsMap; public static menuHtml = `<html> <head> <style> body:before, body:after { position: fixed; background: silver; } body { margin: 0px; overflow: hidden; } .context-menu { list-style: none; padding: 1px 0 1px 0; } .context-menu-item { display: block; cursor: default; font-family: Arial, Helvetica, sans-serif; font-size: 9pt; margin-bottom: 2px; padding: 4px 0 4px 4px; white-space: nowrap; } .context-menu-item span { display: inline-block; min-width: 20px; } .context-menu-item:last-child { margin-bottom: 0; } .context-menu-item:hover { color: #fff; background-color: #0066aa; } .context-menu-image { width: 16px; height: 16px; margin-top: -1px; margin-right: 4px; } </style> <script> document.addEventListener('keydown', (event) => { if (event.keyCode == 27) { window.close(); } }, false); </script> </head> <body> <ul class="context-menu" id="contextMenu"></ul> </body> </html>`; public constructor(desktop?: any, win?: Window, options?: any) { super(win); this.desktop = desktop || (<any>window).fin.desktop; this.hostType = "OpenFin"; this.setOptions(options); this.ipc = this.createMessageBus(); this.desktop.Application.getCurrent().addEventListener("window-created", (event: any) => { this.emit("window-created", { sender: this, name: "window-created", windowId: event.name, windowName: event.name }); Container.emit("window-created", { name: "window-created", windowId: event.name, windowName: event.name }); ContainerWindow.emit("window-created", { name: "window-created", windowId: event.name, windowName: event.name }); }); this.screen = new OpenFinDisplayManager(this.desktop); if (this.desktop.GlobalHotkey) { this.globalShortcut = new OpenFinGlobalShortcutManager(this.desktop); } else { this.log("warn", "Global shortcuts require minimum OpenFin runtime of 9.61.32.34"); } } public setOptions(options: any) { if (options && options.userName && options.appName) { this.desktop.Application.getCurrent().registerUser(options.userName, options.appName); } if (options && options.autoStartOnLogin) { this.desktop.Application.getCurrent().setShortcuts({ systemStartup: options.autoStartOnLogin }); } let replaceNotificationApi = OpenFinContainer.replaceNotificationApi; if (options && typeof options.replaceNotificationApi !== "undefined") { replaceNotificationApi = options.replaceNotificationApi; } if (replaceNotificationApi) { this.registerNotificationsApi(); } } public async getOptions(): Promise<any> { try { return { autoStartOnLogin: await this.isAutoStartEnabledAtLogin() }; } catch(error) { throw new Error("Error getting Container options. " + error); } } private isAutoStartEnabledAtLogin(): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { this.desktop.Application.getCurrent().getShortcuts((config: any) => resolve(config.systemStartup), reject); }); } protected createMessageBus(): MessageBus { return new OpenFinMessageBus(this.desktop.InterApplicationBus, (<any>this.desktop.Application.getCurrent()).uuid); } protected registerNotificationsApi() { if (typeof this.globalWindow !== "undefined" && this.globalWindow) { // Define owningContainer for closure to inner class // eslint-disable-next-line @typescript-eslint/no-this-alias const owningContainer: OpenFinContainer = this; this.globalWindow["Notification"] = class OpenFinNotification extends ContainerNotification { constructor(title: string, options?: NotificationOptions) { super(title, options); options["notification"] = this; // Forward OpenFin notification events back to Notification API options["onClick"] = (event) => { if (this.onclick) { this.onclick(event); } }; options["onError"] = (event) => { if (this.onerror) { this.onerror(event); } }; owningContainer.showNotification(this.title, this.options); } }; } } public getInfo(): Promise<string | undefined> { return new Promise<string | undefined>((resolve, reject) => { this.desktop.System.getRvmInfo(rvmInfo => { this.desktop.System.getRuntimeInfo(runtimeInfo => { this.log("info",runtimeInfo); resolve(`RVM/${rvmInfo.version} Runtime/${runtimeInfo.version}`); }, reject); }, reject); }); } public log(level: "debug" | "info" | "warn" | "error", message: string): Promise<void> { return new Promise<void>((resolve, reject) => { this.desktop.System.log(level, message, resolve, reject); }); } public ready(): Promise<void> { return new Promise(resolve => this.desktop.main(resolve)); } public getMainWindow(): ContainerWindow { if (!this.mainWindow) { this.mainWindow = this.wrapWindow(this.desktop.Application.getCurrent().getWindow()); } return this.mainWindow; } public getCurrentWindow(): ContainerWindow { return this.wrapWindow(this.desktop.Window.getCurrent()); } protected getWindowOptions(options?: any): any { const newOptions = ObjectTransform.transformProperties(options, this.windowOptionsMap); newOptions.customData = options ? JSON.stringify(options) : undefined; // Default behavior is to show window so if there is no override in options, show the window if (!("autoShow" in newOptions)) { newOptions.autoShow = true; } // Change default of window state saving to false if (!("saveWindowState" in newOptions) && ("defaultLeft" in newOptions || "defaultTop" in newOptions)) { newOptions.saveWindowState = false; } if ("icon" in newOptions) { newOptions.icon = this.ensureAbsoluteUrl(newOptions.icon); } return newOptions; } public wrapWindow(containerWindow: any) { return new OpenFinContainerWindow(containerWindow); } public createWindow(url: string, options?: any): Promise<ContainerWindow> { const newOptions = this.getWindowOptions(options); newOptions.url = url; // createWindow param will always take precedence over any passed on options // OpenFin requires a name for the window to show if (!("name" in newOptions)) { newOptions.name = Guid.newGuid(); } return new Promise<ContainerWindow>((resolve, reject) => { const ofWin = new this.desktop.Window(newOptions, win => { resolve(this.wrapWindow(ofWin)); }, reject); }); } public showNotification(title: string, options?: NotificationOptions) { const msg = new this.desktop.Notification(ObjectTransform.transformProperties(options, this.notificationOptionsMap)); } protected getMenuHtml() { return OpenFinContainer.menuHtml; } protected getMenuItemHtml(item: MenuItem) { const imgHtml: string = (item.icon) ? `<span><img align="absmiddle" class="context-menu-image" src="${this.ensureAbsoluteUrl(item.icon)}" /></span>` : "<span>&nbsp;</span>"; return `<li class="context-menu-item" onclick="fin.desktop.InterApplicationBus.send('${(<any>this.desktop.Application.getCurrent()).uuid}` + `', null, 'TrayIcon_ContextMenuClick_${this.uuid}', { id: '${item.id}' });this.close()">${imgHtml}${item.label}</li>`; } private showMenu(x: number, y: number, monitorInfo: any, menuItems: MenuItem[]) { this.menuItemRef = menuItems; const contextMenu = new this.desktop.Window( <any>{ name: `trayMenu${Guid.newGuid()}`, saveWindowState: false, autoShow: false, defaultWidth: 150, defaultHeight: 100, showTaskbarIcon: false, frame: false, contextMenu: true, resizable: false, alwaysOnTop: true, shadow: true, smallWindow: true } , () => { const win: Window = contextMenu.getNativeWindow(); win.document.open("text/html", "replace"); win.document.write(this.getMenuHtml()); win.document.close(); let menuItemHtml = ""; for (const item of menuItems.filter(value => value.label)) { if (!item.id) { item.id = Guid.newGuid(); } menuItemHtml += this.getMenuItemHtml(item); } const contextMenuElement: HTMLElement = win.document.getElementById("contextMenu"); contextMenuElement.innerHTML = menuItemHtml; // Size <ul> to fit const { "offsetWidth": width, "offsetHeight": height } = contextMenuElement; contextMenu.resizeTo(width, height, "top-left"); // If the menu will not fit on the monitor as right/down from x, y then show left/up const left = (x + width) > monitorInfo.primaryMonitor.monitorRect.right ? x - width - OpenFinContainer.trayIconMenuLeftOffset : x; const top = (y + height) > monitorInfo.primaryMonitor.monitorRect.bottom ? y - height - OpenFinContainer.trayIconMenuTopOffset : y; contextMenu.addEventListener("blurred", () => contextMenu.close()); contextMenu.showAt(left, top, false, () => contextMenu.focus()); }); } public addTrayIcon(details: TrayIconDetails, listener: () => void, menuItems?: MenuItem[]) { this.desktop.Application.getCurrent() .setTrayIcon(this.ensureAbsoluteUrl(details.icon), (clickInfo) => { if (clickInfo.button === 0 && listener) { // Passthrough left click to addTrayIcon listener callback listener(); } else if (clickInfo.button === 2) { // handle right click ourselves to display context menu this.showMenu(clickInfo.x + OpenFinContainer.trayIconMenuLeftOffset, clickInfo.y + OpenFinContainer.trayIconMenuTopOffset, clickInfo.monitorInfo, menuItems); } }, () => { // Append desktopJS container instance uuid to topic so communication is unique to this tray icon and window this.desktop.InterApplicationBus.subscribe((<any>this.desktop.Application.getCurrent()).uuid, "TrayIcon_ContextMenuClick_" + this.uuid, (message, uuid) => { for (const prop in this.menuItemRef) { const item = this.menuItemRef[prop]; if (item.id === message.id && item.click) { item.click(item); } } }); }, (error) => { this.log("error", error); }); } protected closeAllWindows(): Promise<void> { return new Promise<void>((resolve, reject) => { const windowClosing: Promise<void>[] = []; this.desktop.Application.getCurrent().getChildWindows(windows => { windows.forEach(window => { windowClosing.push(new Promise<void>((innerResolve, innerReject) => window.close(true, innerResolve, innerReject))); }); Promise.all(windowClosing).then(() => resolve()); }, reject); }); } public getAllWindows(): Promise<ContainerWindow[]> { return new Promise<ContainerWindow[]>((resolve, reject) => { this.desktop.Application.getCurrent().getChildWindows(windows => { windows.push(this.desktop.Application.getCurrent().getWindow()); resolve(windows.map(window => this.wrapWindow(window))); }, reject); }); } public getWindowById(id: string): Promise<ContainerWindow | null> { return this.getWindowByName(id); } public getWindowByName(name: string): Promise<ContainerWindow | null> { return new Promise<ContainerWindow>((resolve, reject) => { this.desktop.Application.getCurrent().getChildWindows(windows => { windows.push(this.desktop.Application.getCurrent().getWindow()); const win = windows.find(window => window.name === name); resolve(win ? this.wrapWindow(win) : null); }); }); } public buildLayout(): Promise<PersistedWindowLayout> { const layout = new PersistedWindowLayout(); // eslint-disable-next-line no-async-promise-executor return new Promise<PersistedWindowLayout>(async (resolve, reject) => { const windows = await this.getAllWindows(); const mainWindow = this.getMainWindow(); const promises: Promise<void>[] = []; windows.filter(window => window.name !== "queueCounter" && !window.name.startsWith(OpenFinContainer.notificationGuid)) .forEach(djsWindow => { // eslint-disable-next-line no-async-promise-executor promises.push(new Promise<void>(async (innerResolve, innerReject) => { const state = await djsWindow.getState(); const window = djsWindow.innerWindow; window.getBounds(bounds => { window.getOptions(options => { // If window was created with persist: false, skip from layout const customData: any = (options.customData ? JSON.parse(options.customData) : undefined); if (customData && "persist" in customData && !customData.persist) { innerResolve(); } else { delete (<any>options).show; // show is an undocumented option that interferes with the createWindow mapping of show -> autoShow window.getGroup(group => { layout.windows.push( { name: window.name, id: window.name, url: window.getNativeWindow() ? window.getNativeWindow().location.toString() : options.url, main: (mainWindow && (mainWindow.name === window.name)), options: options, state: state, bounds: { x: bounds.left, y: bounds.top, width: bounds.width, height: bounds.height }, group: group.map(win => win.name) }); innerResolve(); }, innerReject); } }, innerReject); }, innerReject); })); }); Promise.all(promises).then(() => { resolve(layout); }).catch(reject); }); } } /** @private */ class OpenFinDisplayManager implements ScreenManager { private readonly desktop: any; public constructor(desktop: any) { this.desktop = desktop; } createDisplay(monitorDetails: any) { const display = new Display(); display.id = monitorDetails.name; display.scaleFactor = monitorDetails.deviceScaleFactor; display.bounds = new Rectangle(monitorDetails.monitorRect.left, monitorDetails.monitorRect.top, monitorDetails.monitorRect.right - monitorDetails.monitorRect.left, monitorDetails.monitorRect.bottom - monitorDetails.monitorRect.top); display.workArea = new Rectangle(monitorDetails.availableRect.left, monitorDetails.availableRect.top, monitorDetails.availableRect.right - monitorDetails.availableRect.left, monitorDetails.availableRect.bottom - monitorDetails.availableRect.top); return display; } public getPrimaryDisplay(): Promise<Display> { return new Promise<Display>((resolve, reject) => { this.desktop.System.getMonitorInfo(monitorInfo => { resolve(this.createDisplay(monitorInfo.primaryMonitor)); }, reject); }); } public getAllDisplays(): Promise<Display[]> { return new Promise<Display[]>((resolve, reject) => { this.desktop.System.getMonitorInfo(monitorInfo => { resolve([monitorInfo.primaryMonitor].concat(monitorInfo.nonPrimaryMonitors).map(this.createDisplay)); }, reject); }); } public getMousePosition(): Promise<Point> { return new Promise<Point>((resolve, reject) => { this.desktop.System.getMousePosition(position => { resolve({ x: position.left, y: position.top }); }, reject); }); } } /** @private */ class OpenFinGlobalShortcutManager extends GlobalShortcutManager { private readonly desktop: any; public constructor(desktop: any) { super(); this.desktop = desktop; } public register(shortcut: string, callback: () => void): Promise<void> { return new Promise<void>((resolve, reject) => { this.desktop.GlobalHotkey.register(shortcut, callback, resolve, reject); }); } public isRegistered(shortcut: string): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { this.desktop.GlobalHotkey.isRegistered(shortcut, resolve, reject); }); } public unregister(shortcut: string): Promise<void> { return new Promise<void>((resolve, reject) => { this.desktop.GlobalHotkey.unregister(shortcut, resolve, reject); }); } public unregisterAll(): Promise<void> { return new Promise<void>((resolve, reject) => { this.desktop.GlobalHotkey.unregisterAll(resolve, reject); }); } }
the_stack
import GL from '@luma.gl/constants'; import {cloneTextureFrom, readPixelsToArray, Buffer, Texture2D, Framebuffer} from '@luma.gl/gltools'; import { _transform as transformModule, getShaderInfo, getPassthroughFS, typeToChannelCount, combineInjects } from '@luma.gl/shadertools'; import {updateForTextures, getSizeUniforms} from './transform-shader-utils'; import type {TransformProps, TransformDrawOptions} from './transform-types'; // TODO: move these constants to transform-shader-utils // Texture parameters needed so sample can precisely pick pixel for given element id. const SRC_TEX_PARAMETER_OVERRIDES = { [GL.TEXTURE_MIN_FILTER]: GL.NEAREST, [GL.TEXTURE_MAG_FILTER]: GL.NEAREST, [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE, [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE }; const FS_OUTPUT_VARIABLE = 'transform_output'; export default class TextureTransform { gl: WebGL2RenderingContext; id = 0; currentIndex = 0; _swapTexture = null; targetTextureVarying = null; targetTextureType = null; samplerTextureMap = null; bindings = []; // each element is an object : {sourceTextures, targetTexture, framebuffer} resources = {}; // resources to be deleted hasTargetTexture: boolean = false; hasSourceTextures: boolean = false; ownTexture: Texture2D | null = null; elementIDBuffer: Buffer | null = null; _targetRefTexName: string; elementCount: number; constructor(gl: WebGL2RenderingContext, props: TransformProps = {}) { this.gl = gl; this.id = this.currentIndex = 0; this._swapTexture = null; this.targetTextureVarying = null; this.targetTextureType = null; this.samplerTextureMap = null; this.bindings = []; // each element is an object : {sourceTextures, targetTexture, framebuffer} this.resources = {}; // resources to be deleted this._initialize(props); Object.seal(this); } updateModelProps(props: TransformProps = {}) { const updatedModelProps = this._processVertexShader(props); return Object.assign({}, props, updatedModelProps); } getDrawOptions(opts: TransformProps = {}): TransformDrawOptions { const {sourceBuffers, sourceTextures, framebuffer, targetTexture} = this.bindings[this.currentIndex]; const attributes = Object.assign({}, sourceBuffers, opts.attributes); const uniforms = Object.assign({}, opts.uniforms); const parameters = Object.assign({}, opts.parameters); let discard = opts.discard; if (this.hasSourceTextures || this.hasTargetTexture) { attributes.transform_elementID = this.elementIDBuffer; for (const sampler in this.samplerTextureMap) { const textureName = this.samplerTextureMap[sampler]; uniforms[sampler] = sourceTextures[textureName]; } this._setSourceTextureParameters(); // get texture size uniforms const sizeUniforms = getSizeUniforms({ sourceTextureMap: sourceTextures, targetTextureVarying: this.targetTextureVarying, targetTexture }); Object.assign(uniforms, sizeUniforms); } if (this.hasTargetTexture) { discard = false; parameters.viewport = [0, 0, framebuffer.width, framebuffer.height]; } return {attributes, framebuffer, uniforms, discard, parameters}; } swap() { if (this._swapTexture) { this.currentIndex = this._getNextIndex(); return true; } return false; } // update source and/or feedbackBuffers update(opts = {}) { this._setupTextures(opts); } // returns current target texture getTargetTexture() { const {targetTexture} = this.bindings[this.currentIndex]; return targetTexture; } getData({packed = false} = {}) { const {framebuffer} = this.bindings[this.currentIndex]; const pixels = readPixelsToArray(framebuffer); if (!packed) { return pixels; } // readPixels returns 4 elements for each pixel, pack the elements when requested const ArrayType = pixels.constructor; const channelCount = typeToChannelCount(this.targetTextureType); // @ts-expect-error const packedPixels = new ArrayType((pixels.length * channelCount) / 4); let packCount = 0; for (let i = 0; i < pixels.length; i += 4) { for (let j = 0; j < channelCount; j++) { packedPixels[packCount++] = pixels[i + j]; } } return packedPixels; } // returns current framebuffer object that is being used. getFramebuffer() { const currentResources = this.bindings[this.currentIndex]; return currentResources.framebuffer; } // Delete owned resources. delete() { if (this.ownTexture) { this.ownTexture.delete(); } if (this.elementIDBuffer) { this.elementIDBuffer.delete(); } } // Private _initialize(props: TransformProps = {}) { const {_targetTextureVarying, _swapTexture} = props; this._swapTexture = _swapTexture; this.targetTextureVarying = _targetTextureVarying; this.hasTargetTexture = Boolean(_targetTextureVarying); this._setupTextures(props); } // auto create target texture if requested _createTargetTexture(props) { const {sourceTextures, textureOrReference} = props; if (textureOrReference instanceof Texture2D) { return textureOrReference; } // 'targetTexture' is a reference souce texture. const refTexture = sourceTextures[textureOrReference]; if (!refTexture) { return null; } // save reference texture name, when corresponding source texture is updated // we also update target texture. this._targetRefTexName = textureOrReference; return this._createNewTexture(refTexture); } _setupTextures(props: TransformProps = {}) { const {sourceBuffers, _sourceTextures = {}, _targetTexture} = props; const targetTexture = this._createTargetTexture({ sourceTextures: _sourceTextures, textureOrReference: _targetTexture }); this.hasSourceTextures = this.hasSourceTextures || (_sourceTextures && Object.keys(_sourceTextures).length > 0); this._updateBindings({sourceBuffers, sourceTextures: _sourceTextures, targetTexture}); if ('elementCount' in props) { this._updateElementIDBuffer(props.elementCount); } } _updateElementIDBuffer(elementCount: number): void { if (typeof elementCount !== 'number' || this.elementCount >= elementCount) { return; } // NOTE: using float so this will work with GLSL 1.0 shaders. const elementIds = new Float32Array(elementCount); elementIds.forEach((_, index, array) => { array[index] = index; }); if (!this.elementIDBuffer) { this.elementIDBuffer = new Buffer(this.gl, { data: elementIds, accessor: {size: 1} }); } else { this.elementIDBuffer.setData({data: elementIds}); } this.elementCount = elementCount; } _updateBindings(opts) { this.bindings[this.currentIndex] = this._updateBinding(this.bindings[this.currentIndex], opts); if (this._swapTexture) { const {sourceTextures, targetTexture} = this._swapTextures(this.bindings[this.currentIndex]); const nextIndex = this._getNextIndex(); this.bindings[nextIndex] = this._updateBinding(this.bindings[nextIndex], { sourceTextures, targetTexture }); } } _updateBinding(binding, opts) { const {sourceBuffers, sourceTextures, targetTexture} = opts; if (!binding) { binding = { sourceBuffers: {}, sourceTextures: {}, targetTexture: null }; } Object.assign(binding.sourceTextures, sourceTextures); Object.assign(binding.sourceBuffers, sourceBuffers); if (targetTexture) { binding.targetTexture = targetTexture; const {width, height} = targetTexture; const {framebuffer} = binding; if (framebuffer) { // First update texture without re-sizing attachments framebuffer.update({ attachments: {[GL.COLOR_ATTACHMENT0]: targetTexture}, resizeAttachments: false }); // Resize to new taget texture size framebuffer.resize({width, height}); } else { binding.framebuffer = new Framebuffer(this.gl, { id: `transform-framebuffer`, width, height, attachments: { [GL.COLOR_ATTACHMENT0]: targetTexture } }); } } return binding; } // set texture filtering parameters on source textures. _setSourceTextureParameters() { const index = this.currentIndex; const {sourceTextures} = this.bindings[index]; for (const name in sourceTextures) { sourceTextures[name].setParameters(SRC_TEX_PARAMETER_OVERRIDES); } } _swapTextures(opts) { if (!this._swapTexture) { return null; } const sourceTextures = Object.assign({}, opts.sourceTextures); sourceTextures[this._swapTexture] = opts.targetTexture; const targetTexture = opts.sourceTextures[this._swapTexture]; return {sourceTextures, targetTexture}; } // Create a buffer and add to list of buffers to be deleted. _createNewTexture(refTexture: Texture2D) { const texture = cloneTextureFrom(refTexture, { parameters: { [GL.TEXTURE_MIN_FILTER]: GL.NEAREST, [GL.TEXTURE_MAG_FILTER]: GL.NEAREST, [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE, [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE }, pixelStore: { [GL.UNPACK_FLIP_Y_WEBGL]: false } }); // thre can only be one target texture if (this.ownTexture) { this.ownTexture.delete(); } this.ownTexture = texture; return texture; } _getNextIndex() { return (this.currentIndex + 1) % 2; } // build and return shader releated parameters _processVertexShader(props: TransformProps = {}) { const {sourceTextures, targetTexture} = this.bindings[this.currentIndex]; // @ts-expect-error TODO - uniforms is not present const {vs, uniforms, targetTextureType, inject, samplerTextureMap} = updateForTextures({ vs: props.vs, sourceTextureMap: sourceTextures, targetTextureVarying: this.targetTextureVarying, targetTexture }); const combinedInject = combineInjects([props.inject || {}, inject]); this.targetTextureType = targetTextureType; this.samplerTextureMap = samplerTextureMap; const fs = props._fs || getPassthroughFS({ version: getShaderInfo(vs).version, input: this.targetTextureVarying, inputType: targetTextureType, output: FS_OUTPUT_VARIABLE }); const modules = this.hasSourceTextures || this.targetTextureVarying // @ts-expect-error ? [transformModule].concat(props.modules || []) : props.modules; return {vs, fs, modules, uniforms, inject: combinedInject}; } }
the_stack
import React from 'react' import * as MaterialUI from '@material-ui/core' import { DialogMessageObj, checkResultToString } from '../../scripts/text-generate' import { requestResetCounter } from '../../scripts/background/request-sender' import { MyselfContext, BlockLimiterContext, RedBlockOptionsContext, UIContext } from './contexts' import { ExtraSessionOptionsContext } from './ui-states' import type { TargetCheckResult } from '../../scripts/background/target-checker' import { RadioOptionItem, CheckboxItem } from '../../ui/components' import * as i18n from '../../scripts/i18n' const M = MaterialUI const T = MaterialUI.Typography export interface DialogContent { message: DialogMessageObj dialogType: 'confirm' | 'alert' callbackOnOk?(): void callbackOnCancel?(): void } export function RedBlockPopupUITheme(darkMode: boolean) { return MaterialUI.createTheme({ typography: { fontSize: 12, }, palette: { type: darkMode ? 'dark' : 'light', primary: MaterialUI.colors.pink, secondary: darkMode ? MaterialUI.colors.lightBlue : MaterialUI.colors.indigo, }, }) } export const MyTooltip = MaterialUI.withStyles(() => ({ tooltip: { fontSize: 12, }, }))(MaterialUI.Tooltip) export const SmallAvatar = MaterialUI.withStyles(theme => ({ root: { width: 16, height: 16, border: `1px solid ${theme.palette.background.paper}`, }, }))(M.Avatar) function Icon({ name }: { name: string }) { // overflow: purpose 탭 아이콘 짤림 문제방지 // (특히 탭 라벨이 두 줄이상으로 넘어갈때) return <M.Icon style={{ overflow: 'visible' }}>{name}</M.Icon> } function purposeTypeToIcon(purposeType: Purpose['type']): JSX.Element { switch (purposeType) { case 'chainblock': return <Icon name="block" /> case 'unchainblock': return <Icon name="favorite_border" /> case 'export': return <Icon name="save" /> case 'lockpicker': return <Icon name="no_encryption" /> case 'chainunfollow': return <Icon name="remove_circle_outline" /> case 'chainmute': return <Icon name="volume_off" /> case 'unchainmute': return <Icon name="volume_up" /> } } export function RBDialog({ isOpen, content, closeModal, }: { isOpen: boolean content: DialogContent | null closeModal(): void }) { if (!content) { return <div></div> } const { message, callbackOnOk, callbackOnCancel, dialogType } = content const { title, contentLines, warningLines } = message function confirmOk() { if (typeof callbackOnOk === 'function') { callbackOnOk() } closeModal() } function refused() { if (typeof callbackOnCancel === 'function') { callbackOnCancel() } closeModal() } function renderControls() { switch (dialogType) { case 'confirm': return ( <React.Fragment> <M.Button onClick={confirmOk} color="primary"> {i18n.getMessage('yes')} </M.Button> <M.Button onClick={refused}>{i18n.getMessage('no')}</M.Button> </React.Fragment> ) case 'alert': return ( <React.Fragment> <M.Button onClick={closeModal} color="primary"> {i18n.getMessage('close')} </M.Button> </React.Fragment> ) } } const { Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions } = MaterialUI return ( <Dialog open={isOpen}> <DialogTitle>{title}</DialogTitle> <DialogContent> {contentLines && contentLines.map((line, index) => ( <DialogContentText key={index}>{line}</DialogContentText> ))} {warningLines && warningLines.map((line, index) => ( <DialogContentText key={index} color="error"> {line} </DialogContentText> ))} </DialogContent> <DialogActions>{renderControls()}</DialogActions> </Dialog> ) } // from https://material-ui.com/components/tabs/#SimpleTabs.tsx export function TabPanel({ children, value, index, noPadding, }: { children?: React.ReactNode index: any value: any noPadding?: boolean }) { const padding = noPadding ? 0 : 1 return ( <T component="div" role="tabpanel" hidden={value !== index}> {value === index && ( <M.Box py={1} px={padding}> {children} </M.Box> )} </T> ) } export function PleaseLoginBox() { function closePopup(_event: React.MouseEvent) { window.setTimeout(() => { window.close() }, 200) } return ( <M.Paper> <M.Box px={2} py={1.5}> <T component="div">{i18n.getMessage('please_check_login')}</T> <M.Box mt={1}> <a rel="noopener noreferrer" target="_blank" href="https://twitter.com/login" onClick={closePopup} style={{ textDecoration: 'none' }} > <M.Button variant="outlined" startIcon={<M.Icon>exit_to_app</M.Icon>}> Login </M.Button> </a> </M.Box> </M.Box> </M.Paper> ) } const DenseAccordion = MaterialUI.withStyles(theme => ({ root: { margin: theme.spacing(1, 0), '&:first-child': { margin: '0', }, '&$expanded': { margin: theme.spacing(1, 0), }, }, expanded: {}, }))(MaterialUI.Accordion) const DenseAccordionSummary = MaterialUI.withStyles({ root: { minHeight: 16, '&$expanded': { minHeight: 16, }, }, content: { '&$expanded': { margin: 0, }, }, expanded: {}, })(MaterialUI.AccordionSummary) const useStylesForAccordions = MaterialUI.makeStyles(theme => MaterialUI.createStyles({ details: { padding: theme.spacing(1, 2), }, }) ) export function RBAccordion({ summary, children, defaultExpanded, warning, }: { summary: string children: React.ReactNode defaultExpanded?: boolean warning?: boolean }) { const classes = useStylesForAccordions() return ( <DenseAccordion defaultExpanded={defaultExpanded}> <DenseAccordionSummary expandIcon={<M.Icon>expand_more</M.Icon>}> <T color={warning ? 'error' : 'initial'}>{summary}</T> </DenseAccordionSummary> <M.AccordionDetails className={classes.details}>{children}</M.AccordionDetails> </DenseAccordion> ) } export function BlockLimiterUI() { const { current, max } = React.useContext(BlockLimiterContext) const myself = React.useContext(MyselfContext)! function handleResetButtonClick(event: React.MouseEvent<HTMLButtonElement>) { event.preventDefault() requestResetCounter(myself.user.id_str) } const exceed = current >= max const warningIcon = exceed ? '\u26a0\ufe0f' : '' return ( <RBAccordion summary={`${warningIcon} ${i18n.getMessage('block_counter')}: [${current} / ${max}]`} warning={exceed} > <M.Box display="flex" flexDirection="row"> <M.Box flexGrow="1"> <T component="div" variant="body2"> {i18n.getMessage('wtf_twitter')} </T> </M.Box> <M.Button type="button" variant="outlined" onClick={handleResetButtonClick} disabled={current <= 0} > Reset </M.Button> </M.Box> </RBAccordion> ) } // AudioSpace에는 요것만 있음. 이걸로도 TwitterUserProfile을 사용하는 데 지장이 없으니까. interface UserWithOnlyNameAndProfileImages { name: string screen_name: string profile_image_url_https: string } export function TwitterUserProfile({ user, children, }: { user: TwitterUser | UserWithOnlyNameAndProfileImages children?: React.ReactNode }) { const biggerProfileImageUrl = user.profile_image_url_https.replace('_normal', '_bigger') return ( <div className="target-user-info"> <div className="profile-image-area"> <img alt={i18n.getMessage('profile_image')} className="profile-image" src={biggerProfileImageUrl} /> </div> <div className="profile-right-area"> <div className="profile-right-info"> <div className="nickname" title={user.name}> {user.name} </div> <div className="username"> <a target="_blank" rel="noopener noreferrer" href={`https://twitter.com/${user.screen_name}`} title={i18n.getMessage('go_to_url', `https://twitter.com/${user.screen_name}`)} > @{user.screen_name} </a> </div> </div> <div style={{ margin: '5px 0' }}>{children}</div> </div> </div> ) } const BigBaseButton = MaterialUI.withStyles(theme => ({ root: { width: '100%', padding: theme.spacing(1), fontSize: 'larger', }, }))(MaterialUI.Button) export function BigExecuteButton({ purpose, disabled, type = 'button', onClick, }: { purpose: Purpose disabled: boolean type?: 'button' | 'submit' onClick?(event: React.MouseEvent): void }): JSX.Element { const label = i18n.getMessage('run_xxx', i18n.getMessage(purpose.type)) let BigButton: typeof BigBaseButton switch (purpose.type) { case 'chainblock': case 'chainmute': case 'lockpicker': case 'chainunfollow': BigButton = BigRedButton break case 'unchainblock': case 'unchainmute': BigButton = BigGreenButton break case 'export': BigButton = BigGrayButton break } const startIcon = purposeTypeToIcon(purpose.type) return <BigButton {...{ type, startIcon, disabled, onClick }}>{label}</BigButton> } const BigRedButton = MaterialUI.withStyles(theme => ({ root: { backgroundColor: MaterialUI.colors.red[700], color: theme.palette.getContrastText(MaterialUI.colors.red[700]), '&:hover': { backgroundColor: MaterialUI.colors.red[500], color: theme.palette.getContrastText(MaterialUI.colors.red[500]), }, }, }))(BigBaseButton) const BigGreenButton = MaterialUI.withStyles(theme => ({ root: { backgroundColor: MaterialUI.colors.green[700], color: theme.palette.getContrastText(MaterialUI.colors.green[700]), '&:hover': { backgroundColor: MaterialUI.colors.green[500], color: theme.palette.getContrastText(MaterialUI.colors.green[500]), }, }, }))(BigBaseButton) const BigGrayButton = MaterialUI.withStyles(theme => ({ root: { backgroundColor: MaterialUI.colors.blueGrey[700], color: theme.palette.getContrastText(MaterialUI.colors.blueGrey[700]), '&:hover': { backgroundColor: MaterialUI.colors.blueGrey[500], color: theme.palette.getContrastText(MaterialUI.colors.blueGrey[500]), }, }, }))(BigBaseButton) const PurposeTab = MaterialUI.withStyles(theme => ({ root: { lineHeight: 1.5, paddingLeft: theme.spacing(1), paddingRight: theme.spacing(1), '@media (min-width: 600px)': { minWidth: 'initial', }, }, }))(MaterialUI.Tab) export function LinearProgressWithLabel({ value }: { value: number }) { return ( <M.Box display="flex" alignItems="center"> <M.Box width="100%" mr={1}> <M.LinearProgress variant="determinate" value={value} /> </M.Box> <M.Box minWidth={35}> <T variant="body2" color="textSecondary">{`${Math.round(value)}%`}</T> </M.Box> </M.Box> ) } export function PurposeSelectionUI({ purpose, changePurposeType, mutatePurposeOptions, availablePurposeTypes, }: { purpose: SessionRequest<AnySessionTarget>['purpose'] changePurposeType(purposeType: SessionRequest<AnySessionTarget>['purpose']['type']): void mutatePurposeOptions( partialOptions: Partial<Omit<SessionRequest<AnySessionTarget>['purpose'], 'type'>> ): void availablePurposeTypes: SessionRequest<AnySessionTarget>['purpose']['type'][] }) { const chainblockable = availablePurposeTypes.includes('chainblock') const unchainblockable = availablePurposeTypes.includes('unchainblock') const exportable = availablePurposeTypes.includes('export') const lockpickable = availablePurposeTypes.includes('lockpicker') const chainunfollowable = availablePurposeTypes.includes('chainunfollow') const chainmutable = availablePurposeTypes.includes('chainmute') const unchainmutable = availablePurposeTypes.includes('unchainmute') //const narrow = MaterialUI.useMediaQuery('(max-width:500px)') return ( <div style={{ width: '100%' }}> <M.Tabs style={{ display: availablePurposeTypes.length >= 2 ? 'flex' : 'none' }} variant="fullWidth" scrollButtons="auto" value={purpose.type} onChange={(_ev, val) => changePurposeType(val)} > {chainblockable && ( <PurposeTab value="chainblock" icon={purposeTypeToIcon('chainblock')} label={i18n.getMessage('chainblock')} /> )} {unchainblockable && ( <PurposeTab value="unchainblock" icon={purposeTypeToIcon('unchainblock')} label={i18n.getMessage('unchainblock')} /> )} {lockpickable && ( <PurposeTab value="lockpicker" icon={purposeTypeToIcon('lockpicker')} label={i18n.getMessage('lockpicker')} /> )} {chainunfollowable && ( <PurposeTab value="chainunfollow" icon={purposeTypeToIcon('chainunfollow')} label={i18n.getMessage('chainunfollow')} /> )} {chainmutable && ( <PurposeTab value="chainmute" icon={purposeTypeToIcon('chainmute')} label={i18n.getMessage('chainmute')} /> )} {unchainmutable && ( <PurposeTab value="unchainmute" icon={purposeTypeToIcon('unchainmute')} label={i18n.getMessage('unchainmute')} /> )} {exportable && ( <PurposeTab value="export" icon={purposeTypeToIcon('export')} label={i18n.getMessage('export')} /> )} </M.Tabs> {availablePurposeTypes.length >= 2 && <M.Divider />} {chainblockable && ( <TabPanel value={purpose.type} index="chainblock"> {purpose.type === 'chainblock' && ( <ChainBlockPurposeUI {...{ purpose, mutatePurposeOptions }} /> )} <ExtraSessionOptionsUI showBioBlock={true} showRecurring={true} /> <M.Divider /> <div className="description"> {i18n.getMessage('chainblock_description')}{' '} {i18n.getMessage('my_mutual_followers_wont_block_or_mute')} <div className="wtf">{i18n.getMessage('wtf_twitter') /* massive block warning */}</div> </div> </TabPanel> )} {unchainblockable && ( <TabPanel value={purpose.type} index="unchainblock"> {purpose.type === 'unchainblock' && ( <UnChainBlockOptionsUI {...{ purpose, mutatePurposeOptions }} /> )} <ExtraSessionOptionsUI showRecurring={true} /> <M.Divider /> <div className="description">{i18n.getMessage('unchainblock_description')}</div> </TabPanel> )} {lockpickable && ( <TabPanel value={purpose.type} index="lockpicker"> {purpose.type === 'lockpicker' && ( <LockPickerOptionsUI {...{ purpose, mutatePurposeOptions }} /> )} <ExtraSessionOptionsUI showRecurring={true} /> <div className="description">{i18n.getMessage('lockpicker_description')}</div> </TabPanel> )} {chainunfollowable && ( <TabPanel value={purpose.type} index="chainunfollow"> <ExtraSessionOptionsUI showRecurring={true} /> <div className="description">{i18n.getMessage('chainunfollow_description')}</div> </TabPanel> )} {chainmutable && ( <TabPanel value={purpose.type} index="chainmute"> {purpose.type === 'chainmute' && ( <ChainMutePurposeUI {...{ purpose, mutatePurposeOptions }} /> )} <ExtraSessionOptionsUI showBioBlock={true} showRecurring={true} /> <M.Divider /> <div className="description"> {i18n.getMessage('chainmute_description')}{' '} {i18n.getMessage('my_mutual_followers_wont_block_or_mute')} </div> </TabPanel> )} {unchainmutable && ( <TabPanel value={purpose.type} index="unchainmute"> {purpose.type === 'unchainmute' && ( <UnChainMuteOptionsUI {...{ purpose, mutatePurposeOptions }} /> )} <ExtraSessionOptionsUI showRecurring={true} /> <div className="description">{i18n.getMessage('unchainmute_description')}</div> </TabPanel> )} {exportable && ( <TabPanel value={purpose.type} index="export"> <div className="description">{i18n.getMessage('export_description')}</div> </TabPanel> )} </div> ) } function ExtraSessionOptionsUI({ showBioBlock, showRecurring, }: { showBioBlock?: boolean showRecurring?: boolean }) { const { extraSessionOptions, mutate } = React.useContext(ExtraSessionOptionsContext) const options = React.useContext(RedBlockOptionsContext) const { openDialog } = React.useContext(UIContext) const bioBlockModes: { [label: string]: BioBlockMode } = { [i18n.getMessage('bioblock_never')]: 'never', [i18n.getMessage('bioblock_all')]: 'all', // [i18n.getMessage('bioblock_smart')]: 'smart', } function showRecurringHelp() { openDialog({ message: { title: i18n.getMessage('recurring_session'), contentLines: [i18n.getMessage('recurring_session_description')], }, dialogType: 'alert', callbackOnOk() {}, }) } const revealBioBlockMode = options.revealBioBlockMode && showBioBlock return ( <React.Fragment> {revealBioBlockMode && ( <RadioOptionItem legend="BioBlock &#7517;" options={bioBlockModes} selectedValue={extraSessionOptions.bioBlock} onChange={(bioBlock: BioBlockMode) => mutate({ bioBlock })} /> )} {showRecurring && ( <div style={{ width: '100%' }}> <CheckboxItem label={i18n.getMessage('recurring_session')} onChange={recurring => mutate({ recurring })} checked={extraSessionOptions.recurring} style={{ marginRight: '8px' }} /> <M.IconButton size="small" onClick={showRecurringHelp}> <M.Icon>help_outline</M.Icon> </M.IconButton> </div> )} </React.Fragment> ) } function ChainBlockPurposeUI({ purpose, mutatePurposeOptions, }: { purpose: ChainBlockPurpose mutatePurposeOptions(partialOptions: Partial<Omit<ChainBlockPurpose, 'type'>>): void }) { const userActions = { [i18n.getMessage('skip')]: 'Skip', [i18n.getMessage('do_mute')]: 'Mute', [i18n.getMessage('do_block')]: 'Block', } as const const userActionsToMyFollowers: { [label: string]: ChainBlockPurpose['myFollowers'] } = { ...userActions, [i18n.getMessage('block_and_unblock')]: 'BlockAndUnBlock', } const userActionsToMyFollowings: { [label: string]: ChainBlockPurpose['myFollowings'] } = { ...userActions, [i18n.getMessage('unfollow')]: 'UnFollow', } return ( <React.Fragment> <RadioOptionItem legend={i18n.getMessage('my_followers')} options={userActionsToMyFollowers} selectedValue={purpose.myFollowers} onChange={(myFollowers: ChainBlockPurpose['myFollowers']) => mutatePurposeOptions({ myFollowers }) } /> <RadioOptionItem legend={i18n.getMessage('my_followings')} options={userActionsToMyFollowings} selectedValue={purpose.myFollowings} onChange={(myFollowings: ChainBlockPurpose['myFollowings']) => mutatePurposeOptions({ myFollowings }) } /> </React.Fragment> ) } function UnChainBlockOptionsUI({ purpose, mutatePurposeOptions, }: { purpose: UnChainBlockPurpose mutatePurposeOptions(partialOptions: Partial<Omit<UnChainBlockPurpose, 'type'>>): void }) { const userActions: { [label: string]: UnChainBlockPurpose['mutualBlocked'] } = { [i18n.getMessage('skip')]: 'Skip', [i18n.getMessage('do_unblock')]: 'UnBlock', } return ( <React.Fragment> <RadioOptionItem legend={i18n.getMessage('mutually_blocked')} options={userActions} selectedValue={purpose.mutualBlocked} onChange={(mutualBlocked: UnChainBlockPurpose['mutualBlocked']) => mutatePurposeOptions({ mutualBlocked }) } /> </React.Fragment> ) } function LockPickerOptionsUI({ purpose, mutatePurposeOptions, }: { purpose: LockPickerPurpose mutatePurposeOptions(partialOptions: Partial<Omit<LockPickerPurpose, 'type'>>): void }) { const userActions: { [label: string]: LockPickerPurpose['protectedFollowers'] } = { [i18n.getMessage('do_block')]: 'Block', [i18n.getMessage('block_and_unblock')]: 'BlockAndUnBlock', } return ( <React.Fragment> <RadioOptionItem legend={i18n.getMessage('protected_follower')} options={userActions} selectedValue={purpose.protectedFollowers} onChange={(protectedFollowers: LockPickerPurpose['protectedFollowers']) => mutatePurposeOptions({ protectedFollowers }) } /> </React.Fragment> ) } function ChainMutePurposeUI({ purpose, mutatePurposeOptions, }: { purpose: ChainMutePurpose mutatePurposeOptions(partialOptions: Partial<Omit<ChainMutePurpose, 'type'>>): void }) { const userActions = { [i18n.getMessage('skip')]: 'Skip', [i18n.getMessage('do_mute')]: 'Mute', } as const return ( <React.Fragment> <RadioOptionItem legend={i18n.getMessage('my_followers')} options={userActions} selectedValue={purpose.myFollowers} onChange={(myFollowers: ChainMutePurpose['myFollowers']) => mutatePurposeOptions({ myFollowers }) } /> <RadioOptionItem legend={i18n.getMessage('my_followings')} options={userActions} selectedValue={purpose.myFollowings} onChange={(myFollowings: ChainMutePurpose['myFollowings']) => mutatePurposeOptions({ myFollowings }) } /> </React.Fragment> ) } function UnChainMuteOptionsUI({ purpose, mutatePurposeOptions, }: { purpose: UnChainMutePurpose mutatePurposeOptions(partialOptions: Partial<Omit<UnChainMutePurpose, 'type'>>): void }) { const userActions: { [label: string]: UnChainMutePurpose['mutedAndAlsoBlocked'] } = { [i18n.getMessage('skip')]: 'Skip', [i18n.getMessage('unmute')]: 'UnMute', } return ( <React.Fragment> <RadioOptionItem legend={i18n.getMessage('muted_and_also_blocked')} options={userActions} selectedValue={purpose.mutedAndAlsoBlocked} onChange={(mutedAndAlsoBlocked: UnChainMutePurpose['mutedAndAlsoBlocked']) => mutatePurposeOptions({ mutedAndAlsoBlocked }) } /> </React.Fragment> ) } export function RequestCheckResultUI({ maybeRequest, }: { maybeRequest: Either<TargetCheckResult, SessionRequest<AnySessionTarget>> }) { return ( <div hidden={maybeRequest.ok}> {!maybeRequest.ok && ( <M.Paper square> <T component="div"> <M.Box px={2} py={1} mb={1} color="warning.main"> {checkResultToString(maybeRequest.error)} </M.Box> </T> </M.Paper> )} </div> ) }
the_stack
////////////////////////////////////////////////// // utils.js const audioBuffer = new AudioBuffer({ length: 1, sampleRate: 44100, }); const audioFrame = new AudioFrame({ timestamp: 100, buffer: audioBuffer, }); declare const imageBitmap: ImageBitmap; function genericCodec(codec: AudioDecoder | AudioEncoder | VideoDecoder | VideoEncoder) { const state: CodecState = codec.state; // $ExpectType void codec.reset(); // $ExpectType void codec.close(); } function errorCallback(error: DOMException): void {} ////////////////////////////////////////////////// // audio-decoder.any.js new EncodedAudioChunk({ type: "key", timestamp: 0, data: Uint8Array.of(0), }); const fullAudioDecoderConfig: AudioDecoderConfig = { codec: "opus", sampleRate: 48000, numberOfChannels: 2, description: Uint8Array.of(0), }; // description is optional const audioDecoderConfig: AudioDecoderConfig = { codec: "opus", sampleRate: 48000, numberOfChannels: 2, }; // $ExpectError AudioDecoder.isConfigSupported(); // $ExpectError AudioDecoder.isConfigSupported({ sampleRate: 48000, numberOfChannels: 2, }); // $ExpectError AudioDecoder.isConfigSupported({ codec: "opus", numberOfChannels: 2, }); // $ExpectError AudioDecoder.isConfigSupported({ codec: "opus", sampleRate: 48000, }); AudioDecoder.isConfigSupported(audioDecoderConfig).then((result: AudioDecoderSupport) => { // $ExpectType boolean result.supported; // $ExpectType AudioDecoderConfig result.config; }); function audioOutput(output: AudioFrame): void { // $ExpectType AudioBuffer output.buffer; } // $ExpectError new AudioDecoder({}); // $ExpectError new AudioDecoder({ output: audioOutput, }); // $ExpectError new AudioDecoder({ error: errorCallback, }); const audioDecoder = new AudioDecoder({ output: audioOutput, error: errorCallback, }); // $ExpectError audioDecoder.configure(); // $ExpectError audioDecoder.configure({ sampleRate: 48000, numberOfChannels: 2, }); // $ExpectType void audioDecoder.configure(audioDecoderConfig); // additional properties are allowed const futureAudioDecoderConfig = { codec: "opus", sampleRate: 48000, numberOfChannels: 2, futureConfigFeature: "foo", }; // $ExpectType Promise<AudioDecoderSupport> AudioDecoder.isConfigSupported(futureAudioDecoderConfig); // $ExpectType void audioDecoder.configure(futureAudioDecoderConfig); genericCodec(audioDecoder); ////////////////////////////////////////////////// // audio-encoder-config.any.js const fullAudioEncoderConfig: AudioEncoderConfig = { codec: "opus", sampleRate: 48000, numberOfChannels: 2, bitrate: 128000, }; // bitrate is optional const audioEncoderConfig: AudioEncoderConfig = { codec: "opus", sampleRate: 48000, numberOfChannels: 2, }; // $ExpectError AudioEncoder.isConfigSupported(); // $ExpectError AudioEncoder.isConfigSupported({ sampleRate: 48000, numberOfChannels: 2, }); // $ExpectError AudioEncoder.isConfigSupported({ codec: "opus", numberOfChannels: 2, }); // $ExpectError AudioEncoder.isConfigSupported({ codec: "opus", sampleRate: 48000, }); AudioEncoder.isConfigSupported(audioEncoderConfig).then((result: AudioEncoderSupport) => { // $ExpectType boolean result.supported; // $ExpectType AudioEncoderConfig result.config; }); // additional properties are allowed const futureAudioEncoderConfig = { codec: "opus", sampleRate: 48000, numberOfChannels: 2, futureConfigFeature: "foo", }; // $ExpectType Promise<AudioEncoderSupport> AudioEncoder.isConfigSupported(futureAudioEncoderConfig); ////////////////////////////////////////////////// // audio-encoder.any.js function encodedAudioOutput(output: EncodedAudioChunk, metadata: EncodedAudioChunkMetadata): void { if (metadata.decoderConfig !== undefined) { audioDecoder.configure(metadata.decoderConfig); } audioDecoder.decode(output); } // $ExpectError new AudioEncoder(); // $ExpectError new AudioEncoder({ output: encodedAudioOutput, }); // $ExpectError new AudioEncoder({ error: errorCallback, }); const audioEncoder = new AudioEncoder({ output: encodedAudioOutput, error: errorCallback, }); // $ExpectType void audioEncoder.configure(audioEncoderConfig); // $ExpectType void audioEncoder.configure(futureAudioEncoderConfig); // $ExpectType void audioEncoder.encode(audioFrame); // $ExpectType void audioFrame.close(); // $ExpectType Promise<void> audioEncoder.flush(); // $ExpectType Promise<void> audioDecoder.flush(); genericCodec(audioEncoder); ////////////////////////////////////////////////// // audio-frame.any.js // $ExpectType number audioFrame.timestamp; // $ExpectError new AudioFrame({buffer: audioBuffer}); // $ExpectError new AudioFrame({timestamp: 100}); // $ExpectType AudioFrame new AudioFrame({buffer: audioBuffer, timestamp: 100}); // $ExpectType AudioFrame audioFrame.clone(); ////////////////////////////////////////////////// // image-decoder-utils.js const imageDecoderInit: ImageDecoderInit = { data: new Uint8Array(0), type: "image/jpeg" }; // $ExpectError new ImageDecoder(); // $ExpectError new ImageDecoder({ data: new Uint8Array(0) }); // $ExpectError new ImageDecoder({ type: "image/jpeg" }); const imageDecoder = new ImageDecoder(imageDecoderInit); declare const context2d: OffscreenCanvasRenderingContext2D; imageDecoder.decode().then((result: ImageDecodeResult) => { const imageDecodeImage: VideoFrame = result.image; // $ExpectType number imageDecodeImage.displayWidth; // $ExpectType number imageDecodeImage.displayHeight; // $ExpectType string | null imageDecodeImage.format; context2d.drawImage(imageDecodeImage, 0, 0); }); ////////////////////////////////////////////////// // image-decoder.any.js // $ExpectType ImageDecoder new ImageDecoder({ data: new ArrayBuffer(0), type: "image/jpeg", preferAnimation: true }); // $ExpectType Promise<ImageDecodeResult> imageDecoder.decode({ frameIndex: 1 }); // $ExpectType Promise<ImageDecodeResult> imageDecoder.decode({ completeFramesOnly: false }); // $ExpectType ImageDecoder new ImageDecoder({ data: new ReadableStream(), type: "image/jpeg" }); const imageDecoderTracks: ImageTrackList = imageDecoder.tracks; // $ExpectType number imageDecoderTracks.length; // $ExpectType Promise<void> imageDecoderTracks.ready; // $ExpectType number imageDecoderTracks.selectedIndex; if (imageDecoderTracks.selectedTrack !== null) { // $ExpectType boolean imageDecoderTracks.selectedTrack.selected; // $ExpectType boolean imageDecoderTracks.selectedTrack.animated; // $ExpectType number imageDecoderTracks.selectedTrack.frameCount; // $ExpectType number imageDecoderTracks.selectedTrack.repetitionCount; } // $ExpectType ImageTrack imageDecoderTracks[0]; imageDecoderTracks[0].selected = true; // $ExpectType void imageDecoder.reset(); // $ExpectType void imageDecoder.close(); // $ExpectType string imageDecoder.type; ////////////////////////////////////////////////// // video-decoder.any.js const encodedVideoChunk = new EncodedVideoChunk({ type: "key", timestamp: 0, data: Uint8Array.of(0), }); const fullVideoDecoderConfig: VideoDecoderConfig = { codec: "avc1.64000c", description: new Uint8Array(0), codedWidth: 1920, codedHeight: 1088, visibleRegion: { left: 0, top: 0, width: 1920, height: 1080 }, displayWidth: 1920, displayHeight: 1080, hardwareAcceleration: "require", }; const videoDecoderConfig: VideoDecoderConfig = { codec: "avc1.64000c", }; // $ExpectError VideoDecoder.isConfigSupported(); // $ExpectError VideoDecoder.isConfigSupported({ description: new Uint8Array(0) }); VideoDecoder.isConfigSupported(videoDecoderConfig).then((result: VideoDecoderSupport) => { // $ExpectType boolean result.supported; // $ExpectType VideoDecoderConfig result.config; }); function videoOutput(output: VideoFrame): void { // $ExpectType number output.visibleRegion.width; // $ExpectType number output.visibleRegion.height; // $ExpectType number | null output.timestamp; // $ExpectType void output.close(); } // $ExpectError new VideoDecoder({}); // $ExpectError new VideoDecoder({ output: videoOutput, }); // $ExpectError new VideoDecoder({ error: errorCallback, }); const videoDecoder = new VideoDecoder({ output: videoOutput, error: errorCallback, }); // $ExpectError videoDecoder.configure(); // $ExpectError videoDecoder.configure({ description: new Uint8Array(0) }); // $ExpectType void videoDecoder.configure(videoDecoderConfig); // additional properties are allowed const futureVideoDecoderConfig = { codec: "avc1.64000c", futureConfigFeature: "foo", }; // $ExpectType Promise<VideoDecoderSupport> VideoDecoder.isConfigSupported(futureVideoDecoderConfig); // $ExpectType void videoDecoder.configure(futureVideoDecoderConfig); genericCodec(videoDecoder); // $ExpectType void videoDecoder.decode(encodedVideoChunk); // $ExpectType Promise<void> videoDecoder.flush(); // $ExpectType number videoDecoder.decodeQueueSize; ////////////////////////////////////////////////// // video-encoder-config.any.js const fullVideoEncoderConfig: VideoEncoderConfig = { codec: "avc1.42001E", hardwareAcceleration: "deny", alpha: "keep", width: 640, height: 480, displayWidth: 640, displayHeight: 480, bitrate: 5000000, framerate: 24, avc: { format: "annexb", }, scalabilityMode: "L3T3", }; // Only codec, width, and height are required. const videoEncoderConfig: VideoEncoderConfig = { codec: "avc1.42001E", width: 640, height: 480, }; // $ExpectError VideoEncoder.isConfigSupported(); // $ExpectError VideoEncoder.isConfigSupported({ width: 640, height: 480, }); // $ExpectError VideoEncoder.isConfigSupported({ codec: "avc1.42001E", height: 480, }); // $ExpectError VideoEncoder.isConfigSupported({ codec: "avc1.42001E", width: 640, }); VideoEncoder.isConfigSupported(videoEncoderConfig).then((result: VideoEncoderSupport) => { // $ExpectType boolean result.supported; // $ExpectType VideoEncoderConfig result.config; }); // additional properties are allowed const futureVideoEncoderConfig = { codec: "avc1.42001E", width: 640, height: 480, futureConfigFeature: "foo", }; // $ExpectType Promise<VideoEncoderSupport> VideoEncoder.isConfigSupported(futureVideoEncoderConfig); ////////////////////////////////////////////////// // video-encoder.any.js const videoFrame = new VideoFrame(imageBitmap, { timestamp: 1000000 }); function encodedVideoOutput(output: EncodedVideoChunk, metadata: EncodedVideoChunkMetadata): void { if (metadata.decoderConfig !== undefined) { videoDecoder.configure(metadata.decoderConfig); } videoDecoder.decode(output); // $ExpectType number output.timestamp; } // $ExpectError new VideoEncoder(); // $ExpectError new VideoEncoder({ output: encodedVideoOutput, }); // $ExpectError new VideoEncoder({ error: errorCallback, }); const videoEncoder = new VideoEncoder({ output: encodedVideoOutput, error: errorCallback, }); // $ExpectError videoEncoder.configure({ width: 640, height: 480, }); // $ExpectType void videoEncoder.configure(videoEncoderConfig); // $ExpectType void videoEncoder.configure(futureVideoEncoderConfig); // $ExpectType number videoEncoder.encodeQueueSize; // $ExpectType void videoEncoder.encode(videoFrame); // $ExpectType Promise<void> videoEncoder.flush(); genericCodec(videoEncoder); ////////////////////////////////////////////////// // video-frame-serialization.any.js const videoFrameClone: VideoFrame = videoFrame.clone(); // $ExpectType void videoFrame.close(); ////////////////////////////////////////////////// // video-frame.any.js // $ExpectType number | null videoFrame.timestamp; // $ExpectType number | null videoFrame.duration; // $ExpectType number videoFrame.visibleRegion.left; // $ExpectType number videoFrame.visibleRegion.top; // $ExpectType number videoFrame.visibleRegion.width; // $ExpectType number videoFrame.visibleRegion.height; // $ExpectType number videoFrame.displayWidth; // $ExpectType number videoFrame.displayHeight; // $ExpectType string | null videoFrame.format; if (videoFrame.planes !== null) { // $ExpectType number videoFrame.planes.length; // $ExpectType number videoFrame.planes[0].stride; // $ExpectType number videoFrame.planes[0].rows; // $ExpectType number videoFrame.planes[0].length; // $ExpectType void videoFrame.planes[0].readInto(new Uint8Array(0)); } // $ExpectError new VideoFrame("ABCD", [], { codedWidth: 4, codedHeight: 2, }); // $ExpectError new VideoFrame("ABCD", [], { timestamp: 1234, codedHeight: 2, }); // $ExpectError new VideoFrame("ABCD", [], { timestamp: 1234, codedWidth: 4, }); const videoFramePlaneInit: VideoFramePlaneInit = { timestamp: 1234, codedWidth: 4, codedHeight: 2, }; new VideoFrame("ABCD", [], videoFramePlaneInit); new VideoFrame("ABCD", [{ src: new Uint8Array(0), stride: 4 }], videoFramePlaneInit); new VideoFrame("ABCD", [], { timestamp: 1234, duration: 4321, codedWidth: 4, codedHeight: 2, visibleRegion: { left: 0, top: 0, width: 4, height: 2 }, displayWidth: 4, displayHeight: 2, }); new VideoFrame(videoFrame); new VideoFrame(videoFrame, { duration: 1234 }); new VideoFrame(videoFrame, { timestamp: 1234, duration: 1234 }); new VideoFrame(videoFrame, { alpha: "keep" }); ////////////////////////////////////////////////// // videoFrame-canvasImageSource.html new VideoFrame(document.createElement("video")); new VideoFrame(document.createElement("img")); new VideoFrame(document.createElementNS("http://www.w3.org/2000/svg", "image")); new VideoFrame(document.createElement("canvas")); ////////////////////////////////////////////////// // videoFrame-createImageBitmap.any.js // $ExpectType Promise<ImageBitmap> createImageBitmap(videoFrame); // $ExpectType Promise<ImageBitmap> createImageBitmap(videoFrame, { colorSpaceConversion: "none" }); // $ExpectType void videoEncoder.encode(videoFrame, { keyFrame: true }); ////////////////////////////////////////////////// // videoFrame-texImage.any.js declare const gl: WebGL2RenderingContext; if (!gl) throw new Error("missing context"); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, videoFrame); gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, videoFrame);
the_stack
import Entry from './entry'; import Event from './event'; import { NodeInterface, NodeModelInterface, EditorInterface, PluginEntry, SchemaInterface, SchemaBlock, RangeInterface, } from '../types'; import { ANCHOR, CARD_ELEMENT_KEY, CARD_KEY, CARD_SELECTOR, CURSOR, DATA_ELEMENT, EDITABLE_SELECTOR, FOCUS, READY_CARD_KEY, READY_CARD_SELECTOR, } from '../constants'; import { getDocument, getStyleMap, isEngine } from '../utils'; import $ from './query'; import getHashId, { uuid } from './hash'; import { isNode, isNodeEntry } from './utils'; class NodeModel implements NodeModelInterface { private editor: EditorInterface; constructor(editor: EditorInterface) { this.editor = editor; } isVoid( node: NodeInterface | Node | string, schema: SchemaInterface = this.editor.schema, ) { let name = typeof node === 'string' ? node : ''; if (isNode(node)) name = node.nodeName.toLowerCase(); else if (isNodeEntry(node)) name = node.name; return ( schema.find((rule) => rule.name === name && rule.isVoid === true) .length > 0 ); } isMark( node: NodeInterface | Node, schema: SchemaInterface = this.editor.schema, ) { if (isNode(node)) node = $(node); return schema.getType(node) === 'mark'; } /** * 是否是inline标签 * @param node 节点 */ isInline( node: NodeInterface | Node, schema: SchemaInterface = this.editor.schema, ) { if (isNode(node)) node = $(node); return schema.getType(node) === 'inline'; } /** * 是否是块级节点 * @param node 节点 */ isBlock( node: NodeInterface | Node, schema: SchemaInterface = this.editor.schema, ) { if (isNode(node)) node = $(node); return schema.getType(node) === 'block'; } /** * 判断block节点的子节点是否不包含blcok 节点 */ isNestedBlock(node: NodeInterface) { if (!this.isBlock(node)) return false; let child = node.first(); while (child) { if (this.isBlock(child)) return false; child = child.next(); } return true; } /** * 判断节点是否是顶级根节点,父级为编辑器根节点,且,子级节点没有block节点 * @param node 节点 * @returns */ isRootBlock(node: NodeInterface, schema?: SchemaInterface) { //父级不是根节点 if (!node.parent()?.isEditable()) return false; if (!this.isNestedBlock(node)) return false; //并且规则上不可以设置子节点 return (schema || this.editor.schema) .find((schema) => schema.name === node.name) .every((schema) => { if (schema.type !== 'block') return false; const allowIn = (schema as SchemaBlock).allowIn; if (!allowIn) return true; return allowIn.indexOf('$root') > -1; }); } /** * 判断节点下的文本是否为空 * @param withTrim 是否 trim */ isEmpty(node: NodeInterface, withTrim?: boolean) { if (node.isElement()) { // 卡片不为空 if ( node.attributes(CARD_KEY) || (node.find(CARD_SELECTOR).length > 0 && node.find(EDITABLE_SELECTOR).length === 0) ) { return false; } // 只读卡片不为空 if ( node.attributes(READY_CARD_KEY) || (node.find(READY_CARD_SELECTOR).length > 0 && node.find(EDITABLE_SELECTOR).length === 0) ) { return false; } // 非br节点的空节点不为空 if (node.name !== 'br' && this.isVoid(node)) { return false; } // 多个br节点不为空 if (node.find('br').length > 1) { return false; } } let value = node.isText() ? node[0].nodeValue || '' : node.text(); value = value?.replace(/\u200B/g, ''); value = value?.replace(/\r\n|\n/, ''); if (value && withTrim) { value = value.trim(); } return value === ''; } /** * 判断一个节点下的文本是否为空,或者只有空白字符 */ isEmptyWithTrim(node: NodeInterface) { return this.isEmpty(node, true); } /** * 判断节点包括子节点是否为空 * @param node 节点 * @returns */ isEmptyWidthChild(node: NodeInterface) { if (node.length === 0) return true; const { childNodes } = node[0]; if (childNodes.length === 0) return true; for (let i = 0; i < childNodes.length; i++) { const child = childNodes[i]; if (child.nodeType === Node.TEXT_NODE) { if (child['data'].replace(/\u200b/g, '') !== '') return false; } else if (child.nodeType === Node.ELEMENT_NODE) { if ( child.nodeName.toLowerCase() === 'li' && !this.editor.list.isEmptyItem($(child)) ) return false; if ((child as Element).hasAttribute(CARD_KEY)) return false; if (!this.isEmptyWidthChild($(child))) { return false; } } } return true; } /** * 判断节点是否为列表节点 * @param node 节点或者节点名称 */ isList(node: NodeInterface | string | Node) { let name = typeof node === 'string' ? node : ''; if (isNode(node)) name = node.nodeName.toLowerCase(); else if (isNodeEntry(node)) name = node.name; return ['ul', 'ol'].indexOf(name) > -1; } /** * 判断节点是否是自定义列表 * @param node 节点 */ isCustomize(node: NodeInterface) { const { list } = this.editor; switch (node.name) { case 'li': return node.hasClass(list.CUSTOMZIE_LI_CLASS); case 'ul': return node.hasClass(list.CUSTOMZIE_UL_CLASS); default: return false; } } /** * 去除包裹 * @param node 需要去除包裹的节点 */ unwrap(node: NodeInterface) { let child = node.first(); const nodes: NodeInterface[] = []; while (child) { const next = child.next(); node.before(child); nodes.push(child); child = next; } node.remove(); return nodes; } /** * 包裹节点 * @param source 需要包裹的节点 * @param outer 包裹的外部节点 * @param mergeSame 合并相同名称的节点样式和属性在同一个节点上 */ wrap( source: NodeInterface | Node, outer: NodeInterface, mergeSame: boolean = false, ) { const { mark } = this.editor; if (isNode(source)) source = $(source); outer = this.clone(outer, false); // 文本节点 if (source.isText()) { outer.append(this.clone(source, false)); return source.replaceWith(outer); } // 包裹样式节点 if (mergeSame && this.isMark(outer)) { //合并属性和样式值 const outerClone = this.clone(outer, false, false); if (source.name === outer.name) { const attributes = source.attributes(); delete attributes.style; Object.keys(attributes).forEach((key) => { if (!outer.attributes(key)) outer.attributes(key, attributes[key]); else { const attributes = outer.attributes(key).split(','); if ( attributes[key] !== undefined && attributes.indexOf(attributes[key]) < 0 ) attributes.push(attributes[key]); outer.attributes(key, attributes.join(',')); } }); const styles = source.css(); Object.keys(styles).forEach((key) => { if (!outer.css(key)) outer.css(key, styles[key]); }); outer.append(this.clone(source, true, false).children()); } else { outer.append(this.clone(source, true, false)); } const children = outer.allChildren(); children.forEach((child) => { if ( !child.isText() && this.isMark(child) && mark.compare(child, outerClone) ) { this.unwrap(child); } }); return source.replaceWith(outer); } // 其它情况 const parent = source.parent(); const shadowNode = this.clone(source, false, false); source.after(shadowNode); outer.append(source); // 没有父级节点就直接返回包裹后的节点 return parent ? shadowNode.replaceWith(outer) : outer; } /** * 合并节点 * @param source 合并的节点 * @param target 需要合并的节点 * @param remove 合并后是否移除 */ merge( source: NodeInterface, target: NodeInterface, remove: boolean = true, ) { //要合并的节点是文本,就直接追加 if (target.isText()) { source.append(target); this.removeSide(source); return; } const { block, mark, list } = this.editor; let mergedNode = target; const toIsList = this.isList(source); const fromIsList = this.isList(target.name); // p 与列表合并时需要做特殊处理 if (toIsList && !fromIsList) { const liBlocks = source.find('li'); //没有li标签 if (liBlocks.length === 0) { return; } //设置被合并节点为最后一个li标签 source = $(liBlocks[liBlocks.length - 1]); } //被合并的节点为列表 if (!toIsList && fromIsList) { //查找li节点 const liBlocks = target.find('li'); if (liBlocks.length > 0) { //设置需要合并的节点为第一个li节点 target = $(liBlocks[0]); } if (liBlocks[1]) { mergedNode = $(liBlocks[0]); } } // 自定义列表合并 if (this.isCustomize(source)) { // 源节点如果还有card节点, let sourceFirst = source.first(); if (!sourceFirst?.isCard()) { // 源节点没有卡片节点就添加 const plugins = list.getPlugins(); const pluginName = list.getPluginNameByNode(source); const plugin = plugins.find( (p) => (p.constructor as PluginEntry).pluginName === pluginName, ); if (plugin?.cardName) { list.addCardToCustomize(source, plugin.cardName); sourceFirst = source.first(); } } // 源节点卡片名称与目标节点卡片一样就删除目标节点的第一个卡片节点 if (this.isCustomize(target)) { const targetFirst = target.first(); if ( targetFirst?.isCard() && sourceFirst!.attributes(CARD_KEY) === targetFirst.attributes(CARD_KEY) ) targetFirst.remove(); } } //被合并的节点最后一个子节点为br,则移除 const toNodeLast = source.last(); let child = target.first(); const plugin = block.findPlugin(source); //循环追加 while (child) { const next = child.next(); const markPlugin = mark.findPlugin(child); if ( plugin && markPlugin && plugin.disableMark && plugin.disableMark!.indexOf( (markPlugin.constructor as PluginEntry).pluginName, ) > -1 ) { const result = this.unwrap(child!); result.forEach((children) => { source.append(children); }); } // 孤立的零宽字符删除 else if (child.isText() && /\u200b/.test(child.text())) { const parent = child.parent(); const prev = child.prev(); const next = child.next(); // 不在mark里面,或者没有父级节点,它的上级节点或者下级节点不是inline if ( !parent || (!this.isMark(parent) && ((prev && !this.isInline(prev)) || (next && !this.isInline(next)))) ) { child.remove(); child = next; continue; } } // 移除mark插件下面的所有零宽字符 else if (markPlugin && child.children().length === 1) { const prev = child.prev(); if (!prev || prev.isText()) { child.allChildren().forEach((child) => { const text = child.text(); if ( child.type === getDocument().TEXT_NODE && !!text && !child.next()?.isCursor() ) { child.text(text.replace(/\u200b/, '')); } }); } } //追加到要合并的列表中 if (child.length > 0 && !child.equal(source)) source.append(child); child = next; } //移除需要合并的节点 if (remove) mergedNode.remove(); if (toNodeLast && toNodeLast.name === 'br') { let next = toNodeLast.next(); while (next) { if ( [CURSOR, ANCHOR, FOCUS].indexOf( next.attributes(DATA_ELEMENT), ) ) { toNodeLast.remove(); break; } next = next.next(); } } this.removeSide(source); } /** * 将源节点的子节点追加到目标节点,并替换源节点 * @param source 旧节点 * @param target 新节点 */ replace( source: NodeInterface, target: NodeInterface, copyId: boolean = false, ) { const clone = this.clone(target, false, copyId); let childNode = this.isCustomize(source) && source.name === 'li' && source.first()?.isCard() ? source.first()?.next() : source.first(); while (childNode) { const nextNode = childNode.next(); clone.append(childNode); childNode = nextNode; } if (source.isText()) { clone.append(source.clone()); } return source.replaceWith(clone); } /** * 光标位置插入文本 * @param text 文本 * @param range 光标 */ insertText(text: string, range?: RangeInterface) { if (!isEngine(this.editor)) return; const { change } = this.editor; const safeRange = range || change.range.toTrusty(); const doc = getDocument(safeRange.startContainer); // 范围为折叠状态时先删除内容 if (!safeRange.collapsed) { change.delete(range); } const node = doc.createTextNode(text); this.insert(node, safeRange)?.handleBr(); if (!range) change.apply(safeRange); return safeRange; } /** * 在光标位置插入一个节点 * @param node 节点 * @param range 光标 * @param removeCurrentEmptyBlock 当前光标行是空行时是否删除 */ insert( node: Node | NodeInterface, range?: RangeInterface, removeCurrentEmptyBlock: boolean = false, ) { if (isNodeEntry(node)) { if (node.length === 0) throw 'Not found node'; node = node[0]; } const editor = this.editor; if (!isEngine(editor)) return; const { change, block, schema, mark } = editor; range = range || change.range.get(); const { startNode, startOffset } = range .cloneRange() .shrinkToTextNode(); const prev = startNode.prev(); const parent = startNode.parent(); let text = startNode.text() || ''; const leftText = text.substr(0, startOffset); //文本节点 if (startNode.isText() && /\u200b$/.test(leftText)) { //零宽字符前面还有其它字符。或者节点前面还有节点,不能是inline节点。或者前面没有节点了,并且父级不是inline节点 if ( text.length > 1 && ((prev && !this.isInline(prev)) || (!prev && parent && !this.isInline(parent))) ) { startNode .get<Text>()! .splitText(text.length - 1) .remove(); } } // 是否在卡片上,卡片还没有渲染 let elementType = parent?.attributes(CARD_ELEMENT_KEY); if (!elementType && startNode.isCard()) { range.setStartAfter(startNode); } // 检测是否位于卡片两边节点 if (elementType && parent && ['left', 'right'].includes(elementType)) { const cardComponent = editor.card.find(parent); if (cardComponent) { if (elementType === 'left') { range.setStartBefore(cardComponent.root); } else { range.setStartAfter(cardComponent.root); } } } if (this.isBlock(node)) { // 如果当前光标位置的block节点是空节点,就不用分割 let { commonAncestorNode } = range; if (commonAncestorNode.isText()) { commonAncestorNode = this.editor.block.closest(commonAncestorNode); } let splitNode = null; if ( this.isBlock(commonAncestorNode) && this.isEmpty(commonAncestorNode) ) { splitNode = removeCurrentEmptyBlock ? commonAncestorNode : undefined; } else { let isFirst = false; if (block.isFirstOffset(range, 'start')) { isFirst = true; } splitNode = block.split(range); if (isFirst) { splitNode = splitNode?.prev(); } } let blockNode = block.closest( range.startNode.isEditable() ? range .cloneRange() .shrinkToElementNode() .shrinkToTextNode().startNode : range.startNode, ); if ( !blockNode.isCard() && schema.isAllowIn(blockNode.name, node.nodeName.toLowerCase()) ) { blockNode.find('br').remove(); blockNode.append(node); } else { let parentBlock = blockNode.parent(); while ( parentBlock && this.isBlock(parentBlock) && !blockNode.isEditable() && !schema.isAllowIn( parentBlock.name, node.nodeName.toLowerCase(), ) ) { blockNode = parentBlock; parentBlock = blockNode.parent(); } if ( blockNode.isEditable() && blockNode.children().length === 0 ) { blockNode.append(node); } else { if ( this.isEmptyWidthChild(blockNode) || block.isLastOffset(range, 'start') ) { blockNode.after(node); // 没有分割就不会有新增的行就不用删除 if (this.isEmptyWidthChild(blockNode) && splitNode) blockNode.remove(); } else { blockNode.before(node); if (splitNode && this.isEmptyWidthChild(splitNode)) splitNode.remove(); } } } } else { const targetNode = block.closest( range.startNode.isEditable() ? range .cloneRange() .shrinkToElementNode() .shrinkToTextNode().startNode : range.startNode, ); const targetPlugin = targetNode ? block.findPlugin(targetNode) : undefined; //先移除不能放入块级节点的mark标签 if (targetPlugin) { const nodeDom = $(node); const isUnwrap = (markNode: NodeInterface) => { if (this.isMark(markNode)) { const markPlugin = mark.findPlugin(markNode); if (!markPlugin) return; if ( targetPlugin.disableMark && targetPlugin.disableMark.indexOf( (markPlugin.constructor as PluginEntry) .pluginName, ) > -1 ) { return true; } } return false; }; nodeDom.allChildren().forEach((markNode) => { if (isUnwrap(markNode)) { this.unwrap(markNode); } }); if (isUnwrap(nodeDom)) { const fragment = nodeDom.document!.createDocumentFragment(); nodeDom.children().each((child) => { fragment.appendChild(child); }); nodeDom.remove(); node = fragment.childNodes[fragment.childNodes.length - 1]; range.insertNode(fragment); } else range.insertNode(node); if (nodeDom.length === 0) return range; } else range.insertNode(node); } if ( node.nodeType === Node.ELEMENT_NODE && ((node as Element).hasAttribute(READY_CARD_KEY) || (node as Element).hasAttribute(CARD_KEY)) ) { return range.collapse(false); } return range .select( node, this.isVoid(node) || node.nodeType === Node.TEXT_NODE ? false : true, ) .shrinkToElementNode() .collapse(false); } /** * 设置节点属性 * @param node 节点 * @param props 属性 */ setAttributes(node: NodeInterface, attrs: any) { let style = attrs.style; Object.keys(attrs).forEach((key) => { if (key === 'style') return; if (key === 'className') { const value = attrs[key]; if (Array.isArray(value)) { value.forEach((name) => node.addClass(name)); } else node.addClass(value); } else node.attributes(key, attrs[key].toString()); }); if (typeof style === 'number') style = {}; else if (typeof style === 'string') style = getStyleMap(style); style = style || {}; const keys = Object.keys(style); keys.forEach((key) => { let val = (<{ [k: string]: string | number }>style)[key]; if (/^0(px|em)?$/.test(val.toString())) { val = ''; } node.css(key, val.toString()); }); if (keys.length === 0 || Object.keys(node.css()).length === 0) { node.removeAttributes('style'); } return node; } /** * 移除值为负的样式 * @param node 节点 * @param style 样式名称 */ removeMinusStyle(node: NodeInterface, style: string) { if (node.isElement()) { const styles = node.css(); if (styles[style]) { const val = parseInt(styles[style] || '0', 10) || 0; if (val < 0) node.css(style, ''); } } } /** * 合并节点下的子节点,两个相同的相邻节点的子节点 * @param node 当前节点 */ mergeChild(node: NodeInterface) { const { schema, list } = this.editor; const topTags = schema.getAllowInTags(); //获取第一个子节点 let childDom: NodeInterface | null = node.first(); //遍历全部子节点 while (childDom) { //获取下一个子节点 let nextNode = childDom.next(); while ( //如果下一个子节点不为空,并且与上一个子节点名称一样 nextNode && childDom.name === nextNode.name && //并且上一个节点是可拥有block子节点的节点 或者是 ul、li 并且list列表类型是一致的 ((topTags.indexOf(childDom.name) > -1 && !this.isList(childDom)) || (this.isList(childDom) && list.isSame(childDom, nextNode))) ) { //获取下一个节点的下一个节点 const nNextNode = nextNode.next(); //合并下一个节点 let nextChildNode = nextNode.first(); //循环要合并节点的子节点 while (nextChildNode) { const next = nextChildNode.next(); childDom.append(nextChildNode); nextChildNode = next; } nextNode.remove(); //继续合并当前子节点的子节点 this.mergeChild(childDom); nextNode = nNextNode; } childDom = nextNode; } } /** * 删除节点两边标签 * @param node 节点 * @param tagName 标签名称,默认为br标签 */ removeSide(node: NodeInterface, tagName: string = 'br') { // 删除第一个 BR const firstNode = node.first(); if ( firstNode?.name === tagName && node .children() .toArray() .filter((node) => !node.isCursor()).length > 1 ) { firstNode.remove(); } // 删除最后一个 BR const lastNode = node.last(); if ( lastNode?.name === tagName && node .children() .toArray() .filter((node) => !node.isCursor()).length > 1 ) { lastNode.remove(); } } /** * 扁平化节点 * @param node 节点 * @param root 根节点 */ flat(node: NodeInterface, root: NodeInterface = node) { const { block } = this.editor; //第一个子节点 let childNode = node.first(); const rootElement = root.fragment ? root.fragment : root.get(); const tempNode = node.fragment ? $('<p />') : this.clone(node, false); while (childNode) { //获取下一个兄弟节点 let nextNode = childNode.next(); //如果当前子节点是块级的Card组件,或者是简单的block if (childNode.isBlockCard() || this.isNestedBlock(childNode)) { block.flat(childNode, $(rootElement || [])); } //如果当前是块级标签,递归循环 else if (this.isBlock(childNode)) { childNode = this.flat(childNode, $(rootElement || [])); } else { const cloneNode = this.clone(tempNode, false); const isLI = 'li' === cloneNode.name; childNode.before(cloneNode); while (childNode) { nextNode = childNode.next(); const isBR = 'br' === childNode.name && !isLI; if (isBR && childNode.parent()?.isRoot()) { cloneNode.append(childNode); } //判断当前节点末尾是否是换行符,有换行符就跳出 if (childNode.isText()) { let text = childNode.text(); //先移除开头的换行符 let match = /^((\n|\r)+)/.exec(text); let isBegin = false; if (match) { text = text.substring(match[1].length); isBegin = true; if (text.length === 0) { childNode.remove(); } } //移除末尾换行符 match = /((\n|\r)+)$/.exec(text); if (match) { childNode.text(text.substr(0, match.index)); cloneNode.append(childNode); break; } else if (isBegin && childNode.length > 0) { childNode.text(text); } } if (childNode.length > 0) cloneNode.append(childNode); //判断下一个节点的开头是换行符,有换行符就跳出 if (nextNode?.isText()) { const text = nextNode.text(); let match = /^(\n|\r)+/.exec(text); if (match) { break; } } if ( isBR || !nextNode || this.isBlock(nextNode) || nextNode.isBlockCard() ) break; childNode = nextNode; } this.removeSide(cloneNode); block.flat(cloneNode, $(rootElement || [])); const children = cloneNode.children().toArray(); if ( cloneNode.name === 'p' && children.filter((node) => !node.isCursor()).length === 0 ) { cloneNode.append($('<br />')); } if ( this.isBlock(cloneNode) && this.isEmptyWithTrim(cloneNode) ) { cloneNode.html('<br />'); } } const children = childNode.children().toArray(); if ( childNode.name === 'p' && children.filter((node) => !node.isCursor()).length === 0 ) { childNode.append($('<br />')); } if (this.isBlock(childNode) && this.isEmptyWithTrim(childNode)) { childNode.html('<br />'); } this.removeSide(childNode); childNode = nextNode; } // 重新更新框架的引用 if (node.fragment) { node = $(node.fragment); } //如果没有子节点了,就移除当前这个节点 childNode = node.first(); if (!childNode) node.remove(); return node; } /** * 标准化节点 * @param node 节点 */ normalize(node: NodeInterface) { node = this.flat(node); this.mergeChild(node); return node; } /** * 获取或设置元素节点html文本 * @param {string|undefined} val html文本 * @return {NodeEntry|string} 当前实例或html文本 */ html(node: NodeInterface): string; html(node: NodeInterface, val: string): NodeInterface; html(node: NodeInterface, val?: string): NodeInterface | string { if (val === undefined) { return node.length > 0 ? node.get<HTMLElement>()?.innerHTML || '' : ''; } node.each((node) => { const element = <Element>node; element.innerHTML = val; this.editor.nodeId.generateAll(element); }); return node; } /** * 复制元素节点 * @param {boolean} deep 是否深度复制 * @return 复制后的元素节点 */ clone( node: NodeInterface, deep?: boolean, copyId: boolean = true, ): NodeInterface { const { nodeId } = this.editor; const nodes: Array<Node> = []; node.each((node) => { const cloneNode = node.cloneNode(deep); const nodeDom = $(cloneNode); if (!copyId) { nodeId.generateAll(nodeDom, true); if (nodeId.isNeed(nodeDom)) { nodeId.generate(nodeDom, true); } } nodes.push(cloneNode); }); return $(nodes); } /** * 获取批量追加子节点后的outerHTML * @param nodes 节点集合 * @param selector 追加的节点 */ getBatchAppendHTML(nodes: Array<NodeInterface>, selector: string) { if (nodes.length === 0) return selector; let appendNode = selector.startsWith('\\u') || selector.startsWith('&#') ? $(selector, null) : $(selector); nodes.forEach((node) => { node = node.clone(false); node.append(appendNode); appendNode = node; }); return appendNode.get<Element>()?.outerHTML || ''; } removeZeroWidthSpace(node: NodeInterface) { node.traverse((child) => { const node = child[0]; if (node.nodeType !== Node.TEXT_NODE) { return; } const text = node.nodeValue; if (text?.length !== 2) { return; } const next = node.nextSibling; const prev = node.previousSibling; if ( text.charCodeAt(1) === 0x200b && next && next.nodeType === Node.ELEMENT_NODE && [ANCHOR, FOCUS, CURSOR].indexOf( (<Element>next).getAttribute(DATA_ELEMENT) || '', ) >= 0 ) { return; } const parent = child.parent(); if ( text.charCodeAt(1) === 0x200b && ((!next && parent && this.isInline(parent)) || (next && this.isInline(next))) ) { return; } if ( text.charCodeAt(0) === 0x200b && ((!prev && parent && this.isInline(parent)) || (prev && this.isInline(prev))) ) { return; } if (text.charCodeAt(0) === 0x200b) { const newNode = (<Text>node).splitText(1); if (newNode.previousSibling) newNode.parentNode?.removeChild(newNode.previousSibling); } }); } } export default NodeModel; export { Entry as NodeEntry, Event, $, getHashId, uuid };
the_stack
import { Colors } from '../constants/Colors'; import { Icons } from '../icons/Icons'; import { MouseComboBit, mouseCombo } from '../utils/mouseCombo'; import { Resolution } from '../utils/Resolution'; import { TimeValueRange, dt2dx, dx2dt, dy2dv, snapTime, snapValue, t2x, v2y } from '../utils/TimeValueRange'; import { genID } from '@0b5vr/automaton-with-gui/src/utils/genID'; import { jsonCopy } from '@0b5vr/automaton-with-gui/src/utils/jsonCopy'; import { objectMapHas } from '../utils/objectMap'; import { registerMouseEvent } from '../utils/registerMouseEvent'; import { useDispatch, useSelector } from '../states/store'; import { useDoubleClick } from '../utils/useDoubleClick'; import { useID } from '../utils/useID'; import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; import type { StateChannelItem } from '../../types/StateChannelItem'; // == styles ======================================================================================= const CurvePath = styled.polyline` fill: none; stroke: ${ Colors.fore }; stroke-width: 2px; stroke-linecap: round; stroke-linejoin: round; overflow: hidden; `; const ResetIcon = styled( Icons.Power )` position: absolute; fill: ${ Colors.foresub }; `; const Side = styled.rect` opacity: 0.0; cursor: ew-resize; pointer-events: auto; `; const VerticalSide = styled.rect` opacity: 0.0; cursor: ns-resize; pointer-events: auto; `; const Body = styled.rect<{ isSelected: boolean }>` fill: ${ ( { isSelected } ) => ( isSelected ? Colors.accentdark : Colors.black ) }; opacity: 0.5; rx: 4px; ry: 4px; cursor: pointer; pointer-events: auto; `; const Stroke = styled.rect` fill: none; stroke: ${ Colors.accent }; stroke-width: 2px; rx: 4px; ry: 4px; `; const Root = styled.g` pointer-events: none; `; // == props ======================================================================================== export interface TimelineItemCurveProps { channel: string; item: StateChannelItem; range: TimeValueRange; size: Resolution; grabBody: () => void; grabBodyCtrl: () => void; removeItem: () => void; dopeSheetMode?: boolean; } // == component ==================================================================================== const TimelineItemCurve = ( props: TimelineItemCurveProps ): JSX.Element => { const { item, range, size, grabBody, grabBodyCtrl, removeItem, dopeSheetMode } = props; const channelName = props.channel; const dispatch = useDispatch(); const checkDoubleClick = useDoubleClick(); const curveClipID = 'curveClip' + useID(); const { automaton, selectedItems, curves, guiSettings } = useSelector( ( state ) => ( { automaton: state.automaton.instance, selectedItems: state.timeline.selected.items, curves: state.automaton.curves, guiSettings: state.automaton.guiSettings } ) ); const curve = curves[ item.curveId! ]; const { path, length: curveLength } = curve; const x = useMemo( () => t2x( item.time, range, size.width ), [ item, range, size ] ); const y0 = useMemo( () => dopeSheetMode ? size.height : v2y( item.value, range, size.height ), [ dopeSheetMode, item, range, size ] ); const w = useMemo( () => dt2dx( item.length, range, size.width ), [ item, range, size ] ); const y1 = useMemo( () => dopeSheetMode ? 0.0 : v2y( item.value + item.amp, range, size.height ), [ dopeSheetMode, item, range, size ] ); const y = Math.min( y0, y1 ); const h = Math.abs( y0 - y1 ); const isFlipped = y0 < y1; const curveX = useMemo( () => dt2dx( -item.offset / item.speed, range, size.width ), [ item.offset, item.speed, range, size ] ); const curveWidth = useMemo( () => dt2dx( curveLength / item.speed, range, size.width ), [ item.speed, curveLength, range, size ] ); const isSelected = objectMapHas( selectedItems, item.$id ); const channel = automaton?.getChannel( channelName ); const grabTop = useCallback( (): void => { if ( !channel ) { return; } const valuePrev = item.value + item.amp; let dy = 0.0; let value = valuePrev; let hasMoved = false; registerMouseEvent( ( event, movementSum ) => { hasMoved = true; dy += movementSum.y; const ignoreSnap = event.altKey; value = valuePrev + dy2dv( dy, range, size.height ); if ( !ignoreSnap ) { value = snapValue( value, range, size.height, guiSettings ); } channel.changeCurveAmp( item.$id, value - item.value ); }, () => { if ( !hasMoved ) { return; } channel.changeCurveAmp( item.$id, value - item.value ); dispatch( { type: 'History/Push', description: 'Change Curve Amp', commands: [ { type: 'channel/changeCurveAmp', channel: channelName, item: item.$id, amp: value - item.value, ampPrev: valuePrev - item.value } ], } ); } ); }, [ channel, item, range, size, guiSettings, dispatch, channelName ] ); const grabBottom = useCallback( (): void => { if ( !channel ) { return; } const valuePrev = item.value; const ceil = valuePrev + item.amp; let dy = 0.0; let value = valuePrev; let hasMoved = false; registerMouseEvent( ( event, movementSum ) => { hasMoved = true; dy += movementSum.y; const ignoreSnap = event.altKey; value = valuePrev + dy2dv( dy, range, size.height ); if ( !ignoreSnap ) { value = snapValue( value, range, size.height, guiSettings ); } channel.changeItemValue( item.$id, value ); channel.changeCurveAmp( item.$id, ceil - value ); }, () => { if ( !hasMoved ) { return; } channel.changeItemValue( item.$id, value ); channel.changeCurveAmp( item.$id, ceil - value ); dispatch( { type: 'History/Push', description: 'Change Curve Amp', commands: [ { type: 'channel/changeItemValue', channel: channelName, item: item.$id, value, valuePrev }, { type: 'channel/changeCurveAmp', channel: channelName, item: item.$id, amp: ceil - value, ampPrev: ceil - valuePrev } ], } ); } ); }, [ channel, item, range, size, guiSettings, dispatch, channelName ] ); const grabLeft = useCallback( ( stretch: boolean ): void => { if ( !channel ) { return; } const timePrev = item.time; const timeEnd = item.time + item.length; let dx = 0.0; let time = timePrev; let hasMoved = false; registerMouseEvent( ( event, movementSum ) => { hasMoved = true; dx += movementSum.x; const ignoreSnap = event.altKey; time = timePrev + dx2dt( dx, range, size.width ); if ( !ignoreSnap ) { time = snapTime( time, range, size.width, guiSettings ); } channel.resizeItemByLeft( item.$id, timeEnd - time, stretch ); }, () => { if ( !hasMoved ) { return; } channel.resizeItemByLeft( item.$id, timeEnd - time, stretch ); dispatch( { type: 'History/Push', description: 'Resize Curve', commands: [ { type: 'channel/resizeItemByLeft', channel: channelName, item: item.$id, length: timeEnd - time, lengthPrev: timeEnd - timePrev, stretch } ], } ); } ); }, [ channel, item, range, size, guiSettings, dispatch, channelName ] ); const grabRight = useCallback( ( stretch: boolean ): void => { if ( !channel ) { return; } const timePrev = item.time + item.length; const timeBegin = item.time; let dx = 0.0; let time = timePrev; let hasMoved = false; registerMouseEvent( ( event, movementSum ) => { hasMoved = true; dx += movementSum.x; const ignoreSnap = event.altKey; time = timePrev + dx2dt( dx, range, size.width ); if ( !ignoreSnap ) { time = snapTime( time, range, size.width, guiSettings ); } channel.resizeItem( item.$id, time - timeBegin, stretch ); }, () => { if ( !hasMoved ) { return; } channel.resizeItem( item.$id, time - timeBegin, stretch ); dispatch( { type: 'History/Push', description: 'Resize Curve', commands: [ { type: 'channel/resizeItem', channel: channelName, item: item.$id, length: time - timeBegin, lengthPrev: timePrev - timeBegin, stretch } ], } ); } ); }, [ channel, item, range, size, guiSettings, dispatch, channelName ] ); const handleClickBody = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: () => { if ( checkDoubleClick() ) { removeItem(); } else { grabBody(); } }, [ MouseComboBit.LMB + MouseComboBit.Ctrl ]: () => { grabBodyCtrl(); }, [ MouseComboBit.LMB + MouseComboBit.Shift ]: () => { if ( !channel ) { return; } const newItem = channel.repeatItem( item.$id ); dispatch( { type: 'Timeline/SelectItems', items: [ { id: newItem.$id, channel: channelName } ] } ); dispatch( { type: 'Timeline/SelectChannel', channel: channelName } ); dispatch( { type: 'History/Push', description: 'Repeat Item', commands: [ { type: 'channel/createItemFromData', channel: channelName, data: newItem } ] } ); }, [ MouseComboBit.LMB + MouseComboBit.Alt ]: false, // give a way to seek! } ), [ checkDoubleClick, removeItem, grabBody, grabBodyCtrl, channel, item.$id, dispatch, channelName, ], ); const handleClickLeft = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: () => { grabLeft( false ); }, [ MouseComboBit.LMB + MouseComboBit.Shift ]: () => { grabLeft( true ); }, [ MouseComboBit.LMB + MouseComboBit.Alt ]: false, // give a way to seek! } ), [ grabLeft ] ); const handleClickRight = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: () => { grabRight( false ); }, [ MouseComboBit.LMB + MouseComboBit.Shift ]: () => { grabRight( true ); }, [ MouseComboBit.LMB + MouseComboBit.Alt ]: false, // give a way to seek! } ), [ grabRight ] ); const handleClickTop = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: () => { isFlipped ? grabBottom() : grabTop(); }, [ MouseComboBit.LMB + MouseComboBit.Alt ]: false, // give a way to seek! } ), [ isFlipped, grabBottom, grabTop ] ); const handleClickBottom = useCallback( ( event ) => mouseCombo( event, { [ MouseComboBit.LMB ]: () => { isFlipped ? grabTop() : grabBottom(); }, [ MouseComboBit.LMB + MouseComboBit.Alt ]: false, // give a way to seek! } ), [ isFlipped, grabTop, grabBottom ] ); const editCurve = useCallback( (): void => { dispatch( { type: 'CurveEditor/SelectCurve', curveId: item.curveId } ); dispatch( { type: 'Workspace/ChangeMode', mode: 'curve' } ); }, [ dispatch, item.curveId ] ); const makeCurveUnique = useCallback( (): void => { if ( !automaton || !channel || !item.curveId ) { return; } const src = automaton.getCurveById( item.curveId )!.serialize(); const newCurveData = automaton.createCurve( src ).serializeWithID(); const newItemData = jsonCopy( item ); newItemData.$id = genID(); newItemData.curveId = newCurveData.$id; channel.removeItem( item.$id ); channel.createItemFromData( newItemData ); dispatch( { type: 'CurveEditor/SelectCurve', curveId: newCurveData.$id } ); dispatch( { type: 'Workspace/ChangeMode', mode: 'curve' } ); dispatch( { type: 'History/Push', description: 'Make Curve Unique', commands: [ { type: 'automaton/createCurve', data: newCurveData, }, { type: 'channel/removeItem', channel: channelName, data: item, }, { type: 'channel/createItemFromData', channel: channelName, data: newItemData, } ], } ); }, [ automaton, channel, channelName, dispatch, item ] ); const handleContextMenu = useCallback( ( event: React.MouseEvent ): void => { event.preventDefault(); dispatch( { type: 'ContextMenu/Push', position: { x: event.clientX, y: event.clientY }, commands: [ { name: 'Edit Curve', description: 'Edit the curve.', callback: () => editCurve() }, { name: 'Make Curve Unique', description: 'Duplicate the curve.', callback: () => makeCurveUnique() }, { name: 'Remove', description: 'Remove the curve.', callback: () => removeItem() } ] } ); }, [ dispatch, editCurve, makeCurveUnique, removeItem ] ); return ( <Root style={ { transform: `translate( ${ x }px, ${ y }px )` } } > <clipPath id={ `${ curveClipID }` } > <rect style={ { transform: `translate( 0, ${ -y }px )` } } width={ w } height={ size.height } /> </clipPath> <Body width={ w } height={ h } isSelected={ isSelected } onMouseDown={ handleClickBody } onContextMenu={ handleContextMenu } /> <g clipPath={ `url(#${ curveClipID })` } > <CurvePath style={ { transform: ( isFlipped ? `translate( ${ curveX }px, 0 ) scale( ${ curveWidth }, ${ h } )` : `translate( ${ curveX }px, ${ h }px ) scale( ${ curveWidth }, ${ -h } )` ) } } points={ path } vectorEffect="non-scaling-stroke" /> </g> <Stroke width={ w } height={ h } /> { !dopeSheetMode && <> <VerticalSide style={ { transform: 'translate( 0, -1px )' } } width={ w } height="4" onMouseDown={ handleClickTop } /> <VerticalSide style={ { transform: `translate( 0, ${ h - 3 }px )` } } width={ w } height="4" onMouseDown={ handleClickBottom } /> </> } <Side style={ { transform: 'translate( -1px, 0 )' } } width="4" height={ h } onMouseDown={ handleClickLeft } /> <Side style={ { transform: `translate( ${ w - 3 }px, 0 )` } } width="4" height={ h } onMouseDown={ handleClickRight } /> { item.reset && <g style={ { transform: `translate( ${ w + 5 }px, ${ h - 10 }px )` } } > <ResetIcon width="10" height="10" /> </g> } </Root> ); }; export { TimelineItemCurve };
the_stack
import React from 'react'; import {stripMarkdown} from 'utils/markdown'; describe('stripMarkdown | RemoveMarkdown', () => { const testCases = [ { description: 'emoji: same', inputText: 'Hey :smile: :+1: :)', outputText: 'Hey :smile: :+1: :)', }, { description: 'at-mention: same', inputText: 'Hey @user and @test', outputText: 'Hey @user and @test', }, { description: 'channel-link: same', inputText: 'join ~channelname', outputText: 'join ~channelname', }, { description: 'codespan: single backtick', inputText: '`single backtick`', outputText: 'single backtick', }, { description: 'codespan: double backtick', inputText: '``double backtick``', outputText: 'double backtick', }, { description: 'codespan: triple backtick', inputText: '```triple backtick```', outputText: 'triple backtick', }, { description: 'codespan: inline code', inputText: 'Inline `code` has ``double backtick`` and ```triple backtick``` around it.', outputText: 'Inline code has double backtick and triple backtick around it.', }, { description: 'code block: single line code block', inputText: 'Code block\n```\nline\n```', outputText: 'Code block line', }, { description: 'code block: multiline code block 2', inputText: 'Multiline\n```function(number) {\n return number + 1;\n}```', outputText: 'Multiline function(number) { return number + 1; }', }, { description: 'code block: language highlighting', inputText: '```javascript\nvar s = "JavaScript syntax highlighting";\nalert(s);\n```', outputText: 'var s = "JavaScript syntax highlighting"; alert(s);', }, { description: 'blockquote:', inputText: '> Hey quote', outputText: 'Hey quote', }, { description: 'blockquote: multiline', inputText: '> Hey quote.\n> Hello quote.', outputText: 'Hey quote. Hello quote.', }, { description: 'heading: # H1 header', inputText: '# H1 header', outputText: 'H1 header', }, { description: 'heading: heading with @user', inputText: '# H1 @user', outputText: 'H1 @user', }, { description: 'heading: ## H2 header', inputText: '## H2 header', outputText: 'H2 header', }, { description: 'heading: ### H3 header', inputText: '### H3 header', outputText: 'H3 header', }, { description: 'heading: #### H4 header', inputText: '#### H4 header', outputText: 'H4 header', }, { description: 'heading: ##### H5 header', inputText: '##### H5 header', outputText: 'H5 header', }, { description: 'heading: ###### H6 header', inputText: '###### H6 header', outputText: 'H6 header', }, { description: 'heading: multiline with header and paragraph', inputText: '###### H6 header\nThis is next line.\nAnother line.', outputText: 'H6 header This is next line. Another line.', }, { description: 'heading: multiline with header and list items', inputText: '###### H6 header\n- list item 1\n- list item 2', outputText: 'H6 header list item 1 list item 2', }, { description: 'heading: multiline with header and links', inputText: '###### H6 header\n[link 1](https://mattermost.com) - [link 2](https://mattermost.com)', outputText: 'H6 header link 1 - link 2', }, { description: 'list: 1. First ordered list item', inputText: '1. First ordered list item', outputText: 'First ordered list item', }, { description: 'list: 2. Another item', inputText: '1. 2. Another item', outputText: 'Another item', }, { description: 'list: * Unordered sub-list.', inputText: '* Unordered sub-list.', outputText: 'Unordered sub-list.', }, { description: 'list: - Or minuses', inputText: '- Or minuses', outputText: 'Or minuses', }, { description: 'list: + Or pluses', inputText: '+ Or pluses', outputText: 'Or pluses', }, { description: 'list: multiline', inputText: '1. First ordered list item\n2. Another item', outputText: 'First ordered list item Another item', }, { description: 'tablerow:)', inputText: 'Markdown | Less | Pretty\n' + '--- | --- | ---\n' + '*Still* | `renders` | **nicely**\n' + '1 | 2 | 3\n', outputText: '', }, { description: 'table:', inputText: '| Tables | Are | Cool |\n' + '| ------------- |:-------------:| -----:|\n' + '| col 3 is | right-aligned | $1600 |\n' + '| col 2 is | centered | $12 |\n' + '| zebra stripes | are neat | $1 |\n', outputText: '', }, { description: 'strong: Bold with **asterisks** or __underscores__.', inputText: 'Bold with **asterisks** or __underscores__.', outputText: 'Bold with asterisks or underscores.', }, { description: 'strong & em: Bold and italics with **asterisks and _underscores_**.', inputText: 'Bold and italics with **asterisks and _underscores_**.', outputText: 'Bold and italics with asterisks and underscores.', }, { description: 'em: Italics with *asterisks* or _underscores_.', inputText: 'Italics with *asterisks* or _underscores_.', outputText: 'Italics with asterisks or underscores.', }, { description: 'del: Strikethrough ~~strike this.~~', inputText: 'Strikethrough ~~strike this.~~', outputText: 'Strikethrough strike this.', }, { description: 'links: [inline-style link](http://localhost:8065)', inputText: '[inline-style link](http://localhost:8065)', outputText: 'inline-style link', }, { description: 'image: ![image link](http://localhost:8065/image)', inputText: '![image link](http://localhost:8065/image)', outputText: 'image link', }, { description: 'text: plain', inputText: 'This is plain text.', outputText: 'This is plain text.', }, { description: 'text: multiline', inputText: 'This is multiline text.\nHere is the next line.\n', outputText: 'This is multiline text. Here is the next line.', }, { description: 'text: multiline with blockquote', inputText: 'This is multiline text.\n> With quote', outputText: 'This is multiline text. With quote', }, { description: 'text: multiline with list items', inputText: 'This is multiline text.\n * List item ', outputText: 'This is multiline text. List item', }, { description: 'text: &amp; entity', inputText: 'you & me', outputText: 'you & me', }, { description: 'text: &lt; entity', inputText: '1<2', outputText: '1<2', }, { description: 'text: &gt; entity', inputText: '2>1', outputText: '2>1', }, { description: 'text: &#39; entity', inputText: 'he\'s out', outputText: 'he\'s out', }, { description: 'text: &quot; entity', inputText: 'That is "unique"', outputText: 'That is "unique"', }, { description: 'text: multiple entities', inputText: '&<>\'"', outputText: '&<>\'"', }, { description: 'text: multiple entities', inputText: '"\'><&', outputText: '"\'><&', }, { description: 'text: multiple entities', inputText: '&amp;&lt;&gt;&#39;&quot;', outputText: '&<>\'"', }, { description: 'text: multiple entities', inputText: '&quot;&#39;&gt;&lt;&amp;', outputText: '"\'><&', }, { description: 'text: multiple entities', inputText: '&amp;lt;', outputText: '&lt;', }, { description: 'text: empty string', inputText: '', outputText: '', }, { description: 'text: null', inputText: null, outputText: null, }, { description: 'text: {}', inputText: {key: 'value'}, outputText: {key: 'value'}, }, { description: 'text: []', inputText: [1], outputText: [1], }, { description: 'text: node', inputText: (<div/>), outputText: (<div/>), }, ]; testCases.forEach((testCase) => it(testCase.description, () => { expect(stripMarkdown(testCase.inputText as any)).toEqual(testCase.outputText); })); });
the_stack
import path from 'path' import { testConfig } from 'houdini-common' import * as graphql from 'graphql' import fs from 'fs/promises' import * as recast from 'recast' import * as typeScriptParser from 'recast/parsers/typescript' // local imports import '../../../../../jest.setup' import { runPipeline } from '../../generate' import { mockCollectedDoc } from '../../testUtils' // the config to use in tests const config = testConfig({ schema: ` enum MyEnum { Hello } type Query { user(id: ID, filter: UserFilter, filterList: [UserFilter!], enumArg: MyEnum): User users: [User] nodes: [Node!]! entities: [Entity] listOfLists: [[User]]! node(id: ID!): Node } type Mutation { doThing( filter: UserFilter, list: [UserFilter!]!, id: ID! firstName: String! admin: Boolean age: Int weight: Float ): User } input UserFilter { middle: NestedUserFilter listRequired: [String!]! nullList: [String] recursive: UserFilter enum: MyEnum } input NestedUserFilter { id: ID! firstName: String! admin: Boolean age: Int weight: Float } interface Node { id: ID! } type Cat implements Node & Animal { id: ID! kitty: Boolean! isAnimal: Boolean! } interface Animal { isAnimal: Boolean! } union Entity = User | Cat union AnotherEntity = User | Ghost type Ghost { aka: String! } type User implements Node { id: ID! firstName: String! nickname: String parent: User friends: [User] enumValue: MyEnum admin: Boolean age: Int weight: Float } `, }) describe('typescript', function () { test('fragment types', async function () { // the document to test const doc = mockCollectedDoc( `fragment TestFragment on User { firstName nickname enumValue }` ) // execute the generator await runPipeline(config, [doc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(doc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` enum MyEnum { Hello = "Hello" } export type TestFragment = { readonly "shape"?: TestFragment$data, readonly "$fragments": { "TestFragment": true } }; export type TestFragment$data = { readonly firstName: string, readonly nickname: string | null, readonly enumValue: MyEnum | null }; `) }) test('nested types', async function () { const fragment = `fragment TestFragment on User { firstName parent { firstName } }` // the document to test const doc = mockCollectedDoc(fragment) // execute the generator await runPipeline(config, [doc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(doc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type TestFragment = { readonly "shape"?: TestFragment$data, readonly "$fragments": { "TestFragment": true } }; export type TestFragment$data = { readonly firstName: string, readonly parent: { readonly firstName: string } | null }; `) }) test('scalars', async function () { // the document to test const doc = mockCollectedDoc( `fragment TestFragment on User { firstName admin age id weight }` ) // execute the generator await runPipeline(config, [doc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(doc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type TestFragment = { readonly "shape"?: TestFragment$data, readonly "$fragments": { "TestFragment": true } }; export type TestFragment$data = { readonly firstName: string, readonly admin: boolean | null, readonly age: number | null, readonly id: string, readonly weight: number | null }; `) }) test('list types', async function () { // the document to test const doc = mockCollectedDoc( `fragment TestFragment on User { firstName friends { firstName } }` ) // execute the generator await runPipeline(config, [doc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(doc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type TestFragment = { readonly "shape"?: TestFragment$data, readonly "$fragments": { "TestFragment": true } }; export type TestFragment$data = { readonly firstName: string, readonly friends: ({ readonly firstName: string } | null)[] | null }; `) }) test('query with no input', async function () { // the document to test const doc = mockCollectedDoc(`query Query { user { firstName } }`) // execute the generator await runPipeline(config, [doc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(doc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly user: { readonly firstName: string } | null }; `) }) test('query with root list', async function () { // the document with the query const queryDoc = mockCollectedDoc(` query Query { users { firstName, } } `) // execute the generator await runPipeline(config, [queryDoc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(queryDoc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly users: ({ readonly firstName: string } | null)[] | null }; `) }) test('query with input', async function () { // the document to test const doc = mockCollectedDoc( `query Query($id: ID!, $enum: MyEnum) { user(id: $id, enumArg: $enum ) { firstName } }` ) // execute the generator await runPipeline(config, [doc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(doc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": Query$input, readonly "result": Query$result }; export type Query$result = { readonly user: { readonly firstName: string } | null }; enum MyEnum { Hello = "Hello" } export type Query$input = { id: string, enum: MyEnum | null | undefined }; `) }) test('mutation with input list', async function () { // the document to test const doc = mockCollectedDoc( `mutation Mutation( $filter: UserFilter, $filterList: [UserFilter!]!, $id: ID! $firstName: String! $admin: Boolean $age: Int $weight: Float ) { doThing( filter: $filter, list: $filterList, id:$id firstName:$firstName admin:$admin age:$age weight:$weight ) { firstName } }` ) // execute the generator await runPipeline(config, [doc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(doc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Mutation = { readonly "input": Mutation$input, readonly "result": Mutation$result }; export type Mutation$result = { readonly doThing: { readonly firstName: string } | null }; type NestedUserFilter = { id: string, firstName: string, admin: boolean | null | undefined, age: number | null | undefined, weight: number | null | undefined }; enum MyEnum { Hello = "Hello" } type UserFilter = { middle: NestedUserFilter | null | undefined, listRequired: (string)[], nullList: (string | null | undefined)[] | null | undefined, recursive: UserFilter | null | undefined, enum: MyEnum | null | undefined }; export type Mutation$input = { filter: UserFilter | null | undefined, filterList: (UserFilter)[], id: string, firstName: string, admin: boolean | null | undefined, age: number | null | undefined, weight: number | null | undefined }; `) }) test('nested input objects', async function () { // the document to test const doc = mockCollectedDoc( `query Query($filter: UserFilter!) { user(filter: $filter) { firstName } }` ) // execute the generator await runPipeline(config, [doc]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(doc.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": Query$input, readonly "result": Query$result }; export type Query$result = { readonly user: { readonly firstName: string } | null }; type NestedUserFilter = { id: string, firstName: string, admin: boolean | null | undefined, age: number | null | undefined, weight: number | null | undefined }; enum MyEnum { Hello = "Hello" } type UserFilter = { middle: NestedUserFilter | null | undefined, listRequired: (string)[], nullList: (string | null | undefined)[] | null | undefined, recursive: UserFilter | null | undefined, enum: MyEnum | null | undefined }; export type Query$input = { filter: UserFilter }; `) }) test('generates index file', async function () { // the document to test const doc = mockCollectedDoc( `query Query($filter: UserFilter!) { user(filter: $filter) { firstName } }` ) // execute the generator await runPipeline(config, [doc]) // read the type index file const fileContents = await fs.readFile(config.typeIndexPath, 'utf-8') expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export * from "./artifacts/Query"; export * from "./runtime"; `) }) test('fragment spreads', async function () { // the document with the fragment const fragment = mockCollectedDoc(`fragment Foo on User { firstName }`) // the document to test const query = mockCollectedDoc(`query Query { user { ...Foo } }`) // execute the generator await runPipeline(config, [query, fragment]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly user: { readonly $fragments: { Foo: true } } | null }; `) }) test('interfaces', async function () { // the document to test const query = mockCollectedDoc( ` query Query { nodes { ... on User { id } ... on Cat { id } } } ` ) // execute the generator await runPipeline(config, [query]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly nodes: ({} & (({ readonly id: string, readonly __typename: "User" }) | ({ readonly id: string, readonly __typename: "Cat" })))[] }; `) }) test('unions', async function () { // the document to test const query = mockCollectedDoc( ` query Query { entities { ... on User { id } ... on Cat { id } } } ` ) // execute the generator await runPipeline(config, [query]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly entities: ({} & (({ readonly id: string, readonly __typename: "User" }) | ({ readonly id: string, readonly __typename: "Cat" })) | null)[] | null }; `) }) test('discriminated interface', async function () { // the document to test const query = mockCollectedDoc( ` query Query { nodes { id ... on User { firstName } ... on Cat { kitty } } } ` ) // execute the generator await runPipeline(config, [query]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly nodes: ({ readonly id: string } & (({ readonly firstName: string, readonly __typename: "User" }) | ({ readonly kitty: boolean, readonly __typename: "Cat" })))[] }; `) }) test('intersecting interface', async function () { // the document to test const query = mockCollectedDoc( ` query Query { entities { ... on Animal { isAnimal } ... on User { firstName } ... on Cat { kitty } } } ` ) // execute the generator await runPipeline(config, [query]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly entities: ({} & (({ readonly firstName: string, readonly __typename: "User" }) | ({ readonly kitty: boolean, readonly __typename: "Cat" } & { readonly isAnimal: boolean })) | null)[] | null }; `) }) test('fragment with custom scalars', async function () { // define a config with a custom scalar const localConfig = testConfig({ schema: ` scalar DateTime type TodoItem { text: String! createdAt: DateTime! } type Query { allItems: [TodoItem!]! } `, scalars: { DateTime: { type: 'Date', unmarshal(val: number): Date { return new Date(val) }, marshal(date: Date): number { return date.getTime() }, }, }, }) // the document to test const query = mockCollectedDoc(`query Query { allItems { createdAt } }`) // execute the generator await runPipeline(localConfig, [query]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly allItems: ({ readonly createdAt: Date })[] }; `) }) test('input with custom scalars', async function () { // define a config with a custom scalar const localConfig = testConfig({ schema: ` scalar DateTime type TodoItem { text: String! createdAt: DateTime! } type Query { allItems(createdAt: DateTime): [TodoItem!]! } `, scalars: { DateTime: { type: 'Date', unmarshal(val: number): Date { return new Date(val) }, marshal(date: Date): number { return date.getTime() }, }, }, }) // the document to test const query = mockCollectedDoc( `query Query($date: DateTime!) { allItems(createdAt: $date) { createdAt } }` ) // execute the generator await runPipeline(localConfig, [query]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": Query$input, readonly "result": Query$result }; export type Query$result = { readonly allItems: ({ readonly createdAt: Date })[] }; export type Query$input = { date: Date }; `) }) test('can generate types for list of lists', async function () { // the document to test const query = mockCollectedDoc( ` query Query { listOfLists { firstName nickname } } ` ) // execute the generator await runPipeline(config, [query]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly listOfLists: (({ readonly firstName: string, readonly nickname: string | null } | null)[] | null)[] }; `) }) test('duplicate fields', async function () { // the document to test const query = mockCollectedDoc(`query Query { user { parent { firstName firstName } parent { nickname } } }`) // execute the generator await runPipeline(config, [query]) // look up the files in the artifact directory const fileContents = await fs.readFile(config.artifactTypePath(query.document), 'utf-8') // make sure they match what we expect expect( recast.parse(fileContents, { parser: typeScriptParser, }) ).toMatchInlineSnapshot(` export type Query = { readonly "input": null, readonly "result": Query$result }; export type Query$result = { readonly user: { readonly parent: { readonly firstName: string, readonly nickname: string | null } | null } | null }; `) }) test.todo('fragments on interfaces') test.todo('intersections with __typename in subselection') test.todo('inline fragments') })
the_stack
import { IActionContext, registerCommand as registerCommandAzUI } from "@microsoft/vscode-azext-utils"; import { commands } from "vscode"; import { ext } from "../extensionVariables"; import { scaffold } from "../scaffolding/scaffold"; import { scaffoldCompose } from "../scaffolding/scaffoldCompose"; import { scaffoldDebugConfig } from "../scaffolding/scaffoldDebugConfig"; import { composeDown, composeRestart, composeUp, composeUpSubset } from "./compose/compose"; import { attachShellContainer } from "./containers/attachShellContainer"; import { browseContainer } from "./containers/browseContainer"; import { composeGroupDown, composeGroupLogs, composeGroupRestart, composeGroupStart, composeGroupStop } from "./containers/composeGroup"; import { configureContainersExplorer } from "./containers/configureContainersExplorer"; import { downloadContainerFile } from "./containers/files/downloadContainerFile"; import { openContainerFile } from "./containers/files/openContainerFile"; import { inspectContainer } from "./containers/inspectContainer"; import { pruneContainers } from "./containers/pruneContainers"; import { removeContainer } from "./containers/removeContainer"; import { restartContainer } from "./containers/restartContainer"; import { selectContainer } from "./containers/selectContainer"; import { startContainer } from "./containers/startContainer"; import { stats } from "./containers/stats"; import { stopContainer } from "./containers/stopContainer"; import { viewContainerLogs } from "./containers/viewContainerLogs"; import { createAciContext } from "./context/aci/createAciContext"; import { configureDockerContextsExplorer, dockerContextsHelp } from "./context/DockerContextsViewCommands"; import { inspectDockerContext } from "./context/inspectDockerContext"; import { removeDockerContext } from "./context/removeDockerContext"; import { useDockerContext } from "./context/useDockerContext"; import { help } from "./help"; import { buildImage } from "./images/buildImage"; import { configureImagesExplorer } from "./images/configureImagesExplorer"; import { copyFullTag } from "./images/copyFullTag"; import { inspectImage } from "./images/inspectImage"; import { pruneImages } from "./images/pruneImages"; import { pullImage } from "./images/pullImage"; import { pushImage } from "./images/pushImage"; import { removeImage } from "./images/removeImage"; import { runAzureCliImage } from "./images/runAzureCliImage"; import { runImage, runImageInteractive } from "./images/runImage"; import { hideDanglingImages, setInitialDanglingContextValue, showDanglingImages } from "./images/showDanglingImages"; import { tagImage } from "./images/tagImage"; import { installDocker } from "./installDocker"; import { configureNetworksExplorer } from "./networks/configureNetworksExplorer"; import { createNetwork } from "./networks/createNetwork"; import { inspectNetwork } from "./networks/inspectNetwork"; import { pruneNetworks } from "./networks/pruneNetworks"; import { removeNetwork } from "./networks/removeNetwork"; import { pruneSystem } from "./pruneSystem"; import { registerLocalCommand } from "./registerLocalCommand"; import { registerWorkspaceCommand } from "./registerWorkspaceCommand"; import { createAzureRegistry } from "./registries/azure/createAzureRegistry"; import { deleteAzureRegistry } from "./registries/azure/deleteAzureRegistry"; import { deleteAzureRepository } from "./registries/azure/deleteAzureRepository"; import { deployImageToAci } from "./registries/azure/deployImageToAci"; import { deployImageToAzure } from "./registries/azure/deployImageToAzure"; import { openInAzurePortal } from "./registries/azure/openInAzurePortal"; import { buildImageInAzure } from "./registries/azure/tasks/buildImageInAzure"; import { runAzureTask } from "./registries/azure/tasks/runAzureTask"; import { runFileAsAzureTask } from "./registries/azure/tasks/runFileAsAzureTask"; import { viewAzureTaskLogs } from "./registries/azure/tasks/viewAzureTaskLogs"; import { untagAzureImage } from "./registries/azure/untagAzureImage"; import { viewAzureProperties } from "./registries/azure/viewAzureProperties"; import { connectRegistry } from "./registries/connectRegistry"; import { copyRemoteFullTag } from './registries/copyRemoteFullTag'; import { copyRemoteImageDigest } from "./registries/copyRemoteImageDigest"; import { deleteRemoteImage } from "./registries/deleteRemoteImage"; import { disconnectRegistry } from "./registries/disconnectRegistry"; import { openDockerHubInBrowser } from "./registries/dockerHub/openDockerHubInBrowser"; import { logInToDockerCli } from "./registries/logInToDockerCli"; import { logOutOfDockerCli } from "./registries/logOutOfDockerCli"; import { pullImageFromRepository, pullRepository } from "./registries/pullImages"; import { reconnectRegistry } from "./registries/reconnectRegistry"; import { registryHelp } from "./registries/registryHelp"; import { configureVolumesExplorer } from "./volumes/configureVolumesExplorer"; import { inspectVolume } from "./volumes/inspectVolume"; import { pruneVolumes } from "./volumes/pruneVolumes"; import { removeVolume } from "./volumes/removeVolume"; interface CommandReasonArgument { commandReason: 'tree' | 'palette' | 'install'; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function registerCommand(commandId: string, callback: (context: IActionContext, ...args: any[]) => any, debounce?: number): void { registerCommandAzUI( commandId, // eslint-disable-next-line @typescript-eslint/no-explicit-any async (context, ...args: any[]) => { void ext.activityMeasurementService.recordActivity('overallnoedit'); // If a command reason is given, record it. Currently only the start page provides the reason. const commandReasonArgIndex = args.findIndex(a => (<CommandReasonArgument>a)?.commandReason); if (commandReasonArgIndex >= 0) { const commandReason = (<CommandReasonArgument>args[commandReasonArgIndex]).commandReason; context.telemetry.properties.commandReason = commandReason; if (commandReason === 'install') { context.telemetry.properties.isActivationEvent = 'true'; } // Remove the reason argument from the list to prevent confusing the command args.splice(commandReasonArgIndex, 1); } return callback(context, ...args); }, debounce ); } export function registerCommands(): void { registerWorkspaceCommand('vscode-docker.configure', scaffold); registerWorkspaceCommand('vscode-docker.configureCompose', scaffoldCompose); registerWorkspaceCommand('vscode-docker.debugging.initializeForDebugging', scaffoldDebugConfig); registerWorkspaceCommand('vscode-docker.compose.down', composeDown); registerWorkspaceCommand('vscode-docker.compose.restart', composeRestart); registerWorkspaceCommand('vscode-docker.compose.up', composeUp); registerWorkspaceCommand('vscode-docker.compose.up.subset', composeUpSubset); registerCommand('vscode-docker.pruneSystem', pruneSystem); registerWorkspaceCommand('vscode-docker.containers.attachShell', attachShellContainer); registerCommand('vscode-docker.containers.browse', browseContainer); registerCommand('vscode-docker.containers.downloadFile', downloadContainerFile); registerCommand('vscode-docker.containers.inspect', inspectContainer); registerCommand('vscode-docker.containers.configureExplorer', configureContainersExplorer); registerCommand('vscode-docker.containers.openFile', openContainerFile); registerCommand('vscode-docker.containers.prune', pruneContainers); registerCommand('vscode-docker.containers.remove', removeContainer); registerCommand('vscode-docker.containers.restart', restartContainer); registerCommand('vscode-docker.containers.select', selectContainer); registerCommand('vscode-docker.containers.start', startContainer); registerCommand('vscode-docker.containers.stop', stopContainer); registerWorkspaceCommand('vscode-docker.containers.stats', stats); registerWorkspaceCommand('vscode-docker.containers.viewLogs', viewContainerLogs); registerWorkspaceCommand('vscode-docker.containers.composeGroup.logs', composeGroupLogs); registerWorkspaceCommand('vscode-docker.containers.composeGroup.start', composeGroupStart); registerWorkspaceCommand('vscode-docker.containers.composeGroup.stop', composeGroupStop); registerWorkspaceCommand('vscode-docker.containers.composeGroup.restart', composeGroupRestart); registerWorkspaceCommand('vscode-docker.containers.composeGroup.down', composeGroupDown); registerWorkspaceCommand('vscode-docker.images.build', buildImage); registerCommand('vscode-docker.images.configureExplorer', configureImagesExplorer); registerCommand('vscode-docker.images.inspect', inspectImage); registerCommand('vscode-docker.images.prune', pruneImages); registerCommand('vscode-docker.images.showDangling', showDanglingImages); registerCommand('vscode-docker.images.hideDangling', hideDanglingImages); setInitialDanglingContextValue(); registerWorkspaceCommand('vscode-docker.images.pull', pullImage); registerWorkspaceCommand('vscode-docker.images.push', pushImage); registerCommand('vscode-docker.images.remove', removeImage); registerWorkspaceCommand('vscode-docker.images.run', runImage); registerWorkspaceCommand('vscode-docker.images.runAzureCli', runAzureCliImage); registerWorkspaceCommand('vscode-docker.images.runInteractive', runImageInteractive); registerCommand('vscode-docker.images.tag', tagImage); registerCommand('vscode-docker.images.copyFullTag', copyFullTag); registerCommand('vscode-docker.networks.configureExplorer', configureNetworksExplorer); registerCommand('vscode-docker.networks.create', createNetwork); registerCommand('vscode-docker.networks.inspect', inspectNetwork); registerCommand('vscode-docker.networks.remove', removeNetwork); registerCommand('vscode-docker.networks.prune', pruneNetworks); registerCommand('vscode-docker.registries.connectRegistry', connectRegistry); registerCommand('vscode-docker.registries.copyImageDigest', copyRemoteImageDigest); registerCommand('vscode-docker.registries.copyRemoteFullTag', copyRemoteFullTag); registerCommand('vscode-docker.registries.deleteImage', deleteRemoteImage); registerCommand('vscode-docker.registries.deployImageToAzure', deployImageToAzure); registerCommand('vscode-docker.registries.deployImageToAci', deployImageToAci); registerCommand('vscode-docker.registries.disconnectRegistry', disconnectRegistry); registerCommand('vscode-docker.registries.help', registryHelp); registerWorkspaceCommand('vscode-docker.registries.logInToDockerCli', logInToDockerCli); registerWorkspaceCommand('vscode-docker.registries.logOutOfDockerCli', logOutOfDockerCli); registerWorkspaceCommand('vscode-docker.registries.pullImage', pullImageFromRepository); registerWorkspaceCommand('vscode-docker.registries.pullRepository', pullRepository); registerCommand('vscode-docker.registries.reconnectRegistry', reconnectRegistry); registerCommand('vscode-docker.registries.dockerHub.openInBrowser', openDockerHubInBrowser); registerWorkspaceCommand('vscode-docker.registries.azure.buildImage', buildImageInAzure); registerCommand('vscode-docker.registries.azure.createRegistry', createAzureRegistry); registerCommand('vscode-docker.registries.azure.deleteRegistry', deleteAzureRegistry); registerCommand('vscode-docker.registries.azure.deleteRepository', deleteAzureRepository); registerCommand('vscode-docker.registries.azure.openInPortal', openInAzurePortal); registerCommand('vscode-docker.registries.azure.runTask', runAzureTask); registerWorkspaceCommand('vscode-docker.registries.azure.runFileAsTask', runFileAsAzureTask); registerCommand('vscode-docker.registries.azure.selectSubscriptions', () => commands.executeCommand("azure-account.selectSubscriptions")); registerCommand('vscode-docker.registries.azure.untagImage', untagAzureImage); registerCommand('vscode-docker.registries.azure.viewProperties', viewAzureProperties); registerCommand('vscode-docker.registries.azure.viewTaskLogs', viewAzureTaskLogs); registerCommand('vscode-docker.volumes.configureExplorer', configureVolumesExplorer); registerCommand('vscode-docker.volumes.inspect', inspectVolume); registerCommand('vscode-docker.volumes.prune', pruneVolumes); registerCommand('vscode-docker.volumes.remove', removeVolume); registerCommand('vscode-docker.contexts.configureExplorer', configureDockerContextsExplorer); registerCommand('vscode-docker.contexts.help', dockerContextsHelp); registerCommand('vscode-docker.contexts.inspect', inspectDockerContext); registerCommand('vscode-docker.contexts.remove', removeDockerContext); registerCommand('vscode-docker.contexts.use', useDockerContext); registerCommand('vscode-docker.contexts.create.aci', createAciContext); registerLocalCommand('vscode-docker.installDocker', installDocker); registerCommand('vscode-docker.help', help); registerCommand('vscode-docker.help.openWalkthrough', () => commands.executeCommand('workbench.action.openWalkthrough', 'ms-azuretools.vscode-docker#dockerStart')); }
the_stack
import { RangeNavigator, RangeTooltip } from '../../../src/range-navigator/index'; import { Logarithmic, DateTime, LineSeries, AreaSeries, getElement } from '../../../src/chart/index'; import { createElement, remove } from '@syncfusion/ej2-base'; import { IChangedEventArgs, IRangeEventArgs, IRangeTooltipRenderEventArgs } from '../../../src/range-navigator/model/range-navigator-interface'; import { MouseEvents } from '../../../spec/chart/base/events.spec'; import {profile , inMB, getMemoryProfile} from '../../common.spec'; RangeNavigator.Inject(Logarithmic, DateTime, LineSeries, AreaSeries, RangeTooltip); let value: number = 0; let point: Object; let data: Object[] = []; let args: IChangedEventArgs; let trigger: MouseEvents = new MouseEvents(); for (let j: number = 0; j < 100; j++) { value += (Math.random() * 10); point = { x: j, y: value }; data.push(point); } /** * Spec for range navigator */ describe('Range navigator Tooltip', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('with Sliders double axis', () => { let element: Element; let targetElement: Element; let range: RangeNavigator; let rangeElement: HTMLElement = createElement('div', { id: 'tooltip_container' }); let axisLabel: Element; let isCheck: boolean = false; beforeAll(() => { document.body.appendChild(rangeElement); range = new RangeNavigator({ series: [{ dataSource: [{ x: 10, y: 20 }, { x: 20, y: 12 }, { x: 30, y: 22 }, { x: 40, y: 16 }], xName: 'x', yName: 'y', type: 'Line', animation: { duration: 0 } }], tooltip: { enable: true, textStyle: { size: '11px', fontWeight: 'Normal', color: null, fontStyle: 'Normal', fontFamily: 'Roboto-Regula' } }, value: [10, 20], allowSnapping: false }); range.appendTo('#tooltip_container'); }); afterAll((): void => { range.destroy(); rangeElement.remove(); }); it('checking with left slider moving', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_LeftSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 100, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 100, 10)); expect(getElement('tooltip_container_Secondary_Element') !== null).toBe(true); expect(getElement('tooltip_container_Secondary_Element').childElementCount).toBe(2); done(); }; range.refresh(); }); it('checking with right slider moving', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 100, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 100, 10)); expect(getElement('tooltip_container_leftTooltip_text').textContent).not.toEqual(''); expect(getElement('tooltip_container_rightTooltip_text').textContent).not.toEqual(''); done(); }; range.refresh(); }); it('checking with left slider moving over right slider', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: number = +getElement('tooltip_container_leftTooltip_text').textContent; let rightValue: number = +getElement('tooltip_container_rightTooltip_text').textContent; expect(leftValue < rightValue).toBe(true); done(); }; range.value = [0, 10]; range.refresh(); }); it('checking with tooltip cancel', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); expect(getElement('tooltip_container_leftTooltip_text') === null).toBe(true); done(); }; range.tooltipRender = (args: IRangeTooltipRenderEventArgs) => { args.cancel = true; }; range.value = [0, 10]; range.refresh(); }); it('checking with tooltip format', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: string = getElement('tooltip_container_leftTooltip_text').textContent; let rightValue: string = getElement('tooltip_container_rightTooltip_text').textContent; expect(leftValue.indexOf('$') > -1).toBe(true); expect(rightValue.indexOf('$') > -1).toBe(true); done(); }; range.tooltipRender = null; range.tooltip.format = '${value}' range.refresh(); }); it('checking with tooltip template', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: string = getElement('tooltip_container_leftTooltipparent_template').innerHTML; expect(leftValue.indexOf('template') > -1).toBe(true); done(); }; range.tooltipRender = null; range.tooltip.template = '<div>$template{value}</div>'; range.refresh(); }); it('checking with tooltip template with sample data', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: string = getElement('tooltip_container_leftTooltipparent_template').innerHTML; let rightValue: string = getElement('tooltip_container_leftTooltipparent_template').innerHTML; expect(leftValue === rightValue).toBe(true); done(); }; range.tooltipRender = null; range.tooltip.template = '<div>${start}</div>'; range.refresh(); }); }); describe('with Sliders date time axis with leight weight', () => { let element: Element; let targetElement: Element; let range: RangeNavigator; let rangeElement: HTMLElement = createElement('div', { id: 'tooltip_container' }); let axisLabel: Element; let isCheck: boolean = false; beforeAll(() => { document.body.appendChild(rangeElement); range = new RangeNavigator({ valueType: 'DateTime', dataSource: [ { x: new Date(2000, 1, 1), y: 20 }, { x: new Date(2001, 1, 1), y: 12 }, { x: new Date(2002, 1, 1), y: 22 }, { x: new Date(2003, 1, 1), y: 16 } ], xName: 'x', yName: 'y', tooltip: { enable: true, textStyle: { size: '11px', fontWeight: 'Normal', color: null, fontStyle: 'Normal', fontFamily: 'Roboto-Regula' } }, value: [new Date(2001, 1, 1), new Date(2002, 1, 1)], allowSnapping: false }, rangeElement); }); afterAll((): void => { range.destroy(); rangeElement.remove(); }); it('checking with left slider moving', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_LeftSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 100, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 100, 10)); expect(getElement('tooltip_container_Secondary_Element') !== null).toBe(true); expect(getElement('tooltip_container_Secondary_Element').childElementCount).toBe(2); done(); }; range.refresh(); }); it('checking with right slider moving', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 100, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 100, 10)); expect(getElement('tooltip_container_leftTooltip_text').textContent).not.toEqual(''); expect(getElement('tooltip_container_rightTooltip_text').textContent).not.toEqual(''); done(); }; range.refresh(); }); it('checking with left slider moving over right slider', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: string = getElement('tooltip_container_leftTooltip_text').textContent; let rightValue: string = getElement('tooltip_container_rightTooltip_text').textContent; expect(Date.parse(leftValue) < Date.parse(rightValue)).toBe(true); done(); }; range.value = [new Date(2000, 1, 1), new Date(2000, 1, 1)]; range.refresh(); }); it('checking with tooltip cancel', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); expect(getElement('tooltip_container_leftTooltip_text') === null).toBe(true); done(); }; range.tooltipRender = (args: IRangeTooltipRenderEventArgs) => { args.cancel = true; }; range.refresh(); }); it('checking with tooltip format', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: string = getElement('tooltip_container_leftTooltip_text').textContent; let rightValue: string = getElement('tooltip_container_rightTooltip_text').textContent; expect(rightValue === 'Feb').toBe(true); done(); }; range.tooltipRender = null; range.tooltip.format = 'MMM' range.refresh(); }); it('checking with tooltip template', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: string = getElement('tooltip_container_leftTooltipparent_template').innerHTML; expect(leftValue.indexOf('template') > -1).toBe(true); done(); }; range.tooltipRender = null; range.tooltip.template = '<div>$template{value}</div>'; range.refresh(); }); it('checking with tooltip template with sample data', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: string = getElement('tooltip_container_leftTooltipparent_template').innerHTML; let rightValue: string = getElement('tooltip_container_leftTooltipparent_template').innerHTML; expect(leftValue === rightValue).toBe(true); done(); }; range.tooltipRender = null; range.tooltip.template = '<div>${start}</div>'; range.refresh(); }); it('checking highcontrast theme', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; // expect(getElement('tooltip_container_leftTooltip_path').getAttribute('fill')).toBe('#ffffff'); // expect(getElement('tooltip_container_rightTooltip_path').getAttribute('fill')).toBe('#ffffff'); // expect(getElement('tooltip_container_leftTooltip_text').children[0].getAttribute('fill')).toBe('#000000'); // expect(getElement('tooltip_container_rightTooltip_text').children[0].getAttribute('fill')).toBe('#000000'); done(); }; range.tooltip.displayMode = 'Always'; range.theme = 'HighContrastLight'; range.tooltip.template = null; range.refresh(); }); it('checking tooltip with RTL', (done: Function) => { range.loaded = (args: object) => { element = document.getElementById('tooltip_container_RightSlider'); targetElement = <Element>element.childNodes[2]; let transform: string = element.getAttribute('transform'); let str1: string = transform.substring(transform.indexOf('(') + 1); let xValue: number = +str1.substring(0, str1.indexOf(',')); range.rangeOnMouseDown(<PointerEvent>trigger.onTouchStart(targetElement, null, null, null, null, xValue, 10)); range.mouseMove(<PointerEvent>trigger.onTouchMove(targetElement, null, null, null, null, xValue + 200, 10)); range.mouseEnd(<PointerEvent>trigger.onTouchEnd(targetElement, null, null, null, null, xValue + 200, 10)); let leftValue: string = getElement('tooltip_container_leftTooltip_text').textContent; let rightValue: string = getElement('tooltip_container_rightTooltip_text').textContent; expect(leftValue).toBe('Jun'); expect(rightValue).toBe('May'); done(); }; range.enableRtl = true; range.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) });
the_stack
import { INodeProperties } from 'n8n-workflow'; export const messageConversationOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'messageConversation', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a message in a conversation', }, { name: 'Delete', value: 'delete', description: 'Delete a message in a conversation', }, { name: 'Get', value: 'get', description: 'Get a message in a conversation', }, { name: 'Get All', value: 'getAll', description: 'Get all messages in a conversation', }, { name: 'Update', value: 'update', description: 'Update a message in a conversation', }, ], default: 'create', description: 'The operation to perform.', }, ]; export const messageConversationFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* messageConversation:create */ /* -------------------------------------------------------------------------- */ { displayName: 'Workspace ID', name: 'workspaceId', type: 'options', typeOptions: { loadOptionsMethod: 'getWorkspaces', }, default: '', displayOptions: { show: { operation: [ 'create', ], resource: [ 'messageConversation', ], }, }, required: true, description: 'The ID of the workspace.', }, { displayName: 'Conversation ID', name: 'conversationId', type: 'options', typeOptions: { loadOptionsMethod: 'getConversations', loadOptionsDependsOn: [ 'workspaceId', ], }, default: '', displayOptions: { show: { operation: [ 'create', ], resource: [ 'messageConversation', ], }, }, required: true, description: 'The ID of the conversation.', }, { displayName: 'Content', name: 'content', type: 'string', default: '', displayOptions: { show: { operation: [ 'create', ], resource: [ 'messageConversation', ], }, }, description: 'The content of the new message. Mentions can be used as <code>[Name](twist-mention://user_id)</code> for users or <code>[Group name](twist-group-mention://group_id)</code> for groups.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', displayOptions: { show: { operation: [ 'create', ], resource: [ 'messageConversation', ], }, }, default: {}, description: 'Other options to set.', placeholder: 'Add options', options: [ { displayName: 'Actions', name: 'actionsUi', type: 'fixedCollection', default: {}, placeholder: 'Add Action', typeOptions: { multipleValues: true, }, options: [ { displayName: 'Action', name: 'actionValues', values: [ { displayName: 'Action', name: 'action', type: 'options', description: 'The action of the button.', options: [ { name: 'Open URL', value: 'open_url', }, { name: 'Prefill Message', value: 'prefill_message', }, { name: 'Send Reply', value: 'send_reply', }, ], default: '', }, { displayName: 'Button Text', name: 'button_text', type: 'string', description: 'The text for the action button.', default: '', }, { displayName: 'Message', name: 'message', type: 'string', displayOptions: { show: { action: [ 'send_reply', 'prefill_message', ], }, }, description: 'The text for the action button.', default: '', }, { displayName: 'Type', name: 'type', type: 'options', description: 'The type of the button. (Currently only <code>action</code> is available).', options: [ { name: 'Action', value: 'action', }, ], default: '', }, { displayName: 'URL', name: 'url', type: 'string', displayOptions: { show: { action: [ 'open_url', ], }, }, description: 'URL to redirect.', default: '', }, ], }, ], }, { displayName: 'Attachments', name: 'binaryProperties', type: 'string', default: 'data', description: 'Name of the property that holds the binary data. Multiple can be defined separated by comma.', }, { displayName: 'Direct Mentions', name: 'direct_mentions', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getUsers', }, default: [], description: 'The users that are directly mentioned.', }, // { // displayName: 'Direct Group Mentions ', // name: 'direct_group_mentions', // type: 'multiOptions', // typeOptions: { // loadOptionsMethod: 'getGroups', // }, // default: [], // description: 'The groups that are directly mentioned.', // }, ], }, /* -------------------------------------------------------------------------- */ /* messageConversation:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Workspace ID', name: 'workspaceId', type: 'options', typeOptions: { loadOptionsMethod: 'getWorkspaces', }, default: '', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'messageConversation', ], }, }, required: true, description: 'The ID of the workspace.', }, { displayName: 'Conversation ID', name: 'conversationId', type: 'options', typeOptions: { loadOptionsMethod: 'getConversations', loadOptionsDependsOn: [ 'workspaceId', ], }, default: '', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'messageConversation', ], }, }, required: true, description: 'The ID of the conversation.', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', displayOptions: { show: { operation: [ 'getAll', ], resource: [ 'messageConversation', ], }, }, default: {}, description: 'Other options to set.', options: [ { displayName: 'Ending Object Index', name: 'to_obj_index', type: 'number', default: 50, description: 'Limit messages ending at the specified object index.', }, { displayName: 'Limit', name: 'limit', type: 'number', default: 50, description: 'Limits the number of messages returned.', }, { displayName: 'Order By', name: 'order_by', type: 'options', default: 'ASC', description: 'The order of the conversations returned - one of DESC or ASC.', options: [ { name: 'ASC', value: 'ASC', }, { name: 'DESC', value: 'DESC', }, ], }, { displayName: 'Starting Object Index', name: 'from_obj_index', type: 'number', default: 0, description: 'Limit messages starting at the specified object index.', }, ], }, /* -------------------------------------------------------------------------- */ /* messageConversation:get/delete/update */ /* -------------------------------------------------------------------------- */ { displayName: 'Message ID', name: 'id', type: 'string', default: '', displayOptions: { show: { operation: [ 'delete', 'get', ], resource: [ 'messageConversation', ], }, }, required: true, description: 'The ID of the conversation message.', }, /* -------------------------------------------------------------------------- */ /* messageConversation:update */ /* -------------------------------------------------------------------------- */ { displayName: 'Conversation Message ID', name: 'id', type: 'string', default: '', displayOptions: { show: { operation: [ 'update', ], resource: [ 'messageConversation', ], }, }, required: true, description: 'The ID of the conversation message.', }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', displayOptions: { show: { operation: [ 'update', ], resource: [ 'messageConversation', ], }, }, default: {}, description: 'Other options to set.', options: [ { displayName: 'Actions', name: 'actionsUi', type: 'fixedCollection', default: {}, placeholder: 'Add Action', typeOptions: { multipleValues: true, }, options: [ { displayName: 'Action', name: 'actionValues', values: [ { displayName: 'Action', name: 'action', type: 'options', description: 'The action of the button.', options: [ { name: 'Open URL', value: 'open_url', }, { name: 'Prefill Message', value: 'prefill_message', }, { name: 'Send Reply', value: 'send_reply', }, ], default: '', }, { displayName: 'Button Text', name: 'button_text', type: 'string', description: 'The text for the action button.', default: '', }, { displayName: 'Message', name: 'message', type: 'string', displayOptions: { show: { action: [ 'send_reply', 'prefill_message', ], }, }, description: 'The text for the action button.', default: '', }, { displayName: 'Type', name: 'type', type: 'options', description: 'The type of the button. (Currently only <code>action</code> is available).', options: [ { name: 'Action', value: 'action', }, ], default: '', }, { displayName: 'URL', name: 'url', type: 'string', displayOptions: { show: { action: [ 'open_url', ], }, }, description: 'URL to redirect.', default: '', }, ], }, ], }, { displayName: 'Attachments', name: 'binaryProperties', type: 'string', default: 'data', description: 'Name of the property that holds the binary data. Multiple can be defined separated by comma.', }, { displayName: 'Content', name: 'content', type: 'string', default: '', description: 'The content of the new message. Mentions can be used as <code>[Name](twist-mention://user_id)</code> for users or <code>[Group name](twist-group-mention://group_id)</code> for groups.', }, { displayName: 'Direct Mentions', name: 'direct_mentions', type: 'multiOptions', typeOptions: { loadOptionsMethod: 'getUsers', }, default: [], description: 'The users that are directly mentioned.', }, ], }, ];
the_stack
import { Document } from '../model/document'; import { DocumentKey } from '../model/document_key'; import { FieldPath, ResourcePath } from '../model/path'; import { arrayValueContains, canonicalId, isArray, isReferenceValue, typeOrder, valueCompare, valueEquals } from '../model/values'; import { Value as ProtoValue } from '../protos/firestore_proto_api'; import { debugAssert, debugCast, fail } from '../util/assert'; import { isNullOrUndefined } from '../util/types'; /** * A Target represents the WatchTarget representation of a Query, which is used * by the LocalStore and the RemoteStore to keep track of and to execute * backend queries. While a Query can represent multiple Targets, each Targets * maps to a single WatchTarget in RemoteStore and a single TargetData entry * in persistence. */ export interface Target { readonly path: ResourcePath; readonly collectionGroup: string | null; readonly orderBy: OrderBy[]; readonly filters: Filter[]; readonly limit: number | null; readonly startAt: Bound | null; readonly endAt: Bound | null; } // Visible for testing export class TargetImpl implements Target { memoizedCanonicalId: string | null = null; constructor( readonly path: ResourcePath, readonly collectionGroup: string | null = null, readonly orderBy: OrderBy[] = [], readonly filters: Filter[] = [], readonly limit: number | null = null, readonly startAt: Bound | null = null, readonly endAt: Bound | null = null ) {} } /** * Initializes a Target with a path and optional additional query constraints. * Path must currently be empty if this is a collection group query. * * NOTE: you should always construct `Target` from `Query.toTarget` instead of * using this factory method, because `Query` provides an implicit `orderBy` * property. */ export function newTarget( path: ResourcePath, collectionGroup: string | null = null, orderBy: OrderBy[] = [], filters: Filter[] = [], limit: number | null = null, startAt: Bound | null = null, endAt: Bound | null = null ): Target { return new TargetImpl( path, collectionGroup, orderBy, filters, limit, startAt, endAt ); } export function canonifyTarget(target: Target): string { const targetImpl = debugCast(target, TargetImpl); if (targetImpl.memoizedCanonicalId === null) { let canonicalId = targetImpl.path.canonicalString(); if (targetImpl.collectionGroup !== null) { canonicalId += '|cg:' + targetImpl.collectionGroup; } canonicalId += '|f:'; canonicalId += targetImpl.filters.map(f => canonifyFilter(f)).join(','); canonicalId += '|ob:'; canonicalId += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(','); if (!isNullOrUndefined(targetImpl.limit)) { canonicalId += '|l:'; canonicalId += targetImpl.limit!; } if (targetImpl.startAt) { canonicalId += '|lb:'; canonicalId += canonifyBound(targetImpl.startAt); } if (targetImpl.endAt) { canonicalId += '|ub:'; canonicalId += canonifyBound(targetImpl.endAt); } targetImpl.memoizedCanonicalId = canonicalId; } return targetImpl.memoizedCanonicalId; } export function stringifyTarget(target: Target): string { let str = target.path.canonicalString(); if (target.collectionGroup !== null) { str += ' collectionGroup=' + target.collectionGroup; } if (target.filters.length > 0) { str += `, filters: [${target.filters .map(f => stringifyFilter(f)) .join(', ')}]`; } if (!isNullOrUndefined(target.limit)) { str += ', limit: ' + target.limit; } if (target.orderBy.length > 0) { str += `, orderBy: [${target.orderBy .map(o => stringifyOrderBy(o)) .join(', ')}]`; } if (target.startAt) { str += ', startAt: ' + canonifyBound(target.startAt); } if (target.endAt) { str += ', endAt: ' + canonifyBound(target.endAt); } return `Target(${str})`; } export function targetEquals(left: Target, right: Target): boolean { if (left.limit !== right.limit) { return false; } if (left.orderBy.length !== right.orderBy.length) { return false; } for (let i = 0; i < left.orderBy.length; i++) { if (!orderByEquals(left.orderBy[i], right.orderBy[i])) { return false; } } if (left.filters.length !== right.filters.length) { return false; } for (let i = 0; i < left.filters.length; i++) { if (!filterEquals(left.filters[i], right.filters[i])) { return false; } } if (left.collectionGroup !== right.collectionGroup) { return false; } if (!left.path.isEqual(right.path)) { return false; } if (!boundEquals(left.startAt, right.startAt)) { return false; } return boundEquals(left.endAt, right.endAt); } export function isDocumentTarget(target: Target): boolean { return ( DocumentKey.isDocumentKey(target.path) && target.collectionGroup === null && target.filters.length === 0 ); } export abstract class Filter { abstract matches(doc: Document): boolean; } export const enum Operator { LESS_THAN = '<', LESS_THAN_OR_EQUAL = '<=', EQUAL = '==', NOT_EQUAL = '!=', GREATER_THAN = '>', GREATER_THAN_OR_EQUAL = '>=', ARRAY_CONTAINS = 'array-contains', IN = 'in', NOT_IN = 'not-in', ARRAY_CONTAINS_ANY = 'array-contains-any' } /** * The direction of sorting in an order by. */ export const enum Direction { ASCENDING = 'asc', DESCENDING = 'desc' } export class FieldFilter extends Filter { protected constructor( public field: FieldPath, public op: Operator, public value: ProtoValue ) { super(); } /** * Creates a filter based on the provided arguments. */ static create( field: FieldPath, op: Operator, value: ProtoValue ): FieldFilter { if (field.isKeyField()) { if (op === Operator.IN || op === Operator.NOT_IN) { return this.createKeyFieldInFilter(field, op, value); } else { debugAssert( isReferenceValue(value), 'Comparing on key, but filter value not a RefValue' ); debugAssert( op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY, `'${op.toString()}' queries don't make sense on document keys.` ); return new KeyFieldFilter(field, op, value); } } else if (op === Operator.ARRAY_CONTAINS) { return new ArrayContainsFilter(field, value); } else if (op === Operator.IN) { debugAssert( isArray(value), 'IN filter has invalid value: ' + value.toString() ); return new InFilter(field, value); } else if (op === Operator.NOT_IN) { debugAssert( isArray(value), 'NOT_IN filter has invalid value: ' + value.toString() ); return new NotInFilter(field, value); } else if (op === Operator.ARRAY_CONTAINS_ANY) { debugAssert( isArray(value), 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString() ); return new ArrayContainsAnyFilter(field, value); } else { return new FieldFilter(field, op, value); } } private static createKeyFieldInFilter( field: FieldPath, op: Operator.IN | Operator.NOT_IN, value: ProtoValue ): FieldFilter { debugAssert( isArray(value), `Comparing on key with ${op.toString()}` + ', but filter value not an ArrayValue' ); debugAssert( (value.arrayValue.values || []).every(elem => isReferenceValue(elem)), `Comparing on key with ${op.toString()}` + ', but an array value was not a RefValue' ); return op === Operator.IN ? new KeyFieldInFilter(field, value) : new KeyFieldNotInFilter(field, value); } matches(doc: Document): boolean { const other = doc.data.field(this.field); // Types do not have to match in NOT_EQUAL filters. if (this.op === Operator.NOT_EQUAL) { return ( other !== null && this.matchesComparison(valueCompare(other!, this.value)) ); } // Only compare types with matching backend order (such as double and int). return ( other !== null && typeOrder(this.value) === typeOrder(other) && this.matchesComparison(valueCompare(other, this.value)) ); } protected matchesComparison(comparison: number): boolean { switch (this.op) { case Operator.LESS_THAN: return comparison < 0; case Operator.LESS_THAN_OR_EQUAL: return comparison <= 0; case Operator.EQUAL: return comparison === 0; case Operator.NOT_EQUAL: return comparison !== 0; case Operator.GREATER_THAN: return comparison > 0; case Operator.GREATER_THAN_OR_EQUAL: return comparison >= 0; default: return fail('Unknown FieldFilter operator: ' + this.op); } } isInequality(): boolean { return ( [ Operator.LESS_THAN, Operator.LESS_THAN_OR_EQUAL, Operator.GREATER_THAN, Operator.GREATER_THAN_OR_EQUAL, Operator.NOT_EQUAL, Operator.NOT_IN ].indexOf(this.op) >= 0 ); } } export function canonifyFilter(filter: Filter): string { debugAssert( filter instanceof FieldFilter, 'canonifyFilter() only supports FieldFilters' ); // TODO(b/29183165): Technically, this won't be unique if two values have // the same description, such as the int 3 and the string "3". So we should // add the types in here somehow, too. return ( filter.field.canonicalString() + filter.op.toString() + canonicalId(filter.value) ); } export function filterEquals(f1: Filter, f2: Filter): boolean { debugAssert( f1 instanceof FieldFilter && f2 instanceof FieldFilter, 'Only FieldFilters can be compared' ); return ( f1.op === f2.op && f1.field.isEqual(f2.field) && valueEquals(f1.value, f2.value) ); } /** Returns a debug description for `filter`. */ export function stringifyFilter(filter: Filter): string { debugAssert( filter instanceof FieldFilter, 'stringifyFilter() only supports FieldFilters' ); return `${filter.field.canonicalString()} ${filter.op} ${canonicalId( filter.value )}`; } /** Filter that matches on key fields (i.e. '__name__'). */ export class KeyFieldFilter extends FieldFilter { private readonly key: DocumentKey; constructor(field: FieldPath, op: Operator, value: ProtoValue) { super(field, op, value); debugAssert( isReferenceValue(value), 'KeyFieldFilter expects a ReferenceValue' ); this.key = DocumentKey.fromName(value.referenceValue); } matches(doc: Document): boolean { const comparison = DocumentKey.comparator(doc.key, this.key); return this.matchesComparison(comparison); } } /** Filter that matches on key fields within an array. */ export class KeyFieldInFilter extends FieldFilter { private readonly keys: DocumentKey[]; constructor(field: FieldPath, value: ProtoValue) { super(field, Operator.IN, value); this.keys = extractDocumentKeysFromArrayValue(Operator.IN, value); } matches(doc: Document): boolean { return this.keys.some(key => key.isEqual(doc.key)); } } /** Filter that matches on key fields not present within an array. */ export class KeyFieldNotInFilter extends FieldFilter { private readonly keys: DocumentKey[]; constructor(field: FieldPath, value: ProtoValue) { super(field, Operator.NOT_IN, value); this.keys = extractDocumentKeysFromArrayValue(Operator.NOT_IN, value); } matches(doc: Document): boolean { return !this.keys.some(key => key.isEqual(doc.key)); } } function extractDocumentKeysFromArrayValue( op: Operator.IN | Operator.NOT_IN, value: ProtoValue ): DocumentKey[] { debugAssert( isArray(value), 'KeyFieldInFilter/KeyFieldNotInFilter expects an ArrayValue' ); return (value.arrayValue?.values || []).map(v => { debugAssert( isReferenceValue(v), `Comparing on key with ${op.toString()}, but an array value was not ` + `a ReferenceValue` ); return DocumentKey.fromName(v.referenceValue); }); } /** A Filter that implements the array-contains operator. */ export class ArrayContainsFilter extends FieldFilter { constructor(field: FieldPath, value: ProtoValue) { super(field, Operator.ARRAY_CONTAINS, value); } matches(doc: Document): boolean { const other = doc.data.field(this.field); return isArray(other) && arrayValueContains(other.arrayValue, this.value); } } /** A Filter that implements the IN operator. */ export class InFilter extends FieldFilter { constructor(field: FieldPath, value: ProtoValue) { super(field, Operator.IN, value); debugAssert(isArray(value), 'InFilter expects an ArrayValue'); } matches(doc: Document): boolean { const other = doc.data.field(this.field); return other !== null && arrayValueContains(this.value.arrayValue!, other); } } /** A Filter that implements the not-in operator. */ export class NotInFilter extends FieldFilter { constructor(field: FieldPath, value: ProtoValue) { super(field, Operator.NOT_IN, value); debugAssert(isArray(value), 'NotInFilter expects an ArrayValue'); } matches(doc: Document): boolean { if ( arrayValueContains(this.value.arrayValue!, { nullValue: 'NULL_VALUE' }) ) { return false; } const other = doc.data.field(this.field); return other !== null && !arrayValueContains(this.value.arrayValue!, other); } } /** A Filter that implements the array-contains-any operator. */ export class ArrayContainsAnyFilter extends FieldFilter { constructor(field: FieldPath, value: ProtoValue) { super(field, Operator.ARRAY_CONTAINS_ANY, value); debugAssert(isArray(value), 'ArrayContainsAnyFilter expects an ArrayValue'); } matches(doc: Document): boolean { const other = doc.data.field(this.field); if (!isArray(other) || !other.arrayValue.values) { return false; } return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue!, val) ); } } /** * Represents a bound of a query. * * The bound is specified with the given components representing a position and * whether it's just before or just after the position (relative to whatever the * query order is). * * The position represents a logical index position for a query. It's a prefix * of values for the (potentially implicit) order by clauses of a query. * * Bound provides a function to determine whether a document comes before or * after a bound. This is influenced by whether the position is just before or * just after the provided values. */ export class Bound { constructor(readonly position: ProtoValue[], readonly before: boolean) {} } export function canonifyBound(bound: Bound): string { // TODO(b/29183165): Make this collision robust. return `${bound.before ? 'b' : 'a'}:${bound.position .map(p => canonicalId(p)) .join(',')}`; } /** * An ordering on a field, in some Direction. Direction defaults to ASCENDING. */ export class OrderBy { constructor( readonly field: FieldPath, readonly dir: Direction = Direction.ASCENDING ) {} } export function canonifyOrderBy(orderBy: OrderBy): string { // TODO(b/29183165): Make this collision robust. return orderBy.field.canonicalString() + orderBy.dir; } export function stringifyOrderBy(orderBy: OrderBy): string { return `${orderBy.field.canonicalString()} (${orderBy.dir})`; } export function orderByEquals(left: OrderBy, right: OrderBy): boolean { return left.dir === right.dir && left.field.isEqual(right.field); } /** * Returns true if a document sorts before a bound using the provided sort * order. */ export function sortsBeforeDocument( bound: Bound, orderBy: OrderBy[], doc: Document ): boolean { debugAssert( bound.position.length <= orderBy.length, "Bound has more components than query's orderBy" ); let comparison = 0; for (let i = 0; i < bound.position.length; i++) { const orderByComponent = orderBy[i]; const component = bound.position[i]; if (orderByComponent.field.isKeyField()) { debugAssert( isReferenceValue(component), 'Bound has a non-key value where the key path is being used.' ); comparison = DocumentKey.comparator( DocumentKey.fromName(component.referenceValue), doc.key ); } else { const docValue = doc.data.field(orderByComponent.field); debugAssert( docValue !== null, 'Field should exist since document matched the orderBy already.' ); comparison = valueCompare(component, docValue); } if (orderByComponent.dir === Direction.DESCENDING) { comparison = comparison * -1; } if (comparison !== 0) { break; } } return bound.before ? comparison <= 0 : comparison < 0; } export function boundEquals(left: Bound | null, right: Bound | null): boolean { if (left === null) { return right === null; } else if (right === null) { return false; } if ( left.before !== right.before || left.position.length !== right.position.length ) { return false; } for (let i = 0; i < left.position.length; i++) { const leftPosition = left.position[i]; const rightPosition = right.position[i]; if (!valueEquals(leftPosition, rightPosition)) { return false; } } return true; }
the_stack
module TDev { export module Revisions { declare var io; // ---------- revisionservice urls export function revisionservice_http(): string { return revision_service_url; } var revision_service_url: string = "https://storage.touchdevelop.com/sessions"; export function parseUrlParameters(url: string) { if (/altrevserv3/.test(url)) revision_service_url = "http://localhost:843/sessions3"; else if (/altrevserv2/.test(url)) revision_service_url = "http://localhost:843/sessions2"; else if (/altrevserv1/.test(url)) revision_service_url = "http://localhost:843/sessions1"; else if (/altrevserv/.test(url)) revision_service_url = "http://localhost:843/sessions"; else if (/simrevserv1/.test(url)) revision_service_url = "http://127.0.0.1:82/sessions1"; else if (/simrevserv/.test(url)) revision_service_url = "http://127.0.0.1:82/sessions"; else if (/revserv=/.test(url)) { var myRe = new RegExp("revserv=([^?&#]+)", "i"); var myArray = myRe.exec(url); revision_service_url = "https://" + myArray[1] + "/sessions"; } } // ---------- revisionservice session identifiers and permissions export function localsessionid(scriptguid: string) { return "L" + scriptguid; } export function nodesessionid(guid: string): string { return "userid" + "0pn" + letterify(guid) } export function justmesessionid(userid: string, guid: string): string { return userid + "0pr" + letterify(guid) } export function everyonesessionid(author: string, scriptname: string) { return author + "0pu" + scripthash(author, scriptname); } export function make_astsessionid(userid:string) { return userid + "0pa" + letterify(Util.guidGen()); } export function scripthash(author: string, title: string) { return letterify(author + title); } export function publicpermission(script?: string): string { return "users:*=W" + (script ? " scripts:" + (script) : ""); } export function broadcastpermission(script?: string): string { return "users:*=R" + (script ? " scripts:" + (script) : ""); } export function privatepermission(script?: string): string { return "users:" + (script ? " scripts:" + (script) : ""); } export function letterify(s: string): string { var n = Math.floor(Math.abs(Util.getStableHashCode(s))); var c = ""; while (n > 0) { var d = n % 26; n = Math.floor(n / 26); c = c + String.fromCharCode(97 + d) } return c; } // ---------- revisionservice authentication tokens // get cached token, or fresh token from touchdevelop.com export function getRevisionServiceTokenAsync(forcefreshtoken:boolean = false): Promise { var token = getRevisionServiceToken(forcefreshtoken); if (token) return Promise.wrap(token); else return refreshRevisionServiceTokenAsync(); } // get cached token, or undefined function getRevisionServiceToken(forcefreshtoken: boolean = false) { var expires = parseInt(window.localStorage["rs_token_expires"] || "0"); if (forcefreshtoken || expires > 0 && Date.now() + 600 > expires) { setRevisionServiceToken(undefined); return undefined; } return window.localStorage["rs_access_token"]; } function setRevisionServiceToken(token: string, expires_in = 0) { if (!token) { Util.log('revision service access token expired'); window.localStorage.removeItem("rs_access_token"); window.localStorage.removeItem("rs_token_expires"); } else { Util.log('received revision service token (expires in ' + (expires_in * 1000).toString() + 'ms)'); window.localStorage["rs_access_token"] = token; if (expires_in > 0) window.localStorage["rs_token_expires"] = Date.now() + expires_in * 1000; else window.localStorage.removeItem("rs_token_expires"); } } function refreshRevisionServiceTokenAsync(): Promise { if (Cloud.isOffline()) return Promise.wrapError(lf("cloud is offline")); return Cloud.authenticateAsync(lf("cloud data")) .then((authenticated) => { if (authenticated) { var userid = Cloud.getUserId(); Util.log('asking TD server for revision service access token'); return Cloud.postPrivateApiAsync("me/storage/access_token", {}) .then( (json) => { var token = json["access_token"]; var expires_in = json["expires_in"]; setRevisionServiceToken(token, expires_in); return token; }, (error) => { Util.log('could not get revision service token, web request failed'); return Promise.wrapError("Failed to receive revision service token"); } ); } else { Util.log('could not get revision service token, user not signed in'); return Promise.wrapError("User not signed in"); } }); } // ----------- revision service API // query server for session info export function getServerInfoAsync(id: string): Promise { // json return Revisions.getRevisionServiceTokenAsync().then( (token) => { if (Cloud.isOffline()) return Promise.wrapError("Cloud is offline"); var url = Revisions.revisionservice_http() + "/" + id + "/info?user=" + Cloud.getUserId() + "&access_token=" + encodeURIComponent(token); return Util.httpRequestAsync(url, "GET", undefined).then( (response) => RT.JsonObject.mk(response, RT.Time.log), (error) => undefined ); }, (error) => undefined ); } // query server for existing sessions export function queryMySessionsOnRevisionServerAsync(rt: Runtime, filter_based_on_current_script = false): Promise { var userid = Cloud.getUserId(); return getRevisionServiceTokenAsync().then((token) => { if (Cloud.isOffline()) return Promise.wrapError("Cloud is offline"); var url = revisionservice_http() + "?user=" + userid + "&access_token=" + encodeURIComponent(token); if (filter_based_on_current_script) { url = url + "&guidhash=" + encodeURIComponent(letterify(rt.sessions.getScriptGuid())) + "&scripthash=" + encodeURIComponent(scripthash(rt.sessions.getScriptAuthor(), rt.sessions.getScriptName())); } return Util.httpRequestAsync(url, "GET", undefined).then((s) => { var json = JSON.parse(s); var sessions = new Array<RT.CloudSession>(); for (var f in json) if (json.hasOwnProperty(f)) { var cs = new RT.CloudSession(); cs._id = f; if (!cs.validate()) continue; cs.serverinfo = <Revisions.ServerJson> json[f]; cs._title = cs.serverinfo.title; cs._permissions = ""; // not meant for creating fresh sessions sessions.push(cs); } return sessions; }); }); } // query local storage for cached sessions export function queryCachedSessionsAsync(filter_based_on_current_script: boolean, rt: Runtime): Promise // of CloudSession[] { var sessions: RT.CloudSession[] = []; var confirmedsessions: RT.CloudSession[] = []; return Storage.getTableAsync("Sessions").then((table) => { return table.getValueAsync("%").then( (val: string) => { var sessionlist = (val || "").split(" "); sessionlist.forEach((id) => { var cs = new RT.CloudSession(); cs._id = id; if (cs.validate()) { if (filter_based_on_current_script) { var privatehash = letterify(rt.sessions.getScriptGuid()); var scripthash = Revisions.scripthash(rt.sessions.getScriptAuthor(), rt.sessions.getScriptName()); if (cs.tag === "pr" && cs.guidhash != privatehash) return; if (cs.tag === "pu" && cs.guidhash != scripthash) return; if (cs.tag === "pn") return; if (cs.tag[0] === "c" && cs.guidhash[0] === "s" && cs.guidhash.lastIndexOf(scripthash, 1) !== 1) return; } sessions.push(cs); } }); var keys = sessions.map((s, idx, arr) => s._id + "/S"); return table.getItemsAsync(keys).then( (results) => { for (var i = 0; i < sessions.length; i++) { var cs = sessions[i]; var val = results[keys[i]]; if (val) { var json = JSON.parse(val); Util.assert(cs._id === json.servername); Util.assert(cs._id === json.localname); cs.localname = cs._id; cs._title = json.description; cs._permissions = json.permissions; cs.membernumber = json.membernumber; cs.enable_sync = json.enable_sync; confirmedsessions.push(cs); } else { //SEBTODO remove entries pointing to non-existing sessions from stored list } } return confirmedsessions; }); }); }); } // delete session locally and on server export function deleteSessionAsync(desc: ISessionParams, rt:Runtime): Promise { var tasks = []; tasks.push(Slot.deleteSessionFileAsync(rt.sessions, desc)); // delete on server if (!desc.nodeserver && desc.servername) { var pos = desc.servername.indexOf("0"); if (pos > 3 && pos < desc.servername.length - 4 && desc.servername.substr(0, pos) == Cloud.getUserId()) { tasks.push(Slot.queueSessionWork(desc.localname, "deleting session on server", () => getRevisionServiceTokenAsync().then((token) => { if (Cloud.isOffline()) return Promise.wrapError("Cloud is offline"); var url = revisionservice_http() + "/" + desc.servername + "?user=" + Cloud.getUserId() + "&access_token=" + encodeURIComponent(token); var deleteonserver = Util.httpRequestAsync(url, "DELETE", undefined); return deleteonserver; }))); } } return Promise.join(tasks); } // ----------- functions for safe loading/unloading of sessions w/ local persistence export interface ISessionParams { nodeserver: string; servername: string; localname: string; user: string; permissions: string; title: string; script: string; readonly: boolean; } export interface ISessionContext { url_ws(): string; url_http(): string; tokensource(forcefreshtoken: boolean): Promise; clearCachedData(); updateStatus(); createSession(params: ISessionParams): Revisions.ClientSession; afterload(): Promise; onDoorBell(); } // encapsulate local storage interaction for sessions export class Slot { constructor( public context: ISessionContext, public getCurrent: () => Revisions.ClientSession, public setCurrent: (val?: Revisions.ClientSession) => void ) { } // mechanisms for preventing concurrent async operations on the same session private static slots = {}; // localname -> slot private static busysessions = {}; // localname -> promise public connect(desc: ISessionParams, loadonly=false): Promise { // void, completes when session loaded var cs = this.getCurrent(); if (cs) { if (cs.servername === desc.servername && cs.localname === desc.localname && (cs.user === desc.user || cs.user === "")) { // session already current. if (cs.script !== desc.script || cs.readonly !== desc.readonly || cs.user !== desc.user) { // change requires fresh connection cs.script = desc.script; cs.readonly = desc.readonly; cs.user = desc.user; if (cs.loaded && (cs.servername != "")) { cs.disconnect(); cs.try_reconnect_in(1000); } } this.context.updateStatus(); if (!cs.loadtask.isPending()) this.context.afterload(); return cs.loadtask; } this.disconnect(false, "unload previous session"); } // check if another slot has the same session open if (desc.localname) { var openedby = Slot.slots[desc.localname]; openedby && openedby.disconnect(false, "opening session in different context"); } // connect cs = this.context.createSession(desc); this.setCurrent(cs); if (cs.localname) Slot.slots[cs.localname] = this; cs.user_set_doorbell(() => this.context.onDoorBell()); var loadtask = this.loadSessionAsync(cs); return loadtask; } public disconnect(deletelocalstorage: boolean, msg: string): Promise { var cs = this.getCurrent(); if (!cs) return Promise.as(); cs.user_unlink(); cs.user_set_doorbell(() => undefined); this.setCurrent(undefined); if (cs.localname && Slot.slots[cs.localname] === this) Slot.slots[cs.localname] = undefined; var p = Slot.queueSessionWork(cs.localname, "unloading session" + (msg ? " ("+msg+")" : ""), () => { var promise = cs.closeAsync(deletelocalstorage); promise.done(); return promise; }); this.context.clearCachedData(); this.context.updateStatus(); return p; } private loadSessionAsync(session: ClientSession): Promise { Util.assert(session !== undefined); Util.assert(session.loadtask === undefined); var loadtask = Slot.queueSessionWork(session.localname, "loading session", () => session.loadAsync(() => this.context.afterload())); loadtask.thenalways(() => { this.context.updateStatus(); if (session.loaded) { if (session.servername != "") return session.connect(this.context.url_ws(), (needfreshtoken) => this.context.tokensource(needfreshtoken)); } else session.log("!! failure while loading session"); }).done(); this.context.clearCachedData(); this.context.updateStatus(); return loadtask; } public static createSessionFileAsync(context: ISessionContext, desc: ISessionParams): Promise { // ClientSession Util.assert(desc.localname && !Slot.slots[desc.localname]); var s = context.createSession(desc); return Slot.queueSessionWork(desc.localname, "creating session", () => { return s.loadAsync().then(() => s.closeAsync(false)).then(() => s, () => undefined); }); } public static deleteSessionFileAsync(context:ISessionContext, desc: ISessionParams): Promise { // check if this session is open in some slot - if so, delete by closing it var openedby = desc.localname && Slot.slots[desc.localname]; if (openedby) return openedby.disconnect(true); // delete by opening and then closing var s = context.createSession(desc); return Slot.queueSessionWork(desc.localname, "deleting session cache", () => { return s.loadAsync().then(() => s.closeAsync(true)); }); } public static queueSessionWork(localname: string, description: string, work: () => Promise): Promise { var waitfor = Slot.busysessions[localname]; if (waitfor === undefined) waitfor = Promise.wrap(undefined); else Util.log("[" + localname + "] queued " + description); waitfor = waitfor.then(() => { Util.log("[" + localname + "] started " + description); return work().then((x) => { Slot.busysessions[localname] = undefined; Util.log("[" + localname + "] finished " + description); return x; }, (e) => { Slot.busysessions[localname] = undefined; Util.log("[" + localname + "] unsuccessfully terminated " + description); }); }); Slot.busysessions[localname] = (!!waitfor._state) ? undefined : waitfor; return waitfor; } } export class Sessions implements ISessionContext { public rt: Runtime; public url_http(): string { return (this.current_nodeserver || revisionservice_http()); } public url_ws(): string { return this.url_http().replace("http", "ws"); } public tokensource(forcefreshtoken:boolean): Promise { if (this.current_nodeserver) return Promise.as(this._authtoken || "token"); else return Revisions.getRevisionServiceTokenAsync(forcefreshtoken); } public _authtoken: string; //HACK public setAccessToken(token: string) { this._authtoken = token; } constructor(public wsServer: WebSocketServerWrapper = undefined) { } public isNodeServer(): boolean { return this.wsServer !== undefined; } public isNodeClient(): boolean { return this.current_nodeserver && this.wsServer === undefined; } public hasNodeConnection(): boolean { return this.current_nodeserver && this.CurrentSession !== undefined && (<NodeSession>this.CurrentSession).hasNodeConnection(); } public nodeConnectionPending(): boolean { return false } public afterload():Promise { return undefined; } // ---------- current script context private current_userid: string; private current_scriptguid: string; private current_scriptname: string; private current_script: string; private current_scriptauthor: string; private current_nodeserver: string; public getUserId() { return this.current_userid; } public getScriptGuid() { return this.current_scriptguid; } public getScriptAuthor() { return this.current_scriptauthor; } public getScriptName() { return this.current_scriptname; } public getScript() { return this.current_script; } public getNodeServer() { return this.current_nodeserver; } public setEditorScriptContext(user, guid, title, basescript, author) { this.current_userid = user; this.current_scriptguid = guid; this.current_scriptname = title; this.current_scriptauthor = author; this.current_script = TDev.RT.CloudSession.makeScriptIdentifier(basescript, author); } public refreshFinalScriptContext(): boolean { // returns true if there were any changes var changed; var userid = Cloud.getUserId() || ""; var scriptguid = this.rt.host ? this.rt.host.currentGuid : this.current_scriptguid; var scriptname = this.rt.compiled.scriptTitle; var scriptauthor = this.rt.compiled.authorId || ""; var basescript = this.rt.compiled && this.rt.compiled.baseScriptId || ""; var script = TDev.RT.CloudSession.makeScriptIdentifier(basescript, scriptauthor); var nodeserver = this.rt.compiled.azureSite; if ((!nodeserver && this.current_userid !== userid) || this.current_script != script || this.current_scriptguid != scriptguid || this.current_scriptname != scriptname || this.current_nodeserver != nodeserver) { changed = true; //if ((this.CurrentSession || this.LocalSession) && !this.rt.isStopped()) // this.rt.stopAsync(); this.currentSessionSlot.disconnect(false, "script context changed"); this.localSessionSlot.disconnect(false, "script context changed"); } this.current_userid = userid; this.current_scriptguid = scriptguid; this.current_scriptname = scriptname; this.current_scriptauthor = scriptauthor; this.current_script = script; this.current_nodeserver = nodeserver; return changed; } public clearScriptContext(includinglocal: boolean): Promise { var tasks = []; tasks.push(this.currentSessionSlot.disconnect(false, "clear script context")); if (includinglocal) tasks.push(this.localSessionSlot.disconnect(false, "clear script context")); this.current_userid = undefined; this.current_scriptguid = undefined; this.current_scriptname = undefined; this.current_script = undefined; this.current_scriptauthor = undefined; this.current_nodeserver = undefined; return Promise.join(tasks); } // ---------- current sessions // the current cloud session public CurrentSession: ClientSession = undefined; // the local session public LocalSession: ClientSession = undefined; // get the current cloud or node session public getCurrentSession(): ClientSession { Util.assert(this.CurrentSession !== undefined); return this.CurrentSession; } // get the local session used to persist data locally public getLocalSession(): ClientSession { if (!this.isNodeServer()) { Util.assert(this.LocalSession !== undefined); return this.LocalSession; } else { Util.assert(this.CurrentSession !== undefined); return this.CurrentSession; } } // get last session that was connected (deprecated - always same as current) public getLastSession(): ClientSession { return this.CurrentSession; } private currentSessionSlot: Slot = new Slot(this, () => this.CurrentSession, (cs?: ClientSession) => this.CurrentSession = cs); private localSessionSlot: Slot = new Slot(this, () => this.LocalSession, (cs?: ClientSession) => this.LocalSession = cs); //---------- session descriptors public getJustMeSessionDescriptor(): ISessionParams { if (!this.current_userid) return undefined; return this.getCloudSessionDescriptor( justmesessionid(this.current_userid, this.current_scriptguid), "just-me session for script \"" + this.current_scriptname + "\"", privatepermission() ); } public getNodeSessionDescriptor(user:string): ISessionParams { var desc = this.getCloudSessionDescriptor( nodesessionid(this.current_scriptguid), "node session for script \"" + this.current_scriptname + "\"", publicpermission(this.current_script) ); desc.user = user; return desc; } public getEveryoneSessionDescriptor(): ISessionParams { return this.getCloudSessionDescriptor( everyonesessionid(this.current_scriptauthor, this.current_scriptname), "everyone session for script \"" + this.current_scriptname + "\"", publicpermission(this.current_script) ); } public getLocalSessionDescriptor(): ISessionParams { var desc = <ISessionParams>{}; desc.servername = ""; desc.localname = localsessionid(this.current_scriptguid); desc.user = ""; desc.title = ""; desc.permissions = ""; desc.script = this.current_script; desc.readonly = false; desc.nodeserver = ""; return desc; } public getCloudSessionDescriptor(servername: string, title: string, permissions: string): ISessionParams { var isnode = servername.indexOf("0pn") != -1; var owner = servername.substr(0, servername.indexOf("0")); var desc = <ISessionParams>{}; desc.servername = servername; desc.user = this.current_userid; desc.title = title; desc.script = this.current_script; desc.permissions = permissions; desc.nodeserver = this.current_nodeserver; desc.localname = (!isnode && Browser.isNodeJS) ? undefined : servername; desc.readonly = !isnode && (owner !== this.current_userid) && (servername.indexOf("0cr") != -1); return desc; } // management functions on sessions public disconnect() { this.currentSessionSlot.disconnect(false, "disconnect"); this.localSessionSlot.disconnect(false, "disconnect"); } public unlink() { if (this.CurrentSession) this.CurrentSession.user_unlink(); if (this.LocalSession) this.LocalSession.user_unlink(); } public scriptRestarted() { this.refreshFinalScriptContext(); } public scriptStarted(author: string) { this.refreshFinalScriptContext(); } public createSession(original: ISessionParams): ClientSession { var si = original.nodeserver ? (this.isNodeServer() ? <ClientSession> new ServerSession(original.nodeserver, original.servername, original.localname, original.user, this.rt, this.wsServer) : <ClientSession> new NodeSession(original.nodeserver, original.servername, original.localname, original.user)) : new ClientSession(original.servername, original.localname, original.user); si.permissions = original.permissions; si.title = original.title; si.script = original.script; si.readonly = original.readonly; si.user = original.user; return si; } public connectCurrent(desc: ISessionParams) : Promise { // void, completes when session loaded var isnodesession = desc.servername.indexOf("0pn") != -1; Util.assert(isnodesession == !!this.current_nodeserver, "must not mix cloud/node sessions"); Util.assert(isnodesession || !!this.current_userid, "must be signed in to connect cloud session"); Util.assert(!this.isNodeServer() || isnodesession, "can only use node session on server"); return this.currentSessionSlot.connect(desc); } public enable_script_session_mgt(): boolean { return Cloud.getUserId() && !!this.current_userid && !!this.current_scriptguid && !!this.current_scriptauthor; } // called before running the script public ensureSessionLoaded(): Promise { var sign_in = (this.current_userid || !this.rt.compiled.hasCloudData || this.current_nodeserver) ? Promise.as() : Cloud.authenticateAsync(lf("cloud data")); return sign_in.thenalways(() => { this.refreshFinalScriptContext(); var loadlocal: Promise; var loadcurrent: Promise; // load local session if (this.rt.compiled.hasLocalData && !this.isNodeServer()) { loadlocal = this.localSessionSlot.connect(this.getLocalSessionDescriptor()).thenalways(() => { if (this.LocalSession && this.LocalSession.faulted) { Util.check(false, "local data corrupted - resetting"); this.localSessionSlot.disconnect(true, "delete due to faulted load"); this.localSessionSlot.connect(this.getLocalSessionDescriptor()); } }); } else { this.localSessionSlot.disconnect(false, "no local data"); loadlocal = Promise.as(); } // load cloud session if (this.rt.compiled.hasCloudData || (this.rt.compiled.hasLocalData && this.isNodeServer())) { if (!this.current_nodeserver && !this.current_userid) loadcurrent = Promise.wrapError("cannot run this script without first signing in"); else if (!this.current_scriptguid || !this.current_scriptname || !this.current_scriptauthor || !this.current_script) Util.oops("cannot determine script info: runtime lacks information"); else { var session = this.current_nodeserver ? this.getNodeSessionDescriptor("") : (this.CurrentSession || this.getJustMeSessionDescriptor()); loadcurrent = this.connectCurrent(session); } } else { this.currentSessionSlot.disconnect(false, "no cloud session"); loadcurrent = Promise.as(); } this.updateStatus(); return Promise.join([loadlocal, loadcurrent]); }); } // called immediately before execution to re-check that everything is set up as it should be public readyForExecution(): boolean { if (this.refreshFinalScriptContext()) { Util.check(false, "script info changed between loading and execution"); return false; } if (this.rt.compiled.hasCloudData && !this.current_nodeserver && !this.current_userid) { //Util.check(false, "using cloud data but not signed in"); return false; } if (this.rt.compiled.hasLocalData && !this.isNodeServer() && !(this.LocalSession && this.LocalSession.loaded)) { Util.check(false, "failed to load local session"); return false; } if ( (this.rt.compiled.hasCloudData || (this.rt.compiled.hasLocalData && this.isNodeServer())) && !(this.CurrentSession && this.CurrentSession.loaded)) { Util.check(false, "failed to load cloud session"); return false; } if (this.LocalSession && this.LocalSession.faulted) { Util.check(false, "error loading local session from disk"); return false; } // if (this.current_nodeserver && !(this.CurrentSession && this.CurrentSession.loaded)) { // Util.check(false, "failed to load node session"); // return false; // } return true; } public stopAsync(): Promise { return Promise.as(); // sessions are kept open on client } public receive_operation(p: Packet) { if (!this.current_nodeserver) throw new Error("should not be called for unexported apps"); } public resetCurrentSession(): Promise { var session = this.CurrentSession; if (!session) return; var desc = this.getCloudSessionDescriptor(session.servername, session.title, session.permissions); this.currentSessionSlot.disconnect(true, "reset current session"); return this.currentSessionSlot.connect(desc); } public clearCurrentSession() { if (!this.CurrentSession) return; this.CurrentSession.user_clear_all(); this.clearCachedData(); } // read/write attributes of the local session public getLocalSessionAttributeAsync(key: string, rt: Runtime): Promise //string { Util.assert(!this.isNodeServer(), "cannot access attributes on server"); return this.get_attribute_lval(key, rt).then((lval) => RT.Conv.fromCloud("string", this.LocalSession.user_get_value(lval))); } public setLocalSessionAttributeAsync(key: string, value: string, rt: Runtime): Promise //void { Util.assert(!this.isNodeServer(), "cannot access attributes on server"); var op = RT.Conv.toCloud("string", value, false); return this.get_attribute_lval(key, rt).then((lval) => this.LocalSession.user_modify_lval(lval, op)); } private get_attribute_lval(key: string, rt: Runtime): Promise //Revisions.LVal { var waitfor = this.LocalSession ? Promise.as() : this.localSessionSlot.connect(this.getLocalSessionDescriptor()); return waitfor.then(() => this.LocalSession.user_get_lval(Revisions.Parser.MakeProperty(key, "attributes[]", "string"), [], [])); } // ---------- functions for node server // Queue an incoming http rest request in the async queue public queueRestRequest(sr: RT.ServerRequest) { sr._onStop = new PromiseInv(); (<any> this.rt).dispatchServerRequest(sr, sr._onStop).then((res) => { }, (err) => { RT.App.log("404 " + sr.method().toUpperCase() + " " + sr.url()) var resp = sr.getNodeRequest().tdResponse resp.writeHead(404, "API Error") resp.end(err.message) }); } // ------------ tie state changes to environment // cautious yield public yieldSession(): boolean { var somechanges = false; if (this.CurrentSession) { //CurrentSession.log("yield cloud session"); var changes = this.CurrentSession.user_yield(); if (changes) { this.updateStatus(); this.clearCachedData(); somechanges = true; } } if (this.LocalSession) { //LocalSession.log("yield local session"); var changes = this.LocalSession.user_yield(); if (changes) { this.clearCachedData(); somechanges = true; } } return somechanges; } // push status updates to recipients public updateStatus() { if (this.isNodeServer()) return; // no need to display status to user if (this.CurrentSession) { if (this.rt.host) this.rt.host.updateCloudState(true, this.CurrentSession.getCloudSession().type(), this.CurrentSession.user_get_connectionstatus(false)); TDev.RT.CloudData.refreshSessionInfo(this.CurrentSession); } else { if (this.rt.host) this.rt.host.updateCloudState(false, "", ""); } } // notify recipients of possible changes public onDoorBell() { // for node clients: eagerly & automatically reset local cache if marooned or faulted if (this.isNodeClient() && this.CurrentSession && (this.CurrentSession.marooned || this.CurrentSession.faulted)) { var s = this.CurrentSession; s.log("discard cache because it is " + (s.marooned ? "marooned" : s.faulted ? "faulted" : "")); this.currentSessionSlot.disconnect(true, "reset because " + (s.marooned ? "marooned" : s.faulted ? "faulted" : "")); this.currentSessionSlot.connect(s); } if (!Browser.isNodeJS) { this.rt.yield_when_possible(); } this.doorbelllisteners = this.doorbelllisteners.filter(listener => listener()); this.updateStatus(); } private doorbelllisteners = []; public addDoorbellListener(listener: () => boolean) { this.doorbelllisteners.push(listener); } public clearCachedData() { for (var l in this.registereddatacaches) { if (this.registereddatacaches.hasOwnProperty(l)) (<Revisions.IDataCache> this.registereddatacaches[l]).clearCachedData(); } } public registerDataCache(key: string, o: Revisions.IDataCache) { this.registereddatacaches[key] = o; } public unregisterDataCache(key: string) { delete this.registereddatacaches[key]; } private registereddatacaches = []; // ------------------ session management entry points public deleteAllLocalDataAsync(scriptguid: string): Promise { var localtask = Slot.deleteSessionFileAsync(this, this.getLocalSessionDescriptor()); if (this.current_nodeserver) { return Promise.join([ Slot.deleteSessionFileAsync(this, this.getNodeSessionDescriptor("")), localtask ]); } else { var userid = Cloud.getUserId(); if (!userid || userid !== this.current_userid || scriptguid !== this.current_scriptguid) return localtask; else { var justmesession = this.getJustMeSessionDescriptor(); var everyonesession = this.getEveryoneSessionDescriptor(); return Promise.join([ Slot.deleteSessionFileAsync(this, justmesession), Slot.deleteSessionFileAsync(this, everyonesession), localtask ]); } } } public createCustomSessionAsync(title: string, type: string): Promise { // of CloudSession Util.assert(!!this.current_userid, "must be signed in to create a cloud session"); Util.assert(!this.current_nodeserver, "cannot create sessions for cloud library"); var desc = <ISessionParams>{}; var letter = (permit_all_scripts ? "a" : "s"); var scripth = (permit_all_scripts ? "" : scripthash(this.current_scriptauthor, this.current_scriptname)); var guid = letterify(Util.guidGen()); var id; var permit_all_scripts = false; // we cut this feature. It is too confusing. May re-enable in some other way in the future. if (type === "shareable") { desc.servername = this.current_userid + "0cw" + letter + scripth + guid; desc.permissions = publicpermission(permit_all_scripts ? "" : this.current_script); } else if (type === "broadcast") { desc.servername = this.current_userid + "0cr" + letter + scripth + guid; desc.permissions = broadcastpermission(permit_all_scripts ? "" : this.current_script); } else { desc.servername = this.current_userid + "0cp" + letter + scripth + guid; desc.permissions = privatepermission(permit_all_scripts ? "" : this.current_script); } desc.localname = desc.servername; desc.readonly = false; desc.user = this.current_userid; desc.title = title; desc.nodeserver = ""; desc.script = this.current_script; return Slot.createSessionFileAsync(this, desc).then((s:ClientSession) => s.getCloudSession()); } } // data caches get notified directly to invalidate them export interface IDataCache { clearCachedData(): void; } export interface ServerJson { id: string; title: string; participants: number; owner: string; permissions: string; salt: string; percentfull: number; } //export interface OperationRequest { // operationId: number; // service: string; // actionName: string; // params: any; //} //export interface NodeResponse { // operationResponse?: OperationResponse; // cloudResponse?: CloudResponse; //} //export interface OperationResponse { // operationId: number; // value: any; //} //export interface CloudResponse { //} export enum CloudOperationType { UNKNOWN = 0, RPC = 1, OFFLINE = 2, } export interface CloudOperation { libName: string; actionName: string; paramNames: string[]; returnNames: string[]; args: any[]; uidcountstart?: number; uidcountstop?: number; opid?: number; res?: any; socket?: WebSocket; optype: CloudOperationType; } //export class ClientContext { // constructor( // public serverround: number, // public clientround: number // ) { // } //} //export class NodePacket { // constructor( // public operations: CloudOperation[], // public effects: Packet[], // public clientContext: ClientContext) { // } // public send(ws: WebSocket) { // console.log('sending to node:') // console.log(JSON.stringify(this)); // ws.send(JSON.stringify(this)); // } //} // export interface CloudQItem { // packets: Packet[]; // frame: Packet; // request: any; // socket: any; // membernumber: number; // } } export class WebSocketWrapper { constructor(public server:WebSocketServerWrapper, private request:any, private socket:WebSocket) { } public origin():string { return this.request.headers['origin']; } public path():string { return this.request.url } public accept():WebSocket { (<any>this.socket).tdWrapper = this this.server._conns.push(this.socket) var remove = () => { var conns = this.server._conns var idx = conns.indexOf(this.socket) if (idx >= 0) conns.splice(idx, 1) } this.onClose(remove) this.onError(remove) return this.socket } public reject():void { this.socket.close() } public remoteAddress():string { return (<any>this.socket).remoteAddress } public onMessage(h:(stringData:string, binaryData:any)=>void) { this.socket.addEventListener("message", (msg) => typeof msg.data == "string" ? h(msg.data, null) : h(null, msg.data), false) } public onClose(h:(code:number, reason:string)=>void) { this.socket.addEventListener("close", ev => h(ev.code, ev.reason), false) } public onError(h:(err:any)=>void) { this.socket.addEventListener("error", h, false) } public mkTdWebSocket(rt:Runtime) { if (!this.socket) this.accept() var w = new RT.WebSocket_(this.socket, rt); this.onMessage((str, buff) => { var data = str if (buff) data = RT.Buffer.fromTypedArray(buff) w.receiveMessage(RT.WebSocketMessage.mk(data)) }) this.onError(ev => { var msg = ev.message || (ev + "") RT.App.logEvent(RT.App.DEBUG, "ws", "error: " + msg, undefined); w.receiveMessage(RT.WebSocketMessage.mkError(msg)); }); this.onClose((code, reason) => { w.gotClose() }) return w; } } export class WebSocketServerWrapper { private handlers:any[] = []; public _conns:WebSocket[] = []; constructor(private WebSocketModule:any) { } public isReal() { return !!this.WebSocketModule } public upgradeCallback(request, socket, body) { var ws = this.WebSocketModule if (ws.isWebSocket(request)) { var conn = new ws(request, socket, body) var r = new WebSocketWrapper(this, request, conn) var nextOne = idx => { if (!this.handlers[idx]) r.reject() else this.handlers[idx](r, () => nextOne(idx + 1)) } nextOne(0) } } public closeConnections() { this._conns.forEach(c => c.close()) this._conns = [] } public addHandler(h:(req:WebSocketWrapper, next:()=>void)=>void):void { this.handlers.push(h) } public connections() { return this._conns; } } }
the_stack