text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { UnwrapPromiseTuple } from "../utils/PromiseProvider" import type { QueryRunner, DatabaseType } from "./QueryRunner" export abstract class AbstractQueryRunner implements QueryRunner { abstract readonly database: DatabaseType abstract useDatabase(database: DatabaseType): void abstract getNativeRunner(): unknown abstract execute<RESULT>(fn: (connection: unknown, transaction?: unknown) => Promise<RESULT>): Promise<RESULT> executeSelectOneRow(query: string, params: any[] = []): Promise<any> { return this.executeQueryReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } return rows[0] }) } executeSelectManyRows(query: string, params: any[] = []): Promise<any[]> { return this.executeQueryReturning(query, params) } executeSelectOneColumnOneRow(query: string, params: any[] = []): Promise<any> { return this.executeQueryReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } const row = rows[0] if (row) { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name } return undefined }) } executeSelectOneColumnManyRows(query: string, params: any[] = []): Promise<any[]> { return this.executeQueryReturning(query, params).then((rows) => rows.map((row) => { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name })) } executeInsert(query: string, params: any[] = []): Promise<number> { return this.executeMutation(query, params) } executeInsertReturningLastInsertedId(query: string, params: any[] = []): Promise<any> { return this.executeMutationReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } const row = rows[0] if (row) { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name } throw new Error('Unable to find the last inserted id') }) } executeInsertReturningMultipleLastInsertedId(query: string, params: any[] = []): Promise<any> { return this.executeMutationReturning(query, params).then((rows) => { return rows.map((row) => { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name }) }) } executeInsertReturningOneRow(query: string, params: any[] = []): Promise<any> { return this.executeMutationReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } return rows[0] }) } executeInsertReturningManyRows(query: string, params: any[] = []): Promise<any[]> { return this.executeMutationReturning(query, params) } executeInsertReturningOneColumnOneRow(query: string, params: any[] = []): Promise<any> { return this.executeMutationReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } const row = rows[0] if (row) { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name } return undefined }) } executeInsertReturningOneColumnManyRows(query: string, params: any[] = []): Promise<any[]> { return this.executeMutationReturning(query, params).then((rows) => rows.map((row) => { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name })) } executeUpdate(query: string, params: any[] = []): Promise<number> { return this.executeMutation(query, params) } executeUpdateReturningOneRow(query: string, params: any[] = []): Promise<any> { return this.executeMutationReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } return rows[0] }) } executeUpdateReturningManyRows(query: string, params: any[] = []): Promise<any[]> { return this.executeMutationReturning(query, params) } executeUpdateReturningOneColumnOneRow(query: string, params: any[] = []): Promise<any> { return this.executeMutationReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } const row = rows[0] if (row) { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name } return undefined }) } executeUpdateReturningOneColumnManyRows(query: string, params: any[] = []): Promise<any[]> { return this.executeMutationReturning(query, params).then((rows) => rows.map((row) => { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name })) } executeDelete(query: string, params: any[] = []): Promise<number> { return this.executeMutation(query, params) } executeDeleteReturningOneRow(query: string, params: any[] = []): Promise<any> { return this.executeMutationReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } return rows[0] }) } executeDeleteReturningManyRows(query: string, params: any[] = []): Promise<any[]> { return this.executeMutationReturning(query, params) } executeDeleteReturningOneColumnOneRow(query: string, params: any[] = []): Promise<any> { return this.executeMutationReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } const row = rows[0] if (row) { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name } return undefined }) } executeDeleteReturningOneColumnManyRows(query: string, params: any[] = []): Promise<any[]> { return this.executeMutationReturning(query, params).then((rows) => rows.map((row) => { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name })) } executeProcedure(query: string, params: any[] = []): Promise<void> { return this.executeMutation(query, params).then(() => undefined) } executeFunction(query: string, params: any[] = []): Promise<any> { return this.executeQueryReturning(query, params).then((rows) => { if (rows.length > 1) { throw new Error('Too many rows, expected only zero or one row') } const row = rows[0] if (row) { const columns = Object.getOwnPropertyNames(row) if (columns.length > 1) { throw new Error('Too many columns, expected only one column') } return row[columns[0]!] // Value in the row of the first column without care about the name } return undefined }) } executeDatabaseSchemaModification(query: string, params: any[] = []): Promise<void> { return this.executeMutation(query, params).then(() => undefined) } protected abstract executeQueryReturning(query: string, params: any[]): Promise<any[]> protected abstract executeMutation(query: string, params: any[]): Promise<number> protected containsInsertReturningClause(query: string, params: any[]) { const p = params as any if (p._containsInsertReturningClause === true) { return true } else if (p._containsInsertReturningClause === false) { return false } else { return /\sreturning\s/.test(query) } } protected executeMutationReturning(query: string, params: any[]): Promise<any[]> { return this.executeQueryReturning(query, params) } abstract executeBeginTransaction(): Promise<void> abstract executeCommit(): Promise<void> abstract executeRollback(): Promise<void> abstract isTransactionActive(): boolean abstract addParam(params: any[], value: any): string addOutParam(_params: any[], _name: string): string { throw new Error('Unsupported output parameters') } abstract createResolvedPromise<RESULT>(result: RESULT): Promise<RESULT> abstract executeInTransaction<P extends Promise<any>[]>(fn: () => [...P], outermostQueryRunner: QueryRunner): Promise<UnwrapPromiseTuple<P>> abstract executeInTransaction<T>(fn: () => Promise<T>, outermostQueryRunner: QueryRunner): Promise<T> abstract executeInTransaction(fn: () => Promise<any>[] | Promise<any>, outermostQueryRunner: QueryRunner): Promise<any> abstract executeCombined<R1, R2>(fn1: () => Promise<R1>, fn2: () => Promise<R2>): Promise<[R1, R2]> isMocked(): boolean { return false } }
the_stack
import { ChangeDetectorRef, Component, ElementRef, Input, NgZone, OnInit, ViewChild } from '@angular/core'; import { TUNE_STATE } from '../site_tuner'; import { colorGradient } from '../../scores'; import { ChromeMessageEnum } from '../../messages'; const BUTTON_TEXT_SHOW = 'Show'; const BUTTON_TEXT_HIDE = 'Hide'; // There's a weird bug that happens on twitter where the scrollHeight is // incorrectly greater than the clientHeight by 5 px, which causes janky // animation when expanding a collapsed comment. const SCROLL_HEIGHT_BUG_DIFF_PX = 5; /** * Component wrapper with the "dot" UI for tune. */ @Component({ selector: 'tune-dotted-comment-wrapper', templateUrl: './dotted_comment_wrapper.component.html', styleUrls: ['./dotted_comment_wrapper.component.css'] }) export class DottedCommentWrapperComponent { @Input() filterMessage = ''; @Input() feedbackQuestion = ''; @Input() maxScore = 0; // These variables are for including in submitted feedback. @Input() maxAttribute = ''; // NOTE: This is free-form comment text from the internet! Be mindful of // security issues in how this data is handled. @Input() commentText = ''; @Input() siteName = ''; @Input() buttonText = BUTTON_TEXT_SHOW; @ViewChild('commentWrapper') commentWrapper: ElementRef; // Customizable classes that are platform specific, override in subclass. customHorizontalUIWrapperClass = ''; customPlaceholderClasses: string[] = []; customCommentWrapperClass = ''; // Note: this is the raw value of the state of the comment (shown or // filtered). There's a `tuneState` @Input attribute defined below that wraps // this value with getters/setters to handle transitions (i.e. handling // expand/collapse transitions). rawTuneState = TUNE_STATE.show; // True if the comment has been revealed by the user via the "Show" button. commentVisible = false; // True if the user sent feedback about the comment. feedbackSent = false; // True if the grey background state should be aplied. hasHoverState = false; // Flag for the presence of the weird Twitter scroll height bug. hasScrollHeightBug = false; // Whether the comment should have CSS styles applied that make it invisible // to screenreaders. This field is necessary because we are using scrollHeight // for animation. If we just bind the CSS styles based on whether the comment // is hidden, then our animations won't work. hideCommentForA11y = false; // For data binding. readonly TUNE_STATE = TUNE_STATE; // Since we have disabled ngZone, we must do change detection manually, so we // inject ChangeDetectorRef. constructor(protected changeDetectorRef: ChangeDetectorRef) { } // Note: DO NOT RENAME WITHOUT UPDATING THE CSS. // This gets renamed as tune-state in the webcomponent transformation via // angular elements and so setting this property effectively acts as a // custom attribute, which is important for the CSS. Also note that this CSS // attribute hack will not work with regular data binding in an Angular // project; accomplishing the same thing in that context requires building a // custom Directive with the selector '[tune-state]'. @Input() set tuneState(newState: string) { if (newState === this.rawTuneState) { return; } console.log('tuneState change:', this.rawTuneState, ' --> ', newState); if (newState === TUNE_STATE.filter) { // Hide comment. this.collapseWrappedComment(); } else if (newState === TUNE_STATE.show) { // Show comment this.expandWrappedComment(); } else { console.error('BUG??', newState, this); return; } this.rawTuneState = newState; } get tuneState(): string { return this.rawTuneState; } // Note: this theme expands and collapses the comment with a height transition // so that the comment's verticle space changes smoothly. Transitions on // height must be explicit, they can't be done with 'auto' values. But we also // don't want to keep track of the height of the wrapped element because it // can change (e.g. when the user expands replies, or expands a long comment). // So we use this hack: we explicitly set the height when needed for the // transition, and then unset it afterwards. This is based on the technique // described here: // https://css-tricks.com/using-css-transitions-auto-dimensions/ collapseWrappedComment(): void { const comment = this.commentWrapper.nativeElement; this.hasScrollHeightBug = comment.scrollHeight - comment.clientHeight === SCROLL_HEIGHT_BUG_DIFF_PX; // Set explicit height so transitions work. comment.style.height = comment.scrollHeight + 'px'; console.log('collapse 1: setting initial height to:', comment.scrollHeight, comment.style.height); // Collapse comment once the previous change has taken effect. requestAnimationFrame(() => { // requestAnimationFrame won't run on background tabs that aren't visible, // so it's possible that multiple collapse/expand calls happen but this // callback doesn't get completed until the user switches back to the tab. // So, we check that we should still filter the comment before setitng // height to 0. if (this.rawTuneState === TUNE_STATE.filter && !this.commentVisible) { comment.style.height = '0'; console.log('collapse 2: setting height to 0 now', comment.style.height); } else { comment.style.height = null; console.log('collapse 2: whoops, no longer filter state. unsetting height.', comment.style.height); } }); } expandWrappedComment(): void { const comment = this.commentWrapper.nativeElement; this.unhideCommentFromA11y(comment); const targetHeight = (comment.scrollHeight - (this.hasScrollHeightBug ? SCROLL_HEIGHT_BUG_DIFF_PX : 0)) + 'px'; // Start transition. console.log('expand 1: initial height should be 0 already:', comment.style.height, '; setting to height:', targetHeight); comment.style.height = targetHeight; // Once transition is complete, undo the explicit height setting so later // height changes don't break the layout (expanding full comment text, // viewing replies, writing a reply, etc.). const undoExplicitHeight = () => { comment.removeEventListener('transitionend', undoExplicitHeight); // Unlike the requestAnimationFrame issue above, transitionend events do // happen in background tabs. However, we still need to recheck the state // because if the user is changing visibility quickly, the transitionend // callback may only happen after the user has collapsed the wrapper // again, in which case we shouldn't null the height. if (this.rawTuneState === TUNE_STATE.show || this.commentVisible) { comment.style.height = null; console.log('expand 2: undoing explicit height:', comment.style.height, '; actual height now:', comment.scrollHeight, comment.clientHeight, comment.offsetHeight); } else { comment.style.height = 0; console.log('expand 2: whoops, no longer show state. setting height to 0?', comment.style.height, '; actual height now:', comment.scrollHeight, comment.clientHeight, comment.offsetHeight); } }; comment.addEventListener('transitionend', undoExplicitHeight); } commentStyleTransitionEnd() { // Apply CSS classes that hide the comment from screenreaders after the // hide comment transition completes. if (this.rawTuneState === TUNE_STATE.filter && !this.commentVisible) { this.hideCommentForA11y = true; this.changeDetectorRef.detectChanges(); } } // To hide a comment from the screenreader, it needs to have display: none set // as a property. However, we have to undo this setting before doing expand // animations, or the scrollheight won't be correct. unhideCommentFromA11y(comment: HTMLElement) { this.hideCommentForA11y = false; comment.style.height = '0px'; this.changeDetectorRef.detectChanges(); } mouseEnterCallback() { this.hasHoverState = true; this.changeDetectorRef.detectChanges(); } mouseLeaveCallback() { if (!this.commentVisible) { this.hasHoverState = false; } this.changeDetectorRef.detectChanges(); } // If the comment is hidden, treat the entire horizontal wrapper like // the "show" button. Don't do this for the "hide" case because we don't // want clicking on the feedback buttons to collapse the comment. Note that // this case is only handled for click events, not keyboard events, to prevent // double events from getting fired by the a11y framework and the keypress. // When the user is using the keyboard to interact with tune, the target size // isn't an issue, so they can just use the "show" button. horizontalWrapperClicked(event: Event) { if (!this.commentVisible) { this.showButtonClicked(event); } } showButtonClicked(event: Event) { if (this.commentVisible) { this.buttonText = BUTTON_TEXT_SHOW; this.commentVisible = false; this.collapseWrappedComment(); } else { this.buttonText = BUTTON_TEXT_HIDE; this.commentVisible = true; this.expandWrappedComment(); // TODO: After expanding a comment, we should shift focus to the comment // body for a11y. } this.changeDetectorRef.detectChanges(); // Stop propagation so that the click event doesn't go to the horizontal // wrapper. event.stopPropagation(); } // TODO: refactor so this can be shared by other themes. sendFeedback(isAttribute: boolean) { console.log('feedback button clicked:', isAttribute); chrome.runtime.sendMessage({ action: ChromeMessageEnum.SUBMIT_FEEDBACK, text: this.commentText, attribute: this.maxAttribute, score: isAttribute ? 1 : 0, site: this.siteName, }, (success) => console.log('sending feedback success:', success) ); this.feedbackSent = true; this.changeDetectorRef.detectChanges(); // TODO: Figure out how to focus on the "thanks for your feedback" message // here, for a11y. Just calling .focus() doesn't seem to work. } getColor(score: number): string { return colorGradient(score); } getA11yDescription(): string { return this.commentVisible ? 'Tune hidden comment expanded by user' : 'Comment hidden by tune: ' + this.filterMessage; } }
the_stack
import { encodeInvalidFileChars, hasProperties, bold, JspmUserError, highlight } from '../utils/common'; import { Semver, SemverRange } from 'sver'; import convertRange = require('sver/convert-range'); const { processPjsonConfig } = require('@jspm/resolve'); import crypto = require('crypto'); export { processPjsonConfig } import { sourceProtocols } from './source'; /* * Package name handling */ export interface PackageName { registry: string; name: string; version: string; }; export const resourceInstallRegEx = /^(?:file|https?|git|git\+(?:file|ssh|https)?):/; const packageRegEx = /^([a-z]+):([@\-_\.a-zA-Z\d][-_\.a-zA-Z\d]*(?:\/[-_\.a-zA-Z\d]+)*)(?:@([^@]+))?$/; // this function should also handle the encoding part export function parsePackageName (name: string): PackageName { let packageMatch = name.match(packageRegEx); if (!packageMatch) throw new Error(`\`${name}\` is not a valid package name.`); return { registry: packageMatch[1], name: packageMatch[2], version: packageMatch[3] }; } export function parseExactPackageName (name: string): ExactPackage { let packageMatch = name.match(packageRegEx); if (!packageMatch) throw new Error(`\`${name}\` is not a valid package name.`); const version = packageMatch[3] ? encodeInvalidFileChars(packageMatch[3]) : '*'; return { registry: packageMatch[1], name: packageMatch[2], version, semver: new Semver(version) }; } export function serializePackageName (pkg: PackageName | string) { if (typeof pkg === 'string') return pkg; return `${pkg.registry}:${pkg.name}${(pkg.version ? '@' : '') + pkg.version}`; } export function packageNameEq (pkgA: PackageName | string, pkgB: PackageName | string) { if (typeof pkgA === 'string' || typeof pkgB === 'string') return pkgA === pkgB; return pkgA.registry === pkgB.registry && pkgA.name === pkgB.name && pkgA.version === pkgB.version; } export interface ExactPackage extends PackageName { semver: Semver } export class PackageTarget { registry: string; name: string; version: string; range: SemverRange; constructor (registry: string, name: string, version: string) { this.registry = registry; this.name = name; this.range = new SemverRange(version); // ^ -> ~ conversion save if (version[0] === '^' && this.range.isStable) this.version = this.range.toString(); else this.version = version; } fromRegistry (registry: string) { return new PackageTarget(registry, this.name, this.version); } fromVersion (version: string) { return new PackageTarget(this.registry, this.name, version); } eq (target: PackageTarget) { return target instanceof PackageTarget && this.version === target.version && this.name === target.name && this.registry === target.registry; } has (pkg: ExactPackage) { return this.registry === pkg.registry && this.name === pkg.name && this.range.has(pkg.semver); } contains (target: PackageTarget) { return this.registry === target.registry && this.name === target.name && this.range.contains(target.range); } intersect (target: PackageTarget) { return this.registry === target.registry && this.name === target.name && this.range.intersect(target.range); } toString () { return `${this.registry}:${this.name}${this.version ? `@${this.version}` : ''}`; } } /* * Resolution maps */ export interface ResolveRecord { source: string, resolve: { [name: string]: ExactPackage } } const baseConfig = processPackageConfig({}); export class ResolveTree { resolve: { [name: string]: ExactPackage } dependencies: { [packageName: string]: ResolveRecord } constructor (resolve = {}, dependencies = {}) { Object.keys(resolve).forEach(name => { resolve[name] = parseExactPackageName(resolve[name]); }); Object.keys(dependencies).forEach(parent => { const resolveMap = dependencies[parent]; if (resolveMap.resolve) Object.keys(resolveMap.resolve).forEach(name => { resolveMap.resolve[name] = parseExactPackageName(resolveMap.resolve[name]); }); else resolveMap.resolve = {}; if (resolveMap.override) resolveMap.override = overridePackageConfig(baseConfig, processPackageConfig(resolveMap.override)).override; }); this.resolve = resolve; this.dependencies = dependencies; } serialize () { const resolve = {}; const dependencies = {}; Object.keys(this.resolve).sort().forEach(name => { resolve[name] = serializePackageName(this.resolve[name]); }); Object.keys(this.dependencies).sort().forEach(parent => { const depObj: any = dependencies[parent] = {}; const originalDepObj = this.dependencies[parent]; if (originalDepObj.source) depObj.source = originalDepObj.source; if (originalDepObj.resolve && hasProperties(originalDepObj.resolve)) { depObj.resolve = {}; Object.keys(originalDepObj.resolve).forEach(name => { depObj.resolve[name] = serializePackageName(originalDepObj.resolve[name]); }); } }); return { resolve, dependencies }; } createResolveRecord (resolution: string): ResolveRecord { return this.dependencies[resolution] = { source: undefined, resolve: {} }; } getResolution ({ name, parent }: { name: string, parent: string | void }): ExactPackage { if (!parent) return this.resolve[name]; const depObj = this.dependencies[parent]; if (depObj) return depObj.resolve[name]; } getBestMatch (target: PackageTarget, edge: boolean = false): ExactPackage { let bestMatch; this.visit((pkg, _name, _parent) => { if (pkg.registry !== target.registry || pkg.name !== target.name || !target.range.has(pkg.version, edge)) return; if (!bestMatch) bestMatch = pkg; else if (pkg.semver.gt(bestMatch.version)) bestMatch = pkg; }); return bestMatch; } // package selector select (selector: string): { name: string, parent: string | void }[] { const registryIndex = selector.indexOf(':'); let registry, name, range; if (registryIndex !== -1) { registry = name.substr(0, registryIndex); name = name.substr(registryIndex + 1); } else { name = selector; } const versionIndex = name.indexOf('@'); if (versionIndex > 0) { range = new SemverRange(name.substr(versionIndex + 1)); name = name.substr(0, versionIndex); } else { range = new SemverRange('*'); } const matches = []; this.visit((pkg, pkgName, pkgParent) => { if (range && !range.has(pkg.semver, true) || pkg.name !== name && pkg.name.split('/').pop() !== name || registry && pkg.registry !== registry) return; matches.push({ name: pkgName, parent: pkgParent }); }); return matches; } visit (visitor: (pkg: ExactPackage, name: string, parent?: string) => void | boolean): boolean { for (const name of Object.keys(this.resolve)) { if (visitor(this.resolve[name], name, undefined)) return true; } for (const parent of Object.keys(this.dependencies)) { const depMap = this.dependencies[parent]; if (!depMap.resolve) continue; for (const name of Object.keys(depMap.resolve)) { if (visitor(depMap.resolve[name], name, parent)) return true; } } return false; } async visitAsync (visitor: (pkg: ExactPackage, name: string, parent?: string) => Promise<void | boolean>): Promise<boolean> { for (const name of Object.keys(this.resolve)) { if (await visitor(this.resolve[name], name, undefined)) return true; } for (const parent of Object.keys(this.dependencies)) { const depMap = this.dependencies[parent]; if (!depMap.resolve) continue; for (const name of Object.keys(depMap.resolve)) { if (await visitor(depMap.resolve[name], name, parent)) return true; } } return false; } } /* * Package Configuration */ export interface Conditional { [condition: string]: string | Conditional } export interface MapConfig { [name: string]: string | Conditional } export interface ProcessedPackageConfig { registry?: string; name?: string; version?: string; type?: string; main?: string; noModuleConversion?: boolean | string[]; namedExports?: Record<string, string[]>; map?: MapConfig; bin?: { [name: string]: string; }; dependencies?: { [name: string]: PackageTarget | string; }; peerDependencies?: { [name: string]: PackageTarget | string; }; optionalDependencies?: { [name: string]: PackageTarget | string; }; } // package configuration + sugars export interface PackageConfig { registry?: string; name?: string; version?: string; type?: string; main?: string; noModuleConversion?: boolean | string[]; namedExports?: Record<string, string[]>; map?: MapConfig; bin?: string | { [name: string]: string }; dependencies?: { [name: string]: string }; peerDependencies?: { [name: string]: string }; optionalDependencies?: { [name: string]: string }; 'react-native'?: string; electron?: string; browser?: string | { [name: string]: string | boolean }; } // Target is assumed pre-canonicalized // Note target validation should be performed separately /* export function parseTarget (depTarget: string, defaultRegistry: string): PackageName | string { let registry, name, version; const registryIndex = depTarget.indexOf(':'); if (registryIndex === -1) { registry = defaultRegistry; } // we allow :x to mean registry relative (dependencies: { a: ":b" }) else if (registryIndex === 0) { registry = defaultRegistry; } else { registry = depTarget.substr(0, registryIndex); if (registry in sourceProtocols) return depTarget; } const versionIndex = depTarget.lastIndexOf('@'); if (versionIndex > registryIndex + 1) { name = depTarget.substring(registryIndex + 1, versionIndex); version = depTarget.substr(versionIndex + 1); } else { name = depTarget.substr(registryIndex + 1); version = '*'; } return { registry, name, version }; } */ export function serializePackageTargetCanonical (name: string, target: PackageTarget | string, defaultRegistry = '') { if (typeof target === 'string') return target; const registry = target.registry !== defaultRegistry ? target.registry + ':' : ''; const pkgName = target.name[0] === '@' && target.registry !== defaultRegistry ? target.name.substr(1) : target.name; if (registry || target.name !== name) return registry + pkgName + (target.range.isWildcard ? '' : '@' + target.version); else return target.version || '*'; } /* * Processed package configuration has dependencies in precanonical form * precanonical means canonical down to unknown parent registry * * { * a: 'b@2_*', * b: 'github:x/y', * c: 'https://github.com/x/y#asdf', * d: '>2.0.0' * } * * -> * * { * a: ':b@2_%2A', * b: 'github:x/y', * c: 'https://github.com/x/y#asdf', * d: ':d@^2.0.0' * } * * We do not convert github resource sources into registry sources, as * resource handling should be consistent * * partial is for npm partial package meta where we mustn't fill out things that will come in full package.json parse */ const validKeys = ['peerDependencies', 'type', 'map', 'bin', 'namedExports', 'noModuleConversion', 'registry', 'dependencies', 'peerDependencies', 'optionalDependencies', 'map', 'main']; export function validateOverride (pcfg: PackageConfig, name: string) { for (let p in pcfg) { if (validKeys.indexOf(p) === -1) throw new JspmUserError(`${bold(`"${p}"`)} is not a valid property to override for ${highlight(name)}.`); } return true; } export function processPackageConfig (pcfg: PackageConfig, partial = false, registry = ''): ProcessedPackageConfig { const processed: ProcessedPackageConfig = processPjsonConfig(pcfg); if (processed.peerDependencies) delete processed.peerDependencies; if ((<any>processed).devDependencies) delete (<any>processed).devDependencies; if (typeof pcfg.name === 'string') processed.name = pcfg.name; if (typeof pcfg.version === 'string') processed.version = pcfg.version; if (partial) { delete processed.main; delete processed.map; } else { if (typeof pcfg.type === 'string') processed.type = pcfg.type; else processed.type = 'commonjs'; if (typeof pcfg.namedExports === 'object' && Object.keys(pcfg.namedExports).every(key => pcfg.namedExports[key] instanceof Array && pcfg.namedExports[key].every(value => typeof value === 'string'))) processed.namedExports = pcfg.namedExports; if (pcfg.noModuleConversion === true || pcfg.noModuleConversion instanceof Array && pcfg.noModuleConversion.every(x => typeof x === 'string')) processed.noModuleConversion = pcfg.noModuleConversion; if (processed.type === 'commonjs' && !processed.noModuleConversion) delete processed.type; if (typeof pcfg.bin === 'string') { const binPath = pcfg.bin.startsWith('./') ? pcfg.bin.substr(2) : pcfg.bin; processed.bin = { [pcfg.name]: binPath }; } else if (typeof pcfg.bin === 'object') { processed.bin = {}; for (let p in pcfg.bin) { const mapped = pcfg.bin[p]; const binPath = mapped.startsWith('./') ? mapped.substr(2) : mapped; processed.bin[p] = binPath; } } } registry = registry || pcfg.registry; if (registry) processed.registry = registry; if (pcfg.dependencies) { const dependencies = processed.dependencies = {}; for (const name in pcfg.dependencies) dependencies[name] = processPackageTarget(name, pcfg.dependencies[name], registry || '', true); } if (pcfg.peerDependencies) { const peerDependencies = processed.peerDependencies = {}; for (const name in pcfg.peerDependencies) peerDependencies[name] = processPackageTarget(name, pcfg.peerDependencies[name], registry || '', true); } if (pcfg.optionalDependencies) { const optionalDependencies = processed.optionalDependencies = {}; for (const name in pcfg.optionalDependencies) optionalDependencies[name] = processPackageTarget(name, pcfg.optionalDependencies[name], registry || '', true); } return processed; } /* * We support everything npm does and more (registries), except for * two node conventions (rarely used) not supported here: * 1. "x": "a/b" (github shorthand) * 2. "x": "a/b/c" (file system shorthand) * Support for these could be provided by a custom npm conversion if necessary * but let's see how far we get avoiding this */ export function processPackageTarget (depName: string, depTarget: string, defaultRegistry = '', rangeConversion = false): string | PackageTarget { let registry, name, version; const registryIndex = depTarget.indexOf(':'); if (registryIndex < 1) { registry = defaultRegistry; } else { registry = depTarget.substr(0, registryIndex); if (registry in sourceProtocols) return depTarget; } const versionIndex = depTarget.lastIndexOf('@'); if (versionIndex > registryIndex + 1) { name = depTarget.substring(registryIndex + 1, versionIndex); version = depTarget.substr(versionIndex + 1); } else if (registryIndex === -1) { name = depName; version = depTarget.substr(registryIndex + 1); } else { name = depTarget.substr(registryIndex + 1); // support github:asdf/asdf#version version method as well // for npm compatibility const hashIndex = name.indexOf('#'); if (hashIndex === -1) { version = '*'; } else { name = name.substr(0, hashIndex); version = name.substr(hashIndex + 1); } } if (rangeConversion) { if (!SemverRange.isValid(version)) { let converted = convertRange(version); if (converted.isExact) version = encodeInvalidFileChars(converted.toString()); else version = converted.toString(); } } else if (!(version[0] === '^' && SemverRange.isValid(version)) && version !== '*') { version = encodeInvalidFileChars(version); } const targetNameLen = name.split('/').length; if (targetNameLen > 2) throw new JspmUserError(`Invalid package target name ${bold(name)}`); if (targetNameLen === 2 && name[0] !== '@') name = '@' + name; if (targetNameLen === 1 && name[0] === '@') throw new JspmUserError(`Invalid package target name ${bold(name)}`); return new PackageTarget(registry, name, version); } function overrideConditional (conditional: Conditional, overrideConditional: Conditional) { let override: Conditional; // new map properties take priority first const newConditional: Conditional = {}; for (let c in overrideConditional) { const existingCondition = conditional[c]; const extendCondition = overrideConditional[c]; if (!existingCondition || (typeof existingCondition === 'string' ? existingCondition !== extendCondition : typeof extendCondition === 'object' && JSON.stringify(existingCondition) !== JSON.stringify(extendCondition))) newConditional[c] = (override = override || {})[c] = extendCondition; } if (!newConditional.default) { for (let c in conditional) { if (c in newConditional) continue; newConditional[c] = conditional[c]; } } return { conditional: newConditional, override }; } function overrideMapConfig (map: MapConfig, overrideMap: MapConfig) { let override: MapConfig; for (let m in overrideMap) { const existingVal = map[m]; let extendVal = overrideMap[m]; if (existingVal == undefined || typeof extendVal === 'string') { if (map[m] !== extendVal) map[m] = (override = override || {})[m] = extendVal; } else if (extendVal == undefined) { if (existingVal != undefined) { (override = {})[m] = extendVal; delete map[m]; } } else if (extendVal.default && Object.keys(extendVal).length === 1) { if (existingVal !== extendVal.default) map[m] = (override = override || {})[m] = extendVal.default; } else { // new map properties take priority first let newMapOverride; ({ conditional: map[m], override: newMapOverride } = overrideConditional(typeof existingVal === 'string' ? { default: existingVal } : existingVal, extendVal)); if (newMapOverride) (override = override || {})[m] = newMapOverride; } } return { map, override }; } // recanonicalize the output of a processed package config export function serializePackageConfig (pcfg: ProcessedPackageConfig, defaultRegistry?: string): PackageConfig { const spcfg: PackageConfig = {}; if (pcfg.registry) spcfg.registry = pcfg.registry; if (pcfg.name) spcfg.name = pcfg.name; if (pcfg.version) spcfg.version = pcfg.version; if (pcfg.bin) spcfg.bin = pcfg.bin; if (pcfg.noModuleConversion) spcfg.noModuleConversion = pcfg.noModuleConversion; else if (pcfg.type === 'commonjs') spcfg.type = 'commonjs'; if (pcfg.namedExports) spcfg.namedExports = pcfg.namedExports; if (pcfg.dependencies) { const dependencies = spcfg.dependencies = {}; for (let p in pcfg.dependencies) dependencies[p] = serializePackageTargetCanonical(p, pcfg.dependencies[p], defaultRegistry); } if (pcfg.peerDependencies) { const peerDependencies = spcfg.peerDependencies = {}; for (let p in pcfg.peerDependencies) peerDependencies[p] = serializePackageTargetCanonical(p, pcfg.peerDependencies[p], defaultRegistry); } if (pcfg.optionalDependencies) { const optionalDependencies = spcfg.optionalDependencies = {}; for (let p in pcfg.optionalDependencies) optionalDependencies[p] = serializePackageTargetCanonical(p, pcfg.optionalDependencies[p], defaultRegistry); } spcfg.type = pcfg.type; if (pcfg.main) spcfg.main = pcfg.main; if (pcfg.map) spcfg.map = pcfg.map; return spcfg; } export function overridePackageConfig (pcfg: ProcessedPackageConfig, overridePcfg: ProcessedPackageConfig): { config: ProcessedPackageConfig, override: ProcessedPackageConfig | void } { let override: ProcessedPackageConfig; for (let p in overridePcfg) { const val = overridePcfg[p]; if (typeof val === 'object') { let baseVal = pcfg[p]; if (val === null) { if (pcfg[p] != null) { pcfg[p] = val; if (!override) override = {}; override[p] = null; } } else { if (baseVal === undefined) baseVal = {}; if (p === 'map') { const { map, override: mapOverride } = overrideMapConfig(baseVal, val); if (map) pcfg.map = map; if (mapOverride) { if (!override) override = {}; override.map = mapOverride; } } else if (p === 'bin') { for (let q in overridePcfg.bin) { if (baseVal[q] === overridePcfg.bin[q]) continue; override = override || {}; override.bin = override.bin || {}; baseVal[q] = override.bin[q] = overridePcfg.bin[q]; pcfg.bin = baseVal; } } else if (p === 'namedExports') { for (let q in overridePcfg.namedExports) { if (JSON.stringify(baseVal[q]) === JSON.stringify(overridePcfg.namedExports[q])) continue; override = override || {}; override.namedExports = override.namedExports || {}; baseVal[q] = override.namedExports[q] = overridePcfg.namedExports[q]; pcfg.namedExports = baseVal; } } else if (p === 'noModuleConversion') { if (JSON.stringify(baseVal) === JSON.stringify(overridePcfg.noModuleConversion)) continue; override = override || {}; pcfg.noModuleConversion = override.noModuleConversion = overridePcfg.noModuleConversion; } // dependencies else { let depsOverride; for (let q in val) { const newVal = val[q]; if (typeof newVal === 'string' ? baseVal[q] !== newVal : !newVal.eq(baseVal[q])) { if (depsOverride === undefined) { if (!override) override = {}; override[p] = depsOverride = {}; } baseVal[q] = depsOverride[q] = newVal; } } } } } // undefined is not an override (use null) else if (pcfg[p] !== val && val !== undefined) { if (!override) override = {}; pcfg[p] = override[p] = val; } } if (pcfg.noModuleConversion && pcfg.type === 'commonjs') { delete override.type; } return { config: pcfg, override }; } export function sha256 (input: string): string { return crypto.createHash('sha256').update(input).digest('hex'); }; /* * Dependency Interfaces */ export enum DepType { // primary refers to the main install target (which may or may not have a parent) primary, // dev is top-level dev install dev, // peer is from subdependency or top-level peer, // optional is top-level optional install optional, // secondary is any non-peer install generated for dependencies of install secondary }; export interface DepMap { [name: string]: string | PackageTarget } export interface Dependencies { dependencies?: DepMap, devDependencies?: DepMap, peerDependencies?: DepMap, optionalDependencies?: DepMap }
the_stack
import { EventEmitter } from "@okikio/emitter"; import { Manager } from "@okikio/manager"; import type { TypeEventInput, TypeListenerCallback } from "@okikio/emitter"; import type { TypeAnimationTarget, TypeAnimationOptionTypes, TypeCallbackArgs, TypeComputedAnimationOptions, IAnimationOptions, TypeComputedOptions, TypeKeyFrameOptionsType, TypeAnimationEvents, TypePlayStates } from "./types"; export declare const getElements: (selector: string | Node) => Node[]; export declare const getTargets: (targets: TypeAnimationTarget) => Node[]; export declare const computeOption: (value: TypeAnimationOptionTypes, args: TypeCallbackArgs, context: Animate) => TypeComputedAnimationOptions; export declare const mapAnimationOptions: (options: IAnimationOptions, args: TypeCallbackArgs, animate: Animate) => TypeComputedOptions; /** * From: [https://easings.net] * * Read More about easings on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing) * * ```ts * { * "in": "ease-in", * "out": "ease-out", * "in-out": "ease-in-out", * * // Sine * "in-sine": "cubic-bezier(0.47, 0, 0.745, 0.715)", * "out-sine": "cubic-bezier(0.39, 0.575, 0.565, 1)", * "in-out-sine": "cubic-bezier(0.445, 0.05, 0.55, 0.95)", * * // Quad * "in-quad": "cubic-bezier(0.55, 0.085, 0.68, 0.53)", * "out-quad": "cubic-bezier(0.25, 0.46, 0.45, 0.94)", * "in-out-quad": "cubic-bezier(0.455, 0.03, 0.515, 0.955)", * * // Cubic * "in-cubic": "cubic-bezier(0.55, 0.055, 0.675, 0.19)", * "out-cubic": "cubic-bezier(0.215, 0.61, 0.355, 1)", * "in-out-cubic": "cubic-bezier(0.645, 0.045, 0.355, 1)", * * // Quart * "in-quart": "cubic-bezier(0.895, 0.03, 0.685, 0.22)", * "out-quart": "cubic-bezier(0.165, 0.84, 0.44, 1)", * "in-out-quart": "cubic-bezier(0.77, 0, 0.175, 1)", * * // Quint * "in-quint": "cubic-bezier(0.755, 0.05, 0.855, 0.06)", * "out-quint": "cubic-bezier(0.23, 1, 0.32, 1)", * "in-out-quint": "cubic-bezier(0.86, 0, 0.07, 1)", * * // Expo * "in-expo": "cubic-bezier(0.95, 0.05, 0.795, 0.035)", * "out-expo": "cubic-bezier(0.19, 1, 0.22, 1)", * "in-out-expo": "cubic-bezier(1, 0, 0, 1)", * * // Circ * "in-circ": "cubic-bezier(0.6, 0.04, 0.98, 0.335)", * "out-circ": "cubic-bezier(0.075, 0.82, 0.165, 1)", * "in-out-circ": "cubic-bezier(0.785, 0.135, 0.15, 0.86)", * * // Back * "in-back": "cubic-bezier(0.6, -0.28, 0.735, 0.045)", * "out-back": "cubic-bezier(0.175, 0.885, 0.32, 1.275)", * "in-out-back": "cubic-bezier(0.68, -0.55, 0.265, 1.55)" * } * ``` */ export declare const EASINGS: { in: string; out: string; "in-out": string; "in-sine": string; "out-sine": string; "in-out-sine": string; "in-quad": string; "out-quad": string; "in-out-quad": string; "in-cubic": string; "out-cubic": string; "in-out-cubic": string; "in-quart": string; "out-quart": string; "in-out-quart": string; "in-quint": string; "out-quint": string; "in-out-quint": string; "in-expo": string; "out-expo": string; "in-out-expo": string; "in-circ": string; "out-circ": string; "in-out-circ": string; "in-back": string; "out-back": string; "in-out-back": string; }; /** * The keys of {@link EASINGS} * * @remark * "in", "out", "in-out", "in-sine", "out-sine", "in-out-sine", "in-quad", "out-quad", "in-out-quad", "in-cubic", "out-cubic", "in-out-cubic", "in-quart", "out-quart", "in-out-quart", "in-quint", "out-quint", "in-out-quint", "in-expo", "out-expo", "in-out-expo", "in-circ", "out-circ", "in-out-circ", "in-back", "out-back", "in-out-back" */ export declare const EasingKeys: string[]; /** * Converts users input into a usable easing function string * * @param ease - easing functions; {@link EasingKeys}, cubic-bezier, steps, linear, etc... * @returns an easing function that `KeyframeEffect` can accept */ export declare const GetEase: (ease?: keyof typeof EASINGS | string) => string; /** * The default options for every Animate instance * * ```ts * { * keyframes: [], * * loop: 1, * delay: 0, * speed: 1, * endDelay: 0, * easing: "ease", * autoplay: true, * duration: 1000, * fillMode: "none", * direction: "normal", * padEndDelay: false, * timeline: document.timeline, * extend: {} * } * ``` */ export declare const DefaultAnimationOptions: IAnimationOptions; /** Parses the different ways to define options, and returns a merged options object */ export declare const parseOptions: (options: IAnimationOptions) => IAnimationOptions; export declare const FUNCTION_SUPPORTED_TIMING_KEYS: string[]; export declare const NOT_FUNCTION_SUPPORTED_TIMING_KEYS: string[]; export declare const ALL_TIMING_KEYS: string[]; /** * An animation library for the modern web, which. Inspired by animate plus, and animejs, [@okikio/animate](https://www.skypack.dev/view/@okikio/animate) is a Javascript animation library focused on performance and ease of use. * * You can check it out here: <https://codepen.io/okikio/pen/qBbdGaW?editors=0011> */ export declare class Animate { /** * Stores the options for the current animation * * Read more about the {@link DefaultAnimationOptions} */ options: IAnimationOptions; /** * The properties to animate */ properties: object; /** * The total duration of all Animation's */ totalDuration: number; /** * The smallest delay out of all Animation's */ minDelay: number; /** * The smallest speed out of all Animation's */ maxSpeed: number; /** * The Element the mainAnimation runs on */ mainElement: HTMLElement; /** * Stores an animation that runs on the total duration of all the `Animation` instances, and as such it's the main Animation. */ mainAnimation: Animation; /** * The Keyframe Effect for the mainAnimation */ mainkeyframeEffect: KeyframeEffect; /** * An event emitter */ emitter: EventEmitter; /** * Returns a promise that is fulfilled when the mainAnimation is finished */ promise: Promise<Animate[]>; /** * The list of Elements to Animate */ targets: Manager<number, Node>; /** * The indexs of target Elements in Animate */ targetIndexes: WeakMap<Node, number>; /** * A WeakMap of KeyFrameEffects */ keyframeEffects: WeakMap<HTMLElement, KeyframeEffect>; /** * The options for individual animations * * A WeakMap that stores all the fully calculated options for individual Animation instances. * * _**Note**: the computedOptions are changed to their proper Animation instance options, so, some of the names are different, and options that can't be computed are not present. E.g. fillMode in the animation options is now just fill in the computedOptions.*_ * * _**Note**: keyframes are not included, both the array form and the object form; the options, speed, extend, padEndDelay, and autoplay animation options are not included_ */ computedOptions: WeakMap<HTMLElement, TypeComputedOptions>; /** * A WeakMap of Animations */ animations: WeakMap<KeyframeEffect, Animation>; /** * The keyframes for individual animations * * A WeakMap that stores all the fully calculated keyframes for individual Animation instances. * * _**Note**: the computedKeyframes are changed to their proper Animation instance options, so, some of the names are different, and options that can't be computed are not present. E.g. translateX, skew, etc..., they've all been turned into the transform property.*_ */ computedKeyframes: WeakMap<HTMLElement, TypeKeyFrameOptionsType>; constructor(options: IAnimationOptions); /** * Tells all animate instances to pause when the page is hidden */ static pauseOnPageHidden: Boolean; /** * Stores all currently running instances of the Animate Class that are actively using requestAnimationFrame to check progress, * it's meant to ensure you don't have multiple instances of the Animate Class creating multiple requestAnimationFrames at the same time * this can cause performance hiccups */ static RUNNING: Set<Animate>; /** * Stores request frame calls */ static animationFrame: number; /** * Calls requestAnimationFrame for each running instance of Animate */ static requestFrame(): void; /** * Cancels animationFrame */ static cancelFrame(): void; /** * Represents an Animation Frame Loop */ loop(): void; /** * Cancels animation frame */ stopLoop(): void; /** * Store the last remebered playstate before page was hidden */ protected visibilityPlayState: TypePlayStates; /** * document `visibilitychange` event handler */ protected onVisibilityChange(): void; /** * Returns a new Promise that is resolved when the animation finishes */ newPromise(): Promise<Animate[]>; /** * Fulfills the `this.promise` Promise */ then(onFulfilled?: (value?: any) => any, onRejected?: (reason?: any) => any): Animate; /** * Catches error that occur in the `this.promise` Promise */ catch(onRejected: (reason?: any) => any): Animate; /** * If you don't care if the `this.promise` Promise has either been rejected or resolved */ finally(onFinally: () => any): Animate; /** * Calls a method that affects all animations **excluding** the mainAnimation; the method only allows the animation parameter */ allAnimations(method: (animation?: Animation, target?: HTMLElement) => void): this; /** * Calls a method that affects all animations **including** the mainAnimation; the method only allows the animation parameter */ all(method: (animation?: Animation, target?: HTMLElement) => void): this; /** * Register the begin event */ protected beginEvent(): void; /** * Play Animation */ play(): Animate; /** * Pause Animation */ pause(): Animate; /** * Reverse Animation */ reverse(): this; /** * Reset all Animations */ reset(): this; /** * Cancels all Animations */ cancel(): this; /** * Force complete all Animations */ finish(): this; /** * Cancels & Clears all Animations */ stop(): void; /** * Get a specific Animation from an Animate instance */ getAnimation(target: HTMLElement): Animation; /** * Returns the timings of an Animation, given a target * E.g. { duration, endDelay, delay, iterations, iterationStart, direction, easing, fill, etc... } */ getTiming(target: HTMLElement): TypeComputedAnimationOptions; /** * Returns the current time of the Main Animation */ getCurrentTime(): number; /** * Returns the Animation progress as a fraction of the current time / duration * 100 */ getProgress(): number; /** * Return the playback speed of the animation */ getSpeed(): number; /** * Returns the current playing state */ getPlayState(): TypePlayStates; /** * Returns a boolean determining if the `animate` instances playstate is equal to the `playstate` parameter. */ is(playstate: TypePlayStates): boolean; /** * Set the current time of the Main Animation */ setCurrentTime(time: number): Animate; /** * Set the Animation progress as a value from 0 to 100 */ setProgress(percent: number): Animate; /** * Set the playback speed of an Animation */ setSpeed(speed?: number): Animate; /** * Returns an array of computed options */ protected createArrayOfComputedOptions(optionsFromParam: IAnimationOptions, len: number): object | Keyframe[] | import("./types").TypeGeneric[]; /** * Creates animations out of an array of computed options */ protected createAnimations(param: { arrOfComputedOptions: any; padEndDelay: any; oldCSSProperties: any; onfinish: any; oncancel: any; timeline?: any; }, len: number): void; /** * Update the options for all targets * * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `updateOptions` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_ * * @beta */ updateOptions(options?: IAnimationOptions): void; /** * Adds a target to the Animate instance, and update the animation options with the change * * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `add` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_ * * @beta */ add(target: HTMLElement): void; /** * Removes a target from an Animate instance * * _**Note**: it doesn't update the current running options, you need to use the `Animate.prototype.remove(...)` method if you want to also update the running options_ */ removeTarget(target: HTMLElement): void; /** * Removes a target from an Animate instance, and update the animation options with the change * * _**Note**: `KeyframeEffect` support is really low, so, I am suggest that you avoid using the `remove` method, until browser support for `KeyframeEffect.updateTiming(...)` and `KeyframeEffefct.setKeyframes(...)` is better_ * * @beta */ remove(target: HTMLElement): void; /** * Adds a listener for a given event */ on(events: TypeAnimationEvents[] | TypeAnimationEvents | TypeEventInput, callback?: TypeListenerCallback | object, scope?: object): Animate; /** * Removes a listener from an event */ off(events: TypeAnimationEvents[] | TypeAnimationEvents | TypeEventInput, callback?: TypeListenerCallback | object, scope?: object): Animate; /** * Call all listeners within an event */ emit(events: TypeAnimationEvents[] | TypeAnimationEvents | string | any[], ...args: any): Animate; /** Returns the Animate options, as JSON */ toJSON(): IAnimationOptions; /** * The Symbol.toStringTag well-known symbol is a string valued property that is used * in the creation of the default string description of an object. * It is accessed internally by the Object.prototype.toString() method. */ get [Symbol.toStringTag](): string; } /** * Creates a new Animate instance * * @remark * `@okikio/animate` create animations by creating instances of `Animate`, a class that acts as a wrapper around the Web Animation API. To create new instances of the `Animate` class, you can either import the `Animate` class and do this, `new Animate({ ... })` or import the `animate` (lowercase) method and do this, `animate({ ... })`. The `animate` method creates new instances of the `Animate` class and passes the options it recieves as arguments to the `Animate` class. * * The `Animate` class recieves a set of targets to animate, it then creates a list of Web Animation API `Animation` instances, along side a main animation, which is small `Animation` instance that is set to animate the opacity of a non visible element, the `Animate` class then plays each `Animation` instances keyframes including the main animation. * The main animation is there to ensure accuracy in different browser vendor implementation of the Web Animation API. The main animation is stored in `Animate.prototype.mainAnimation: Animation`, the other `Animation` instances are stored in a `Manager` (from [@okikio/manager](https://www.npmjs.com/package/@okikio/manager)) `Animate.prototype.animations: Manager<HTMLElement, Animation>`. * @example * ```ts * import animate from "@okikio/animate"; * * // Do note, on the web you need to do this, if you installed it via the script tag: * // const { animate } = window.animate; * * (async () => { * let [options] = await animate({ * target: ".div", * // NOTE: If you turn this on you have to comment out the transform property. The keyframes property is a different format for animation you cannot you both styles of formatting in the same animation * // keyframes: [ * // { transform: "translateX(0px)" }, * // { transform: "translateX(300px)" } * // ], * transform: ["translateX(0px)", "translateX(300px)"], * easing: "out", * duration(i) { * return (i + 1) * 500; * }, * loop: 1, * speed: 2, * fillMode: "both", * direction: "normal", * autoplay: true, * delay(i) { * return (i + 1) * 100; * }, * endDelay(i) { * return (i + 1) * 100; * }, * }); * * animate({ * options, * transform: ["translateX(300px)", "translateX(0px)"], * }); * })(); * * // or you can use the .then() method * animate({ * target: ".div", * // NOTE: If you turn this on you have to comment out the transform property. The keyframes property is a different format for animation you cannot you both styles of formatting in the same animation * // keyframes: [ * // { transform: "translateX(0px)" }, * // { transform: "translateX(300px)" } * // ], * transform: ["translateX(0px)", "translateX(300px)"], * easing: "out", * duration(i) { * return (i + 1) * 500; * }, * loop: 1, * speed: 2, * fillMode: "both", * direction: "normal", * delay(i) { * return (i + 1) * 100; * }, * autoplay: true, * endDelay(i) { * return (i + 1) * 100; * } * }).then((options) => { * animate({ * options, * transform: ["translateX(300px)", "translateX(0px)"] * }); * }); * ``` * * [Preview this example &#8594;](https://codepen.io/okikio/pen/mdPwNbJ?editors=0010) * * @packageDocumentation */ export declare const animate: (options?: IAnimationOptions) => Animate; export default animate;
the_stack
jest.useFakeTimers('modern').setSystemTime(new Date(1606896235000)); import {createTestConnection, resetTestConnection} from '@typedorm/testing'; import {EntityManager} from '../entity-manager'; import {User, UserPrimaryKey} from '../../../../__mocks__/user'; import { UserUniqueEmail, UserUniqueEmailPrimaryKey, } from '../../../../__mocks__/user-unique-email'; import { UserAutoGenerateAttributesPrimaryKey, UserAutoGenerateAttributes, } from '../../../../__mocks__/user-auto-generate-attributes'; import {Connection} from '../../connection/connection'; import { CONSUMED_CAPACITY_TYPE, InvalidDynamicUpdateAttributeValueError, } from '@typedorm/common'; import { UserAttrAlias, UserAttrAliasPrimaryKey, } from '@typedorm/core/__mocks__/user-with-attribute-alias'; let manager: EntityManager; let connection: Connection; const dcMock = { put: jest.fn(), get: jest.fn(), update: jest.fn(), delete: jest.fn(), query: jest.fn(), transactWrite: jest.fn(), }; beforeEach(() => { connection = createTestConnection({ entities: [ User, UserUniqueEmail, UserAutoGenerateAttributes, UserAttrAlias, ], documentClient: dcMock, }); manager = new EntityManager(connection); }); afterEach(() => { resetTestConnection(); }); /** * @group create */ test('creates entity', async () => { dcMock.put.mockReturnValue({ promise: () => ({}), }); const user = new User(); user.id = '1'; user.name = 'Test User'; user.status = 'active'; const userEntity = await manager.create(user, undefined, { returnConsumedCapacity: CONSUMED_CAPACITY_TYPE.TOTAL, }); expect(dcMock.put).toHaveBeenCalledTimes(1); expect(dcMock.put).toHaveBeenCalledWith({ Item: { GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Test User', PK: 'USER#1', SK: 'USER#1', id: '1', __en: 'user', name: 'Test User', status: 'active', }, TableName: 'test-table', ReturnConsumedCapacity: 'TOTAL', ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, }); expect(userEntity).toEqual({ id: '1', name: 'Test User', status: 'active', }); }); test('creates entity with possible overwrite', async () => { dcMock.put.mockReturnValue({ promise: () => ({}), }); const user = new User(); user.id = '1'; user.name = 'Test User'; user.status = 'active'; const userEntity = await manager.create(user, { overwriteIfExists: true, }); expect(dcMock.put).toHaveBeenCalledTimes(1); expect(dcMock.put).toHaveBeenCalledWith({ Item: { GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Test User', PK: 'USER#1', SK: 'USER#1', id: '1', __en: 'user', name: 'Test User', status: 'active', }, TableName: 'test-table', }); expect(userEntity).toEqual({ id: '1', name: 'Test User', status: 'active', }); }); test('creates entity with possible overwrite and given condition', async () => { dcMock.put.mockReturnValue({ promise: () => ({}), }); const user = new User(); user.id = '1'; user.name = 'Test User'; user.status = 'active'; const userEntity = await manager.create<User>(user, { overwriteIfExists: true, where: { NOT: { id: { EQ: '1', }, }, }, }); expect(dcMock.put).toHaveBeenCalledTimes(1); expect(dcMock.put).toHaveBeenCalledWith({ Item: { GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Test User', PK: 'USER#1', SK: 'USER#1', id: '1', __en: 'user', name: 'Test User', status: 'active', }, ConditionExpression: 'NOT (#CE_id = :CE_id)', ExpressionAttributeNames: { '#CE_id': 'id', }, ExpressionAttributeValues: { ':CE_id': '1', }, TableName: 'test-table', }); expect(userEntity).toEqual({ id: '1', name: 'Test User', status: 'active', }); }); /** * Issue: #11 */ test('creates entity and returns all attributes, including auto generated ones', async () => { dcMock.put.mockReturnValue({ promise: () => ({}), }); const user = new UserAutoGenerateAttributes(); user.id = '1'; const userEntity = await manager.create(user); expect(dcMock.put).toHaveBeenCalledTimes(1); expect(dcMock.put).toHaveBeenCalledWith({ Item: { GSI1PK: 'USER#UPDATED_AT#1606896235', GSI1SK: 'USER#1', PK: 'USER#1', SK: 'USER#1', id: '1', __en: 'user-auto-generate-attr', updatedAt: 1606896235, }, TableName: 'test-table', ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, }); expect(userEntity).toEqual({ id: '1', updatedAt: 1606896235, }); }); /** * @group findOne */ test('finds one entity by given primary key', async () => { dcMock.get.mockReturnValue({ promise: () => ({ Item: { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'Me', status: 'active', }, }), }); const userEntity = await manager.findOne<User, UserPrimaryKey>(User, { id: '1', }); expect(dcMock.get).toHaveBeenCalledTimes(1); expect(dcMock.get).toHaveBeenCalledWith({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }); expect(userEntity).toEqual({ id: '1', name: 'Me', status: 'active', }); expect(userEntity).toBeInstanceOf(User); }); // issue: 110 test('returns undefined when no item was found with given primary key', async () => { dcMock.get.mockReturnValue({ promise: () => ({}), }); const userEntity = await manager.findOne<User, UserPrimaryKey>(User, { id: '1', }); expect(dcMock.get).toHaveBeenCalledTimes(1); expect(dcMock.get).toHaveBeenCalledWith({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }); expect(userEntity).toBeUndefined(); }); test('throws an error when trying to do a get request with non primary key attributes', async () => { await expect( manager.findOne(User, { name: 'User', }) ).rejects.toThrowError( '"id" was referenced in USER#{{id}} but it\'s value could not be resolved.' ); }); /** * @group exists */ test('checks if given item exists', async () => { dcMock.get.mockReturnValue({ promise: () => ({ Item: { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'Me', status: 'active', }, }), }); const userEntity = await manager.exists<User, UserUniqueEmailPrimaryKey>( User, { id: '1', }, { returnConsumedCapacity: CONSUMED_CAPACITY_TYPE.INDEXES, } ); expect(dcMock.get).toHaveBeenCalledWith({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', ReturnConsumedCapacity: 'INDEXES', }); expect(userEntity).toEqual(true); }); // issue: 110 test('returns correct value when trying check existence of item that does not exist', async () => { dcMock.get.mockReturnValue({ promise: () => ({}), }); const userEntity = await manager.exists<User, UserUniqueEmailPrimaryKey>( User, { id: '1', } ); expect(dcMock.get).toHaveBeenCalledWith({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }); expect(userEntity).toEqual(false); }); test('checks if item with given unique attribute exists', async () => { dcMock.get.mockReturnValue({ promise: () => ({ Item: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@example.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@example.com', }, }), }); const userEntity = await manager.exists<UserUniqueEmail>(UserUniqueEmail, { email: 'user@example.com', }); expect(dcMock.get).toHaveBeenCalledWith({ Key: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@example.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#user@example.com', }, TableName: 'test-table', }); expect(userEntity).toEqual(true); }); test('throws an error if trying to perform exists check with non key or non unique attributes', async () => { expect(dcMock.get).not.toHaveBeenCalled(); await expect( async () => await manager.exists<UserUniqueEmail>(UserUniqueEmail, { status: 'active', }) ).rejects.toThrowError( 'Only attributes that are part of primary key or is marked as unique attribute can be queried, attribute "status is neither."' ); }); test('throws an error if trying to perform exists check with partial primary key', async () => { await expect( manager.findOne(User, { name: 'User', }) ).rejects.toThrowError( '"id" was referenced in USER#{{id}} but it\'s value could not be resolved.' ); }); /** * @group update */ test('updates item and return all new attributes', async () => { dcMock.update.mockReturnValue({ promise: () => ({ Attributes: { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'user', status: 'active', }, }), }); const updatedItem = await manager.update<User, UserPrimaryKey>( User, {id: '1'}, { name: 'user', status: 'active', } ); expect(dcMock.update).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#UE_GSI1PK': 'GSI1PK', '#UE_GSI1SK': 'GSI1SK', '#UE_name': 'name', '#UE_status': 'status', }, ExpressionAttributeValues: { ':UE_GSI1PK': 'USER#STATUS#active', ':UE_GSI1SK': 'USER#user', ':UE_name': 'user', ':UE_status': 'active', }, Key: { PK: 'USER#1', SK: 'USER#1', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_name = :UE_name, #UE_status = :UE_status, #UE_GSI1SK = :UE_GSI1SK, #UE_GSI1PK = :UE_GSI1PK', }); expect(updatedItem).toEqual({id: '1', name: 'user', status: 'active'}); }); test('updates item with multiple body actions', async () => { dcMock.update.mockReturnValue({ promise: () => ({ Attributes: { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'user', status: 'active', }, }), }); const updatedItem = await manager.update<User, UserPrimaryKey>( User, {id: '1'}, { name: 'user', status: { IF_NOT_EXISTS: { $PATH: 'id', $VALUE: 'active', }, }, } ); expect(dcMock.update).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#UE_GSI1SK': 'GSI1SK', '#UE_GSI1PK': 'GSI1PK', '#UE_id': 'id', '#UE_name': 'name', '#UE_status': 'status', }, ExpressionAttributeValues: { ':UE_GSI1SK': 'USER#user', ':UE_GSI1PK': 'USER#STATUS#active', ':UE_name': 'user', ':UE_status': 'active', }, Key: { PK: 'USER#1', SK: 'USER#1', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_name = :UE_name, #UE_status = if_not_exists(#UE_id, :UE_status), #UE_GSI1SK = :UE_GSI1SK, #UE_GSI1PK = :UE_GSI1PK', }); expect(updatedItem).toEqual({id: '1', name: 'user', status: 'active'}); }); test('updates item when trying to update attribute with dynamic value that is not referenced in any index', async () => { dcMock.update.mockReturnValue({ promise: () => ({}), }); await manager.update<User, UserPrimaryKey>( User, {id: '1'}, { age: { INCREMENT_BY: 3, }, } ); expect(dcMock.update).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#UE_age': 'age', }, ExpressionAttributeValues: { ':UE_age': 3, }, Key: { PK: 'USER#1', SK: 'USER#1', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_age = #UE_age + :UE_age', }); }); test('fails to transform when trying to use dynamic update expression for attribute that is also referenced in a index', async () => { // this should fail as update to age is not static and is also referenced by GSI1 const updatedItem = async () => manager.update<UserAttrAlias, UserAttrAliasPrimaryKey>( UserAttrAlias, {id: '1'}, { age: { INCREMENT_BY: 3, }, } ); await expect(updatedItem).rejects.toThrow( InvalidDynamicUpdateAttributeValueError ); expect(dcMock.update).not.toHaveBeenCalled(); }); test('updates item and attributes marked to be autoUpdated', async () => { jest.useFakeTimers('modern').setSystemTime(new Date('2020-01-01')); dcMock.update.mockReturnValue({ promise: () => ({ Attributes: { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'Me', status: 'active', }, }), }); const updatedItem = await manager.update< UserAutoGenerateAttributes, UserAutoGenerateAttributesPrimaryKey >( UserAutoGenerateAttributes, {id: '1'}, {}, { nestedKeySeparator: '.', } ); expect(dcMock.update).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#UE_updatedAt': 'updatedAt', '#UE_GSI1PK': 'GSI1PK', }, ExpressionAttributeValues: { ':UE_updatedAt': 1577836800, ':UE_GSI1PK': 'USER#UPDATED_AT#1577836800', }, Key: { PK: 'USER#1', SK: 'USER#1', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_updatedAt = :UE_updatedAt, #UE_GSI1PK = :UE_GSI1PK', }); expect(updatedItem).toEqual({id: '1', name: 'Me', status: 'active'}); }); test('updates item with unique attributes and returns all updated attributes', async () => { manager.findOne = jest .fn() // mock first call to return existing item, this will be called before update is performed .mockImplementationOnce(() => ({ id: '1', email: 'old@email.com', status: 'active', })) // mock send call to return new updated item, this will be called after update is performed .mockImplementationOnce(() => ({ id: '1', email: 'new@email.com', status: 'active', })); const updateOperationSpy = dcMock.transactWrite.mockReturnValue({ on: jest.fn(), send: jest.fn().mockImplementation(cb => { cb(null, { ConsumedCapacity: [ { TableName: 'my-table', CapacityUnits: 123.3, }, ], ItemCollectionMetrics: [{}], }); }), }); const updatedItem = await manager.update< UserUniqueEmail, UserUniqueEmailPrimaryKey >( UserUniqueEmail, { id: '1', }, { email: 'new@examil.com', }, {}, { requestId: 'MY_CUSTOM_UNIQUE_REQUEST_ID', } ); expect(updateOperationSpy).toHaveBeenCalledTimes(1); expect(updateOperationSpy).toHaveBeenCalledWith({ TransactItems: [ { Update: { ExpressionAttributeNames: { '#UE_email': 'email', }, ExpressionAttributeValues: { ':UE_email': 'new@examil.com', }, Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', UpdateExpression: 'SET #UE_email = :UE_email', }, }, { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, Item: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@examil.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@examil.com', }, TableName: 'test-table', }, }, { Delete: { Key: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', }, TableName: 'test-table', }, }, ], }); expect(updatedItem).toEqual({ id: '1', email: 'new@email.com', status: 'active', }); }); test('updates item and return all new attributes with given condition', async () => { dcMock.update.mockReturnValue({ promise: () => ({ Attributes: { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'user', status: 'active', age: 4, }, }), }); const updatedItem = await manager.update<User, UserPrimaryKey>( User, {id: '1'}, { name: 'user', status: 'active', }, { where: { age: { BETWEEN: [1, 11], }, }, } ); expect(dcMock.update).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#UE_GSI1PK': 'GSI1PK', '#UE_GSI1SK': 'GSI1SK', '#UE_name': 'name', '#UE_status': 'status', '#CE_age': 'age', }, ExpressionAttributeValues: { ':UE_GSI1PK': 'USER#STATUS#active', ':UE_GSI1SK': 'USER#user', ':UE_name': 'user', ':UE_status': 'active', ':CE_age_end': 11, ':CE_age_start': 1, }, Key: { PK: 'USER#1', SK: 'USER#1', }, ReturnValues: 'ALL_NEW', TableName: 'test-table', UpdateExpression: 'SET #UE_name = :UE_name, #UE_status = :UE_status, #UE_GSI1SK = :UE_GSI1SK, #UE_GSI1PK = :UE_GSI1PK', ConditionExpression: '#CE_age BETWEEN :CE_age_start AND :CE_age_end', }); expect(updatedItem).toEqual({ id: '1', name: 'user', status: 'active', age: 4, }); }); test('updates item and create new unique item when no previous record was found', async () => { manager.findOne = jest .fn() .mockImplementationOnce(() => null) .mockImplementationOnce(() => ({ id: '1', name: 'user', status: 'active', age: 4, })); dcMock.transactWrite.mockReturnValue({ on: jest.fn(), send: jest.fn().mockImplementation(cb => { cb(null, { ConsumedCapacity: [{}], ItemCollectionMetrics: [{}], }); }), }); const updatedItem = await manager.update< UserUniqueEmail, UserUniqueEmailPrimaryKey >( UserUniqueEmail, { id: '1', }, { email: 'new@examil.com', } ); expect(manager.findOne).toHaveBeenCalledTimes(2); expect(dcMock.transactWrite).toHaveBeenCalledWith({ TransactItems: [ { Update: { ExpressionAttributeNames: { '#UE_email': 'email', }, ExpressionAttributeValues: { ':UE_email': 'new@examil.com', }, Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', UpdateExpression: 'SET #UE_email = :UE_email', }, }, { Put: { ConditionExpression: '(attribute_not_exists(#CE_PK)) AND (attribute_not_exists(#CE_SK))', ExpressionAttributeNames: { '#CE_PK': 'PK', '#CE_SK': 'SK', }, Item: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@examil.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#new@examil.com', }, TableName: 'test-table', }, }, ], }); expect(updatedItem).toEqual({ age: 4, id: '1', name: 'user', status: 'active', }); }); /** * @group delete */ test('deletes item by primary key', async () => { dcMock.delete.mockReturnValue({ promise: jest.fn().mockReturnValue({ Attributes: {}, }), }); const result = await manager.delete<User, UserPrimaryKey>(User, { id: '1', }); expect(dcMock.delete).toHaveBeenCalledWith({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }); expect(result).toEqual({ success: true, }); }); test('deletes item by primary key and given condition', async () => { dcMock.delete.mockReturnValue({ promise: jest.fn().mockReturnValue({ Attributes: {}, }), }); const result = await manager.delete<User, UserPrimaryKey>( User, { id: '1', }, { where: { status: { NE: 'active', }, }, } ); expect(dcMock.delete).toHaveBeenCalledWith({ Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', ConditionExpression: '#CE_status <> :CE_status', ExpressionAttributeNames: { '#CE_status': 'status', }, ExpressionAttributeValues: { ':CE_status': 'active', }, }); expect(result).toEqual({ success: true, }); }); test('throws an error when trying to delete item by non primary key attributes', async () => { await expect( manager.delete(User, { name: 'User', }) ).rejects.toThrowError( '"id" was referenced in USER#{{id}} but it\'s value could not be resolved.' ); }); test('deletes an item with unique attributes', async () => { manager.findOne = jest.fn().mockReturnValue({ id: '1', email: 'old@email.com', status: 'active', }); const deleteItemOperation = dcMock.transactWrite.mockReturnValue({ on: jest.fn(), send: jest.fn().mockImplementation(cb => { cb(null, { ConsumedCapacity: [{}], ItemCollectionMetrics: [{}], }); }), }); const deletedResponse = await manager.delete< UserUniqueEmail, UserUniqueEmailPrimaryKey >(UserUniqueEmail, { id: '1', }); expect(deleteItemOperation).toHaveBeenCalledTimes(1); expect(deleteItemOperation).toHaveBeenCalledWith({ TransactItems: [ { Delete: { Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }, }, { Delete: { Key: { PK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', SK: 'DRM_GEN_USERUNIQUEEMAIL.EMAIL#old@email.com', }, TableName: 'test-table', }, }, ], }); expect(deletedResponse).toEqual({ success: true, }); }); test('deletes an item with unique attributes when no existing item is found', async () => { // make find one return undefined manager.findOne = jest.fn(); const deleteItemOperation = dcMock.transactWrite.mockReturnValue({ on: jest.fn(), send: jest.fn().mockImplementation(cb => { cb(null, { ConsumedCapacity: [{}], ItemCollectionMetrics: [{}], }); }), }); const deletedResponse = await manager.delete< UserUniqueEmail, UserUniqueEmailPrimaryKey >(UserUniqueEmail, { id: '1', }); expect(manager.findOne).toHaveBeenCalledTimes(1); expect(deleteItemOperation).toHaveBeenCalledTimes(1); expect(deleteItemOperation).toHaveBeenCalledWith({ TransactItems: [ { Delete: { Key: { PK: 'USER#1', SK: 'USER#1', }, TableName: 'test-table', }, }, ], }); expect(deletedResponse).toEqual({ success: true, }); }); /** * @group find */ test('finds items matching given query params', async () => { dcMock.query.mockReturnValue({ promise: jest.fn().mockReturnValue({ Items: [ { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'Me', status: 'active', }, { PK: 'USER#2', SK: 'USER#2', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me2', id: '2', name: 'Me', status: 'active', }, ], }), }); const users = await manager.find<User, UserPrimaryKey>( User, { id: 'aaaa', }, { keyCondition: { BEGINS_WITH: 'USER#', }, limit: 10, } ); expect(dcMock.query).toHaveBeenCalledTimes(1); expect(dcMock.query).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#aaaa', ':KY_CE_SK': 'USER#', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', Limit: 10, ScanIndexForward: true, TableName: 'test-table', }); expect(users).toEqual({ items: [ { id: '1', name: 'Me', status: 'active', }, { id: '2', name: 'Me', status: 'active', }, ], }); users.items.forEach(user => { expect(user).toBeInstanceOf(User); }); }); test('finds items matching given query params and options', async () => { dcMock.query.mockReturnValue({ promise: jest.fn().mockReturnValue({ Items: [ { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'Me', status: 'active', age: 4, }, ], }), }); const users = await manager.find<User, UserPrimaryKey>( User, { id: 'aaaa', }, { keyCondition: { BEGINS_WITH: 'USER#', }, where: { AND: { age: { BETWEEN: [1, 5], }, name: { EQ: 'Me', }, status: 'ATTRIBUTE_EXISTS', }, }, limit: 10, } ); expect(dcMock.query).toHaveBeenCalledTimes(1); expect(dcMock.query).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', '#FE_age': 'age', '#FE_name': 'name', '#FE_status': 'status', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#aaaa', ':KY_CE_SK': 'USER#', ':FE_age_end': 5, ':FE_age_start': 1, ':FE_name': 'Me', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', FilterExpression: '(#FE_age BETWEEN :FE_age_start AND :FE_age_end) AND (#FE_name = :FE_name) AND (attribute_exists(#FE_status))', Limit: 10, ScanIndexForward: true, TableName: 'test-table', }); expect(users).toEqual({ items: [ { id: '1', name: 'Me', status: 'active', age: 4, }, ], }); expect(users.items[0]).toBeInstanceOf(User); }); test('finds items with alternate syntax', async () => { dcMock.query.mockReturnValue({ promise: jest.fn().mockReturnValue({ Items: [ { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'Me', status: 'active', }, ], }), }); const users = await manager.find<User>(User, 'USER#1', { keyCondition: { BEGINS_WITH: 'USER#', }, limit: 10, }); expect(dcMock.query).toHaveBeenCalledTimes(1); expect(dcMock.query).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#1', ':KY_CE_SK': 'USER#', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', Limit: 10, ScanIndexForward: true, TableName: 'test-table', }); expect(users).toEqual({ items: [ { id: '1', name: 'Me', status: 'active', }, ], }); }); test('finds item from given cursor position', async () => { dcMock.query.mockReturnValue({ promise: jest.fn().mockReturnValue({ Items: [ { PK: 'USER#1', SK: 'USER#1', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me', id: '1', name: 'Me', status: 'active', }, { PK: 'USER#2', SK: 'USER#2', GSI1PK: 'USER#STATUS#active', GSI1SK: 'USER#Me2', id: '2', name: 'Me', status: 'active', }, ], }), }); await manager.find<User, UserPrimaryKey>( User, { id: 'aaaa', }, { keyCondition: { BEGINS_WITH: 'USER#', }, limit: 10, cursor: { partitionKey: 'USER#1', sortKey: 'USER#1', }, } ); expect(dcMock.query).toHaveBeenCalledWith({ ExclusiveStartKey: { partitionKey: 'USER#1', sortKey: 'USER#1', }, ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#aaaa', ':KY_CE_SK': 'USER#', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', Limit: 10, ScanIndexForward: true, TableName: 'test-table', }); }); test('queries items until limit is met', async () => { const itemsToReturn: any[] = []; for (let index = 1; index <= 1000; index++) { itemsToReturn.push({ id: index.toString(), status: 'active', PK: `USER#${index}`, SK: `USER#${index}`, }); } dcMock.query .mockImplementationOnce(() => ({ promise: jest.fn().mockReturnValue({ Items: itemsToReturn, Count: itemsToReturn.length, LastEvaluatedKey: { partitionKey: 'USER#1000', sortKey: 'USER#1000', }, }), })) .mockImplementationOnce(() => ({ promise: jest.fn().mockReturnValue({ Items: itemsToReturn, Count: itemsToReturn.length, }), })); const users = await manager.find<User, UserPrimaryKey>( User, { id: '1', }, { keyCondition: { BEGINS_WITH: 'USER#', }, limit: 2000, } ); expect(dcMock.query).toHaveBeenCalledTimes(2); expect(dcMock.query.mock.calls).toEqual([ [ { ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#1', ':KY_CE_SK': 'USER#', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', Limit: 2000, ScanIndexForward: true, TableName: 'test-table', }, ], [ { ExclusiveStartKey: { partitionKey: 'USER#1000', sortKey: 'USER#1000', }, ExpressionAttributeNames: {'#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK'}, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#1', ':KY_CE_SK': 'USER#', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', Limit: 2000, ScanIndexForward: true, TableName: 'test-table', }, ], ]); expect(users.items.length).toEqual(2000); }); /** * @group count */ test('counts items matching given query params', async () => { dcMock.query.mockReturnValue({ promise: jest.fn().mockReturnValue({ Count: 132, }), }); const usersCount = await manager.count<User, UserPrimaryKey>( User, { id: 'aaaa', }, { keyCondition: { BEGINS_WITH: 'USER#', }, } ); expect(dcMock.query).toHaveBeenCalledTimes(1); expect(dcMock.query).toHaveBeenCalledWith({ ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#aaaa', ':KY_CE_SK': 'USER#', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', Select: 'COUNT', ScanIndexForward: true, TableName: 'test-table', }); expect(usersCount).toEqual(132); }); test('counts items with multiple requests', async () => { dcMock.query .mockImplementationOnce(() => ({ promise: jest.fn().mockReturnValue({ Count: 121, LastEvaluatedKey: 'AAAA', }), })) .mockImplementationOnce(() => ({ promise: jest.fn().mockReturnValue({ Count: 56, LastEvaluatedKey: 'BB', }), })) .mockImplementationOnce(() => ({ promise: jest.fn().mockReturnValue({ Count: 13, }), })); const users = await manager.count<User, UserPrimaryKey>( User, { id: 'aaaa', }, { keyCondition: { BEGINS_WITH: 'USER#', }, where: { AND: { age: { BETWEEN: [1, 5], }, name: { EQ: 'Me', }, status: 'ATTRIBUTE_EXISTS', }, }, } ); expect(dcMock.query).toHaveBeenCalledTimes(3); expect(dcMock.query.mock.calls).toEqual([ [ { ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', '#FE_age': 'age', '#FE_name': 'name', '#FE_status': 'status', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#aaaa', ':KY_CE_SK': 'USER#', ':FE_age_end': 5, ':FE_age_start': 1, ':FE_name': 'Me', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', FilterExpression: '(#FE_age BETWEEN :FE_age_start AND :FE_age_end) AND (#FE_name = :FE_name) AND (attribute_exists(#FE_status))', Select: 'COUNT', ScanIndexForward: true, TableName: 'test-table', }, ], [ { ExclusiveStartKey: 'AAAA', ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', '#FE_age': 'age', '#FE_name': 'name', '#FE_status': 'status', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#aaaa', ':KY_CE_SK': 'USER#', ':FE_age_end': 5, ':FE_age_start': 1, ':FE_name': 'Me', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', FilterExpression: '(#FE_age BETWEEN :FE_age_start AND :FE_age_end) AND (#FE_name = :FE_name) AND (attribute_exists(#FE_status))', Select: 'COUNT', ScanIndexForward: true, TableName: 'test-table', }, ], [ { ExclusiveStartKey: 'BB', ExpressionAttributeNames: { '#KY_CE_PK': 'PK', '#KY_CE_SK': 'SK', '#FE_age': 'age', '#FE_name': 'name', '#FE_status': 'status', }, ExpressionAttributeValues: { ':KY_CE_PK': 'USER#aaaa', ':KY_CE_SK': 'USER#', ':FE_age_end': 5, ':FE_age_start': 1, ':FE_name': 'Me', }, KeyConditionExpression: '(#KY_CE_PK = :KY_CE_PK) AND (begins_with(#KY_CE_SK, :KY_CE_SK))', FilterExpression: '(#FE_age BETWEEN :FE_age_start AND :FE_age_end) AND (#FE_name = :FE_name) AND (attribute_exists(#FE_status))', Select: 'COUNT', ScanIndexForward: true, TableName: 'test-table', }, ], ]); expect(users).toEqual(190); });
the_stack
import { addCronJob, removeCronJob } from './cronUtil'; import { createMutator, Globals } from './vulcan-lib'; import { LWEvents } from '../lib/collections/lwevents/collection'; import fetch from 'node-fetch'; import WebSocket from 'ws'; import { DatabaseServerSetting } from './databaseSettings'; import { gatherTownRoomId, gatherTownRoomName } from '../lib/publicSettings'; import { isProduction, onStartup } from '../lib/executionEnvironment'; import { toDictionary } from '../lib/utils/toDictionary'; import * as _ from 'underscore'; import { forumTypeSetting } from '../lib/instanceSettings'; import type { OpenEvent } from 'ws'; const gatherTownRoomPassword = new DatabaseServerSetting<string | null>("gatherTownRoomPassword", "the12thvirtue") // Version number of the GatherTown bot in this file. This matches the version // number field in the GatherTown connection header, ie it tracks their releases. // If this is a non-integer, the integer part is the GatherTown version number and // the fractional part is our internal iteration on the bot. const currentGatherTownTrackerVersion = 7; // Minimum version number of the GatherTown bot that should run. If this is higher // than the bot version in this file, then the cronjob shuts off so some other // server can update it instead. const minGatherTownTrackerVersion = new DatabaseServerSetting<number>("gatherTownTrackerVersion", currentGatherTownTrackerVersion); if (isProduction && forumTypeSetting.get() === "LessWrong") { onStartup(() => { if (currentGatherTownTrackerVersion >= minGatherTownTrackerVersion.get()) { addCronJob({ name: 'gatherTownBot'+currentGatherTownTrackerVersion, interval: "every 3 minutes", job() { void pollGatherTownUsers(); } }); } }); } const pollGatherTownUsers = async () => { if (currentGatherTownTrackerVersion < minGatherTownTrackerVersion.get()) { removeCronJob("gatherTownBot"); } const roomName = gatherTownRoomName.get(); const roomId = gatherTownRoomId.get(); if (!roomName || !roomId) return; const result = await getGatherTownUsers(gatherTownRoomPassword.get(), roomId, roomName); const {gatherTownUsers, checkFailed, failureReason} = result; // eslint-disable-next-line no-console console.log(`GatherTown users: ${JSON.stringify(result)}`); void createMutator({ collection: LWEvents, document: { name: 'gatherTownUsersCheck', important: false, properties: { time: new Date(), trackerVersion: currentGatherTownTrackerVersion, gatherTownUsers, checkFailed, failureReason } }, validate: false, }) } Globals.pollGatherTownUsers = pollGatherTownUsers; type GatherTownPlayerInfo = any; interface GatherTownCheckResult { gatherTownUsers: Record<string,GatherTownPlayerInfo>, checkFailed: boolean, failureReason: string|null, } const ignoredJsonMessages = ["message"]; const getGatherTownUsers = async (password: string|null, roomId: string, roomName: string): Promise<GatherTownCheckResult> => { // Register new user to Firebase const authResponse = await fetch("https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=AIzaSyCifrUkqu11lgjkz2jtp4Fx_GJh58HDlFQ", { "headers": { "accept": "*/*", "accept-language": "en-US,en;q=0.9", "cache-control": "no-cache", "content-type": "application/json", "pragma": "no-cache", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "x-client-version": "Chrome/JsCore/7.16.0/FirebaseCore-web" }, "body": "{\"returnSecureToken\":true}", "method": "POST" }); if (!authResponse.ok) { return { gatherTownUsers: [], checkFailed: true, failureReason: "Error during OAuth signin step 1: "+authResponse.status, } } const parsedResponse = await authResponse.json(); const token = parsedResponse.idToken; // Get user information const userInformation = await fetch("https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=AIzaSyCifrUkqu11lgjkz2jtp4Fx_GJh58HDlFQ", { "headers": { "accept": "*/*", "accept-language": "en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7", "cache-control": "no-cache", "content-type": "application/json", "pragma": "no-cache", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "cross-site", "x-client-data": "CIa2yQEIpbbJAQjBtskBCKmdygEImbXKAQj1x8oBCOfIygEI6cjKAQj0zcoBCNvVygEI+tjKAQ==", "x-client-version": "Chrome/JsCore/7.16.0/FirebaseCore-web" }, "body": `{ "idToken":"${token}" }`, "method": "POST", }); if (!userInformation.ok) { return { gatherTownUsers: [], checkFailed: true, failureReason: "Error during OAuth signin step 2: "+userInformation.status, } } const parsedUserInformation = await userInformation.json() const localId = parsedUserInformation.users[0].localId // Register user to Gather Town const registerUserResponse = await fetch(`https://gather.town/api/registerUser?roomId=${roomId}%5C${roomName}&authToken=${token}`, { "headers": { "accept": "application/json, text/plain, */*", "accept-language": "en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7", "cache-control": "no-cache", "pragma": "no-cache", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin" }, "body": undefined, "method": "GET", }); if (!registerUserResponse.ok) { return { gatherTownUsers: [], checkFailed: true, failureReason: "Error during registerUser step: "+registerUserResponse.status, } } // Enter password await fetch("https://gather.town/api/submitPassword", { "headers": { "accept": "application/json, text/plain, */*", "accept-language": "en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7", "cache-control": "no-cache", "content-type": "application/json;charset=UTF-8", "pragma": "no-cache", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", }, "body": `{"roomId":"${roomId}\\\\${roomName}","password":"${password}","authUser":"${localId}"}`, "method": "POST" }); // Response NOT checked, because we removed the password and that makes this fail, but that's actually ok // Find out what websocket server we're supposed to connect to const getGameServerResponse = await fetch("https://gather.town/api/getGameServer", { "headers": { "accept": "application/json, text/plain, */*", "accept-language": "en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7", "cache-control": "no-cache", "content-type": "application/json;charset=UTF-8", "pragma": "no-cache", "sec-fetch-dest": "empty", "sec-fetch-mode": "cors", "sec-fetch-site": "same-origin", }, "body": `{"room":"${roomId}\\\\${roomName}"}`, method: "POST", }); if (!getGameServerResponse.ok) { return { gatherTownUsers: [], checkFailed: true, failureReason: "Error during getGameServer step: "+registerUserResponse.status, } } const websocketServerUrl = await getGameServerResponse.text(); // Create WebSocket connection. let socketConnectedSuccessfully = false; let socketReceivedAnyMessage = false; let reloadRequested = false; // eslint-disable-next-line no-console console.log(`Connecting to websocket server ${websocketServerUrl}`); const socket = new WebSocket(websocketServerUrl); socket.on('open', function (data: OpenEvent) { socketConnectedSuccessfully = true; sendMessageOnSocket(socket, { event: "init", token: token, version: Math.floor(currentGatherTownTrackerVersion), }); }); let playerNamesById: Record<string,string> = {} let playerInfoByName: Record<string,GatherTownPlayerInfo> = {}; socket.on('message', function (data: any) { socketReceivedAnyMessage = true; const firstByte: any = data.readUInt8(0); if (firstByte === 0) { // A JSON message const jsonResponse = messageToJson(data); if (jsonResponse) { if (jsonResponse.event === "ready") { sendMessageOnSocket(socket, { event: "rpc", target: "space", args: { type: "subscribe", space: `${roomId}\\${roomName}` } }); } else { if (jsonResponse.event === "reload") { reloadRequested = true; } else if (ignoredJsonMessages.indexOf(jsonResponse.event) >= 0) { // Ignore this message } else { // eslint-disable-next-line no-console console.log(`Unrecognized message type: ${jsonResponse.event}`); } } } } else if (firstByte === 1) { // A binary message const parsedMessage = interpretBinaryMessage(data) if (parsedMessage?.players) { for (let player of parsedMessage.players) { playerNamesById[player.id] = player.name; playerInfoByName[player.name] = player; } } } }); // We wait 3s for any responses to arrive via the socket message await wait(3000); socket.close(); if (reloadRequested) { return { checkFailed: true, gatherTownUsers: [], failureReason: "Version number mismatch", }; } else if (socketConnectedSuccessfully && socketReceivedAnyMessage) { const playerNames = _.values(playerNamesById); return { checkFailed: false, gatherTownUsers: toDictionary(playerNames, name=>name, name=>playerInfoByName[name]), failureReason: null, }; } else if (socketConnectedSuccessfully) { return { checkFailed: true, gatherTownUsers: [], failureReason: "WebSocket connected but did not receive any messages (check gatherTownWebsocketServer setting)", }; } else { return { checkFailed: true, gatherTownUsers: [], failureReason: "Websocket connection failed", }; } } function stringToArrayBuffer(str: string) { var binary_string = Buffer.from(str).toString(`binary`); var len = binary_string.length; var bytes = new Uint8Array(len); for (var i = 0; i <= len; i++) { bytes[i] = binary_string.charCodeAt(i); } return bytes.buffer; } const sendMessageOnSocket = (socket: any, message: any) => { const json = JSON.stringify(message); const arrayBuffer = stringToArrayBuffer(json); socket.send(arrayBuffer); } const messageToJson = (data: any) => { const messageBody = data.toString('utf8').substring(1); if (isJson(messageBody)) return JSON.parse(messageBody); else return null; } function isJson(str: string): boolean { try { JSON.parse(str); } catch (e) { return false; } return true; } const playerMessageHeaderLen = 32; const mapNameOffset = 18 const playerNameOffset = 20 const playerStatusOffset = 24 const playerIconOffset = 26 const unknownStringFieldOffset = 28; const playerIdOffset = 30 // Decoded using echo AS...<rest of base64 message> | base64 -d | hexdump -C function interpretBinaryMessage(data: any): {players: {map: string, name: string, id: string, status: string}[]} | null { const buf = Buffer.from(data); // First byte is 1 to indicate it's a binary message if (buf.readUInt8(0) !== 1) { //eslint-disable-next-line no-console console.log("Not a recognizable binary message"); return null; } // Second byte is the length of string roomId\roomName const targetSpaceLen = buf.readUInt8(1); // This is followed by a series of messages where the first byte is a message // type. The message lengths/alignment are unfortunately not marked. We only // understand message type 0 (player metadata). let pos = 2+targetSpaceLen; const players: Array<any> = []; while (pos < buf.length) { const messageType = buf.readUInt8(pos); if (messageType === 0) { // eslint-disable-next-line no-console console.log("Parsing players-list message"); const mapNameLen = buf.readUInt8(pos+mapNameOffset); const playerNameLen = buf.readUInt8(pos+playerNameOffset); const playerStatusLen = buf.readUInt8(pos+playerStatusOffset) const playerIconLen = buf.readUInt8(pos+playerIconOffset); const unknownStringFieldLen = buf.readUInt8(pos+unknownStringFieldOffset); const playerIdLen = buf.readUInt8(pos+playerIdOffset); const mapNameStart = pos+playerMessageHeaderLen; const playerNameStart = mapNameStart+mapNameLen; const playerStatusStart = playerNameStart+playerNameLen; const playerIconStart = playerStatusStart+playerIconLen; const unknownStringFieldStart = playerIconStart+unknownStringFieldLen; const playerIdStart = unknownStringFieldStart+playerStatusLen; const mapName = buf.slice(mapNameStart, mapNameStart+mapNameLen).toString("utf8"); const playerName = buf.slice(playerNameStart, playerNameStart+playerNameLen).toString("utf8"); const playerstatus = buf.slice(playerStatusStart, playerStatusStart+playerStatusLen).toString("utf8"); const unknownField = buf.slice(unknownStringFieldStart, unknownStringFieldStart+unknownStringFieldLen).toString("utf8"); const playerId = buf.slice(playerIdStart, playerIdStart+playerIdLen).toString("utf8"); players.push({ map: mapName, name: playerName, id: playerId, status: playerstatus, unknownField, }); pos = playerIdStart+playerIdLen; } else { // Unrecognized message type. Return what we have so far. return {players}; } } return {players}; } // Wait utility function const wait = (ms: number) => new Promise((r, j) => setTimeout(r, ms))
the_stack
import { ResolvedConfig, Plugin, normalizePath } from "vite"; import mime from "mime/lite"; import fs, { promises as fsp } from "fs"; import { createHash } from "crypto"; import { parse as parseUrl, URLSearchParams, pathToFileURL, URL } from "url"; import type Rollup from "rollup"; import path from "path"; import { OutputOptions, PluginContext, RollupWarning, WarningHandler, } from "rollup"; import chalk from "chalk"; const warningIgnoreList = [`CIRCULAR_DEPENDENCY`, `THIS_IS_UNDEFINED`]; const dynamicImportWarningIgnoreList = [ `Unsupported expression`, `statically analyzed`, ]; export function onRollupWarning( warning: RollupWarning, warn: WarningHandler, config: ResolvedConfig ): void { if (warning.code === "UNRESOLVED_IMPORT") { const id = warning.source; const importer = warning.importer; // throw unless it's commonjs external... if (!importer || !/\?commonjs-external$/.test(importer)) { throw new Error( `[vite]: Rollup failed to resolve import "${id}" from "${importer}".\n` + `This is most likely unintended because it can break your application at runtime.\n` + `If you do want to externalize this module explicitly add it to\n` + `\`build.rollupOptions.external\`` ); } } if ( warning.plugin === "rollup-plugin-dynamic-import-variables" && dynamicImportWarningIgnoreList.some((msg) => warning.message.includes(msg)) ) { return; } if (!warningIgnoreList.includes(warning.code!)) { const userOnWarn = config.build.rollupOptions?.onwarn; if (userOnWarn) { userOnWarn(warning, warn); } else if (warning.code === "PLUGIN_WARNING") { config.logger.warn( `${chalk.bold.yellow(`[plugin:${warning.plugin}]`)} ${chalk.yellow( warning.message )}` ); } else { warn(warning); } } } export const ENV_PUBLIC_PATH = `/@vite/env`; export const FS_PREFIX = `/@fs/`; export const queryRE = /\?.*$/s; export const hashRE = /#.*$/s; export function injectQuery(url: string, queryToInject: string): string { // encode percents for consistent behavior with pathToFileURL // see #2614 for details let resolvedUrl = new URL(url.replace(/%/g, "%25"), "relative:///"); if (resolvedUrl.protocol !== "relative:") { resolvedUrl = pathToFileURL(url); } let { protocol, pathname, search, hash } = resolvedUrl; if (protocol === "file:") { pathname = pathname.slice(1); } pathname = decodeURIComponent(pathname); return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ""}${ hash || "" }`; } export const cleanUrl = (url: string): string => url.replace(hashRE, "").replace(queryRE, ""); export function checkPublicFile( url: string, { publicDir }: ResolvedConfig ): string | undefined { // note if the file is in /public, the resolver would have returned it // as-is so it's not going to be a fully resolved path. if (!publicDir || !url.startsWith("/")) { return; } const publicFile = path.join(publicDir, cleanUrl(url)); if (fs.existsSync(publicFile)) { return publicFile; } else { return; } } /** * converts the source filepath of the asset to the output filename based on the assetFileNames option. \ * this function imitates the behavior of rollup.js. \ * https://rollupjs.org/guide/en/#outputassetfilenames * * @example * ```ts * const content = Buffer.from('text'); * const fileName = assetFileNamesToFileName( * 'assets/[name].[hash][extname]', * '/path/to/file.txt', * getAssetHash(content), * content * ) * // fileName: 'assets/file.982d9e3e.txt' * ``` * * @param assetFileNames filename pattern. e.g. `'assets/[name].[hash][extname]'` * @param file filepath of the asset * @param contentHash hash of the asset. used for `'[hash]'` placeholder * @param content content of the asset. passed to `assetFileNames` if `assetFileNames` is a function * @returns output filename */ export function assetFileNamesToFileName( assetFileNames: Exclude<OutputOptions["assetFileNames"], undefined>, file: string, contentHash: string, content: string | Buffer ): string { const basename = path.basename(file); // placeholders for `assetFileNames` // `hash` is slightly different from the rollup's one const extname = path.extname(basename); const ext = extname.substring(1); const name = basename.slice(0, -extname.length); const hash = contentHash; if (typeof assetFileNames === "function") { assetFileNames = assetFileNames({ name: file, source: content, type: "asset", }); if (typeof assetFileNames !== "string") { throw new TypeError("assetFileNames must return a string"); } } else if (typeof assetFileNames !== "string") { throw new TypeError("assetFileNames must be a string or a function"); } const fileName = assetFileNames.replace( /\[\w+\]/g, (placeholder: string): string => { switch (placeholder) { case "[ext]": return ext; case "[extname]": return extname; case "[hash]": return hash; case "[name]": return name; } throw new Error( `invalid placeholder ${placeholder} in assetFileNames "${assetFileNames}"` ); } ); return fileName; } const assetCache = new WeakMap<ResolvedConfig, Map<string, string>>(); const assetHashToFilenameMap = new WeakMap< ResolvedConfig, Map<string, string> >(); // save hashes of the files that has been emitted in build watch const emittedHashMap = new WeakMap<ResolvedConfig, Set<string>>(); export function getAssetHash(content: Buffer): string { return createHash("sha256").update(content).digest("hex").slice(0, 8); } export async function fileToBuiltUrl( id: string, config: ResolvedConfig, pluginContext: PluginContext, skipPublicCheck = false ): Promise<string> { if (!skipPublicCheck && checkPublicFile(id, config)) { return config.base + id.slice(1); } const cache = assetCache.get(config)!; const cached = cache.get(id); if (cached) { return cached; } const file = cleanUrl(id); const content = await fsp.readFile(file); let url: string; if ( config.build.lib || (!file.endsWith(".svg") && content.length < Number(config.build.assetsInlineLimit)) ) { // base64 inlined as a string url = `data:${mime.getType(file)};base64,${content.toString("base64")}`; } else { // emit as asset // rollup supports `import.meta.ROLLUP_FILE_URL_*`, but it generates code // that uses runtime url sniffing and it can be verbose when targeting // non-module format. It also fails to cascade the asset content change // into the chunk's hash, so we have to do our own content hashing here. // https://bundlers.tooling.report/hashing/asset-cascade/ // https://github.com/rollup/rollup/issues/3415 const map = assetHashToFilenameMap.get(config)!; const contentHash = getAssetHash(content); const { search, hash } = parseUrl(id); const postfix = (search || "") + (hash || ""); const output = config.build?.rollupOptions?.output; const assetFileNames = (output && !Array.isArray(output) ? output.assetFileNames : undefined) ?? // defaults to '<assetsDir>/[name].[hash][extname]' // slightly different from rollup's one ('assets/[name]-[hash][extname]') path.posix.join(config.build.assetsDir, "[name].[hash][extname]"); const fileName = assetFileNamesToFileName( assetFileNames, file, contentHash, content ); if (!map.has(contentHash)) { map.set(contentHash, fileName); } const emittedSet = emittedHashMap.get(config)!; if (!emittedSet.has(contentHash)) { const name = normalizePath(path.relative(config.root, file)); pluginContext.emitFile({ name, fileName, type: "asset", source: content, }); emittedSet.add(contentHash); } url = `__VITE_ASSET__${contentHash}__${postfix ? `$_${postfix}__` : ``}`; } cache.set(id, url); return url; } export function fileToDevUrl(id: string, config: ResolvedConfig) { let rtn: string; if (checkPublicFile(id, config)) { // in public dir, keep the url as-is rtn = id; } else if (id.startsWith(config.root)) { // in project root, infer short public path rtn = "/" + path.posix.relative(config.root, id); } else { // outside of project root, use absolute fs path // (this is special handled by the serve static middleware rtn = path.posix.join(FS_PREFIX + id); } const origin = config.server?.origin ?? ""; return origin + config.base + rtn.replace(/^\//, ""); } export function fileToUrl( id: string, config: ResolvedConfig, ctx: PluginContext ): string | Promise<string> { if (config.command === "serve") { return fileToDevUrl(id, config); } else { return fileToBuiltUrl(id, config, ctx); } } export function parseWorkerRequest(id: string): Record<string, string> | null { const { search } = parseUrl(id); if (!search) { return null; } return Object.fromEntries(new URLSearchParams(search.slice(1))); } const WorkerFileId = "worker_file"; export function webWorkerPlugin(config: ResolvedConfig): Plugin { const isBuild = config.command === "build"; return { name: "vite:worker", load(id) { if (isBuild) { const parsedQuery = parseWorkerRequest(id); if ( parsedQuery && (parsedQuery.worker ?? parsedQuery.sharedworker) != null ) { return ""; } } }, async transform(_, id) { const query = parseWorkerRequest(id); if (query && query[WorkerFileId] != null) { return { code: `import '${ENV_PUBLIC_PATH}'\n` + _, }; } if ( query == null || (query && (query.worker ?? query.sharedworker) == null) ) { return; } let url: string; if (isBuild) { // bundle the file as entry to support imports const rollup = require("rollup") as typeof Rollup; const bundle = await rollup.rollup({ input: cleanUrl(id), // plugins: await resolvePlugins({ ...config }, [], [], []), onwarn(warning, warn) { onRollupWarning(warning, warn, config); }, }); let code: string; try { const { output } = await bundle.generate({ format: "iife", sourcemap: config.build.sourcemap, }); code = output[0].code; } finally { await bundle.close(); } const content = Buffer.from(code); if (query.inline != null) { // inline as blob data url return `const encodedJs = "${content.toString("base64")}"; const blob = typeof window !== "undefined" && window.Blob && new Blob([atob(encodedJs)], { type: "text/javascript;charset=utf-8" }); export default function WorkerWrapper() { const objURL = blob && (window.URL || window.webkitURL).createObjectURL(blob); try { return objURL ? new Worker(objURL) : new Worker("data:application/javascript;base64," + encodedJs, {type: "module"}); } finally { objURL && (window.URL || window.webkitURL).revokeObjectURL(objURL); } }`; } else { const basename = path.parse(cleanUrl(id)).name; const contentHash = getAssetHash(content); const fileName = path.posix.join( config.build.assetsDir, `${basename}.${contentHash}.js` ); url = `__VITE_ASSET__${this.emitFile({ fileName, type: "asset", source: code, })}__`; } } else { url = await fileToUrl(cleanUrl(id), config, this); url = injectQuery(url, WorkerFileId); } const workerConstructor = query.sharedworker != null ? "SharedWorker" : "Worker"; const workerOptions = { type: "module" }; return `export default function WorkerWrapper() { return new ${workerConstructor}(${JSON.stringify( url )}, ${JSON.stringify(workerOptions, null, 2)}) }`; }, }; }
the_stack
import { gql } from "@apollo/client"; import { v4 as uuidV4 } from "uuid"; import { Membership, MembershipRole, MutationCreateWorkspaceArgs, MutationCreateMembershipArgs, Workspace, WorkspaceType, } from "@labelflow/graphql-types"; import { getPrismaClient } from "../../prisma-client"; import { client, user } from "../../dev/apollo-client"; import { WorkspacePlan } from ".prisma/client"; // @ts-ignore fetch.disableFetchMocks(); const testUser1Id = uuidV4(); const testUser2Id = uuidV4(); beforeAll(async () => { await ( await getPrismaClient() ).user.create({ data: { id: testUser1Id, name: "test-user-1" } }); await ( await getPrismaClient() ).user.create({ data: { id: testUser2Id, name: "test-user-2" } }); }); beforeEach(async () => { user.id = testUser1Id; await (await getPrismaClient()).membership.deleteMany({}); return await (await getPrismaClient()).workspace.deleteMany({}); }); afterAll(async () => { // Needed to avoid having the test process running indefinitely after the test suite has been run await (await getPrismaClient()).$disconnect(); }); const createWorkspace = async ( data?: Partial<MutationCreateWorkspaceArgs["data"]> ) => { return await client.mutate<{ createWorkspace: Pick<Workspace, "id" | "name" | "slug" | "plan" | "type">; }>({ mutation: gql` mutation createWorkspace($data: WorkspaceCreateInput!) { createWorkspace(data: $data) { id name slug plan type } } `, variables: { data: { ...data, name: data?.name ?? "test" } }, }); }; describe("createWorkspace mutation", () => { it("fails if the user isn't logged in", async () => { user.id = undefined; await expect(() => createWorkspace({ name: "should fail" }) ).rejects.toThrow("Couldn't create workspace: No user id"); }); it("fails if the user doesn't exist in the database", async () => { user.id = uuidV4(); await expect(() => createWorkspace({ name: "should fail" }) ).rejects.toThrow( `Couldn't create workspace: User with id "${user.id}" doesn't exist in the database` ); }); it("fails if no name is provided", async () => { await expect(() => client.mutate({ mutation: gql` mutation createWorkspace($data: WorkspaceCreateInput!) { createWorkspace(data: $data) { id } } `, variables: { data: { name: null } }, }) ).rejects.toThrow(); }); it("fails if the name is an empty string", async () => { await expect(() => client.mutate({ mutation: gql` mutation createWorkspace($data: WorkspaceCreateInput!) { createWorkspace(data: $data) { id } } `, variables: { data: { name: "" } }, }) ).rejects.toThrow("Name is empty"); }); it("fails if the name contains non-alphanumeric chars is provided", async () => { await expect(() => client.mutate({ mutation: gql` mutation createWorkspace($data: WorkspaceCreateInput!) { createWorkspace(data: $data) { id } } `, variables: { data: { name: "Hello!" } }, }) ).rejects.toThrow("Name contains invalid characters"); }); it("fails if the name is reserved", async () => { await expect(() => client.mutate({ mutation: gql` mutation createWorkspace($data: WorkspaceCreateInput!) { createWorkspace(data: $data) { id } } `, variables: { data: { name: "pricing" } }, }) ).rejects.toThrow("This name is reserved"); }); it("accepts a name with hyphens, spaces, underscores, and alphanumeric characters", async () => { const { data } = await createWorkspace({ name: "Test with spaces-and-Caps-and-hyphens", }); expect(data?.createWorkspace.slug).toEqual( "test-with-spaces-and-caps-and-hyphens" ); }); it("returns the created workspace", async () => { const { data } = await createWorkspace(); expect(data?.createWorkspace.name).toEqual("test"); }); it("accepts an id", async () => { const id = uuidV4(); const { data } = await createWorkspace({ id }); expect(data?.createWorkspace.id).toEqual(id); }); it("generates a slug based on the workspace name", async () => { const { data } = await createWorkspace({ name: "Test with spaces and Caps", }); expect(data?.createWorkspace.slug).toEqual("test-with-spaces-and-caps"); }); it("creates a workspace with the Community plan", async () => { const { data } = await createWorkspace(); expect(data?.createWorkspace.plan).toEqual(WorkspacePlan.Community); }); it("returns a workspace with the Online type", async () => { const { data } = await createWorkspace(); expect(data?.createWorkspace.type).toEqual(WorkspaceType.Online); }); it("sets the user who created the workspace as owner", async () => { const { data } = await client.mutate<{ createWorkspace: Pick<Workspace, "id" | "memberships">; }>({ mutation: gql` mutation createWorkspace($data: WorkspaceCreateInput!) { createWorkspace(data: $data) { id memberships { id role user { id } } } } `, variables: { data: { name: "test" } }, }); expect(data?.createWorkspace.memberships[0]?.user?.id).toEqual(user.id); expect(data?.createWorkspace.memberships[0]?.role).toEqual( MembershipRole.Owner ); }); }); describe("workspaces query", () => { it("returns an empty array when there aren't any", async () => { const { data } = await client.query({ query: gql` { workspaces { id } } `, fetchPolicy: "no-cache", }); expect(data.workspaces).toEqual([]); }); it("returns the already created workspaces", async () => { await createWorkspace({ name: "test1" }); await createWorkspace({ name: "test2" }); await createWorkspace({ name: "test3" }); await createWorkspace({ name: "test4" }); const { data } = await client.query<{ workspaces: Pick<Workspace, "id" | "name">[]; }>({ query: gql` { workspaces { id name } } `, fetchPolicy: "no-cache", }); expect(data.workspaces.map((workspace) => workspace.name)).toEqual([ "test1", "test2", "test3", "test4", ]); }); it("returns an empty array if the user does not have any workspace", async () => { await createWorkspace({ name: "test1" }); await createWorkspace({ name: "test2" }); await createWorkspace({ name: "test3" }); await createWorkspace({ name: "test4" }); user.id = testUser2Id; const { data } = await client.query<{ workspaces: Pick<Workspace, "id" | "name">[]; }>({ query: gql` { workspaces { id name } } `, fetchPolicy: "no-cache", }); expect(data.workspaces.map((workspace) => workspace.name)).toEqual([]); }); it("returns workspaces with the Online type", async () => { await createWorkspace({ name: "test1" }); await createWorkspace({ name: "test2" }); await createWorkspace({ name: "test3" }); await createWorkspace({ name: "test4" }); const { data } = await client.query<{ workspaces: Pick<Workspace, "id" | "type">[]; }>({ query: gql` { workspaces { id type } } `, fetchPolicy: "no-cache", }); expect( data.workspaces.every( (workspace) => workspace.type === WorkspaceType.Online ) ).toEqual(true); }); it("can skip results", async () => { await createWorkspace({ name: "test1" }); await createWorkspace({ name: "test2" }); await createWorkspace({ name: "test3" }); await createWorkspace({ name: "test4" }); const { data } = await client.query<{ workspaces: Pick<Workspace, "id" | "name">[]; }>({ query: gql` { workspaces(skip: 2) { id name } } `, fetchPolicy: "no-cache", }); expect(data.workspaces.map((workspace) => workspace.name)).toEqual([ "test3", "test4", ]); }); it("can limit the number of results", async () => { await createWorkspace({ name: "test1" }); await createWorkspace({ name: "test2" }); await createWorkspace({ name: "test3" }); await createWorkspace({ name: "test4" }); const { data } = await client.query<{ workspaces: Pick<Workspace, "id" | "name">[]; }>({ query: gql` { workspaces(first: 2) { id name } } `, fetchPolicy: "no-cache", }); expect(data.workspaces.map((workspace) => workspace.name)).toEqual([ "test1", "test2", ]); }); it("can limit the number of results and also skip some", async () => { await createWorkspace({ name: "test1" }); await createWorkspace({ name: "test2" }); await createWorkspace({ name: "test3" }); await createWorkspace({ name: "test4" }); const { data } = await client.query<{ workspaces: Pick<Workspace, "id" | "name">[]; }>({ query: gql` { workspaces(first: 2, skip: 1) { id name } } `, fetchPolicy: "no-cache", }); expect(data.workspaces.map((workspace) => workspace.name)).toEqual([ "test2", "test3", ]); }); }); describe("workspace query", () => { it("fails if not provided an id", async () => { await expect(() => client.query({ query: gql` { workspace { id name } } `, fetchPolicy: "no-cache", }) ).rejects.toThrow(); }); it("fails if no workspace match the given id", async () => { const idCorrespondingToNoWorkspace = uuidV4(); await expect(() => client.query({ query: gql` query workspace($id: ID!) { workspace(where: { id: $id }) { id name } } `, variables: { id: idCorrespondingToNoWorkspace }, fetchPolicy: "no-cache", }) ).rejects.toThrow( `Couldn't find workspace from input "{"id":"${idCorrespondingToNoWorkspace}"}"` ); }); it("fails if user is not logged in", async () => { const id = (await createWorkspace()).data?.createWorkspace.id; user.id = undefined; await expect(() => client.query({ query: gql` query workspace($id: ID!) { workspace(where: { id: $id }) { id name } } `, variables: { id }, fetchPolicy: "no-cache", }) ).rejects.toThrow(`User not authenticated`); }); it("fails if user does not have access to workspace", async () => { const id = (await createWorkspace()).data?.createWorkspace.id; user.id = testUser2Id; await expect(() => client.query({ query: gql` query workspace($id: ID!) { workspace(where: { id: $id }) { id name } } `, variables: { id }, fetchPolicy: "no-cache", }) ).rejects.toThrow(`User not authorized to access workspace`); }); it("returns the workspace corresponding to the id", async () => { const id = (await createWorkspace()).data?.createWorkspace.id; const { data } = await client.query<{ workspace: Pick<Workspace, "id" | "name">; }>({ query: gql` query workspace($id: ID!) { workspace(where: { id: $id }) { id name } } `, variables: { id }, fetchPolicy: "no-cache", }); expect(data.workspace.name).toEqual("test"); }); it("returns the workspace with an Online type", async () => { const id = (await createWorkspace()).data?.createWorkspace.id; const { data } = await client.query<{ workspace: Pick<Workspace, "id" | "type">; }>({ query: gql` query workspace($id: ID!) { workspace(where: { id: $id }) { id type } } `, variables: { id }, fetchPolicy: "no-cache", }); expect(data.workspace.type).toEqual(WorkspaceType.Online); }); }); describe("updatedWorkspace mutation", () => { it("can change the name of a workspace", async () => { const id = (await createWorkspace())?.data?.createWorkspace.id; const { data } = await client.mutate<{ updateWorkspace: Pick<Workspace, "id" | "name">; }>({ mutation: gql` mutation updateWorkspace($id: ID!, $data: WorkspaceUpdateInput!) { updateWorkspace(where: { id: $id }, data: $data) { id name } } `, variables: { id, data: { name: "new name" } }, fetchPolicy: "no-cache", }); expect(data?.updateWorkspace.name).toEqual("new name"); }); it("fails if the user does not have access to the workspace", async () => { const id = (await createWorkspace())?.data?.createWorkspace.id; user.id = testUser2Id; await expect( client.mutate<{ updateWorkspace: Pick<Workspace, "id" | "name">; }>({ mutation: gql` mutation updateWorkspace($id: ID!, $data: WorkspaceUpdateInput!) { updateWorkspace(where: { id: $id }, data: $data) { id name } } `, variables: { id, data: { name: "new name" } }, fetchPolicy: "no-cache", }) ).rejects.toThrow("User not authorized to access workspace"); }); it("changes the slug is the name of the workspace is changed", async () => { const id = (await createWorkspace())?.data?.createWorkspace.id; const { data } = await client.mutate<{ updateWorkspace: Pick<Workspace, "id" | "slug">; }>({ mutation: gql` mutation updateWorkspace($id: ID!, $data: WorkspaceUpdateInput!) { updateWorkspace(where: { id: $id }, data: $data) { id slug } } `, variables: { id, data: { name: "new name" } }, fetchPolicy: "no-cache", }); expect(data?.updateWorkspace.slug).toEqual("new-name"); }); }); describe("nested resolvers", () => { const createMembership = async ( data?: MutationCreateMembershipArgs["data"] ) => { return await client.mutate<{ createMembership: Membership; }>({ mutation: gql` mutation createMembership($data: MembershipCreateInput!) { createMembership(data: $data) { id role } } `, variables: { data }, }); }; it("can query memberships", async () => { const slug = (await createWorkspace()).data?.createWorkspace.slug as string; const membershipId = ( await createMembership({ userId: testUser2Id, workspaceSlug: slug, role: MembershipRole.Admin, }) ).data?.createMembership.id as string; const { data } = await client.query<{ workspace: Pick<Workspace, "id" | "memberships">; }>({ query: gql` query workspace($slug: String!) { workspace(where: { slug: $slug }) { id memberships { id } } } `, variables: { slug }, fetchPolicy: "no-cache", }); // memberships[0] is generated when the workspace is created expect(data.workspace.memberships[1].id).toEqual(membershipId); }); it("can query datasets", async () => { const id = (await createWorkspace()).data?.createWorkspace.id as string; const { data } = await client.query<{ workspace: Pick<Workspace, "id" | "datasets">; }>({ query: gql` query workspace($id: ID!) { workspace(where: { id: $id }) { id datasets { id } } } `, variables: { id }, fetchPolicy: "no-cache", }); expect(data.workspace.datasets).toEqual([]); }); });
the_stack
import { css, SerializedStyles } from '@emotion/react'; import { Theme } from '@sumup/design-tokens'; import { warn } from '../util/logger'; import { isFunction } from '../util/type-check'; type ThemeArgs = Theme | { theme: Theme }; function isTheme(args: ThemeArgs): args is Theme { return (args as { theme: Theme }).theme === undefined; } /** * @private */ const getTheme = (args: ThemeArgs): Theme => isTheme(args) ? args : args.theme; type StyleFn = | ((theme: Theme) => SerializedStyles) | ((args: ThemeArgs) => SerializedStyles) | SerializedStyles | false | null | undefined; /** * Helper to pass multiple style mixins to the `css` prop. * Mixins can be applied conditionally, falsy values are omitted. */ export const cx = (...styleFns: StyleFn[]) => (theme: Theme): (SerializedStyles | false | null | undefined)[] => styleFns.map((styleFn) => (isFunction(styleFn) ? styleFn(theme) : styleFn)); type Spacing = keyof Theme['spacings']; export type SpacingValue = Spacing | 'auto' | 0; export type SpacingObject = { top?: SpacingValue; bottom?: SpacingValue; right?: SpacingValue; left?: SpacingValue; }; const mapSpacingValue = (theme: Theme, value: SpacingValue) => { if (process.env.NODE_ENV !== 'production') { if (typeof value === 'number' && value !== 0) { warn( 'spacing', `The number "${value as number}" was passed to the spacing mixin.`, "This is not supported. Pass a spacing constant, 'auto', or 0 instead.", ); } } if (value === 0 || value === 'auto') { return String(value); } return theme.spacings[value]; }; /** * Adds margin to one or more sides of an element. */ export const spacing = ( size: SpacingValue | SpacingObject, ): ((args: ThemeArgs) => SerializedStyles) => { if (typeof size === 'string' || typeof size === 'number') { return (args: ThemeArgs) => { const theme = getTheme(args); return css({ margin: mapSpacingValue(theme, size) }); }; } const margins: { marginTop?: string; marginBottom?: string; marginRight?: string; marginLeft?: string; } = {}; return (args: ThemeArgs) => { const theme = getTheme(args); if (typeof size.top !== 'undefined') { margins.marginTop = mapSpacingValue(theme, size.top); } if (typeof size.right !== 'undefined') { margins.marginRight = mapSpacingValue(theme, size.right); } if (typeof size.bottom !== 'undefined') { margins.marginBottom = mapSpacingValue(theme, size.bottom); } if (typeof size.left !== 'undefined') { margins.marginLeft = mapSpacingValue(theme, size.left); } return css(margins); }; }; /** * Adds a drop shadow to an element to visually elevate it above the * surrounding content. */ export function shadow(options?: never): (args: ThemeArgs) => SerializedStyles; export function shadow(args: ThemeArgs): SerializedStyles; export function shadow( argsOrOptions?: ThemeArgs | never, ): SerializedStyles | ((args: ThemeArgs) => SerializedStyles) { if (!argsOrOptions) { return (): SerializedStyles => css` box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.2); `; } return css` box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.2); `; } /** * @deprecated Use the `shadow` style mixin instead. */ export const shadowSingle = (args: ThemeArgs): SerializedStyles => { const theme = getTheme(args); return css` box-shadow: 0 0 0 1px ${theme.colors.shadow}, 0 0 1px 0 ${theme.colors.shadow}, 0 2px 2px 0 ${theme.colors.shadow}; `; }; /** * @deprecated Use the `shadow` style mixin instead. */ export const shadowDouble = (args: ThemeArgs): SerializedStyles => { const theme = getTheme(args); return css` box-shadow: 0 0 0 1px ${theme.colors.shadow}, 0 2px 2px 0 ${theme.colors.shadow}, 0 4px 4px 0 ${theme.colors.shadow}; `; }; /** * @deprecated Use the `shadow` style mixin instead. */ export const shadowTriple = (args: ThemeArgs): SerializedStyles => { const theme = getTheme(args); return css` box-shadow: 0 0 0 1px ${theme.colors.shadow}, 0 4px 4px 0 ${theme.colors.shadow}, 0 8px 8px 0 ${theme.colors.shadow}; `; }; /** * Sets the font size and line height matching the Body component. */ export function typography( size: keyof Theme['typography']['body'], ): (args: ThemeArgs) => SerializedStyles { return (args: ThemeArgs) => { const theme = getTheme(args); return css(theme.typography.body[size]); }; } /** * Visually communicates to the user that an element is disabled * and prevents user interactions. */ export const disableVisually = (): SerializedStyles => css` opacity: 0.5; pointer-events: none; box-shadow: none; `; /** * Visually hides an element while keeping it accessible to users * who rely on a screen reader. */ export const hideVisually = (): SerializedStyles => css` border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; white-space: nowrap; width: 1px; `; /** * Visually communicates to the user that an element is focused. */ export function focusOutline( options: 'inset', ): (args: ThemeArgs) => SerializedStyles; export function focusOutline(args: ThemeArgs): SerializedStyles; export function focusOutline( argsOrOptions: ThemeArgs | 'inset', ): SerializedStyles | ((args: ThemeArgs) => SerializedStyles) { if (typeof argsOrOptions === 'string') { return (args: ThemeArgs): SerializedStyles => { const theme = getTheme(args); return css` outline: 0; box-shadow: inset 0 0 0 4px ${theme.colors.p300}; &::-moz-focus-inner { border: 0; } `; }; } const theme = getTheme(argsOrOptions); return css` outline: 0; box-shadow: 0 0 0 4px ${theme.colors.p300}; &::-moz-focus-inner { border: 0; } `; } /** * Visually communicates to the user that an element is focused when * the user agent determines via heuristics that the focus should be * made evident on the element. */ export function focusVisible( options: 'inset', ): (args: ThemeArgs) => SerializedStyles; export function focusVisible(args: ThemeArgs): SerializedStyles; export function focusVisible( argsOrOptions: ThemeArgs | 'inset', ): SerializedStyles | ((args: ThemeArgs) => SerializedStyles) { if (typeof argsOrOptions === 'string') { return (args: ThemeArgs): SerializedStyles => { const theme = getTheme(args); return css` &:focus { outline: 0; box-shadow: inset 0 0 0 4px ${theme.colors.p300}; &::-moz-focus-inner { border: 0; } } &:focus:not(:focus-visible) { box-shadow: none; } `; }; } const theme = getTheme(argsOrOptions); return css` &:focus { outline: 0; box-shadow: 0 0 0 4px ${theme.colors.p300}; &::-moz-focus-inner { border: 0; } } &:focus:not(:focus-visible) { box-shadow: none; } `; } /** * Forces an element to self-clear its floated children. * Taken from [CSS Tricks](https://css-tricks.com/clearfix-a-lesson-in-web-development-evolution/). */ export const clearfix = (): SerializedStyles => css` &::before, &::after { content: ' '; display: table; } &::after { clear: both; } `; /** * Hides the browser scrollbar on a scrollable element, e.g. with overflow. */ export const hideScrollbar = (): SerializedStyles => css` -ms-overflow-style: none; scrollbar-width: none; &::-webkit-scrollbar { display: none; } `; /** * Visually communicates to the user that an element is hovered, focused, or * active in the disabled, invalid, and warning states. */ export const inputOutline = ( args: | Theme | { theme: Theme; disabled?: boolean; invalid?: boolean; hasWarning?: boolean; /** * @deprecated */ showValid?: boolean; }, ): SerializedStyles => { const theme = getTheme(args); const options = isTheme(args) ? { disabled: false, invalid: false, hasWarning: false } : args; if (options.disabled) { return css` box-shadow: 0 0 0 1px ${theme.colors.n500}; `; } let colors; switch (true) { case options.invalid: { colors = { default: theme.colors.danger, hover: theme.colors.r700, focus: theme.colors.danger, active: theme.colors.danger, }; break; } case options.hasWarning: { colors = { default: theme.colors.warning, hover: theme.colors.y700, focus: theme.colors.warning, active: theme.colors.warning, }; break; } default: { colors = { default: theme.colors.n500, hover: theme.colors.n700, focus: theme.colors.p500, active: theme.colors.p500, }; } } return css` box-shadow: 0 0 0 1px ${colors.default}; &:hover { box-shadow: 0 0 0 1px ${colors.hover}; } &:focus { box-shadow: 0 0 0 2px ${colors.focus}; } &:active { box-shadow: 0 0 0 1px ${colors.active}; } `; }; /** * @private * * Common styles for list items (e.g. in the Popover component). */ export const listItem = ( args: | Theme | { theme: Theme; destructive?: boolean; }, ): SerializedStyles => { const theme = getTheme(args); const options = isTheme(args) ? { destructive: false } : args; return css` background-color: ${theme.colors.white}; padding: ${theme.spacings.kilo} ${theme.spacings.tera} ${theme.spacings.kilo} ${theme.spacings.mega}; border: 0; color: ${options.destructive ? theme.colors.danger : theme.colors.bodyColor}; text-decoration: none; position: relative; &:hover { background-color: ${theme.colors.n100}; cursor: pointer; } ${focusVisible('inset')(theme)}; &:active { background-color: ${theme.colors.n200}; } &:disabled, &[disabled] { ${disableVisually()}; } `; }; /** * @private * * Common styles for navigation items (e.g. in the TopNavigation and * SideNavigation components). */ export const navigationItem = ( args: | Theme | { theme: Theme; isActive?: boolean; }, ): SerializedStyles => { const theme = getTheme(args); const options = isTheme(args) ? { isActive: false } : args; return css` display: flex; align-items: center; border: none; outline: none; color: ${options.isActive ? theme.colors.p500 : theme.colors.bodyColor}; background-color: ${options.isActive ? theme.colors.p100 : theme.colors.white}; text-align: left; cursor: pointer; transition: color ${theme.transitions.default}, background-color ${theme.transitions.default}; &:hover { background-color: ${options.isActive ? theme.colors.p100 : theme.colors.n100}; } &:active { background-color: ${theme.colors.n200}; } ${focusVisible('inset')(theme)}; &:disabled { ${disableVisually()}; } `; };
the_stack
import { ICertificate } from '@aws-cdk/aws-certificatemanager'; import { IOrigin, IDistribution, Distribution, ErrorResponse, PriceClass, HttpVersion, GeoRestriction, BehaviorOptions, CachePolicy, SecurityPolicyProtocol, } from '@aws-cdk/aws-cloudfront'; import { S3Origin } from '@aws-cdk/aws-cloudfront-origins'; import { Bucket, IBucket } from '@aws-cdk/aws-s3'; import { Construct, Duration, RemovalPolicy, Stack, ResourceEnvironment, CfnResource } from '@aws-cdk/core'; import { IAuthorization, IStaticSiteAuthorization, ISpaAuthorization } from './authorizations'; export interface CommonDistributionProps { /** * The origin that you want CloudFront to route requests */ readonly origin?: IOrigin; /** * The price class that corresponds with the maximum price that you want to pay for CloudFront service. * If you specify PriceClass_All, CloudFront responds to requests for your objects from all CloudFront edge locations. * If you specify a price class other than PriceClass_All, CloudFront serves your objects from the CloudFront edge location * that has the lowest latency among the edge locations in your price class. * * @default PriceClass.PRICE_CLASS_100 */ readonly priceClass?: PriceClass; /** * Alternative domain names for this distribution. * * If you want to use your own domain name, such as www.example.com, instead of the cloudfront.net domain name, * you can add an alternate domain name to your distribution. If you attach a certificate to the distribution, * you must add (at least one of) the domain names of the certificate to this list. * * @default - The distribution will only support the default generated name (e.g., d111111abcdef8.cloudfront.net) */ readonly domainNames?: string[]; /** * A certificate to associate with the distribution. The certificate must be located in N. Virginia (us-east-1). * * @default - the CloudFront wildcard certificate (*.cloudfront.net) will be used. */ readonly certificate?: ICertificate; /** * Any comments you want to include about the distribution. * * @default - no comment */ readonly comment?: string; /** * The object that you want CloudFront to request from your origin (for example, index.html) * when a viewer requests the root URL for your distribution. If no default object is set, the * request goes to the origin's root (e.g., example.com/). * * @default - index.html */ readonly defaultRootObject?: string; /** * Enable or disable the distribution. * * @default true */ readonly enabled?: boolean; /** * Whether CloudFront will respond to IPv6 DNS requests with an IPv6 address. * * If you specify false, CloudFront responds to IPv6 DNS requests with the DNS response code NOERROR and with no IP addresses. * This allows viewers to submit a second request, for an IPv4 address for your distribution. * * @default true */ readonly enableIpv6?: boolean; /** * Enable access logging for the distribution. * * @default - false, unless `logBucket` is specified. */ readonly enableLogging?: boolean; /** * The Amazon S3 bucket to store the access logs in. * * @default - A bucket is created if `enableLogging` is true */ readonly logBucket?: IBucket; /** * Specifies whether you want CloudFront to include cookies in access logs * * @default false */ readonly logIncludesCookies?: boolean; /** * An optional string that you want CloudFront to prefix to the access log filenames for this distribution. * * @default - no prefix */ readonly logFilePrefix?: string; /** * Controls the countries in which your content is distributed. * * @default - No geographic restrictions */ readonly geoRestriction?: GeoRestriction; /** * Specify the maximum HTTP version that you want viewers to use to communicate with CloudFront. * * For viewers and CloudFront to use HTTP/2, viewers must support TLS 1.2 or later, and must support server name identification (SNI). * * @default HttpVersion.HTTP2 */ readonly httpVersion?: HttpVersion; /** * Unique identifier that specifies the AWS WAF web ACL to associate with this CloudFront distribution. * * To specify a web ACL created using the latest version of AWS WAF, use the ACL ARN, for example * `arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a`. * To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example `473e64fd-f30b-4765-81a0-62ad96dd167a`. * * @see https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html * @see https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html#API_CreateDistribution_RequestParameters. * * @default - No AWS Web Application Firewall web access control list (web ACL). */ readonly webAclId?: string; /** * The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections. * * CloudFront serves your objects only to browsers or devices that support at * least the SSL version that you specify. * * @default SecurityPolicyProtocol.TLS_V1_2_2019 */ readonly minimumProtocolVersion?: SecurityPolicyProtocol; /** * @default Destroy */ readonly removalPolicy?: RemovalPolicy; } export interface BaseDistributionProps extends CommonDistributionProps { readonly authorization: IAuthorization; readonly errorResponses?: ErrorResponse[]; } export class BaseDistribution extends Construct implements IDistribution { public readonly domainName: string; public readonly distributionDomainName: string; public readonly distributionId: string; public readonly stack: Stack; public readonly env: ResourceEnvironment; constructor(scope: Construct, id: string, props: BaseDistributionProps) { super(scope, id); const removalPolicy = props.removalPolicy ?? RemovalPolicy.DESTROY; const origin = props.origin ?? this.defaultOrigin(removalPolicy); const distribution = new Distribution(this, 'Distribution', { enabled: props.enabled ?? true, enableIpv6: props.enableIpv6 ?? true, comment: props.comment, enableLogging: props.enableLogging, logBucket: props.logBucket, logIncludesCookies: props.logIncludesCookies, logFilePrefix: props.logFilePrefix, priceClass: props.priceClass ?? PriceClass.PRICE_CLASS_100, geoRestriction: props.geoRestriction, httpVersion: props.httpVersion ?? HttpVersion.HTTP2, webAclId: props.webAclId, minimumProtocolVersion: props.minimumProtocolVersion, errorResponses: props.errorResponses, domainNames: props.domainNames, certificate: props.certificate, defaultBehavior: this.renderDefaultBehaviour(origin, props.authorization), additionalBehaviors: this.renderAdditionalBehaviors(origin, props.authorization), defaultRootObject: props.defaultRootObject ?? 'index.html', }); const callbackUrls = props.domainNames?.map((name) => `https://${name}${props.authorization.redirectPaths.signIn}`) ?? []; const logoutUrls = props.domainNames?.map((name) => `https://${name}${props.authorization.redirectPaths.signOut}`) ?? []; props.authorization.updateUserPoolClientCallbacks({ callbackUrls: [`https://${distribution.distributionDomainName}${props.authorization.redirectPaths.signIn}`, ...callbackUrls], logoutUrls: [`https://${distribution.distributionDomainName}${props.authorization.redirectPaths.signOut}`, ...logoutUrls], }); this.domainName = distribution.domainName; this.distributionDomainName = distribution.distributionDomainName; this.distributionId = distribution.distributionId; this.stack = Stack.of(this); this.env = { account: this.stack.account, region: this.stack.region, }; } public applyRemovalPolicy(policy: RemovalPolicy) { const child = this.node.defaultChild; if (!child || !CfnResource.isCfnResource(child)) { throw new Error('Cannot apply RemovalPolicy: no child or not a CfnResource. Apply the removal policy on the CfnResource directly.'); } child.applyRemovalPolicy(policy); } protected renderDefaultBehaviour(origin: IOrigin, authorization: IAuthorization): BehaviorOptions { return authorization.createDefaultBehavior(origin, { originRequestPolicy: undefined, cachePolicy: CachePolicy.CACHING_DISABLED, }); } protected renderAdditionalBehaviors(origin: IOrigin, authorization: IAuthorization): Record<string, BehaviorOptions> { return authorization.createAdditionalBehaviors(origin, { originRequestPolicy: undefined, cachePolicy: CachePolicy.CACHING_DISABLED, }); } private defaultOrigin(removalPolicy: RemovalPolicy): IOrigin { const bucket = new Bucket(this, 'Bucket', { autoDeleteObjects: removalPolicy === RemovalPolicy.DESTROY, removalPolicy, }); return new S3Origin(bucket); } } export interface StaticSiteDistributionProps extends CommonDistributionProps { readonly authorization: IStaticSiteAuthorization; readonly errorResponses?: ErrorResponse[]; } export class StaticSiteDistribution extends BaseDistribution { constructor(scope: Construct, id: string, props: StaticSiteDistributionProps) { super(scope, id, props); } } export interface SpaDistributionProps extends CommonDistributionProps { readonly authorization: ISpaAuthorization; /** * The minimum amount of time, in seconds, that you want CloudFront * to cache the HTTP status code specified in ErrorCode. * * @default 300 seconds */ readonly ttl?: Duration; } export class SpaDistribution extends BaseDistribution { constructor(scope: Construct, id: string, props: SpaDistributionProps) { super(scope, id, { ...props, errorResponses: [ { httpStatus: 404, responseHttpStatus: 200, ttl: props.ttl ?? Duration.seconds(300), responsePagePath: '/index.html', }, ], }); } }
the_stack
import { Directive, Input, Output, HostListener, Inject, OnInit, OnChanges, OnDestroy, SimpleChanges, SimpleChange, EventEmitter, ElementRef, ChangeDetectorRef } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { Meta } from '@angular/platform-browser'; import { Platform } from '@angular/cdk/platform'; import { Clipboard } from '@angular/cdk/clipboard'; import { EMPTY, Observable, Subject, Subscriber } from 'rxjs'; import { takeUntil, tap } from 'rxjs/operators'; import { ShareService } from './share.service'; import { IShareButton, ShareDirectiveUpdater, ShareParams, ShareParamsFunc, SharerMethod } from './share.models'; import { getValidUrl } from './utils'; @Directive({ selector: '[shareButton]', exportAs: 'shareButton' }) export class ShareDirective implements OnInit, OnChanges, OnDestroy { /** Variable used to check for the final sharer url (For testing only) */ private _finalUrl: string; /** Share directive element ref */ private readonly _el: HTMLButtonElement; /** A ref to button class - used to remove previous class when the button type is changed */ private _buttonClass: string; /** Stream that emits when button is destroyed */ private readonly _destroyed = new Subject<void>(); /** Stream that emit when share button need to be updated */ private readonly _updater = new Subject<ShareDirectiveUpdater>(); /** Share button properties */ shareButton: IShareButton; /** Share button color */ color: string; /** Share button text */ text: string; /** Share button icon */ icon: string | string[]; /** Share button type */ @Input('shareButton') shareButtonName: string; /** Set meta tags from document head, useful when SEO is supported */ @Input() autoSetMeta: boolean = this._share.config.autoSetMeta; /** Sharing link */ @Input() url: string = this._share.config.url; /** Sets the title parameter */ @Input() title: string = this._share.config.title; /** Sets the description parameter */ @Input() description: string = this._share.config.description; /** Sets the image parameter for sharing on Pinterest */ @Input() image: string = this._share.config.image; /** Sets the tags parameter for sharing on Twitter and Tumblr */ @Input() tags: string = this._share.config.tags; /** Stream that emits when share dialog is opened */ @Output() opened = new EventEmitter<string>(); /** Stream that emits when share dialog is closed */ @Output() closed = new EventEmitter<string>(); constructor(_el: ElementRef, private _meta: Meta, private _platform: Platform, private _clipboard: Clipboard, private _share: ShareService, private _cd: ChangeDetectorRef, @Inject(DOCUMENT) private _document: any) { this._el = _el.nativeElement; } /** * Share the link */ @HostListener('click') share() { // Avoid SSR error if (this._platform.isBrowser && this.shareButton) { // Prepare sharer url params const params: ShareParams = this.autoSetMeta ? this.getParamsFromMetaTags() : this.getParamsFromInputs(); // Prepare share button click const click = this.shareButton.share ? this.open(params) : this.shareButton.func({ params, data: this.shareButton.data, clipboard: this._clipboard, updater: this._updater }); click.pipe(takeUntil(this._destroyed)).subscribe(); } else { console.warn(`${ this.text } button is not compatible on this Platform`); } } ngOnInit() { // This stream is mainly used to update the copy button text and icon when it is being clicked this._updater.pipe( tap((data: any) => { this.icon = data.icon; this.text = data.text; this._el.style.pointerEvents = data.disabled ? 'none' : 'auto'; this._cd.markForCheck(); }), takeUntil(this._destroyed) ).subscribe(); } ngOnChanges(changes: SimpleChanges) { // Avoid SSR error if (this._platform.isBrowser) { // Create share button if (this._shareButtonChanged(changes.shareButtonName)) { this._createShareButton(); } // Prepare share url if (this._urlChanged(changes.url)) { this.url = getValidUrl( this.autoSetMeta ? this.url || this._getMetaTagContent('og:url') : this.url, this._document.defaultView.location.href ); } } } ngOnDestroy() { this._destroyed.next(); this._destroyed.complete(); } private _createShareButton() { const button: IShareButton = this._share.config.prop[this.shareButtonName]; if (button) { // Set share button properties this.shareButton = button; // Remove previous button class this._el.classList.remove(`sb-${ this._buttonClass }`); // Add new button class this._el.classList.add(`sb-${ this.shareButtonName }`); // Set button css color variable this._el.style.setProperty('--button-color', this.shareButton.color); // Keep a copy of the class for future replacement this._buttonClass = this.shareButtonName; this.color = this.shareButton.color; this.text = this.shareButton.text; this.icon = this.shareButton.icon; // Set aria-label attribute this._el.setAttribute('aria-label', button.ariaLabel); } else { console.error(`[ShareButtons]: The share button '${ this.shareButtonName }' does not exist!`); } } /** * Get meta tag content */ private _getMetaTagContent(key: string): string { const metaUsingProperty: HTMLMetaElement = this._meta.getTag(`property="${ key }"`); if (metaUsingProperty) { return metaUsingProperty.getAttribute('content'); } const metaUsingName: HTMLMetaElement = this._meta.getTag(`name="${ key }"`); if (metaUsingName) { return metaUsingName.getAttribute('content'); } } private _shareButtonChanged(change: SimpleChange): boolean { return change && (change.firstChange || change.previousValue !== change.currentValue); } private _urlChanged(change: SimpleChange): boolean { return !this.url || (change && change.previousValue !== change.currentValue); } /** * Get share params from meta tags first and fallback to user inputs */ private getParamsFromMetaTags(): ShareParams { return { url: this.url, title: this.title || this._getMetaTagContent('og:title'), description: this.description || this._getMetaTagContent('og:description'), image: this.image || this._getMetaTagContent('og:image'), via: this._share.config.twitterAccount, tags: this.tags }; } /** * Get share params from user inputs */ private getParamsFromInputs(): ShareParams { return { url: this.url, title: this.title, description: this.description, image: this.image, tags: this.tags, via: this._share.config.twitterAccount, }; } private open(params: ShareParams): Observable<void> { // Set sharer link based on user's device let sharerLink: string; if (this._platform.IOS && this.shareButton.share.ios) { sharerLink = this.shareButton.share.ios; } else if (this._platform.ANDROID && this.shareButton.share.android) { sharerLink = this.shareButton.share.android; } else { sharerLink = this.shareButton.share.desktop; } if (sharerLink) { // Set sharer link params this._finalUrl = sharerLink + this._serializeParams(params); // Log the sharer link in debug mode if (this._share.config.debug) { console.log('[DEBUG SHARE BUTTON]: ', this._finalUrl); } // Open the share window // There are two methods available for opening the share window: // 1. Using a real anchor // 2. Using window.open const sharerMethod = this.shareButton.method || this._share.config.sharerMethod; const sharerTarget = this.shareButton.target || this._share.config.sharerTarget; switch (sharerMethod) { case SharerMethod.Anchor: const linkElement: HTMLLinkElement = this._document.createElement('a'); // Make it open in a new tab/window (depends on user's browser configuration) linkElement.setAttribute('target', sharerTarget); // Prevent security vulnerability https://medium.com/@jitbit/target-blank-the-most-underestimated-vulnerability-ever-96e328301f4c linkElement.setAttribute('rel', 'noopener noreferrer'); linkElement.href = this._finalUrl; linkElement.click(); linkElement.remove(); break; case SharerMethod.Window: // Open link using Window object const openWindow = this._share.config.windowObj[this._share.config.windowFuncName]; const popUpWindow = openWindow(this._finalUrl, sharerTarget, this._share.windowSize); // Prevent security vulnerability https://medium.com/@jitbit/target-blank-the-most-underestimated-vulnerability-ever-96e328301f4c this._share.config.windowObj.opener = null; // Resolve when share dialog is closed if (popUpWindow) { return new Observable<void>((sub: Subscriber<void>) => { const pollTimer = this._document.defaultView.setInterval(() => { if (popUpWindow.closed) { this._document.defaultView.clearInterval(pollTimer); // Emit when share windows is closed this.closed.emit(this.shareButtonName); sub.next(); sub.complete(); } }, 200); }); } break; } // Emit when share window is opened this.opened.emit(this.shareButtonName); } return EMPTY; } private _serializeParams(params: ShareParams): string { return Object.entries(this.shareButton.params) .map(([key, value]) => { // Check if share button param has a map function const paramFunc: ShareParamsFunc = this.shareButton.paramsFunc ? this.shareButton.paramsFunc[key] : null; if (params[key] || paramFunc) { const paramValue = paramFunc ? paramFunc(params) : params[key]; return `${ value }=${ encodeURIComponent(paramValue) }`; } return ''; }) .filter(urlParam => urlParam !== '') .join('&'); } }
the_stack
import * as path from 'path'; import { BlockDevice, BlockDeviceVolume, } from '@aws-cdk/aws-autoscaling'; import { IVpc, SubnetSelection, SubnetType, } from '@aws-cdk/aws-ec2'; import { Role, Policy, PolicyStatement, } from '@aws-cdk/aws-iam'; import { Code, Function as LambdaFunction, Runtime, } from '@aws-cdk/aws-lambda'; import { RetentionDays } from '@aws-cdk/aws-logs'; import { Annotations, Construct, CustomResource, Duration, Fn, IResolvable, Lazy, Stack, } from '@aws-cdk/core'; import { PluginSettings, SEPConfiguratorResourceProps, LaunchSpecification, SpotFleetRequestConfiguration, SpotFleetRequestProps, SpotFleetSecurityGroupId, SpotFleetTagSpecification, BlockDeviceMappingProperty, BlockDeviceProperty, } from '../../lambdas/nodejs/configure-spot-event-plugin'; import { IRenderQueue, RenderQueue, } from './render-queue'; import { SecretsManagementRegistrationStatus, SecretsManagementRole, } from './secrets-management-ref'; import { SpotEventPluginFleet } from './spot-event-plugin-fleet'; import { SpotFleetRequestType, SpotFleetResourceType, } from './spot-event-plugin-fleet-ref'; import { Version } from './version'; /** * How the event plug-in should respond to events. */ export enum SpotEventPluginState { /** * The Render Queue, all jobs and Workers will trigger the events for this plugin. */ GLOBAL_ENABLED = 'Global Enabled', /** * No events are triggered for the plugin. */ DISABLED = 'Disabled', } /** * Logging verbosity levels for the Spot Event Plugin. */ export enum SpotEventPluginLoggingLevel { /** * Standard logging level. */ STANDARD = 'Standard', /** * Detailed logging about the inner workings of the Spot Event Plugin. */ VERBOSE = 'Verbose', /** * All Verbose logs plus additional information on AWS API calls that are used. */ DEBUG = 'Debug', /** * No logging enabled. */ OFF = 'Off', } /** * How the Spot Event Plugin should handle Pre Job Tasks. * See https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/job-scripts.html */ export enum SpotEventPluginPreJobTaskMode { /** * Only start 1 Spot instance for the pre job task and ignore any other tasks for that job until the pre job task is completed. */ CONSERVATIVE = 'Conservative', /** * Do not take the pre job task into account when calculating target capacity. */ IGNORE = 'Ignore', /** * Treat the pre job task like a regular job queued task. */ NORMAL = 'Normal', } /** * The Worker Extra Info column to be used to display AWS Instance Status * if the instance has been marked to be stopped or terminated by EC2 or Spot Event Plugin. * See "AWS Instance Status" option at https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/event-spot.html#event-plugin-configuration-options * and https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/worker-config.html#extra-info */ export enum SpotEventPluginDisplayInstanceStatus { DISABLED = 'Disabled', EXTRA_INFO_0 = 'ExtraInfo0', EXTRA_INFO_1 = 'ExtraInfo0', EXTRA_INFO_2 = 'ExtraInfo0', EXTRA_INFO_3 = 'ExtraInfo0', EXTRA_INFO_4 = 'ExtraInfo0', EXTRA_INFO_5 = 'ExtraInfo0', EXTRA_INFO_6 = 'ExtraInfo0', EXTRA_INFO_7 = 'ExtraInfo0', EXTRA_INFO_8 = 'ExtraInfo0', EXTRA_INFO_9 = 'ExtraInfo0', } /** * The settings of the Spot Event Plugin. * For more details see https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/event-spot.html#event-plugin-configuration-options */ export interface SpotEventPluginSettings { /** * How the event plug-in should respond to events. * * @default SpotEventPluginState.GLOBAL_ENABLED */ readonly state?: SpotEventPluginState; /** * Determines whether the Deadline Resource Tracker should be used. * See https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/resource-tracker-overview.html * * @default true */ readonly enableResourceTracker?: boolean; /** * Spot Event Plugin logging level. * Note that Spot Event Plugin adds output to the logs of the render queue and the Workers. * * @default SpotEventPluginLoggingLevel.STANDARD */ readonly loggingLevel?: SpotEventPluginLoggingLevel; /** * The AWS region in which to start the spot fleet request. * * @default The region of the Render Queue if it is available; otherwise the region of the current stack. */ readonly region?: string; /** * The length of time that an AWS Worker will wait in a non-rendering state before it is shutdown. * Should evenly divide into minutes. * * @default Duration.minutes(10) */ readonly idleShutdown?: Duration; /** * Determines if Deadline Spot Event Plugin terminated AWS Workers will be deleted from the Workers Panel on the next House Cleaning cycle. * * @default false */ readonly deleteSEPTerminatedWorkers?: boolean; /** * Determines if EC2 Spot interrupted AWS Workers will be deleted from the Workers Panel on the next House Cleaning cycle. * * @default false */ readonly deleteEC2SpotInterruptedWorkers?: boolean; /** * Determines if any active instances greater than the target capacity for each group will be terminated. * Workers may be terminated even while rendering. * * @default false */ readonly strictHardCap?: boolean; /** * The Spot Event Plugin will request this maximum number of instances per House Cleaning cycle. * * @default 50 */ readonly maximumInstancesStartedPerCycle?: number; /** * Determines how the Spot Event Plugin should handle Pre Job Tasks. * See https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/job-scripts.html * * @default SpotEventPluginPreJobTaskMode.CONSERVATIVE */ readonly preJobTaskMode?: SpotEventPluginPreJobTaskMode; /** * The Worker Extra Info column to be used to display AWS Instance Status * if the instance has been marked to be stopped or terminated by EC2 or Spot Event Plugin. * All timestamps are displayed in UTC format. * * @default SpotEventPluginDisplayInstanceStatus.DISABLED */ readonly awsInstanceStatus?: SpotEventPluginDisplayInstanceStatus; } /** * Input properties for ConfigureSpotEventPlugin. */ export interface ConfigureSpotEventPluginProps { /** * The VPC in which to create the network endpoint for the lambda function that is * created by this construct. */ readonly vpc: IVpc; /** * The RenderQueue that Worker fleet should connect to. */ readonly renderQueue: IRenderQueue; /** * Where within the VPC to place the lambda function's endpoint. * * @default The instance is placed within a Private subnet. */ readonly vpcSubnets?: SubnetSelection; /** * The array of Spot Event Plugin spot fleets used to generate the mapping between groups and spot fleet requests. * * @default Spot Fleet Request Configurations will not be updated. */ readonly spotFleets?: SpotEventPluginFleet[]; /** * The Spot Event Plugin settings. * See https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/event-spot.html#event-plugin-configuration-options * * @default Default values of SpotEventPluginSettings will be set. */ readonly configuration?: SpotEventPluginSettings; } /** * This construct configures the Deadline Spot Event Plugin to deploy and auto-scale one or more spot fleets. * * For example, to configure the Spot Event Plugin with one spot fleet: * * ```ts * import { App, Stack, Vpc } from '@aws-rfdk/core'; * import { InstanceClass, InstanceSize, InstanceType } from '@aws-cdk/aws-ec2'; * import { AwsThinkboxEulaAcceptance, ConfigureSpotEventPlugin, RenderQueue, Repository, SpotEventPluginFleet, ThinkboxDockerImages, VersionQuery } from '@aws-rfdk/deadline'; * const app = new App(); * const stack = new Stack(app, 'Stack'); * const vpc = new Vpc(stack, 'Vpc'); * const version = new VersionQuery(stack, 'Version', { * version: '10.1.12', * }); * const images = new ThinkboxDockerImages(stack, 'Image', { * version, * // Change this to AwsThinkboxEulaAcceptance.USER_ACCEPTS_AWS_THINKBOX_EULA to accept the terms * // of the AWS Thinkbox End User License Agreement * userAwsThinkboxEulaAcceptance: AwsThinkboxEulaAcceptance.USER_REJECTS_AWS_THINKBOX_EULA, * }); * const repository = new Repository(stack, 'Repository', { * vpc, * version, * }); * const renderQueue = new RenderQueue(stack, 'RenderQueue', { * vpc, * images: images.forRenderQueue(), * repository: repository, * }); * * const fleet = new SpotEventPluginFleet(this, 'SpotEventPluginFleet', { * vpc, * renderQueue, * deadlineGroups: ['group_name'], * instanceTypes: [InstanceType.of(InstanceClass.T3, InstanceSize.LARGE)], * workerMachineImage: new GenericLinuxImage({'us-west-2': 'ami-039f0c1faba28b015'}), * naxCapacity: 1, * }); * * const spotEventPluginConfig = new ConfigureSpotEventPlugin(this, 'ConfigureSpotEventPlugin', { * vpc, * renderQueue: renderQueue, * spotFleets: [fleet], * configuration: { * enableResourceTracker: true, * }, * }); * ``` * * To provide this functionality, this construct will create an AWS Lambda function that is granted the ability * to connect to the render queue. This lambda is run automatically when you deploy or update the stack containing this construct. * Logs for all AWS Lambdas are automatically recorded in Amazon CloudWatch. * * This construct will configure the Spot Event Plugin, but the Spot Fleet Requests will not be created unless you: * - Submit the job with the assigned Deadline Group and Deadline Pool. See [Deadline Documentation](https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/job-submitting.html#submitting-jobs). * * Important: Disable 'Allow Workers to Perform House Cleaning If Pulse is not Running' in the 'Configure Repository Options' * when using Spot Event Plugin. * See https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/event-spot.html#prerequisites * * Important: Any resources created by the Spot Event Plugin will not be deleted with 'cdk destroy'. * Make sure that all such resources (e.g. Spot Fleet Request or Fleet Instances) are cleaned up, before destroying the stacks. * Disable the Spot Event Plugin by setting 'state' property to 'SpotEventPluginState.DISABLED' or via Deadline Monitor, * ensure you shutdown all Pulse instances and then terminate any Spot Fleet Requests in the AWS EC2 Instance Console. * * Note that this construct adds additional policies to the Render Queue's role * required to run the Spot Event Plugin and launch a Resource Tracker: * - AWSThinkboxDeadlineSpotEventPluginAdminPolicy * - AWSThinkboxDeadlineResourceTrackerAdminPolicy * - A policy to pass a fleet and instance role * - A policy to create tags for spot fleet requests * * ![architecture diagram](/diagrams/deadline/ConfigureSpotEventPlugin.svg) * * Resources Deployed * ------------------------ * - An AWS Lambda that is used to connect to the render queue, and save Spot Event Plugin configurations. * - A CloudFormation Custom Resource that triggers execution of the Lambda on stack deployment, update, and deletion. * - An Amazon CloudWatch log group that records history of the AWS Lambda's execution. * - An IAM Policy attached to Render Queue's Role. * * Security Considerations * ------------------------ * - The AWS Lambda that is deployed through this construct will be created from a deployment package * that is uploaded to your CDK bootstrap bucket during deployment. You must limit write access to * your CDK bootstrap bucket to prevent an attacker from modifying the actions performed by this Lambda. * 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. * - The AWS Lambda function that is created by this resource has access to both the certificates used to connect to the render queue, * and the render queue port. An attacker that can find a way to modify and execute this lambda could use it to * execute any requets against the render queue. You should not grant any additional actors/principals the ability to modify * or execute this Lambda. */ export class ConfigureSpotEventPlugin extends Construct { /** * Only one Spot Event Plugin Configuration is allowed per render queue / repository. */ private static uniqueRenderQueues: Set<IRenderQueue> = new Set<IRenderQueue>(); constructor(scope: Construct, id: string, props: ConfigureSpotEventPluginProps) { super(scope, id); if (ConfigureSpotEventPlugin.uniqueRenderQueues.has(props.renderQueue)) { throw new Error('Only one ConfigureSpotEventPlugin construct is allowed per render queue.'); } else { ConfigureSpotEventPlugin.uniqueRenderQueues.add(props.renderQueue); } if (props.renderQueue instanceof RenderQueue) { // We do not check the patch version, so it's set to 0. const minimumVersion: Version = new Version([10, 1, 12, 0]); if (props.renderQueue.version.isLessThan(minimumVersion)) { throw new Error(`Minimum supported Deadline version for ${this.constructor.name} is ` + `${minimumVersion.versionString}. ` + `Received: ${props.renderQueue.version.versionString}.`); } if (props.spotFleets && props.spotFleets.length !== 0) { // Always add Resource Tracker admin policy, even if props.configuration?.enableResourceTracker is false. // This improves usability, as customers won't need to add this policy manually, if they // enable Resource Tracker later in the Spot Event Plugin configuration (e.g., using Deadline Monitor and not RFDK). props.renderQueue.addSEPPolicies(true); const fleetRoles = props.spotFleets.map(sf => sf.fleetRole.roleArn); const fleetInstanceRoles = props.spotFleets.map(sf => sf.fleetInstanceRole.roleArn); new Policy(this, 'SpotEventPluginPolicy', { statements: [ new PolicyStatement({ actions: [ 'iam:PassRole', ], resources: [...fleetRoles, ...fleetInstanceRoles], conditions: { StringLike: { 'iam:PassedToService': 'ec2.amazonaws.com', }, }, }), new PolicyStatement({ actions: [ 'ec2:CreateTags', ], resources: ['arn:aws:ec2:*:*:spot-fleet-request/*'], }), ], roles: [ props.renderQueue.grantPrincipal as Role, ], }); } } else { throw new Error('The provided render queue is not an instance of RenderQueue class. Some functionality is not supported.'); } const region = Construct.isConstruct(props.renderQueue) ? Stack.of(props.renderQueue).region : Stack.of(this).region; const timeoutMins = 15; const configurator = new LambdaFunction(this, 'Configurator', { vpc: props.vpc, vpcSubnets: props.vpcSubnets ?? { subnetType: SubnetType.PRIVATE }, description: `Used by a ConfigureSpotEventPlugin ${this.node.addr} to perform configuration of Deadline Spot Event Plugin`, code: Code.fromAsset(path.join(__dirname, '..', '..', 'lambdas', 'nodejs'), { }), environment: { DEBUG: 'false', LAMBDA_TIMEOUT_MINS: timeoutMins.toString(), }, runtime: Runtime.NODEJS_12_X, handler: 'configure-spot-event-plugin.configureSEP', timeout: Duration.minutes(timeoutMins), logRetention: RetentionDays.ONE_WEEK, }); configurator.connections.allowToDefaultPort(props.renderQueue); props.renderQueue.certChain?.grantRead(configurator.grantPrincipal); const pluginConfig: PluginSettings = { AWSInstanceStatus: props.configuration?.awsInstanceStatus ?? SpotEventPluginDisplayInstanceStatus.DISABLED, DeleteInterruptedSlaves: props.configuration?.deleteEC2SpotInterruptedWorkers ?? false, DeleteTerminatedSlaves: props.configuration?.deleteSEPTerminatedWorkers ?? false, IdleShutdown: props.configuration?.idleShutdown?.toMinutes({integral: true}) ?? 10, Logging: props.configuration?.loggingLevel ?? SpotEventPluginLoggingLevel.STANDARD, PreJobTaskMode: props.configuration?.preJobTaskMode ?? SpotEventPluginPreJobTaskMode.CONSERVATIVE, Region: props.configuration?.region ?? region, ResourceTracker: props.configuration?.enableResourceTracker ?? true, StaggerInstances: props.configuration?.maximumInstancesStartedPerCycle ?? 50, State: props.configuration?.state ?? SpotEventPluginState.GLOBAL_ENABLED, StrictHardCap: props.configuration?.strictHardCap ?? false, }; const spotFleetRequestConfigs = this.mergeSpotFleetRequestConfigs(props.spotFleets); const deadlineGroups = Array.from(new Set(props.spotFleets?.map(fleet => fleet.deadlineGroups).reduce((p, c) => p.concat(c), []))); const deadlinePools = Array.from(new Set(props.spotFleets?.map(fleet => fleet.deadlinePools).reduce((p, c) => p?.concat(c ?? []), []))); const properties: SEPConfiguratorResourceProps = { connection: { hostname: props.renderQueue.endpoint.hostname, port: props.renderQueue.endpoint.portAsString(), protocol: props.renderQueue.endpoint.applicationProtocol, caCertificateArn: props.renderQueue.certChain?.secretArn, }, spotFleetRequestConfigurations: spotFleetRequestConfigs, spotPluginConfigurations: pluginConfig, deadlineGroups, deadlinePools, }; const resource = new CustomResource(this, 'Default', { serviceToken: configurator.functionArn, resourceType: 'Custom::RFDK_ConfigureSpotEventPlugin', properties, }); // Prevents a race during a stack-update. resource.node.addDependency(configurator.role!); // We need to add this dependency to avoid failures while deleting a Custom Resource: // 'Custom Resource failed to stabilize in expected time. If you are using the Python cfn-response module, // you may need to update your Lambda function code so that CloudFormation can attach the updated version.'. // This happens, because Route Table Associations are deleted before the Custom Resource and we // don't get a response from 'doDelete()'. // Ideally, we would only want to add dependency on 'internetConnectivityEstablished' as shown below, // but it seems that CDK misses dependencies on Route Table Associations in that case: // const { internetConnectivityEstablished } = props.vpc.selectSubnets(props.vpcSubnets); // resource.node.addDependency(internetConnectivityEstablished); resource.node.addDependency(props.vpc); // /* istanbul ignore next */ // Add a dependency on the render queue to ensure that // it is running before we try to send requests to it. resource.node.addDependency(props.renderQueue); if (props.spotFleets && props.renderQueue.repository.secretsManagementSettings.enabled) { props.spotFleets.forEach(spotFleet => { if (spotFleet.defaultSubnets) { Annotations.of(spotFleet).addWarning( 'Deadline Secrets Management is enabled on the Repository and VPC subnets have not been supplied. Using dedicated subnets is recommended. See https://github.com/aws/aws-rfdk/blobs/release/packages/aws-rfdk/lib/deadline/README.md#using-dedicated-subnets-for-deadline-components', ); } props.renderQueue.configureSecretsManagementAutoRegistration({ dependent: resource, role: SecretsManagementRole.CLIENT, registrationStatus: SecretsManagementRegistrationStatus.REGISTERED, vpc: props.vpc, vpcSubnets: spotFleet.subnets, }); }); } this.node.defaultChild = resource; } private tagSpecifications(fleet: SpotEventPluginFleet, resourceType: SpotFleetResourceType): IResolvable { return Lazy.any({ produce: () => { if (fleet.tags.hasTags()) { const tagSpecification: SpotFleetTagSpecification = { ResourceType: resourceType, Tags: fleet.tags.renderTags(), }; return [tagSpecification]; } return undefined; }, }); } /** * Construct Spot Fleet Configurations from the provided fleet. * Each congiguration is a mapping between one Deadline Group and one Spot Fleet Request Configuration. */ private generateSpotFleetRequestConfig(fleet: SpotEventPluginFleet): SpotFleetRequestConfiguration[] { const securityGroupsToken = Lazy.any({ produce: () => { return fleet.securityGroups.map(sg => { const securityGroupId: SpotFleetSecurityGroupId = { GroupId: sg.securityGroupId, }; return securityGroupId; }); }}); const userDataToken = Lazy.string({ produce: () => Fn.base64(fleet.userData.render()) }); const blockDeviceMappings = (fleet.blockDevices !== undefined ? this.synthesizeBlockDeviceMappings(fleet.blockDevices) : undefined); const { subnetIds } = fleet.subnets; const subnetId = subnetIds.join(','); const instanceTagsToken = this.tagSpecifications(fleet, SpotFleetResourceType.INSTANCE); const spotFleetRequestTagsToken = this.tagSpecifications(fleet, SpotFleetResourceType.SPOT_FLEET_REQUEST); const launchSpecifications: LaunchSpecification[] = []; fleet.instanceTypes.map(instanceType => { const launchSpecification: LaunchSpecification = { BlockDeviceMappings: blockDeviceMappings, IamInstanceProfile: { Arn: fleet.instanceProfile.attrArn, }, ImageId: fleet.imageId, KeyName: fleet.keyName, // Need to convert from IResolvable to bypass TypeScript SecurityGroups: (securityGroupsToken as unknown) as SpotFleetSecurityGroupId[], SubnetId: subnetId, // Need to convert from IResolvable to bypass TypeScript TagSpecifications: (instanceTagsToken as unknown) as SpotFleetTagSpecification[], UserData: userDataToken, InstanceType: instanceType.toString(), }; launchSpecifications.push(launchSpecification); }); const spotFleetRequestProps: SpotFleetRequestProps = { AllocationStrategy: fleet.allocationStrategy, IamFleetRole: fleet.fleetRole.roleArn, LaunchSpecifications: launchSpecifications, ReplaceUnhealthyInstances: true, // In order to work with Deadline, the 'Target Capacity' of the Spot fleet Request is // the maximum number of Workers that Deadline will start. TargetCapacity: fleet.maxCapacity, TerminateInstancesWithExpiration: true, // In order to work with Deadline, Spot Fleets Requests must be set to maintain. Type: SpotFleetRequestType.MAINTAIN, ValidUntil: fleet.validUntil?.date.toISOString(), // Need to convert from IResolvable to bypass TypeScript TagSpecifications: (spotFleetRequestTagsToken as unknown) as SpotFleetTagSpecification[], }; const spotFleetRequestConfigurations = fleet.deadlineGroups.map(group => { const spotFleetRequestConfiguration: SpotFleetRequestConfiguration = { [group.toLowerCase()]: spotFleetRequestProps, }; return spotFleetRequestConfiguration; }); return spotFleetRequestConfigurations; } /** * Synthesize an array of block device mappings from a list of block devices * * @param blockDevices list of block devices */ private synthesizeBlockDeviceMappings(blockDevices: BlockDevice[]): BlockDeviceMappingProperty[] { return blockDevices.map(({ deviceName, volume, mappingEnabled }) => { const { virtualName, ebsDevice: ebs } = volume; if (volume === BlockDeviceVolume._NO_DEVICE || mappingEnabled === false) { return { DeviceName: deviceName, // To omit the device from the block device mapping, specify an empty string. // See https://docs.aws.amazon.com/cli/latest/reference/ec2/request-spot-fleet.html NoDevice: '', }; } let Ebs: BlockDeviceProperty | undefined; if (ebs) { const { iops, volumeType, volumeSize, snapshotId, deleteOnTermination } = ebs; Ebs = { DeleteOnTermination: deleteOnTermination, Iops: iops, SnapshotId: snapshotId, VolumeSize: volumeSize, VolumeType: volumeType, // encrypted is not exposed as part of ebsDeviceProps so we need to access it via []. // eslint-disable-next-line dot-notation Encrypted: 'encrypted' in ebs ? ebs['encrypted'] : undefined, }; } return { DeviceName: deviceName, Ebs, VirtualName: virtualName, }; }); } private mergeSpotFleetRequestConfigs(spotFleets?: SpotEventPluginFleet[]): SpotFleetRequestConfiguration | undefined { if (!spotFleets || spotFleets.length === 0) { return undefined; } const fullSpotFleetRequestConfiguration: SpotFleetRequestConfiguration = {}; spotFleets.map(fleet => { const spotFleetRequestConfigurations = this.generateSpotFleetRequestConfig(fleet); spotFleetRequestConfigurations.map(configuration => { for (const [key, value] of Object.entries(configuration)) { if (key in fullSpotFleetRequestConfiguration) { throw new Error(`Bad Group Name: ${key}. Group names in Spot Fleet Request Configurations should be unique.`); } fullSpotFleetRequestConfiguration[key] = value; } }); }); return fullSpotFleetRequestConfiguration; } }
the_stack
/// <reference path="../metricsPlugin.ts"/> /// <reference path="../services/alertsManager.ts"/> /// <reference path="../services/errorsManager.ts"/> module HawkularMetrics { export class AppServerDatasourcesDetailsController implements IRefreshable { public static AVAILABLE_COLOR = '#1884c7'; /// blue public static IN_USE_COLOR = '#49a547'; /// green public static TIMED_OUT_COLOR = '#515252'; /// dark gray public static WAIT_COLOR = '#bcb932'; /// yellow public static CREATION_COLOR = '#95489c'; /// purple private static BASE_URL = '/hawkular-ui/app/app-details'; public static DEFAULT_CONN_THRESHOLD = 200; // < 200 # connections available public static DEFAULT_WAIT_THRESHOLD = 200; // > 200 ms average wait time public static DEFAULT_CREA_THRESHOLD = 200; // > 200 ms average creatiion time private autoRefreshPromise: ng.IPromise<number>; private resourceList; ///private expandedList; public alertList; public chartAvailData; public chartRespData; // will contain in the format: 'metric name' : true | false public skipChartData = {}; public driversList; public resolvedAvailData = {}; public resolvedRespData = {}; public defaultEmail: string; public startTimeStamp: TimestampInMillis; public endTimeStamp: TimestampInMillis; private feedId: FeedId; private resourceId: ResourceId; constructor(private $scope: any, private $rootScope: IHawkularRootScope, private $routeParams: any, private $interval: ng.IIntervalService, private $q: ng.IQService, private $filter: any, private HawkularInventory: any, private HawkularMetric: any, private HawkularNav: any, private HawkularAlertsManager: HawkularMetrics.IHawkularAlertsManager, private HawkularAlertRouterManager: IHawkularAlertRouterManager, private ErrorsManager: IErrorsManager, private MetricsService: IMetricsService, private $log: ng.ILogService, private $location: ng.ILocationService, private $modal: any) { $scope.vm = this; this.feedId = this.$routeParams.feedId; this.resourceId = this.$routeParams.resourceId + '~~'; this.startTimeStamp = +moment().subtract(($routeParams.timeOffset || 3600000), 'milliseconds'); this.endTimeStamp = +moment(); this.chartAvailData = {}; this.chartRespData = {}; this.defaultEmail = this.$rootScope.userDetails.email || 'myemail@company.com'; if ($routeParams.action && $routeParams.action === 'add-new') { this.showDatasourceAddDialog(); $location.search('action', null); } // handle drag ranges on charts to change the time range this.$scope.$on('ChartTimeRangeChanged', (event, data: Date[]) => { this.startTimeStamp = data[0].getTime(); this.endTimeStamp = data[1].getTime(); this.HawkularNav.setTimestampStartEnd(this.startTimeStamp, this.endTimeStamp); this.refresh(); }); if ($rootScope.currentPersona) { this.refresh(); } else { /// currentPersona hasn't been injected to the rootScope yet, wait for it.. $rootScope.$watch('currentPersona', (currentPersona) => currentPersona && this.refresh()); } this.autoRefresh(20); } public showDriverAddDialog(): void { /// create a new isolate scope for dialog inherited from current scope instead of default $rootScope let driverAddDialog = this.$modal.open({ templateUrl: 'plugins/metrics/html/app-details/modals/detail-datasources-driver-add.html', controller: 'AppServerDatasourcesDriverAddDialogController as dac', scope: this.$scope.$new() }); driverAddDialog.result.then((modalValue) => { this.refresh(); }, (reason) => { // handle any returned cancel reason if required }); } public showDatasourceAddDialog(): void { /// create a new isolate scope for dialog inherited from current scope instead of default $rootScope let datasourceAddDialog = this.$modal.open({ templateUrl: 'plugins/metrics/html/app-details/modals/detail-datasources-add.html', controller: 'AppServerDatasourcesAddDialogController as dac', scope: this.$scope.$new() }); datasourceAddDialog.result.then((modalValue) => { console.log('sdfsdf'); this.refresh(); }, (reason) => { console.log('sdfsdf'); // handle any returned cancel reason if required }); } /* tslint:disable:no-unused-variable */ public showDatasourceEditDialog(datasource: any): void { /// create a new isolate scope for dialog inherited from current scope instead of default $rootScope let datasourceEditDialog = this.$modal.open({ templateUrl: 'plugins/metrics/html/app-details/modals/detail-datasources-edit.html', controller: 'AppServerDatasourcesEditDialogController as mvm', resolve: { datasource: () => datasource } }); } public deleteDatasource(datasource: any): void { /// create a new isolate scope for dialog inherited from current scope instead of default $rootScope let datasourceDeleteDialog = this.$modal.open({ templateUrl: 'plugins/metrics/html/app-details/modals/detail-datasources-delete.html', controller: 'AppServerDatasourcesDeleteDialogController as mvm', resolve: { datasource: () => datasource } }); datasourceDeleteDialog.result.then((modalValue) => { this.refresh(); }, (reason) => { // handle any returned cancel reason if required }); } public deleteDriver(driver: any): void { /// create a new isolate scope for dialog inherited from current scope instead of default $rootScope let driverDeleteDialog = this.$modal.open({ templateUrl: 'plugins/metrics/html/app-details/modals/detail-datasources-driver-delete.html', controller: 'AppServerDatasourcesDriverDeleteDialogController as mvm', resolve: { driver: () => driver } }); } public autoRefresh(intervalInSeconds: number): void { this.autoRefreshPromise = this.$interval(() => { this.refresh(); }, intervalInSeconds * 1000); this.$scope.$on('$destroy', () => { this.$interval.cancel(this.autoRefreshPromise); }); } public refresh(): void { this.endTimeStamp = this.$routeParams.endTime || +moment(); this.startTimeStamp = this.endTimeStamp - (this.$routeParams.timeOffset || 3600000); this.getDatasources(); this.$rootScope.lastUpdateTimestamp = new Date(); } private getDSMetrics(resourceLists, currentTenantId?: TenantId) { let tenantId: TenantId = currentTenantId || this.$rootScope.currentPersona.id; let promises = []; let tmpResourceList = []; if (!resourceLists.length || _.every(resourceLists, { 'length': 0 })) { this.resourceList = []; this.resourceList.$resolved = true; } angular.forEach(resourceLists, (aResourceList) => { angular.forEach(aResourceList, (res: IResource) => { if (res.id.indexOf(this.$routeParams.resourceId + '~/') === 0) { res.feedId = this.feedId; tmpResourceList.push(res); promises.push(this.HawkularMetric.GaugeMetricData(tenantId).queryMetrics({ gaugeId: MetricsService.getMetricId('M', this.feedId, res.id, 'Datasource Pool Metrics~Available Count'), distinct: true }, (data: number[]) => { res.availableCount = data[0]; }).$promise); promises.push(this.HawkularMetric.GaugeMetricData(tenantId).queryMetrics({ gaugeId: MetricsService.getMetricId('M', this.feedId, res.id, 'Datasource Pool Metrics~In Use Count'), distinct: true }, (data: number[]) => { res.inUseCount = data[0]; }).$promise); this.HawkularAlertRouterManager.registerForAlerts( res.feedId + '/' + res.id, 'datasource', _.bind(AppServerDatasourcesDetailsController.filterAlerts, this, _, res) ); this.getAlerts(res); } }); this.$q.all(promises).then(() => { _.each(tmpResourceList, (item) => { this.initPie(item); }); this.resourceList = tmpResourceList; this.resourceList.$resolved = true; }); }); } public getDatasources(currentTenantId?: TenantId): void { let xaDSsPromise = this.HawkularInventory.ResourceOfTypeUnderFeed.query({ feedId: this.$routeParams.feedId, resourceTypeId: 'XA Datasource' }).$promise; let nonXaDSsPromise = this.HawkularInventory.ResourceOfTypeUnderFeed.query({ feedId: this.$routeParams.feedId, resourceTypeId: 'Datasource' }).$promise; this.$q.all([xaDSsPromise, nonXaDSsPromise]).then((resourceLists) => { this.getDSMetrics(resourceLists, currentTenantId); }); this.getDrivers(); } public static filterAlerts(alertData: IHawkularAlertQueryResult, res: IResource) { let currentAlertList = alertData.alertList; _.forEach(currentAlertList, (item: IAlert) => { item.alertType = item.context.alertType; }); res.alertList = currentAlertList; return currentAlertList; } private getAlerts(res: IResource): void { this.HawkularAlertRouterManager.getAlertsForResourceId( res.feedId + '/' + res.id, this.startTimeStamp, this.endTimeStamp ); } public getDrivers(currentTenantId?: TenantId): void { this.HawkularInventory.ResourceOfTypeUnderFeed.query({ feedId: this.$routeParams.feedId, resourceTypeId: 'JDBC Driver' }, (aResourceList, getResponseHeaders) => { this.driversList = aResourceList; }); } // FIXME: This should be simplified public redirectToDataSource(resource, event) { if (this.canRedirect(event.target)) { this.$location.path( [ AppServerDatasourcesDetailsController.BASE_URL, this.$routeParams.feedId, this.$routeParams.resourceId, this.$routeParams.tabId, Utility.encodeResourceId(resource.id), this.$routeParams.timeOffset || 3600000 * 12, this.$routeParams.endTime || +moment() ].join('/') ); //let newLocation = `${AppServerDatasourcesDetailsController.BASE_URL}/${this.$routeParams.feedId}/` + // `${this.$routeParams.resourceId}/${this.$routeParams.tabId}/${Utility.encodeResourceId(resource.id)}`; //newLocation += this.$routeParams.timeOffset ? `/${this.$routeParams.timeOffset}` : ''; //newLocation += this.$routeParams.endTime ? `/${this.$routeParams.endTime}` : ''; //console.log(newLocation); //this.$location.path(newLocation); } } private canRedirect(clickedElement): boolean { let tags = ['button', 'a']; return !( tags.indexOf(clickedElement.tagName.toLowerCase()) !== -1 || clickedElement.classList.contains('caret') ); } public isDefinedAndValue(value) { return typeof value !== 'undefined' && value != null; } public initPie(data) { if (data && data.inUseCount) { let used = data.inUseCount.value / (data.inUseCount.value + data.availableCount.value) * 100 || 0; used = Math.round(used * 100) / 100; data.chartConfig = { multiLineTitle: [ { text: this.$filter('number')(used, used ? 1 : 0) + '%', dy: -10, classed: 'donut-title-big-pf' }, { text: 'Connections', dy: 20, classed: 'donut-title-small-pf' }, { text: 'Used', dy: 15, classed: 'donut-title-small-pf' } ], type: 'donut', donut: { label: { show: false }, title: used + '%', width: 15 }, size: { height: 171 }, legend: { show: false }, color: { pattern: ['#0088CE', '#D1D1D1'] }, data: { type: 'donut', columns: [ ['Used', used], ['Available', 100 - used] ], groups: [ ['used', 'available'] ], order: null } }; } } } _module.controller('AppServerDatasourcesDetailsController', AppServerDatasourcesDetailsController); }
the_stack
enum TileDir { //% block="--" None, //% block="Left" Left, //% block="Right" Right, //% block="Up" Up, //% block="Down" Down } //% blockId=tiledir block="$dir" function _tileDir(dir: TileDir): number { return dir; } enum ResultSet { //% block="no" Zero, //% block="a" One, //% block="only" Only } enum Membership { //% block="one of" OneOf, //% block="not one of" NotOneOf } enum Spritely { //% block="fixed" Fixed, //% block="movable" Movable } //% weight=1000 color="#442255" icon="\uf45c" //% groups='["Tiles", "Events", "Assertions", "Actions"]' //% blockGap=8 namespace TileWorld { enum CallBackKind { AtRest = TileDir.Down + 1, MoveInto } const tileBits = 4; // a sprite that moves by tiles, but only in one of four directions class TileSprite extends Sprite implements Tile { // which tile map code does this sprite represent? private code: number; // which direction is the target private dir: TileDir; // previous sprite coord value private old: number; // the next tile target private next: number; // have we received a stop request? private stop: boolean; // notification private tileSpriteEvent: (ts: TileSprite, n: CallBackKind) => void; // constructor(world: TileWorld, code: number, image: Image, kind: number) { super(image); const scene = game.currentScene(); scene.physicsEngine.addSprite(this); this.setKind(kind); this.code = code; this.dir = TileDir.None; this.tileSpriteEvent = undefined; this.stop = false; } // moveOne(dir: number) { if (this.dir == TileDir.None) { this.stop = false; if (dir == TileDir.Left || dir == TileDir.Right) this.moveInX(dir); else if (dir == TileDir.Up || dir == TileDir.Down) this.moveInY(dir); } } // stop at current tile deadStop() { if (this.dir == TileDir.Left || this.dir == TileDir.Right) { this.reachedTargetX(this.centerIt(this.x), false) } else { this.reachedTargetY(this.centerIt(this.y), false) } } // back to previous tile knockBack() { if ((this.dir == TileDir.Left || this.dir == TileDir.Right) && this.old != this.getColumn()) { this.x = this.old << tileBits } else if ((this.dir == TileDir.Up || this.dir == TileDir.Down) && this.old != this.getRow()) { this.y = this.old << tileBits } this.deadStop() } // getCode() { return this.code } getDirection() { return this.dir } getColumn() { return this.x >> tileBits } getRow() { return this.y >> tileBits } // notify client on entering tile onTileSpriteEvent(handler: (ts: TileSprite, d: number) => void) { this.tileSpriteEvent = handler } // call from game update loop updateInMotion() { if (this.dir == TileDir.None) return; // have we crossed into a new tile? if (this.tileSpriteEvent) { if (this.dir == TileDir.Left || this.dir == TileDir.Right) { if (this.old != this.getColumn()) { this.tileSpriteEvent(this, CallBackKind.MoveInto+this.dir) } // this.old = this.getColumn() } else if (this.dir == TileDir.Up || this.dir == TileDir.Down) { if (this.old != this.getRow()) { this.tileSpriteEvent(this, CallBackKind.MoveInto+this.dir) } // this.old = this.getRow() } } // have we reached the target? let size = 1 << tileBits if (this.dir == TileDir.Left && this.x <= this.next) { this.reachedTargetX(this.next); } else if (this.dir == TileDir.Right && this.x >= this.next) { this.reachedTargetX(this.next); } else if (this.dir == TileDir.Up && this.y <= this.next) { this.reachedTargetY(this.next); } else if (this.dir == TileDir.Down && this.y >= this.next) { this.reachedTargetY(this.next); } } // updateStationary() { if (this.tileSpriteEvent && this.dir == TileDir.None) { this.tileSpriteEvent(this, CallBackKind.AtRest); } } // private moveInX(dir: TileDir) { let size = 1 << tileBits; let sign = dir == TileDir.Left ? -1 : 1; this.next = this.x + sign * size; this.old = this.getColumn(); this.dir = dir; this.vx = sign * 100; } private moveInY(dir: TileDir) { let size = 1 << tileBits; let sign = dir == TileDir.Up ? -1 : 1 this.next = this.y + sign * size; this.old = this.getRow(); this.dir = dir; this.vy = sign * 100; } private reachedTargetX(x: number, reentrant: boolean = true) { this.x = x; this.vx = 0; let lastDir = this.dir this.dir = TileDir.None if (this.tileSpriteEvent && reentrant) { this.tileSpriteEvent(this, <number>lastDir); } this.old = this.getColumn(); } private reachedTargetY(y: number,reentrant: boolean = true) { this.y = y this.vy = 0 let lastDir = this.dir this.dir = TileDir.None if (this.tileSpriteEvent && reentrant) { this.tileSpriteEvent(this, <number>lastDir) } this.old = this.getRow() } private centerIt(n: number) { return ((n >> tileBits) << tileBits) + (1 << (tileBits - 1)) } } // tileworld actions enum TheActions { Move, Remove, Create, Stop, KnockBack, SetTile } class ClosedAction { constructor(public self: boolean, public action: TheActions, public args: any[]) { } } // the tile world manages tile sprites class TileWorld { // what tile code to put behind a sprite? private backgroundTile: number; private tileKind: number; // the current tile map (no sprites) private tileMap: Image; // fill in with sprites private spriteMap: Image; // note tiles with more than one sprite private multiples: Image; // which codes map to sprites? private spriteCodes: number[]; // map codes to kinds private codeToKind: number[]; // the sprites, divided up by codes private sprites: TileSprite[][]; // event handlers private onPushHandlers: { [index:number]: ((ts: TileSprite, d: TileDir) => void)[] }; private moveIntoHandlers: { [index:number]: ((ts: TileSprite, d: TileDir) => void)[] }; private atRestHandlers: { [index:number]: ((ts: TileSprite) => void)[] }; // constructor() { this.backgroundTile = -1 this.sprites = [] this.codeToKind = [] this.spriteCodes = [] this.onPushHandlers = {} this.moveIntoHandlers = {} this.atRestHandlers = {} this.tileKind = SpriteKind.create() } // methods for defining map and sprites setMap(tileMap: Image) { this.tileMap = tileMap.clone(); this.spriteMap = tileMap.clone(); this.multiples = tileMap.clone(); scene.setTileMap(this.tileMap) game.onUpdate(() => { this.update(); }) } // setBackgroundTile(backgroundTile: number) { this.backgroundTile = backgroundTile } // setCode(curs: Tile, code: number) { this.tileMap.setPixel(curs.getColumn(), curs.getRow(), code) } getCode(curs: Tile) { return this.tileMap.getPixel(curs.getColumn(), curs.getRow()) } getKindFromCode(code: number) { return this.codeToKind[code] } addTiles(code: number, art: Image, kind: number) { let tiles = scene.getTilesByType(code) this.codeToKind[code] = kind; scene.setTile(code, art); } // addTileSprites(code: number, art:Image, kind: number) { let tiles = scene.getTilesByType(code) scene.setTile(code, art); this.spriteCodes.push(code); this.codeToKind[code] = kind; this.initHandlers(kind) this.sprites[code] = [] for (let value of tiles) { let tileSprite = new TileSprite(this, code, art, kind) this.hookupHandlers(tileSprite) this.sprites[code].push(tileSprite) value.place(tileSprite) } // remove from tile map if (this.backgroundTile != -1) { for (let y = 0; y < this.tileMap.height; y++) { for (let x = 0; x < this.tileMap.width; x++) { let pixel = this.tileMap.getPixel(x, y) if (code == pixel) this.tileMap.setPixel(x, y, this.backgroundTile) } } } } getSpritesCount(code: number) { if (this.sprites[code]) return this.sprites[code].length return 0 } createTileSpriteAt(code: number, cursor: Tile) { //let tileSprite = new TileSprite(this, code, art, kind) //this.hookupHandlers(tileSprite) //this.sprites[code].push(tileSprite) } // register event handlers ifAtRest(kind: number, h: (ts: TileSprite) => void) { if (!this.atRestHandlers[kind]) this.atRestHandlers[kind] = [] this.atRestHandlers[kind].push(h); } onPushRequest(kind: number, h: (ts: TileSprite, d: TileDir) => void) { if (!this.onPushHandlers[kind]) this.onPushHandlers[kind] = []; this.onPushHandlers[kind].push(h); } onMoveInto(kind: number, h: (ts: TileSprite, d: TileDir) => void) { if (!this.moveIntoHandlers[kind]) this.moveIntoHandlers[kind] = []; this.moveIntoHandlers[kind].push(h); } public isFixedCode(codeKind: number) { return codeKind < this.tileKind && this.spriteCodes.indexOf(codeKind) == -1 } // how many fixed/movable sprites of codeKind are at a location? // returns -1 if result needs to consult actual sprite list at location countCodeKindAt(codeKind: number, cursor: Cursor) { let col = cursor.getColumn(), row = cursor.getRow() let tileMapCode = this.tileMap.getPixel(col, row) let spriteMapCode = this.spriteMap.getPixel(col, row) if (this.isFixedCode(codeKind)) return (codeKind == tileMapCode) ? 1 : 0 else if (this.multiples.getPixel(col, row)) return -1 else if (codeKind < this.tileKind) return (codeKind == spriteMapCode) ? 1 : 0 else { let tileMapKind = this.codeToKind[tileMapCode] let spriteMapKind = this.codeToKind[spriteMapCode] return (codeKind == tileMapKind ? 1 : 0) + (tileMapCode == spriteMapCode ? 0 : (codeKind == spriteMapKind ? 1 : 0)) } } hasMovableSprite(cursor: Cursor) { let tileMapCode = this.tileMap.getPixel(cursor.getColumn(), cursor.getRow()) let spriteMapCode = this.spriteMap.getPixel(cursor.getColumn(), cursor.getRow()) return spriteMapCode != tileMapCode } // is the underlying tile at a location of codeKind? tileIs(codeKind: number, cursor: Cursor) { let targetCodeKind = this.tileMap.getPixel(cursor.getColumn(), cursor.getRow()) if (codeKind < this.tileKind) return targetCodeKind == codeKind else return this.codeToKind[targetCodeKind] == codeKind } // get all the sprites of codeKind at an (optional) location getSprites(codeKind: number, cursor: Cursor = null) { if (cursor) { return this._getSpritesCursor(codeKind, cursor); } else return this._getSprites(codeKind) } // removeSprite(s: TileSprite) { // TODO: we may want to consider a two phase process where we // TODO: disable the TileSprite and leave Sprite intact this.sprites[s.getCode()].removeElement(s) s.destroy() } private _getSpritesCursor(codeKind: number, cursor: Cursor) { let ss = this._getSprites(codeKind) if (ss) return ss.filter((t: TileSprite) => t.getColumn() == cursor.getColumn() && t.getRow() == cursor.getRow()) else return null } private _getSprites(codeKind: number): any[] { if (codeKind < this.tileKind && this.spriteCodes.indexOf(codeKind) != -1) { return this.sprites[codeKind] } else if (codeKind > this.tileKind) { if (game.currentScene().spritesByKind[codeKind]) return game.currentScene().spritesByKind[codeKind].sprites() } return null; } // private actions: ClosedAction[] = []; private update() { // first recompute the map this.spriteMap.copyFrom(this.tileMap) this.multiples.fill(0) this.sprites.forEach((arr, code) => { if (arr) { arr.forEach((sprite) => { let col = sprite.getColumn(), row = sprite.getRow() let here = this.spriteMap.getPixel(col, row) if (this.spriteCodes.indexOf(here) != -1 && !this.multiples.getPixel(col, row)) { // we have more than 1 sprite at (col,row) this.multiples.setPixel(col, row, 1) } else { // no sprite at this tile yet this.spriteMap.setPixel(col, row, code) } }) } }) // because we queue up actions, there are no state changes here // update sprites in motion this.sprites.forEach((a) => { if (a) a.forEach((s) => s.updateInMotion()) }) // update stationary sprites this.sprites.forEach((a) => { if (a) { a.forEach((s) => s.updateStationary()) } }) // now apply the updates this.actions.forEach((a) => this.processAction(a)) this.actions = [] } public addAction(self: boolean, action: TheActions, args: any[]) { let a = new ClosedAction(self, action, args) // resolve conflicts on motion if (a.action == TheActions.Move) { if (a.self) { // remove non-self moves on same sprite let filter = this.actions.filter(b => !(b.action == TheActions.Move && b.args[0] == a.args[0] && !b.self)) this.actions = filter } else { // don't add if a self move on same sprite if (this.actions.find(b => (b.action == TheActions.Move && b.args[0] == a.args[0] && b.self))) return; } } this.actions.push(a) } private processAction(a: ClosedAction) { switch (a.action) { case TheActions.Move: { (<TileSprite>a.args[0]).moveOne(a.args[1]) break; } case TheActions.Stop: { (<TileSprite>a.args[0]).deadStop() break; } case TheActions.KnockBack: { (<TileSprite>a.args[0]).knockBack() break; } case TheActions.Remove: { this.removeSprite(a.args[0]) break; } case TheActions.Create: { this.createTileSpriteAt(a.args[0], a.args[1]) break; } case TheActions.SetTile: { this.setCode(a.args[0], a.args[1]) break; } } } // handlers private initHandlers(kind: number) { if (!this.atRestHandlers[kind]) this.atRestHandlers[kind] = [] if (!this.onPushHandlers[kind]) this.onPushHandlers[kind] = [] if (!this.moveIntoHandlers[kind]) this.moveIntoHandlers[kind] = [] } private invokeHandlers(s: TileSprite, dir: number, intercept: boolean) { if (dir == CallBackKind.AtRest) { this.atRestHandlers[s.kind()].forEach((h) => { h(s) }); } else if (dir >= CallBackKind.MoveInto) { dir = dir - CallBackKind.MoveInto; this.moveIntoHandlers[s.kind()].forEach((h) => { h(s, dir) }); } else { // process requests out of band if (intercept) { let r = this.interceptRequests.find(r => r.sprite == s && r.dir == dir) if (r) { dir = r.next; // restore default behavior r.next = r.dir } } this.onPushHandlers[s.kind()].forEach((h) => { h(s, dir) }); } } private hookupHandlers(s: TileSprite) { s.onTileSpriteEvent((s, d) => this.invokeHandlers(s,d,true)) } // support for key stroke handling private interceptRequests: { sprite: TileSprite, dir: TileDir, next: TileDir}[] = []; private keyDowns: boolean[] = [ false, false, false, false, false]; private getRequest(sprite: TileSprite, dir: TileDir) { let r = this.interceptRequests.find(r => r.sprite == sprite && r.dir == dir) if (!r) { r = { sprite: sprite, dir: dir, next: dir }; this.interceptRequests.push(r) } return r } requestPush(sprite: TileSprite, dir: TileDir) { this.keyDowns[dir] = true; // is the sprite moving? if (sprite.getDirection() == TileDir.None) { // no - generate push request this.invokeHandlers(sprite, dir, false); let r = this.getRequest(sprite, dir); // set default next direction r.next = dir; } else { // yes - update the next direction for sprite let r = this.getRequest(sprite, sprite.getDirection()); r.next = dir; } } requestStop(sprite: TileSprite, dir: TileDir) { this.keyDowns[dir] = false; // is something else down? let r = this.getRequest(sprite, dir); r.next = TileDir.None; let r2 = this.getRequest(sprite, sprite.getDirection()) // if no change to direction, then stop let down = this.keyDowns.indexOf(true) if (down != -1) r2.next = down; } } class BindController { private sprite: TileSprite; private world: TileWorld; constructor() { } private requestMove(dir: TileDir) { this.world.requestPush(this.sprite, dir) } private requestStop(dir: TileDir) { this.world.requestStop(this.sprite, dir) } // basic movement for tile sprite bindToController(w: TileWorld, s: TileSprite) { this.world = w; this.sprite = s; scene.cameraFollowSprite(s) controller.left.onEvent(ControllerButtonEvent.Pressed, () => { this.requestMove(TileDir.Left) }) controller.left.onEvent(ControllerButtonEvent.Released, () => { this.requestStop(TileDir.Left) }) controller.right.onEvent(ControllerButtonEvent.Pressed, () => { this.requestMove(TileDir.Right) }) controller.right.onEvent(ControllerButtonEvent.Released, () => { this.requestStop(TileDir.Right) }) controller.up.onEvent(ControllerButtonEvent.Pressed, () => { this.requestMove(TileDir.Up) }) controller.up.onEvent(ControllerButtonEvent.Released, () => { this.requestStop(TileDir.Up) }) controller.down.onEvent(ControllerButtonEvent.Pressed, () => { this.requestMove(TileDir.Down) }) controller.down.onEvent(ControllerButtonEvent.Released, () => { this.requestStop(TileDir.Down) }) } } // helpers export interface Tile { getColumn(): number; getRow(): number; } // a cursor is just a coordinate class Cursor implements Tile { private col: number; private row: number; constructor(s: Tile, dir: TileDir, dir2: TileDir = TileDir.None) { this.col = s.getColumn(); this.row = s.getRow(); this.move(dir); this.move(dir2) } private move(dir: TileDir) { switch (dir) { case TileDir.Left: this.col--; break; case TileDir.Right: this.col++; break; case TileDir.Up: this.row--; break; case TileDir.Down: this.row++; break; } } public getColumn() { return this.col } public getRow() { return this.row } } // for assertion checking class CheckFailed { } let checkFailed = new CheckFailed(); function check(expr: boolean) { if (!expr) { throw checkFailed; } } // state here supports blocks let myWorld = new TileWorld(); let myPlayerController = new BindController() // keep track of sprites passed down through active handler // so user code doesn't need to refer to it. let active: TileSprite[] = []; // for current handler, track the sprites targeted by asserytions let targets: { [index:number]: TileSprite } = {}; function getTargetSprite(dir: TileDir) { return targets[dir] } function enterHandler(t: TileSprite) { active.push(t); targets = {}; } function exitHandler(t: TileSprite) { active.pop(); targets = {} } /** * Set the map for placing tiles in the scene * @param map */ //% blockId=TWsettilemap block="set tile map to %map=tilemap_image_picker" //% group="Tiles" export function setTileMap(map: Image) { myWorld.setMap(map) } /** * Set the background tile * @param color */ //% group="Tiles" //% blockId=TWsetbackgroundtile block="set background tile to %color=colorindexpicker" export function setBackgroundTile(code: number) { myWorld.setBackgroundTile(code) } /** * Map a color to a 16x16 tile image and sprite kind. * @param code * @param image * @param moving * @param kind */ //% blockId=TWaddsprite block="map $code=colorindexpicker to $moving sprite $image=tile_image_picker as $kind=spritekind" //% group="Tiles" //% inlineInputMode=inline export function addSprite(code: number, image: Image, moving: Spritely, kind: number) { if (moving == Spritely.Fixed) myWorld.addTiles(code, image, kind) else myWorld.addTileSprites(code, image, kind) } /** * Move sprite with buttons * @param color */ //% group="Tiles" //% blockId=TWmoveButtons block="push $kind=spritekind on dpad" export function moveWithButtons(kind: number) { let sprites = game.currentScene().spritesByKind[kind].sprites() if (sprites && sprites.length > 0) { let first = sprites[0] if (first instanceof TileSprite) { myPlayerController.bindToController(myWorld, first) } } } //% blockId=TWgettilecode block="get code at $dir=tiledir" //% group="Tiles" export function getCode(dir: number) { let sprite = getCurrentSprite() if (sprite) { let cursor = new Cursor(sprite, dir); return myWorld.getCode(cursor) } return 0; } // notifications /** * Act on a sprite that is resting on a tile * @param body code to execute */ //% group="Events" color="#444488" //% blockId=TWontilestationary block="at rest $kind=spritekind" //% blockAllowMultiple=1 draggableParameters="reporter" export function onChangeAround(kind: number, h: () => void) { myWorld.ifAtRest(kind, (t) => { try { enterHandler(t) h() } catch (e) { } finally { exitHandler(t) } }); } /** * Sprite is at center of tile and received request to move * @param body code to execute */ //% group="Events" color="#444488" //% blockId=TWontilearrived block="on push $kind=spritekind $dir" //% blockAllowMultiple=1 draggableParameters="reporter" export function onMoveRequest(kind: number, h: (dir: TileDir) => void) { myWorld.onPushRequest(kind, (t, d) => { try { enterHandler(t) h(d) } catch (e) { } finally { exitHandler(t) } }) } /** * Sprite is moving into a tile * @param body code to execute */ //% group="Events" color="#444488" //% blockId=TWontiletransition block="if $kind=spritekind moves $dir into tile" //% blockAllowMultiple=1 draggableParameters="reporter" export function onMovedInto(kind: number, h: (dir: TileDir) => void) { myWorld.onMoveInto(kind, (t, d) => { try { enterHandler(t) h(d) } catch (e) { } finally { exitHandler(t) } }) } /** * Get the currently active sprite */ //% group="Tiles" //% blockId=TWgetsprite block="get current sprite" export function getCurrentSprite(): TileSprite { if (active.length > 0) return active[active.length-1] else return null } //% group="Tiles" //% blockId=TWgetspritecount block="get sprite count $code=colorindexpicker" export function getSpriteCount(code: number): number { return myWorld.getSpritesCount(code) } // Assertions //% blockId=TWhascode block="pass if $size $code=colorindexpicker at $dir=tiledir $dir2=tiledir " //% group="Assertions" color="#448844" inlineInputMode=inline export function hasCode(code: number, dir: number = TileDir.None, dir2: number = TileDir.None, size: ResultSet = ResultSet.Zero) { let sprite = getCurrentSprite() if (sprite) { let delta = (dir == TileDir.None && dir2 == TileDir.None) ? (code == sprite.getCode() ? -1 : 0) : 0 supportHas(code, true, dir, dir2, size, sprite, delta) } } //% blockId=TWhaskind block="pass if $size $kind=spritekind at $dir=tiledir $dir2=tiledir" //% group="Assertions" color="#448844" inlineInputMode=inline export function hasKind(kind: number, dir: number = TileDir.None, dir2: number = TileDir.None, size: ResultSet = ResultSet.Zero) { let sprite = getCurrentSprite() if (sprite) { let delta = (dir == TileDir.None && dir2 == TileDir.None) ? (kind == sprite.kind() ? -1 : 0) : 0 supportHas(kind, false, dir, dir2, size, sprite, delta) } } // record the sprite, but not two steps away function recordSprite(sprites: TileSprite[], dir: TileDir, dir2: TileDir) { if (sprites && sprites.length > 0) { if (dir == TileDir.None || dir2 == TileDir.None) { let theDir = (dir == TileDir.None) ? dir2 : dir targets[theDir] = sprites[0] } } } function supportHas(codeKind: number, code: boolean, dir: TileDir, dir2: TileDir, size: ResultSet, sprite: TileSprite, delta: number) { let cursor = new Cursor(sprite, dir, dir2) let approxCount = myWorld.countCodeKindAt(codeKind, cursor) if (size == ResultSet.Zero || size == ResultSet.One) { if (approxCount + delta >= 0) { check(size == ResultSet.Zero ? approxCount + delta == 0 : approxCount + delta > 0) recordSprite(myWorld.getSprites(codeKind, cursor), dir, dir2) return; } } else if (size == ResultSet.Only) { // this only applies to fixed sprites, so count is accurate check(!myWorld.hasMovableSprite(cursor) && approxCount == 1) return; } // assert(!myWorld.isFixedCode(codeKind)) let sprites = myWorld.getSprites(codeKind, cursor) let kindOfFixed = myWorld.getKindFromCode(myWorld.getCode(cursor)) let count = (sprites ? sprites.length : 0) + (code ? 0 : (kindOfFixed == codeKind ? 1 : 0)) if (size == ResultSet.Zero) { check(count + delta == 0) } else if (size == ResultSet.One) { check(count + delta > 0) recordSprite(sprites, dir, dir2) } } /** * Check if a direction is one of several values. */ //% group="Assertions" color="#448844" //% blockId=TWisoneof block="pass if %dir=variables_get(dir) $cmp %c1 %c2" //% inlineInputMode=inline export function _isOneOf(dir: number, cmp: Membership = Membership.OneOf, c1: TileDir, c2: TileDir) { if (cmp == Membership.OneOf) check(dir == c1 || dir == c2) else check(dir != c1 && dir != c2) } // Actions // request sprite to move in specified direction //% blockId=TWmoveself block="move $dir=tiledir self" //% group="Actions" color="#88CC44" export function moveSelf(dir: number) { let sprite = getCurrentSprite() if (sprite) { myWorld.addAction(true, TheActions.Move, [sprite,dir]) } } // request sprite to move in specified direction //% blockId=TWmoveother block="move $dir=tiledir other at $otherdir=tiledir" //% group="Actions" color="#88CC44" export function moveOther(otherdir: number, dir: number) { let sprite = getTargetSprite(otherdir) if (sprite) { myWorld.addAction(false, TheActions.Move, [sprite, dir]) } } //% blockId=TWknockbackself block="knockback self" //% group="Actions" color="#88CC44" export function knockBackSelf() { let sprite = getCurrentSprite() if (sprite && sprite.getDirection() != TileDir.None) { myWorld.addAction(false, TheActions.KnockBack, [sprite]) } } //% blockId=TWstopother block="stop other $otherdir=tiledir" //% group="Actions" color="#88CC44" export function stopOther(otherdir: number) { let sprite = getTargetSprite(otherdir) if (sprite && sprite.getDirection() != TileDir.None) { myWorld.addAction(false, TheActions.Stop, [sprite]) } } //% blockId=TWremoveSelf block="remove self" //% group="Actions" color="#88CC44" export function removeSelf() { let sprite = getCurrentSprite() if (sprite) { myWorld.addAction(true, TheActions.Remove, [sprite]) } } //% blockId=TWremoveother block="remove other at $otherdir=tiledir" //% group="Actions" color="#88CC44" export function removeOther(otherdir: number) { let sprite = getTargetSprite(otherdir) if (sprite) { myWorld.addAction(false, TheActions.Remove, [sprite]) } } // direction-based // - set tile code // - create sprite //% blockId=TWsettilecode block="set code $code=colorindexpicker at $dir=tiledir" //% group="Actions" color="#88CC44" export function setCode(code: number, dir: number) { let sprite = getCurrentSprite() if (sprite) { let cursor = new Cursor(sprite, dir); myWorld.addAction(false, TheActions.SetTile, [cursor, code]) } } //% blockId=TWcreatesprite block="create sprite $code=colorindexpicker at $dir=tiledir" //% group="Actions" color="#88CC44" export function createSprite(code: number, dir: number) { let sprite = getCurrentSprite() if (sprite) { myWorld.addAction(false, TheActions.Create, [code, new Cursor(sprite, dir)]) } } }
the_stack
import { IluckyImageBorder,IluckyImageCrop,IluckyImageDefault,IluckyImages,IluckySheetCelldata,IluckySheetCelldataValue,IMapluckySheetborderInfoCellForImp,IluckySheetborderInfoCellValue,IluckySheetborderInfoCellValueStyle,IFormulaSI,IluckySheetRowAndColumnLen,IluckySheetRowAndColumnHidden,IluckySheetSelection,IcellOtherInfo,IformulaList,IformulaListItem, IluckysheetHyperlink, IluckysheetHyperlinkType, IluckysheetDataVerification} from "./ILuck"; import {LuckySheetCelldata} from "./LuckyCell"; import { IattributeList } from "../ICommon"; import {getXmlAttibute, getColumnWidthPixel, fromulaRef,getRowHeightPixel,getcellrange,generateRandomIndex,getPxByEMUs, getMultiSequenceToNum, getTransR1C1ToSequence, getPeelOffX14, getMultiFormulaValue} from "../common/method"; import {borderTypes, COMMON_TYPE2, DATA_VERIFICATION_MAP, DATA_VERIFICATION_TYPE2_MAP, worksheetFilePath} from "../common/constant"; import { ReadXml, IStyleCollections, Element,getColor } from "./ReadXml"; import { LuckyFileBase,LuckySheetBase,LuckyConfig,LuckySheetborderInfoCellForImp,LuckySheetborderInfoCellValue,LuckysheetCalcChain,LuckySheetConfigMerge } from "./LuckyBase"; import {ImageList} from "./LuckyImage"; import dayjs from "dayjs"; export class LuckySheet extends LuckySheetBase { private readXml:ReadXml private sheetFile:string private isInitialCell:boolean private styles:IStyleCollections private sharedStrings:Element[] private mergeCells:Element[] private calcChainEles:Element[] private sheetList:IattributeList private imageList:ImageList private formulaRefList:IFormulaSI constructor(sheetName:string, sheetId:string, sheetOrder:number,isInitialCell:boolean=false, allFileOption:any){ //Private super(); this.isInitialCell = isInitialCell; this.readXml = allFileOption.readXml; this.sheetFile = allFileOption.sheetFile; this.styles = allFileOption.styles; this.sharedStrings = allFileOption.sharedStrings; this.calcChainEles = allFileOption.calcChain; this.sheetList = allFileOption.sheetList; this.imageList = allFileOption.imageList; this.hide = allFileOption.hide; //Output this.name = sheetName; this.index = sheetId; this.order = sheetOrder.toString(); this.config = new LuckyConfig(); this.celldata = []; this.mergeCells = this.readXml.getElementsByTagName("mergeCells/mergeCell", this.sheetFile); let clrScheme = this.styles["clrScheme"] as Element[]; let sheetView = this.readXml.getElementsByTagName("sheetViews/sheetView", this.sheetFile); let showGridLines = "1", tabSelected="0", zoomScale = "100", activeCell = "A1"; if(sheetView.length>0){ let attrList = sheetView[0].attributeList; showGridLines = getXmlAttibute(attrList, "showGridLines", "1"); tabSelected = getXmlAttibute(attrList, "tabSelected", "0"); zoomScale = getXmlAttibute(attrList, "zoomScale", "100"); // let colorId = getXmlAttibute(attrList, "colorId", "0"); let selections = sheetView[0].getInnerElements("selection"); if(selections!=null && selections.length>0){ activeCell = getXmlAttibute(selections[0].attributeList, "activeCell", "A1"); let range:IluckySheetSelection = getcellrange(activeCell, this.sheetList, sheetId); this.luckysheet_select_save = []; this.luckysheet_select_save.push(range); } } this.showGridLines = showGridLines; this.status = tabSelected; this.zoomRatio = parseInt(zoomScale)/100; let tabColors = this.readXml.getElementsByTagName("sheetPr/tabColor", this.sheetFile); if(tabColors!=null && tabColors.length>0){ let tabColor = tabColors[0], attrList = tabColor.attributeList; // if(attrList.rgb!=null){ let tc = getColor(tabColor, this.styles, "b"); this.color = tc; // } } let sheetFormatPr = this.readXml.getElementsByTagName("sheetFormatPr", this.sheetFile); let defaultColWidth, defaultRowHeight; if(sheetFormatPr.length>0){ let attrList = sheetFormatPr[0].attributeList; defaultColWidth = getXmlAttibute(attrList, "defaultColWidth", "9.21"); defaultRowHeight = getXmlAttibute(attrList, "defaultRowHeight", "19"); } this.defaultColWidth = getColumnWidthPixel(parseFloat(defaultColWidth)); this.defaultRowHeight = getRowHeightPixel(parseFloat(defaultRowHeight)); this.generateConfigColumnLenAndHidden(); let cellOtherInfo:IcellOtherInfo = this.generateConfigRowLenAndHiddenAddCell(); if(this.formulaRefList!=null){ for(let key in this.formulaRefList){ let funclist = this.formulaRefList[key]; let mainFunc = funclist["mainRef"], mainCellValue = mainFunc.cellValue; let formulaTxt = mainFunc.fv; let mainR = mainCellValue.r, mainC = mainCellValue.c; // let refRange = getcellrange(ref); for(let name in funclist){ if(name == "mainRef"){ continue; } let funcValue = funclist[name], cellValue = funcValue.cellValue; if(cellValue==null){ continue; } let r = cellValue.r, c = cellValue.c; let func = formulaTxt; let offsetRow = r - mainR, offsetCol = c - mainC; if(offsetRow > 0){ func = "=" + fromulaRef.functionCopy(func, "down", offsetRow); } else if(offsetRow < 0){ func = "=" + fromulaRef.functionCopy(func, "up", Math.abs(offsetRow)); } if(offsetCol > 0){ func = "=" + fromulaRef.functionCopy(func, "right", offsetCol); } else if(offsetCol < 0){ func = "=" + fromulaRef.functionCopy(func, "left", Math.abs(offsetCol)); } // console.log(offsetRow, offsetCol, func); (cellValue.v as IluckySheetCelldataValue ).f = func; } } } if(this.calcChain==null){ this.calcChain = []; } let formulaListExist:IformulaList={}; for(let c=0;c<this.calcChainEles.length;c++){ let calcChainEle = this.calcChainEles[c], attrList = calcChainEle.attributeList; if(attrList.i!=sheetId){ continue; } let r = attrList.r , i = attrList.i, l = attrList.l, s = attrList.s, a = attrList.a, t = attrList.t; let range = getcellrange(r); let chain = new LuckysheetCalcChain(); chain.r = range.row[0]; chain.c = range.column[0]; chain.index = this.index; this.calcChain.push(chain); formulaListExist["r"+r+"c"+c] = null; } //There may be formulas that do not appear in calcChain for(let key in cellOtherInfo.formulaList){ if(!(key in formulaListExist)){ let formulaListItem = cellOtherInfo.formulaList[key]; let chain = new LuckysheetCalcChain(); chain.r = formulaListItem.r; chain.c = formulaListItem.c; chain.index = this.index; this.calcChain.push(chain); } } // dataVerification config this.dataVerification = this.generateConfigDataValidations(); // hyperlink config this.hyperlink = this.generateConfigHyperlinks(); // sheet hide this.hide = this.hide; if(this.mergeCells!=null){ for(let i=0;i<this.mergeCells.length;i++){ let merge = this.mergeCells[i], attrList = merge.attributeList; let ref = attrList.ref; if(ref==null){ continue; } let range = getcellrange(ref, this.sheetList, sheetId); let mergeValue = new LuckySheetConfigMerge(); mergeValue.r = range.row[0]; mergeValue.c = range.column[0]; mergeValue.rs = range.row[1]-range.row[0]+1; mergeValue.cs = range.column[1]-range.column[0]+1; if(this.config.merge==null){ this.config.merge = {}; } this.config.merge[range.row[0] + "_" + range.column[0]] = mergeValue; } } let drawingFile = allFileOption.drawingFile, drawingRelsFile = allFileOption.drawingRelsFile; if(drawingFile!=null && drawingRelsFile!=null){ let twoCellAnchors = this.readXml.getElementsByTagName("xdr:twoCellAnchor", drawingFile); if(twoCellAnchors!=null && twoCellAnchors.length>0){ for(let i=0;i<twoCellAnchors.length;i++){ let twoCellAnchor = twoCellAnchors[i]; let editAs = getXmlAttibute(twoCellAnchor.attributeList, "editAs", "twoCell"); let xdrFroms = twoCellAnchor.getInnerElements("xdr:from"), xdrTos = twoCellAnchor.getInnerElements("xdr:to"); let xdr_blipfills = twoCellAnchor.getInnerElements("a:blip"); if(xdrFroms!=null && xdr_blipfills!=null && xdrFroms.length>0 && xdr_blipfills.length>0){ let xdrFrom = xdrFroms[0], xdrTo = xdrTos[0],xdr_blipfill = xdr_blipfills[0]; let rembed = getXmlAttibute(xdr_blipfill.attributeList, "r:embed", null); let imageObject = this.getBase64ByRid(rembed, drawingRelsFile); // let aoff = xdr_xfrm.getInnerElements("a:off"), aext = xdr_xfrm.getInnerElements("a:ext"); // if(aoff!=null && aext!=null && aoff.length>0 && aext.length>0){ // let aoffAttribute = aoff[0].attributeList, aextAttribute = aext[0].attributeList; // let x = getXmlAttibute(aoffAttribute, "x", null); // let y = getXmlAttibute(aoffAttribute, "y", null); // let cx = getXmlAttibute(aextAttribute, "cx", null); // let cy = getXmlAttibute(aextAttribute, "cy", null); // if(x!=null && y!=null && cx!=null && cy!=null && imageObject !=null){ // let x_n = getPxByEMUs(parseInt(x), "c"),y_n = getPxByEMUs(parseInt(y)); // let cx_n = getPxByEMUs(parseInt(cx), "c"),cy_n = getPxByEMUs(parseInt(cy)); let x_n =0,y_n = 0; let cx_n = 0, cy_n = 0; imageObject.fromCol = this.getXdrValue(xdrFrom.getInnerElements("xdr:col")); imageObject.fromColOff = getPxByEMUs(this.getXdrValue(xdrFrom.getInnerElements("xdr:colOff"))); imageObject.fromRow= this.getXdrValue(xdrFrom.getInnerElements("xdr:row")); imageObject.fromRowOff = getPxByEMUs(this.getXdrValue(xdrFrom.getInnerElements("xdr:rowOff"))); imageObject.toCol = this.getXdrValue(xdrTo.getInnerElements("xdr:col")); imageObject.toColOff = getPxByEMUs(this.getXdrValue(xdrTo.getInnerElements("xdr:colOff"))); imageObject.toRow = this.getXdrValue(xdrTo.getInnerElements("xdr:row")); imageObject.toRowOff = getPxByEMUs(this.getXdrValue(xdrTo.getInnerElements("xdr:rowOff"))); imageObject.originWidth = cx_n; imageObject.originHeight = cy_n; if(editAs=="absolute"){ imageObject.type = "3"; } else if(editAs=="oneCell"){ imageObject.type = "2"; } else{ imageObject.type = "1"; } imageObject.isFixedPos = false; imageObject.fixedLeft = 0; imageObject.fixedTop = 0; let imageBorder:IluckyImageBorder = { color: "#000", radius: 0, style: "solid", width: 0 } imageObject.border = imageBorder; let imageCrop:IluckyImageCrop = { height: cy_n, offsetLeft: 0, offsetTop: 0, width: cx_n } imageObject.crop = imageCrop; let imageDefault:IluckyImageDefault = { height: cy_n, left: x_n, top: y_n, width: cx_n } imageObject.default = imageDefault; if(this.images==null){ this.images = {}; } this.images[generateRandomIndex("image")] = imageObject; // } // } } } } } } private getXdrValue(ele:Element[]):number{ if(ele==null || ele.length==0){ return null; } return parseInt(ele[0].value); } private getBase64ByRid(rid:string, drawingRelsFile:string){ let Relationships = this.readXml.getElementsByTagName("Relationships/Relationship", drawingRelsFile); if(Relationships!=null && Relationships.length>0){ for(let i=0;i<Relationships.length;i++){ let Relationship = Relationships[i]; let attrList = Relationship.attributeList; let Id = getXmlAttibute(attrList, "Id", null); let src = getXmlAttibute(attrList, "Target", null); if(Id == rid){ src = src.replace(/\.\.\//g, ""); src = "xl/" + src; let imgage = this.imageList.getImageByName(src); return imgage; } } } return null; } /** * @desc This will convert cols/col to luckysheet config of column'width */ private generateConfigColumnLenAndHidden(){ let cols = this.readXml.getElementsByTagName("cols/col", this.sheetFile); for(let i=0;i<cols.length;i++){ let col = cols[i], attrList = col.attributeList; let min = getXmlAttibute(attrList, "min", null); let max = getXmlAttibute(attrList, "max", null); let width = getXmlAttibute(attrList, "width", null); let hidden = getXmlAttibute(attrList, "hidden", null); let customWidth = getXmlAttibute(attrList, "customWidth", null); if(min==null || max==null){ continue; } let minNum = parseInt(min)-1, maxNum=parseInt(max)-1, widthNum=parseFloat(width); for(let m=minNum;m<=maxNum;m++){ if(width!=null){ if(this.config.columnlen==null){ this.config.columnlen = {}; } this.config.columnlen[m] = getColumnWidthPixel(widthNum); } if(hidden=="1"){ if(this.config.colhidden==null){ this.config.colhidden = {}; } this.config.colhidden[m] = 0; if(this.config.columnlen){ delete this.config.columnlen[m]; } } if(customWidth!=null){ if(this.config.customWidth==null){ this.config.customWidth = {}; } this.config.customWidth[m] = 1; } } } } /** * @desc This will convert cols/col to luckysheet config of column'width */ private generateConfigRowLenAndHiddenAddCell():IcellOtherInfo{ let rows = this.readXml.getElementsByTagName("sheetData/row", this.sheetFile); let cellOtherInfo:IcellOtherInfo = {}; let formulaList:IformulaList = {}; cellOtherInfo.formulaList = formulaList; for(let i=0;i<rows.length;i++){ let row = rows[i], attrList = row.attributeList; let rowNo = getXmlAttibute(attrList, "r", null); let height = getXmlAttibute(attrList, "ht", null); let hidden = getXmlAttibute(attrList, "hidden", null); let customHeight = getXmlAttibute(attrList, "customHeight", null); if(rowNo==null){ continue; } let rowNoNum = parseInt(rowNo) - 1; if(height!=null){ let heightNum = parseFloat(height); if(this.config.rowlen==null){ this.config.rowlen = {}; } this.config.rowlen[rowNoNum] = getRowHeightPixel(heightNum); } if(hidden=="1"){ if(this.config.rowhidden==null){ this.config.rowhidden = {}; } this.config.rowhidden[rowNoNum] = 0; if(this.config.rowlen){ delete this.config.rowlen[rowNoNum]; } } if(customHeight!=null){ if(this.config.customHeight==null){ this.config.customHeight = {}; } this.config.customHeight[rowNoNum] = 1; } if(this.isInitialCell){ let cells = row.getInnerElements("c"); for(let key in cells){ let cell = cells[key]; let cellValue = new LuckySheetCelldata(cell, this.styles, this.sharedStrings, this.mergeCells,this.sheetFile, this.readXml); if(cellValue._borderObject!=null){ if(this.config.borderInfo==null){ this.config.borderInfo = []; } this.config.borderInfo.push(cellValue._borderObject); delete cellValue._borderObject; } // let borderId = cellValue._borderId; // if(borderId!=null){ // let borders = this.styles["borders"] as Element[]; // if(this.config._borderInfo==null){ // this.config._borderInfo = {}; // } // if( borderId in this.config._borderInfo){ // this.config._borderInfo[borderId].cells.push(cellValue.r + "_" + cellValue.c); // } // else{ // let border = borders[borderId]; // let borderObject = new LuckySheetborderInfoCellForImp(); // borderObject.rangeType = "cellGroup"; // borderObject.cells = []; // let borderCellValue = new LuckySheetborderInfoCellValue(); // let lefts = border.getInnerElements("left"); // let rights = border.getInnerElements("right"); // let tops = border.getInnerElements("top"); // let bottoms = border.getInnerElements("bottom"); // let diagonals = border.getInnerElements("diagonal"); // let left = this.getBorderInfo(lefts); // let right = this.getBorderInfo(rights); // let top = this.getBorderInfo(tops); // let bottom = this.getBorderInfo(bottoms); // let diagonal = this.getBorderInfo(diagonals); // let isAdd = false; // if(left!=null && left.color!=null){ // borderCellValue.l = left; // isAdd = true; // } // if(right!=null && right.color!=null){ // borderCellValue.r = right; // isAdd = true; // } // if(top!=null && top.color!=null){ // borderCellValue.t = top; // isAdd = true; // } // if(bottom!=null && bottom.color!=null){ // borderCellValue.b = bottom; // isAdd = true; // } // if(isAdd){ // borderObject.value = borderCellValue; // this.config._borderInfo[borderId] = borderObject; // } // } // } if(cellValue._formulaType=="shared"){ if(this.formulaRefList==null){ this.formulaRefList = {}; } if(this.formulaRefList[cellValue._formulaSi]==null){ this.formulaRefList[cellValue._formulaSi] = {} } let fv; if(cellValue.v!=null){ fv = (cellValue.v as IluckySheetCelldataValue).f; } let refValue = { t:cellValue._formulaType, ref:cellValue._fomulaRef, si:cellValue._formulaSi, fv:fv, cellValue:cellValue } if(cellValue._fomulaRef!=null){ this.formulaRefList[cellValue._formulaSi]["mainRef"] = refValue; } else{ this.formulaRefList[cellValue._formulaSi][cellValue.r+"_"+cellValue.c] = refValue; } // console.log(refValue, this.formulaRefList); } //There may be formulas that do not appear in calcChain if(cellValue.v!=null && (cellValue.v as IluckySheetCelldataValue).f!=null){ let formulaCell:IformulaListItem = { r:cellValue.r, c:cellValue.c } cellOtherInfo.formulaList["r"+cellValue.r+"c"+cellValue.c] = formulaCell; } this.celldata.push(cellValue); } } } return cellOtherInfo; } /** * luckysheet config of dataValidations * * @returns {IluckysheetDataVerification} - dataValidations config */ private generateConfigDataValidations(): IluckysheetDataVerification { let rows = this.readXml.getElementsByTagName( "dataValidations/dataValidation", this.sheetFile ); let extLst = this.readXml.getElementsByTagName( "extLst/ext/x14:dataValidations/x14:dataValidation", this.sheetFile ) || []; rows = rows.concat(extLst); let dataVerification: IluckysheetDataVerification = {}; for (let i = 0; i < rows.length; i++) { let row = rows[i]; let attrList = row.attributeList; let formulaValue = row.value; let type = getXmlAttibute(attrList, "type", null); let operator = "", sqref = "", sqrefIndexArr: string[] = [], valueArr: string[] = []; let _prohibitInput = getXmlAttibute(attrList, "allowBlank", null) !== "1" ? false : true; // x14 processing const formulaReg = new RegExp(/<x14:formula1>|<xm:sqref>/g) if (formulaReg.test(formulaValue) && extLst?.length >= 0) { operator = getXmlAttibute(attrList, "operator", null); const peelOffData = getPeelOffX14(formulaValue); sqref = peelOffData?.sqref; sqrefIndexArr = getMultiSequenceToNum(sqref); valueArr = getMultiFormulaValue(peelOffData?.formula); } else { operator = getXmlAttibute(attrList, "operator", null); sqref = getXmlAttibute(attrList, "sqref", null); sqrefIndexArr = getMultiSequenceToNum(sqref); valueArr = getMultiFormulaValue(formulaValue); } let _type = DATA_VERIFICATION_MAP[type]; let _type2 = null; let _value1: string | number = valueArr?.length >= 1 ? valueArr[0] : ""; let _value2: string | number = valueArr?.length === 2 ? valueArr[1] : ""; let _hint = getXmlAttibute(attrList, "prompt", null); let _hintShow = _hint ? true : false const matchType = COMMON_TYPE2.includes(_type) ? "common" : _type; _type2 = operator ? DATA_VERIFICATION_TYPE2_MAP[matchType][operator] : "bw"; // mobile phone number processing if ( _type === "text_content" && (_value1?.includes("LEN") || _value1?.includes("len")) && _value1?.includes("=11") ) { _type = "validity"; _type2 = "phone"; } // date processing if (_type === "date") { const D1900 = new Date(1899, 11, 30, 0, 0, 0); _value1 = dayjs(D1900) .clone() .add(Number(_value1), "day") .format("YYYY-MM-DD"); _value2 = dayjs(D1900) .clone() .add(Number(_value2), "day") .format("YYYY-MM-DD"); } // checkbox and dropdown processing if (_type === "checkbox" || _type === "dropdown") { _type2 = null; } // dynamically add dataVerifications for (const ref of sqrefIndexArr) { dataVerification[ref] = { type: _type, type2: _type2, value1: _value1, value2: _value2, checked: false, remote: false, prohibitInput: _prohibitInput, hintShow: _hintShow, hintText: _hint }; } } return dataVerification; } /** * luckysheet config of hyperlink * * @returns {IluckysheetHyperlink} - hyperlink config */ private generateConfigHyperlinks(): IluckysheetHyperlink { let rows = this.readXml.getElementsByTagName( "hyperlinks/hyperlink", this.sheetFile ); let hyperlink: IluckysheetHyperlink = {}; for (let i = 0; i < rows.length; i++) { let row = rows[i]; let attrList = row.attributeList; let ref = getXmlAttibute(attrList, "ref", null), refArr = getMultiSequenceToNum(ref), _display = getXmlAttibute(attrList, "display", null), _address = getXmlAttibute(attrList, "location", null), _tooltip = getXmlAttibute(attrList, "tooltip", null); let _type: IluckysheetHyperlinkType = _address ? "internal" : "external"; // external hyperlink if (!_address) { let rid = attrList["r:id"]; let sheetFile = this.sheetFile; let relationshipList = this.readXml.getElementsByTagName( "Relationships/Relationship", `xl/worksheets/_rels/${sheetFile.replace(worksheetFilePath, "")}.rels` ); const findRid = relationshipList?.find( (e) => e.attributeList["Id"] === rid ); if (findRid) { _address = findRid.attributeList["Target"]; _type = findRid.attributeList[ "TargetMode" ]?.toLocaleLowerCase() as IluckysheetHyperlinkType; } } // match R1C1 const addressReg = new RegExp(/^.*!R([\d$])+C([\d$])*$/g) if (addressReg.test(_address)) { _address = getTransR1C1ToSequence(_address); } // dynamically add hyperlinks for (const ref of refArr) { hyperlink[ref] = { linkAddress: _address, linkTooltip: _tooltip || "", linkType: _type, display: _display || "", }; } } return hyperlink; } // private getBorderInfo(borders:Element[]):LuckySheetborderInfoCellValueStyle{ // if(borders==null){ // return null; // } // let border = borders[0], attrList = border.attributeList; // let clrScheme = this.styles["clrScheme"] as Element[]; // let style:string = attrList.style; // if(style==null || style=="none"){ // return null; // } // let colors = border.getInnerElements("color"); // let colorRet = "#000000"; // if(colors!=null){ // let color = colors[0]; // colorRet = getColor(color, clrScheme); // } // let ret = new LuckySheetborderInfoCellValueStyle(); // ret.style = borderTypes[style]; // ret.color = colorRet; // return ret; // } }
the_stack
import { Uri, DisposableCollection, Event, Emitter, CancellationToken } from '@opensumi/ide-core-common'; import { createBrowserInjector } from '../../../../tools/dev-tool/src/injector-helper'; import { MockInjector } from '../../../../tools/dev-tool/src/mock-injector'; import { IDecorationsService, IDecorationsProvider, IDecorationData } from '../../src'; import { DecorationModule } from '../../src/browser'; describe('DecorationsService', () => { let injector: MockInjector; let service: IDecorationsService; const toTearDown = new DisposableCollection(); beforeEach(() => { injector = createBrowserInjector([DecorationModule]); service = injector.get(IDecorationsService); toTearDown.push(service); }); afterEach(() => toTearDown.dispose()); it('empty result', () => { const uri = Uri.parse('/workspace/test'); expect(service.getDecoration(uri, false)).toBe(undefined); }); it('Async provider, async/evented result', () => { const uri = Uri.parse('foo:bar'); let callCounter = 0; service.registerDecorationsProvider( new (class implements IDecorationsProvider { readonly label: string = 'Test'; readonly onDidChange: Event<Uri[]> = Event.None; provideDecorations(_uri: Uri) { callCounter += 1; return new Promise<IDecorationData>((resolve) => { setTimeout(() => resolve({ color: 'someBlue', tooltip: 'Tooltip', letter: 'L', }), ); }); } })(), ); // trigger -> async expect(service.getDecoration(uri, false)).toBe(undefined); expect(callCounter).toBe(1); // event when result is computed return Event.toPromise(service.onDidChangeDecorations).then((e) => { expect(e.affectsResource(uri)).toBeTruthy(); // sync result expect(service.getDecoration(uri, false)!.tooltip).toBe('Tooltip'); expect(service.getDecoration(uri, false)!.badge).toBe('L'); expect(callCounter).toBe(1); }); }); it('Sync provider, sync result', () => { const uri = Uri.parse('foo:bar'); let callCounter = 0; service.registerDecorationsProvider( new (class implements IDecorationsProvider { readonly label: string = 'Test'; readonly onDidChange: Event<Uri[]> = Event.None; provideDecorations(_uri: Uri) { callCounter += 1; return { color: 'someBlue', tooltip: 'Z' }; } })(), ); // trigger -> sync expect(service.getDecoration(uri, false)!.tooltip).toBe('Z'); expect(callCounter).toBe(1); }); it('Clear decorations on provider dispose', async () => { const uri = Uri.parse('foo:bar'); let callCounter = 0; const reg = service.registerDecorationsProvider( new (class implements IDecorationsProvider { readonly label: string = 'Test'; readonly onDidChange: Event<Uri[]> = Event.None; provideDecorations(_uri: Uri) { callCounter += 1; return { color: 'someBlue', tooltip: 'J' }; } })(), ); // trigger -> sync expect(service.getDecoration(uri, false)!.tooltip).toBe('J'); expect(callCounter).toBe(1); // un-register -> ensure good event let didSeeEvent = false; const p = new Promise<void>((resolve) => { service.onDidChangeDecorations((e) => { expect(e.affectsResource(uri)).toBeTruthy(); expect(service.getDecoration(uri, false)).toBeUndefined(); expect(callCounter).toBe(1); didSeeEvent = true; resolve(); }); }); reg.dispose(); // will clear all data await p; expect(didSeeEvent).toBeTruthy(); }); it('No default bubbling', () => { let reg = service.registerDecorationsProvider({ label: 'Test', onDidChange: Event.None, provideDecorations(uri: Uri) { return uri.path.match(/\.txt/) ? { tooltip: '.txt', weight: 17 } : undefined; }, }); const childUri = Uri.parse('file:///some/path/some/file.txt'); let deco = service.getDecoration(childUri, false)!; expect(deco.tooltip).toBe('.txt'); deco = service.getDecoration(childUri.with({ path: 'some/path/' }), true)!; expect(deco).toBeUndefined(); reg.dispose(); // bubble reg = service.registerDecorationsProvider({ label: 'Test', onDidChange: Event.None, provideDecorations(uri: Uri) { return uri.path.match(/\.txt/) ? { tooltip: '.txt.bubble', weight: 71, bubble: true } : undefined; }, }); deco = service.getDecoration(childUri, false)!; expect(deco.tooltip).toBe('.txt.bubble'); deco = service.getDecoration(childUri.with({ path: 'some/path/' }), true)!; expect(typeof deco.tooltip).toBe('string'); }); it('Decorations not showing up for second root folder #48502', async () => { let cancelCount = 0; let callCount = 0; const provider = new (class implements IDecorationsProvider { _onDidChange = new Emitter<Uri[]>(); onDidChange: Event<Uri[]> = this._onDidChange.event; label = 'foo'; provideDecorations(_uri: Uri, token: CancellationToken): Promise<IDecorationData> { token.onCancellationRequested(() => { cancelCount += 1; }); return new Promise((resolve) => { callCount += 1; setTimeout(() => { resolve({ letter: 'foo' }); }, 10); }); } })(); const reg = service.registerDecorationsProvider(provider); const uri = Uri.parse('foo://bar'); service.getDecoration(uri, false); provider._onDidChange.fire([uri]); service.getDecoration(uri, false); expect(cancelCount).toBe(1); expect(callCount).toBe(2); reg.dispose(); }); it('Decorations not bubbling... #48745', () => { const reg = service.registerDecorationsProvider({ label: 'Test', onDidChange: Event.None, provideDecorations(uri: Uri) { if (uri.path.match(/hello$/)) { return { tooltip: 'FOO', weight: 17, bubble: true }; } else { return new Promise<IDecorationData>((_resolve) => {}); } }, }); const data1 = service.getDecoration(Uri.parse('a:b/'), true); expect(!data1).not.toBeUndefined(); const data2 = service.getDecoration(Uri.parse('a:b/c.hello'), false)!; expect(data2.tooltip).not.toBeUndefined(); const data3 = service.getDecoration(Uri.parse('a:b/'), true); expect(data3).not.toBeUndefined(); reg.dispose(); }); it("Folder decorations don't go away when file with problems is deleted #61919 (part1)", () => { const emitter = new Emitter<Uri[]>(); let gone = false; const reg = service.registerDecorationsProvider({ label: 'Test', onDidChange: emitter.event, provideDecorations(uri: Uri) { if (!gone && uri.path.match(/file.ts$/)) { return { tooltip: 'FOO', weight: 17, bubble: true }; } return undefined; }, }); const uri = Uri.parse('foo:/folder/file.ts'); const uri2 = Uri.parse('foo:/folder/'); let data = service.getDecoration(uri, true)!; expect(data.tooltip).toBe('FOO'); data = service.getDecoration(uri2, true)!; expect(data.tooltip); // emphazied items...not.toBeUndefined(). gone = true; emitter.fire([uri]); data = service.getDecoration(uri, true)!; expect(data).toBeUndefined(); data = service.getDecoration(uri2, true)!; expect(data).toBeUndefined(); reg.dispose(); }); it("Folder decorations don't go away when file with problems is deleted #61919 (part2)", () => { const emitter = new Emitter<Uri[]>(); let gone = false; const reg = service.registerDecorationsProvider({ label: 'Test', onDidChange: emitter.event, provideDecorations(uri: Uri) { if (!gone && uri.path.match(/file.ts$/)) { return { tooltip: 'FOO', weight: 17, bubble: true }; } return undefined; }, }); const uri = Uri.parse('foo:/folder/file.ts'); const uri2 = Uri.parse('foo:/folder/'); let data = service.getDecoration(uri, true)!; expect(data.tooltip).toBe('FOO'); data = service.getDecoration(uri2, true)!; expect(data.tooltip); // emphazied items...not.toBeUndefined(). return new Promise<void>((resolve, reject) => { const l = service.onDidChangeDecorations((e) => { l.dispose(); try { expect(e.affectsResource(uri)).not.toBeUndefined(); expect(e.affectsResource(uri2)).not.toBeUndefined(); resolve(); reg.dispose(); } catch (err) { reject(err); reg.dispose(); } }); gone = true; emitter.fire([uri]); }); }); it('Initial flush/Flush all', async () => { let callCount = 0; const provider = new (class implements IDecorationsProvider { _onDidChange = new Emitter<Uri[]>(); onDidChange: Event<Uri[]> = this._onDidChange.event; label = 'foo'; provideDecorations(_uri: Uri): IDecorationData { callCount += 1; return { letter: 'foo', }; } })(); const uri = Uri.file('/test/workspace'); service.getDecoration(uri, false); const reg = service.registerDecorationsProvider(provider); // test for flush const event1 = service.onDidChangeDecorations((e) => { event1.dispose(); expect(e.affectsResource(uri)).toBeTruthy(); expect(e.affectsResource(Uri.parse('git://aa.ts'))).toBeTruthy(); expect(e.affectsResource(undefined as any)).toBeTruthy(); }); provider._onDidChange.fire([uri]); service.getDecoration(uri, false); expect(callCount).toBe(1); // test for flush const event2 = service.onDidChangeDecorations((e) => { event2.dispose(); expect(e.affectsResource(uri)).toBeTruthy(); expect(e.affectsResource(Uri.parse('git://aa.ts'))).toBeTruthy(); expect(e.affectsResource(undefined as any)).toBeTruthy(); reg.dispose(); }); // force flush data provider._onDidChange.fire(undefined as any); }); it('Multi decorations', async () => { const uri = Uri.parse('foo:bar'); let callCounter = 0; toTearDown.push( service.registerDecorationsProvider( new (class implements IDecorationsProvider { readonly label: string = 'TestSync'; readonly onDidChange: Event<Uri[]> = Event.None; provideDecorations(_uri: Uri) { callCounter += 1; return { color: 'someBlue', tooltip: 'Z', letter: 'A', }; } })(), ), ); // trigger -> sync expect(service.getDecoration(uri, false)!.tooltip).toBe('Z'); expect(service.getDecoration(uri, false)!.color).toBe('someBlue'); expect(service.getDecoration(uri, false)!.badge).toBe('A'); expect(callCounter).toBe(1); toTearDown.push( service.registerDecorationsProvider( new (class implements IDecorationsProvider { readonly label: string = 'TestSync1'; readonly onDidChange: Event<Uri[]> = Event.None; provideDecorations(_uri: Uri) { callCounter += 1; return { color: 'someGreen', tooltip: 'Tooltip', letter: 'L', weight: 1, }; } })(), ), ); // trigger -> sync expect(service.getDecoration(uri, false)!.tooltip).toBe('Tooltip • Z'); expect(service.getDecoration(uri, false)!.color).toBe('someGreen'); expect(service.getDecoration(uri, false)!.badge).toBe('L,A'); expect(callCounter).toBe(2); }); });
the_stack
import Taro, { Config } from "@tarojs/taro"; import { View, Text, Image, Input, Swiper, SwiperItem, } from "@tarojs/components"; import { banners, classify, homeCenterQuery, items, homeCenter, invitedUsers, projectItems, singleItem } from "./service"; import { AtIcon } from "taro-ui"; import { userInfo } from "../orderDetails/service"; import shoppingScan from '../../img/shoppingScan.png' import { connect } from '@tarojs/redux'; import "./index.less"; import scan from "../../img/scan.png"; import diamond from "../../img/diamond.png"; // 引入moment import moment from "moment"; moment.locale("zh-cn"); interface IState { tabbarFix: boolean; fixTop: number, authorization: boolean; query: { data: any; }; myUserDetail: { data: any; }; myLatitude: number; myLongitude: number; sotreQuery: { data: any; }; addressQuery: { data: any; }; centerQuery: { data: any; }; bottomQuery: { data: any; }; classifyQuery: { data: any; }; itemsQuery: { data: any; }; StoreName: { data: any; }; projectItems1: { data: any; } projectItems2: { data: any; } projectItems3: { data: any; } input: string; list?: any; statusBar: number; ToUpper: boolean; } @connect(({ common }) => ({ common })) export default class Home extends Taro.Component<any, IState> { config: Config = { navigationBarTitleText: "有地道", // 状态栏自定义 navigationStyle: "custom", // 状态栏颜色白色 navigationBarTextStyle: "white", }; state = { statusBar: 0, fixTop: 0, tabbarFix: false, authorization: false, query: { data: null, loading: true, }, myUserDetail: { data: null, loading: true, }, StoreName: { data: null, loading: true, }, sotreQuery: { data: null, loading: true }, addressQuery: { data: null }, centerQuery: { data: null }, bottomQuery: { data: null }, classifyQuery: { data: null }, itemsQuery: { data: null }, projectItems1: { data: null }, projectItems2: { data: null }, projectItems3: { data: null }, myLatitude: 1, myLongitude: 1, input: "", ToUpper: false }; // 页面加载前 async componentWillMount() { Taro.showShareMenu({ withShareTicket: true }); if (!Taro.getStorageSync("storeId")) { Taro.navigateTo({ url: "../nearbystores/index" }); } const projectItems1 = await projectItems(1, 1) const { imageUrl } = projectItems1.data.items.list[0]; this.setState({ projectItems1: imageUrl }); const projectItems2 = await projectItems(2, 2) const { list: projectItems2List } = projectItems2.data.items; this.setState({ projectItems2: projectItems2List }); const projectItems3 = await projectItems(3, 2) const { list: projectItems3List } = projectItems3.data.items; this.setState({ projectItems3: projectItems3List }); const userDetail = await userInfo(); this.setState({ myUserDetail: userDetail.data.userInfo }); } async componentDidShow() { //会获取组件到最上面的距离(就是我菜单的class) if (this.state.fixTop === 0) { wx.createSelectorQuery().select('#topTabBar').boundingClientRect(res => { console.log('componentDidMount res', res); if (res && res.top) { this.setState({ fixTop: res.top, }) } }).exec(); } //店铺名称 const nearbyStoreName = Taro.getStorageSync("nearbyStoreName"); this.setState({ StoreName: nearbyStoreName }); } //下拉刷新 async onPullDownRefresh() { // 获取top Banner const result = await banners("top"); this.setState({ query: result }); const centerImge = await homeCenterQuery("center"); this.setState({ centerQuery: centerImge }); const bottomResult = await homeCenter("bottom"); this.setState({ bottomQuery: bottomResult }); // 商品分类 const classResult = await classify(); this.setState({ classifyQuery: classResult }); // 商品 const goods = await items(18, 1); this.setState({ itemsQuery: goods }); setTimeout(() => { Taro.stopPullDownRefresh(); //停止下拉刷新 this.setState({ ToUpper: false }) }, 1500); } // 搜索按钮 clickSearch() { const { input } = this.state; Taro.navigateTo({ url: `../searchPage/index?nameLike=${input}` }); } // 跳转取货码 itemDetails() { Taro.switchTab({ url: "../certificates/index" }); } // 跳转附件商家列表 nearbystores() { Taro.navigateTo({ url: "../nearbystores/index" }); } async lookForward() { const { dispatch } = this.props; const { result } = await Taro.scanCode(); console.log('扫码result', result); const obj = JSON.parse(result); if (obj.userId) { console.log('扫码邀请'); const { data } = await invitedUsers(obj.userId); console.log('lookForward data',data); if (data) { Taro.showToast({ title: "绑定成功", icon: "success" }) } } else { console.log('扫码加购'); const itemResult = await singleItem(result); console.log('扫码加入购物车itemResult', itemResult); const data: any = {}; data.itemId = itemResult.data.item.code; data.name = itemResult.data.item.name; data.number = 1; data.price = itemResult.data.item.price; data.unit = itemResult.data.item.unit; data.imageUrl = itemResult.data.item.imageUrl; data.pointDiscountPrice = itemResult.data.item.pointDiscountPrice; data.originalPrice = itemResult.data.item.originalPrice; data.memberPrice = itemResult.data.item.memberPrice; await dispatch({ type: 'common/addToCartByCode', payload: data }); } } // 专题 handleProject(id) { Taro.navigateTo({ url: `../project/index?id=${id}` }); } onOpenDoor(code, name, number, price, unit, imageUrl, pointDiscountPrice, originalPrice, memberPrice) { const data: any = {}; data.itemId = code; data.name = name; data.number = number; data.price = price; data.unit = unit; data.imageUrl = imageUrl; data.pointDiscountPrice = pointDiscountPrice; data.originalPrice = originalPrice; data.memberPrice = memberPrice; console.log('data', data); const { dispatch } = this.props; dispatch({ type: 'common/addToCartByCode', payload: data }); } // 跳转商品详情 handleDetails(code) { Taro.navigateTo({ url: `../details/index?code=${code}` }); } //分类跳转 handleItemLists(id, title) { Taro.navigateTo({ url: `../itemLists/index?id=${id}&title=${title}` }); } // 搜索框内容修改 handleOnChange(e) { this.setState({ input: e.detail.value }); } async componentDidMount() { // 获取设备状态栏高度 var that = this; wx.getSystemInfo({ success(e) { console.log('设备状态栏高度e', e); console.log('设备状态栏高度this', this); that.setState({ statusBar: e.statusBarHeight }) console.log('setState statusBar'); } }) // 获取top Banner const result = await banners("top"); this.setState({ query: result }); const centerImge = await homeCenterQuery("center"); this.setState({ centerQuery: centerImge }); const bottomResult = await homeCenter("bottom"); this.setState({ bottomQuery: bottomResult }); // 商品分类 const classResult = await classify(); this.setState({ classifyQuery: classResult }); // 商品 const goods = await items(18, 1); console.log('首页商品goods', goods); this.setState({ itemsQuery: goods }); } // 会员活动 TopUPGetMember() { const { myUserDetail } = this.state; Taro.checkSession({ success() { if (myUserDetail.role === 'member') { Taro.navigateTo({ url: "../theMemberCenter/index" }); } else { Taro.navigateTo({ url: '../../packageA/pages/topup/index' }); } }, fail() { Taro.showToast({ title: "请跳转我的界面进行登录", icon: "none" }); } }) } // 监听用户滑动页面事件 onPageScroll(e) { // console.log('监听用户滑动onPageScrollonPageScroll', e); const scrollTop = parseInt(e.scrollTop); const isSatisfy = scrollTop >= this.state.fixTop ? true : false; if (this.state.tabbarFix === isSatisfy) { return false; } this.setState({ tabbarFix: isSatisfy }) } // 手势触摸开始 // onTouchStart(e){ // console.log('onTouchStart e',e); // } render() { const { cartItems } = this.props.common; // 购物车右上角图标 if (cartItems.length === 0) { Taro.removeTabBarBadge({ index: 2 }) } else { let sum = 0; let i; for (i in cartItems) { if (cartItems[i].checked) { sum += parseInt(cartItems[i].number); } } Taro.setTabBarBadge({ index: 2, text: "" + sum + "", }) } const { query, classifyQuery, itemsQuery, StoreName, projectItems1, projectItems2, projectItems3, tabbarFix, statusBar, ToUpper } = this.state; // 状态栏高度大于20 定义barHeight let barHeight = 32; if (statusBar > 20) { barHeight = barHeight + (statusBar - 20) } console.log('barHeight', barHeight); console.log('状态栏高度', statusBar); if (query.loading) { return Taro.showLoading({ title: "加载中" }); } else { Taro.hideLoading(); } if (ToUpper) { return Taro.showLoading({ title: "加载中" }); } else { Taro.hideLoading(); } const banners = query.data.banners; // const upper = 10 return ( <View className="index" // onTouchStart={this.onTouchStart} > {/* 轮播图 */} <Swiper indicatorColor="#333" indicatorActiveColor="#00bc71" circular indicatorDots autoplay style={ statusBar <= 20 ? "width: 100%;height: 250PX;z-index: 1;" : `width: 100%;height: ${statusBar - 20 + 250}PX;z-index: 1;` } className="topBanner-box" > {banners.map(topBanner => ( <SwiperItem key={topBanner.id}> <Image src={topBanner.imageUrl} style={ statusBar <= 20 ? 'width:100%;height:250PX;z-index:0;' : `width:100%;height:${statusBar - 20 + 250}PX;z-index:0;` } /> </SwiperItem> ))} </Swiper> <View className={tabbarFix ? 'absorption' : 'firstViewBox'} style={ tabbarFix ? `height:${statusBar - 20 + 115}Px;top:0;` : `top:${barHeight}PX;` } id="topTabBar" > <View className='youDiDaoTitle' style={ tabbarFix? `display: flex;justify-content: space-between;margin-top: ${statusBar - 20 + 33}PX;` :`display: flex;justify-content: space-between;margin: 9px;margin-top: 0;margin-left:15px;` } > <Text className="youDiDaoName"> 有地道门店平台 </Text> </View> {/* 第一行地址扫码及取货 */} <View className={tabbarFix ? "firstAbsorption" : "firstLineView"} style={ tabbarFix ? `display: flex;justify-content: space-between;margin: 9px;margin-left:15px;margin-top: ${statusBar - 20 + 16}PX;` : "display: flex;justify-content: space-between;margin: 9px;margin-top: 0;margin-left:15px;" } > <View className="firstLineLeft" onClick={this.nearbystores} > <Image src="https://mengmao-qingying-files.oss-cn-hangzhou.aliyuncs.com/bottomIcon.png" className="storeIcon" /> <Text /> <Text className="chooseStore"> {StoreName ? StoreName : '请选择店铺!'} </Text> </View> <View className="rightSearchBox"> <Image src='https://mengmao-qingying-files.oss-cn-hangzhou.aliyuncs.com/searchimg.png' className="searchImg" /> <Input type="text" placeholder="搜索你想要的商品" className="input" value={this.state.input} onInput={this.handleOnChange} // disabled onConfirm={this.clickSearch} /> <View className="firstLineLeft" onClick={this.lookForward}> <Image src={scan} className="scanIcon" /> </View> </View> </View> {/* {tabbarFix ? null : ( <View className='searchAscan'> <View className="rightSearchBox"> <Image src='https://mengmao-qingying-files.oss-cn-hangzhou.aliyuncs.com/searchimg.png' className="searchImg" /> <Input type="text" placeholder="搜索你想要的商品" className="input" value={this.state.input} onInput={this.handleOnChange} // disabled onConfirm={this.clickSearch} /> </View> <View className="firstLineLeft"> <View className="firstLineLeft" onClick={this.lookForward}> <Image src={scan} className="scanIcon" /> <Text className="sweep">扫码</Text> </View> </View> </View> )} */} </View> {/* 分类 */} <View className="Grid"> {classifyQuery.data.classify.map(gir => ( <View className="gird" onClick={this.handleItemLists.bind(this, gir.id, gir.title)} key={gir.id} > <Image src={gir.imageUrl} className="gird_img" /> <Text className="grid_title">{gir.title}</Text> </View> ))} </View> {/* 横线 */} <View className="boldLine" /> {/* 充值 */} <View className='bg_f5' onClick={this.TopUPGetMember} > <View className='TopUP'> <View style="flex-direction:row;align-items:center;display:flex;"> <Image src={diamond} className="diamondImg" /> <Text className='leftTopUp'>加入有地道会员·每月领99元专享券</Text> </View> <Text className='rightTopUp'>丨1折开卡</Text> </View> </View> {/* 横线 */} <View className="boldLine" /> {/* 特色专区 */} <View className="SpecialZone"> <View className="WithinSpecialZone" onClick={this.handleProject.bind(this, 1)} > <View className="TodaySpecial"> <View className="TodaySpecialCode"> <Text className="TodaySpecialTitle">每周新品</Text> <Text className="TodaySpecialLittle">低至一元起</Text> </View> <Text className="TodaySpecialCon">精选低价 持续热销</Text> </View> <View className="specialLeftBox"> <Image src={projectItems1} className="leftSpecial" /> </View> </View> <View className="WithinSpecialZone2"> <View className="specialLeftBox1" onClick={this.handleProject.bind(this, 2)} > <View className="TodaySpecial"> <View className="TodaySpecialCode"> <Text className="TodaySpecialTitle">品牌主打</Text> <Text className="TodaySpecialLittle SpecialCoupon">领券超优惠</Text> </View> <Text className="TodaySpecialBrand">品牌特色 味蕾释放</Text> </View> <View className="SpecialZoneImg"> <Image src={projectItems2[0].imageUrl} className="leftSpecial1" /> <Image src={projectItems2[1].imageUrl} className="leftSpecial1" /> </View> </View> <View className='divider'></View> <View className="specialLeftBox2" onClick={this.handleProject.bind(this, 3)} > <View className="TodaySpecial"> <View className="TodaySpecialCode"> <Text className="TodaySpecialTitle">能量必备</Text> </View> <Text className="TodaySpecialBrand">能量加油站 精神整天</Text> </View> <View className="SpecialZoneImg"> <Image src={projectItems3[0].imageUrl} className="leftSpecial1" /> <Image src={projectItems3[1].imageUrl} className="leftSpecial1" /> </View> </View> </View> </View> {/* 横线 */} <View className="boldLine" /> {/* 为你优选 */} <View className="optimizationBox"> <View className="optimizationLine"> <View className="line" /> <Text className="optimizationText">为你推荐</Text> <View className="line" /> </View> <View className="items_box"> {itemsQuery.data.items.list.map(item => ( <View className="item_box" key={item.code} > <Image src={item.imageUrl} className="image" onClick={this.handleDetails.bind(this, item.code)} /> <View className="item_bottom_box"> <Text className="title" onClick={this.handleDetails.bind(this, item.code)}>{item.name}</Text> <View className="item_right_box"> <View className="priceBox"> <Text className="price"> ¥{(item.price / 100).toFixed(2)}/{item.unit} </Text> <Text className="originalPrice"> ¥{(item.originalPrice / 100).toFixed(2)} </Text> </View> <View className="shoppingCart" onClick={this.onOpenDoor.bind(this, item.code, item.name, 1, item.price, item.unit, item.imageUrl, item.pointDiscountPrice, item.originalPrice, item.memberPrice, )} > <AtIcon value='shopping-cart' size='20' color='#fff'></AtIcon> </View> </View> </View> </View> ))} </View> </View> <View className='shoppingScan' onClick={this.lookForward}> <Image src={shoppingScan} /> <Text className='shoppingScanTxt1'>扫一扫</Text> <Text className='shoppingScanTxt2'>商品条形码</Text> </View> </View> ); } }
the_stack
import { CObject, Collab, CollabEventsRecord, DefaultSerializer, InitToken, Message, MessageMeta, Optional, Pre, PublicCObject, RunLocallyLayer, Runtime, Serializer, } from "@collabs/core"; import { ISemidirectProductRevSenderHistory, SemidirectProductRevSave, } from "../../generated/proto_compiled"; import { CRDTMeta, CRDTMetaRequestee } from "../crdt-runtime"; /* eslint-disable */ // TODO: revise this file. class StoredMessage { constructor( readonly senderCounter: number, readonly receiptCounter: number, readonly targetPath: string[], readonly crdtMeta: CRDTMeta | null, readonly message: Uint8Array ) {} } export class StoredMessageEvent { constructor(readonly eventName: string, readonly event: any) {} } // TODO: future opts: indexed messages; setting the history // to a subset; causal stability. // TODO: for this to work, replicaID's must be comparable according // to the same-equals approach. Typically, this requires them // to be primitive types, as objects which are equal-valued but have // different pointers will be considered different. // TODO: mention that to get a proper CRDT (equal internal states), // we technically must compare receipt orders as equivalent if // they are both in causal order. // TODO: In runtime, store a mapping from `${meta.sender}{meta.vectorClock.get(meta.sender)}` to the events triggered by the message. // TODO: In runtime, add a getMessageEvents() method that retrieves the list of events from mapping.get(`${meta.sender}{meta.vectorClock.get(meta.sender)}`) // TODO: In runtime, add an addMessageEventIfTracked() method that does mapping.get(`${meta.sender}{meta.vectorClock.get(meta.sender)}`).push(event) if the mapping has the key. // TODO: In runtime, add a trackMessageEvents() method that adds `${meta.sender}{meta.vectorClock.get(meta.sender)}`: [] to the mapping. // TODO: In runtime, add an untrackMessageEvents() method that removes `${meta.sender}{meta.vectorClock.get(meta.sender)}` from the mapping. // TODO: In Collab's omit, call addMessageEventIfTracked() export class MessageHistory<Events extends CollabEventsRecord> { protected receiptCounter = 0; /** * Maps a replica id to an array of messages sent by that * replica, in order. Keep in mind that per-sender message * counters may not be contiguous, since they are shared between * all Collabs with a given root. */ protected history: Map<string, Array<StoredMessage>> = new Map(); protected messageEvents: Map<string, Array<StoredMessageEvent>> = new Map(); constructor( private readonly historyTimestamps: boolean, private readonly historyDiscard1Dominated: boolean, private readonly historyDiscard2Dominated: boolean ) {} /** * Add message to the history with the given crdtMeta. * replicaID is our replica id. */ add( replicaID: string, targetPath: string[], crdtMeta: CRDTMeta, message: Uint8Array ): string { if (this.historyDiscard2Dominated) { this.processTimestamp(replicaID, crdtMeta, false, true); } let senderHistory = this.history.get(crdtMeta.sender); if (senderHistory === undefined) { senderHistory = []; this.history.set(crdtMeta.sender, senderHistory); } senderHistory.push( new StoredMessage( crdtMeta.senderCounter, this.receiptCounter, targetPath, this.historyTimestamps ? crdtMeta : null, message ) ); const m2Id = `${crdtMeta.sender}${crdtMeta.senderCounter}`; // Start tracking message events this.messageEvents.set(`${crdtMeta.sender}${crdtMeta.senderCounter}`, []); this.receiptCounter++; return m2Id; } /** * Return all messages in the history concurrent to the given * crdtMeta, in some causal order (specifically, this replica's * receipt order). If we are the sender (i.e., replicaID === * crdtMeta.sender), it is assumed that the crdtMeta is * causally greater than all prior messages, hence [] is returned. */ getConcurrent(replicaID: string, crdtMeta: CRDTMeta) { return this.processTimestamp( replicaID, crdtMeta, true, this.historyDiscard1Dominated ); } /** * Performs specified actions on all messages in the history: * - if returnConcurrent is true, returns the list of * all messages in the history concurrent to crdtMeta, in * receipt order. * - if discardDominated is true, deletes all messages from * the history whose crdtMetas are causally dominated by * or equal to the given crdtMeta. (Note that this means that * if we want to keep a message with the given crdtMeta in * the history, it must be added to the history after calling * this method.) */ private processTimestamp( replicaID: string, crdtMeta: CRDTMeta, returnConcurrent: boolean, discardDominated: boolean ) { if (replicaID === crdtMeta.sender) { if (discardDominated) { for (let historyEntry of this.history.entries()) { for (let message of historyEntry[1]) { // Stop tracking message events this.messageEvents.delete( `${message.crdtMeta!.sender}${message.crdtMeta!.senderCounter}` ); } } // Nothing's concurrent, so clear everything this.history.clear(); } return []; } // Gather up the concurrent messages. These are all // messages by each replicaID with sender counter // greater than crdtMeta.vectorClock.get(replicaID). let concurrent: Array<[string, StoredMessage]> = []; for (let historyEntry of this.history.entries()) { let senderHistory = historyEntry[1]; let vcEntry = crdtMeta.vectorClockGet(historyEntry[0]); if (senderHistory !== undefined) { let concurrentIndexStart = MessageHistory.indexAfter( senderHistory, vcEntry ); if (returnConcurrent) { for (let i = concurrentIndexStart; i < senderHistory.length; i++) { concurrent.push([historyEntry[0], senderHistory[i]]); } } if (discardDominated) { for (let i = 0; i < concurrentIndexStart; i++) { // Stop tracking message events this.messageEvents.delete( `${senderHistory[i].crdtMeta!.sender}${ senderHistory[i].crdtMeta!.senderCounter }` ); } // Keep only the messages with index // >= concurrentIndexStart senderHistory.splice(0, concurrentIndexStart); // TODO: delete it from the map if empty, // as a form of garbage collection. // This also makes isHistoryEmpty simpler. } } } if (returnConcurrent) { // Sort the concurrent messages in receipt order. concurrent.sort((a, b) => a[1].receiptCounter - b[1].receiptCounter); // Strip away everything except the messages. return concurrent; } else return []; } /** * Returns true if there are no messages stored in the history, * i.e., either there have been no crd1 messages, or * our SemidirectInternal's historyKeepOnlyConcurrent flag is true * and all crdt1 messages have been causally less than a crdt2 * message. */ isHistoryEmpty(): boolean { for (let value of this.history.values()) { if (value.length !== 0) return false; } return true; } /** * Utility method for working with the per-sender history * arrays. Returns the index after the last entry whose * per-sender counter (the first tuple element) is <= * value. */ private static indexAfter( sparseArray: Array<StoredMessage>, value: number ): number { // TODO: binary search when sparseArray is large // Note that there may be duplicate crdtMetas. // So it would be inappropriate to find an entry whose // per-sender counter equals value and infer that // the desired index is 1 greater. for (let i = sparseArray.length - 1; i >= 0; i--) { if (sparseArray[i].senderCounter <= value) return i + 1; } return 0; } addMessageEvent(messageId: string, eventName: string, event: any) { if (this.messageEvents.has(messageId)) { this.messageEvents .get(messageId)! .push(new StoredMessageEvent(eventName, event)); } } getMessageEvents( sender: string, senderCounter: number ): StoredMessageEvent[] | null { if (this.messageEvents.has(`${sender}${senderCounter}`)) { return this.messageEvents.get(`${sender}${senderCounter}`)!; } return null; } save(runtime: Runtime, subclassSave: Uint8Array): Uint8Array { const historySave: { [sender: string]: ISemidirectProductRevSenderHistory; } = {}; for (const [sender, messages] of this.history) { historySave[sender] = { messages: messages.map((message) => { return { senderCounter: message.senderCounter, receiptCounter: message.receiptCounter, targetPath: message.targetPath, // TODO: crdtMeta, if this.historyTimestamps. message: message.message, }; }), }; } const messageEventsSave: { [id: string]: string } = {}; for (const [id, event] of this.messageEvents) { // TODO: intelligent way to serialize events. // In particular, this will do silly things to // crdtMeta. messageEventsSave[id] = JSON.stringify(event); } const saveMessage = SemidirectProductRevSave.create({ receiptCounter: this.receiptCounter, history: historySave, messageEvents: messageEventsSave, subclassSave, }); return SemidirectProductRevSave.encode(saveMessage).finish(); } /** * [load description] * @param saveData [description] * @param runtime [description] * @return subclassSave */ load(saveData: Uint8Array, runtime: Runtime): Uint8Array { const saveMessage = SemidirectProductRevSave.decode(saveData); this.receiptCounter = saveMessage.receiptCounter; for (const [sender, messages] of Object.entries(saveMessage.history)) { this.history.set( sender, messages.messages!.map( (message) => new StoredMessage( message.senderCounter, message.receiptCounter, message.targetPath!, null, // this.historyTimestamps // ? runtime.metaSerializer.deserialize(message.meta!, runtime) // : null, message.message ) ) ); } for (const [id, eventSave] of Object.entries(saveMessage.messageEvents)) { this.messageEvents.set(id, JSON.parse(eventSave)); } return saveMessage.subclassSave; } } export type m1Start<m1ArgsT> = { m: 1; args: m1ArgsT; }; export type m2Start<m2ArgsT> = { m: 2; args: m2ArgsT; }; export type SemidirectMessage<m1ArgsT, m2ArgsT> = | m1Start<m1ArgsT> | m2Start<m2ArgsT>; /** * # Experimental */ export abstract class SemidirectProductRev< Events extends CollabEventsRecord = CollabEventsRecord, C extends Collab = Collab, m1Args extends Array<any> = [], m2Args extends Array<any> = [], m1Ret extends any | void = any | void, m2Ret extends any | void = any | void > extends CObject<Events> { protected history = new MessageHistory(false, false, false); private receivedMessages = false; private m2Id = ""; private _m1?: (...args: m1Args) => m1Ret; private _m2?: (...args: m2Args) => m2Ret; private m1RetVal?: m1Ret; private m2RetVal?: m2Ret; private messageValueSerializer: Serializer<SemidirectMessage<m1Args, m2Args>>; protected readonly runLocallyLayer: RunLocallyLayer; private readonly internalCObject: PublicCObject; constructor( initToken: InitToken, historyTimestamps: boolean = false, historyDiscard1Dominated: boolean = false, historyDiscard2Dominated: boolean = false ) { super(initToken); this.runLocallyLayer = super.addChild("", Pre(RunLocallyLayer)()); this.internalCObject = this.runLocallyLayer.setChild(Pre(PublicCObject)()); this.messageValueSerializer = DefaultSerializer.getInstance(); this.history = new MessageHistory( historyTimestamps, historyDiscard1Dominated, historyDiscard2Dominated ); // TODO: fix this subterfuge: separate methods for // implementing (abstract, not called by users) and // calling (the concrete wrappers here). this._m1 = this.m1; this._m2 = this.m2; this.m1 = (...args: m1Args) => { this.m1RetVal = undefined; // Request all context. const crdtMetaRequestee = <CRDTMetaRequestee>( this.getContext(CRDTMetaRequestee.CONTEXT_KEY) ); crdtMetaRequestee.requestAll(); // Send. this.send([this.messageValueSerializer.serialize({ m: 1, args })]); return this.m1RetVal as m1Ret; }; this.m2 = (...args: m2Args) => { this.m2RetVal = undefined; // Request all context. const crdtMetaRequestee = <CRDTMetaRequestee>( this.getContext(CRDTMetaRequestee.CONTEXT_KEY) ); crdtMetaRequestee.requestAll(); // Send. this.send([this.messageValueSerializer.serialize({ m: 2, args })]); return this.m2RetVal as m2Ret; }; } protected addSemidirectChild<D extends C>(name: string, preChild: Pre<D>): D { return this.internalCObject.addChild(name, preChild); } protected trackM2Event(eventName: string, event: any) { this.history.addMessageEvent(this.m2Id, eventName, event); } abstract m1(...args: m1Args): m1Ret; abstract m2(...args: m2Args): m2Ret; /** * TODO * @param m2TargetPath [description] * @param m2Timestamp [description] * @param m2Message [description] * @param m1TargetPath [description] * @param m1Timestamp [description] * @param m1Message [description] * @return [description] */ protected action( // TODO: make abstract m2TargetPath: string[], m2Timestamp: CRDTMeta | null, m2Message: m2Start<m2Args>, m2TrackedEvents: [string, any][], m1TargetPath: string[], m1Timestamp: CRDTMeta, m1Message: m1Start<m1Args> ): { m1TargetPath: string[]; m1Message: m1Start<m1Args> } | null { return { m1TargetPath, m1Message }; } receive(messagePath: Message[], meta: MessageMeta) { const crdtMeta = <CRDTMeta>meta[CRDTMeta.MESSAGE_META_KEY]; this.receivedMessages = this.receivedMessages || true; const message = messagePath[messagePath.length - 1]; if (typeof message !== "string") { // Uint8Array, message for ourselves. const semidirectMessage = this.messageValueSerializer.deserialize( <Uint8Array>message ); switch (true) { case semidirectMessage.m === 1: let concurrent = this.history.getConcurrent( this.runtime.replicaID, crdtMeta ); let mAct = { m1TargetPath: <string[]>[], // TODO: not actually used/usable m1Message: semidirectMessage, }; if (concurrent.length > 0) { for (let i = 0; i < concurrent.length; i++) { // TODO: can we avoid serializing and // deserializing each time? let mActOrNull = this.action( concurrent[i][1].targetPath, concurrent[i][1].crdtMeta, this.messageValueSerializer.deserialize( concurrent[i][1].message ) as m2Start<m2Args>, this.history .getMessageEvents( concurrent[i][0], concurrent[i][1].senderCounter )! .map(({ eventName, event }) => [eventName, event]), mAct.m1TargetPath, crdtMeta, mAct.m1Message as m1Start<m1Args> ); if (mActOrNull === null) return; else mAct = mActOrNull; } } this.m1RetVal = this.runLocallyLayer.runLocally(meta, () => { return this._m1!(...(mAct.m1Message as m1Start<m1Args>).args); }); return; case semidirectMessage.m === 2: this.m2Id = this.history.add( this.runtime.replicaID, [], // TODO: not actually used/usable crdtMeta, <Uint8Array>message ); this.m2RetVal = this.runLocallyLayer.runLocally(meta, () => { return this._m2!(...(semidirectMessage as m2Start<m2Args>).args); }); return; default: console.log("somehow got to default"); console.log(semidirectMessage); return; } } let child = this.children.get(message); if (child === undefined) { throw new Error( "Unknown child: " + message + " in: " + JSON.stringify(messagePath) + ", children: " + JSON.stringify([...this.children.keys()]) ); } messagePath.length--; child.receive(messagePath, meta); } canGC(): boolean { // TODO: this may spuriously return false if one of the Collab's is not // in its initial state only because we overwrote that state with // the semidirect initial state. Although, for our Collab's so far // (e.g CNumber), it ends up working because they check canGC() // by asking the state if it is in its initial state. return this.history.isHistoryEmpty() && super.canGC(); } protected saveObject(): Uint8Array { return this.history.save(this.runtime, this.saveSemidirectProductRev()); } /** * Override to return your own saveData, which will * be passed to loadSemidirectProductRev during this.load, * after loading the semidirect product state. */ protected saveSemidirectProductRev(): Uint8Array { return new Uint8Array(); } protected loadSemidirectProductRev(saveData: Optional<Uint8Array>) {} // TODO: the children loading their own states (both // of them, in arbitrary order) must correctly set // this.internalState, whatever it is. // Need option to do custom loading if that's not the // case. protected loadObject(saveData: Optional<Uint8Array>) { if (!saveData.isPresent) this.loadSemidirectProductRev(saveData); else { this.loadSemidirectProductRev( Optional.of(this.history.load(saveData.get(), this.runtime)) ); } } }
the_stack
import { MIRAssembly, MIRConstructableEntityTypeDecl, MIRConstructableInternalEntityTypeDecl, MIRDataBufferInternalEntityTypeDecl, MIRDataStringInternalEntityTypeDecl, MIREntityType, MIREntityTypeDecl, MIREnumEntityTypeDecl, MIREphemeralListType, MIRFieldDecl, MIRHavocEntityTypeDecl, MIRInternalEntityTypeDecl, MIRPrimitiveCollectionEntityTypeDecl, MIRPrimitiveInternalEntityTypeDecl, MIRPrimitiveListEntityTypeDecl, MIRPrimitiveMapEntityTypeDecl, MIRRecordType, MIRStringOfInternalEntityTypeDecl, MIRTupleType, MIRType } from "../../compiler/mir_assembly"; import { MIRGlobalKey, MIRInvokeKey, MIRResolvedTypeKey } from "../../compiler/mir_ops"; import { SMTCallGeneral, SMTCallSimple, SMTConst, SMTExp, SMTTypeInfo, VerifierOptions } from "./smt_exp"; import * as assert from "assert"; class SMTTypeEmitter { readonly assembly: MIRAssembly; readonly vopts: VerifierOptions; private namectr: number = 0; private allshortnames = new Set<string>(); private mangledTypeNameMap: Map<string, string> = new Map<string, string>(); private mangledFunctionNameMap: Map<string, string> = new Map<string, string>(); private mangledGlobalNameMap: Map<string, string> = new Map<string, string>(); private typeDataMap: Map<MIRResolvedTypeKey, SMTTypeInfo> = new Map<MIRResolvedTypeKey, SMTTypeInfo>(); constructor(assembly: MIRAssembly, vopts: VerifierOptions, namectr?: number, mangledTypeNameMap?: Map<string, string>, mangledFunctionNameMap?: Map<string, string>, mangledGlobalNameMap?: Map<string, string>) { this.assembly = assembly; this.vopts = vopts; this.namectr = namectr || 0; this.mangledTypeNameMap = mangledTypeNameMap || new Map<string, string>(); this.mangledFunctionNameMap = mangledFunctionNameMap || new Map<string, string>(); this.mangledGlobalNameMap = mangledGlobalNameMap || new Map<string, string>(); this.allshortnames = new Set<string>(); this.mangledTypeNameMap.forEach((sn) => this.allshortnames.add(sn)); this.mangledFunctionNameMap.forEach((sn) => this.allshortnames.add(sn)); this.mangledGlobalNameMap.forEach((sn) => this.allshortnames.add(sn)); } internTypeName(keyid: MIRResolvedTypeKey) { if (!this.mangledTypeNameMap.has(keyid)) { let cleanname = keyid.replace(/:/g, ".").replace(/[<>, \[\]\{\}\(\)\\\/\#\=\|]/g, "_"); if(this.allshortnames.has(cleanname)) { cleanname = cleanname + "$" + this.namectr++; } this.mangledTypeNameMap.set(keyid, cleanname); this.allshortnames.add(cleanname); } } lookupTypeName(keyid: MIRResolvedTypeKey): string { assert(this.mangledTypeNameMap.has(keyid)); return this.mangledTypeNameMap.get(keyid) as string; } internFunctionName(keyid: MIRInvokeKey, shortname: string) { if (!this.mangledFunctionNameMap.has(keyid)) { let cleanname = shortname.replace(/:/g, ".").replace(/[<>, \[\]\{\}\(\)\\\/\#\=\|]/g, "_"); if(this.allshortnames.has(cleanname)) { cleanname = cleanname + "$" + this.namectr++; } this.mangledFunctionNameMap.set(keyid, cleanname); this.allshortnames.add(cleanname); } } lookupFunctionName(keyid: MIRInvokeKey): string { assert(this.mangledFunctionNameMap.has(keyid), `Missing -- ${keyid}`); return this.mangledFunctionNameMap.get(keyid) as string; } internGlobalName(keyid: MIRGlobalKey, shortname: string) { if (!this.mangledGlobalNameMap.has(keyid)) { let cleanname = shortname.replace(/:/g, ".").replace(/[<>, \[\]\{\}\(\)\\\/\#\=\|]/g, "_"); if(this.allshortnames.has(cleanname)) { cleanname = cleanname + "$" + this.namectr++; } this.mangledGlobalNameMap.set(keyid, cleanname); this.allshortnames.add(cleanname); } } lookupGlobalName(keyid: MIRGlobalKey): string { assert(this.mangledGlobalNameMap.has(keyid)); return this.mangledGlobalNameMap.get(keyid) as string; } getMIRType(tkey: MIRResolvedTypeKey): MIRType { return this.assembly.typeMap.get(tkey) as MIRType; } isType(tt: MIRType, tkey: MIRResolvedTypeKey): boolean { return tt.typeID === tkey; } isUniqueTupleType(tt: MIRType): boolean { return tt.options.length === 1 && (tt.options[0] instanceof MIRTupleType); } isUniqueRecordType(tt: MIRType): boolean { return tt.options.length === 1 && (tt.options[0] instanceof MIRRecordType); } isUniqueEntityType(tt: MIRType): boolean { return tt.options.length === 1 && (tt.options[0] instanceof MIREntityType); } isUniqueEphemeralType(tt: MIRType): boolean { return tt.options.length === 1 && (tt.options[0] instanceof MIREphemeralListType); } isUniqueType(tt: MIRType): boolean { return this.isUniqueTupleType(tt) || this.isUniqueRecordType(tt) || this.isUniqueEntityType(tt) || this.isUniqueEphemeralType(tt); } getSMTTypeFor(tt: MIRType, fordecl?: boolean): SMTTypeInfo { if(this.typeDataMap.has(tt.typeID)) { return this.typeDataMap.get(tt.typeID) as SMTTypeInfo; } this.internTypeName(tt.typeID); if(this.isUniqueTupleType(tt)) { return new SMTTypeInfo(this.lookupTypeName(tt.typeID), `TypeTag_${this.lookupTypeName(tt.typeID)}`, tt.typeID); } else if(this.isUniqueRecordType(tt)) { return new SMTTypeInfo(this.lookupTypeName(tt.typeID), `TypeTag_${this.lookupTypeName(tt.typeID)}`, tt.typeID); } else if(this.isUniqueEntityType(tt)) { return this.getSMTTypeInfoForEntity(tt, this.assembly.entityDecls.get(tt.typeID) as MIREntityTypeDecl, fordecl || false); } else if (this.isUniqueEphemeralType(tt)) { return new SMTTypeInfo(this.lookupTypeName(tt.typeID), `TypeTag_${this.lookupTypeName(tt.typeID)}`, tt.typeID); } else if(this.assembly.subtypeOf(tt, this.getMIRType("KeyType"))) { return new SMTTypeInfo("BKey", "[BKEY]", tt.typeID); } else { return new SMTTypeInfo("BTerm", "[BTERM]", tt.typeID); } } private getSMTTypeInfoForEntity(tt: MIRType, entity: MIREntityTypeDecl, fordecl: boolean): SMTTypeInfo { if(entity instanceof MIRInternalEntityTypeDecl) { if(entity instanceof MIRPrimitiveInternalEntityTypeDecl) { if (this.isType(tt, "None")) { return new SMTTypeInfo("bsq_none", "TypeTag_None", entity.tkey); } else if (this.isType(tt, "Nothing")) { return new SMTTypeInfo("bsq_nothing", "TypeTag_Nothing", entity.tkey); } else if (this.isType(tt, "Bool")) { return new SMTTypeInfo("Bool", "TypeTag_Bool", entity.tkey); } else if (this.isType(tt, "Int")) { return new SMTTypeInfo("BInt", "TypeTag_Int", entity.tkey); } else if (this.isType(tt, "Nat")) { return new SMTTypeInfo("BNat", "TypeTag_Nat", entity.tkey); } else if (this.isType(tt, "BigInt")) { return new SMTTypeInfo("BBigInt", "TypeTag_BigInt", entity.tkey); } else if (this.isType(tt, "BigNat")) { return new SMTTypeInfo("BBigNat", "TypeTag_BigInt", entity.tkey); } else if (this.isType(tt, "Float")) { return new SMTTypeInfo("BFloat", "TypeTag_Float", entity.tkey); } else if (this.isType(tt, "Decimal")) { return new SMTTypeInfo("BDecimal", "TypeTag_Decimal", entity.tkey); } else if (this.isType(tt, "Rational")) { return new SMTTypeInfo("BRational", "TypeTag_Rational", entity.tkey); } else if (this.isType(tt, "String")) { return new SMTTypeInfo("BString", "TypeTag_String", entity.tkey); } else if (this.isType(tt, "ByteBuffer")) { return new SMTTypeInfo("BByteBuffer", "TypeTag_ByteBuffer", entity.tkey); } else if(this.isType(tt, "DateTime")) { return new SMTTypeInfo("BDateTime", "TypeTag_DateTime", entity.tkey); } else if(this.isType(tt, "TickTime")) { return new SMTTypeInfo("BTickTime", "TypeTag_TickTime", entity.tkey); } else if(this.isType(tt, "LogicalTime")) { return new SMTTypeInfo("BLogicalTime", "TypeTag_LogicalTime", entity.tkey); } else if(this.isType(tt, "UUID")) { return new SMTTypeInfo("BUUID", "TypeTag_UUID", entity.tkey); } else if(this.isType(tt, "ContentHash")) { return new SMTTypeInfo("BContentHash", "TypeTag_ContentHash", entity.tkey); } else if(this.isType(tt, "Regex")) { return new SMTTypeInfo("bsq_regex", "TypeTag_Regex", entity.tkey); } else { assert(false, "Unknown primitive internal entity"); } } else if (entity instanceof MIRHavocEntityTypeDecl) { return new SMTTypeInfo("HavocSequence", "TypeTag_HavocSequence", entity.tkey); } else if (entity instanceof MIRStringOfInternalEntityTypeDecl) { return new SMTTypeInfo(this.lookupTypeName(entity.tkey), `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } else if (entity instanceof MIRDataStringInternalEntityTypeDecl) { return new SMTTypeInfo(this.lookupTypeName(entity.tkey), `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } else if (entity instanceof MIRDataBufferInternalEntityTypeDecl) { return new SMTTypeInfo(this.lookupTypeName(entity.tkey), `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } else if (entity instanceof MIRConstructableInternalEntityTypeDecl) { //Convert all refs of the type into refs to the underlying type const ulltype = this.getSMTTypeFor(this.getMIRType(entity.fromtype)); return new SMTTypeInfo(ulltype.smttypename, `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } else { assert(entity instanceof MIRPrimitiveCollectionEntityTypeDecl, "Should be a collection type"); if(entity instanceof MIRPrimitiveListEntityTypeDecl) { return new SMTTypeInfo(this.lookupTypeName(entity.tkey), `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } else { assert(entity instanceof MIRPrimitiveMapEntityTypeDecl); return new SMTTypeInfo(this.lookupTypeName(entity.tkey), `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } } } else if (entity instanceof MIREnumEntityTypeDecl) { return new SMTTypeInfo(this.lookupTypeName(entity.tkey), `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } else if (entity instanceof MIRConstructableEntityTypeDecl) { return new SMTTypeInfo(this.lookupTypeName(entity.tkey), `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } else { return new SMTTypeInfo(this.lookupTypeName(entity.tkey), `TypeTag_${this.lookupTypeName(entity.tkey)}`, entity.tkey); } } getSMTConstructorName(tt: MIRType): { cons: string, box: string, bfield: string } { assert(tt.options.length === 1); this.internTypeName(tt.typeID); const kfix = this.assembly.subtypeOf(tt, this.getMIRType("KeyType")) ? "bsqkey_" : "bsqobject_" if (this.isUniqueTupleType(tt)) { return { cons: `${this.lookupTypeName(tt.typeID)}@cons`, box: `${this.lookupTypeName(tt.typeID)}@box`, bfield: `${kfix}${this.lookupTypeName(tt.typeID)}_value` }; } else if (this.isUniqueRecordType(tt)) { return { cons: `${this.lookupTypeName(tt.typeID)}@cons`, box: `${this.lookupTypeName(tt.typeID)}@box`, bfield: `${kfix}${this.lookupTypeName(tt.typeID)}_value` }; } else if (this.isUniqueEntityType(tt)) { return { cons: `${this.lookupTypeName(tt.typeID)}@cons`, box: `${this.lookupTypeName(tt.typeID)}@box`, bfield: `${kfix}${this.lookupTypeName(tt.typeID)}_value` }; } else { assert(this.isUniqueEphemeralType(tt), "should not be other options") return { cons: `${this.lookupTypeName(tt.typeID)}@cons`, box: "[UNDEF_EPHEMERAL_BOX]", bfield: "[UNDEF_EPHEMERAL_BOX]" }; } } private coerceFromAtomicToKey(exp: SMTExp, from: MIRType): SMTExp { assert(this.assembly.subtypeOf(from, this.getMIRType("KeyType"))); if (from.typeID === "None") { return new SMTConst("BKey@none"); } else { const smtfrom = this.getSMTTypeFor(from); let oftypetag = "[UNDEFINED]"; let objval: SMTExp | undefined = undefined; if (this.isType(from, "Bool")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_bool@box", [exp]); } else if (this.isType(from, "Int")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_int@box", [exp]); } else if (this.isType(from, "Nat")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_nat@box", [exp]); } else if (this.isType(from, "BigInt")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_bigint@box", [exp]); } else if (this.isType(from, "BigNat")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_bignat@box", [exp]); } else if (this.isType(from, "String")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_string@box", [exp]); } else if(this.isType(from, "LogicalTime")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_logicaltime@box", [exp]); } else if(this.isType(from, "UUID")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_uuid@box", [exp]); } else if(this.isType(from, "ContentHash")) { oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple("bsqkey_contenthash@box", [exp]); } else { const entity = this.assembly.entityDecls.get(from.typeID) as MIREntityTypeDecl; if (entity instanceof MIRStringOfInternalEntityTypeDecl) { oftypetag = this.getSMTTypeFor(this.getMIRType("String")).smttypetag; objval = objval = new SMTCallSimple("bsqkey_string@box", [exp]); } else if (entity instanceof MIRDataStringInternalEntityTypeDecl) { oftypetag = this.getSMTTypeFor(this.getMIRType("String")).smttypetag; objval = objval = new SMTCallSimple("bsqkey_string@box", [exp]); } else if (entity instanceof MIRConstructableInternalEntityTypeDecl) { oftypetag = this.getSMTTypeFor(this.getMIRType(entity.fromtype)).smttypetag; objval = new SMTCallSimple(this.getSMTConstructorName(this.getMIRType(entity.fromtype)).box, [exp]); } else if (entity instanceof MIREnumEntityTypeDecl) { oftypetag = this.getSMTTypeFor(this.getMIRType("Nat")).smttypetag; objval = new SMTCallSimple("bsqkey_nat@box", [exp]); } else if (entity instanceof MIRConstructableEntityTypeDecl) { oftypetag = this.getSMTTypeFor(this.getMIRType(entity.fromtype)).smttypetag; objval = new SMTCallSimple(this.getSMTConstructorName(this.getMIRType(entity.fromtype)).box, [exp]); } else { assert(this.isUniqueEntityType(from)); oftypetag = smtfrom.smttypetag; objval = new SMTCallSimple(this.getSMTConstructorName(from).box, [exp]); } } return new SMTCallSimple("BKey@box", [new SMTConst(smtfrom.smttypetag), new SMTConst(oftypetag), objval as SMTExp]); } } private coerceFromAtomicToTerm(exp: SMTExp, from: MIRType): SMTExp { if (from.typeID === "None") { return new SMTConst(`BTerm@none`); } else if (from.typeID === "Nothing") { return new SMTConst(`BTerm@nothing`); } else { if(this.assembly.subtypeOf(from, this.getMIRType("KeyType"))) { return new SMTCallSimple("BTerm@keybox", [this.coerceFromAtomicToKey(exp, from)]); } else { const smtfrom = this.getSMTTypeFor(from); let objval: SMTExp | undefined = undefined; if (this.isType(from, "Float")) { objval = new SMTCallSimple("bsqobject_float@box", [exp]); } else if (this.isType(from, "Decimal")) { objval = new SMTCallSimple("bsqobject_decimal@box", [exp]); } else if (this.isType(from, "Rational")) { objval = new SMTCallSimple("bsqobject_rational@box", [exp]); } else if (this.isType(from, "ByteBuffer")) { objval = new SMTCallSimple("bsqobject_bytebuffer@box", [exp]); } else if(this.isType(from, "DateTime")) { objval = new SMTCallSimple("bsqobject_datetime@box", [exp]); } else if(this.isType(from, "TickTime")) { objval = new SMTCallSimple("bsqobject_ticktime@box", [exp]); } else if (this.isType(from, "Regex")) { objval = new SMTCallSimple("bsqobject_regex@box", [exp]); } else if (this.isUniqueTupleType(from)) { objval = new SMTCallSimple(this.getSMTConstructorName(from).box, [exp]); } else if (this.isUniqueRecordType(from)) { objval = new SMTCallSimple(this.getSMTConstructorName(from).box, [exp]); } else { assert(this.isUniqueEntityType(from)); objval = new SMTCallSimple(this.getSMTConstructorName(from).box, [exp]); } return new SMTCallSimple("BTerm@termbox", [new SMTConst(smtfrom.smttypetag), objval as SMTExp]); } } } private coerceKeyIntoAtomic(exp: SMTExp, into: MIRType): SMTExp { if (this.isType(into, "None")) { return new SMTConst("bsq_none@literal"); } else { const oexp = new SMTCallSimple("BKey_value", [exp]); if (this.isType(into, "Bool")) { return new SMTCallSimple("bsqkey_bool_value", [oexp]); } else if (this.isType(into, "Int")) { return new SMTCallSimple("bsqkey_int_value", [oexp]); } else if (this.isType(into, "Nat")) { return new SMTCallSimple("bsqkey_nat_value", [oexp]); } else if (this.isType(into, "BigInt")) { return new SMTCallSimple("bsqkey_bigint_value", [oexp]); } else if (this.isType(into, "BigNat")) { return new SMTCallSimple("bsqkey_bignat_value", [oexp]); } else if (this.isType(into, "String")) { return new SMTCallSimple("bsqkey_string_value", [oexp]); } else if(this.isType(into, "LogicalTime")) { return new SMTCallSimple("bsqkey_logicaltime_value", [oexp]); } else if(this.isType(into, "UUID")) { return new SMTCallSimple("bsqkey_uuid_value", [oexp]); } else if(this.isType(into, "ContentHash")) { return new SMTCallSimple("bsqkey_contenthash_value", [oexp]); } else if (this.isUniqueTupleType(into)) { return new SMTCallSimple(this.getSMTConstructorName(into).bfield, [oexp]); } else if (this.isUniqueRecordType(into)) { return new SMTCallSimple(this.getSMTConstructorName(into).bfield, [oexp]); } else { assert(this.isUniqueEntityType(into)); return new SMTCallSimple(this.getSMTConstructorName(into).bfield, [oexp]); } } } private coerceTermIntoAtomic(exp: SMTExp, into: MIRType): SMTExp { if (this.isType(into, "None")) { return new SMTConst("bsq_none@literal"); } else if (this.isType(into, "Nothing")) { return new SMTConst("bsq_nothing@literal"); } else { if(this.assembly.subtypeOf(into, this.getMIRType("KeyType"))) { return this.coerceKeyIntoAtomic(new SMTCallSimple("BTerm_keyvalue", [exp]), into) } else { const oexp = new SMTCallSimple("BTerm_termvalue", [exp]); if (this.isType(into, "Float")) { return new SMTCallSimple("bsqobject_float_value", [oexp]); } else if (this.isType(into, "Decimal")) { return new SMTCallSimple("bsqobject_decimal_value", [oexp]); } else if (this.isType(into, "Rational")) { return new SMTCallSimple("bsqobject_rational_value", [oexp]); } else if (this.isType(into, "ByteBuffer")) { return new SMTCallSimple("bsqobject_bytebuffer_value", [oexp]); } else if(this.isType(into, "DateTime")) { return new SMTCallSimple("bsqobject_datetime_value", [oexp]); } else if(this.isType(into, "TickTime")) { return new SMTCallSimple("bsqobject_ticktime_value", [oexp]); } else if (this.isType(into, "Regex")) { return new SMTCallSimple("bsqobject_regex_value", [oexp]); } else if (this.isUniqueTupleType(into)) { return new SMTCallSimple(this.getSMTConstructorName(into).bfield, [oexp]); } else if (this.isUniqueRecordType(into)) { return new SMTCallSimple(this.getSMTConstructorName(into).bfield, [oexp]); } else { assert(this.isUniqueEntityType(into)); return new SMTCallSimple(this.getSMTConstructorName(into).bfield, [oexp]); } } } } coerce(exp: SMTExp, from: MIRType, into: MIRType): SMTExp { const smtfrom = this.getSMTTypeFor(from); const smtinto = this.getSMTTypeFor(into); if(smtfrom.smttypename === smtinto.smttypename) { return exp; } if (smtinto.isGeneralKeyType()) { if(smtfrom.isGeneralKeyType()) { return exp; } if(smtfrom.isGeneralTermType()) { return new SMTCallSimple("BTerm_keyvalue", [exp]); } else { return this.coerceFromAtomicToKey(exp, from); } } else if (smtinto.isGeneralTermType()) { if(smtfrom.isGeneralTermType()) { return exp; } else if(smtfrom.isGeneralKeyType()) { return new SMTCallSimple("BTerm@keybox", [exp]); } else { return this.coerceFromAtomicToTerm(exp, from); } } else { if (smtfrom.isGeneralKeyType()) { return this.coerceKeyIntoAtomic(exp, into); } else { assert(smtfrom.isGeneralTermType()); return this.coerceTermIntoAtomic(exp, into); } } } coerceToKey(exp: SMTExp, from: MIRType): SMTExp { const smtfrom = this.getSMTTypeFor(from); if (smtfrom.isGeneralKeyType()) { return exp; } else { if(smtfrom.isGeneralTermType()) { return new SMTCallSimple("BTerm_keyvalue", [exp]); } else { return this.coerceFromAtomicToKey(exp, from); } } } generateTupleIndexGetFunction(tt: MIRTupleType, idx: number): string { this.internTypeName(tt.typeID); return `${this.lookupTypeName(tt.typeID)}@_${idx}`; } generateRecordPropertyGetFunction(tt: MIRRecordType, pname: string): string { this.internTypeName(tt.typeID); return `${this.lookupTypeName(tt.typeID)}@_${pname}`; } generateEntityFieldGetFunction(tt: MIREntityTypeDecl, field: MIRFieldDecl): string { this.internTypeName(tt.tkey); return `${this.lookupTypeName(tt.tkey)}@_${field.fname}`; } generateEphemeralListGetFunction(tt: MIREphemeralListType, idx: number): string { this.internTypeName(tt.typeID); return `${this.lookupTypeName(tt.typeID)}@_${idx}`; } generateResultType(ttype: MIRType): SMTTypeInfo { return new SMTTypeInfo(`$Result_${this.getSMTTypeFor(ttype).smttypename}`, "[INTERNAL RESULT]", "[INTERNAL RESULT]"); } generateResultTypeConstructorSuccess(ttype: MIRType, val: SMTExp): SMTExp { return new SMTCallSimple(`$Result_${this.getSMTTypeFor(ttype).smttypename}@success`, [val]); } generateResultTypeConstructorError(ttype: MIRType, err: SMTExp): SMTExp { return new SMTCallSimple(`$Result_${this.getSMTTypeFor(ttype).smttypename}@error`, [err]); } generateErrorResultAssert(rtype: MIRType): SMTExp { return this.generateResultTypeConstructorError(rtype, new SMTConst("ErrorID_AssumeCheck")); } generateResultIsSuccessTest(ttype: MIRType, exp: SMTExp): SMTExp { return new SMTCallSimple(`(_ is $Result_${this.getSMTTypeFor(ttype).smttypename}@success)`, [exp]); } generateResultIsErrorTest(ttype: MIRType, exp: SMTExp): SMTExp { return new SMTCallSimple(`(_ is $Result_${this.getSMTTypeFor(ttype).smttypename}@error)`, [exp]); } generateResultGetSuccess(ttype: MIRType, exp: SMTExp): SMTExp { return new SMTCallSimple(`$Result_${this.getSMTTypeFor(ttype).smttypename}@success_value`, [exp]); } generateResultGetError(ttype: MIRType, exp: SMTExp): SMTExp { return new SMTCallSimple(`$Result_${this.getSMTTypeFor(ttype).smttypename}@error_value`, [exp]); } generateAccessWithSetGuardResultType(ttype: MIRType): SMTTypeInfo { return new SMTTypeInfo(`$GuardResult_${this.getSMTTypeFor(ttype).smttypename}`, "[INTERNAL GUARD RESULT]", "[INTERNAL GUARD RESULT]"); } generateAccessWithSetGuardResultTypeConstructorLoad(ttype: MIRType, value: SMTExp, flag: boolean): SMTExp { return new SMTCallSimple(`$GuardResult_${this.getSMTTypeFor(ttype).smttypename}@cons`, [value, new SMTConst(flag ? "true" : "false")]); } generateAccessWithSetGuardResultGetValue(ttype: MIRType, exp: SMTExp): SMTExp { return new SMTCallSimple(`$GuardResult_${this.getSMTTypeFor(ttype).smttypename}@result`, [exp]); } generateAccessWithSetGuardResultGetFlag(ttype: MIRType, exp: SMTExp): SMTExp { return new SMTCallSimple(`$GuardResult_${this.getSMTTypeFor(ttype).smttypename}@flag`, [exp]); } generateListTypeConsInfoSeq(ttype: MIRType): {cons: string, seqf: string} { return {cons: `${this.getSMTTypeFor(ttype).smttypename}@cons`, seqf: `${this.getSMTTypeFor(ttype).smttypename}_seq`}; } generateListTypeConsInfoArray(ttype: MIRType): {cons: string, lenf: string, seqf: string} { return {cons: `${this.getSMTTypeFor(ttype).smttypename}@cons`, lenf: `${this.getSMTTypeFor(ttype).smttypename}_len`, seqf: `${this.getSMTTypeFor(ttype).smttypename}_seq`}; } generateArrayEntryType(ttype: MIRType): SMTTypeInfo { return new SMTTypeInfo(`$ListEntry_${this.getSMTTypeFor(ttype).smttypename}`, "[INTERNAL RESULT]", "[INTERNAL RESULT]"); } generateArrayEntryTypeConsInfo(ttype: MIRType): {cons: string, empty: string, idxf: string, valf: string} { return {cons: `$ListEntry_${this.getSMTTypeFor(ttype).smttypename}@cons`, empty: `$ListEntry_${this.getSMTTypeFor(ttype).smttypename}@empty`, idxf: `$ListEntry_${this.getSMTTypeFor(ttype).smttypename}_idx`, valf: `$ListEntry_${this.getSMTTypeFor(ttype).smttypename}_value`}; } generateArrayEntryTypeConstructorValid(ttype: MIRType, idx: SMTExp, val: SMTExp): SMTExp { const consinfo = this.generateArrayEntryTypeConsInfo(ttype); return new SMTCallSimple(consinfo.cons, [idx, val]); } generateArrayEntryTypeConstructorEmpty(ttype: MIRType): SMTExp { const consinfo = this.generateArrayEntryTypeConsInfo(ttype); return new SMTConst(consinfo.empty); } generateArrayEntryTypeIsValid(ttype: MIRType, entry: SMTExp): SMTExp { const consinfo = this.generateArrayEntryTypeConsInfo(ttype); return SMTCallSimple.makeNotEq(new SMTConst(consinfo.empty), entry); } generateArrayEntryTypeGetIdx(ttype: MIRType, entry: SMTExp): SMTExp { const consinfo = this.generateArrayEntryTypeConsInfo(ttype); return new SMTCallSimple(consinfo.idxf, [entry]); } generateArrayEntryTypeGetValue(ttype: MIRType, entry: SMTExp): SMTExp { const consinfo = this.generateArrayEntryTypeConsInfo(ttype); return new SMTCallSimple(consinfo.valf, [entry]); } generateListTypeConstructorSeq(ttype: MIRType, seq: SMTExp): SMTExp { const consinfo = this.generateListTypeConsInfoSeq(ttype); return new SMTCallSimple(consinfo.cons, [seq]); } generateListTypeConstructorArray(ttype: MIRType, len: SMTExp, seq: SMTExp): SMTExp { const consinfo = this.generateListTypeConsInfoArray(ttype); return new SMTCallSimple(consinfo.cons, [len, seq]); } generateListTypeConstructorArrayElements(ttype: MIRType, len: SMTExp, elements: SMTExp[]): SMTExp { const consinfo = this.generateListTypeConsInfoArray(ttype); const entryinfo = this.generateArrayEntryTypeConsInfo(ttype); const mirttype = (this.assembly.entityDecls.get(ttype.typeID) as MIRPrimitiveListEntityTypeDecl).getTypeT(); let array: SMTExp = new SMTConst(`((as const (Array BNat ${this.getSMTTypeFor(mirttype).smttypename})) ${entryinfo.empty})`); for(let i = 0; i < elements.length; ++i) { array = new SMTCallSimple("store", [array, new SMTConst(`${i}`), this.generateArrayEntryTypeConstructorValid(ttype, new SMTConst(`${i}`), elements[i])]); } return new SMTCallSimple(consinfo.cons, [len, array]); } generateListTypeGetData(ttype: MIRType, ll: SMTExp): SMTExp { if(this.vopts.ARRAY_MODE === "Seq") { return new SMTCallSimple(this.generateListTypeConsInfoSeq(ttype).seqf, [ll]); } else { return new SMTCallSimple(this.generateListTypeConsInfoArray(ttype).seqf, [ll]); } } generateListTypeGetLength(ttype: MIRType, ll: SMTExp): SMTExp { if(this.vopts.ARRAY_MODE === "Seq") { return new SMTCallSimple("seq.len", [this.generateListTypeGetData(ttype, ll)]); } else { const consinfo = this.generateListTypeConsInfoArray(ttype); return new SMTCallSimple(consinfo.lenf, [ll]); } } generateListTypeSeq_GetLengthMinus1(ttype: MIRType, ll: SMTExp): SMTExp { const len = this.generateListTypeGetLength(ttype, ll); return new SMTCallSimple("-", [len, new SMTConst("1")]); } generateMapEntryType(ttype: MIRType): SMTTypeInfo { return new SMTTypeInfo(`$MapEntry_${this.getSMTTypeFor(ttype).smttypename}`, "[INTERNAL RESULT]", "[INTERNAL RESULT]"); } generateMapEntryTypeConsInfo(ttype: MIRType): {cons: string, empty: string, keyf: string, valf: string} { return {cons: `$MapEntry_${this.getSMTTypeFor(ttype).smttypename}@cons`, empty: `$MapEntry_${this.getSMTTypeFor(ttype).smttypename}@empty`, keyf: `$MapEntry_${this.getSMTTypeFor(ttype).smttypename}_key`, valf: `$MapEntry_${this.getSMTTypeFor(ttype).smttypename}_vtup`}; } generateMapEntryTypeConstructorValid(ttype: MIRType, key: SMTExp, val: SMTExp): SMTExp { const consinfo = this.generateMapEntryTypeConsInfo(ttype); return new SMTCallSimple(consinfo.cons, [key, val]); } generateMapEntryTypeConstructorEmpty(ttype: MIRType): SMTExp { const consinfo = this.generateMapEntryTypeConsInfo(ttype); return new SMTConst(consinfo.empty); } generateMapEntryTypeIsValid(ttype: MIRType, entry: SMTExp): SMTExp { const consinfo = this.generateMapEntryTypeConsInfo(ttype); return SMTCallSimple.makeNotEq(new SMTConst(consinfo.empty), entry); } generateMapEntryTypeGetKey(ttype: MIRType, entry: SMTExp): SMTExp { const consinfo = this.generateMapEntryTypeConsInfo(ttype); return new SMTCallSimple(consinfo.keyf, [entry]); } generateMapEntryTypeGetValueTuple(ttype: MIRType, entry: SMTExp): SMTExp { const consinfo = this.generateMapEntryTypeConsInfo(ttype); return new SMTCallSimple(consinfo.valf, [entry]); } generateMapTypeConsInfo(ttype: MIRType): {cons: string, lenf: string, arrayf: string} { return {cons: `${this.getSMTTypeFor(ttype).smttypename}@cons`, lenf: `${this.getSMTTypeFor(ttype).smttypename}_len`, arrayf: `${this.getSMTTypeFor(ttype).smttypename}_array`}; } generateMapTypeConstructor(ttype: MIRType, len: SMTExp, array: SMTExp): SMTExp { const consinfo = this.generateMapTypeConsInfo(ttype); return new SMTCallSimple(consinfo.cons, [len, array]); } generateMapTypeConstructorElements(ttype: MIRType, len: SMTExp, elements: SMTExp[]): SMTExp { const consinfo = this.generateMapTypeConsInfo(ttype); const entrytype = this.generateMapEntryType(ttype); const entryinfo = this.generateMapEntryTypeConsInfo(ttype); const mirktype = (this.assembly.entityDecls.get(ttype.typeID) as MIRPrimitiveMapEntityTypeDecl).getTypeK(); const mirtuptype = this.getMIRType((this.assembly.entityDecls.get(ttype.typeID) as MIRPrimitiveMapEntityTypeDecl).tupentrytype); let array: SMTExp = new SMTConst(`((as const (Array ${this.getSMTTypeFor(mirktype).smttypename} ${entrytype.smttypename})) ${entryinfo.empty})`); for(let i = 0; i < elements.length; ++i) { const ekey = new SMTCallSimple(this.generateTupleIndexGetFunction(mirtuptype.getUniqueTupleTargetType(), 0), [elements[i]]); array = new SMTCallSimple("store", [array, ekey, this.generateMapEntryTypeConstructorValid(ttype, ekey, elements[i])]); } return new SMTCallSimple(consinfo.cons, [len, array]); } generateMapTypeGetLength(ttype: MIRType, mm: SMTExp): SMTExp { const consinfo = this.generateMapTypeConsInfo(ttype); return new SMTCallSimple(consinfo.lenf, [mm]); } generateMapTypeGetArray(ttype: MIRType, mm: SMTExp): SMTExp { const consinfo = this.generateMapTypeConsInfo(ttype); return new SMTCallSimple(consinfo.arrayf, [mm]); } generateHavocConstructorName(tt: MIRType): string { return `_@@cons_${this.lookupTypeName(tt.typeID)}_entrypoint`; } generateHavocConstructorPathExtend(path: SMTExp, step: SMTExp): SMTExp { return new SMTCallSimple("seq.++", [path, new SMTCallSimple("seq.unit", [step])]); } generateHavocConstructorCall(tt: MIRType, path: SMTExp, step: SMTExp): SMTExp { return new SMTCallGeneral(this.generateHavocConstructorName(tt), [this.generateHavocConstructorPathExtend(path, step)]); } generateHavocConstructorCall_PassThrough(tt: MIRType, path: SMTExp): SMTExp { return new SMTCallGeneral(this.generateHavocConstructorName(tt), [path]); } } export { SMTTypeEmitter };
the_stack
import { filter, take } from 'rxjs/operators'; import { AdapterInsertOptions, AdapterAppendOptions, AdapterPrependOptions, ItemsPredicate, AdapterFixOptions, AdapterUpdateOptions, AdapterPropName as Adapter, AdapterMethodResult, } from './miscellaneous/vscroll'; import { makeTest, TestBedConfig, ItFuncConfig } from './scaffolding/runner'; import { configureTestBedSub } from './scaffolding/testBed'; import { Misc } from './miscellaneous/misc'; import { generateItem } from './miscellaneous/items'; const ITEM_SIZE = 20; interface ICustom { method: Adapter; // Adapter method name options: unknown; // Adapter method params async: boolean; // produces asynchronicity newWFCycle: boolean; // produces additional Workflow cycle error?: boolean; // produces error } interface ICustom2 { count: number; interrupt?: 'reload' | 'reset'; } const configBase = { datasourceName: 'default-delay-25', datasourceSettings: { itemSize: ITEM_SIZE, startIndex: 1, bufferSize: 10, padding: 0.5, adapter: true }, // datasourceDevSettings: { debug: true }, templateSettings: { viewportHeight: ITEM_SIZE * 10 } }; const delayedConfigList: TestBedConfig<ICustom>[] = [{ ...configBase, custom: { method: Adapter.reset, options: void 0, newWFCycle: true, async: true } }, { ...configBase, custom: { method: Adapter.reload, options: void 0, newWFCycle: true, async: true } }, { ...configBase, custom: { method: Adapter.append, options: { items: [generateItem(100.1)] } as AdapterAppendOptions, newWFCycle: true, async: true } }, { ...configBase, custom: { method: Adapter.prepend, options: { items: [generateItem(100.1)] } as AdapterPrependOptions, newWFCycle: true, async: true } }, { ...configBase, custom: { method: Adapter.check, options: void 0, newWFCycle: true, async: true } }, { ...configBase, custom: { method: Adapter.remove, options: (({ $index }) => $index > 1) as ItemsPredicate, newWFCycle: true, async: true } }, { ...configBase, custom: { method: Adapter.insert, options: { after: ({ $index }) => $index === 5, items: [generateItem(5 + 0.1)] } as AdapterInsertOptions, newWFCycle: true, async: true } }, { ...configBase, custom: { method: Adapter.update, options: { predicate: ({ $index }) => $index !== 1, // remove 1st item } as AdapterUpdateOptions, newWFCycle: true, async: true } }]; const immediateConfigSyncList: TestBedConfig<ICustom>[] = [{ ...configBase, custom: { method: Adapter.append, options: { items: [generateItem(100.1)], eof: true } as AdapterAppendOptions, newWFCycle: false, async: false } }, { ...configBase, custom: { method: Adapter.prepend, options: { items: [generateItem(100.1)], bof: true } as AdapterAppendOptions, newWFCycle: false, async: false } }, { ...configBase, custom: { method: Adapter.check, options: void 0, newWFCycle: false, async: false } }, { ...configBase, custom: { method: Adapter.remove, options: (({ $index }) => $index > 100) as ItemsPredicate, newWFCycle: false, async: false } }, { ...configBase, custom: { method: Adapter.insert, options: { after: ({ $index }) => $index === 55, items: [generateItem(55 + 0.1)] } as AdapterInsertOptions, newWFCycle: false, async: false } }, { ...configBase, datasourceSettings: { ...configBase.datasourceSettings, bufferSize: 1 // clip will be skipped }, custom: { method: Adapter.clip, options: void 0, newWFCycle: true, async: false } }, { ...configBase, datasourceSettings: { ...configBase.datasourceSettings, bufferSize: 40 // clip will happen }, custom: { method: Adapter.clip, options: void 0, newWFCycle: true, async: false } }, { ...configBase, custom: { method: Adapter.fix, options: { minIndex: -99 } as AdapterFixOptions, newWFCycle: false, async: false } }, { ...configBase, custom: { method: Adapter.update, options: { predicate: _x => true, } as AdapterUpdateOptions, newWFCycle: false, async: false } }]; const immediateConfigErrorList: TestBedConfig<ICustom>[] = [{ ...configBase, custom: { method: Adapter.reset, options: { get: 'error' }, newWFCycle: false, async: false, error: true } }, { ...configBase, custom: { method: Adapter.append, options: { items: 'error' }, newWFCycle: false, async: false, error: true } }, { ...configBase, custom: { method: Adapter.remove, options: 'error', newWFCycle: false, async: false, error: true } }, { ...configBase, custom: { method: Adapter.insert, options: 'error', newWFCycle: false, async: false, error: true } }, { ...configBase, custom: { method: Adapter.fix, options: { minIndex: 'error' }, newWFCycle: false, async: false, error: true } }]; const concurrentSequencesConfigList: TestBedConfig<ICustom2>[] = [{ datasourceName: 'limited-1-100-no-delay', datasourceSettings: { adapter: true, startIndex: 100 }, custom: { count: 25 } }, { datasourceName: 'limited-51-200-no-delay', datasourceSettings: { adapter: true, startIndex: 200, horizontal: true }, templateSettings: { viewportWidth: 450, itemWidth: 100, horizontal: true }, custom: { count: 30 } }]; const concurrentSequencesInterruptConfigList: TestBedConfig<ICustom2>[] = [{ ...concurrentSequencesConfigList[0], custom: { count: 99, interrupt: 'reload' } }, { ...concurrentSequencesConfigList[1], custom: { count: 99, interrupt: 'reset' } }]; const checkPromisifiedMethod: ItFuncConfig<ICustom> = config => misc => done => { const { workflow } = misc; const { method: token, options, newWFCycle, async, error } = config.custom; misc.adapter.isLoading$ .pipe(filter(v => !v), take(1)) .subscribe(() => { expect(workflow.cyclesDone).toEqual(1); if (token === Adapter.check && async) { misc.adapter.fix({ updater: ({ $index }) => misc.getElement($index).style.height = 5 + 'px' }); } const method = (misc.adapter[token]) as unknown as (opt: unknown) => Promise<AdapterMethodResult>; method(options).then(({ success, immediate, details: err }) => { expect(workflow.cyclesDone).toEqual(newWFCycle ? 2 : 1); expect(immediate).toEqual(!newWFCycle); expect(success).toEqual(!error); if (error) { expect(success).toBeFalsy(); expect(workflow.errors.length).toEqual(1); expect(workflow.errors[0].process).toEqual(`adapter.${token}`); expect(err).toBeTruthy(); } else { expect(success).toBeTruthy(); expect(err).toBeFalsy(); } done(); }); expect(workflow.cyclesDone).toEqual(!async && newWFCycle ? 2 : 1); }); }; const doAppendAndScroll = async (misc: Misc, index: number): Promise<void> => { const { adapter } = misc; const { success } = await adapter.relax(); if (success) { await adapter.append(generateItem(index)); await adapter.fix({ scrollPosition: Infinity }); } }; const checkConcurrentSequences: ItFuncConfig<ICustom2> = config => misc => async done => { await misc.relaxNext(); const { startIndex } = misc.scroller.settings; const { count, interrupt } = config.custom; const scrollPosition = misc.getScrollPosition(); for (let i = 0; i < count; i++) { // multiple concurrent calls doAppendAndScroll(misc, startIndex + i + 1); } if (interrupt === 'reload') { await misc.adapter.reload(); } else if (interrupt === 'reset') { await misc.adapter.reset(); } else { await misc.adapter.relax(); } if (interrupt) { expect(misc.workflow.cyclesDone).toEqual(2); } else { const newScrollPosition = scrollPosition + misc.getItemSize() * count; expect(misc.getScrollPosition()).toEqual(newScrollPosition); expect(misc.workflow.cyclesDone).toEqual(count + 1); } done(); }; describe('Adapter Promises Spec', () => { describe('Promisified method', () => { delayedConfigList.forEach(config => makeTest({ config, title: `should resolve "${config.custom.method}" asynchronously`, it: checkPromisifiedMethod(config) }) ); immediateConfigSyncList.forEach(config => makeTest({ config, title: `should resolve "${config.custom.method}" immediately by no async processes`, it: checkPromisifiedMethod(config) }) ); immediateConfigErrorList.forEach(config => makeTest({ config, title: `should resolve "${config.custom.method}" immediately due to error`, it: checkPromisifiedMethod(config) }) ); }); describe('Concurrent sequences', () => { concurrentSequencesConfigList.forEach(config => makeTest({ title: 'should run a sequence within sequence', config, it: checkConcurrentSequences(config) }) ); concurrentSequencesInterruptConfigList.forEach(config => makeTest({ title: `should reset all promises after Adapter.${config.custom.interrupt}`, config, it: checkConcurrentSequences(config) }) ); }); describe('Call before init', () => [Adapter.relax, Adapter.reload, Adapter.reset, Adapter.check].forEach(token => it(`should resolve immediately ("${token}")`, async () => { const misc = new Misc(configureTestBedSub()); const method = (misc.adapter[token]) as unknown as () => Promise<AdapterMethodResult>; const result = await method(); expect(result.immediate).toBe(true); expect(result.success).toBe(true); // expect(result.details).toBe('Adapter is not initialized'); }) ) ); });
the_stack
import * as tf from '../../index'; import {ALL_ENVS, describeWithFlags} from '../../jasmine_util'; import {expectArraysClose, expectArraysEqual} from '../../test_util'; describeWithFlags('nonMaxSuppression', ALL_ENVS, () => { describe('NonMaxSuppression Basic', () => { it('select from three clusters', async () => { const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]); const maxOutputSize = 3; const iouThreshold = 0.5; const scoreThreshold = 0; const indices = tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold); expect(indices.shape).toEqual([3]); expectArraysEqual(await indices.data(), [3, 0, 5]); }); it('select from three clusters flipped coordinates', async () => { const boxes = tf.tensor2d( [ 1, 1, 0, 0, 0, 0.1, 1, 1.1, 0, .9, 1, -0.1, 0, 10, 1, 11, 1, 10.1, 0, 11.1, 1, 101, 0, 100 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]); const maxOutputSize = 3; const iouThreshold = 0.5; const scoreThreshold = 0; const indices = tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold); expect(indices.shape).toEqual([3]); expectArraysEqual(await indices.data(), [3, 0, 5]); }); it('select at most two boxes from three clusters', async () => { const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]); const maxOutputSize = 2; const iouThreshold = 0.5; const scoreThreshold = 0; const indices = tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold); expect(indices.shape).toEqual([2]); expectArraysEqual(await indices.data(), [3, 0]); }); it('select at most thirty boxes from three clusters', async () => { const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]); const maxOutputSize = 30; const iouThreshold = 0.5; const scoreThreshold = 0; const indices = tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold); expect(indices.shape).toEqual([3]); expectArraysEqual(await indices.data(), [3, 0, 5]); }); it('select single box', async () => { const boxes = tf.tensor2d([0, 0, 1, 1], [1, 4]); const scores = tf.tensor1d([0.9]); const maxOutputSize = 3; const iouThreshold = 0.5; const scoreThreshold = 0; const indices = tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold); expect(indices.shape).toEqual([1]); expectArraysEqual(await indices.data(), [0]); }); it('select from ten identical boxes', async () => { const numBoxes = 10; const corners = new Array(numBoxes) .fill(0) .map(_ => [0, 0, 1, 1]) .reduce((arr, curr) => arr.concat(curr)); const boxes = tf.tensor2d(corners, [numBoxes, 4]); const scores = tf.tensor1d(Array(numBoxes).fill(0.9)); const maxOutputSize = 3; const iouThreshold = 0.5; const scoreThreshold = 0; const indices = tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold); expect(indices.shape).toEqual([1]); expectArraysEqual(await indices.data(), [0]); }); it('inconsistent box and score shapes', () => { const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5]); const maxOutputSize = 30; const iouThreshold = 0.5; const scoreThreshold = 0; expect( () => tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold)) .toThrowError(/scores has incompatible shape with boxes/); }); it('invalid iou threshold', () => { const boxes = tf.tensor2d([0, 0, 1, 1], [1, 4]); const scores = tf.tensor1d([0.9]); const maxOutputSize = 3; const iouThreshold = 1.2; const scoreThreshold = 0; expect( () => tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold)) .toThrowError(/iouThreshold must be in \[0, 1\]/); }); it('empty input', async () => { const boxes = tf.tensor2d([], [0, 4]); const scores = tf.tensor1d([]); const maxOutputSize = 3; const iouThreshold = 0.5; const scoreThreshold = 0; const indices = tf.image.nonMaxSuppression( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold); expect(indices.shape).toEqual([0]); expectArraysEqual(await indices.data(), []); }); it('accepts a tensor-like object', async () => { const boxes = [[0, 0, 1, 1], [0, 1, 1, 2]]; const scores = [1, 2]; const indices = tf.image.nonMaxSuppression(boxes, scores, 10); expect(indices.shape).toEqual([2]); expect(indices.dtype).toEqual('int32'); expectArraysEqual(await indices.data(), [1, 0]); }); it('throws when boxes is int32', async () => { const boxes = tf.tensor2d([[0, 0, 1, 1], [0, 1, 1, 2]], [2, 4], 'int32'); const scores = [1, 2]; expect(() => tf.image.nonMaxSuppression(boxes, scores, 10)) .toThrowError( /Argument 'boxes' passed to 'nonMaxSuppression' must be float32/); }); it('throws when scores is int32', async () => { const boxes = [[0, 0, 1, 1], [0, 1, 1, 2]]; const scores = tf.tensor1d([1, 2], 'int32'); const errRegex = /Argument 'scores' passed to 'nonMaxSuppression' must be float32/; expect(() => tf.image.nonMaxSuppression(boxes, scores, 10)) .toThrowError(errRegex); }); it('works when inputs are not explicitly initialized on the CPU', async () => { // This test ensures that asynchronous backends work with NMS, which // requires inputs to reside on the CPU. const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const a = tf.tensor1d([0, 1, -2, -4, 4, -4]); const b = tf.tensor1d([0.15, 0.2, 0.25, 0.5, 0.7, 1.2]); const scores = a.div(b); const maxOutputSize = 2; const iouThreshold = 0.5; const scoreThreshold = 0; await scores.data(); const indices = tf.image.nonMaxSuppression( boxes, scores as tf.Tensor1D, maxOutputSize, iouThreshold, scoreThreshold); expect(indices.shape).toEqual([2]); expectArraysEqual(await indices.data(), [4, 1]); }); }); describe('NonMaxSuppressionWithScore', () => { it('select from three clusters with SoftNMS', async () => { const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]); const maxOutputSize = 6; const iouThreshold = 1.0; const scoreThreshold = 0; const softNmsSigma = 0.5; const {selectedIndices, selectedScores} = tf.image.nonMaxSuppressionWithScore( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, softNmsSigma); expectArraysEqual(await selectedIndices.data(), [3, 0, 1, 5, 4, 2]); expectArraysClose( await selectedScores.data(), [0.95, 0.9, 0.384, 0.3, 0.256, 0.197]); }); }); describe('NonMaxSuppressionPadded', () => { it('select from three clusters with pad five.', async () => { const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]); const maxOutputSize = 5; const iouThreshold = 0.5; const scoreThreshold = 0; const before = tf.memory().numTensors; const {selectedIndices, validOutputs} = tf.image.nonMaxSuppressionPadded( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, true); const after = tf.memory().numTensors; expectArraysEqual(await selectedIndices.data(), [3, 0, 5, 0, 0]); expectArraysEqual(await validOutputs.data(), 3); expect(after).toEqual(before + 2); }); it('select from three clusters with pad five and score threshold.', async () => { const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]); const maxOutputSize = 6; const iouThreshold = 0.5; const scoreThreshold = 0.4; const before = tf.memory().numTensors; const {selectedIndices, validOutputs} = tf.image.nonMaxSuppressionPadded( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, true); const after = tf.memory().numTensors; expectArraysEqual(await selectedIndices.data(), [3, 0, 0, 0, 0, 0]); expectArraysEqual(await validOutputs.data(), 2); expect(after).toEqual(before + 2); }); it('select from three clusters with no padding when pad option is false.', async () => { const boxes = tf.tensor2d( [ 0, 0, 1, 1, 0, 0.1, 1, 1.1, 0, -0.1, 1, 0.9, 0, 10, 1, 11, 0, 10.1, 1, 11.1, 0, 100, 1, 101 ], [6, 4]); const scores = tf.tensor1d([0.9, 0.75, 0.6, 0.95, 0.5, 0.3]); const maxOutputSize = 5; const iouThreshold = 0.5; const scoreThreshold = 0.0; const {selectedIndices, validOutputs} = tf.image.nonMaxSuppressionPadded( boxes, scores, maxOutputSize, iouThreshold, scoreThreshold, false); expectArraysEqual(await selectedIndices.data(), [3, 0, 5]); expectArraysEqual(await validOutputs.data(), 3); }); }); });
the_stack
declare module 'rclnodejs' { /** * Identifies type of ROS message such as msg or srv. */ type TypeClass<T = TypeClassName> = | (() => any) | T // a string representing the message class, e.g. 'std_msgs/msg/String', | { // object representing a message class, e.g. {package: 'std_msgs', type: 'msg', name: 'String'} package: string; type: string; name: string; }; /** * Configuration options when creating new Publishers, Subscribers, * Clients and Services. * * See {@link DEFAULT_OPTIONS} */ interface Options<T = QoS | QoS.ProfileRef> { /** * A messages will use TypedArray if necessary, default: true. */ enableTypedArray?: boolean; /** * Indicates messages are serialized, default: false. * * @remarks * See {@link Node#createSubscription | Node.createSubscription} */ isRaw?: boolean; /** * ROS Middleware "quality of service" setting, default: QoS.profileDefault. */ qos?: T; } /** * Default options when creating a Node, Publisher, Subscription, Client or Service * * ```ts * { * enableTypedArray: true, * qos: QoS.profileDefault, * isRaw: false * } * ``` */ const DEFAULT_OPTIONS: Options; /** * Callback for receiving periodic interrupts from a Timer. * * @remarks * See {@link Node.createTimer | Node.createTimer} * See {@link Timer} */ type TimerRequestCallback = () => void; /** * Callback indicating parameters are about to be declared or set. * The callback is provided a list of parameters and returns a SetParameterResult * to indicate approval or veto of the operation. * * @param parameters - The parameters to be declared or set * @returns A successful property value of true indicates approval of the operation; * otherwise indicates a veto of the operation. * * @remarks * See {@link Node.addOnSetParametersCallback | Node.addOnSetParametersCallback} * See {@link Node.removeOnSetParametersCallback | Node.removeOnSetParametersCallback} */ type SetParametersCallback = ( parameters: Parameter[] ) => rcl_interfaces.msg.SetParametersResult; /** * Standard result of Node.getXXXNamesAndTypes() queries * * @example * ``` * [ * { name: '/rosout', types: [ 'rcl_interfaces/msg/Log' ] }, * { name: '/scan', types: [ 'sensor_msgs/msg/LaserScan' ] }, * { name: '/topic', types: [ 'std_msgs/msg/String' ] } * ] * ``` */ type NamesAndTypesQueryResult = { name: string; types: Array<string>; }; /** * Result of Node.getNodeNames() query * * @example * ``` * [ * { name: 'gazebo', namespace: '/' }, * { name: 'robot_state_publisher', namespace: '/' }, * { name: 'cam2image', namespace: '/demo' } * ] * ``` */ type NodeNamesQueryResult = { name: string; namespace: string; }; /** * Node is the primary entrypoint in a ROS system for communication. * It can be used to create ROS entities such as publishers, subscribers, * services, clients and timers. */ class Node { /** * Create a node instance. * * @param nodeName - The name used to register in ROS. * @param namespace - The namespace used in ROS, default is an empty string. * @param context - The context, default is Context.defaultContext(). * @param options - The node options, default is NodeOptions.defaultOptions. */ constructor( nodeName: string, namespace?: string, context?: Context, options?: NodeOptions ); /** * Get the name of the node. * * @returns The node name. */ name(): string; /** * Get the namespace of the node. * * @returns The node namespace. */ namespace(): string; /** * Get the Context that manages this node. * * @returns The context. */ get context(): Context; /** * Get the nodes logger. * * @returns The logger for the node. */ getLogger(): Logging; /** * Get the clock used by the node. * * @returns The nodes clock. */ getClock(): Clock; /** * Get the current time using the node's clock. * * @returns The current time. */ now(): Time; /** * Get the nodeOptions provided through the constructor. * * @returns The nodeOptions. */ options(): NodeOptions; /** * Trigger the event loop to continuously check for and route. * incoming events. * @param node - The node to be spun up. * @param - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0. * @throws Error if the node is already spinning. */ spin(timeout?: number): void; /** * Spin the node and trigger the event loop to check for one incoming event. Thereafter the node * will not received additional events until running additional calls to spin() or spinOnce(). * @param node - The node to be spun. * @param - Timeout to wait in milliseconds. Block forever if negative. Don't wait if 0. * @throws An error if the node is already spinning. */ spinOnce(timeout?: number): void; /** * Terminate spinning - no further events will be received. */ stop(): void; /** * Create a Timer. * * @param period - Elapsed time between interrupt events (milliseconds). * @param callback - Called on timeout interrupt. * @param clock - Optional clock to use for the timer. * @returns New instance of Timer. */ createTimer( period: number, callback: TimerRequestCallback, clock?: Clock ): Timer; /** * Create a Rate. * * @param hz - The frequency of the rate timer; default is 1 hz. * @returns Promise resolving to new instance of Rate. */ createRate(hz: number): Promise<Rate>; /** * Create a Publisher. * * @param typeClass - Type of message that will be published. * @param topic - Name of the topic the publisher will publish to. * @param options - Configuration options, see DEFAULT_OPTIONS * @returns New instance of Publisher. */ createPublisher<T extends TypeClass<MessageTypeClassName>>( typeClass: T, topic: string, options?: Options ): Publisher<T>; /** * Create a Subscription. * * @param typeClass - Type of ROS messages the subscription will subscribe to * @param topic - Name of the topic the subcription will subscribe to. * @param options - Configuration options, see DEFAULT_OPTIONS * @param callback - Called when a new message is received. The serialized message will be null-terminated. * @returns New instance of Subscription. */ createSubscription<T extends TypeClass<MessageTypeClassName>>( typeClass: T, topic: string, options: Options, callback: SubscriptionCallback<T> ): Subscription; /** * Create a Client for making server requests. * * @param typeClass - Service type. * @param serviceName - Service name. * @param options - The options argument used to parameterize the client. * @returns New instance of Client. */ createClient<T extends TypeClass<ServiceTypeClassName>>( typeClass: T, serviceName: string, options?: Options ): Client<T>; /** * Create a Service. * * @param typeClass - Service type * @param serviceName - Name of the service. * @param options - Configuration options * @param callback - Notified for receiving incoming requests. * @returns An instance of Service. */ createService<T extends TypeClass<ServiceTypeClassName>>( typeClass: T, serviceName: string, options: Options, callback: ServiceRequestHandler<T> ): ServiceType<T>; /** * Create a guard condition. * * @param callback - The callback to be called when the guard condition is triggered. * @returns An instance of GuardCondition. */ createGuardCondition(callback: () => any): GuardCondition; /** * Destroy all entities allocated by this node, including * Timers, Publishers, Subscriptions, Clients, Services * and Timers. */ destroy(): void; /** * Destroy a Publisher. * * @param publisher - Publisher to be destroyed. */ destroyPublisher<T extends TypeClass<MessageTypeClassName>>( publisher: Publisher<T> ): void; /** * Destroy a Subscription. * * @param subscription - Subscription to be destroyed. */ destroySubscription(subscription: Subscription): void; /** * Destroy a Client. * * @param client - Client to be destroyed. */ destroyClient<T extends TypeClass<ServiceTypeClassName>>( client: Client<T> ): void; /** * Destroy a Service. * * @param service - Service to be destroyed. */ destroyService(service: Service): void; /** * Destroy a Timer. * * @param timer - Timer to be destroyed. */ destroyTimer(timer: Timer): void; /** * Declare a parameter. * * Internally, register a parameter and it's descriptor. * If a parameter-override exists, it's value will replace that of the parameter * unless ignoreOverride is true. * If the descriptor is undefined, then a ParameterDescriptor will be inferred * from the parameter's state. * * If a parameter by the same name has already been declared then an Error is thrown. * A parameter must be undeclared before attempting to redeclare it. * * @param parameter - Parameter to declare. * @param descriptor - Optional descriptor for parameter. * @param ignoreOveride - When true disregard any parameter-override that may be present. * @returns The newly declared parameter. */ declareParameter( parameter: Parameter, descriptor?: ParameterDescriptor, ignoreOveride?: boolean ): Parameter; /** * Declare a list of parameters. * * Internally register parameters with their corresponding descriptor one by one * in the order they are provided. This is an atomic operation. If an error * occurs the process halts and no further parameters are declared. * Parameters that have already been processed are undeclared. * * While descriptors is an optional parameter, when provided there must be * a descriptor for each parameter; otherwise an Error is thrown. * If descriptors is not provided then a descriptor will be inferred * from each parameter's state. * * When a parameter-override is available, the parameter's value * will be replaced with that of the parameter-override unless ignoreOverrides * is true. * * If a parameter by the same name has already been declared then an Error is thrown. * A parameter must be undeclared before attempting to redeclare it. * * @param parameters - The parameters to declare. * @param descriptors - Optional descriptors, a 1-1 correspondence with parameters. * @param ignoreOverrides - When true, parameter-overrides are * not considered, i.e.,ignored. * @returns The declared parameters. */ declareParameters( parameters: Array<Parameter>, descriptors?: Array<ParameterDescriptor>, ignoreOverrides?: boolean ): Array<Parameter>; /** * Undeclare a parameter. * * Readonly parameters can not be undeclared or updated. * @param name - Name of parameter to undeclare. */ undeclareParameter(name: string): void; /** * Determine a parameter has been declared. * * @param name - Name of the parameter * @returns True if parameter exists; false otherwise. */ hasParameter(name: string): boolean; /** * Get a declared parameter by name. * * If unable to locate a declared parameter then a * parameter with type == PARAMETER_NOT_SET is returned. * * @param name - The name of the parameter. * @returns The parameter. */ getParameter(name: string): Parameter; /** * Get a list of parameters. * * Find and return the declared parameters. * If no names are provided return all declared parameters. * * If unable to locate a declared parameter then a * parameter with type == PARAMETER_NOT_SET is returned in * it's place. * * @param names - The names of the declared parameters * to find or null indicating to return all declared parameters. * @returns The parameters. */ getParameters(name?: Array<string>): Array<Parameter>; /** * Get the names of all declared parameters. * * @returns The declared parameter names or empty array if * no parameters have been declared. */ getParameterNames(): Array<string>; /** * Get the list of parameter-overrides found on the commandline and * in the NodeOptions.parameter_overrides property. * * @returns An array of Parameters */ getParameterOverrides(): Array<Parameter>; /** * Determine if a parameter descriptor exists. * * @param name - The name of a descriptor to detect. * @returns True if a descriptor has been declared; otherwise false. */ hasParameterDescriptor(name: string): boolean; /** * Get a declared parameter descriptor by name. * * If unable to locate a declared parameter descriptor then a * descriptor with type == PARAMETER_NOT_SET is returned. * * @param name - The name of the parameter descriptor to find. * @returns The parameter descriptor. */ getParameterDescriptor(name: string): ParameterDescriptor; /** * Find a list of declared ParameterDescriptors. * * If no names are provided return all declared descriptors. * * If unable to locate a declared descriptor then a * descriptor with type == PARAMETER_NOT_SET is returned in * it's place. * * @param names - The names of the declared parameter * descriptors to find or null indicating to return all declared descriptors. * @returns The parameter descriptors. */ getParameterDescriptors(name?: string[]): ParameterDescriptor[]; /** * Replace a declared parameter. * * The parameter being replaced must be a declared parameter who's descriptor * is not readOnly; otherwise an Error is thrown. * * @param parameter - The new parameter. * @returns The result of the operation. */ setParameter(parameter: Parameter): rcl_interfaces.msg.SetParametersResult; /** * Replace a list of declared parameters. * * Declared parameters are replaced in the order they are provided and * a ParameterEvent is published for each individual parameter change. * * If an error occurs, the process is stopped and returned. Parameters * set before an error remain unchanged. * * @param parameters - The parameters to set. * @returns An array of SetParameterResult, one for each parameter that was set. */ setParameters( parameters: Array<Parameter> ): Array<rcl_interfaces.msg.SetParametersResult>; /** * Repalce a list of declared parameters atomically. * * Declared parameters are replaced in the order they are provided. * A single ParameterEvent is published collectively for all changed * parameters. * * If an error occurs, the process stops immediately. All parameters updated to * the point of the error are reverted to their previous state. * * @param parameters - The parameters to set. * @returns Describes the result of setting 1 or more */ setParametersAtomically( parameters: Array<Parameter> ): rcl_interfaces.msg.SetParametersResult; /** * Add a callback to the front of the list of callbacks invoked for parameter declaration * and setting. No checks are made for duplicate callbacks. * * @param callback - The callback to add. */ addOnSetParametersCallback(callback: SetParametersCallback): void; /** * Remove a callback from the list of SetParameterCallbacks. * If the callback is not found the process is a nop. * * @param callback - The callback to be removed */ removeOnSetParametersCallback(call: SetParametersCallback): void; /** * Get a remote node's published topics. * * @param remoteNodeName - Name of a remote node. * @param namespace - Name of the remote namespace. * @param noDemangle - If true, topic names and types returned will not be demangled, default: false. * @returns An array of the names and types. * [ * { name: '/rosout', types: [ 'rcl_interfaces/msg/Log' ] }, * { name: '/scan', types: [ 'sensor_msgs/msg/LaserScan' ] } * ] */ getPublisherNamesAndTypesByNode( remoteNodeName: string, namespace?: string, noDemangle?: boolean ): Array<NamesAndTypesQueryResult>; /** * Get a remote node's subscribed topics. * * @param nodeName - Name of the remote node. * @param namespace - Name of the remote namespace. * @param noDemangle - If true topic, names and types returned will not be demangled, default: false. * @returns An array of the names and types. * [ * { name: '/topic', types: [ 'std_msgs/msg/String' ] } * ]s */ getSubscriptionNamesAndTypesByNode( remoteNodeName: string, namespace?: string, noDemangle?: boolean ): Array<NamesAndTypesQueryResult>; /** * Get a remote node's service topics. * * @param remoteNodeName - Name of the remote node. * @param namespace - Name of the remote namespace. * @returns An array of the names and types. * [ * { name: '/rosout', types: [ 'rcl_interfaces/msg/Log' ] }, * ... * ] */ getServiceNamesAndTypesByNode( remoteNodeName: string, namespace?: string ): Array<NamesAndTypesQueryResult>; /** * Get this node's topics and corresponding types. * * @param noDemangle - If true. topic names and types returned will not be demangled, default: false. * @returns An array of the names and types. * [ * { name: '/rosout', types: [ 'rcl_interfaces/msg/Log' ] }, * { name: '/scan', types: [ 'sensor_msgs/msg/LaserScan' ] }, * { name: '/topic', types: [ 'std_msgs/msg/String' ] } * ] */ getTopicNamesAndTypes( noDemangle?: boolean ): Array<NamesAndTypesQueryResult>; /** * Get this node's service names and corresponding types. * * @returns An array of the names and types. * [ * { name: '/start_motor', types: [ 'rplidar_ros/srv/Control' ] }, * { name: '/stop_motor', types: [ 'rplidar_ros/srv/Control' ] } * ] */ getServiceNamesAndTypes(): Array<NamesAndTypesQueryResult>; /** * Get the list of nodes discovered by the provided node. * * @returns An array of the node names. */ getNodeNames(): string[]; /** * Get the list of nodes and their namespaces discovered by the provided node. * * @returns An array of the node names and namespaces. * [ * { name: 'gazebo', namespace: '/' }, * { name: 'robot_state_publisher', namespace: '/' }, * { name: 'cam2image', namespace: '/demo' } * ] */ getNodeNamesAndNamespaces(): Array<NodeNamesQueryResult>; /** * Return the number of publishers on a given topic. * @param topic - The name of the topic. * @returns Number of publishers on the given topic. */ countPublishers(topic: string): number; /** * Return the number of subscribers on a given topic. * @param topic - The name of the topic. * @returns Number of subscribers on the given topic. */ countSubscribers(topic: string): number; } }
the_stack
import BaseDb, { KeyFilter } from './BaseDb' import chainIdToSlug from 'src/utils/chainIdToSlug' import { BigNumber } from 'ethers' import { OneWeekMs, TxError, TxRetryDelayMs } from 'src/constants' import { normalizeDbItem } from './utils' interface BaseTransfer { amount?: BigNumber amountOutMin?: BigNumber bonderFee?: BigNumber bondWithdrawalAttemptedAt?: number committed?: boolean deadline?: BigNumber destinationChainId?: number destinationChainSlug?: string isBondable?: boolean isNotFound?: boolean isTransferSpent?: boolean recipient?: string sourceChainId?: number sourceChainSlug?: string transferNonce?: string transferRootHash?: string transferRootId?: string transferSentBlockNumber?: number transferSentIndex?: number transferSentTimestamp?: number transferSentTxHash?: string transferSpentTxHash?: string withdrawalBondBackoffIndex?: number withdrawalBonded?: boolean withdrawalBondedTxHash?: string withdrawalBonder?: string withdrawalBondSettled?: boolean withdrawalBondTxError?: TxError } export interface Transfer extends BaseTransfer { transferId: string } interface UpdateTransfer extends BaseTransfer { transferId?: string } type TransfersDateFilter = { fromUnix?: number toUnix?: number } type GetItemsFilter = Partial<Transfer> & { destinationChainIds?: number[] } const invalidTransferIds: Record<string, boolean> = { } class TransfersDb extends BaseDb { subDbTimestamps: BaseDb subDbIncompletes: BaseDb subDbRootHashes: BaseDb constructor (prefix: string, _namespace?: string) { super(prefix, _namespace) this.subDbTimestamps = new BaseDb(`${prefix}:timestampedKeys`, _namespace) this.subDbIncompletes = new BaseDb(`${prefix}:incompleteItems`, _namespace) this.subDbRootHashes = new BaseDb(`${prefix}:transferRootHashes`, _namespace) } async migration () { this.logger.debug('TransfersDb migration started') const entries = await this.getKeyValues() this.logger.debug(`TransfersDb migration: ${entries.length} entries`) const promises: Array<Promise<any>> = [] for (const { key, value } of entries) { let shouldUpdate = false if (value?.sourceChainSlug === 'xdai') { shouldUpdate = true value.sourceChainSlug = 'gnosis' } if (value?.destinationChainSlug === 'xdai') { shouldUpdate = true value.destinationChainSlug = 'gnosis' } if (shouldUpdate) { promises.push(this._update(key, value)) } } await Promise.all(promises) this.logger.debug('TransfersDb migration complete') } private getTimestampedKey (transfer: Transfer) { if (transfer.transferSentTimestamp && transfer.transferId) { return `transfer:${transfer.transferSentTimestamp}:${transfer.transferId}` } } private getTransferRootHashKey (transfer: Transfer) { if (transfer.transferRootHash && transfer.transferId) { return `${transfer.transferRootHash}:${transfer.transferId}` } } private isInvalidOrNotFound (item: Transfer) { const isNotFound = item?.isNotFound const isInvalid = invalidTransferIds[item.transferId] return isNotFound || isInvalid // eslint-disable-line @typescript-eslint/prefer-nullish-coalescing } private isRouteOk (filter: GetItemsFilter = {}, item: Transfer) { if (filter.sourceChainId) { if (!item.sourceChainId || filter.sourceChainId !== item.sourceChainId) { return false } } if (filter.destinationChainIds) { if (!item.destinationChainId || !filter.destinationChainIds.includes(item.destinationChainId)) { return false } } return true } private normalizeItem (item: Transfer) { if (!item) { return null } if (item.destinationChainId) { item.destinationChainSlug = chainIdToSlug(item.destinationChainId) } if (item.sourceChainId) { item.sourceChainSlug = chainIdToSlug(item.sourceChainId) } if (item.deadline !== undefined) { // convert number to BigNumber for backward compatibility reasons if (typeof item.deadline === 'number') { item.deadline = BigNumber.from((item.deadline as number).toString()) } } return normalizeDbItem(item) } private readonly filterValueTransferId = (x: any) => { return x?.value?.transferId } private async insertTimestampedKeyItem (transfer: Transfer) { const { transferId } = transfer const logger = this.logger.create({ id: transferId }) const key = this.getTimestampedKey(transfer) if (key) { const exists = await this.subDbTimestamps.getById(key) if (!exists) { logger.debug(`storing db transfer timestamped key item. key: ${key}`) await this.subDbTimestamps._update(key, { transferId }) logger.debug(`updated db transfer timestamped key item. key: ${key}`) } } } private async insertRootHashKeyItem (transfer: Transfer) { const { transferId } = transfer const logger = this.logger.create({ id: transferId }) const key = this.getTransferRootHashKey(transfer) if (key) { const exists = await this.subDbRootHashes.getById(key) if (!exists) { logger.debug(`storing db transfer rootHash key item. key: ${key}`) await this.subDbRootHashes._update(key, { transferId }) logger.debug(`updated db transfer rootHash key item. key: ${key}`) } } } private async upsertTransferItem (transfer: Transfer) { const { transferId } = transfer const logger = this.logger.create({ id: transferId }) await this._update(transferId, transfer) const entry = await this.getById(transferId) logger.debug(`updated db transfer item. ${JSON.stringify(entry)}`) await this.upsertIncompleteItem(entry) } private async upsertIncompleteItem (transfer: Transfer) { const { transferId } = transfer const logger = this.logger.create({ id: transferId }) const isIncomplete = this.isItemIncomplete(transfer) const exists = await this.subDbIncompletes.getById(transferId) const shouldUpsert = isIncomplete && !exists const shouldDelete = !isIncomplete && exists if (shouldUpsert) { logger.debug('updating db transfer incomplete key item') await this.subDbIncompletes._update(transferId, { transferId }) logger.debug('updated db transfer incomplete key item') } else if (shouldDelete) { logger.debug('deleting db transfer incomplete key item') await this.subDbIncompletes.deleteById(transferId) logger.debug('deleted db transfer incomplete key item') } } // sort explainer: https://stackoverflow.com/a/9175783/1439168 private readonly sortItems = (a: any, b: any) => { /* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */ if (a.transferSentBlockNumber! > b.transferSentBlockNumber!) return 1 if (a.transferSentBlockNumber! < b.transferSentBlockNumber!) return -1 if (a.transferSentIndex! > b.transferSentIndex!) return 1 if (a.transferSentIndex! < b.transferSentIndex!) return -1 /* eslint-enable @typescript-eslint/no-unnecessary-type-assertion */ return 0 } async update (transferId: string, transfer: UpdateTransfer) { const logger = this.logger.create({ id: transferId }) logger.debug('update called') transfer.transferId = transferId await Promise.all([ this.insertTimestampedKeyItem(transfer as Transfer), this.insertRootHashKeyItem(transfer as Transfer), this.upsertTransferItem(transfer as Transfer) ]) } async getByTransferId (transferId: string): Promise<Transfer> { const item: Transfer = await this.getById(transferId) return this.normalizeItem(item) } async getTransferIds (dateFilter?: TransfersDateFilter): Promise<string[]> { const filter: KeyFilter = { gte: 'transfer:', lte: 'transfer:~' } // return only transfer-id keys that are within specified range (filter by timestamped keys) if (dateFilter?.fromUnix || dateFilter?.toUnix) { // eslint-disable-line @typescript-eslint/prefer-nullish-coalescing if (dateFilter.fromUnix) { filter.gte = `transfer:${dateFilter.fromUnix}` } if (dateFilter.toUnix) { filter.lte = `transfer:${dateFilter.toUnix}~` // tilde is intentional } } const kv = await this.subDbTimestamps.getKeyValues(filter) return kv.map(this.filterValueTransferId).filter(this.filterExisty) } async getItems (dateFilter?: TransfersDateFilter): Promise<Transfer[]> { const transferIds = await this.getTransferIds(dateFilter) const batchedItems = await this.batchGetByIds(transferIds) const transfers = batchedItems.map(this.normalizeItem) const items = transfers.sort(this.sortItems) this.logger.info(`items length: ${items.length}`) return items } async getTransfers (dateFilter?: TransfersDateFilter): Promise<Transfer[]> { await this.tilReady() return await this.getItems(dateFilter) } // gets only transfers within range: now - 1 week ago async getTransfersFromWeek () { await this.tilReady() const fromUnix = Math.floor((Date.now() - OneWeekMs) / 1000) return await this.getTransfers({ fromUnix }) } async getTransfersWithTransferRootHash (transferRootHash: string) { await this.tilReady() if (!transferRootHash) { throw new Error('expected transfer root hash') } const filter: KeyFilter = { gte: `${transferRootHash}`, lte: `${transferRootHash}~` // tilde is intentional } const kv = await this.subDbRootHashes.getKeyValues(filter) const unsortedTransferIds = kv.map(this.filterValueTransferId).filter(this.filterExisty) const items = await this.batchGetByIds(unsortedTransferIds) const sortedTransferids = items.sort(this.sortItems).map(this.filterValueTransferId) return sortedTransferids } async getUncommittedTransfers ( filter: GetItemsFilter = {} ): Promise<Transfer[]> { const transfers: Transfer[] = await this.getTransfersFromWeek() return transfers.filter(item => { if (!this.isRouteOk(filter, item)) { return false } return ( item.transferId && !item.transferRootId && item.transferSentTxHash && !item.committed ) }) } async getUnbondedSentTransfers ( filter: GetItemsFilter = {} ): Promise<Transfer[]> { const transfers: Transfer[] = await this.getTransfersFromWeek() return transfers.filter(item => { if (!item?.transferId) { return false } if (invalidTransferIds[item.transferId]) { return false } if (!this.isRouteOk(filter, item)) { return false } const shouldIgnoreItem = this.isInvalidOrNotFound(item) if (shouldIgnoreItem) { return false } let timestampOk = true if (item.bondWithdrawalAttemptedAt) { if (TxError.BonderFeeTooLow === item.withdrawalBondTxError) { const delay = TxRetryDelayMs + ((1 << item.withdrawalBondBackoffIndex!) * 60 * 1000) // eslint-disable-line // TODO: use `sentTransferTimestamp` once it's added to db // don't attempt to bond withdrawals after a week if (delay > OneWeekMs) { return false } timestampOk = item.bondWithdrawalAttemptedAt + delay < Date.now() } else { timestampOk = item.bondWithdrawalAttemptedAt + TxRetryDelayMs < Date.now() } } return ( item.transferId && item.transferSentTimestamp && !item.withdrawalBonded && item.transferSentTxHash && item.isBondable && !item.isTransferSpent && timestampOk ) }) } isItemIncomplete (item: Transfer) { if (!item?.transferId) { return false } const shouldIgnoreItem = this.isInvalidOrNotFound(item) if (shouldIgnoreItem) { return false } return ( /* eslint-disable @typescript-eslint/prefer-nullish-coalescing */ !item.sourceChainId || !item.destinationChainId || !item.transferSentBlockNumber || (item.transferSentBlockNumber && !item.transferSentTimestamp) || (item.withdrawalBondedTxHash && !item.withdrawalBonder) /* eslint-enable @typescript-eslint/prefer-nullish-coalescing */ ) } async getIncompleteItems ( filter: GetItemsFilter = {} ) { const kv = await this.subDbIncompletes.getKeyValues() const transferIds = kv.map(this.filterValueTransferId).filter(this.filterExisty) if (!transferIds.length) { return [] } const batchedItems = await this.batchGetByIds(transferIds) const transfers = batchedItems.map(this.normalizeItem) return transfers.filter((item: any) => { if (filter.sourceChainId && item.sourceChainId) { if (filter.sourceChainId !== item.sourceChainId) { return false } } const shouldIgnoreItem = this.isInvalidOrNotFound(item) if (shouldIgnoreItem) { return false } return this.isItemIncomplete(item) }) } } export default TransfersDb
the_stack
import * as React from "react"; import { BoardType, SpaceSubtype, Space, EditorEventActivationType, GameVersion } from "./types"; import { ISpace, addEventToSpace, removeEventFromSpace, getCurrentBoard, IEventInstance, setHostsStar } from "./boards"; import { EventsList } from "./components/EventList"; import { $setting, get } from "./views/settings"; import { makeKeyClick, useForceUpdate } from "./utils/react"; import { IEvent, createEventInstance } from "./events/events"; import { changeDecisionTree, getValidSelectedSpaceIndices } from "./app/appControl"; import { Button } from "./controls"; import { $$log } from "./utils/debug"; import blueImage from "./img/toolbar/blue.png"; import blue3Image from "./img/toolbar/blue3.png"; import redImage from "./img/toolbar/red.png"; import red3Image from "./img/toolbar/red3.png"; import happeningImage from "./img/toolbar/happening.png"; import happening3Image from "./img/toolbar/happening3.png"; import chanceImage from "./img/toolbar/chance.png"; import chance2Image from "./img/toolbar/chance2.png"; import chance3Image from "./img/toolbar/chance3.png"; import bowserImage from "./img/toolbar/bowser.png"; import bowser3Image from "./img/toolbar/bowser3.png"; import minigameImage from "./img/toolbar/minigame.png"; import shroomImage from "./img/toolbar/shroom.png"; import otherImage from "./img/toolbar/other.png"; import starImage from "./img/toolbar/star.png"; import blackstarImage from "./img/toolbar/blackstar.png"; import arrowImage from "./img/toolbar/arrow.png"; import startImage from "./img/toolbar/start.png"; import itemImage from "./img/toolbar/item.png"; import item3Image from "./img/toolbar/item3.png"; import battleImage from "./img/toolbar/battle.png"; import battle3Image from "./img/toolbar/battle3.png"; import bankImage from "./img/toolbar/bank.png"; import bank3Image from "./img/toolbar/bank3.png"; import gameguyImage from "./img/toolbar/gameguy.png"; import banksubtypeImage from "./img/toolbar/banksubtype.png"; import banksubtype2Image from "./img/toolbar/banksubtype2.png"; import bankcoinsubtypeImage from "./img/toolbar/bankcoinsubtype.png"; import itemshopsubtypeImage from "./img/toolbar/itemshopsubtype.png"; import itemshopsubtype2Image from "./img/toolbar/itemshopsubtype2.png"; import toadImage from "./img/toolbar/toad.png"; import mstarImage from "./img/toolbar/mstar.png"; import booImage from "./img/toolbar/boo.png"; import bowsercharacterImage from "./img/toolbar/bowsercharacter.png"; import koopaImage from "./img/toolbar/koopa.png"; import basic3Image from "./img/toolbar/basic3.png"; import minigameduel3Image from "./img/toolbar/minigameduel3.png"; import reverse3Image from "./img/toolbar/reverse3.png"; import happeningduel3Image from "./img/toolbar/happeningduel3.png"; import gameguyduelImage from "./img/toolbar/gameguyduel.png"; import powerupImage from "./img/toolbar/powerup.png"; import startblueImage from "./img/toolbar/startblue.png"; import startredImage from "./img/toolbar/startred.png"; import { SectionHeading } from "./propertiesshared"; import { useCallback } from "react"; import { useSelectedSpaceIndices, useSelectedSpaces } from "./app/hooks"; import { setSpaceEventActivationTypeAction, setSpaceEventEventParameterAction, setSpacePositionsAction, setSpaceTypeAction } from "./app/boardState"; import { store } from "./app/store"; interface ISpacePropertiesProps { boardType: BoardType; gameVersion: GameVersion; } export function SpaceProperties(props: ISpacePropertiesProps) { const forceUpdate = useForceUpdate(); const selectedSpaceIndices = useSelectedSpaceIndices(); const spaces = useSelectedSpaces(); const onTypeChanged = useCallback((type: Space, subtype?: SpaceSubtype) => { store.dispatch(setSpaceTypeAction({ spaceIndices: selectedSpaceIndices, type, subtype, })); forceUpdate(); }, [selectedSpaceIndices, forceUpdate]); const onStarCheckChanged = useCallback((checked: boolean) => { setHostsStar(getValidSelectedSpaceIndices(), !!checked); forceUpdate(); }, [forceUpdate]); if (!spaces || !spaces.length) { return ( <div className="propertiesEmptyText">No space selected.</div> ); } const multipleSelections = spaces.length > 1; const curSpace = spaces[0]; const curSpaceIndex = getValidSelectedSpaceIndices()[0]; const gameVersion = props.gameVersion; const boardType = props.boardType; const isDuel = boardType === BoardType.DUEL; const spaceToggleTypes = _getSpaceTypeToggles(gameVersion, boardType); const spaceToggleSubTypes = _getSpaceSubTypeToggles(gameVersion, boardType); let currentType: Space | undefined = curSpace.type; let currentSubtype = curSpace.subtype; let hostsStarChecked = curSpace.star || false; let hostsStarIndeterminate = false; if (multipleSelections) { // Only show a type as selected if all spaces are the same. for (const space of spaces) { if (!space) continue; if (space.type !== currentType) currentType = undefined; if (space.subtype !== currentSubtype) currentSubtype = undefined; if (!!space.star !== hostsStarChecked) hostsStarIndeterminate = true; } } return ( <div className="properties"> <div className="propertiesPadded"> {!multipleSelections && <SpaceCoords space={curSpace} spaceIndex={curSpaceIndex} />} <SpaceTypeToggle toggleTypes={spaceToggleTypes} type={currentType} subtype={currentSubtype} typeChanged={onTypeChanged} /> <SpaceTypeToggle toggleTypes={spaceToggleSubTypes} type={currentType} subtype={currentSubtype} typeChanged={onTypeChanged} /> {!isDuel && <SpaceStarCheckbox checked={hostsStarChecked} indeterminate={hostsStarIndeterminate} onStarCheckChanged={onStarCheckChanged} />} <SpaceDecisionTreeButton space={curSpace} /> </div> {!multipleSelections && <SpaceEventList selectedSpace={curSpace} />} </div> ); }; interface ISpaceCoordsProps { space: ISpace; spaceIndex: number; } class SpaceCoords extends React.Component<ISpaceCoordsProps, any> { state: any = {} onChangeX = (event: any) => { var newX = parseInt(event.target.value, 10); var isBlank = event.target.value === ""; var curBgWidth = getCurrentBoard().bg.width; if ((!isBlank && isNaN(newX)) || newX < 0 || newX > curBgWidth) return; if (!this.state.oldX) this.setState({ oldX: this.props.space.x }); store.dispatch(setSpacePositionsAction({ spaceIndices: [this.props.spaceIndex], coords: [{ x: isBlank ? 0 : newX }] })); this.forceUpdate(); } onChangeY = (event: any) => { let newY = parseInt(event.target.value, 10); let isBlank = event.target.value === ""; let curBgHeight = getCurrentBoard().bg.height; if ((!isBlank && isNaN(newY)) || newY < 0 || newY > curBgHeight) return; if (!this.state.oldY) this.setState({ oldY: this.props.space.y }); store.dispatch(setSpacePositionsAction({ spaceIndices: [this.props.spaceIndex], coords: [{ y: isBlank ? 0 : newY }] })); this.forceUpdate(); } // onChangeRotation = (event: any) => { // let newRot = parseInt(event.target.value, 10); // let isBlank = event.target.value === ""; // if ((!isBlank && isNaN(newRot)) || newRot < 0 || newRot > 360) // return; // if (!this.state.oldRot) // this.setState({ oldRot: this.props.space.rotation }); // if (!newRot) // delete this.props.space.rotation; // else // this.props.space.rotation = newRot; // this.forceUpdate(); // } onCoordSet = () => { store.dispatch(setSpacePositionsAction({ spaceIndices: [this.props.spaceIndex], coords: [{ x: this.props.space.x || 0, y: this.props.space.y || 0, }] })); this.setState({ oldX: undefined, oldY: undefined, oldRot: undefined }); this.forceUpdate(); } onKeyUp = (event: any) => { if (event.key === "Enter") this.onCoordSet(); } render() { let space = this.props.space; if (!space) return null; // const isArrow = space.type === Space.ARROW; return ( <> <div className="spaceCoordRow"> <span className="coordLabel">X:</span> <input className="coordInput" type="number" value={space.x} onChange={this.onChangeX} onBlur={this.onCoordSet} onKeyUp={this.onKeyUp} /> <span className="coordLabel">Y:</span> <input className="coordInput" type="number" value={space.y} onChange={this.onChangeY} onBlur={this.onCoordSet} onKeyUp={this.onKeyUp} /> </div> {/* {isArrow && <div className="spaceCoordRow"> <span className="coordLabel">Rotation:</span> <input className="coordInput" type="text" value={space.rotation} onChange={this.onChangeRotation} onBlur={this.onCoordSet} onKeyUp={this.onKeyUp} /> </div> } */} </> ); } }; interface SpaceTypeToggleItem { name: string; icon: string; type?: Space subtype?: SpaceSubtype; advanced?: boolean; } const SpaceTypeToggleTypes_1: SpaceTypeToggleItem[] = [ // Types { name: "Change to blue space", icon: blueImage, type: Space.BLUE }, { name: "Change to red space", icon: redImage, type: Space.RED }, { name: "Change to happening space", icon: happeningImage, type: Space.HAPPENING }, { name: "Change to chance time space", icon: chanceImage, type: Space.CHANCE }, { name: "Change to Mini-Game space", icon: minigameImage, type: Space.MINIGAME }, { name: "Change to shroom space", icon: shroomImage, type: Space.SHROOM }, { name: "Change to Bowser space", icon: bowserImage, type: Space.BOWSER }, { name: "Change to invisible space", icon: otherImage, type: Space.OTHER }, { name: "Change to star space", icon: starImage, type: Space.STAR, advanced: true }, { name: "Change to start space", icon: startImage, type: Space.START, advanced: true }, ]; const SpaceSubTypeToggleTypes_1: SpaceTypeToggleItem[] = [ // Subtypes { name: "Show Toad", icon: toadImage, subtype: SpaceSubtype.TOAD }, { name: "Show Boo", icon: booImage, subtype: SpaceSubtype.BOO }, { name: "Show Bowser", icon: bowsercharacterImage, subtype: SpaceSubtype.BOWSER }, { name: "Show Koopa Troopa", icon: koopaImage, subtype: SpaceSubtype.KOOPA }, ]; const SpaceTypeToggleTypes_2: SpaceTypeToggleItem[] = [ // Types { name: "Change to blue space", icon: blueImage, type: Space.BLUE }, { name: "Change to red space", icon: redImage, type: Space.RED }, { name: "Change to happening space", icon: happeningImage, type: Space.HAPPENING }, { name: "Change to chance time space", icon: chance2Image, type: Space.CHANCE }, { name: "Change to Bowser space", icon: bowserImage, type: Space.BOWSER }, { name: "Change to item space", icon: itemImage, type: Space.ITEM }, { name: "Change to battle space", icon: battleImage, type: Space.BATTLE }, { name: "Change to bank space", icon: bankImage, type: Space.BANK }, { name: "Change to invisible space", icon: otherImage, type: Space.OTHER }, { name: "Change to star space", icon: starImage, type: Space.STAR, advanced: true }, { name: "Change to black star space", icon: blackstarImage, type: Space.BLACKSTAR, advanced: true }, { name: "Change to start space", icon: startImage, type: Space.START, advanced: true }, { name: "Change to arrow space", icon: arrowImage, type: Space.ARROW }, ]; const SpaceSubTypeToggleTypes_2: SpaceTypeToggleItem[] = [ // Subtypes { name: "Show Toad", icon: toadImage, subtype: SpaceSubtype.TOAD }, { name: "Show Boo", icon: booImage, subtype: SpaceSubtype.BOO }, { name: "Show bank", icon: banksubtype2Image, subtype: SpaceSubtype.BANK }, { name: "Show bank coin stack", icon: bankcoinsubtypeImage, subtype: SpaceSubtype.BANKCOIN }, { name: "Show item shop", icon: itemshopsubtype2Image, subtype: SpaceSubtype.ITEMSHOP }, ]; const SpaceTypeToggleTypes_3: SpaceTypeToggleItem[] = [ // Types { name: "Change to blue space", icon: blue3Image, type: Space.BLUE }, { name: "Change to red space", icon: red3Image, type: Space.RED }, { name: "Change to happening space", icon: happening3Image, type: Space.HAPPENING }, { name: "Change to chance time space", icon: chance3Image, type: Space.CHANCE }, { name: "Change to Bowser space", icon: bowser3Image, type: Space.BOWSER }, { name: "Change to item space", icon: item3Image, type: Space.ITEM }, { name: "Change to battle space", icon: battle3Image, type: Space.BATTLE }, { name: "Change to bank space", icon: bank3Image, type: Space.BANK }, { name: "Change to Game Guy space", icon: gameguyImage, type: Space.GAMEGUY }, { name: "Change to invisible space", icon: otherImage, type: Space.OTHER }, { name: "Change to star space", icon: starImage, type: Space.STAR, advanced: true }, { name: "Change to start space", icon: startImage, type: Space.START, advanced: true }, { name: "Change to arrow space", icon: arrowImage, type: Space.ARROW }, ]; const SpaceSubTypeToggleTypes_3: SpaceTypeToggleItem[] = [ // Subtypes { name: "Show Millenium Star", icon: mstarImage, subtype: SpaceSubtype.TOAD }, { name: "Show Boo", icon: booImage, subtype: SpaceSubtype.BOO }, { name: "Show bank", icon: banksubtypeImage, subtype: SpaceSubtype.BANK }, { name: "Show bank coin stack", icon: bankcoinsubtypeImage, subtype: SpaceSubtype.BANKCOIN }, { name: "Show item shop", icon: itemshopsubtypeImage, subtype: SpaceSubtype.ITEMSHOP }, ]; const SpaceTypeToggleTypes_3_Duel: SpaceTypeToggleItem[] = [ // Types { name: "Change to basic space", icon: basic3Image, type: Space.DUEL_BASIC }, { name: "Change to Mini-Game space", icon: minigameduel3Image, type: Space.MINIGAME }, { name: "Change to reverse space", icon: reverse3Image, type: Space.DUEL_REVERSE }, { name: "Change to happening space", icon: happeningduel3Image, type: Space.HAPPENING }, { name: "Change to Game Guy space", icon: gameguyduelImage, type: Space.GAMEGUY }, { name: "Change to power-up space", icon: powerupImage, type: Space.DUEL_POWERUP }, { name: "Change to invisible space", icon: otherImage, type: Space.OTHER }, { name: "Change to blue start space", icon: startblueImage, type: Space.DUEL_START_BLUE, advanced: true }, { name: "Change to red start space", icon: startredImage, type: Space.DUEL_START_RED, advanced: true }, ]; function _getSpaceTypeToggles(gameVersion: 1 | 2 | 3, boardType: BoardType) { let types: SpaceTypeToggleItem[] = []; switch (gameVersion) { case 1: types = SpaceTypeToggleTypes_1; break; case 2: types = SpaceTypeToggleTypes_2; break; case 3: switch (boardType) { case BoardType.DUEL: types = SpaceTypeToggleTypes_3_Duel; break; default: types = SpaceTypeToggleTypes_3; break; } break; } if (!get($setting.uiAdvanced)) { types = types.filter(a => !a.advanced); } return types; } function _getSpaceSubTypeToggles(gameVersion: 1 | 2 | 3, boardType: BoardType) { let types: SpaceTypeToggleItem[] = []; switch (gameVersion) { case 1: types = SpaceSubTypeToggleTypes_1; break; case 2: types = SpaceSubTypeToggleTypes_2; break; case 3: switch (boardType) { case BoardType.DUEL: types = []; //SpaceSubTypeToggleTypes_3_Duel; break; default: types = SpaceSubTypeToggleTypes_3; break; } break; } if (!get($setting.uiAdvanced)) { types = types.filter(a => !a.advanced); } return types; } interface ISpaceTypeToggleProps { type?: Space; subtype?: SpaceSubtype; toggleTypes: any; typeChanged(type?: Space, subtype?: SpaceSubtype): any; } class SpaceTypeToggle extends React.Component<ISpaceTypeToggleProps> { onTypeChanged = (type: Space, subtype?: SpaceSubtype) => { this.props.typeChanged(type, subtype); } render() { const type = this.props.type; if (type === Space.START && !get($setting.uiAdvanced)) return null; // Can't switch start space type const subtype = this.props.subtype; const onTypeChanged = this.onTypeChanged; const toggleTypes = this.props.toggleTypes || []; const toggles = toggleTypes.map((item: any) => { const key = item.type + "-" + item.subtype; const selected = (item.type !== undefined && type === item.type) || (item.subtype !== undefined && subtype !== undefined && subtype === item.subtype); return ( <SpaceTypeToggleBtn key={key} type={item.type} subtype={item.subtype} icon={item.icon} title={item.name} selected={selected} typeChanged={onTypeChanged} /> ); }); return ( <div className="spaceToggleContainer"> {toggles} </div> ); } }; interface ISpaceTypeToggleBtnProps { selected: boolean; icon: string; title: string; type: Space; subtype?: SpaceSubtype; typeChanged(type: Space, subtype?: SpaceSubtype): any; } class SpaceTypeToggleBtn extends React.Component<ISpaceTypeToggleBtnProps> { onTypeChanged = () => { if (this.props.subtype !== undefined && this.props.selected) this.props.typeChanged(this.props.type, undefined); else this.props.typeChanged(this.props.type, this.props.subtype); } render() { let btnClass = "spaceToggleButton"; if (this.props.selected) btnClass += " selected"; const size = this.props.subtype !== undefined ? 25 : 20; return ( <div className={btnClass} title={this.props.title} tabIndex={0} onClick={this.onTypeChanged} onKeyDown={makeKeyClick(this.onTypeChanged)}> <img src={this.props.icon} height={size} width={size} alt="" /> </div> ); } }; interface ISpaceStarCheckboxProps { checked: boolean; indeterminate: boolean; onStarCheckChanged(changed: boolean): void; } class SpaceStarCheckbox extends React.Component<ISpaceStarCheckboxProps> { private checkboxEl: HTMLInputElement | null = null; render() { return ( <div className="starCheckbox"> <label><input type="checkbox" ref={el => this.checkboxEl = el} checked={this.props.checked} value={this.props.checked as any} onChange={this.onChange} /> Hosts star</label> </div> ); } onChange = (event: any) => { this.props.onStarCheckChanged(event.target.checked); } componentDidMount() { this.checkboxEl!.indeterminate = this.props.indeterminate; } componentDidUpdate(prevProps: ISpaceStarCheckboxProps) { if (prevProps.indeterminate !== this.props.indeterminate) { this.checkboxEl!.indeterminate = this.props.indeterminate; } } }; interface ISpaceDecisionTreeButtonProps { space: ISpace; } function SpaceDecisionTreeButton(props: ISpaceDecisionTreeButtonProps) { if (!props.space.aiTree) { return null; } return ( <Button css="propertiesAiTreeButton" onClick={() => { $$log("Showing decision tree", props.space.aiTree); changeDecisionTree(props.space.aiTree!); }}> AI Decision Tree </Button> ); } interface ISpaceEventListProps { selectedSpace: ISpace; } const SpaceEventList: React.FC<ISpaceEventListProps> = props => { const forceUpdate = useForceUpdate(); function onEventAdded(event: IEvent) { const space = props.selectedSpace; const spaceEvent = createEventInstance(event, { activationType: getDefaultActivationType(space) }); addEventToSpace(spaceEvent); forceUpdate(); } function onEventDeleted(event: IEventInstance, eventIndex: number) { removeEventFromSpace(eventIndex); forceUpdate(); } function onEventActivationTypeToggle(event: IEventInstance, eventIndex: number) { let activationType: EditorEventActivationType; if (event.activationType === EditorEventActivationType.WALKOVER) activationType = EditorEventActivationType.LANDON; else activationType = EditorEventActivationType.WALKOVER; store.dispatch(setSpaceEventActivationTypeAction({ eventIndex, activationType })); } function onEventParameterSet(event: IEventInstance, eventIndex: number, name: string, value: number | boolean) { store.dispatch(setSpaceEventEventParameterAction({ eventIndex, name, value })); } return ( <> <SectionHeading text="Events" /> <div className="propertiesPadded"> <EventsList events={props.selectedSpace.events} board={getCurrentBoard()} onEventAdded={onEventAdded} onEventDeleted={onEventDeleted} onEventActivationTypeToggle={onEventActivationTypeToggle} onEventParameterSet={onEventParameterSet} /> </div> </> ); }; function getDefaultActivationType(space: ISpace): EditorEventActivationType { switch (space.type) { // These spaces are not solid, so default to passing. case Space.OTHER: case Space.START: case Space.ARROW: case Space.STAR: case Space.BLACKSTAR: return EditorEventActivationType.WALKOVER; } return EditorEventActivationType.LANDON; }
the_stack
// clang-format off import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {AllSitesElement, ContentSetting, ContentSettingsTypes, LocalDataBrowserProxyImpl, SiteGroup, SiteSettingsPrefsBrowserProxyImpl, SortMethod} from 'chrome://settings/lazy_load.js'; import {CrSettingsPrefs, Router, routes} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {isChildVisible} from 'chrome://webui-test/test_util.js'; import {TestLocalDataBrowserProxy} from './test_local_data_browser_proxy.js'; import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js'; import {createContentSettingTypeToValuePair, createOriginInfo, createRawSiteException, createSiteGroup, createSiteSettingsPrefs, SiteSettingsPref} from './test_util.js'; // clang-format on suite('AllSites_DisabledConsolidatedControls', function() { /** * An example eTLD+1 Object with multiple origins grouped under it. */ const TEST_MULTIPLE_SITE_GROUP = createSiteGroup('example.com', [ 'http://example.com', 'https://www.example.com', 'https://login.example.com', ]); /** * An example pref with multiple categories and multiple allow/block * state. */ let prefsVarious: SiteSettingsPref; let testElement: AllSitesElement; /** * The mock proxy object to use during test. */ let browserProxy: TestSiteSettingsPrefsBrowserProxy; /** * The mock local data proxy object to use during test. */ let localDataBrowserProxy: TestLocalDataBrowserProxy; suiteSetup(function() { CrSettingsPrefs.setInitialized(); loadTimeData.overrideValues({ consolidatedSiteStorageControlsEnabled: false, }); }); suiteTeardown(function() { CrSettingsPrefs.resetForTesting(); }); // Initialize a site-list before each test. setup(async function() { document.body.innerHTML = ''; prefsVarious = createSiteSettingsPrefs([], [ createContentSettingTypeToValuePair( ContentSettingsTypes.GEOLOCATION, [ createRawSiteException('https://foo.com'), createRawSiteException('https://bar.com', { setting: ContentSetting.BLOCK, }) ]), createContentSettingTypeToValuePair( ContentSettingsTypes.NOTIFICATIONS, [ createRawSiteException('https://google.com', { setting: ContentSetting.BLOCK, }), createRawSiteException('https://bar.com', { setting: ContentSetting.BLOCK, }), createRawSiteException('https://foo.com', { setting: ContentSetting.BLOCK, }), ]) ]); browserProxy = new TestSiteSettingsPrefsBrowserProxy(); localDataBrowserProxy = new TestLocalDataBrowserProxy(); SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy); LocalDataBrowserProxyImpl.setInstance(localDataBrowserProxy); testElement = document.createElement('all-sites'); assertTrue(!!testElement); document.body.appendChild(testElement); }); teardown(function() { // The code being tested changes the Route. Reset so that state is not // leaked across tests. Router.getInstance().resetRouteForTesting(); }); /** * Configures the test element. * @param prefs The prefs to use. * @param sortOrder the URL param used to establish default sort order. */ function setUpAllSites(prefs: SiteSettingsPref, sortOrder?: SortMethod) { browserProxy.setPrefs(prefs); if (sortOrder) { Router.getInstance().navigateTo( routes.SITE_SETTINGS_ALL, new URLSearchParams(`sort=${sortOrder}`)); } else { Router.getInstance().navigateTo(routes.SITE_SETTINGS_ALL); } } test('All sites list populated', async function() { setUpAllSites(prefsVarious); testElement.currentRouteChanged(routes.SITE_SETTINGS_ALL); await browserProxy.whenCalled('getAllSites'); assertEquals(3, testElement.siteGroupMap.size); // Flush to be sure list container is populated. flush(); const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(3, siteEntries.length); }); test('search query filters list', async function() { const SEARCH_QUERY = 'foo'; setUpAllSites(prefsVarious); testElement.currentRouteChanged(routes.SITE_SETTINGS_ALL); await browserProxy.whenCalled('getAllSites'); // Flush to be sure list container is populated. flush(); let siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(3, siteEntries.length); testElement.filter = SEARCH_QUERY; flush(); siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); const hiddenSiteEntries = Array.from( testElement.shadowRoot!.querySelectorAll('site-entry[hidden]')); assertEquals(1, siteEntries.length - hiddenSiteEntries.length); for (const entry of siteEntries) { if (!hiddenSiteEntries.includes(entry)) { assertTrue(entry.siteGroup.origins.some(origin => { return origin.origin.includes(SEARCH_QUERY); })); } } }); test('can be sorted by most visited', function() { setUpAllSites(prefsVarious); testElement.currentRouteChanged(routes.SITE_SETTINGS_ALL); return browserProxy.whenCalled('getAllSites').then(() => { // Add additional origins and artificially insert fake engagement scores // to sort. assertEquals(3, testElement.siteGroupMap.size); const fooSiteGroup = testElement.siteGroupMap.get('foo.com')!; fooSiteGroup.origins.push( createOriginInfo('https://login.foo.com', {engagement: 20})); assertEquals(2, fooSiteGroup.origins.length); fooSiteGroup.origins[0]!.engagement = 50.4; const googleSiteGroup = testElement.siteGroupMap.get('google.com')!; assertEquals(1, googleSiteGroup.origins.length); googleSiteGroup.origins[0]!.engagement = 55.1261; const barSiteGroup = testElement.siteGroupMap.get('bar.com')!; assertEquals(1, barSiteGroup.origins.length); barSiteGroup.origins[0]!.engagement = 0.5235; // 'Most visited' is the default sort method, so sort by a different // method first to ensure changing to 'Most visited' works. testElement.$.sortMethod.value = 'name'; testElement.$.sortMethod.dispatchEvent(new CustomEvent('change')); flush(); let siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals('bar.com', siteEntries[0]!.$.displayName.innerText.trim()); assertEquals('foo.com', siteEntries[1]!.$.displayName.innerText.trim()); assertEquals( 'google.com', siteEntries[2]!.$.displayName.innerText.trim()); testElement.$.sortMethod.value = 'most-visited'; testElement.$.sortMethod.dispatchEvent(new CustomEvent('change')); flush(); siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); // Each site entry is sorted by its maximum engagement, so expect // 'foo.com' to come after 'google.com'. assertEquals( 'google.com', siteEntries[0]!.$.displayName.innerText.trim()); assertEquals('foo.com', siteEntries[1]!.$.displayName.innerText.trim()); assertEquals('bar.com', siteEntries[2]!.$.displayName.innerText.trim()); }); }); test('can be sorted by storage', async function() { setUpAllSites(prefsVarious); testElement.currentRouteChanged(routes.SITE_SETTINGS_ALL); await browserProxy.whenCalled('getAllSites'); flush(); let siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); // Add additional origins to SiteGroups with cookies to simulate their // being grouped entries, plus add local storage. siteEntries[0]!.siteGroup.origins[0]!.usage = 900; siteEntries[1]!.siteGroup.origins.push(createOriginInfo('http://bar.com')); siteEntries[1]!.siteGroup.origins[0]!.usage = 500; siteEntries[1]!.siteGroup.origins[1]!.usage = 500; siteEntries[2]!.siteGroup.origins.push( createOriginInfo('http://google.com')); testElement.$.sortMethod.dispatchEvent(new CustomEvent('change')); siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); // Verify all sites is not sorted by storage. assertEquals(3, siteEntries.length); assertEquals('foo.com', siteEntries[0]!.$.displayName.innerText.trim()); assertEquals('bar.com', siteEntries[1]!.$.displayName.innerText.trim()); assertEquals('google.com', siteEntries[2]!.$.displayName.innerText.trim()); // Change the sort method, then verify all sites is now sorted by // name. testElement.$.sortMethod.value = 'data-stored'; testElement.$.sortMethod.dispatchEvent(new CustomEvent('change')); flush(); siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals( 'bar.com', siteEntries[0]!.shadowRoot! .querySelector<HTMLElement>( '#displayName .url-directionality')!.innerText.trim()); assertEquals( 'foo.com', siteEntries[1]!.shadowRoot! .querySelector<HTMLElement>( '#displayName .url-directionality')!.innerText.trim()); assertEquals( 'google.com', siteEntries[2]!.shadowRoot! .querySelector<HTMLElement>( '#displayName .url-directionality')!.innerText.trim()); }); test('can be sorted by storage by passing URL param', async function() { // The default sorting (most visited) will have the ascending storage // values. With the URL param, we expect the sites to be sorted by usage in // descending order. document.body.innerHTML = ''; setUpAllSites(prefsVarious, SortMethod.STORAGE); testElement = document.createElement('all-sites'); document.body.appendChild(testElement); testElement.currentRouteChanged(routes.SITE_SETTINGS_ALL); await browserProxy.whenCalled('getAllSites'); flush(); const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals( 'google.com', siteEntries[0]!.shadowRoot! .querySelector<HTMLElement>( '#displayName .url-directionality')!.innerText.trim()); assertEquals( 'bar.com', siteEntries[1]!.shadowRoot! .querySelector<HTMLElement>( '#displayName .url-directionality')!.innerText.trim()); assertEquals( 'foo.com', siteEntries[2]!.shadowRoot! .querySelector<HTMLElement>( '#displayName .url-directionality')!.innerText.trim()); }); test('can be sorted by name', async function() { setUpAllSites(prefsVarious); testElement.currentRouteChanged(routes.SITE_SETTINGS_ALL); await browserProxy.whenCalled('getAllSites'); flush(); let siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); // Verify all sites is not sorted by name. assertEquals(3, siteEntries.length); assertEquals('foo.com', siteEntries[0]!.$.displayName.innerText.trim()); assertEquals('bar.com', siteEntries[1]!.$.displayName.innerText.trim()); assertEquals('google.com', siteEntries[2]!.$.displayName.innerText.trim()); // Change the sort method, then verify all sites is now sorted by name. testElement.$.sortMethod.value = 'name'; testElement.$.sortMethod.dispatchEvent(new CustomEvent('change')); flush(); siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals('bar.com', siteEntries[0]!.$.displayName.innerText.trim()); assertEquals('foo.com', siteEntries[1]!.$.displayName.innerText.trim()); assertEquals('google.com', siteEntries[2]!.$.displayName.innerText.trim()); }); test('can sort by name by passing URL param', async function() { document.body.innerHTML = ''; setUpAllSites(prefsVarious, SortMethod.NAME); testElement = document.createElement('all-sites'); document.body.appendChild(testElement); testElement.currentRouteChanged(routes.SITE_SETTINGS_ALL); await browserProxy.whenCalled('getAllSites'); flush(); const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals('bar.com', siteEntries[0]!.$.displayName.innerText.trim()); assertEquals('foo.com', siteEntries[1]!.$.displayName.innerText.trim()); assertEquals('google.com', siteEntries[2]!.$.displayName.innerText.trim()); }); test('merging additional SiteGroup lists works', async function() { setUpAllSites(prefsVarious); testElement.currentRouteChanged(routes.SITE_SETTINGS_ALL); await browserProxy.whenCalled('getAllSites'); flush(); let siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(3, siteEntries.length); // Pretend an additional set of SiteGroups were added. const fooEtldPlus1 = 'foo.com'; const addEtldPlus1 = 'additional-site.net'; const fooOrigin = 'https://login.foo.com'; const addOrigin = 'http://www.additional-site.net'; const STORAGE_SITE_GROUP_LIST: SiteGroup[] = [ { // Test merging an existing site works, with overlapping origin lists. etldPlus1: fooEtldPlus1, origins: [ createOriginInfo(fooOrigin), createOriginInfo('https://foo.com'), ], hasInstalledPWA: false, numCookies: 0, }, { // Test adding a new site entry works. etldPlus1: addEtldPlus1, origins: [createOriginInfo(addOrigin)], hasInstalledPWA: false, numCookies: 0, }, ]; testElement.onStorageListFetched(STORAGE_SITE_GROUP_LIST); flush(); siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(4, siteEntries.length); assertEquals(fooEtldPlus1, siteEntries[0]!.siteGroup.etldPlus1); assertEquals(2, siteEntries[0]!.siteGroup.origins.length); assertEquals(fooOrigin, siteEntries[0]!.siteGroup.origins[0]!.origin); assertEquals( 'https://foo.com', siteEntries[0]!.siteGroup.origins[1]!.origin); assertEquals(addEtldPlus1, siteEntries[3]!.siteGroup.etldPlus1); assertEquals(1, siteEntries[3]!.siteGroup.origins.length); assertEquals(addOrigin, siteEntries[3]!.siteGroup.origins[0]!.origin); }); function resetSettingsViaOverflowMenu(buttonType: string) { assertTrue( buttonType === 'cancel-button' || buttonType === 'action-button'); flush(); const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(1, siteEntries.length); const overflowMenuButton = siteEntries[0]!.$$<HTMLElement>('#overflowMenuButton')!; assertFalse( overflowMenuButton.closest<HTMLElement>('.row-aligned')!.hidden); // Open the reset settings dialog. const overflowMenu = testElement.$.menu.get(); const menuItems = overflowMenu.querySelectorAll<HTMLElement>('.dropdown-item'); // Test clicking on the overflow menu button opens the menu. assertFalse(overflowMenu.open); overflowMenuButton.click(); assertTrue(overflowMenu.open); // Open the reset settings dialog and tap the |buttonType| button. assertFalse(testElement.$.confirmResetSettings.get().open); menuItems[0]!.click(); assertTrue(testElement.$.confirmResetSettings.get().open); const actionButtonList = testElement.$.confirmResetSettings.get().querySelectorAll<HTMLElement>( `.${buttonType}`); assertEquals(1, actionButtonList.length); actionButtonList[0]!.click(); // Check the dialog and overflow menu are now both closed. assertFalse(testElement.$.confirmResetSettings.get().open); assertFalse(overflowMenu.open); } test('cancelling the confirm dialog on resetting settings works', function() { testElement.siteGroupMap.set( TEST_MULTIPLE_SITE_GROUP.etldPlus1, JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP))); testElement.forceListUpdateForTesting(); resetSettingsViaOverflowMenu('cancel-button'); }); test('reset settings via overflow menu (no data or cookies)', function() { // Test when entire siteGroup has no data or cookies. // Clone this object to avoid propagating changes made in this test. testElement.siteGroupMap.set( TEST_MULTIPLE_SITE_GROUP.etldPlus1, JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP))); testElement.forceListUpdateForTesting(); resetSettingsViaOverflowMenu('action-button'); // Ensure a call was made to setOriginPermissions for each origin. assertEquals( TEST_MULTIPLE_SITE_GROUP.origins.length, browserProxy.getCallCount('setOriginPermissions')); assertEquals(testElement.$.allSitesList.items!.length, 0); }); test( 'reset settings via overflow menu (one has data and cookies)', function() { // Test when one origin has data and cookies. // Clone this object to avoid propagating changes made in this test. const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = true; siteGroup.origins[0].usage = 100; siteGroup.origins[0].numCookies = 2; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); resetSettingsViaOverflowMenu('action-button'); assertEquals(testElement.$.allSitesList.items!.length, 1); assertEquals(1, testElement.$.allSitesList.items![0].origins.length); assertFalse(testElement.$.allSitesList.items![0] .origins[0] .hasPermissionSettings); assertEquals( testElement.$.allSitesList.items![0].origins[0].usage, 100); assertEquals( testElement.$.allSitesList.items![0].origins[0].numCookies, 2); }); test('reset settings via overflow menu (etld+1 has cookies)', function() { // Test when none of origin have data or cookies, but etld+1 has // cookies. In this case, a placeholder origin will be created with the // Etld+1 cookies number. Clone this object to avoid propagating changes // made in this test. const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.numCookies = 5; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); resetSettingsViaOverflowMenu('action-button'); assertEquals(testElement.$.allSitesList.items!.length, 1); assertEquals(1, testElement.$.allSitesList.items![0].origins.length); assertFalse( testElement.$.allSitesList.items![0].origins[0].hasPermissionSettings); assertEquals(testElement.$.allSitesList.items![0].origins[0].usage, 0); assertEquals(testElement.$.allSitesList.items![0].origins[0].numCookies, 5); }); function clearDataViaOverflowMenu(buttonType: string) { assertTrue( buttonType === 'cancel-button' || buttonType === 'action-button'); flush(); const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(1, siteEntries.length); const overflowMenuButton = siteEntries[0]!.$$<HTMLElement>('#overflowMenuButton')!; assertFalse( overflowMenuButton.closest<HTMLElement>('.row-aligned')!.hidden); // Open the clear data dialog. const overflowMenu = testElement.$.menu.get(); const menuItems = overflowMenu.querySelectorAll<HTMLElement>('.dropdown-item'); // Test clicking on the overflow menu button opens the menu. assertFalse(overflowMenu.open); overflowMenuButton.click(); assertTrue(overflowMenu.open); // Open the clear data dialog and tap the |buttonType| button. assertFalse(testElement.$.confirmClearData.get().open); menuItems[1]!.click(); assertTrue(testElement.$.confirmClearData.get().open); const actionButtonList = testElement.$.confirmClearData.get().querySelectorAll<HTMLElement>( `.${buttonType}`); assertEquals(1, actionButtonList.length); actionButtonList[0]!.click(); // Check the dialog and overflow menu are now both closed. assertFalse(testElement.$.confirmClearData.get().open); assertFalse(overflowMenu.open); } test('cancelling the confirm dialog on clear data works', function() { testElement.siteGroupMap.set( TEST_MULTIPLE_SITE_GROUP.etldPlus1, JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP))); testElement.forceListUpdateForTesting(); clearDataViaOverflowMenu('cancel-button'); }); test('clear data via overflow menu (no permission and no data)', function() { // Test when all origins has no permission settings and no data. // Clone this object to avoid propagating changes made in this test. testElement.siteGroupMap.set( TEST_MULTIPLE_SITE_GROUP.etldPlus1, JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP))); testElement.forceListUpdateForTesting(); clearDataViaOverflowMenu('action-button'); // Ensure a call was made to clearEtldPlus1DataAndCookies. assertEquals(1, browserProxy.getCallCount('clearEtldPlus1DataAndCookies')); assertEquals(testElement.$.allSitesList.items!.length, 0); }); test('clear data via overflow menu (one origin has permission)', function() { // Test when there is one origin has permissions settings. // Clone this object to avoid propagating changes made in this test. const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = true; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); clearDataViaOverflowMenu('action-button'); assertEquals(testElement.$.allSitesList.items!.length, 1); assertEquals(testElement.$.allSitesList.items![0].origins.length, 1); }); test( 'clear data via overflow menu (one origin has permission and data)', function() { // Test when one origin has permission settings and data, clear data // only clears the data and cookies. const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = true; siteGroup.origins[0].usage = 100; siteGroup.origins[0].numCookies = 3; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); clearDataViaOverflowMenu('action-button'); assertEquals(testElement.$.allSitesList.items!.length, 1); assertEquals(testElement.$.allSitesList.items![0].origins.length, 1); assertTrue(testElement.$.allSitesList.items![0] .origins[0] .hasPermissionSettings); assertEquals(testElement.$.allSitesList.items![0].origins[0].usage, 0); assertEquals( testElement.$.allSitesList.items![0].origins[0].numCookies, 0); }); function clearDataViaClearAllButton(buttonType: string) { assertTrue( buttonType === 'cancel-button' || buttonType === 'action-button'); flush(); const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertTrue(siteEntries.length >= 1); const clearAllButton = testElement.$.clearAllButton.querySelector('cr-button')!; const confirmClearAllData = testElement.$.confirmClearAllData.get(); // Open the clear all data dialog. // Test clicking on the clear all button opens the clear all dialog. assertFalse(confirmClearAllData.open); clearAllButton.click(); assertTrue(confirmClearAllData.open); // Open the clear data dialog and tap the |buttonType| button. const actionButtonList = testElement.$.confirmClearAllData.get().querySelectorAll<HTMLElement>( `.${buttonType}`); assertEquals(1, actionButtonList.length); actionButtonList[0]!.click(); // Check the dialog and overflow menu are now both closed. assertFalse(confirmClearAllData.open); } test('cancelling the confirm dialog on clear all data works', function() { testElement.siteGroupMap.set( TEST_MULTIPLE_SITE_GROUP.etldPlus1, JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP))); testElement.forceListUpdateForTesting(); clearDataViaClearAllButton('cancel-button'); }); test('clearing data via clear all dialog', function() { // Test when all origins has no permission settings and no data. // Clone this object to avoid propagating changes made in this test. testElement.siteGroupMap.set( TEST_MULTIPLE_SITE_GROUP.etldPlus1, JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP))); const googleSiteGroup = createSiteGroup('google.com', [ 'https://www.google.com', 'https://docs.google.com', 'https://mail.google.com', ]); testElement.siteGroupMap.set(googleSiteGroup.etldPlus1, googleSiteGroup); testElement.forceListUpdateForTesting(); clearDataViaClearAllButton('action-button'); // Ensure a call was made to clearEtldPlus1DataAndCookies. assertEquals(2, browserProxy.getCallCount('clearEtldPlus1DataAndCookies')); assertEquals(testElement.$.allSitesList.items!.length, 0); }); test( 'clear data via clear all button (one origin has permission)', function() { // Test when there is one origin has permissions settings. // Clone this object to avoid propagating changes made in this test. const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = true; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); const googleSiteGroup = createSiteGroup('google.com', [ 'https://www.google.com', 'https://docs.google.com', 'https://mail.google.com', ]); testElement.siteGroupMap.set( googleSiteGroup.etldPlus1, googleSiteGroup); testElement.forceListUpdateForTesting(); assertEquals(testElement.$.allSitesList.items!.length, 2); assertEquals( testElement.$.allSitesList.items![0].origins.length, siteGroup.origins.length); clearDataViaClearAllButton('action-button'); assertEquals(testElement.$.allSitesList.items!.length, 1); assertEquals(testElement.$.allSitesList.items![0].origins.length, 1); }); /** * Opens the overflow menu for a specific origin within a SiteEntry, clicks * on the clear data option, and then clicks on either the cancel or clear * data button. * @param buttonType The button to click on the clear data dialog * @param siteGroup The SiteGroup for which the origin to clear * belongs to. * @param originIndex The index of the origin to clear in the * SiteGroup.origins array. */ function clearOriginDataViaOverflowMenu( buttonType: string, siteGroup: SiteGroup, originIndex: number) { assertTrue( buttonType === 'cancel-button' || buttonType === 'action-button'); flush(); const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(1, siteEntries.length); const expandButton = siteEntries[0]!.$.expandIcon; // Open the overflow menu. const overflowMenu = testElement.$.menu.get(); assertFalse(overflowMenu.open); testElement.dispatchEvent(new CustomEvent('open-menu', { bubbles: true, composed: true, detail: { target: expandButton, index: 0, item: siteGroup, origin: siteGroup.origins[originIndex]!.origin, actionScope: 'origin', } })); assertTrue(overflowMenu.open); const menuItems = overflowMenu.querySelectorAll<HTMLElement>('.dropdown-item'); // Open the clear data dialog and tap the |buttonType| button. assertFalse(testElement.$.confirmClearData.get().open); menuItems[1]!.click(); assertTrue(testElement.$.confirmClearData.get().open); const actionButtonList = testElement.$.confirmClearData.get().querySelectorAll<HTMLElement>( `.${buttonType}`); assertEquals(1, actionButtonList.length); actionButtonList[0]!.click(); // Check the dialog and overflow menu are now both closed. assertFalse(testElement.$.confirmClearData.get().open); assertFalse(overflowMenu.open); } test('cancelling the confirm dialog on clear data works', function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); testElement.siteGroupMap.set(siteGroup.etldPlus1, siteGroup); testElement.forceListUpdateForTesting(); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(3, testElement.$.allSitesList.items![0].origins.length); clearOriginDataViaOverflowMenu('cancel-button', siteGroup, 0); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(3, testElement.$.allSitesList.items![0].origins.length); }); test('clear single origin data via overflow menu', function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = false; siteGroup.origins[0].usage = 100; siteGroup.origins[0].numCookies = 3; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); clearOriginDataViaOverflowMenu('action-button', siteGroup, 0); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(2, testElement.$.allSitesList.items![0].origins.length); }); test( 'clear single origin data via overflow menu (has permissions)', function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = true; siteGroup.origins[0].usage = 100; siteGroup.origins[0].numCookies = 3; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); clearOriginDataViaOverflowMenu('action-button', siteGroup, 0); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(3, testElement.$.allSitesList.items![0].origins.length); const updatedOrigin = testElement.$.allSitesList.items![0].origins[0]; assertTrue(updatedOrigin.hasPermissionSettings); assertEquals(0, updatedOrigin.usage); assertEquals(0, updatedOrigin.numCookies); }); /** * Clicks on the overflow menu for a specific origin, hits the reset * permissions button on the overflow menu, and takes the specified action on * the confirmation dialog. * @param buttonType The button to click on the confirmation dialog. * @param siteGroup The SiteGroup to which the origin to reset * belongs to. * @param originIndex The index in the SiteGroup.origins array of the * origin to reset permissions for. */ function resetOriginSettingsViaOverflowMenu( buttonType: string, siteGroup: SiteGroup, originIndex: number) { assertTrue( buttonType === 'cancel-button' || buttonType === 'action-button'); flush(); const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(1, siteEntries.length); const expandButton = siteEntries[0]!.$.expandIcon; // Open the overflow menu. const overflowMenu = testElement.$.menu.get(); assertFalse(overflowMenu.open); testElement.dispatchEvent(new CustomEvent('open-menu', { bubbles: true, composed: true, detail: { target: expandButton, index: 0, item: siteGroup, origin: siteGroup.origins[originIndex]!.origin, actionScope: 'origin', } })); assertTrue(overflowMenu.open); const menuItems = overflowMenu.querySelectorAll<HTMLElement>('.dropdown-item'); // Open the clear data dialog and tap the |buttonType| button. assertFalse(testElement.$.confirmResetSettings.get().open); menuItems[0]!.click(); assertTrue(testElement.$.confirmResetSettings.get().open); const actionButtonList = testElement.$.confirmResetSettings.get().querySelectorAll<HTMLElement>( `.${buttonType}`); assertEquals(1, actionButtonList.length); actionButtonList[0]!.click(); // Check the dialog and overflow menu are now both closed. assertFalse(testElement.$.confirmResetSettings.get().open); assertFalse(overflowMenu.open); } test('cancelling the confirm dialog on resetting settings works', function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); testElement.siteGroupMap.set(siteGroup.etldPlus1, siteGroup); testElement.forceListUpdateForTesting(); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(3, testElement.$.allSitesList.items![0].origins.length); resetOriginSettingsViaOverflowMenu('cancel-button', siteGroup, 0); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(3, testElement.$.allSitesList.items![0].origins.length); }); test( 'clear single origin permissions via overflow menu (no usage/cookies)', function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = true; siteGroup.origins[0].usage = 0; siteGroup.origins[0].numCookies = 0; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); resetOriginSettingsViaOverflowMenu('action-button', siteGroup, 0); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(2, testElement.$.allSitesList.items![0].origins.length); }); test( 'clear single origin permissions via overflow menu (has usage/cookies)', function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = true; siteGroup.origins[0].usage = 100; siteGroup.origins[0].numCookies = 10; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); resetOriginSettingsViaOverflowMenu('action-button', siteGroup, 0); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(3, testElement.$.allSitesList.items![0].origins.length); }); }); suite('AllSites_EnabledConsolidatedControls', function() { /** * An example eTLD+1 Object with multiple origins grouped under it. */ const TEST_MULTIPLE_SITE_GROUP = createSiteGroup('example.com', [ 'http://subdomain.example.com/', 'https://www.example.com/', 'https://login.example.com/', ]); /** * An example eTLD+1 Object with a single origin grouped under it. */ const TEST_SINGLE_SITE_GROUP = createSiteGroup('example.com', [ 'https://single.example.com', ]); let testElement: AllSitesElement; /** * The mock proxy object to use during test. */ let browserProxy: TestSiteSettingsPrefsBrowserProxy; /** * The mock local data proxy object to use during test. */ let localDataBrowserProxy: TestLocalDataBrowserProxy; suiteSetup(function() { loadTimeData.overrideValues({ consolidatedSiteStorageControlsEnabled: true, }); }); // Initialize a site-list before each test. setup(async function() { document.body.innerHTML = ''; browserProxy = new TestSiteSettingsPrefsBrowserProxy(); localDataBrowserProxy = new TestLocalDataBrowserProxy(); SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy); LocalDataBrowserProxyImpl.setInstance(localDataBrowserProxy); testElement = document.createElement('all-sites'); assertTrue(!!testElement); document.body.appendChild(testElement); }); function removeFirstOrigin() { const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(1, siteEntries.length); const originList = siteEntries[0]!.$.originList.get(); flush(); const originEntries = originList.querySelectorAll('.hr'); assertEquals(3, originEntries.length); originEntries[0]!.querySelector<HTMLElement>( '#removeOriginButton')!.click(); } function removeFirstSiteGroup() { const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); assertEquals(1, siteEntries.length); siteEntries[0]!.$$<HTMLElement>('#removeSiteButton')!.click(); } function confirmDialog() { assertTrue(testElement.$.confirmRemoveSite.get().open); testElement.$.confirmRemoveSite.get() .querySelector<HTMLElement>('.action-button')!.click(); } function cancelDialog() { assertTrue(testElement.$.confirmRemoveSite.get().open); testElement.$.confirmRemoveSite.get() .querySelector<HTMLElement>('.cancel-button')!.click(); } function getString(messageId: string): string { return testElement.i18n(messageId); } function getSubstitutedString(messageId: string, substitute: string): string { return loadTimeData.substituteString( testElement.i18n(messageId), substitute); } test('remove site group', function() { testElement.siteGroupMap.set( TEST_MULTIPLE_SITE_GROUP.etldPlus1, JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP))); testElement.forceListUpdateForTesting(); flush(); removeFirstSiteGroup(); confirmDialog(); assertEquals( TEST_MULTIPLE_SITE_GROUP.origins.length, browserProxy.getCallCount('setOriginPermissions')); assertEquals(0, testElement.$.allSitesList.items!.length); assertEquals(1, browserProxy.getCallCount('clearEtldPlus1DataAndCookies')); }); test('remove origin', async function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].numCookies = 1; siteGroup.origins[1].numCookies = 2; siteGroup.origins[2].numCookies = 3; siteGroup.numCookies = 6; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstOrigin(); confirmDialog(); assertEquals( siteGroup.origins[0].origin, await browserProxy.whenCalled( 'clearUnpartitionedOriginDataAndCookies')); const [origin, types, setting] = await browserProxy.whenCalled('setOriginPermissions'); assertEquals(origin, siteGroup.origins[0].origin); assertEquals(types, null); // Null affects all content types. assertEquals(setting, ContentSetting.DEFAULT); assertEquals( 1, browserProxy.getCallCount('clearUnpartitionedOriginDataAndCookies')); assertEquals(1, browserProxy.getCallCount('setOriginPermissions')); assertEquals(5, testElement.$.allSitesList.items![0].numCookies); }); test('remove partitioned origin', async function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].isPartitioned = true; siteGroup.origins[0].numCookies = 1; siteGroup.origins[1].numCookies = 2; siteGroup.origins[2].numCookies = 3; siteGroup.numCookies = 6; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); flush(); // Remove the the partitioned entry, which will have been ordered to the // bottom of the displayed origins. const siteEntries = testElement.$.listContainer.querySelectorAll('site-entry'); const originList = siteEntries[0]!.$.originList.get(); flush(); const originEntries = originList.querySelectorAll('.hr'); assertEquals(3, originEntries.length); originEntries[2]!.querySelector<HTMLElement>( '#removeOriginButton')!.click(); confirmDialog(); const [origin, etldPlus1] = await browserProxy.whenCalled('clearPartitionedOriginDataAndCookies'); assertEquals(siteGroup.origins[0].origin, origin); assertEquals(siteGroup.etldPlus1, etldPlus1); assertEquals( 1, browserProxy.getCallCount('clearPartitionedOriginDataAndCookies')); assertEquals(0, browserProxy.getCallCount('setOriginPermissions')); assertEquals(5, testElement.$.allSitesList.items![0].numCookies); }); test('cancel remove site group', function() { testElement.siteGroupMap.set( TEST_MULTIPLE_SITE_GROUP.etldPlus1, JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP))); testElement.forceListUpdateForTesting(); flush(); removeFirstSiteGroup(); cancelDialog(); assertEquals(0, browserProxy.getCallCount('setOriginPermissions')); assertEquals(1, testElement.$.allSitesList.items!.length); assertEquals(0, browserProxy.getCallCount('clearEtldPlus1DataAndCookies')); }); test('cancel remove origin', function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].numCookies = 1; siteGroup.origins[1].numCookies = 2; siteGroup.origins[2].numCookies = 3; siteGroup.numCookies = 6; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstOrigin(); cancelDialog(); assertEquals( 0, browserProxy.getCallCount('clearUnpartitionedOriginDataAndCookies')); assertEquals(0, browserProxy.getCallCount('setOriginPermissions')); assertEquals(6, testElement.$.allSitesList.items![0].numCookies); }); test('permissions bullet point visbility', function() { const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); siteGroup.origins[0].hasPermissionSettings = true; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstOrigin(); assertTrue(testElement.$.confirmRemoveSite.get().open); assertTrue(isChildVisible(testElement, '#permissionsBulletPoint')); cancelDialog(); removeFirstSiteGroup(); assertTrue(testElement.$.confirmRemoveSite.get().open); assertTrue(isChildVisible(testElement, '#permissionsBulletPoint')); cancelDialog(); siteGroup.origins[0].hasPermissionSettings = false; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstOrigin(); assertTrue(testElement.$.confirmRemoveSite.get().open); assertFalse(isChildVisible(testElement, '#permissionsBulletPoint')); cancelDialog(); removeFirstSiteGroup(); assertTrue(testElement.$.confirmRemoveSite.get().open); assertFalse(isChildVisible(testElement, '#permissionsBulletPoint')); cancelDialog(); }); test('dynamic strings', async function() { // Single origin, no apps. const siteGroup = JSON.parse(JSON.stringify(TEST_MULTIPLE_SITE_GROUP)); testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstOrigin(); assertEquals( getSubstitutedString( 'siteSettingsRemoveSiteOriginDialogTitle', 'subdomain.example.com'), testElement.shadowRoot!.querySelector<HTMLElement>( '#removeSiteTitle')!.innerText); assertEquals( getString('siteSettingsRemoveSiteOriginLogout'), testElement.shadowRoot! .querySelector<HTMLElement>('#logoutBulletPoint')!.innerText); cancelDialog(); // Site group, multiple origins, no apps. removeFirstSiteGroup(); assertEquals( getSubstitutedString( 'siteSettingsRemoveSiteGroupDialogTitle', 'example.com'), testElement.shadowRoot!.querySelector<HTMLElement>( '#removeSiteTitle')!.innerText); assertEquals( getString('siteSettingsRemoveSiteGroupLogout'), testElement.shadowRoot! .querySelector<HTMLElement>('#logoutBulletPoint')!.innerText); cancelDialog(); // Single origin with app. siteGroup.origins[0].isInstalled = true; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstOrigin(); assertEquals( getSubstitutedString( 'siteSettingsRemoveSiteOriginAppDialogTitle', 'subdomain.example.com'), testElement.shadowRoot!.querySelector<HTMLElement>( '#removeSiteTitle')!.innerText); assertEquals( getString('siteSettingsRemoveSiteOriginLogout'), testElement.shadowRoot! .querySelector<HTMLElement>('#logoutBulletPoint')!.innerText); cancelDialog(); // Site group, multiple origins, with single app. removeFirstSiteGroup(); assertEquals( getSubstitutedString( 'siteSettingsRemoveSiteGroupAppDialogTitle', 'example.com'), testElement.shadowRoot!.querySelector<HTMLElement>( '#removeSiteTitle')!.innerText); assertEquals( getString('siteSettingsRemoveSiteGroupLogout'), testElement.shadowRoot! .querySelector<HTMLElement>('#logoutBulletPoint')!.innerText); cancelDialog(); // Site group, multiple sites, multiple apps. siteGroup.origins[1].isInstalled = true; testElement.siteGroupMap.set( siteGroup.etldPlus1, JSON.parse(JSON.stringify(siteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstSiteGroup(); assertEquals( getSubstitutedString( 'siteSettingsRemoveSiteGroupAppPluralDialogTitle', 'example.com'), testElement.shadowRoot!.querySelector<HTMLElement>( '#removeSiteTitle')!.innerText); assertEquals( getString('siteSettingsRemoveSiteGroupLogout'), testElement.shadowRoot! .querySelector<HTMLElement>('#logoutBulletPoint')!.innerText); cancelDialog(); // Site group, single origin, no app. const singleOriginSiteGroup = JSON.parse(JSON.stringify(TEST_SINGLE_SITE_GROUP)); testElement.siteGroupMap.set( singleOriginSiteGroup.etldPlus1, JSON.parse(JSON.stringify(singleOriginSiteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstSiteGroup(); assertEquals( getSubstitutedString( 'siteSettingsRemoveSiteOriginDialogTitle', 'single.example.com'), testElement.shadowRoot!.querySelector<HTMLElement>( '#removeSiteTitle')!.innerText); assertEquals( getString('siteSettingsRemoveSiteOriginLogout'), testElement.shadowRoot! .querySelector<HTMLElement>('#logoutBulletPoint')!.innerText); cancelDialog(); // Site group, single origin, one app. singleOriginSiteGroup.origins[0].isInstalled = true; testElement.siteGroupMap.set( singleOriginSiteGroup.etldPlus1, JSON.parse(JSON.stringify(singleOriginSiteGroup))); testElement.forceListUpdateForTesting(); flush(); removeFirstSiteGroup(); assertEquals( getSubstitutedString( 'siteSettingsRemoveSiteOriginAppDialogTitle', 'single.example.com'), testElement.shadowRoot!.querySelector<HTMLElement>( '#removeSiteTitle')!.innerText); assertEquals( getString('siteSettingsRemoveSiteOriginLogout'), testElement.shadowRoot! .querySelector<HTMLElement>('#logoutBulletPoint')!.innerText); }); });
the_stack
import { ComponentPMT, MediaType, ModuleListEntry, ProgramInfoMessage, ResponseMessage } from "../server/ws_api"; import { Indicator, IP } from "./bml_browser"; type Module = { moduleId: number, files: ReadonlyMap<string | null, CachedFile>, version: number, dataEventId: number, }; type Component = { componentId: number, modules: Map<number, Module>, }; export type CachedComponent = { componentId: number, modules: Map<number, CachedModule>, dataEventId: number, }; export type CachedModule = { moduleId: number, files: ReadonlyMap<string | null, CachedFile>, version: number, dataEventId: number, }; export type CachedFileMetadata = { blobUrl: string, width?: number, height?: number, }; export type CachedFile = { contentLocation: string | null, contentType: MediaType, data: Uint8Array, blobUrl: Map<any, CachedFileMetadata>, }; export type RemoteCachedFile = CachedFile & { cacheControl?: string, }; export type LockedComponent = { componentId: number, modules: Map<number, LockedModule>, }; export type LockedModule = { moduleId: number, files: ReadonlyMap<string | null, CachedFile>, lockedBy: "lockModuleOnMemory" | "lockModuleOnMemoryEx", version: number, dataEventId: number, }; export type DownloadComponentInfo = { componentId: number, modules: ReadonlyMap<number, ModuleListEntry>, dataEventId: number, returnToEntryFlag?: boolean, }; // `${componentId}/${moduleId}`がダウンロードされたらコールバックを実行する type ComponentRequest = { moduleRequests: Map<number, ModuleRequest[]> }; type ModuleRequest = { filename: string | null, resolve: (resolveValue: CachedFile | null) => void, }; type RemoteResourceRequest = { url: string, resolve: (resolveValue: RemoteCachedFile | null) => void, }; function moduleAndComponentToString(componentId: number, moduleId: number) { return `${componentId.toString(16).padStart(2, "0")}/${moduleId.toString(16).padStart(4, "0")}`; } interface ResourcesEventMap { "dataeventchanged": CustomEvent<{ prevComponent: DownloadComponentInfo, component: DownloadComponentInfo, returnToEntryFlag?: boolean }>; // DDB "moduleupdated": CustomEvent<{ componentId: number, moduleId: number, version: number, dataEventId: number }>; // DII "componentupdated": CustomEvent<{ component: DownloadComponentInfo }>; // PMT "pmtupdated": CustomEvent<{ prevComponents: Map<number, ComponentPMT>, components: Map<number, ComponentPMT> }>; } interface CustomEventTarget<M> { addEventListener<K extends keyof M>(type: K, callback: EventListenerOrEventListenerObject, options?: AddEventListenerOptions | boolean): void; dispatchEvent<K extends keyof M>(event: M[K]): boolean; removeEventListener<K extends keyof M>(type: K, callback: EventListenerOrEventListenerObject, options?: EventListenerOptions | boolean): void; } export type ResourcesEventTarget = CustomEventTarget<ResourcesEventMap>; // ブラウザのキャッシュとは別 class CacheMap { private readonly cachedRemoteResources: Map<string, RemoteCachedFile | null> = new Map(); private readonly maxEntryCount: number; private readonly maxSizeBytes: number; private sizeBytes = 0; public constructor(maxEntryCount: number, maxSizeBytes: number) { this.maxEntryCount = maxEntryCount; this.maxSizeBytes = maxSizeBytes; } public get(url: string): RemoteCachedFile | null | undefined { return this.cachedRemoteResources.get(url); } public set(url: string, file: RemoteCachedFile | null): void { this.delete(url); if ((file?.data.length ?? 0) > this.maxSizeBytes) { return; } this.cachedRemoteResources.set(url, file); this.sizeBytes += file?.data.length ?? 0; // 挿入順に列挙される // 列挙中に削除しても安全らしい if (this.sizeBytes > this.maxSizeBytes || this.cachedRemoteResources.size > this.maxEntryCount) { for (const [key] of this.cachedRemoteResources.keys()) { if (this.sizeBytes > this.maxSizeBytes || this.cachedRemoteResources.size > this.maxEntryCount) { this.delete(key); } else { break; } } } } public delete(url: string): boolean { const entry = this.cachedRemoteResources.get(url); if (entry != null) { this.sizeBytes -= entry.data.length; for (const [_, blob] of entry.blobUrl) { URL.revokeObjectURL(blob.blobUrl); } return this.cachedRemoteResources.delete(url); } else { return false; } } } export class Resources { private readonly indicator?: Indicator; private readonly eventTarget: ResourcesEventTarget = new EventTarget(); private readonly ip: IP; // ブラウザのキャッシュとは別に用意 どのみちblob urlの寿命の管理の役目もある // とりあえず10 MiB, 400ファイル private readonly cachedRemoteResources: CacheMap = new CacheMap(400, 1024 * 1024 * 10); private readonly remoteResourceRequests: Map<string, RemoteResourceRequest[]> = new Map(); public constructor(indicator: Indicator | undefined, ip: IP) { this.indicator = indicator; this.ip = ip; } private _activeDocument: null | string = null; private _currentComponentId: null | number = null; private _currentModuleId: null | number = null; public set activeDocument(doc: string | null) { const { componentId, moduleId } = this.parseURLEx(doc); this._activeDocument = doc; this._currentComponentId = componentId; this._currentModuleId = moduleId; if (!doc?.startsWith("http://") && !doc?.startsWith("https://")) { this.baseURIDirectory = null; } } public get activeDocument(): string | null { return this._activeDocument; } public get currentComponentId(): number | null { return this._currentComponentId; } public get currentModuleId(): number | null { return this._currentModuleId; } public get currentDataEventId(): number | null { return this._currentComponentId && (this.cachedComponents.get(this._currentComponentId)?.dataEventId ?? null); } private cachedComponents = new Map<number, CachedComponent>(); private downloadComponents = new Map<number, DownloadComponentInfo>(); public getCachedFileBlobUrl(file: CachedFile, key?: any): string { let b = file.blobUrl.get(key)?.blobUrl; if (b != null) { return b; } b = URL.createObjectURL(new Blob([file.data], { type: `${file.contentType.type}/${file.contentType.originalSubtype}` })); file.blobUrl.set(key, { blobUrl: b }); return b; } private lockedComponents = new Map<number, LockedComponent>(); // component id => PMT private pmtComponents = new Map<number, ComponentPMT>(); private pmtRetrieved = false; public getCachedModule(componentId: number, moduleId: number): CachedModule | undefined { const cachedComponent = this.cachedComponents.get(componentId); if (cachedComponent == null) { return undefined; } return cachedComponent.modules.get(moduleId); } public getPMTComponent(componentId: number): ComponentPMT | undefined { const pmtComponent = this.pmtComponents.get(componentId); return pmtComponent; } public lockCachedModule(componentId: number, moduleId: number, lockedBy: "lockModuleOnMemory" | "lockModuleOnMemoryEx"): boolean { const cachedModule = this.getCachedModule(componentId, moduleId); if (cachedModule == null) { return false; } const cachedComponent = this.cachedComponents.get(componentId)!; const lockedComponent = this.lockedComponents.get(componentId) ?? { componentId, modules: new Map<number, LockedModule>(), dataEventId: cachedComponent.dataEventId, }; lockedComponent.modules.set(moduleId, { files: cachedModule.files, lockedBy, moduleId: cachedModule.moduleId, version: cachedModule.version, dataEventId: cachedModule.dataEventId }); this.lockedComponents.set(componentId, lockedComponent); return true; } public isModuleLocked(componentId: number, moduleId: number): boolean { return this.lockedComponents.get(componentId)?.modules?.has(moduleId) ?? false; } public getModuleLockedBy(componentId: number, moduleId: number): "lockModuleOnMemory" | "lockModuleOnMemoryEx" | undefined { return this.lockedComponents.get(componentId)?.modules?.get(moduleId)?.lockedBy; } public unlockModules(lockedBy?: "lockModuleOnMemory" | "lockModuleOnMemoryEx") { if (lockedBy == null) { this.lockedComponents.clear(); } else { for (const component of this.lockedComponents.values()) { for (const mod of [...component.modules.values()]) { if (mod.lockedBy === lockedBy) { component.modules.delete(mod.moduleId); } } } } } public unlockModule(componentId: number, moduleId: number, lockedBy?: "lockModuleOnMemory" | "lockModuleOnMemoryEx"): boolean { const m = this.lockedComponents.get(componentId); if (m != null) { const lockedModule = m.modules.get(moduleId); if (lockedModule == null) { return false; } if (lockedModule.lockedBy !== lockedBy) { return false; } return m.modules.delete(moduleId); } return false; } public componentExistsInDownloadInfo(componentId: number): boolean { return this.downloadComponents.has(componentId); } public getDownloadComponentInfo(componentId: number): DownloadComponentInfo | undefined { return this.downloadComponents.get(componentId); } public moduleExistsInDownloadInfo(componentId: number, moduleId: number): boolean { const dcomp = this.downloadComponents.get(componentId); if (!dcomp) { return false; } return dcomp.modules.has(moduleId); } private currentProgramInfo: ProgramInfoMessage | null = null; // STD-B24 第二分冊(1/2) 第二編 9.2.1.2 public get dataCarouselURI() { let url = `arib-dc://${this.originalNetworkId?.toString(16)?.padStart(4, "0") ?? -1}.${this.transportStreamId?.toString(16)?.padStart(4, "0") ?? -1}.${this.serviceId?.toString(16)?.padStart(4, "0") ?? -1}`; if (this.contentId != null) { url += ";" + this.contentId.toString(16)?.padStart(8, "0"); } if (this.eventId != null) { url += "." + this.eventId.toString(16)?.padStart(4, "0"); } return url; } // STD-B24 第二分冊(1/2) 第二編 9.2.5 public get serviceURI() { return `arib://${this.originalNetworkId?.toString(16)?.padStart(4, "0") ?? -1}.${this.transportStreamId?.toString(16)?.padStart(4, "0") ?? -1}.${this.serviceId?.toString(16)?.padStart(4, "0") ?? -1}`; } // STD-B24 第二分冊(1/2) 第二編 9.2.6 public get eventURI() { return `arib://${this.originalNetworkId?.toString(16)?.padStart(4, "0") ?? -1}.${this.transportStreamId?.toString(16)?.padStart(4, "0") ?? -1}.${this.serviceId?.toString(16)?.padStart(4, "0") ?? -1}.${this.eventId?.toString(16)?.padStart(4, "0") ?? -1}`; } public get eventName(): string | null { return this.currentProgramInfo?.eventName ?? null; } public get eventId(): number | null { return this.currentProgramInfo?.eventId ?? null; } // not implemented public get contentId(): number | null { return null; } public get startTimeUnixMillis(): number | null { return this.currentProgramInfo?.startTimeUnixMillis ?? null; } public get durationSeconds(): number | null { return this.currentProgramInfo?.durationSeconds ?? null; } public get serviceId(): number | null { return this.currentProgramInfo?.serviceId ?? null; } public get originalNetworkId(): number | null { return this.currentProgramInfo?.originalNetworkId ?? null; } public get transportStreamId(): number | null { return this.currentProgramInfo?.transportStreamId ?? null; } private currentTimeNearestPCRBase?: number; private _currentTimeUnixMillis?: number; private maxTOTIntervalMillis = 30 * 1000; // STD-B10的には30秒に1回は送る必要がある ただし実際の運用は5秒間隔で送られる public get currentTimeUnixMillis(): number | null { if (this._currentTimeUnixMillis != null && this.nearestPCRBase != null && this.currentTimeNearestPCRBase != null) { const pcr = this.nearestPCRBase - this.currentTimeNearestPCRBase; if (pcr > 0) { return this._currentTimeUnixMillis + Math.min(this.maxTOTIntervalMillis, Math.floor(pcr / 90)); } } return this._currentTimeUnixMillis ?? null; } nearestPCRBase?: number; public onMessage(msg: ResponseMessage) { if (msg.type === "moduleDownloaded") { const cachedComponent = this.cachedComponents.get(msg.componentId) ?? { componentId: msg.componentId, modules: new Map<number, CachedModule>(), dataEventId: msg.dataEventId, }; if (cachedComponent.dataEventId !== msg.dataEventId) { return; } const prevModule = cachedComponent.modules.get(msg.moduleId); if (prevModule != null && prevModule.version === msg.version && prevModule.dataEventId === msg.dataEventId) { return; } const cachedModule: CachedModule = { moduleId: msg.moduleId, files: new Map(msg.files.map(file => ([file.contentLocation?.toLowerCase() ?? null, { contentLocation: file.contentLocation, contentType: file.contentType, data: Uint8Array.from(window.atob(file.dataBase64), c => c.charCodeAt(0)), blobUrl: new Map(), } as CachedFile]))), version: msg.version, dataEventId: msg.dataEventId, }; cachedComponent.modules.set(msg.moduleId, cachedModule); this.cachedComponents.set(msg.componentId, cachedComponent); // OnModuleUpdated const str = moduleAndComponentToString(msg.componentId, msg.moduleId); const creq = this.componentRequests.get(msg.componentId); const callbacks = creq?.moduleRequests?.get(msg.moduleId); if (creq != null && callbacks != null) { creq.moduleRequests.delete(msg.moduleId); for (const cb of callbacks) { if (cb.filename == null) { console.warn("async fetch done", str); cb.resolve(null); } else { const file = cachedModule.files.get(cb.filename); console.warn("async fetch done", str, cb.filename); cb.resolve(file ?? null); } } this.setReceivingStatus(); } this.eventTarget.dispatchEvent<"moduleupdated">(new CustomEvent("moduleupdated", { detail: { componentId: msg.componentId, dataEventId: msg.dataEventId, moduleId: msg.moduleId, version: msg.version } })); } else if (msg.type === "moduleListUpdated") { const component: DownloadComponentInfo = { componentId: msg.componentId, modules: new Map(msg.modules.map(x => [x.id, x])), dataEventId: msg.dataEventId, returnToEntryFlag: msg.returnToEntryFlag, }; const prevComponent = this.getDownloadComponentInfo(msg.componentId); this.downloadComponents.set(msg.componentId, component); const creqs = this.componentRequests.get(msg.componentId); const cachedComponent = this.cachedComponents.get(msg.componentId); if (cachedComponent != null) { for (const cachedModule of cachedComponent.modules.values()) { const newEntry = component.modules.get(cachedModule.moduleId); if (newEntry == null || newEntry.version !== cachedModule.version) { cachedComponent.modules.delete(cachedModule.moduleId); } } } if (creqs) { for (const [moduleId, mreqs] of creqs.moduleRequests) { if (!component.modules.has(moduleId)) { // DIIに存在しない for (const mreq of mreqs) { console.warn("async fetch done (failed)", moduleAndComponentToString(msg.componentId, moduleId)); mreq.resolve(null); } mreqs.length = 0; } } this.setReceivingStatus(); } this.eventTarget.dispatchEvent<"componentupdated">(new CustomEvent("componentupdated", { detail: { component } })); // DIIのdata_event_idが更新された if (prevComponent != null && prevComponent.dataEventId !== component.dataEventId) { this.cachedComponents.delete(msg.componentId); this.eventTarget.dispatchEvent<"dataeventchanged">(new CustomEvent("dataeventchanged", { detail: { prevComponent, component, returnToEntryFlag: msg.returnToEntryFlag } })); } } else if (msg.type === "pmt") { this.pmtRetrieved = true; const prevComponents = this.pmtComponents; // 0x0d: データカルーセル this.pmtComponents = new Map(msg.components.filter(x => x.streamType === 0x0d).map(x => [x.componentId, x])); for (const [componentId, creqs] of this.componentRequests) { if (this.pmtComponents.has(componentId)) { continue; } for (const [moduleId, mreqs] of creqs.moduleRequests) { // PMTに存在しない for (const mreq of mreqs) { console.warn("async fetch done (failed)", moduleAndComponentToString(componentId, moduleId)); mreq.resolve(null); } mreqs.length = 0; } } this.setReceivingStatus(); this.eventTarget.dispatchEvent<"pmtupdated">(new CustomEvent("pmtupdated", { detail: { components: this.pmtComponents, prevComponents } })); } else if (msg.type === "programInfo") { this.currentProgramInfo = msg; const callbacks = this.programInfoCallbacks.slice(); this.programInfoCallbacks.length = 0; for (const cb of callbacks) { cb(msg); } this.setReceivingStatus(); } else if (msg.type === "currentTime") { this.currentTimeNearestPCRBase = this.nearestPCRBase; this._currentTimeUnixMillis = msg.timeUnixMillis; } else if (msg.type === "pcr") { this.nearestPCRBase = msg.pcrBase; } else if (msg.type === "error") { console.error(msg); } } // 自ストリームのarib-dc://-1.-1.-1/を除去 private removeDCReferencePrefix(url: string): string { const result = /^arib-dc:\/\/(?<originalNetworkId>[0-9a-f]+|-1)\.(?<transportStreamId>[0-9a-f]+|-1)\.(?<serviceId>[0-9a-f]+|-1)($|\/)/i.exec(url); if (result?.groups == null) { return url; } const { originalNetworkId, transportStreamId, serviceId } = result.groups; if ((Number.parseInt(originalNetworkId, 16) === -1 || Number.parseInt(originalNetworkId, 16) === this.originalNetworkId) && (Number.parseInt(transportStreamId, 16) === -1 || Number.parseInt(transportStreamId, 16) === this.transportStreamId) && (Number.parseInt(serviceId, 16) === -1 || Number.parseInt(serviceId, 16) === this.serviceId)) { const suffix = url.substring(result[0].length); return "/" + suffix; } return url; } public parseURL(url: string | null | undefined): { component: string | null, module: string | null, filename: string | null } { if (url == null) { return { component: null, module: null, filename: null }; } if (url.startsWith("http://") || url.startsWith("https://")) { return { component: null, module: null, filename: null }; } if (!url.startsWith("arib-dc://") && !url.startsWith("arib://") && (this.activeDocument?.startsWith("http://") || this.activeDocument?.startsWith("https://"))) { return { component: null, module: null, filename: null }; } url = this.removeDCReferencePrefix(url); if (url.startsWith("~/")) { url = ".." + url.substring(1); } url = new URL(url, "http://localhost" + this.activeDocument).pathname.toLowerCase(); const components = url.split("/"); // [0] "" // [1] component // [2] module // [3] filename if (components.length > 4) { return { component: null, module: null, filename: null }; } return { component: components[1] ?? null, module: components[2] ?? null, filename: components[3] == null ? null : decodeURI(components[3]) }; } public parseURLEx(url: string | null | undefined): { componentId: number | null, moduleId: number | null, filename: string | null } { const { component, module, filename } = this.parseURL(url); const componentId = Number.parseInt(component ?? "", 16); const moduleId = Number.parseInt(module ?? "", 16); if (!Number.isInteger(componentId)) { return { componentId: null, moduleId: null, filename: null }; } if (!Number.isInteger(moduleId)) { return { componentId, moduleId: null, filename: null }; } return { componentId, moduleId, filename: filename == null ? null : filename }; } public fetchLockedResource(url: string): CachedFile | null { const { component, module, filename } = this.parseURL(url); const componentId = Number.parseInt(component ?? "", 16); const moduleId = Number.parseInt(module ?? "", 16); if (!Number.isInteger(componentId) || !Number.isInteger(moduleId)) { return null; } let cachedComponent: Component | undefined = this.lockedComponents.get(componentId); if (cachedComponent == null) { cachedComponent = this.cachedComponents.get(componentId); if (cachedComponent == null) { console.error("component not found failed to fetch ", url); return null; } } let cachedModule = cachedComponent.modules.get(moduleId); if (cachedModule == null) { cachedComponent = this.cachedComponents.get(componentId); cachedModule = cachedComponent?.modules?.get(moduleId); if (cachedModule == null) { console.error("module not found ", url); return null; } } const cachedFile = cachedModule.files.get(filename); if (cachedFile == null) { return null; } return cachedFile; } private componentRequests = new Map<number, ComponentRequest>(); private async fetchRemoteResource(url: string): Promise<CachedFile | null> { if (this.ip.get == null || this.activeDocument == null || this.baseURIDirectory == null) { return null; } const full = this.activeDocument.startsWith("http://") || this.activeDocument.startsWith("https://") ? new URL(url, this.activeDocument).toString() : url; const cachedFile = this.cachedRemoteResources.get(full); if (typeof cachedFile !== "undefined") { return cachedFile; } const requests = this.remoteResourceRequests.get(full); if (requests != null) { return new Promise((resolve, _) => { requests.push({ url: full, resolve: (file) => { if (file?.cacheControl !== "no-store") { resolve(file); } else { this.fetchRemoteResource(url).then(x => { resolve(x); }); } }, }); }); } const requests2: RemoteResourceRequest[] = []; this.remoteResourceRequests.set(full, requests2); this.indicator?.setNetworkingGetStatus(true); const { response, headers } = await this.ip.get(full); this.remoteResourceRequests.delete(full); if (this.remoteResourceRequests.size === 0) { this.indicator?.setNetworkingGetStatus(false); } if (response == null || headers == null) { for (const { resolve } of requests2) { resolve(null); } return null; } const file: RemoteCachedFile = { contentLocation: null, contentType: { originalSubtype: "", originalType: "", parameters: [], subtype: "", type: "" }, data: response, blobUrl: new Map<any, CachedFileMetadata>(), cacheControl: headers.get("Cache-Control")?.toLowerCase() }; if (file.cacheControl !== "no-store") { this.cachedRemoteResources.set(full, file); for (const { resolve } of requests2) { resolve(file); } } return file; } public fetchResourceAsync(url: string): Promise<CachedFile | null> { if (this.isInternetContent) { if ( ((this.activeDocument?.startsWith("http://") || this.activeDocument?.startsWith("https://")) && !url.startsWith("arib://") && !url.startsWith("arib-dc://")) || url.startsWith("http://") || url.startsWith("https://") ) { return this.fetchRemoteResource(url); } } const res = this.fetchLockedResource(url); if (res) { return Promise.resolve(res); } const { componentId, moduleId, filename } = this.parseURLEx(url); if (componentId == null || moduleId == null) { return Promise.resolve(null); } if (this.pmtRetrieved) { if (this.getCachedModule(componentId, moduleId)) { return Promise.resolve(null); } if (!this.getPMTComponent(componentId)) { return Promise.resolve(null); } const dcomponents = this.downloadComponents.get(componentId); if (dcomponents != null && !dcomponents.modules.has(moduleId)) { return Promise.resolve(null); } } // PMTにcomponentが存在しかつDIIにmoduleが存在するまたはDIIが取得されていないときにコールバックを登録 // TODO: ModuleUpdated用にDII取得後に存在しないことが判明したときの処理が必要 console.warn("async fetch requested", url); return new Promise((resolve, _) => { const c = this.componentRequests.get(componentId); const entry = { filename, resolve }; if (c == null) { this.componentRequests.set(componentId, { moduleRequests: new Map<number, ModuleRequest[]>([[moduleId, [entry]]]) }); } else { const m = c.moduleRequests.get(moduleId); if (m == null) { c.moduleRequests.set(moduleId, [entry]); } else { m.push(entry); } } this.setReceivingStatus(); }); } public *getLockedModules() { for (const c of this.lockedComponents.values()) { for (const m of c.modules.values()) { yield { module: `/${moduleAndComponentToString(c.componentId, m.moduleId)}`, isEx: m.lockedBy === "lockModuleOnMemoryEx" }; } } } private programInfoCallbacks: ((msg: ProgramInfoMessage) => void)[] = [] public getProgramInfoAsync(): Promise<ProgramInfoMessage> { if (this.currentProgramInfo != null) { return Promise.resolve(this.currentProgramInfo); } return new Promise<ProgramInfoMessage>((resolve, _) => { this.programInfoCallbacks.push(resolve); this.setReceivingStatus(); }); } public parseServiceReference(serviceRef: string): { originalNetworkId: number | null, transportStreamId: number | null, serviceId: number | null } { const groups = /^arib:\/\/(?<originalNetworkId>[0-9a-f]+|-1)\.(?<transportStreamId>[0-9a-f]+|-1)\.(?<serviceId>[0-9a-f]+|-1)\/?$/i.exec(serviceRef)?.groups; if (groups == null) { return { originalNetworkId: null, transportStreamId: null, serviceId: null }; } let originalNetworkId: number | null = Number.parseInt(groups.originalNetworkId, 16); let transportStreamId: number | null = Number.parseInt(groups.transportStreamId, 16); let serviceId: number | null = Number.parseInt(groups.serviceId, 16); if (originalNetworkId == -1) { originalNetworkId = this.originalNetworkId; } if (transportStreamId == -1) { transportStreamId = this.transportStreamId; } if (serviceId == -1) { serviceId = this.serviceId; } return { originalNetworkId, transportStreamId, serviceId }; } private setReceivingStatus() { if (this.programInfoCallbacks.length != 0 || [...this.componentRequests.values()].some(x => x.moduleRequests.size != 0)) { // エントリコンポーネントが存在しない場合か空カルーセルの場合データ放送番組でないのでデータ取得中を表示させない if (this.pmtRetrieved && !this.pmtComponents.has(this.startupComponentId)) { this.indicator?.setReceivingStatus(false); } else if (this.downloadComponents.get(this.startupComponentId)?.modules?.size === 0) { this.indicator?.setReceivingStatus(false); } else { this.indicator?.setReceivingStatus(true); } } else { this.indicator?.setReceivingStatus(false); } } public addEventListener<K extends keyof ResourcesEventMap>(type: K, callback: (this: undefined, evt: ResourcesEventMap[K]) => void, options?: AddEventListenerOptions | boolean) { this.eventTarget.addEventListener(type, callback as EventListener, options); } public removeEventListener<K extends keyof ResourcesEventMap>(type: K, callback: (this: undefined, evt: ResourcesEventMap[K]) => void, options?: AddEventListenerOptions | boolean) { this.eventTarget.removeEventListener(type, callback as EventListener, options); } public clearCache(): void { // this.cachedComponents.clear(); } // Cプロファイルだと0x50 public get startupComponentId(): number { return 0x40; } public get startupModuleId(): number { return 0x0000; } public get isInternetContent(): boolean { return this.baseURIDirectory != null; } baseURIDirectory: string | null = null; public setBaseURIDirectory(baseURIDirectory: string) { this.baseURIDirectory = uriToBaseURIDirectory(baseURIDirectory); } public checkBaseURIDirectory(url: string) { if (this.baseURIDirectory == null) { return false; } const base = uriToBaseURIDirectory(this.activeDocument?.startsWith("http://") || this.activeDocument?.startsWith("https://") ? new URL(url, this.activeDocument).toString() : url); return base.startsWith(this.baseURIDirectory); } } function uriToBaseURIDirectory(uri: string): string { const url = new URL(uri); // host: ポート番号含む // hostname: 含まない const hostname = url.hostname.toLowerCase(); let pathname = url.pathname; const lastSlash = pathname.lastIndexOf("/"); if (lastSlash !== -1 && lastSlash !== pathname.length - 1) { pathname = pathname.substring(0, lastSlash); } // ASCIIの範囲のURLエンコードをデコード pathname = pathname.replace(/%([0-9A-Fa-f]{2})/g, (e, hex: string) => { const d = Number.parseInt(hex, 16); if (d !== 0x2F && d >= 0x20 && d < 0x7F) { return String.fromCharCode(d); } else { return e; } }); return hostname + pathname; }
the_stack
import { Quaternion, Vector3, AnimationClip, VectorKeyframeTrack, QuaternionKeyframeTrack } from 'three' import gsap from 'gsap' import { CameraRig } from '../CameraRig' import { FreeMovementControls } from '../controlschemes/FreeMovementControls' import './index.css' const easeFunctions = ['none', 'power1', 'power2', 'power3', 'power4', 'sine', 'expo', 'circ'] interface POI { position: Vector3 quaternion: Quaternion duration: number ease: string image: string } const DOMClass = { visit: 'visit', remove: 'remove', duration: 'duration', ease: 'ease', moveUp: 'move-up', moveDown: 'move-down', } /** * A helper tool for creating camera animation paths and/or choosing camera look-at positions for points of interest in a scene * * @remarks * A helper tool for creating camera animation paths and/or choosing camera look-at positions for points of interest in a scene. * * The `CameraHelper` can be set up with any scene along with {@link three-story-controls#FreeMovementControls | FreeMovementControls}. * * It renders as an overlay with functionality to add/remove/reorders points of interest, and create an animation path between them. * Each saved camera position is displayed with an image on the `CameraHelper` panel. * * The data can be exported as a JSON file that can then be used with different control schemes. * * {@link https://nytimes.github.io/three-story-controls/examples/demos/camera-helper | DEMO } * * @example * Here's an example of initializing the CameraHelper * ```js * const scene = new Scene() * const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) * const cameraRig = new CameraRig(camera, scene) * const controls = new FreeMovementControls(cameraRig) * * controls.enable() * * const cameraHelper = new CameraHelper(rig, controls, renderer.domElement) * * // Render loop * // To allow for capturing an image of the canvas, * // it's important to update the CameraHelper after the scene is rendered, * // but before requesting the animation frame * function render(t) { * controls.update(t) * renderer.render(scene, camera) * cameraHelper.update(t) * window.requestAnimationFrame(render) * } * * render() * ``` * * * * The following examples demonstrate using the exported data. Note: Depending on your setup, you may need to change the .json extension to .js and prepend the text with `export default` such that you can import it as javascript * * @example * Here's an example using the exported JSON data with ScrollControls. * ```javascript * import * as cameraData from 'camera-control.json' * const scene = new Scene() * const gltfLoader = new GLTFLoader() * const camera = new PerspectiveCamera() * const cameraRig = new CameraRig(camera, scene) * * // Parse the JSON animation clip * cameraRig.setAnimationClip(AnimationClip.parse(cameraData.animationClip)) * cameraRig.setAnimationTime(0) * * const controls = new ScrollControls(cameraRig, { * scrollElement: document.querySelector('.scroller'), * }) * * controls.enable() * * function render(t) { * window.requestAnimationFrame(render) * if (rig.hasAnimation) { * controls.update(t) * } * renderer.render(scene, camera) * } * ``` * * @example * Here's an example using the exported data with Story Point controls * ```javascript * import * as cameraData from 'camera-control.json' * const scene = new Scene() * const gltfLoader = new GLTFLoader() * const camera = new PerspectiveCamera() * const cameraRig = new CameraRig(camera, scene) * * // Format the exported data to create three.js Vector and Quaternions * const pois = cameraData.pois.map((poi, i) => { * return { * position: new Vector3(...poi.position), * quaternion: new Quaternion(...poi.quaternion), * duration: poi.duration, * ease: poi.ease, * } * }) * * const controls = new StoryPointsControls(rig, pois) * controls.enable() * * function render(t) { * window.requestAnimationFrame(render) * controls.update(t) * renderer.render(scene, camera) * } * ``` */ export class CameraHelper { readonly rig: CameraRig readonly controls: FreeMovementControls readonly canvas: HTMLCanvasElement private pois: POI[] private currentIndex: number | null private drawer: HTMLElement private domList: HTMLElement private collapseBtn: HTMLElement private fileInput: HTMLInputElement private btnImport: HTMLElement private doCapture: boolean private animationClip: AnimationClip private isPlaying: boolean private playStartTime: number private useSlerp = true constructor(rig: CameraRig, controls: FreeMovementControls, canvas: HTMLCanvasElement, canvasParent?: HTMLElement) { this.rig = rig this.controls = controls this.canvas = canvas this.pois = [] this.currentIndex = null this.doCapture = false this.isPlaying = false this.initUI(canvasParent) } private capture(): void { this.doCapture = true } update(time: number): void { if (this.doCapture) { const image = this.canvas.toDataURL() this.addPoi(image) this.doCapture = false } if (this.isPlaying) { if (!this.playStartTime) { this.playStartTime = time this.controls.disable() this.rig.packTransform() } const t = (time - this.playStartTime) / 1000 this.rig.setAnimationTime(t) if (t > this.animationClip.duration) { this.isPlaying = false this.playStartTime = null this.controls.enable() this.rig.unpackTransform() } } } private addPoi(image: string): void { this.pois.push({ ...this.rig.getWorldCoordinates(), duration: 1, ease: 'power1', image, }) this.currentIndex = this.pois.length - 1 this.createClip() this.render() } private updatePoi(index: number, props: Partial<POI>): void { this.pois[index] = { ...this.pois[index], ...props, } } private movePoi(index: number, direction: number): void { if (index + direction >= 0 && index + direction < this.pois.length) { const temp = this.pois[index] this.pois[index] = this.pois[index + direction] this.pois[index + direction] = temp this.render() } } private removePoi(index: number): void { this.pois.splice(index, 1) this.render() } private goToPoi(index: number): void { const poi = this.pois[index] this.rig.flyTo(poi.position, poi.quaternion, poi.duration, poi.ease, this.useSlerp) } private createClip(): void { if (this.pois.length > 0) { const times = [] const positionValues = [] const quaternionValues = [] const tmpPosition = new Vector3() const tmpQuaternion = new Quaternion() const framesPerPoi = 10 let tweenStartTime = 0 // transform imported arrays to quaternions and vector3 when loading a camera file if (!this.pois[0].quaternion.isQuaternion && !this.pois[0].position.isVector3) { for (let i = 0; i < this.pois.length; i++) { const p = this.pois[i] p.quaternion = new Quaternion(p.quaternion[0], p.quaternion[1], p.quaternion[2], p.quaternion[3]) p.position = new Vector3(p.position[0], p.position[1], p.position[2]) } } for (let i = 0; i < this.pois.length - 1; i++) { const p1 = this.pois[i] const p2 = this.pois[i + 1] const values = { px: p1.position.x, py: p1.position.y, pz: p1.position.z, qx: p1.quaternion.x, qy: p1.quaternion.y, qz: p1.quaternion.z, qw: p1.quaternion.w, slerpAmount: 0, } const target = { px: p2.position.x, py: p2.position.y, pz: p2.position.z, qx: p2.quaternion.x, qy: p2.quaternion.y, qz: p2.quaternion.z, qw: p2.quaternion.w, slerpAmount: 1, duration: p2.duration, ease: p2.ease, } const tween = gsap.to(values, target) for (let j = 0; j < framesPerPoi; j++) { const lerpAmount = p2.duration * (j / framesPerPoi) times.push(tweenStartTime + lerpAmount) tween.seek(lerpAmount) if (this.useSlerp) { tmpQuaternion.slerpQuaternions(p1.quaternion, p2.quaternion, values.slerpAmount) } else { tmpQuaternion.set(values.qx, values.qy, values.qz, values.qw) } tmpPosition.set(values.px, values.py, values.pz) tmpQuaternion.toArray(quaternionValues, quaternionValues.length) tmpPosition.toArray(positionValues, positionValues.length) } tweenStartTime += p2.duration } // add last point const last = this.pois[this.pois.length - 1] last.quaternion.toArray(quaternionValues, quaternionValues.length) last.position.toArray(positionValues, positionValues.length) times.push(tweenStartTime) this.animationClip = new AnimationClip(null, tweenStartTime, [ new VectorKeyframeTrack('Translation.position', times, positionValues), new QuaternionKeyframeTrack('Rotation.quaternion', times, quaternionValues), ]) this.rig.setAnimationClip(this.animationClip) } } private scrubClip(amount: number): void { if (this.pois.length > 0) { this.rig.setAnimationPercentage(amount) } } private playClip(): void { if (this.pois.length > 0) { this.isPlaying = true } } private import(): void { if (this.fileInput) { this.fileInput.click() const reader = new FileReader() this.fileInput.onchange = () => { reader.readAsText(this.fileInput.files[0]) reader.onload = (e) => { const parsed = JSON.parse(<string>e.target.result) this.pois = parsed.pois this.animationClip = parsed.animationClip this.createClip() this.render() } } } } private export({ draft }): void { if (this.pois.length > 0) { const jsondata = {} as any jsondata.pois = this.pois.map((poi) => { const position = [poi.position.x, poi.position.y, poi.position.z] const quaternion = [poi.quaternion.x, poi.quaternion.y, poi.quaternion.z, poi.quaternion.w] const obj = { position, quaternion, duration: poi.duration, ease: poi.ease, } as any if (draft) { obj.image = poi.image } return obj }) if (this.animationClip) { jsondata.animationClip = AnimationClip.toJSON(this.animationClip) } const data = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(jsondata)) const a = document.createElement('a') a.href = 'data:' + data a.download = `camera-data${draft ? '-draft' : ''}.json` document.body.appendChild(a) a.click() a.remove() } } private exportImages(): void { const link = document.createElement('a') document.body.appendChild(link) this.pois.forEach((poi, index) => { link.href = poi.image link.download = `camera-poi-${index}.png` link.click() }) link.remove() } // ui private initUI(canvasParent?: HTMLElement): void { this.drawer = document.createElement('div') this.drawer.classList.add('tb-ch') const btnAdd = document.createElement('button') btnAdd.classList.add('btn-round', 'add') btnAdd.innerText = '+' btnAdd.onclick = this.capture.bind(this) this.collapseBtn = document.createElement('button') this.collapseBtn.classList.add('btn-round', 'collapse') this.collapseBtn.innerText = '<' this.collapseBtn.onclick = this.collapse.bind(this) const controlWrapper = document.createElement('div') controlWrapper.classList.add('controls') this.fileInput = document.createElement('input') this.fileInput.type = 'file' this.fileInput.id = 'import' this.fileInput.accept = 'application/json' this.fileInput.style.display = 'none' this.btnImport = document.createElement('button') this.btnImport.classList.add('btn-text', 'import') this.btnImport.innerText = 'import draft JSON' this.btnImport.onclick = this.import.bind(this) const btnExportImages = document.createElement('button') btnExportImages.classList.add('btn-text', 'export') btnExportImages.innerText = 'export draft JSON' btnExportImages.onclick = this.export.bind(this, { draft: true }) const btnExport = document.createElement('button') btnExport.classList.add('btn-text', 'export') btnExport.innerText = 'export production JSON' btnExport.onclick = this.export.bind(this, { draft: false }) const bntExportImages = document.createElement('button') bntExportImages.classList.add('btn-text', 'export-images') bntExportImages.innerHTML = 'export images' bntExportImages.onclick = this.exportImages.bind(this) const btnPlay = document.createElement('button') btnPlay.classList.add('btn-text', 'play') btnPlay.innerText = 'play' btnPlay.onclick = this.playClip.bind(this) const sliderTime: HTMLInputElement = document.createElement('input') sliderTime.type = 'range' sliderTime.min = '0' sliderTime.max = '1000' sliderTime.step = '0.1' sliderTime.value = '0' const updateTime = this.scrubClip.bind(this) sliderTime.onmousedown = () => this.rig.packTransform() sliderTime.onmouseup = () => this.rig.unpackTransform() sliderTime.oninput = (e) => updateTime(parseInt((<HTMLInputElement>e.target).value) / 1000) this.domList = document.createElement('div') this.domList.classList.add('pois') this.domList.onclick = this.handleEvents.bind(this) this.domList.onchange = this.handleEvents.bind(this) controlWrapper.append( this.fileInput, this.btnImport, btnPlay, sliderTime, bntExportImages, btnExportImages, btnExport, ) this.drawer.append(btnAdd, this.collapseBtn, this.domList, controlWrapper) const parent = canvasParent || document.body parent.append(this.drawer) } private handleEvents(event): void { const index = event.target.dataset.index if (index) { if (event.target.classList.contains(DOMClass.visit)) { this.goToPoi(parseInt(index)) } else if (event.target.classList.contains(DOMClass.remove)) { this.removePoi(parseInt(index)) } else if (event.target.classList.contains(DOMClass.duration)) { this.updatePoi(parseInt(index), { duration: parseFloat((<HTMLInputElement>event.target).value) }) } else if (event.target.classList.contains(DOMClass.ease)) { this.updatePoi(parseInt(index), { ease: (<HTMLSelectElement>event.target).value }) } else if (event.target.classList.contains(DOMClass.moveUp)) { this.movePoi(parseInt(index), -1) } else if (event.target.classList.contains(DOMClass.moveDown)) { this.movePoi(parseInt(index), 1) } this.createClip() } } private collapse(): void { if (this.drawer.classList.contains('collapsed')) { this.drawer.classList.remove('collapsed') this.collapseBtn.innerText = '<' } else { this.drawer.classList.add('collapsed') this.collapseBtn.innerText = '>' } } private render(): void { this.domList.innerHTML = '' this.pois.forEach((poi, index) => { const div = document.createElement('div') div.classList.add('poi') const textHeading = document.createElement('h2') textHeading.innerText = `${index + 1}.` const wrapper = document.createElement('div') wrapper.classList.add('wrapper') const controls = document.createElement('div') controls.classList.add('poi-controls') const params = document.createElement('div') params.classList.add('poi-params') const image = new Image() image.src = poi.image const labelDuration = document.createElement('label') labelDuration.innerText = 'Duration' const inputDuration = document.createElement('input') inputDuration.classList.add(DOMClass.duration) inputDuration.dataset.index = `${index}` inputDuration.type = 'number' inputDuration.value = String(poi.duration) const labelEase = document.createElement('label') labelEase.innerText = 'Easing' const selectEase = document.createElement('select') selectEase.classList.add(DOMClass.ease) selectEase.dataset.index = `${index}` const options = easeFunctions.map((x) => { const op = document.createElement('option') op.innerText = x op.value = x op.selected = x === poi.ease return op }) selectEase.append(...options) const btnRemove = document.createElement('button') btnRemove.classList.add(DOMClass.remove) btnRemove.title = 'Remove' btnRemove.dataset.index = `${index}` btnRemove.innerText = 'x' const btnVisit = document.createElement('button') btnVisit.classList.add(DOMClass.visit) btnVisit.title = 'Visit' btnVisit.dataset.index = `${index}` btnVisit.innerHTML = '&rarr;' const btnMoveUp = document.createElement('button') btnMoveUp.classList.add(DOMClass.moveUp) btnMoveUp.title = 'Move up' btnMoveUp.dataset.index = `${index}` btnMoveUp.innerHTML = '&uarr;' const btnMoveDown = document.createElement('button') btnMoveDown.classList.add(DOMClass.moveDown) btnMoveDown.title = 'Move down' btnMoveDown.dataset.index = `${index}` btnMoveDown.innerHTML = '&darr;' controls.append(btnRemove, btnVisit, btnMoveUp, btnMoveDown) params.append(labelDuration, inputDuration, labelEase, selectEase) wrapper.append(image, controls) div.append(textHeading, wrapper, params) this.domList.appendChild(div) }) } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A jQuery UI plugin that lets users select a subset of items from a larger set. */ namespace VRS { /** * The options for the OptionFieldOrderedSubsetPlugin */ export interface OptionFieldOrderedSubsetPlugin_Options extends OptionControl_BaseOptions { field: OptionFieldOrderedSubset; } /** * The state held by the OptionFieldOrderedSubsetPlugin */ class OptionFieldOrderedSubsetPlugin_State { /** * The jQuery element that holds all of the elements for the selected subset. */ subsetElement: JQuery = null; /** * The jQuery UI sortable element; */ sortableElement: JQuery = null; /** * The jQuery element that holds the edit controls toolstrip. */ toolstripElement: JQuery = null; /** * The jQuery element that holds the list of values that can be added to the subset. */ addSelectElement: JQuery = null; /** * The jQuery element for the add to subset button. */ addButtonElement: JQuery = null; /** * The jQuery element for the lock buton. */ lockElement: JQuery = null; /** * True if modifications to the list are locked, false if they are not. */ lockEnabled = true; } /* * jQueryUIHelper methods */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; VRS.jQueryUIHelper.getOptionFieldOrderedSubsetPlugin = function(jQueryElement: JQuery) : OptionFieldOrderedSubsetPlugin { return jQueryElement.data('vrsVrsOptionFieldOrderedSubset'); } VRS.jQueryUIHelper.getOptionFieldOrderedSubsetOptions = function(overrides?: OptionFieldOrderedSubsetPlugin_Options) : OptionFieldOrderedSubsetPlugin_Options { return $.extend({ optionPageParent: null, }, overrides); } /** * A plugin that allows users to select a subset of a larger set of items. */ export class OptionFieldOrderedSubsetPlugin extends JQueryUICustomWidget { options: OptionFieldOrderedSubsetPlugin_Options; constructor() { super(); this.options = VRS.jQueryUIHelper.getOptionFieldOrderedSubsetOptions(); } private _getState() : OptionFieldOrderedSubsetPlugin_State { var result = this.element.data('vrsOptionFieldOrderedSubsetState'); if(result === undefined) { result = new OptionFieldOrderedSubsetPlugin_State(); this.element.data('vrsOptionFieldOrderedSubsetState', result); } return result; } _create() { var state = this._getState(); var options = this.options; var field = options.field; var values = field.getValues(); var subset = field.getValue() || []; var subsetValues = this._getSubsetValueObjects(values, subset); this.element .addClass('vrsOptionPluginSubset'); state.toolstripElement = $('<div/>') .addClass('toolstrip') .appendTo(this.element); state.subsetElement = $('<div/>') .addClass('subset') .appendTo(this.element); this._buildToolstripContent(state, values, subsetValues); this._buildSortableList(state, state.subsetElement, subsetValues); this._showEnabledDisabled(state); } _destroy() { var state = this._getState(); if(state.sortableElement) { state.sortableElement.off(); state.sortableElement.find('.button').off(); state.sortableElement.sortable('destroy'); state.subsetElement.remove(); state.sortableElement = null; } if(state.subsetElement) { state.subsetElement.remove(); } state.subsetElement = null; this._removeToolstripContent(state); if(state.toolstripElement) { state.toolstripElement.remove(); } state.toolstripElement = null; this.element.empty(); } /** * Populates the toolstrip element with controls. */ private _buildToolstripContent(state: OptionFieldOrderedSubsetPlugin_State, values: ValueText[], subsetValues: ValueText[], autoSelect?: any) { this._removeToolstripContent(state); var allValues = values.slice(); allValues.sort(function(lhs, rhs) { var lhsText = lhs.getText() || ''; var rhsText = rhs.getText() || ''; return lhsText.localeCompare(rhsText); }); var availableValues = VRS.arrayHelper.except(allValues, subsetValues); var autoSelectValue = autoSelect === undefined ? undefined : VRS.arrayHelper.findFirst(availableValues, function(value) { return value.getValue() === autoSelect; }); if(autoSelect !== undefined && !autoSelectValue) { var autoSelectIndex = VRS.arrayHelper.indexOfMatch(allValues, function(value) { return value.getValue() === autoSelect; }); if(autoSelectIndex !== -1) { for(var searchDirection = 0;!autoSelectValue && searchDirection < 2;++searchDirection) { var startIndex = searchDirection ? autoSelectIndex - 1 : autoSelectIndex + 1; var step = startIndex < autoSelectIndex ? -1 : 1; var limit = step === -1 ? -1 : allValues.length; for(var i = startIndex;i !== limit;i += step) { var candidate = allValues[i]; if(VRS.arrayHelper.indexOf(availableValues, candidate) !== -1) { autoSelectValue = candidate; break; } } } } } var parent = state.toolstripElement; state.addSelectElement = $('<select/>') .appendTo(parent); $.each(availableValues, function(idx, value) { $('<option/>') .attr('value', value.getValue()) .text(value.getText()) .appendTo(state.addSelectElement); }); if(autoSelectValue) { state.addSelectElement.val(autoSelectValue.getValue()); } state.addButtonElement = $('<button/>') .on('click', $.proxy(this._addValueButtonClicked, this)) .appendTo(parent) .button({ label: VRS.$$.Add }); state.lockElement = $('<div/>') .addClass('lockButton vrsIcon') .on('click', $.proxy(this._lockButtonClicked, this)) .appendTo(parent); this._showEnabledDisabled(state); } /** * Modifies the display to reflect the state of the controls. */ private _showEnabledDisabled(state: OptionFieldOrderedSubsetPlugin_State) { if(state.sortableElement && state.lockElement) { var listItems = state.sortableElement.children('li'); var icons = state.sortableElement.find('.button'); var firstSortUp = state.sortableElement.find('.vrsIcon-sort-up').first(); var lastSortDown = state.sortableElement.find('.vrsIcon-sort-down').last(); if(state.lockEnabled) { state.lockElement.removeClass('vrsIcon-unlocked').addClass('locked vrsIcon-locked'); listItems.addClass('locked'); icons.addClass('locked'); state.addSelectElement.prop('disabled', true); state.addButtonElement.button('disable'); } else { state.lockElement.removeClass('locked vrsIcon-locked').addClass('vrsIcon-unlocked'); listItems.removeClass('locked'); icons.removeClass('locked'); firstSortUp.addClass('locked'); lastSortDown.addClass('locked'); if(state.addSelectElement.children().length === 0) { state.addSelectElement.prop('disabled', true); state.addButtonElement.button('disable'); } else { state.addSelectElement.prop('disabled', false); state.addButtonElement.button('enable'); } } } } /** * Removes all of the controls in the toolstrip. */ private _removeToolstripContent(state: OptionFieldOrderedSubsetPlugin_State) { if(state.addSelectElement) { state.addSelectElement.remove(); } state.addSelectElement = null; if(state.addButtonElement) { state.addButtonElement.off(); state.addButtonElement.button('destroy'); state.addButtonElement.remove(); } state.addButtonElement = null; if(state.lockElement) { state.lockElement.off(); state.lockElement.remove(); } state.lockElement = null; } /** * Creates the sortable element containing entries for the selected list. */ private _buildSortableList(state: OptionFieldOrderedSubsetPlugin_State, parent: JQuery, values: ValueText[]) { state.sortableElement = $('<ul/>') .uniqueId() .appendTo(parent); var length = values.length; for(var i = 0;i < length;++i) { var value = values[i]; this._addValueToSortableList(state, value); } state.sortableElement.sortable({ containment: 'parent', disabled: state.lockEnabled, cancel: '.button', stop: $.proxy(this._sortableSortStopped, this) }); } /** * Adds a value to the sortable list. */ private _addValueToSortableList(state: OptionFieldOrderedSubsetPlugin_State, value: ValueText) { $('<li/>') .data('vrs', { value: value.getValue() }) .text(value.getText()) .append($('<div/>') .addClass('button vrsIcon vrsIcon-sort-up') .on('click', $.proxy(this._sortIncrementClicked, this)) ) .append($('<div/>') .addClass('button vrsIcon vrsIcon-sort-down') .on('click', $.proxy(this._sortIncrementClicked, this)) ) .append($('<div/>') .addClass('button vrsIcon vrsIcon-remove') .on('click', $.proxy(this._removeIconClicked, this)) ) .appendTo(state.sortableElement); } /** * Destroys the element representing the sortable list value. */ private _destroySortableListValue(valueElement: JQuery) { valueElement.hide({ effect: 'Clip', duration: 300, complete: function() { valueElement.find('div') .off() .remove(); valueElement .data('vrs', null) .off() .remove(); } }); } /** * Returns a copy of the subset array filtered so that any elements not present in the values array are removed. */ private _getSubsetValueObjects(values: ValueText[], subset: any[]) : ValueText[] { var result: ValueText[] = []; var subsetLength = subset.length; var valuesLength = values.length; for(var i = 0;i < subsetLength;++i) { var subsetValue = undefined; for(var c = 0;c < valuesLength;++c) { var value = values[c]; if(value.getValue() === subset[i]) { subsetValue = value; break; } } if(!subsetValue) throw 'Cannot find the value that corresponds with subset value ' + subset[i]; result.push(subsetValue); } return result; } /** * Returns an array of values that are present in the subset control. */ private _getSelectedValues(state: OptionFieldOrderedSubsetPlugin_State) : any[] { var result: any[] = []; var items = state.sortableElement.find('> li'); items.each(function(idx, item) { var data = $(item).data('vrs'); if(data) result.push(data.value); }); return result; } /** * Called when the user stops sorting the subset of selected values. */ private _sortableSortStopped(event: JQueryEventObject, ui: JQueryUI.SortableUIParams) { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var state = this._getState(); var options = this.options; var field = options.field; var values = this._getSelectedValues(state); field.setValue(values); field.saveState(); options.optionPageParent.raiseFieldChanged(); this._showEnabledDisabled(state); } /** * Called when the user clicks one of the sort-up or sort-down buttons. */ private _sortIncrementClicked(event: JQueryEventObject) { if(VRS.timeoutManager) VRS.timeoutManager.resetTimer(); var state = this._getState(); if(!state.lockEnabled) { var options = this.options; var field = options.field; var values = this._getSelectedValues(state); var clickedIcon = $(event.target); var moveUp = clickedIcon.hasClass('vrsIcon-sort-up'); var clickedListItem = clickedIcon.parent(); var clickedValue = clickedListItem.data('vrs').value; var clickedIndex = VRS.arrayHelper.indexOf(values, clickedValue); if((moveUp && clickedIndex !== 0) || (!moveUp && clickedIndex + 1 < values.length)) { values.splice(clickedIndex, 1); var index = moveUp ? clickedIndex - 1 : clickedIndex + 1; values.splice(index, 0, clickedValue); var topElement = moveUp ? clickedListItem.prev() : clickedListItem; var bottomElement = moveUp ? clickedListItem : clickedListItem.next(); var topOffset = topElement.offset().top; var bottomOffset = bottomElement.offset().top; var animationsCompleted = 0; var complete = () => { if(++animationsCompleted == 2) { topElement.css({ position: '', top: ''}); bottomElement.css({ position: '', top: ''}); if(moveUp) clickedListItem.insertBefore(topElement); else clickedListItem.insertAfter(bottomElement); field.setValue(values); field.saveState(); options.optionPageParent.raiseFieldChanged(); this._showEnabledDisabled(state); } }; topElement.css('position', 'relative'); bottomElement.css('position', 'relative'); var duration = 300; topElement.animate({ top: bottomOffset - topOffset }, { duration: duration, queue: false, complete: complete }); bottomElement.animate({ top: topOffset - bottomOffset }, { duration: duration, queue: false, complete: complete }); } } } /** * Called when the user clicks the ADD button for a new subset value. */ private _addValueButtonClicked() { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var state = this._getState(); var options = this.options; var field = options.field; var allValues = field.getValues(); var newValue; var selectedValue = state.addSelectElement.val(); if(selectedValue) { newValue = VRS.arrayHelper.findFirst(allValues, function(searchValue) { return searchValue.getValue() === selectedValue; }); } if(newValue) { var values = this._getSelectedValues(state); values.push(selectedValue); field.setValue(values); field.saveState(); options.optionPageParent.raiseFieldChanged(); var subsetValues = this._getSubsetValueObjects(allValues, values); this._addValueToSortableList(state, newValue); this._buildToolstripContent(state, allValues, subsetValues, selectedValue); } } /** * Called when the user clicks the toggle delete mode button. */ private _lockButtonClicked() { var state = this._getState(); state.lockEnabled = !state.lockEnabled; state.sortableElement.sortable('option', 'disabled', state.lockEnabled); this._showEnabledDisabled(state); } /** * Called when the user clicks a delete icon. */ private _removeIconClicked(event: JQueryEventObject) { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var state = this._getState(); if(!state.lockEnabled) { var options = this.options; var field = options.field; var allValues = field.getValues(); var subsetValues = this._getSubsetValueObjects(allValues, this._getSelectedValues(state)); var clickedIcon = $(event.target); var clickedListItem = clickedIcon.parent(); var clickedValue = clickedListItem.data('vrs').value; var clickedIndex = VRS.arrayHelper.indexOfMatch(subsetValues, function(/** VRS.ValueText */ valueText) { return valueText.getValue() === clickedValue; }); subsetValues.splice(clickedIndex, 1); var values = VRS.arrayHelper.select(subsetValues, function(/** VRS.ValueText */ valueText) { return valueText.getValue(); }); field.setValue(values); field.saveState(); options.optionPageParent.raiseFieldChanged(); this._destroySortableListValue(clickedListItem); this._buildToolstripContent(state, allValues, subsetValues, clickedValue); } } } $.widget('vrs.vrsOptionFieldOrderedSubset', new OptionFieldOrderedSubsetPlugin()); if(VRS.optionControlTypeBroker) { VRS.optionControlTypeBroker.addControlTypeHandlerIfNotRegistered( VRS.optionControlTypes.orderedSubset, function(settings: OptionFieldOrderedSubsetPlugin_Options) { return $('<div/>') .appendTo(settings.fieldParentJQ) .vrsOptionFieldOrderedSubset(VRS.jQueryUIHelper.getOptionFieldOrderedSubsetOptions(settings)); } ); } } declare interface JQuery { vrsOptionFieldOrderedSubset(); vrsOptionFieldOrderedSubset(options: VRS.OptionFieldOrderedSubsetPlugin_Options); vrsOptionFieldOrderedSubset(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
import { ITextIntentSequenceLabelObjectByPosition} from "./ITextIntentSequenceLabelObjectByPosition"; import { Data } from "./Data"; import { DataWithSubwordFeaturizer } from "./DataWithSubwordFeaturizer"; import { NgramSubwordFeaturizer } from "../model/language_understanding/featurizer/NgramSubwordFeaturizer"; import { Utility } from "../utility/Utility"; export class ColumnarDataWithSubwordFeaturizer extends DataWithSubwordFeaturizer { public static createColumnarDataWithSubwordFeaturizerFromSamplingExistingColumnarDataUtterances( existingColumnarDataWithSubwordFeaturizer: ColumnarDataWithSubwordFeaturizer, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, samplingIndexArray: number[], toResetFeaturizerLabelFeatureMaps: boolean): ColumnarDataWithSubwordFeaturizer { // ------------------------------------------------------------------- const columnarDataWithSubwordFeaturizer: ColumnarDataWithSubwordFeaturizer = ColumnarDataWithSubwordFeaturizer.createColumnarDataWithSubwordFeaturizer( existingColumnarDataWithSubwordFeaturizer.getContent(), existingColumnarDataWithSubwordFeaturizer.getFeaturizer(), labelColumnIndex, textColumnIndex, weightColumnIndex, linesToSkip, toResetFeaturizerLabelFeatureMaps); // ------------------------------------------------------------------- const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = columnarDataWithSubwordFeaturizer.luUtterances; const lengthUtterancesArray: number = luUtterances.length; columnarDataWithSubwordFeaturizer.luUtterances = []; for (const index of samplingIndexArray) { if ((index < 0) || (index > lengthUtterancesArray)) { Utility.debuggingThrow(`(index|${index}|<0)||(index|${index}|>lengthUtterancesArray|${lengthUtterancesArray}|)`); } columnarDataWithSubwordFeaturizer.luUtterances.push(luUtterances[index]); } // ------------------------------------------------------------------- columnarDataWithSubwordFeaturizer.intentInstanceIndexMapArray = columnarDataWithSubwordFeaturizer.collectIntents(columnarDataWithSubwordFeaturizer.luUtterances); columnarDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray = columnarDataWithSubwordFeaturizer.collectEntityTypes(columnarDataWithSubwordFeaturizer.luUtterances); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.intents = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.text); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.weights = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight); // ------------------------------------------------------------------- if (toResetFeaturizerLabelFeatureMaps) { columnarDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps(); } // ------------------------------------------------------------------- columnarDataWithSubwordFeaturizer.featurizeIntentsUtterances(); // ------------------------------------------------------------------- return columnarDataWithSubwordFeaturizer; } public static createColumnarDataWithSubwordFeaturizerFromFilteringExistingColumnarDataUtterances( existingColumnarDataWithSubwordFeaturizer: ColumnarDataWithSubwordFeaturizer, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, filteringIndexSet: Set<number>, toResetFeaturizerLabelFeatureMaps: boolean): ColumnarDataWithSubwordFeaturizer { // ------------------------------------------------------------------- const columnarDataWithSubwordFeaturizer: ColumnarDataWithSubwordFeaturizer = ColumnarDataWithSubwordFeaturizer.createColumnarDataWithSubwordFeaturizer( existingColumnarDataWithSubwordFeaturizer.getContent(), existingColumnarDataWithSubwordFeaturizer.getFeaturizer(), labelColumnIndex, textColumnIndex, weightColumnIndex, linesToSkip, toResetFeaturizerLabelFeatureMaps); // ------------------------------------------------------------------- const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = columnarDataWithSubwordFeaturizer.luUtterances; columnarDataWithSubwordFeaturizer.luUtterances = luUtterances.filter( (value: ITextIntentSequenceLabelObjectByPosition, index: number, array: ITextIntentSequenceLabelObjectByPosition[]) => { return (filteringIndexSet.has(index)); }); // ------------------------------------------------------------------- columnarDataWithSubwordFeaturizer.intentInstanceIndexMapArray = columnarDataWithSubwordFeaturizer.collectIntents(columnarDataWithSubwordFeaturizer.luUtterances); columnarDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray = columnarDataWithSubwordFeaturizer.collectEntityTypes(columnarDataWithSubwordFeaturizer.luUtterances); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.intents = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.text); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.weights = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight); // ------------------------------------------------------------------- if (toResetFeaturizerLabelFeatureMaps) { columnarDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps(); } // ------------------------------------------------------------------- columnarDataWithSubwordFeaturizer.featurizeIntentsUtterances(); // ------------------------------------------------------------------- return columnarDataWithSubwordFeaturizer; } public static createColumnarDataWithSubwordFeaturizer( content: string, featurizer: NgramSubwordFeaturizer, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, toResetFeaturizerLabelFeatureMaps: boolean): ColumnarDataWithSubwordFeaturizer { // ------------------------------------------------------------------- const columnarDataWithSubwordFeaturizer: ColumnarDataWithSubwordFeaturizer = new ColumnarDataWithSubwordFeaturizer( featurizer, labelColumnIndex, textColumnIndex, weightColumnIndex, linesToSkip); columnarDataWithSubwordFeaturizer.content = content; // ------------------------------------------------------------------- columnarDataWithSubwordFeaturizer.luUtterances = columnarDataWithSubwordFeaturizer.retrieveColumnarUtterances(content); // ------------------------------------------------------------------- columnarDataWithSubwordFeaturizer.intentInstanceIndexMapArray = columnarDataWithSubwordFeaturizer.collectIntents(columnarDataWithSubwordFeaturizer.luUtterances); columnarDataWithSubwordFeaturizer.entityTypeInstanceIndexMapArray = columnarDataWithSubwordFeaturizer.collectEntityTypes(columnarDataWithSubwordFeaturizer.luUtterances); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.intents = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.utterances = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.text); columnarDataWithSubwordFeaturizer.intentsUtterancesWeights.weights = columnarDataWithSubwordFeaturizer.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight); // ------------------------------------------------------------------- if (toResetFeaturizerLabelFeatureMaps) { columnarDataWithSubwordFeaturizer.resetFeaturizerLabelFeatureMaps(); } // ------------------------------------------------------------------- columnarDataWithSubwordFeaturizer.featurizeIntentsUtterances(); // ------------------------------------------------------------------- return columnarDataWithSubwordFeaturizer; } protected labelColumnIndex: number = 0; protected textColumnIndex: number = 1; protected weightColumnIndex: number = -1; protected linesToSkip: number = 0; protected constructor( featurizer: NgramSubwordFeaturizer, labelColumnIndex: number = 0, textColumnIndex: number = 1, weightColumnIndex: number = -1, linesToSkip: number = 0) { super(featurizer); this.labelColumnIndex = labelColumnIndex; this.textColumnIndex = textColumnIndex; this.weightColumnIndex = weightColumnIndex; this.linesToSkip = linesToSkip; } public async createDataFromSamplingExistingDataUtterances( existingDataWithSubwordFeaturizer: DataWithSubwordFeaturizer, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, samplingIndexArray: number[], toResetFeaturizerLabelFeatureMaps: boolean): Promise<Data> { if (!(existingDataWithSubwordFeaturizer instanceof ColumnarDataWithSubwordFeaturizer)) { Utility.debuggingThrow("logic error: the input DataWithSubwordFeaturizer object should be a ColumnarDataWithSubwordFeaturizer object."); } return ColumnarDataWithSubwordFeaturizer. createColumnarDataWithSubwordFeaturizerFromSamplingExistingColumnarDataUtterances( existingDataWithSubwordFeaturizer as ColumnarDataWithSubwordFeaturizer, labelColumnIndex, textColumnIndex, weightColumnIndex, linesToSkip, samplingIndexArray, toResetFeaturizerLabelFeatureMaps); } public async createDataFromFilteringExistingDataUtterances( existingDataWithSubwordFeaturizer: DataWithSubwordFeaturizer, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, filteringIndexSet: Set<number>, toResetFeaturizerLabelFeatureMaps: boolean): Promise<Data> { if (!(existingDataWithSubwordFeaturizer instanceof ColumnarDataWithSubwordFeaturizer)) { Utility.debuggingThrow("logic error: the input DataWithSubwordFeaturizer object should be a ColumnarDataWithSubwordFeaturizer object."); } return ColumnarDataWithSubwordFeaturizer. createColumnarDataWithSubwordFeaturizerFromFilteringExistingColumnarDataUtterances( existingDataWithSubwordFeaturizer as ColumnarDataWithSubwordFeaturizer, labelColumnIndex, textColumnIndex, weightColumnIndex, linesToSkip, filteringIndexSet, toResetFeaturizerLabelFeatureMaps); } public retrieveColumnarUtterances(content: string): ITextIntentSequenceLabelObjectByPosition[] { // ---- NOTE ---- the return is newly allocated, unlike the one in LuData const intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] } = Utility.loadLabelUtteranceColumnarContent( content, // ---- filename: string, this.getLabelColumnIndex(), // ---- labelColumnIndex: number = 0, this.getTextColumnIndex(), // ---- textColumnIndex: number = 1, this.getWeightColumnIndex(), // ---- weightColumnIndex: number = -1, this.getLinesToSkip(), // ---- lineIndexToStart: number = 0, "\t", // ---- columnDelimiter: string = "\t", "\n", // ---- rowDelimiter: string = "\n", "utf8", // ---- encoding: string = "utf8", -1, // ---- lineIndexToEnd: number = -1 ); const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = []; const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; for (let i = 0; i < intents.length; i++) { const intent: string = intents[i]; const text: string = utterances[i]; const weight: number = weights[i]; const luUtterance: ITextIntentSequenceLabelObjectByPosition = { entities: [], partOfSpeechTags: [], intent, text, weight, }; luUtterances.push(luUtterance); } return luUtterances; } public getLuObject(): any { // ---- NOTE: can be overriden by a child class. throw new Error("Logical error as it's not implemented for a " + "ColumnarDataWithSubwordFeaturizer object to generate a LU object."); } public getLuLuisJsonStructure(): any { // ---- NOTE: can be overriden by a child class. throw new Error("Logical error as it's not implemented for a " + "ColumnarDataWithSubwordFeaturizer object to generate a LUIS JSON object."); } public getLuQnaJsonStructure(): any { // ---- NOTE: can be overriden by a child class. throw new Error("Logical error as it's not implemented for a " + "ColumnarDataWithSubwordFeaturizer object to generate a QnA JSON object."); } public getLuQnaAlterationsJsonStructure(): any { // ---- NOTE: can be overriden by a child class. throw new Error("Logical error as it's not implemented for a " + "ColumnarDataWithSubwordFeaturizer to generate a QnA Alterations JSON object."); } public getLabelColumnIndex(): number { return this.labelColumnIndex; } public getTextColumnIndex(): number { return this.textColumnIndex; } public getWeightColumnIndex(): number { return this.weightColumnIndex; } public getLinesToSkip(): number { return this.linesToSkip; } }
the_stack
import { expect } from 'chai' import { BaseTestingResource, PostResource, UserResource, GroupResource, TodoResource, CommentResource } from '..' describe('Resources', () => { it('correctly gets remote resource', async () => { let post = await PostResource.detail('1') expect(post.get('user')).to.exist let user = await UserResource.detail('1') expect(user.get('name')).to.exist }) it('creates and saves resources', async () => { let user = new UserResource({ name: 'Test User', username: 'testing123321', email: 'testuser@dsf.com', }) await user.save() expect(user).to.have.property('id') expect(user.id).to.exist expect(user._attributes.id).to.exist // Make sure save() only sends requested fields const CustomUserResource = UserResource.extend({ fields: ['username', 'email'], }) let user2 = new CustomUserResource({ name: 'Another Test User', username: 'testing54321', email: 'anothertest@dsf.com', }) let result = await user2.save() expect(user).to.have.property('id') expect(user.changes.id).to.exist expect(result.response.data.email).to.exist expect(result.response.data.username).to.exist expect(result.response.data.name).to.be.undefined // Make sure this also works with save({ fields: [...] } let user3 = new CustomUserResource({ name: 'Another Another Test User', username: 'testing3212', email: 'anothertest2@dsf.com', address: '123 Fake St', }) let result2 = await user3.save({ fields: ['address'] }) expect(result2.response.data.address).to.equal('123 Fake St') expect(result2.response.data.email).to.be.undefined expect(result2.response.data.username).to.be.undefined expect(result2.response.data.name).to.be.undefined // Make sure changes are unset after they're sent user3.set('city', 'San Francisco') expect(user3.changes).to.have.property('city') await user3.save({ fields: ['city'] }) expect(user3.changes.city).to.be.undefined }) it('gets/sets properties correctly (static)', async () => { let changingUser = new UserResource({ name: 'Test User', username: 'testing123321', email: 'testuser@dsf.com', }) expect(changingUser.get('name')).to.equal('Test User') changingUser.set('name', 'Test User (Changed)') expect(changingUser.get('name')).to.equal('Test User (Changed)') expect(changingUser.changes.name).to.exist expect(changingUser.changes.name).to.equal('Test User (Changed)') expect(changingUser.attributes.name).to.equal('Test User (Changed)') expect(typeof changingUser.get()).to.equal('object') changingUser.set('name', 'Test User (Changed again)') expect(changingUser.get('name')).to.equal('Test User (Changed again)') }) it('correctly gets a cached related item', async () => { let post = await PostResource.detail('1', { resolveRelated: true }) let cached = UserResource.getCached(post.get('user.id')) expect(cached).to.be.string expect(cached.resource).to.be.instanceOf(UserResource) expect(await PostResource.detail('1') === post).to.be.true // Repeatedly GET /posts/1 ... await PostResource.detail('1') await PostResource.detail('1') await PostResource.detail('1') // Then check how many requests it sent to it (should be only 1) expect(PostResource.client.requestTracker[PostResource.getDetailRoutePath('1')]).to.equal(1) }) it('should never allow extended classes to share the same cache', async () => { class A extends PostResource {} class B extends A {} class C extends B {} expect(C.cache === A.cache).to.be.false expect(C.cache === B.cache).to.be.false expect(C._cache === B._cache).to.be.false expect(C._cache === A._cache).to.be.false expect(C._cache === PostResource._cache).to.be.false }) it('gets properties correctly (async)', async () => { // This post should already be cached by this point let comment = await CommentResource.detail('90') // Make sure resolveAttribute works let userName = await comment.resolveAttribute('post.user.name') // Also make sure getAsync is an alias of resolveAttribute let userEmail = await comment.getAsync('post.user.email') expect(userName).to.equal('Ervin Howell') expect(userEmail).to.equal('Shanna@melissa.tv') expect(await comment.resolveAttribute('post.user.propDoesNotExist')).to.be.undefined try { await comment.resolveAttribute('post.user.nested.propDoesNotExist') } catch (e) { expect(e.name).to.equal('ImproperlyConfiguredError') } }) it('caching can be turned off and on again', async () => { PostResource.cacheMaxAge = -1 PostResource.clearCache() await PostResource.detail('1') expect(PostResource.client.requestTracker[PostResource.getDetailRoutePath('1')]).to.equal(2) await PostResource.detail('1') expect(PostResource.client.requestTracker[PostResource.getDetailRoutePath('1')]).to.equal(3) await PostResource.detail('1') expect(PostResource.client.requestTracker[PostResource.getDetailRoutePath('1')]).to.equal(4) // Turn cache back on PostResource.cacheMaxAge = Infinity // At this point, the above resources aren't being cached, so one more request to the server (5 so far) await PostResource.detail('1') expect(PostResource.client.requestTracker[PostResource.getDetailRoutePath('1')]).to.equal(5) // Now the resource should be cached (still 5) await PostResource.detail('1') expect(PostResource.client.requestTracker[PostResource.getDetailRoutePath('1')]).to.equal(5) }) it('cross-relating resources reference single resource by cache key', async () => { let group = await GroupResource.detail('1', { resolveRelatedDeep: true }) // ...At this point, group has a cached user (ID 1) let user = await UserResource.detail('1', { resolveRelatedDeep: true }) // And getting the user again will yield the same exact user in memory stored at cache[cacheKey] address expect(group.managers.users.resources[0] === user).to.be.true }) it('handles empty values correctly', async () => { // Custom group resource const CustomGroupResource = BaseTestingResource.extend({ endpoint: '/groups', related: { todos: TodoResource, users: UserResource, owner: UserResource, }, }) // ...that is created with empty lists and some emptyish values on related field const someGroup = new CustomGroupResource({ name: 'Test Group', // This is what we're testing users: [], // empty list owner: null, // null todos: undefined, }) expect(someGroup.get('owner')).to.be.null expect(someGroup.get('users')).to.be.instanceOf(CustomGroupResource.RelatedManagerClass) expect(someGroup.get('users').resources).to.be.empty expect(someGroup.get('todos')).to.be.undefined }) it('correctly lists remote resources', async () => { const PostResourceDupe = PostResource.extend({}) let result = await PostResourceDupe.list() result.resources.forEach((post) => { expect(post instanceof PostResourceDupe).to.be.true expect(post.id).to.exist }) }) it('calls relative list routes correctly', async () => { let filteredPostResult = await PostResource.wrap('/1', { user: 1 }).get() expect(filteredPostResult.config.method.toLowerCase()).to.equal('get') expect(filteredPostResult.config.url).to.equal('/posts/1?user=1') let optionsResult = await PostResource.wrap('/1', { user: 1 }).get({ headers: { 'X-Taco': true } }) expect(optionsResult.config.headers['X-Taco']).to.be.true try { await PostResource.wrap('/does_not_____exist', { user: 1 }).post({ someBody: true }) } catch(e) { expect(String(e.response.status)).to.equal('404') expect(e.config.method.toLowerCase()).to.equal('post') expect(e.config.url).to.equal('/posts/does_not_____exist?user=1') expect(JSON.parse(e.config.data)).to.eql({ someBody: true }) } try { await PostResource.wrap('does_not_start_with_a_/').post() } catch(e) { expect(e.name).to.contain('AssertionError') } }) it('calls relative detail routes correctly', async () => { let post = await PostResource.detail(1) let postResult = await post.wrap('/comments').get() let data = postResult.data as any expect(data).to.exist expect(data[0].post).to.equal(1) try { // Remove ID and try to run post.attributes.id = undefined await post.wrap('/comments').get() } catch(e) { expect(e.name).to.contain('AssertionError') } }) it('can accept resource instances as value', async () => { let post = await PostResource.detail(80) let userDoesNotEqualPostUserId = post.attributes.user + 1 let otherUser = await UserResource.detail(userDoesNotEqualPostUserId) post.set('user', otherUser) // Normalization should be turned off for PostResource, so newly set user should be an object expect('object' === typeof post.attributes.user).to.be.true expect(post.attributes.user).to.eql(otherUser.toJSON()) expect(post.rel('user').canAutoResolve()).to.be.false }) })
the_stack
import * as vscode from 'vscode'; import * as cfg from '../configuration'; import * as util from '../utility'; import SourceDocument from '../SourceDocument'; import CSymbol from '../CSymbol'; import SubSymbol from '../SubSymbol'; import { ProposedPosition } from '../ProposedPosition'; import { showSingleQuickPick, showMultiQuickPick, MultiQuickPickOptions } from '../QuickPick'; import { createMatchingSourceFile } from './createSourceFile'; import { getMatchingHeaderSource, logger } from '../extension'; export const title = { currentFile: 'Add Definition in this file', matchingSourceFile: 'Add Definition in matching source file', multiple: 'Add Definitions...', constructorCurrentFile: 'Generate Constructor in this file', constructorMatchingSourceFile: 'Generate Constructor in matching source file' }; export const failure = { noActiveTextEditor: 'No active text editor detected.', noDocumentSymbol: 'No document symbol detected.', notHeaderFile: 'This file is not a header file.', noFunctionDeclaration: 'No function declaration detected.', noMatchingSourceFile: 'No matching source file was found.', hasUnspecializedTemplate: 'Unspecialized templates must be defined in the file that they are declared.', isConstexpr: 'Constexpr functions must be defined in the file that they are declared.', isConsteval: 'Consteval functions must be defined in the file that they are declared.', isInline: 'Inline functions must be defined in the file that they are declared.', definitionExists: 'A definition for this function already exists.', noUndefinedFunctions: 'No undefined functions found in this file.' }; export async function addDefinitionInSourceFile(): Promise<boolean | undefined> { const editor = vscode.window.activeTextEditor; if (!editor) { logger.alertError(failure.noActiveTextEditor); return; } const headerDoc = new SourceDocument(editor.document); if (!headerDoc.isHeader()) { logger.alertWarning(failure.notHeaderFile); return; } const [matchingUri, symbol] = await Promise.all([ getMatchingHeaderSource(headerDoc.uri), headerDoc.getSymbol(editor.selection.start) ]); if (!symbol?.isFunctionDeclaration()) { logger.alertWarning(failure.noFunctionDeclaration); return; } else if (!matchingUri) { logger.alertWarning(failure.noMatchingSourceFile); return; } else if (symbol.isInline()) { logger.alertInformation(failure.isInline); return; } else if (symbol.isConstexpr()) { logger.alertInformation(failure.isConstexpr); return; } else if (symbol.isConsteval()) { logger.alertInformation(failure.isConsteval); return; } else if (symbol.hasUnspecializedTemplate()) { logger.alertInformation(failure.hasUnspecializedTemplate); return; } return addDefinition(symbol, headerDoc, matchingUri); } export async function addDefinitionInCurrentFile(): Promise<boolean | undefined> { const editor = vscode.window.activeTextEditor; if (!editor) { logger.alertError(failure.noActiveTextEditor); return; } const sourceDoc = new SourceDocument(editor.document); const symbol = await sourceDoc.getSymbol(editor.selection.start); if (!symbol?.isFunctionDeclaration()) { logger.alertWarning(failure.noFunctionDeclaration); return; } return addDefinition(symbol, sourceDoc, sourceDoc.uri); } export async function addDefinition( functionDeclaration: CSymbol, declarationDoc: SourceDocument, targetUri: vscode.Uri, skipExistingDefinitionCheck?: boolean ): Promise<boolean | undefined> { if (!skipExistingDefinitionCheck) { const existingDefinition = await functionDeclaration.findDefinition(); if (existingDefinition) { if (!cfg.revealNewDefinition(declarationDoc)) { logger.alertInformation(failure.definitionExists); return; } const editor = await vscode.window.showTextDocument(existingDefinition.uri); editor.revealRange(existingDefinition.range, vscode.TextEditorRevealType.InCenter); return; } } const p_initializers = getInitializersIfFunctionIsConstructor(functionDeclaration); const targetDoc = (targetUri.fsPath === declarationDoc.uri.fsPath) ? declarationDoc : await SourceDocument.open(targetUri); const targetPos = await declarationDoc.findSmartPositionForFunctionDefinition(functionDeclaration, targetDoc); const functionSkeleton = await constructFunctionSkeleton( functionDeclaration, targetDoc, targetPos, p_initializers); if (functionSkeleton === undefined) { return; } const workspaceEdit = new vscode.WorkspaceEdit(); workspaceEdit.insert(targetDoc.uri, targetPos, functionSkeleton); const success = await vscode.workspace.applyEdit(workspaceEdit); if (success && cfg.revealNewDefinition(declarationDoc)) { await revealNewFunction(workspaceEdit, targetDoc); } return success; } export async function addDefinitions( sourceDoc?: SourceDocument, matchingUri?: vscode.Uri ): Promise<boolean | undefined> { if (!sourceDoc) { // Command was called from the command-palette const editor = vscode.window.activeTextEditor; if (!editor) { logger.alertError(failure.noActiveTextEditor); return; } sourceDoc = new SourceDocument(editor.document); matchingUri = await getMatchingHeaderSource(sourceDoc.uri); } const functionDeclarations: CSymbol[] = []; (await sourceDoc.allFunctions()).forEach(functionSymbol => { if (functionSymbol.isFunctionDeclaration()) { functionDeclarations.push(functionSymbol); } }); const undefinedFunctions = await findAllUndefinedFunctions(functionDeclarations); if (!undefinedFunctions) { return; } else if (undefinedFunctions.length === 0) { logger.alertInformation(failure.noUndefinedFunctions); return; } const selection = await promptUserForFunctionsAndTargetUri(undefinedFunctions, sourceDoc, matchingUri); if (!selection) { return; } const targetDoc = (selection.targetUri.fsPath === sourceDoc.uri.fsPath) ? sourceDoc : await SourceDocument.open(selection.targetUri); const workspaceEdit = await generateDefinitionsWorkspaceEdit(selection.functions, sourceDoc, targetDoc); if (!workspaceEdit) { return; } const success = await vscode.workspace.applyEdit(workspaceEdit); if (success && cfg.revealNewDefinition(sourceDoc)) { await revealNewFunction(workspaceEdit, targetDoc); } return success; } type Initializer = CSymbol | SubSymbol; interface InitializerItem extends vscode.QuickPickItem { initializer: Initializer; } async function getInitializersIfFunctionIsConstructor( functionDeclaration: CSymbol, token?: vscode.CancellationToken ): Promise<Initializer[] | undefined> { if (!functionDeclaration.isConstructor() || !functionDeclaration.parent?.isClassType()) { return []; } const parentClass = functionDeclaration.parent; const initializers: Initializer[] = []; if (parentClass.constructors().length > 1) { initializers.push(parentClass); } initializers.push(...parentClass.baseClasses(), ...parentClass.nonStaticMemberVariables()); if (initializers.length === 0) { return []; } const initializerItems: InitializerItem[] = []; initializers.forEach(initializer => { const initializerItem: InitializerItem = { label: '', initializer: initializer }; if (initializer === parentClass) { initializerItem.label = '$(symbol-class) ' + initializer.name; initializerItem.description = 'Delegating constructor (cannot be used with any other initializers)'; } else if (initializer instanceof SubSymbol) { initializerItem.label = '$(symbol-class) ' + initializer.text(); initializerItem.description = 'Base class constructor'; } else { initializerItem.label = '$(symbol-field) ' + initializer.name; initializerItem.description = util.formatSignature(initializer); } initializerItems.push(initializerItem); }); const selectedInitializers = await showInitializersQuickPick(initializerItems, functionDeclaration, parentClass, token); if (!selectedInitializers) { return; } parentClass.memberVariablesThatRequireInitialization().forEach(memberVariable => { if (!selectedInitializers.some(initializer => initializer.name === memberVariable.name)) { selectedInitializers.push(memberVariable); } }); selectedInitializers.sort(util.sortByRange); return selectedInitializers; } async function showInitializersQuickPick( initializerItems: InitializerItem[], ctorDeclaration: CSymbol, parentClass: CSymbol, token?: vscode.CancellationToken ): Promise<Initializer[] | undefined> { const options: MultiQuickPickOptions<InitializerItem> = { matchOnDescription: true, ignoreFocusOut: true, title: `Select initializers for "${util.formatSignature(ctorDeclaration)}"` }; if (initializerItems[0].initializer === parentClass) { let lastSelection: readonly InitializerItem[] = initializerItems.filter(item => item.picked); options.onDidChangeSelection = (selectedItems, quickPick) => { if ((lastSelection.length < initializerItems.length - 1 && selectedItems.length === initializerItems.length) || (lastSelection[0].initializer === parentClass && selectedItems.length > lastSelection.length) ) { selectedItems.shift(); quickPick.selectedItems = selectedItems; } else if (selectedItems.some(item => item.initializer === parentClass) && !lastSelection.some(item => item.initializer === parentClass)) { quickPick.selectedItems = [initializerItems[0]]; } lastSelection = quickPick.selectedItems; }; } const selectedItems = await showMultiQuickPick(initializerItems, options, token); return selectedItems?.map(item => item.initializer); } async function constructFunctionSkeleton( functionDeclaration: CSymbol, targetDoc: SourceDocument, position: ProposedPosition, p_initializers: Promise<Initializer[] | undefined> ): Promise<string | undefined> { const curlyBraceFormat = cfg.functionCurlyBraceFormat(targetDoc.languageId, targetDoc); const eol = targetDoc.endOfLine; const indentation = util.indentation(); const [definition, initializers] = await Promise.all([ functionDeclaration.newFunctionDefinition(targetDoc, position), p_initializers ]); if (initializers === undefined) { // Undefined only when the user cancels the QuickPick, so return. return; } const initializerList = constructInitializerList(initializers, eol); let functionSkeleton: string; if (curlyBraceFormat === cfg.CurlyBraceFormat.NewLine || (curlyBraceFormat === cfg.CurlyBraceFormat.NewLineCtorDtor && (functionDeclaration.isConstructor() || functionDeclaration.isDestructor()))) { // Opening brace on new line. functionSkeleton = definition + initializerList + eol + '{' + eol + indentation + eol + '}'; } else { // Opening brace on same line. functionSkeleton = definition + initializerList + ' {' + eol + indentation + eol + '}'; } return position.formatTextToInsert(functionSkeleton, targetDoc); } function constructInitializerList(initializers: Initializer[], eol: string): string { if (initializers.length === 0) { return ''; } const indentation = util.indentation(); const initializerBody = cfg.bracedInitialization(initializers[0].uri) ? '{},' : '(),'; let initializerList = eol + indentation + ': '; initializers.forEach(initializer => initializerList += initializer.name + initializerBody + eol + indentation + ' '); return initializerList.trimEnd().slice(0, -1); } export async function revealNewFunction(workspaceEdit: vscode.WorkspaceEdit, targetDoc: vscode.TextDocument): Promise<void> { const textEdits = workspaceEdit.get(targetDoc.uri); if (textEdits.length === 0) { return; } const editor = await vscode.window.showTextDocument(targetDoc); const firstEdit = textEdits[0]; const start = firstEdit.range.start; util.revealRange(editor, new vscode.Range(start, start.translate(util.lineCount(firstEdit.newText)))); const cursorPosition = targetDoc.validatePosition(getPositionForCursor(start, firstEdit.newText)); editor.selection = new vscode.Selection(cursorPosition, cursorPosition); } function getPositionForCursor(position: vscode.Position, functionSkeleton: string): vscode.Position { const lines = functionSkeleton.split('\n'); for (let i = 0; i < lines.length; ++i) { if (lines[i].trimStart().startsWith(':')) { // The function is a constructor, so we want to position the cursor in the first initializer. let index = lines[i].lastIndexOf(')'); if (index === -1) { index = lines[i].lastIndexOf('}'); if (index === -1) { return position; } } return new vscode.Position(i + position.line, index); } if (lines[i].trimEnd().endsWith('{')) { return new vscode.Position(i + 1 + position.line, lines[i + 1].length); } } return position; } /** * Returns the functionDeclarations that do not have a definition. * Returns undefined if the user cancels the operation. */ async function findAllUndefinedFunctions(functionDeclarations: CSymbol[]): Promise<CSymbol[] | undefined> { const undefinedFunctions: CSymbol[] = []; async function findDefinitionsForNextChunkOfFunctions(i: number): Promise<void> { const p_declarationDefinitionLinks: Promise<util.DeclarationDefinitionLink>[] = []; functionDeclarations.slice(i, i + 10).forEach(declaration => { p_declarationDefinitionLinks.push(util.makeDeclDefLink(declaration)); }); (await Promise.all(p_declarationDefinitionLinks)).forEach(link => { if (!link.definition) { undefinedFunctions.push(link.declaration); } }); } await findDefinitionsForNextChunkOfFunctions(0); if (functionDeclarations.length <= 10) { return undefinedFunctions; } const increment = (10 / functionDeclarations.length) * 100; let userCancelledOperation = false; await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'Finding undefined functions', cancellable: true }, async (progress, token) => { for (let i = 10; i < functionDeclarations.length; i += 10) { if (token.isCancellationRequested) { userCancelledOperation = true; return; } progress.report({ message: `${i}/${functionDeclarations.length} functions checked`, increment: increment }); await findDefinitionsForNextChunkOfFunctions(i); } progress.report({ message: `${functionDeclarations.length}/${functionDeclarations.length}`, increment: increment }); }); if (!userCancelledOperation) { return undefinedFunctions; } } type WorkspaceEditArguments = [vscode.Uri, vscode.Position, string]; interface WorkspaceEditArgumentsEntry { declaration: CSymbol; args: WorkspaceEditArguments; } export async function generateDefinitionsWorkspaceEdit( functionDeclarations: CSymbol[], declarationDoc: SourceDocument, targetDoc: SourceDocument ): Promise<vscode.WorkspaceEdit | undefined> { /* Since generating constructors requires additional user input, we must generate them * separately, one at a time. In order to insert them all in the same order that their * declarations appear in the file, we map the declarations to the WorkspaceEditArguments * and insert them all into the WorkspaceEdit at the end. */ const ctors: CSymbol[] = []; const nonCtors: CSymbol[] = []; functionDeclarations.forEach(declaration => { if (declaration.isConstructor()) { ctors.push(declaration); } else { nonCtors.push(declaration); } }); const allArgs = new WeakMap<CSymbol, WorkspaceEditArguments>(); async function generateNextChunkOfNonConstructors(i: number): Promise<void> { const p_argsEntries: Promise<WorkspaceEditArgumentsEntry | undefined>[] = []; nonCtors.slice(i, i + 5).forEach(declaration => { p_argsEntries.push(getWorkspaceEditArgumentsEntry(declaration, declarationDoc, targetDoc)); }); (await Promise.all(p_argsEntries)).forEach(entry => { if (entry) { allArgs.set(entry.declaration, entry.args); } }); } let userCancelledOperation = false; await vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'Generating function definitions', cancellable: true }, async (progress, token) => { progress.report({ message: `${0}/${functionDeclarations.length} generated`, increment: 0 }); const increment = (1 / functionDeclarations.length) * 100; let ctorsAdded = 0; let nonCtorAdded = 0; const p_generatedConstructors = (async (): Promise<void> => { for (const declaration of ctors) { const entry = await getWorkspaceEditArgumentsEntry(declaration, declarationDoc, targetDoc, token); if (entry) { allArgs.set(entry.declaration, entry.args); } else if (token.isCancellationRequested) { userCancelledOperation = true; return; } progress.report({ message: `${++ctorsAdded + nonCtorAdded}/${functionDeclarations.length} generated`, increment: increment }); } }) (); for (let i = 0; i < nonCtors.length; i += 5) { if (token.isCancellationRequested) { userCancelledOperation = true; return; } await generateNextChunkOfNonConstructors(i); nonCtorAdded = Math.min(i + 5, nonCtors.length); progress.report({ message: `${ctorsAdded + nonCtorAdded}/${functionDeclarations.length} generated`, increment: increment * (nonCtorAdded - i) }); } await p_generatedConstructors; }); if (userCancelledOperation) { return; } const workspaceEdit = new vscode.WorkspaceEdit(); functionDeclarations.forEach(declaration => { const args = allArgs.get(declaration); if (args) { workspaceEdit.insert(...args); } }); return workspaceEdit; } async function getWorkspaceEditArgumentsEntry( functionDeclaration: CSymbol, declarationDoc: SourceDocument, targetDoc: SourceDocument, token?: vscode.CancellationToken ): Promise<WorkspaceEditArgumentsEntry | undefined> { const p_initializers = getInitializersIfFunctionIsConstructor(functionDeclaration, token); const targetPos = await declarationDoc.findSmartPositionForFunctionDefinition(functionDeclaration, targetDoc); const functionSkeleton = await constructFunctionSkeleton( functionDeclaration, targetDoc, targetPos, p_initializers); if (functionSkeleton === undefined) { return; } return { declaration: functionDeclaration, args: [targetDoc.uri, targetPos, functionSkeleton] }; } interface FunctionsAndTargetUri { functions: CSymbol[]; targetUri: vscode.Uri; } async function promptUserForFunctionsAndTargetUri( undefinedFunctions: CSymbol[], sourceDoc: SourceDocument, matchingUri: vscode.Uri | undefined ): Promise<FunctionsAndTargetUri | undefined> { const p_selectedFunctions = promptUserToSelectFunctions(undefinedFunctions); const functionsThatRequireVisibleDefinition = undefinedFunctions.filter(declaration => { return util.requiresVisibleDefinition(declaration); }); const selectedFunctions = await p_selectedFunctions; if (!selectedFunctions || selectedFunctions.length === 0) { return; } if (!sourceDoc.isHeader() || util.arraysShareAnyElement(selectedFunctions, functionsThatRequireVisibleDefinition)) { return { functions: selectedFunctions, targetUri: sourceDoc.uri }; } interface DefinitionLocationItem extends vscode.QuickPickItem { uri?: vscode.Uri; } const locationItems: DefinitionLocationItem[] = []; if (matchingUri) { locationItems.push({ label: `Add Definitions to "${vscode.workspace.asRelativePath(matchingUri)}"`, uri: matchingUri }); } else { locationItems.push({ label: 'Add Definitions to a new source file' }); } locationItems.push({ label: 'Add Definitions to this file', uri: sourceDoc.uri }); let userTriggeredBackButton = false; const selectedItem = await showSingleQuickPick(locationItems, { ignoreFocusOut: true, title: 'Select which file to add the definitions to', buttons: [vscode.QuickInputButtons.Back], onDidTriggerButton: ((button, quickPick) => { if (button === vscode.QuickInputButtons.Back) { userTriggeredBackButton = true; quickPick.hide(); } }) }); if (userTriggeredBackButton) { return promptUserForFunctionsAndTargetUri(undefinedFunctions, sourceDoc, matchingUri); } else if (!selectedItem) { return; } const targetUri = selectedItem.uri ?? await createMatchingSourceFile(sourceDoc, true); if (!targetUri) { return; } return { functions: selectedFunctions, targetUri: targetUri }; } export async function promptUserToSelectFunctions(functionDeclarations: CSymbol[]): Promise<CSymbol[] | undefined> { interface FunctionItem extends vscode.QuickPickItem { declaration: CSymbol; } const functionItems: FunctionItem[] = functionDeclarations.map(declaration => { return { label: '$(symbol-function) ' + declaration.name, description: util.formatSignature(declaration), declaration: declaration }; }); const selectedItems = await showMultiQuickPick(functionItems, { matchOnDescription: true, ignoreFocusOut: true, title: 'Select the functions to add definitions for' }); return selectedItems?.map(item => item.declaration); }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_workorderproduct_Information { interface tab_f1tab_actualcost_Sections { tab_5_section_1: DevKit.Controls.Section; } interface tab_f1tab_actualqtysaleamt_Sections { f1tabgeneral_section_3: DevKit.Controls.Section; } interface tab_f1tab_estimateinfo_Sections { f1tab_estimateinfo_section_cost: DevKit.Controls.Section; tab_3_section_1: DevKit.Controls.Section; } interface tab_f1tab_general_Sections { _A490AE2A_B9CE_4B27_8103_C8D177EF9C0D: DevKit.Controls.Section; f1generaltab_section_2: DevKit.Controls.Section; f1generaltab_section_3: DevKit.Controls.Section; } interface tab_f1tab_other_Sections { tab_7_section_1: DevKit.Controls.Section; } interface tab_f1tab_relatedinfo_Sections { tab_4_section_1: DevKit.Controls.Section; } interface tab_f1tab_actualcost extends DevKit.Controls.ITab { Section: tab_f1tab_actualcost_Sections; } interface tab_f1tab_actualqtysaleamt extends DevKit.Controls.ITab { Section: tab_f1tab_actualqtysaleamt_Sections; } interface tab_f1tab_estimateinfo extends DevKit.Controls.ITab { Section: tab_f1tab_estimateinfo_Sections; } interface tab_f1tab_general extends DevKit.Controls.ITab { Section: tab_f1tab_general_Sections; } interface tab_f1tab_other extends DevKit.Controls.ITab { Section: tab_f1tab_other_Sections; } interface tab_f1tab_relatedinfo extends DevKit.Controls.ITab { Section: tab_f1tab_relatedinfo_Sections; } interface Tabs { f1tab_actualcost: tab_f1tab_actualcost; f1tab_actualqtysaleamt: tab_f1tab_actualqtysaleamt; f1tab_estimateinfo: tab_f1tab_estimateinfo; f1tab_general: tab_f1tab_general; f1tab_other: tab_f1tab_other; f1tab_relatedinfo: tab_f1tab_relatedinfo; } interface Body { Tab: Tabs; /** Enter any additional costs associated with this product. The values are manually entered. Note: additional cost is not unit dependent. */ msdyn_AdditionalCost: DevKit.Controls.Money; /** Agreement Booking Product linked to this Work Order Product */ msdyn_AgreementBookingProduct: DevKit.Controls.Lookup; msdyn_Allocated: DevKit.Controls.Boolean; /** The booking where this product was added */ msdyn_Booking: DevKit.Controls.Lookup; /** Enter the commission costs associated with this product. The value is manually specified and isn't automatically calculated. */ msdyn_CommissionCosts: DevKit.Controls.Money; /** Unique identifier for Customer Asset associated with Work Order Product. */ msdyn_CustomerAsset: DevKit.Controls.Lookup; /** Enter the description of the product as presented to the customer. The value defaults to the description defined on the product. */ msdyn_Description: DevKit.Controls.String; /** Choose whether to disable entitlement selection for this work order product. */ msdyn_DisableEntitlement: DevKit.Controls.Boolean; /** Specify any discount amount on this product. Note: If you enter a discount amount you cannot enter a discount % */ msdyn_DiscountAmount: DevKit.Controls.Money; /** Specify any discount % on this product. Note: If you enter a discount % it will overwrite the discount $ */ msdyn_DiscountPercent: DevKit.Controls.Double; /** Entitlement to apply to the Work Order Product. */ msdyn_Entitlement: DevKit.Controls.Lookup; /** Enter a discount amount on the subtotal amount. Note: If you enter a discount amount you cannot enter a discount % */ msdyn_EstimateDiscountAmount: DevKit.Controls.Money; /** Enter a discount % on the subtotal amount. Note: If you enter a discount % it will overwrite the discount $ */ msdyn_EstimateDiscountPercent: DevKit.Controls.Double; /** Enter the estimated required quantity of this product. */ msdyn_EstimateQuantity: DevKit.Controls.Double; /** Shows the total amount for this product, excluding discounts. */ msdyn_EstimateSubtotal: DevKit.Controls.Money; /** Shows the estimated total amount of this product, including discounts. */ msdyn_EstimateTotalAmount: DevKit.Controls.Money; /** Shows the estimated total cost of this product. */ msdyn_EstimateTotalCost: DevKit.Controls.Money; /** Shows the estimated sale amount per unit. */ msdyn_EstimateUnitAmount: DevKit.Controls.Money; /** Shows the estimated cost amount per unit. */ msdyn_EstimateUnitCost: DevKit.Controls.Money; /** Enter any internal notes you want to track on this product. */ msdyn_InternalDescription: DevKit.Controls.String; msdyn_LineOrder: DevKit.Controls.Integer; /** Enter the current status of the line, estimate or used. */ msdyn_LineStatus: DevKit.Controls.OptionSet; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Price List that determines the pricing for this product */ msdyn_PriceList: DevKit.Controls.Lookup; /** Product to use */ msdyn_Product: DevKit.Controls.Lookup; /** Purchase Order Receipt Product linked to this Work Order Product */ msdyn_PurchaseOrderReceiptProduct: DevKit.Controls.Lookup; /** Enter the quantity you wish to bill the customer for. By default, this will default to the same value as "Quantity." */ msdyn_QtyToBill: DevKit.Controls.Double; /** Shows the actual quantity of the product. */ msdyn_Quantity: DevKit.Controls.Double; /** Enter the total amount excluding discounts. */ msdyn_Subtotal: DevKit.Controls.Money; /** Specify if product is taxable. If you do not wish to charge tax set this field to No. */ msdyn_Taxable: DevKit.Controls.Boolean; /** Enter the total amount charged to the customer. */ msdyn_TotalAmount: DevKit.Controls.Money; /** Shows the total cost of this product. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs. */ msdyn_TotalCost: DevKit.Controls.Money; /** The unit that determines the pricing and final quantity for this product */ msdyn_Unit: DevKit.Controls.Lookup; /** Enter the amount you want to charge the customer per unit. By default, this is calculated based on the selected price list. The amount can be changed. */ msdyn_UnitAmount: DevKit.Controls.Money; /** Shows the actual cost per unit. */ msdyn_UnitCost: DevKit.Controls.Money; /** Warehouse this product is being retrieved from */ msdyn_Warehouse: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Work Order Product. */ msdyn_WorkOrder: DevKit.Controls.Lookup; /** The Incident related to this product */ msdyn_WorkOrderIncident: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Footer extends DevKit.Controls.IFooter { /** Status of the Work Order Product */ statecode: DevKit.Controls.OptionSet; } interface Navigation { nav_msdyn_msdyn_workorderproduct_msdyn_customerasset_WorkOrderProduct: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorderproduct_msdyn_inventoryjournal_WorkOrderProduct: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorderproduct_msdyn_rmaproduct_WOProduct: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorderproduct_msdyn_rtvproduct_WorkOrderProduct: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } } class Formmsdyn_workorderproduct_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_workorderproduct_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_workorderproduct_Information */ Body: DevKit.Formmsdyn_workorderproduct_Information.Body; /** The Footer section of form msdyn_workorderproduct_Information */ Footer: DevKit.Formmsdyn_workorderproduct_Information.Footer; /** The Navigation of form msdyn_workorderproduct_Information */ Navigation: DevKit.Formmsdyn_workorderproduct_Information.Navigation; } namespace FormWork_Order_Product_Mobile { interface tab_fstab_estimate_Sections { fstab_estimate_cost_amount: DevKit.Controls.Section; fstab_estimate_section_sale_amount: DevKit.Controls.Section; } interface tab_fstab_general_Sections { fstab_general_section_6: DevKit.Controls.Section; fstab_general_section_description: DevKit.Controls.Section; fstab_general_section_general: DevKit.Controls.Section; fstab_general_section_INVENTORY: DevKit.Controls.Section; fstab_general_section_misc: DevKit.Controls.Section; fstab_sub_grids_section: DevKit.Controls.Section; } interface tab_fstab_pricing_Sections { fstab_pricing_section_cost_amount: DevKit.Controls.Section; fstab_pricing_section_sale_amount: DevKit.Controls.Section; } interface tab_fstab_estimate extends DevKit.Controls.ITab { Section: tab_fstab_estimate_Sections; } interface tab_fstab_general extends DevKit.Controls.ITab { Section: tab_fstab_general_Sections; } interface tab_fstab_pricing extends DevKit.Controls.ITab { Section: tab_fstab_pricing_Sections; } interface Tabs { fstab_estimate: tab_fstab_estimate; fstab_general: tab_fstab_general; fstab_pricing: tab_fstab_pricing; } interface Body { Tab: Tabs; /** Enter any additional costs associated with this product. The values are manually entered. Note: additional cost is not unit dependent. */ msdyn_AdditionalCost: DevKit.Controls.Money; msdyn_Allocated: DevKit.Controls.Boolean; /** The booking where this product was added */ msdyn_Booking: DevKit.Controls.Lookup; /** Enter the commission costs associated with this product. The value is manually specified and isn't automatically calculated. */ msdyn_CommissionCosts: DevKit.Controls.Money; /** Unique identifier for Customer Asset associated with Work Order Product. */ msdyn_CustomerAsset: DevKit.Controls.Lookup; /** Enter the description of the product as presented to the customer. The value defaults to the description defined on the product. */ msdyn_Description: DevKit.Controls.String; /** Choose whether to disable entitlement selection for this work order product. */ msdyn_DisableEntitlement: DevKit.Controls.Boolean; /** Specify any discount amount on this product. Note: If you enter a discount amount you cannot enter a discount % */ msdyn_DiscountAmount: DevKit.Controls.Money; /** Specify any discount % on this product. Note: If you enter a discount % it will overwrite the discount $ */ msdyn_DiscountPercent: DevKit.Controls.Double; /** Entitlement to apply to the Work Order Product. */ msdyn_Entitlement: DevKit.Controls.Lookup; /** Enter a discount amount on the subtotal amount. Note: If you enter a discount amount you cannot enter a discount % */ msdyn_EstimateDiscountAmount: DevKit.Controls.Money; /** Enter a discount % on the subtotal amount. Note: If you enter a discount % it will overwrite the discount $ */ msdyn_EstimateDiscountPercent: DevKit.Controls.Double; /** Enter the estimated required quantity of this product. */ msdyn_EstimateQuantity: DevKit.Controls.Double; /** Shows the total amount for this product, excluding discounts. */ msdyn_EstimateSubtotal: DevKit.Controls.Money; /** Shows the estimated total amount of this product, including discounts. */ msdyn_EstimateTotalAmount: DevKit.Controls.Money; /** Shows the estimated total cost of this product. */ msdyn_EstimateTotalCost: DevKit.Controls.Money; /** Shows the estimated sale amount per unit. */ msdyn_EstimateUnitAmount: DevKit.Controls.Money; /** Shows the estimated cost amount per unit. */ msdyn_EstimateUnitCost: DevKit.Controls.Money; /** Enter any internal notes you want to track on this product. */ msdyn_InternalDescription: DevKit.Controls.String; msdyn_LineOrder: DevKit.Controls.Integer; /** Enter the current status of the line, estimate or used. */ msdyn_LineStatus: DevKit.Controls.OptionSet; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** Price List that determines the pricing for this product */ msdyn_PriceList: DevKit.Controls.Lookup; /** Product to use */ msdyn_Product: DevKit.Controls.Lookup; /** Purchase Order Receipt Product linked to this Work Order Product */ msdyn_PurchaseOrderReceiptProduct: DevKit.Controls.Lookup; /** Enter the quantity you wish to bill the customer for. By default, this will default to the same value as "Quantity." */ msdyn_QtyToBill: DevKit.Controls.Double; /** Shows the actual quantity of the product. */ msdyn_Quantity: DevKit.Controls.Double; /** Enter the total amount excluding discounts. */ msdyn_Subtotal: DevKit.Controls.Money; /** Specify if product is taxable. If you do not wish to charge tax set this field to No. */ msdyn_Taxable: DevKit.Controls.Boolean; /** Enter the total amount charged to the customer. */ msdyn_TotalAmount: DevKit.Controls.Money; /** Shows the total cost of this product. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs. */ msdyn_TotalCost: DevKit.Controls.Money; /** The unit that determines the pricing and final quantity for this product */ msdyn_Unit: DevKit.Controls.Lookup; /** Enter the amount you want to charge the customer per unit. By default, this is calculated based on the selected price list. The amount can be changed. */ msdyn_UnitAmount: DevKit.Controls.Money; /** Shows the actual cost per unit. */ msdyn_UnitCost: DevKit.Controls.Money; /** Warehouse this product is being retrieved from */ msdyn_Warehouse: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Work Order Product. */ msdyn_WorkOrder: DevKit.Controls.Lookup; /** The Incident related to this product */ msdyn_WorkOrderIncident: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_msdyn_msdyn_workorderproduct_invoicedetail: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorderproduct_msdyn_customerasset_WorkOrderProduct: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorderproduct_msdyn_inventoryjournal_WorkOrderProduct: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorderproduct_msdyn_rmaproduct_WOProduct: DevKit.Controls.NavigationItem, nav_msdyn_msdyn_workorderproduct_msdyn_rtvproduct_WorkOrderProduct: DevKit.Controls.NavigationItem, navAsyncOperations: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } } class FormWork_Order_Product_Mobile extends DevKit.IForm { /** * DynamicsCrm.DevKit form Work_Order_Product_Mobile * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Work_Order_Product_Mobile */ Body: DevKit.FormWork_Order_Product_Mobile.Body; /** The Navigation of form Work_Order_Product_Mobile */ Navigation: DevKit.FormWork_Order_Product_Mobile.Navigation; } class msdyn_workorderproductApi { /** * DynamicsCrm.DevKit msdyn_workorderproductApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Shows the sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Enter any additional costs associated with this product. The values are manually entered. Note: additional cost is not unit dependent. */ msdyn_AdditionalCost: DevKit.WebApi.MoneyValue; /** Shows the value of the additional cost in the base currency. */ msdyn_additionalcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Agreement Booking Product linked to this Work Order Product */ msdyn_AgreementBookingProduct: DevKit.WebApi.LookupValue; msdyn_Allocated: DevKit.WebApi.BooleanValue; /** The booking where this product was added */ msdyn_Booking: DevKit.WebApi.LookupValue; /** Enter the commission costs associated with this product. The value is manually specified and isn't automatically calculated. */ msdyn_CommissionCosts: DevKit.WebApi.MoneyValue; /** Shows the value of the commission costs in the base currency. */ msdyn_commissioncosts_Base: DevKit.WebApi.MoneyValueReadonly; /** Unique identifier for Customer Asset associated with Work Order Product. */ msdyn_CustomerAsset: DevKit.WebApi.LookupValue; /** Enter the description of the product as presented to the customer. The value defaults to the description defined on the product. */ msdyn_Description: DevKit.WebApi.StringValue; /** Choose whether to disable entitlement selection for this work order product. */ msdyn_DisableEntitlement: DevKit.WebApi.BooleanValue; /** Specify any discount amount on this product. Note: If you enter a discount amount you cannot enter a discount % */ msdyn_DiscountAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the discount amount in the base currency. */ msdyn_discountamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Specify any discount % on this product. Note: If you enter a discount % it will overwrite the discount $ */ msdyn_DiscountPercent: DevKit.WebApi.DoubleValue; /** Entitlement to apply to the Work Order Product. */ msdyn_Entitlement: DevKit.WebApi.LookupValue; /** Enter a discount amount on the subtotal amount. Note: If you enter a discount amount you cannot enter a discount % */ msdyn_EstimateDiscountAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the estimate discount amount in the base currency. */ msdyn_estimatediscountamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Enter a discount % on the subtotal amount. Note: If you enter a discount % it will overwrite the discount $ */ msdyn_EstimateDiscountPercent: DevKit.WebApi.DoubleValue; /** Enter the estimated required quantity of this product. */ msdyn_EstimateQuantity: DevKit.WebApi.DoubleValue; /** Shows the total amount for this product, excluding discounts. */ msdyn_EstimateSubtotal: DevKit.WebApi.MoneyValue; /** Shows the value of the estimate subtotal in the base currency. */ msdyn_estimatesubtotal_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the estimated total amount of this product, including discounts. */ msdyn_EstimateTotalAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the estimate total amount in the base currency. */ msdyn_estimatetotalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the estimated total cost of this product. */ msdyn_EstimateTotalCost: DevKit.WebApi.MoneyValue; /** Shows the value of the estimate total cost in the base currency. */ msdyn_estimatetotalcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the estimated sale amount per unit. */ msdyn_EstimateUnitAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the estimate unit amount in the base currency. */ msdyn_estimateunitamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the estimated cost amount per unit. */ msdyn_EstimateUnitCost: DevKit.WebApi.MoneyValue; /** Shows the value of the estimate unit cost in the base currency. */ msdyn_estimateunitcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Enter any internal notes you want to track on this product. */ msdyn_InternalDescription: DevKit.WebApi.StringValue; /** For internal use only. */ msdyn_InternalFlags: DevKit.WebApi.StringValue; msdyn_LineOrder: DevKit.WebApi.IntegerValue; /** Enter the current status of the line, estimate or used. */ msdyn_LineStatus: DevKit.WebApi.OptionSetValue; /** Enter the name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; /** Price List that determines the pricing for this product */ msdyn_PriceList: DevKit.WebApi.LookupValue; /** Product to use */ msdyn_Product: DevKit.WebApi.LookupValue; /** Purchase Order Receipt Product linked to this Work Order Product */ msdyn_PurchaseOrderReceiptProduct: DevKit.WebApi.LookupValue; /** Enter the quantity you wish to bill the customer for. By default, this will default to the same value as "Quantity." */ msdyn_QtyToBill: DevKit.WebApi.DoubleValue; /** Shows the actual quantity of the product. */ msdyn_Quantity: DevKit.WebApi.DoubleValue; /** Enter the total amount excluding discounts. */ msdyn_Subtotal: DevKit.WebApi.MoneyValue; /** Shows the value of the subtotal in the base currency. */ msdyn_subtotal_Base: DevKit.WebApi.MoneyValueReadonly; /** Specify if product is taxable. If you do not wish to charge tax set this field to No. */ msdyn_Taxable: DevKit.WebApi.BooleanValue; /** Enter the total amount charged to the customer. */ msdyn_TotalAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the total amount in the base currency. */ msdyn_totalamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the total cost of this product. This is calculated by (Unit Cost * Units) + Additional Cost + Commission Costs. */ msdyn_TotalCost: DevKit.WebApi.MoneyValue; /** Shows the value of the total cost in the base currency. */ msdyn_totalcost_Base: DevKit.WebApi.MoneyValueReadonly; /** The unit that determines the pricing and final quantity for this product */ msdyn_Unit: DevKit.WebApi.LookupValue; /** Enter the amount you want to charge the customer per unit. By default, this is calculated based on the selected price list. The amount can be changed. */ msdyn_UnitAmount: DevKit.WebApi.MoneyValue; /** Shows the value of the unit amount in the base currency. */ msdyn_unitamount_Base: DevKit.WebApi.MoneyValueReadonly; /** Shows the actual cost per unit. */ msdyn_UnitCost: DevKit.WebApi.MoneyValue; /** Shows the value of the unit cost in the base currency. */ msdyn_unitcost_Base: DevKit.WebApi.MoneyValueReadonly; /** Warehouse this product is being retrieved from */ msdyn_Warehouse: DevKit.WebApi.LookupValue; /** Unique identifier for Work Order associated with Work Order Product. */ msdyn_WorkOrder: DevKit.WebApi.LookupValue; /** The Incident related to this product */ msdyn_WorkOrderIncident: DevKit.WebApi.LookupValue; /** Shows the entity instances. */ msdyn_workorderproductId: DevKit.WebApi.GuidValue; /** Shows the date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the Work Order Product */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Work Order Product */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Shows the time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_workorderproduct { enum msdyn_LineStatus { /** 690970000 */ Estimated, /** 690970001 */ Used } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information','Work Order Product - Mobile'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import {AIO_NGINX_HOSTNAME} from '../common/env-variables'; import {computeShortSha} from '../common/utils'; import {ALT_SHA, BuildNums, PrNums, SHA} from './constants'; import {helper as h, makeCurl, payload} from './helper'; import {customMatchers} from './jasmine-custom-matchers'; // Tests h.runForAllSupportedSchemes((scheme, port) => describe(`integration (on ${scheme.toUpperCase()})`, () => { const hostname = AIO_NGINX_HOSTNAME; const host = `${hostname}:${port}`; const curlPrUpdated = makeCurl(`${scheme}://${host}/pr-updated`); const getFile = (pr: number, sha: string, file: string) => h.runCmd(`curl -iL ${scheme}://pr${pr}-${computeShortSha(sha)}.${host}/${file}`); const prUpdated = (prNum: number, action?: string) => curlPrUpdated({ data: { number: prNum, action } }); const circleBuild = makeCurl(`${scheme}://${host}/circle-build`); beforeEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; jasmine.addMatchers(customMatchers); }); afterEach(() => h.cleanUp()); describe('for a new/non-existing PR', () => { it('should be able to create and serve a public preview', async () => { const BUILD = BuildNums.TRUST_CHECK_ACTIVE_TRUSTED_USER; const PR = PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER; const regexPrefix = `^BUILD: ${BUILD} \\| PR: ${PR} \\| SHA: ${SHA} \\| File:`; const idxContentRegex = new RegExp(`${regexPrefix} \\/index\\.html$`); const barContentRegex = new RegExp(`${regexPrefix} \\/foo\\/bar\\.js$`); await circleBuild(payload(BUILD)).then(h.verifyResponse(201)); await Promise.all([ getFile(PR, SHA, 'index.html').then(h.verifyResponse(200, idxContentRegex)), getFile(PR, SHA, 'foo/bar.js').then(h.verifyResponse(200, barContentRegex)), ]); expect({ prNum: PR }).toExistAsABuild(); expect({ prNum: PR, isPublic: false }).not.toExistAsABuild(); }); it('should be able to create but not serve a hidden preview', async () => { const BUILD = BuildNums.TRUST_CHECK_UNTRUSTED; const PR = PrNums.TRUST_CHECK_UNTRUSTED; await circleBuild(payload(BUILD)).then(h.verifyResponse(202)); await Promise.all([ getFile(PR, SHA, 'index.html').then(h.verifyResponse(404)), getFile(PR, SHA, 'foo/bar.js').then(h.verifyResponse(404)), ]); expect({ prNum: PR }).not.toExistAsABuild(); expect({ prNum: PR, isPublic: false }).toExistAsABuild(); }); it('should reject if verification fails', async () => { const BUILD = BuildNums.TRUST_CHECK_ERROR; const PR = PrNums.TRUST_CHECK_ERROR; await circleBuild(payload(BUILD)).then(h.verifyResponse(500)); expect({ prNum: PR }).toExistAsAnArtifact(); expect({ prNum: PR }).not.toExistAsABuild(); expect({ prNum: PR, isPublic: false }).not.toExistAsABuild(); }); it('should be able to notify that a PR has been updated (and do nothing)', async () => { await prUpdated(PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER).then(h.verifyResponse(200)); // The PR should still not exist. expect({ prNum: PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, isPublic: false }).not.toExistAsABuild(); expect({ prNum: PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, isPublic: true }).not.toExistAsABuild(); }); }); describe('for an existing PR', () => { it('should be able to create and serve a public preview', async () => { const BUILD = BuildNums.TRUST_CHECK_ACTIVE_TRUSTED_USER; const PR = PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER; const regexPrefix1 = `^PR: ${PR} \\| SHA: ${ALT_SHA} \\| File:`; const idxContentRegex1 = new RegExp(`${regexPrefix1} \\/index\\.html$`); const barContentRegex1 = new RegExp(`${regexPrefix1} \\/foo\\/bar\\.js$`); const regexPrefix2 = `^BUILD: ${BUILD} \\| PR: ${PR} \\| SHA: ${SHA} \\| File:`; const idxContentRegex2 = new RegExp(`${regexPrefix2} \\/index\\.html$`); const barContentRegex2 = new RegExp(`${regexPrefix2} \\/foo\\/bar\\.js$`); h.createDummyBuild(PR, ALT_SHA); await circleBuild(payload(BUILD)).then(h.verifyResponse(201)); await Promise.all([ getFile(PR, ALT_SHA, 'index.html').then(h.verifyResponse(200, idxContentRegex1)), getFile(PR, ALT_SHA, 'foo/bar.js').then(h.verifyResponse(200, barContentRegex1)), getFile(PR, SHA, 'index.html').then(h.verifyResponse(200, idxContentRegex2)), getFile(PR, SHA, 'foo/bar.js').then(h.verifyResponse(200, barContentRegex2)), ]); expect({ prNum: PR, sha: SHA }).toExistAsABuild(); expect({ prNum: PR, sha: ALT_SHA }).toExistAsABuild(); }); it('should be able to create but not serve a hidden preview', async () => { const BUILD = BuildNums.TRUST_CHECK_UNTRUSTED; const PR = PrNums.TRUST_CHECK_UNTRUSTED; h.createDummyBuild(PR, ALT_SHA, false); await circleBuild(payload(BUILD)).then(h.verifyResponse(202)); await Promise.all([ getFile(PR, ALT_SHA, 'index.html').then(h.verifyResponse(404)), getFile(PR, ALT_SHA, 'foo/bar.js').then(h.verifyResponse(404)), getFile(PR, SHA, 'index.html').then(h.verifyResponse(404)), getFile(PR, SHA, 'foo/bar.js').then(h.verifyResponse(404)), ]); expect({ prNum: PR, sha: SHA }).not.toExistAsABuild(); expect({ prNum: PR, sha: SHA, isPublic: false }).toExistAsABuild(); expect({ prNum: PR, sha: ALT_SHA }).not.toExistAsABuild(); expect({ prNum: PR, sha: ALT_SHA, isPublic: false }).toExistAsABuild(); }); it('should reject if verification fails', async () => { const BUILD = BuildNums.TRUST_CHECK_ERROR; const PR = PrNums.TRUST_CHECK_ERROR; h.createDummyBuild(PR, ALT_SHA, false); await circleBuild(payload(BUILD)).then(h.verifyResponse(500)); expect({ prNum: PR }).toExistAsAnArtifact(); expect({ prNum: PR }).not.toExistAsABuild(); expect({ prNum: PR, isPublic: false }).not.toExistAsABuild(); expect({ prNum: PR, sha: ALT_SHA, isPublic: false }).toExistAsABuild(); }); it('should not be able to overwrite an existing public preview', async () => { const BUILD = BuildNums.TRUST_CHECK_ACTIVE_TRUSTED_USER; const PR = PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER; const regexPrefix = `^PR: ${PR} \\| SHA: ${SHA} \\| File:`; const idxContentRegex = new RegExp(`${regexPrefix} \\/index\\.html$`); const barContentRegex = new RegExp(`${regexPrefix} \\/foo\\/bar\\.js$`); h.createDummyBuild(PR, SHA); await circleBuild(payload(BUILD)).then(h.verifyResponse(409)); await Promise.all([ getFile(PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, SHA, 'index.html').then(h.verifyResponse(200, idxContentRegex)), getFile(PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, SHA, 'foo/bar.js').then(h.verifyResponse(200, barContentRegex)), ]); expect({ prNum: PR }).toExistAsAnArtifact(); expect({ prNum: PR }).toExistAsABuild(); }); it('should not be able to overwrite an existing hidden preview', async () => { const BUILD = BuildNums.TRUST_CHECK_UNTRUSTED; const PR = PrNums.TRUST_CHECK_UNTRUSTED; h.createDummyBuild(PR, SHA, false); await circleBuild(payload(BUILD)).then(h.verifyResponse(409)); expect({ prNum: PR }).toExistAsAnArtifact(); expect({ prNum: PR, isPublic: false }).toExistAsABuild(); }); it('should be able to request re-checking visibility (if outdated)', async () => { const publicPr = PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER; const hiddenPr = PrNums.TRUST_CHECK_UNTRUSTED; h.createDummyBuild(publicPr, SHA, false); h.createDummyBuild(hiddenPr, SHA, true); // PR visibilities are outdated (i.e. the opposte of what the should). expect({ prNum: publicPr, sha: SHA, isPublic: false }).toExistAsABuild(false); expect({ prNum: publicPr, sha: SHA, isPublic: true }).not.toExistAsABuild(false); expect({ prNum: hiddenPr, sha: SHA, isPublic: false }).not.toExistAsABuild(false); expect({ prNum: hiddenPr, sha: SHA, isPublic: true }).toExistAsABuild(false); await Promise.all([ prUpdated(publicPr).then(h.verifyResponse(200)), prUpdated(hiddenPr).then(h.verifyResponse(200)), ]); // PR visibilities should have been updated. expect({ prNum: publicPr, isPublic: false }).not.toExistAsABuild(); expect({ prNum: publicPr, isPublic: true }).toExistAsABuild(); expect({ prNum: hiddenPr, isPublic: false }).toExistAsABuild(); expect({ prNum: hiddenPr, isPublic: true }).not.toExistAsABuild(); }); it('should be able to request re-checking visibility (if up-to-date)', async () => { const publicPr = PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER; const hiddenPr = PrNums.TRUST_CHECK_UNTRUSTED; h.createDummyBuild(publicPr, SHA, true); h.createDummyBuild(hiddenPr, SHA, false); // PR visibilities are already up-to-date. expect({ prNum: publicPr, sha: SHA, isPublic: false }).not.toExistAsABuild(false); expect({ prNum: publicPr, sha: SHA, isPublic: true }).toExistAsABuild(false); expect({ prNum: hiddenPr, sha: SHA, isPublic: false }).toExistAsABuild(false); expect({ prNum: hiddenPr, sha: SHA, isPublic: true }).not.toExistAsABuild(false); await Promise.all([ prUpdated(publicPr).then(h.verifyResponse(200)), prUpdated(hiddenPr).then(h.verifyResponse(200)), ]); // PR visibilities are still up-to-date. expect({ prNum: publicPr, isPublic: true }).toExistAsABuild(); expect({ prNum: publicPr, isPublic: false }).not.toExistAsABuild(); expect({ prNum: hiddenPr, isPublic: true }).not.toExistAsABuild(); expect({ prNum: hiddenPr, isPublic: false }).toExistAsABuild(); }); it('should reject a request if re-checking visibility fails', async () => { const errorPr = PrNums.TRUST_CHECK_ERROR; h.createDummyBuild(errorPr, SHA, true); expect({ prNum: errorPr, isPublic: false }).not.toExistAsABuild(false); expect({ prNum: errorPr, isPublic: true }).toExistAsABuild(false); await prUpdated(errorPr).then(h.verifyResponse(500, /TRUST_CHECK_ERROR/)); // PR visibility should not have been updated. expect({ prNum: errorPr, isPublic: false }).not.toExistAsABuild(); expect({ prNum: errorPr, isPublic: true }).toExistAsABuild(); }); it('should reject a request if updating visibility fails', async () => { // One way to cause an error is to have both a public and a hidden directory for the same PR. h.createDummyBuild(PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, SHA, false); h.createDummyBuild(PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, SHA, true); const hiddenPrDir = h.getPrDir(PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, false); const publicPrDir = h.getPrDir(PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, true); const bodyRegex = new RegExp(`Request to move '${hiddenPrDir}' to existing directory '${publicPrDir}'`); expect({ prNum: PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, isPublic: false }).toExistAsABuild(false); expect({ prNum: PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, isPublic: true }).toExistAsABuild(false); await prUpdated(PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER).then(h.verifyResponse(409, bodyRegex)); // PR visibility should not have been updated. expect({ prNum: PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, isPublic: false }).toExistAsABuild(); expect({ prNum: PrNums.TRUST_CHECK_ACTIVE_TRUSTED_USER, isPublic: true }).toExistAsABuild(); }); }); }));
the_stack
import * as vscode from 'vscode'; import { Utils } from 'vscode-uri'; import { FileSystem, Output, JsonValidator } from '../../utils'; import { SchematicJsonSchema, SchematicOptionJsonSchema } from './json-schemas'; export class Schematic { optionsChoices: vscode.QuickPickItem[] = []; private name: string; private collectionName: string; private options = new Map<string, SchematicOptionJsonSchema>(); private requiredOptionsNames: string[] = []; constructor(name: string, collectionName: string) { this.name = name; this.collectionName = collectionName; } /** * Load the schematic. * **Must** be called after each `new Schematic()` * (delegated because `async` is not possible on a constructor). */ async init({ uri, collectionUri }: { uri?: vscode.Uri | undefined; collectionUri?: vscode.Uri | undefined; }): Promise<void> { /* Schematics extended from another collection needs to get back the schema path */ if (!uri) { if (!collectionUri) { throw new Error(`"${this.collectionName}:${this.name}" schematic cannot be extended.`); } try { uri = await this.getUriFromCollection(collectionUri); } catch { throw new Error(`"${this.collectionName}:${this.name}" can not be extended.`); } } const unsafeConfig = await FileSystem.parseJsonFile(uri); if (!unsafeConfig) { throw new Error(`"${this.collectionName}:${this.name}" schematic cannot be loaded.`); } const config = this.validateConfig(unsafeConfig); /* Set all options */ this.options = config.properties; Output.logInfo(`${this.options.size} options detected for "${this.name}" schematic: ${Array.from(this.options.keys()).join(', ')}`); this.initGlobalOptions(); this.requiredOptionsNames = this.initRequiredOptions(config); Output.logInfo(`${this.requiredOptionsNames.length} required option(s) detected for "${this.name}" schematic${this.requiredOptionsNames.length > 0 ? `: ${this.requiredOptionsNames.join(', ')}` : ``}`); this.optionsChoices = this.initOptionsChoices(config, this.requiredOptionsNames); } /** * Get schema's name without collection */ getName(): string { return this.name; } /** * Get options' details from their names */ getSomeOptions(names: string[]): Map<string, SchematicOptionJsonSchema> { return new Map(names .filter((name) => this.options.has(name)) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion .map((name) => [name, this.options.get(name)!]) ); } /** * Get required options details */ getRequiredOptions(): Map<string, SchematicOptionJsonSchema> { return new Map(this.requiredOptionsNames // eslint-disable-next-line @typescript-eslint/no-non-null-assertion .map((name) => [name, this.options.get(name)!]) ); } /** * Get the default value of an option, or `undefined`. */ getOptionDefaultValue(name: string): SchematicOptionJsonSchema['default'] { return this.options.get(name)?.default; } /** * Tells if an option exists in the schematic. */ hasOption(name: string): boolean { return this.options.has(name); } /** * Tells if the schematic requires a path/to/name as first command line argument */ hasNameAsFirstArg(): boolean { for (const [name, option] of this.options) { /* `argv[0]` means it is the first argument in command line after `ng g <some-schema>` */ if ((name === 'name') && (option.$default?.$source === 'argv') && (option.$default?.index === 0)) { return true; } } return false; } /** * Get the schema filesystem path. */ private async getUriFromCollection(collectionUri: vscode.Uri): Promise<vscode.Uri> { const collectionJsonConfig = await FileSystem.parseJsonFile(collectionUri); const schemaPath = JsonValidator.string(JsonValidator.object(JsonValidator.object(JsonValidator.object(collectionJsonConfig)?.['schematics'])?.[this.name])?.['schema']); /* `package.json` should have a `schematics` property with relative path to `collection.json` */ if (!schemaPath) { throw new Error(); } return vscode.Uri.joinPath(Utils.dirname(collectionUri), schemaPath); } /** * Validate schema.json */ private validateConfig(rawConfig: unknown): SchematicJsonSchema { const config = JsonValidator.object(rawConfig); const properties = new Map(Object.entries(JsonValidator.object(config?.['properties']) ?? {}) .map(([name, rawConfig]) => { const config = JsonValidator.object(rawConfig); const $default = JsonValidator.object(config?.['$default']); if ($default) { $default['$source'] = JsonValidator.string($default['$source']); $default['index'] = JsonValidator.number($default['index']); } let items = JsonValidator.object(config?.['items']); const xPromptString = JsonValidator.string(config?.['x-prompt']); const xPromptObject = JsonValidator.object(config?.['x-prompt']); if (items) { items['enum'] = this.validateConfigArrayChoices(JsonValidator.array(items['enum'])); } /** Deprecated, Angular >= 8.3 uses `items.enum` instead */ else if (xPromptObject) { const multiselect = JsonValidator.boolean(xPromptObject['multiselect']); if (multiselect === true) { items = {}; items['enum'] = this.validateConfigArrayChoices(JsonValidator.array(xPromptObject['items'])); } } return [name, { type: JsonValidator.string(config?.['type']), description: JsonValidator.string(config?.['description']), visible: JsonValidator.boolean(config?.['visible']), default: config?.['default'], $default, enum: this.validateConfigArrayChoices(JsonValidator.array(config?.['enum'])), items, ['x-deprecated']: JsonValidator.string(config?.['x-deprecated']), ['x-prompt']: xPromptString ?? JsonValidator.string(xPromptObject?.['message']), }] as [string, SchematicOptionJsonSchema]; })); return { properties, required: JsonValidator.array(config?.['required'], 'string'), }; } /** * Convert array of choices into strings for user input */ private validateConfigArrayChoices(list: unknown[] | undefined): string[] | undefined { if (list === undefined) { return undefined; } return list .map((item) => JsonValidator.string(item) ?? JsonValidator.number(item) ?? JsonValidator.boolean(item)) .map((item) => (item ?? '').toString()) .filter((item) => item); } /** * Add global CLI options */ private initGlobalOptions(): void { this.options.set('force', { type: 'boolean', default: false, description: `Forces overwriting of existing files.`, }); } /** * Initialize required options' names */ private initRequiredOptions(config: Pick<SchematicJsonSchema, 'required' | 'properties'>): string[] { /* Set required options' names */ return (config.required ?? []) /* Options which have a `$default` will be taken care by the CLI, so they are not required */ .filter((name) => (config.properties.get(name)?.$default === undefined)); } /** * Cache options choices */ private initOptionsChoices(config: Pick<SchematicJsonSchema, 'properties'>, requiredOptionsNames: string[]): vscode.QuickPickItem[] { const choices: vscode.QuickPickItem[] = []; const filteredOptionsNames = Array.from(config.properties) /* Project is already managed by the extension */ .filter(([name]) => (name !== 'project')) /* Do not keep options marked as not visible (internal options for the CLI) */ .filter(([, option]) => (option.visible !== false)) /* Do not keep deprecated options */ .filter(([, option]) => (option['x-deprecated'] === undefined)) /* Do not keep option already managed by first command line arg (name) */ .filter(([, option]) => !(option.$default && (option.$default.$source === 'argv') && (option.$default.index === 0))); for (const [label, option] of filteredOptionsNames) { let picked = false; /* UX: inform the user why some options are pre-select */ let requiredOrSuggestedInfo = ''; /* Do not pre-select options with defaults values, as the CLI will take care of them */ if (option.$default === undefined) { /* Required options */ if (requiredOptionsNames.includes(label)) { picked = true; requiredOrSuggestedInfo = `(required) `; } /* Suggested options (because they have a prompt) */ else if (option['x-prompt'] !== undefined) { picked = true; requiredOrSuggestedInfo = `(suggested) `; } } choices.push({ label, description: `${requiredOrSuggestedInfo}${option.description ?? ''}`, picked }); } /* Sort required first, then in alphabetical order */ const sortedPickedChoices = choices .filter((choice) => choice.picked) .sort((a, b) => a.label.localeCompare(b.label)); const sortedOptionalChoices = choices .filter((choice) => !choice.picked) .sort((a, b) => a.label.localeCompare(b.label)); /* Required and suggested options first */ return [...sortedPickedChoices, ...sortedOptionalChoices]; } }
the_stack
import * as React from "react"; import { Dispatch } from "redux"; import { connect, MapDispatchToProps } from "react-redux"; import IMlsClient, { IRunRequest, IWorkspaceRequest } from "../IMlsClient"; import IState, { IRunState, IWorkspace, IDiagnostic, ICompileState } from "../IState"; import DiagnosticsAdapter from "./DiagnosticsAdapter"; import InstrumentationAdapter from "./InstrumentationAdapter"; import * as monacoEditor from "monaco-editor"; import ReactMonacoEditor, { EditorDidMount, EditorWillMount } from "react-monaco-editor"; import actions from "../actionCreators/actions"; import deepEqual = require("deep-equal"); import { cloneWorkspace, setBufferContent } from "../workspaces"; import ICompletionItem from "../ICompletionItem"; import { CreateProjectFromGistRequest, CreateRegionsFromFilesRequest } from "../clientApiProtocol"; import { Subject, interval } from "rxjs"; import { debounce } from "rxjs/operators"; import { SupportedLanguages } from "../constants/supportedLanguages"; export interface IEditorProps { completionProvider?: string; editorDidMount?: EditorDidMount; editorWillMount?: EditorWillMount; editorOptions?: monacoEditor.editor.IEditorOptions; showEditor?: boolean; sourceCode?: string; sourceCodeDidChange?: (sourceCode: string, bufferId: string) => void; theme?: string; themes?: { [x: string]: monacoEditor.editor.IStandaloneThemeData }; client?: IMlsClient; showCompletions?: boolean; runState?: IRunState; compileState?: ICompileState; activeBufferId?: string; workspace?: IWorkspace; instrumentationEnabled?: boolean; updateDiagnostics?: (diagnostics: IDiagnostic[]) => void; editorLanguage?: SupportedLanguages; } export interface IEditorState { editor: monacoEditor.editor.IEditor; defineTheme: (name: string, value: monacoEditor.editor.IStandaloneThemeData) => void; setTheme: (t: string) => void; diagnosticsAdapter: DiagnosticsAdapter; instrumentationAdapter: InstrumentationAdapter; monacoModule: typeof monacoEditor; editorLanguage: SupportedLanguages; } export interface TextChangedEvent { text: string; position: number; } export class Editor extends React.Component<IEditorProps, IEditorState> { constructor(props: IEditorProps) { super(props); this.editorDidMount = this.editorDidMount.bind(this); this.editorWillMount = this.editorWillMount.bind(this); this.componentDidUpdate = this.componentDidUpdate.bind(this); this.defineThemes = this.defineThemes.bind(this); } private completionPosition: monacoEditor.Position; private completionItems: ICompletionItem[]; private contentChangedChannel: Subject<TextChangedEvent> = new Subject<TextChangedEvent>(); private editorWillMount: EditorWillMount = (monacoModule: typeof monacoEditor) => { let defineTheme = (name: string, theme: monacoEditor.editor.IStandaloneThemeData) => monacoModule.editor.defineTheme(name, theme); this.setState({ ...this.state, defineTheme: defineTheme, editorLanguage: this.props.editorLanguage }); this.defineThemes(defineTheme); this.props.editorWillMount(monacoModule); } private queueDiagnosticsUpdateRequest = (() => { if (this.state && this.state.editor && this.contentChangedChannel) { let model = this.state.editor.getModel() as monacoEditor.editor.ITextModel; if (model) { let text = model.getValue(); this.contentChangedChannel.next({ text: text ? text : "", position: 0 }); } } }).bind(this); private textChangedEventHandler = (async (event: TextChangedEvent) => { if (this.props && this.props.client && this.props.workspace) { let client = this.props.client; let workspace = cloneWorkspace(this.props.workspace); let activeBuffer = this.props.activeBufferId; setBufferContent(workspace, activeBuffer, event.text ? event.text : ""); let diagnosticsResult = await client.getDiagnostics(workspace, activeBuffer); this.setDiagnostics(diagnosticsResult.diagnostics); } }).bind(this); private editorDidMount: EditorDidMount = ( editor: monacoEditor.editor.IStandaloneCodeEditor, monacoModule: typeof monacoEditor) => { if (editor.onDidChangeModelContent) { editor.onDidChangeModelContent((e: monacoEditor.editor.IModelContentChangedEvent) => { if (e.changes.length === 1) { let change = e.changes[0]; if (this.completionPosition && this.completionPosition.column === change.range.startColumn && this.completionPosition.lineNumber === change.range.startLineNumber && this.completionItems) { let acceptedItem: ICompletionItem = this.completionItems.find((t) => t.insertText === change.text); if (acceptedItem) { this.props.client.acceptCompletionItem(acceptedItem); } } } }); } this.setState({ ...this.state, editorLanguage: this.props.editorLanguage, editor, setTheme: (t) => monacoModule.editor.setTheme(t), diagnosticsAdapter: new DiagnosticsAdapter(monacoModule, editor), instrumentationAdapter: new InstrumentationAdapter(editor), monacoModule: monacoModule }); if (this.props.showCompletions) { let language = this.props.editorLanguage; let monaco = monacoModule; let capturedEditor = this; this.setupLanguageServices(monaco, language, capturedEditor); } window.addEventListener("resize", () => editor.layout()); this.props.editorDidMount(editor, monacoModule); this.contentChangedChannel .pipe(debounce(() => interval(1000))) .subscribe((event) => this.textChangedEventHandler(event)); } private setupLanguageServices = (monaco: typeof monacoEditor, language: SupportedLanguages, capturedEditor: Editor) => { monaco.languages.registerCompletionItemProvider(language, { provideCompletionItems: async function ( model: monacoEditor.editor.ITextModel, position: monacoEditor.Position, _token: monacoEditor.CancellationToken, _context: monacoEditor.languages.CompletionContext) { capturedEditor.completionPosition = position; let client = capturedEditor.props.client; let workspace = cloneWorkspace(capturedEditor.props.workspace); let activeBuffer = capturedEditor.props.activeBufferId; setBufferContent(workspace, activeBuffer, model.getValue()); let completionResult = await client.getCompletionList( workspace, activeBuffer, model.getOffsetAt(position), capturedEditor.props.completionProvider); capturedEditor.completionItems = completionResult.items; capturedEditor.setDiagnostics(completionResult.diagnostics); return capturedEditor.completionItems; }, triggerCharacters: ["."] }); monaco.languages.registerSignatureHelpProvider(language, { provideSignatureHelp: async function ( model: monacoEditor.editor.ITextModel, position: monacoEditor.Position, _token: monacoEditor.CancellationToken) { let client = capturedEditor.props.client; let workspace = cloneWorkspace(capturedEditor.props.workspace); let activeBuffer = capturedEditor.props.activeBufferId; setBufferContent(workspace, activeBuffer, model.getValue()); let result = await client.getSignatureHelp(workspace, activeBuffer, model.getOffsetAt(position)); capturedEditor.setDiagnostics(result.diagnostics); return result; }, signatureHelpTriggerCharacters: ["("] } ); } private defineThemes = (defineTheme: (name: string, themeData: monacoEditor.editor.IStandaloneThemeData) => void) => { if (this.props.themes) { for (var name in this.props.themes) { if (defineTheme === null) { this.state.defineTheme(name, this.props.themes[name]); } else { defineTheme(name, this.props.themes[name]); } } } } public componentDidUpdate(oldProps: IEditorProps) { if (this.props.editorOptions) { if (oldProps.editorOptions !== this.props.editorOptions) { if (this.state && this.state.editor) { this.state.editor.updateOptions(this.props.editorOptions); } } } if (this.props.themes) { if (!oldProps.themes || !deepEqual(oldProps.themes, this.props.themes)) { if (this.state && this.state.defineTheme) { this.defineThemes(null); } } } if (this.props.theme) { if (oldProps.theme !== this.props.theme) { if (this.state && this.state.setTheme) { this.state.setTheme(this.props.theme); } } } let runState = this.props.runState; let compileState = this.props.compileState; let diagnostics: IDiagnostic[] = []; if (runState && runState.diagnostics && runState.diagnostics.length > 0) { diagnostics = runState.diagnostics; } else if (compileState && compileState.diagnostics && compileState.diagnostics.length > 0) { diagnostics = compileState.diagnostics; } this.setDiagnostics(diagnostics); const canShowInstrumentation = this.state && this.state.instrumentationAdapter && this.props.runState && this.props.runState.instrumentation; if (canShowInstrumentation) { this.state.instrumentationAdapter.setOrUpdateInstrumentation(oldProps, this.props, this.state); } const instrumentationEnabledFallingEdge = this.props && oldProps && oldProps.instrumentationEnabled && !this.props.instrumentationEnabled; if (instrumentationEnabledFallingEdge) { this.state.instrumentationAdapter.clearInstrumentation(); } if (this.props && oldProps && oldProps.workspace !== this.props.workspace) { this.queueDiagnosticsUpdateRequest(); } if (this.state && (this.props.editorLanguage !== oldProps.editorLanguage)) { this.setState({ ...this.state, editorLanguage: this.props.editorLanguage }); if (this.state && this.state.monacoModule && this.props.showCompletions) { let language = this.props.editorLanguage; let monaco = this.state.monacoModule; let capturedEditor = this; this.setupLanguageServices(monaco, language, capturedEditor); } } } private setDiagnostics = ((diagnostics: IDiagnostic[]): void => { let shouldUpdate = false; if (this.state && this.state.diagnosticsAdapter) { if (diagnostics && diagnostics.length > 0) { shouldUpdate = this.state.diagnosticsAdapter.setDiagnostics(diagnostics); } else { shouldUpdate = this.state.diagnosticsAdapter.clearDiagnostics(); } } if (shouldUpdate && this.props && this.props.updateDiagnostics) { this.props.updateDiagnostics(diagnostics); } }).bind(this); private onChange = ((newValue: any, _event: monacoEditor.editor.IModelContentChangedEvent) => { if (this.props.sourceCodeDidChange) { this.props.sourceCodeDidChange(newValue, this.props.activeBufferId); } if (this.state && this.state.instrumentationAdapter) { this.state.instrumentationAdapter.clearInstrumentation(); } let offset = 0; if (this.state && this.state.editor) { let model = this.state.editor.getModel() as monacoEditor.editor.ITextModel; if (model) { let pos = this.state.editor.getPosition(); offset = model.getOffsetAt(pos); } } this.contentChangedChannel.next({ text: newValue, position: offset }); //this.setDiagnostics([]); }).bind(this); public render() { return this.props.showEditor ? (<ReactMonacoEditor editorDidMount={this.editorDidMount} editorWillMount={this.editorWillMount} language={this.props.editorLanguage} options={this.props.editorOptions} onChange={this.onChange} value={this.props.sourceCode} /> ) : (<div></div>); } public static defaultProps: IEditorProps = { completionProvider: "", editorDidMount: (_editor: monacoEditor.editor.IEditor) => { }, editorWillMount: (_editor: typeof monacoEditor) => { }, editorOptions: { scrollBeyondLastLine: false }, showEditor: true, sourceCodeDidChange: (_sourceCode: string) => { }, client: { acceptCompletionItem: (_selection: ICompletionItem) => { throw Error(); }, getWorkspaceFromGist: async (_gistId: string, _workspaceType: string, _extractBuffers: boolean) => { throw Error(); }, getSourceCode: async (_request: IWorkspaceRequest) => { throw Error(); }, run: async (_args: IRunRequest) => { throw Error(); }, getCompletionList: async (_workspace: IWorkspace, _bufferId: string, _position: number, _completionProvider: string) => { throw Error(); }, getSignatureHelp: async (_workspace: IWorkspace, _bufferId: string, _position: number) => { throw Error(); }, compile: async (_args: IRunRequest) => { throw Error(); }, createProjectFromGist: (_request: CreateProjectFromGistRequest) => { throw Error(); }, createRegionsFromProjectFiles: (_request: CreateRegionsFromFilesRequest) => { throw Error(); }, getDiagnostics: (_workspace: IWorkspace, _bufferId: string) => { throw Error(); }, getConfiguration: () => { throw Error(); } }, showCompletions: true, activeBufferId: "Program.cs", editorLanguage: "csharp" }; } const mapStateToProps = (state: IState): IEditorProps => { var props: IEditorProps = { completionProvider: state.config.completionProvider, editorOptions: { ...state.monaco.editorOptions, scrollBeyondLastLine: false }, showEditor: state.ui.showEditor, sourceCode: state.monaco.displayedCode, theme: state.monaco.theme, themes: state.monaco.themes, client: state.config.client, showCompletions: state.config.version >= 2, runState: state.run, compileState: state.compile, activeBufferId: state.monaco.bufferId, workspace: state.workspace.workspace, instrumentationEnabled: state.workspace.workspace.includeInstrumentation, editorLanguage: state.monaco.language }; return props; }; const mapDispatchToProps: MapDispatchToProps<IEditorProps, IEditorProps> = (dispatch: Dispatch, _ownProps: IEditorProps): IEditorProps => { return ({ editorDidMount: (editor: monacoEditor.editor.IEditor) => dispatch(actions.notifyMonacoReady(editor)), sourceCodeDidChange: (sourceCode: string, bufferId: string) => { dispatch(actions.updateWorkspaceBuffer(sourceCode, bufferId)); }, updateDiagnostics: (diagnostics: IDiagnostic[]) => dispatch(actions.setDiagnostics(diagnostics)) }); }; export default connect(mapStateToProps, mapDispatchToProps)(Editor);
the_stack
import * as React from "react"; import { PropsWithChildren } from "react"; import * as ReactNativeScript from "react-nativescript"; import { NSVElement, FrameAttributes, PageAttributes } from "react-nativescript"; import { Page, Frame, NavigationButton } from "@nativescript/core"; import { DockLayoutTest, FlexboxLayoutTest, AbsoluteLayoutTest } from "./layout"; export class NestedHub extends React.Component<{ forwardedRef: React.RefObject<NSVElement<Page>>; } & PageAttributes, {}> { render() { const { forwardedRef, ...rest } = this.props; const greenPageRef = React.createRef<NSVElement<Page>>(); const redPageRef = React.createRef<NSVElement<Page>>(); return (<page ref={forwardedRef} actionBarHidden={false} {...rest}> <actionBar title="Hub" className="action-bar" /> <stackLayout> <button text={"Navigate to green page"} onTap={() => { const currentPage: Page = forwardedRef.current!.nativeView; currentPage.frame.navigate({ create: () => { return greenPageRef.current.nativeView; } }); }} /> </stackLayout> <PortalToPageWithActionBar forwardedRef={greenPageRef} actionBarTitle={"Green"} backgroundColor={"green"}> <stackLayout> <label>You're viewing the green page!</label> <button text={"Navigate to red page"} onTap={() => { const currentPage: Page = greenPageRef.current!.nativeView; currentPage.frame.navigate({ create: () => { return redPageRef.current.nativeView; } }); }} /> </stackLayout> </PortalToPageWithActionBar> <PortalToPageWithActionBar forwardedRef={redPageRef} actionBarTitle={"Red"} backgroundColor={"red"}> <stackLayout> <label>You're viewing the red page!</label> </stackLayout> </PortalToPageWithActionBar> </page>); } } export class NestedModalTest extends React.Component<{ forwardedRef: React.RefObject<NSVElement<Page>>; } & PageAttributes, {}> { render() { const { forwardedRef, ...rest } = this.props; const yellowPageRef = React.createRef<NSVElement<Page>>(); const greenPageRef = React.createRef<NSVElement<Page>>(); return (<page ref={forwardedRef} actionBarHidden={false} {...rest}> <actionBar title="Navigation Hub" className="action-bar" /> <stackLayout> <button text={"Open yellow modal"} onTap={() => { const currentPage: Page = forwardedRef.current!.nativeView; currentPage.showModal(yellowPageRef.current!.nativeView, { context: {}, closeCallback: () => { }, animated: true, stretched: false, }); }} /> </stackLayout> <PortalToPageWithActionBar forwardedRef={yellowPageRef} actionBarTitle={"Yellow page"} backgroundColor={"yellow"}> <stackLayout> <label>You're viewing the yellow page!</label> <button text={"Open green modal"} onTap={() => { const currentPage: Page = yellowPageRef.current!.nativeView; currentPage.showModal(greenPageRef.current!.nativeView, { context: {}, closeCallback: () => { }, animated: true, stretched: false, }); }} /> <button text={"Close yellow modal"} onTap={() => { const currentPage: Page = yellowPageRef.current!.nativeView; currentPage.closeModal({}); }} /> </stackLayout> </PortalToPageWithActionBar> <PortalToPageWithActionBar forwardedRef={greenPageRef} actionBarTitle={"Green page"} backgroundColor={"green"}> <stackLayout> <label>You're viewing the green page!</label> <button text={"Close green modal"} onTap={() => { const currentPage: Page = greenPageRef.current!.nativeView; currentPage.closeModal({}); }} /> </stackLayout> </PortalToPageWithActionBar> </page>); } } export class ActionBarTest extends React.Component<{}, {}> { render(){ const navigationButton = new NavigationButton(); navigationButton.text = "Go Back"; return React.createElement( "actionBar", { navigationButton, // color: new Color("red"), // backgroundColor: new Color("blue"), }, null ); } } export class TabViewTest extends React.Component<{}, {}> { render(){ return React.createElement( "tabView", { selectedIndex: 1 }, React.createElement( "tabViewItem", { title: "Dock", }, React.createElement( DockLayoutTest, {}, null ) ), React.createElement( "tabViewItem", { title: "Flexbox", }, React.createElement( FlexboxLayoutTest, {}, null ) ), // React.createElement( // ReactTabViewItem, // { // title: "Clock", // }, // React.createElement( // Clock, // {}, // null // ) // ), // React.createElement( // ReactTabViewItem, // { // title: "Marquee", // }, // React.createElement( // GameLoopComponent, // { // frameRateMs: 1000, // }, // React.createElement( // Marquee, // { // text: "Have you ever seen a game-looped Marquee before?" // }, // null // ) // ) // ), ); } } export class PageWithActionBar extends React.Component< { actionBarTitle?: string, forwardedRef: React.RefObject<NSVElement<Page>>, } & PageAttributes, {} > { render(){ const { children, forwardedRef, actionBarTitle, ...rest } = this.props; return ( <page ref={forwardedRef} actionBarHidden={false} {...rest} > <actionBar {...{ title: actionBarTitle }} /> {children} </page> ); } } export function FrameWithPageWithActionBarNew(props: PropsWithChildren<PageAttributes>){ const { children, ...rest } = props; return ( // Page expected to be auto-mounted by the Frame in the new React NativeScript. <frame> <PageWithActionBarNew> <label>Hello Page</label> </PageWithActionBarNew> </frame> ); } export function PageWithActionBarNew(props: PropsWithChildren<PageAttributes>){ const { children, ...rest } = props; return ( <page actionBarHidden={false} {...rest}> <actionBar> <label nodeRole={"titleView"}>Hello Title View</label> <actionItem nodeRole={"actionItems"}> <button nodeRole={"actionView"}>One</button> </actionItem> <actionItem nodeRole={"actionItems"}> <button nodeRole={"actionView"}>Two</button> </actionItem> <actionItem nodeRole={"actionItems"}> <button nodeRole={"actionView"}>Three</button> </actionItem> </actionBar> {children} </page> ); } export class PageWithComplexActionBarTest extends React.Component< { actionBarTitle?: string, forwardedRef: React.RefObject<NSVElement<Page>>, }, {} > { render(){ const { children, forwardedRef, ...rest } = this.props; return ( <page ref={forwardedRef} actionBarHidden={false} {...rest} > <actionBar> {/* The Switch will become the titleView */} <switch/> {/* The ActionItem will be added to the actionItems array */} <actionItem text={"AI"} ios={{ position: "right" as const, systemIcon: 4 }}></actionItem> {/* The NavigationButton will set as the NavigationButton (but won't be visible because there's no backwards navigation to do from here). */} <navigationButton text={"NB"}></navigationButton> </actionBar> {children} </page> ); } } export class FramedPageWithComplexActionBarTest extends React.Component<{ forwardedRef: React.RefObject<NSVElement<Frame>> }, {}> { private readonly pageWithActionBarRef = React.createRef<NSVElement<Page>>(); render(){ const { forwardedRef, children, ...rest } = this.props; return ( <FramedChildTest forwardedRef={forwardedRef} childPageRef={this.pageWithActionBarRef} {...rest} > <PageWithComplexActionBarTest forwardedRef={this.pageWithActionBarRef}> {children} </PageWithComplexActionBarTest> </FramedChildTest> ); } } const PortalToPage: React.SFC<{ forwardedRef: React.RefObject<NSVElement<Page>>, actionBarTitle: string }> = (props) => { const { forwardedRef, actionBarTitle, children } = props; return ReactNativeScript.createPortal( ( <PageWithActionBar forwardedRef={forwardedRef} actionBarTitle={actionBarTitle}> {children} </PageWithActionBar> ), null, `Portal('${actionBarTitle}')` ); } export class HubTest extends React.Component<{ forwardedRef: React.RefObject<NSVElement<Page>> }, {}> { private readonly absoluteLayoutPageRef = React.createRef<NSVElement<Page>>(); private readonly dockLayoutPageRef = React.createRef<NSVElement<Page>>(); private readonly flexboxLayoutPageRef = React.createRef<NSVElement<Page>>(); private navigateToPage(targetPage: Page, title: string){ const page: Page = this.props.forwardedRef.current!.nativeView; const frame: Frame|undefined = page.frame; if(!frame){ console.error(`No frame found for page ${page}. Ensure that HubTest is embedded in a Frame (e.g. via FramedHubTest).`); return; } frame.navigate({ create: () => { console.log(`Navigating from ${page} to ${title} page. Ref:`, targetPage); return targetPage; } }); } render(){ const { forwardedRef } = this.props; return ( <page ref={forwardedRef} actionBarHidden={false}> <actionBar title="Navigation Hub" className="action-bar" /> <stackLayout> <button text={"Navigate to AbsoluteLayout"} onTap={() => { this.navigateToPage(this.absoluteLayoutPageRef.current!.nativeView, "AbsoluteLayout"); }} /> <button text={"Navigate to DockLayout"} onTap={() => { this.navigateToPage(this.dockLayoutPageRef.current!.nativeView, "DockLayout"); }} /> <button text={"Navigate to FlexboxLayout"} onTap={() => { this.navigateToPage(this.flexboxLayoutPageRef.current!.nativeView, "FlexboxLayout"); }} /> </stackLayout> <PortalToPage forwardedRef={this.absoluteLayoutPageRef} actionBarTitle={"AbsoluteLayout"}> <AbsoluteLayoutTest/> </PortalToPage> <PortalToPage forwardedRef={this.dockLayoutPageRef} actionBarTitle={"DockLayout"}> <DockLayoutTest/> </PortalToPage> <PortalToPage forwardedRef={this.flexboxLayoutPageRef} actionBarTitle={"FlexboxLayout"}> <FlexboxLayoutTest/> </PortalToPage> </page> ); } } /** * MUST render the portal into a container (but only via a Host Config hack, as Pages can't have containers) or null. * * Rendering into forwardedRef.current mysteriously works on the first render, but only because forwardedRef.current * is null at first. On second render (due to a state change of any component within), forwardedRef.current will become * populated and thus cause this to break (because it's not a container of the root component; it IS the root component). * * ... So we render into null. This seems to work perfectly, but we'll probably have to add special-case handling in the * Host Config so that if the root component (Page) is ever unmounted, we don't call null.removeChild(). * * The converse case of outerparent.removeChild(null) (when we unmount the Portal) might not need special handling, * because null is not regarded as a ReactNode to begin with. */ export const PortalToPageWithActionBar: React.SFC< { forwardedRef: React.RefObject<NSVElement<Page>>, actionBarTitle: string } & PageAttributes > = (props) => { const { forwardedRef, actionBarTitle, children, ...rest } = props; console.log(`[PortalToPageWithActionBar - "${actionBarTitle}"] createPortal() forwardedRef.current: ${forwardedRef.current}`); return ReactNativeScript.createPortal( ( <page ref={forwardedRef} actionBarHidden={false} {...rest} > <actionBar title={actionBarTitle} className={"action-bar"}/> {children} </page> ), null, `Portal('${actionBarTitle}')` ); } /** * Above, we use a Stateless Functional Component. Here is the equivalent using a regular class component. * * We may find that a class component is necessary to provide the lifecycle methods to clean up upon unmount * (componentWillUnmount), but also... maybe not. * * An explicit shouldComponentUpdate() is purely there to help me follow the logs. It's not needed otherwise. */ export class StatefulPortalToPageWithActionBar extends React.Component< { forwardedRef: React.RefObject<NSVElement<Page>>, actionBarTitle: string } & PageAttributes, {} > { shouldComponentUpdate( nextProps: StatefulPortalToPageWithActionBar["props"], nextState: StatefulPortalToPageWithActionBar["state"] ): boolean { console.log(`[StatefulPortalToPageWithActionBar.shouldComponentUpdate]`); return true; } render(){ const { forwardedRef, actionBarTitle, children, ...rest } = this.props; console.log(`[StatefulPortalToPageWithActionBar - "${actionBarTitle}"] createPortal() forwardedRef.current: ${forwardedRef.current}`); return ReactNativeScript.createPortal( ( <page actionBarHidden={false} {...rest} ref={forwardedRef} > <actionBar title={actionBarTitle} className={"action-bar"}/> {children} </page> ), null, `Portal('${actionBarTitle}')` ); } } export class SimpleHub extends React.Component<{ forwardedRef: React.RefObject<NSVElement<Page>> } & PageAttributes, {}> { private readonly bluePageRef = React.createRef<NSVElement<Page>>(); render(){ const { forwardedRef, ...rest } = this.props; return ( <page ref={forwardedRef} actionBarHidden={false} {...rest}> <actionBar title="Navigation Hub" className="action-bar" /> <stackLayout> <button text={"Navigate to blue page"} onTap={() => { const currentPage: Page = forwardedRef.current!.nativeView; currentPage.frame.navigate({ create: () => { return this.bluePageRef.current.nativeView; } }); }} /> </stackLayout> <PortalToPageWithActionBar forwardedRef={this.bluePageRef} actionBarTitle={"Blue page"} backgroundColor={"blue"}> <label>You're viewing the blue page!</label> </PortalToPageWithActionBar> </page> ); } } export class FrameTest extends React.Component<{ forwardedRef: React.RefObject<NSVElement<Frame>> } & FrameAttributes, {}> { private readonly bluePageRef = React.createRef<NSVElement<Page>>(); componentDidMount(){ const node: Frame|null = this.props.forwardedRef.current.nativeView; if(node){ node.navigate({ create: () => { return this.bluePageRef.current.nativeView; } }); } else { console.warn(`React ref to NativeScript View lost, so unable to update event listeners.`); } } render(){ const { forwardedRef, ...rest } = this.props; return ( <frame ref={forwardedRef} {...rest}> <PortalToPageWithActionBar forwardedRef={this.bluePageRef} actionBarTitle={"Blue page"} backgroundColor={"blue"}> <label>You're viewing the blue page!</label> </PortalToPageWithActionBar> </frame> ); } } export class FramedChildTest extends React.Component< { forwardedRef: React.RefObject<NSVElement<Frame>>, childPageRef: React.RefObject<NSVElement<Page>>, }, {} > { componentDidMount(){ const node: Frame|null = this.props.forwardedRef.current.nativeView; if(!node){ console.warn(`[FramedChildTest] React ref to NativeScript View lost, so unable to update event listeners.`); return; } console.log(`[FramedChildTest] componentDidMount; shall navigate to page within.`); node.navigate({ create: () => { const childPage: Page|undefined = this.props.childPageRef.current!.nativeView; console.log(`[FramedChildTest] create(); shall return ref to page: ${childPage}`); return childPage; } }); } componentWillUnmount(){ console.log(`[FramedChildTest] componentWillUnmount`); } render(){ return ( <frame ref={this.props.forwardedRef}> {( ReactNativeScript.createPortal( ( this.props.children ), null, `Portal('FramedChild')` ) )} </frame> ); } } export class FramedHubTest extends React.Component<{ forwardedRef: React.RefObject<NSVElement<Frame>> }, {}> { private readonly hubTestPageRef = React.createRef<NSVElement<Page>>(); render(){ const { forwardedRef, children, ...rest } = this.props; return ( <FramedChildTest forwardedRef={forwardedRef} childPageRef={this.hubTestPageRef} {...rest} > <HubTest forwardedRef={this.hubTestPageRef}/> </FramedChildTest> ); } } export class FramedLayoutTest extends React.Component<{ forwardedRef: React.RefObject<NSVElement<Frame>> }, {}> { private readonly layoutTestPageRef = React.createRef<NSVElement<Page>>(); componentDidMount(){ const node: Frame|null = this.props.forwardedRef.current.nativeView; if(node){ node.navigate({ create: () => { return this.layoutTestPageRef.current.nativeView; } }); } else { console.warn(`React ref to NativeScript View lost, so unable to update event listeners.`); } } render(){ return ( <frame ref={this.props.forwardedRef}> {( ReactNativeScript.createPortal( ( <contentView ref={this.layoutTestPageRef}> <DockLayoutTest/> </contentView> ), null, `Portal('Dock Layout Test')` ) )} </frame> ); } }
the_stack
import { CodeAction, commands, ConfigurationScope, Diagnostic, Disposable, FileType, Position, QuickPickItem, QuickPickOptions, Range, Selection, TextDocument, TextEditorRevealType, Uri, window, workspace, WorkspaceEdit, } from 'vscode'; import { TextEdit } from 'vscode-languageclient/node'; import { ClientSideCommandHandlerApi, SpellCheckerSettingsProperties } from './client'; import * as di from './di'; import { extractMatchingDiagRanges, extractMatchingDiagTexts, getCSpellDiags } from './diags'; import * as Settings from './settings'; import { ConfigFields, ConfigTargetLegacy, ConfigurationTarget, createConfigFileRelativeToDocumentUri, getSettingFromVSConfig, normalizeTarget, setEnableSpellChecking, TargetsAndScopes, toggleEnableSpellChecker, } from './settings'; import { ClientConfigTarget } from './settings/clientConfigTarget'; import { ConfigRepository, createCSpellConfigRepository, createVSCodeConfigRepository } from './settings/configRepository'; import { configTargetToConfigRepo } from './settings/configRepositoryHelper'; import { createClientConfigTargetVSCode, createConfigTargetMatchPattern, dictionaryTargetBestMatches, dictionaryTargetBestMatchesCSpell, dictionaryTargetBestMatchesFolder, dictionaryTargetBestMatchesUser, dictionaryTargetBestMatchesVSCodeFolder as dtVSCodeFolder, dictionaryTargetBestMatchesVSCodeUser as dtVSCodeUser, dictionaryTargetBestMatchesVSCodeWorkspace as dtVSCodeWorkspace, dictionaryTargetBestMatchesWorkspace, filterClientConfigTargets, matchKindAll, matchScopeAll, MatchTargetsFn, patternMatchNoDictionaries, quickPickTarget, } from './settings/configTargetHelper'; import { normalizeWords } from './settings/CSpellSettings'; import { createDictionaryTargetForFile, DictionaryTarget } from './settings/DictionaryTarget'; import { mapConfigTargetToClientConfigTarget } from './settings/mappers/configTarget'; import { configurationTargetToClientConfigScope, configurationTargetToClientConfigScopeInfluenceRange, configurationTargetToDictionaryScope, dictionaryScopeToConfigurationTarget, } from './settings/targetAndScope'; import { catchErrors, handleErrors, ignoreError, OnErrorResolver } from './util/errors'; import { performance, toMilliseconds } from './util/perf'; import { scrollToText } from './util/textEditor'; import { toUri } from './util/uriHelper'; import { findMatchingDocument } from './vscode/findDocument'; const commandsFromServer: ClientSideCommandHandlerApi = { 'cSpell.addWordsToConfigFileFromServer': (words, _documentUri, config) => { return addWordsToConfig(words, createCSpellConfigRepository(toUri(config.uri), config.name)); }, 'cSpell.addWordsToDictionaryFileFromServer': (words, _documentUri, dict) => { return addWordsToDictionaryTarget(words, createDictionaryTargetForFile(toUri(dict.uri), dict.name)); }, 'cSpell.addWordsToVSCodeSettingsFromServer': (words, documentUri, target) => { const cfgTarget = dictionaryScopeToConfigurationTarget(target); const cfgRepo = createVSCodeConfigRepository(cfgTarget, toUri(documentUri), false); return addWordsToConfig(words, cfgRepo); }, }; type CommandHandler = { [key in string]: (...params: any[]) => void | Promise<void>; }; const prompt = onCommandUseDiagsSelectionOrPrompt; const tsFCfg = (configTarget: ConfigurationTarget, limitToTarget = false) => targetsAndScopeFromConfigurationTarget(configTarget, undefined, undefined, limitToTarget); const actionAddWordToFolder = prompt('Add Words to Folder Dictionary', addWordToFolderDictionary); const actionAddWordToWorkspace = prompt('Add Words to Workspace Dictionaries', addWordToWorkspaceDictionary); const actionAddWordToUser = prompt('Add Words to User Dictionary', addWordToUserDictionary); const actionAddWordToFolderSettings = prompt('Add Words to Folder Settings', fnWTarget(addWordToTarget, dtVSCodeFolder)); const actionAddWordToWorkspaceSettings = prompt('Add Words to Workspace Settings', fnWTarget(addWordToTarget, dtVSCodeWorkspace)); const actionAddWordToUserSettings = prompt('Add Words to User Settings', fnWTarget(addWordToTarget, dtVSCodeUser)); const actionRemoveWordFromFolderDictionary = prompt('Remove Words from Folder Dictionary', removeWordFromFolderDictionary); const actionRemoveWordFromWorkspaceDictionary = prompt('Remove Words from Workspace Dictionaries', removeWordFromWorkspaceDictionary); const actionRemoveWordFromUserDictionary = prompt('Remove Words from Global Dictionary', removeWordFromUserDictionary); const actionAddIgnoreWord = prompt('Ignore Words', fnWTarget(addIgnoreWordsToTarget, undefined)); const actionAddIgnoreWordToFolder = prompt( 'Ignore Words in Folder Settings', fnWTarget(addIgnoreWordsToTarget, ConfigurationTarget.WorkspaceFolder) ); const actionAddIgnoreWordToWorkspace = prompt( 'Ignore Words in Workspace Settings', fnWTarget(addIgnoreWordsToTarget, ConfigurationTarget.Workspace) ); const actionAddIgnoreWordToUser = prompt('Ignore Words in User Settings', fnWTarget(addIgnoreWordsToTarget, ConfigurationTarget.Global)); const actionAddWordToCSpell = prompt('Add Words to cSpell Configuration', fnWTarget(addWordToTarget, dictionaryTargetBestMatchesCSpell)); const actionAddWordToDictionary = prompt('Add Words to Dictionary', fnWTarget(addWordToTarget, dictionaryTargetBestMatches)); const commandHandlers: CommandHandler = { 'cSpell.addWordToDictionary': actionAddWordToDictionary, 'cSpell.addWordToFolderDictionary': actionAddWordToFolder, 'cSpell.addWordToWorkspaceDictionary': actionAddWordToWorkspace, 'cSpell.addWordToUserDictionary': actionAddWordToUser, 'cSpell.addWordToFolderSettings': actionAddWordToFolderSettings, 'cSpell.addWordToWorkspaceSettings': actionAddWordToWorkspaceSettings, 'cSpell.addWordToUserSettings': actionAddWordToUserSettings, 'cSpell.removeWordFromFolderDictionary': actionRemoveWordFromFolderDictionary, 'cSpell.removeWordFromWorkspaceDictionary': actionRemoveWordFromWorkspaceDictionary, 'cSpell.removeWordFromUserDictionary': actionRemoveWordFromUserDictionary, 'cSpell.addIgnoreWord': actionAddIgnoreWord, 'cSpell.addIgnoreWordsToFolder': actionAddIgnoreWordToFolder, 'cSpell.addIgnoreWordsToWorkspace': actionAddIgnoreWordToWorkspace, 'cSpell.addIgnoreWordsToUser': actionAddIgnoreWordToUser, 'cSpell.suggestSpellingCorrections': actionSuggestSpellingCorrections, 'cSpell.goToNextSpellingIssue': () => actionJumpToSpellingError('next', false), 'cSpell.goToPreviousSpellingIssue': () => actionJumpToSpellingError('previous', false), 'cSpell.goToNextSpellingIssueAndSuggest': () => actionJumpToSpellingError('next', true), 'cSpell.goToPreviousSpellingIssueAndSuggest': () => actionJumpToSpellingError('previous', true), 'cSpell.enableLanguage': enableLanguageIdCmd, 'cSpell.disableLanguage': disableLanguageIdCmd, 'cSpell.enableForGlobal': async () => setEnableSpellChecking(await tsFCfg(ConfigurationTarget.Global), true), 'cSpell.disableForGlobal': async () => setEnableSpellChecking(await tsFCfg(ConfigurationTarget.Global), false), 'cSpell.toggleEnableForGlobal': async () => toggleEnableSpellChecker(await tsFCfg(ConfigurationTarget.Global, true)), 'cSpell.enableForWorkspace': async () => setEnableSpellChecking(await tsFCfg(ConfigurationTarget.Workspace), true), 'cSpell.disableForWorkspace': async () => setEnableSpellChecking(await tsFCfg(ConfigurationTarget.Workspace), false), 'cSpell.toggleEnableForWorkspace': async () => toggleEnableSpellChecker(await tsFCfg(ConfigurationTarget.Workspace)), 'cSpell.toggleEnableSpellChecker': async () => toggleEnableSpellChecker(await tsFCfg(ConfigurationTarget.Global)), 'cSpell.enableCurrentLanguage': enableCurrentLanguage, 'cSpell.disableCurrentLanguage': disableCurrentLanguage, 'cSpell.editText': handlerApplyTextEdits(), 'cSpell.logPerfTimeline': dumpPerfTimeline, 'cSpell.addWordToCSpellConfig': actionAddWordToCSpell, 'cSpell.addIssuesToDictionary': addAllIssuesFromDocument, 'cSpell.createCustomDictionary': createCustomDictionary, 'cSpell.createCSpellConfig': createCSpellConfig, 'cSpell.openFileAtLine': openFileAtLine, }; function pVoid<T>(p: Promise<T> | Thenable<T>, context: string, onErrorHandler: OnErrorResolver = ignoreError): Promise<void> { const v = Promise.resolve(p).then(() => {}); return handleErrors(v, context, onErrorHandler); } // function notImplemented(cmd: string) { // return () => pVoid(window.showErrorMessage(`Not yet implemented "${cmd}"`)); // } const propertyFixSpellingWithRenameProvider: SpellCheckerSettingsProperties = 'fixSpellingWithRenameProvider'; function handlerApplyTextEdits() { return async function applyTextEdits(uri: string, documentVersion: number, edits: TextEdit[]): Promise<void> { const client = di.get('client').client; const textEditor = window.activeTextEditor; if (!textEditor || textEditor.document.uri.toString() !== uri) return; if (textEditor.document.version !== documentVersion) { return pVoid( window.showInformationMessage('Spelling changes are outdated and cannot be applied to the document.'), 'handlerApplyTextEdits' ); } const cfg = workspace.getConfiguration(Settings.sectionCSpell, textEditor.document); if (cfg.get(propertyFixSpellingWithRenameProvider) && edits.length === 1) { console.log(`${propertyFixSpellingWithRenameProvider} Enabled`); const edit = edits[0]; const range = client.protocol2CodeConverter.asRange(edit.range); if (await attemptRename(textEditor.document, range, edit.newText)) { return; } } return textEditor .edit((mutator) => { for (const edit of edits) { mutator.replace(client.protocol2CodeConverter.asRange(edit.range), edit.newText); } }) .then((success) => success ? undefined : pVoid(window.showErrorMessage('Failed to apply spelling changes to the document.'), 'handlerApplyTextEdits2') ); }; } async function attemptRename(document: TextDocument, range: Range, text: string): Promise<boolean> { if (range.start.line !== range.end.line) { return false; } const wordRange = document.getWordRangeAtPosition(range.start); if (!wordRange || !wordRange.contains(range)) { return false; } const orig = wordRange.start.character; const a = range.start.character - orig; const b = range.end.character - orig; const docText = document.getText(wordRange); const newText = [docText.slice(0, a), text, docText.slice(b)].join(''); try { const workspaceEdit = await commands .executeCommand('vscode.executeDocumentRenameProvider', document.uri, range.start, newText) .then( (a) => a as WorkspaceEdit | undefined, (reason) => (console.log(reason), false) ); return !!workspaceEdit && workspaceEdit.size > 0 && (await workspace.applyEdit(workspaceEdit)); } catch (e) { return false; } } function addWordsToConfig(words: string[], cfg: ConfigRepository) { return handleErrors(di.get('dictionaryHelper').addWordsToConfigRep(words, cfg), 'addWordsToConfig'); } function addWordsToDictionaryTarget(words: string[], dictTarget: DictionaryTarget) { return handleErrors(di.get('dictionaryHelper').addWordToDictionary(words, dictTarget), 'addWordsToDictionaryTarget'); } // function removeWordsFromConfig(words: string[], cfg: ConfigRepository) { // return handleErrors(di.get('dictionaryHelper').removeWordsFromConfigRep(words, cfg)); // } // function removeWordsFromDictionaryTarget(words: string[], dictTarget: DictionaryTarget) { // return handleErrors(di.get('dictionaryHelper').removeWordFromDictionary(words, dictTarget)); // } function registerCmd(cmd: string, fn: (...args: any[]) => any): Disposable { return commands.registerCommand(cmd, catchErrors(fn, `Register command: ${cmd}`)); } export function registerCommands(): Disposable[] { const registeredHandlers = Object.entries(commandHandlers).map(([cmd, fn]) => registerCmd(cmd, fn)); const registeredFromServer = Object.entries(commandsFromServer).map(([cmd, fn]) => registerCmd(cmd, fn)); return [...registeredHandlers, ...registeredFromServer]; } function addWordToFolderDictionary(word: string, docUri: string | null | Uri | undefined): Promise<void> { return addWordToTarget(word, dictionaryTargetBestMatchesFolder, docUri); } export function addWordToWorkspaceDictionary(word: string, docUri: string | null | Uri | undefined): Promise<void> { // eslint-disable-next-line prefer-rest-params console.log('addWordToWorkspaceDictionary %o', arguments); return addWordToTarget(word, dictionaryTargetBestMatchesWorkspace, docUri); } export function addWordToUserDictionary(word: string): Promise<void> { return addWordToTarget(word, dictionaryTargetBestMatchesUser, undefined); } function addWordToTarget(word: string, target: MatchTargetsFn, docUri: string | null | Uri | undefined) { return handleErrors(_addWordToTarget(word, target, docUri), 'addWordToTarget'); } function _addWordToTarget(word: string, target: MatchTargetsFn, docUri: string | null | Uri | undefined) { docUri = toUri(docUri); return di.get('dictionaryHelper').addWordsToTargets(word, target, docUri); } function addAllIssuesFromDocument(): Promise<void> { return handleErrors(di.get('dictionaryHelper').addIssuesToDictionary(), 'addAllIssuesFromDocument'); } function addIgnoreWordsToTarget( word: string, target: ConfigurationTarget | undefined, uri: string | null | Uri | undefined ): Promise<void> { return handleErrors(_addIgnoreWordsToTarget(word, target, uri), ctx('addIgnoreWordsToTarget', undefined, uri)); } async function _addIgnoreWordsToTarget( word: string, target: ConfigurationTarget | undefined, uri: string | null | Uri | undefined ): Promise<void> { uri = toUri(uri); const targets = await targetsForUri(uri); const filteredTargets = target ? targets.filter((t) => t.scope === configurationTargetToDictionaryScope(target)) : targets; return Settings.addIgnoreWordsToSettings(filteredTargets, word); } function removeWordFromFolderDictionary(word: string, uri: string | null | Uri | undefined): Promise<void> { return removeWordFromTarget(word, ConfigurationTarget.WorkspaceFolder, uri); } function removeWordFromWorkspaceDictionary(word: string, uri: string | null | Uri | undefined): Promise<void> { return removeWordFromTarget(word, ConfigurationTarget.Workspace, uri); } function removeWordFromUserDictionary(word: string): Promise<void> { return removeWordFromTarget(word, ConfigurationTarget.Global, undefined); } function removeWordFromTarget(word: string, target: ConfigurationTarget, uri: string | null | Uri | undefined) { return handleErrors(_removeWordFromTarget(word, target, uri), ctx('removeWordFromTarget', target, uri)); } function _removeWordFromTarget(word: string, cfgTarget: ConfigurationTarget, docUri: string | null | Uri | undefined) { docUri = toUri(docUri); const target = createClientConfigTargetVSCode(cfgTarget, docUri, undefined); return di.get('dictionaryHelper').removeWordsFromTargets(word, [target], docUri); } export function enableLanguageIdCmd(languageId: string, uri?: Uri | string): Promise<void> { return enableDisableLanguageId(languageId, toUri(uri), undefined, true); } export function disableLanguageIdCmd(languageId: string, uri?: string | Uri): Promise<void> { return enableDisableLanguageId(languageId, toUri(uri), undefined, false); } export function enableDisableLanguageId( languageId: string, uri: Uri | undefined, configTarget: ConfigurationTarget | undefined, enable: boolean ): Promise<void> { return handleErrors(async () => { const t = await (configTarget ? targetsFromConfigurationTarget(configTarget, uri) : targetsForUri(uri)); return Settings.enableLanguageIdForTarget(languageId, enable, t); }, ctx(`enableDisableLanguageId enable: ${enable}`, configTarget, uri)); } export function enableDisableLocale( locale: string, uri: Uri | undefined, configTarget: ConfigurationTarget | undefined, configScope: ConfigurationScope | undefined, enable: boolean ): Promise<void> { return handleErrors(async () => { const { targets, scopes } = await targetsAndScopeFromConfigurationTarget( configTarget || ConfigurationTarget.Global, uri, configScope ); return Settings.enableLocaleForTarget(locale, enable, targets, scopes); }, ctx(`enableDisableLocale enable: ${enable}`, configTarget, uri)); } export function enableDisableLocaleLegacy(target: ConfigTargetLegacy | boolean, locale: string, enable: boolean): Promise<void> { const _target = typeof target === 'boolean' ? (target ? ConfigurationTarget.Global : ConfigurationTarget.Workspace) : target; const t = normalizeTarget(_target); return enableDisableLocale(locale, t.uri, t.target, t.configScope, enable); } export function enableCurrentLanguage(): Promise<void> { return handleErrors(async () => { const document = window.activeTextEditor?.document; if (!document) return; const targets = await targetsForTextDocument(document); return Settings.enableLanguageId(targets, document.languageId); }, 'enableCurrentLanguage'); } export function disableCurrentLanguage(): Promise<void> { return handleErrors(async () => { const document = window.activeTextEditor?.document; if (!document) return; const targets = await targetsForTextDocument(document); return Settings.disableLanguageId(targets, document.languageId); }, 'disableCurrentLanguage'); } async function targetsAndScopeFromConfigurationTarget( cfgTarget: ConfigurationTarget, docUri?: string | null | Uri | undefined, configScope?: ConfigurationScope, cfgTargetIsExact?: boolean ): Promise<TargetsAndScopes> { const scopes = cfgTargetIsExact ? [configurationTargetToClientConfigScope(cfgTarget)] : configurationTargetToClientConfigScopeInfluenceRange(cfgTarget); const pattern = createConfigTargetMatchPattern(matchKindAll, matchScopeAll, { dictionary: false }); docUri = toUri(docUri); const targets = await (docUri ? targetsForUri(docUri, pattern) : targetsForTextDocument(window.activeTextEditor?.document, pattern)); return { targets: targets.map((t) => (t.kind === 'vscode' ? { ...t, configScope } : t)), scopes, }; } async function targetsFromConfigurationTarget( cfgTarget: ConfigurationTarget, docUri?: string | null | Uri | undefined, configScope?: ConfigurationScope ): Promise<ClientConfigTarget[]> { const r = await targetsAndScopeFromConfigurationTarget(cfgTarget, docUri, configScope); const { targets, scopes } = r; const allowedScopes = new Set(scopes); return targets.filter((t) => allowedScopes.has(t.scope)); } async function targetsForTextDocument( document: TextDocument | { uri: Uri; languageId?: string } | undefined, patternMatch = patternMatchNoDictionaries ) { const { uri, languageId } = document || {}; const config = await di.get('client').getConfigurationForDocument({ uri, languageId }); const targets = config.configTargets.map(mapConfigTargetToClientConfigTarget); return filterClientConfigTargets(targets, patternMatch); } async function targetsForUri(docUri?: string | null | Uri | undefined, patternMatch = patternMatchNoDictionaries) { docUri = toUri(docUri); const document = docUri ? await uriToTextDocInfo(docUri) : window.activeTextEditor?.document; return targetsForTextDocument(document, patternMatch); } async function uriToTextDocInfo(uri: Uri): Promise<{ uri: Uri; languageId?: string }> { const doc = findMatchingDocument(uri); if (doc) return doc; const fsStat = await workspace.fs.stat(uri); if (fsStat.type !== FileType.File) return { uri }; return await workspace.openTextDocument(uri); } const compareStrings = new Intl.Collator().compare; function onCommandUseDiagsSelectionOrPrompt( prompt: string, fnAction: (text: string, uri: Uri | undefined) => Promise<void> ): () => Promise<void> { return async function () { const document = window.activeTextEditor?.document; const selection = window.activeTextEditor?.selection; const range = selection && document?.getWordRangeAtPosition(selection.active); const diags = document ? getCSpellDiags(document.uri) : undefined; const matchingDiagWords = normalizeWords(extractMatchingDiagTexts(document, selection, diags) || []); if (matchingDiagWords.length) { const picked = selection?.anchor.isEqual(selection.active) && matchingDiagWords.length === 1 ? matchingDiagWords : await chooseWords(matchingDiagWords.sort(compareStrings), { title: prompt, placeHolder: 'Choose words' }); if (!picked) return; return fnAction(picked.join(' '), document?.uri); } if (!range || !selection || !document || !document.getText(range)) { const word = await window.showInputBox({ title: prompt, prompt }); if (!word) return; return fnAction(word, document?.uri); } const text = selection.contains(range) ? document.getText(selection) : document.getText(range); const words = normalizeWords(text); const picked = words.length > 1 ? await chooseWords(words.sort(compareStrings), { title: prompt, placeHolder: 'Choose words' }) : [await window.showInputBox({ title: prompt, prompt, value: words[0] })]; if (!picked) return; return fnAction(picked.join(' '), document?.uri); }; } async function chooseWords(words: string[], options: QuickPickOptions): Promise<string[] | undefined> { if (words.length <= 1) { const picked = await window.showInputBox({ ...options, value: words[0] }); if (!picked) return; return [picked]; } const items = words.map((label) => ({ label, picked: true })); const picked = await window.showQuickPick(items, { ...options, canPickMany: true }); return picked?.map((p) => p.label); } function ctx(method: string, target: ConfigurationTarget | undefined, uri: Uri | string | null | undefined): string { const scope = target ? configurationTargetToDictionaryScope(target) : ''; return scope ? `${method} ${scope} ${toUri(uri)}` : `${method} ${toUri(uri)}`; } interface SuggestionQuickPickItem extends QuickPickItem { _action: CodeAction; } async function actionSuggestSpellingCorrections(): Promise<void> { const document = window.activeTextEditor?.document; const selection = window.activeTextEditor?.selection; const range = selection && document?.getWordRangeAtPosition(selection.active); const diags = document ? getCSpellDiags(document.uri) : undefined; const matchingRanges = extractMatchingDiagRanges(document, selection, diags); const r = matchingRanges?.[0] || range; const matchingDiags = r && diags?.filter((d) => !!d.range.intersection(r)); if (!document || !selection || !r || !matchingDiags) { return pVoid(window.showInformationMessage('Nothing to suggest.'), 'actionSuggestSpellingCorrections'); } const menu = getSettingFromVSConfig(ConfigFields.suggestionMenuType, document); if (menu === 'quickFix') { return await commands.executeCommand('editor.action.quickFix'); } const actions = await di.get('client').requestSpellingSuggestions(document, r, matchingDiags); if (!actions || !actions.length) { return pVoid(window.showInformationMessage(`No Suggestions Found for ${document.getText(r)}`), 'actionSuggestSpellingCorrections'); } const items: SuggestionQuickPickItem[] = actions.map((a) => ({ label: a.title, _action: a })); const picked = await window.showQuickPick(items); if (picked && picked._action.command) { const { command: cmd, arguments: args = [] } = picked._action.command; commands.executeCommand(cmd, ...args); } } async function createCustomDictionary(): Promise<void> { const targets = await targetsForTextDocument(window.activeTextEditor?.document); const t = await quickPickTarget(targets); if (!t) return; const cfg = configTargetToConfigRepo(t); if (!cfg) return; await di.get('dictionaryHelper').createCustomDictionary(cfg); } function dumpPerfTimeline(): void { performance.getEntries().forEach((entry) => { console.log(entry.name, toMilliseconds(entry.startTime), entry.duration); }); } function fnWTarget<TT>( fn: (word: string, t: TT, uri: Uri | undefined) => Promise<void>, t: TT ): (word: string, uri: Uri | undefined) => Promise<void> { return (word, uri) => fn(word, t, uri); } async function createCSpellConfig(): Promise<void> { const uri = await createConfigFileRelativeToDocumentUri(window.activeTextEditor?.document.uri); if (uri) { const editor = await window.showTextDocument(uri); // for `package.json` files, we might need to scroll to the right position. scrollToText(editor, '"cspell":'); } } export const __testing__ = { commandHandlers, }; function nextDiags(diags: Diagnostic[], selection: Selection): Diagnostic | undefined { // concat next diags with the first diag to get a cycle return diags.filter((d) => d.range?.start.isAfter(selection.end)).concat(diags[0])[0]; } function previousDiags(diags: Diagnostic[], selection: Selection): Diagnostic | undefined { // concat the last diag with all previous diags to get a cycle return [diags[diags.length - 1]].concat(diags.filter((d) => d.range?.end.isBefore(selection.start))).pop(); } async function actionJumpToSpellingError(which: 'next' | 'previous', suggest: boolean) { const editor = window.activeTextEditor; if (!editor) return; const document = editor.document; const selection = editor.selection; const diags = document ? getCSpellDiags(document.uri) : undefined; const matchingDiags = diags ? (which === 'next' ? nextDiags(diags, selection) : previousDiags(diags, selection)) : undefined; const range = matchingDiags?.range; if (!document || !selection || !range || !matchingDiags) { return pVoid(window.showInformationMessage('No issues found in this document.'), 'actionJumpToSpellingError'); } editor.revealRange(range, TextEditorRevealType.InCenterIfOutsideViewport); editor.selection = new Selection(range.start, range.end); if (suggest) { return actionSuggestSpellingCorrections(); } } async function openFileAtLine(uri: string | Uri, line: number | undefined): Promise<void> { uri = toUri(uri); const options = (line && { selection: lineToRange(line), }) || undefined; await window.showTextDocument(uri, options); } function lineToRange(line: number | string | undefined) { if (line === undefined) return undefined; line = typeof line === 'string' ? Number.parseInt(line) : line; const pos = new Position(line - 1, 0); const range = new Range(pos, pos); return range; }
the_stack
import { ConnextToken } from "@connext/contracts"; import { Address, ContractAddresses, IChannelSigner, MessagingConfig, ContractAddressBook, AddressBook, AllowedSwap, PriceOracleTypes, NetworkContexts, JsonRpcProvider, } from "@connext/types"; import { ChannelSigner, getEthProvider } from "@connext/utils"; import { Injectable, OnModuleInit } from "@nestjs/common"; import { Wallet, Contract, providers, constants, utils, BigNumber } from "ethers"; import { DEFAULT_DECIMALS } from "../constants"; import { LoggerService } from "../logger/logger.service"; import { RebalanceProfile } from "../rebalanceProfile/rebalanceProfile.entity"; const { AddressZero, Zero } = constants; const { getAddress, parseEther } = utils; type PostgresConfig = { database: string; host: string; password: string; port: number; username: string; }; type MaxCollateralMap<T = string> = { [assetId: string]: T; }; @Injectable() export class ConfigService implements OnModuleInit { private readonly envConfig: { [key: string]: string }; // signer on same mnemonic, connected to different providers public readonly signers: Map<number, IChannelSigner> = new Map(); // keyed on chainId public readonly providers: Map<number, providers.JsonRpcProvider> = new Map(); constructor(private readonly log: LoggerService) { this.log.setContext("ConfigService"); this.envConfig = process.env as any; // NOTE: will be reassigned in module-init (WHICH NOTHING ACTUALLY WAITS FOR) const urls = this.getProviderUrls(); this.getSupportedChains().forEach((chainId, idx) => { const provider = getEthProvider(urls[idx], chainId); this.providers.set(chainId, provider); this.signers.set(chainId, new ChannelSigner(this.getPrivateKey(), provider)); this.log.info(`Registered new provider at url ${urls[idx]} & signer for chain ${chainId}`); }); } getAdminToken(): string { return this.get("INDRA_ADMIN_TOKEN"); } get(key: string): string { return this.envConfig[key]; } private getPrivateKey(): string { return Wallet.fromMnemonic(this.get(`INDRA_MNEMONIC`)).privateKey; } getSigner(chainId?: number): IChannelSigner { if (chainId) { const providers = this.getIndraChainProviders(); const provider = getEthProvider(providers[chainId], chainId); const signer = new ChannelSigner(this.getPrivateKey(), provider); return signer; } return new ChannelSigner(this.getPrivateKey()); } getProviderUrls(): string[] { // default to first option in env return Object.values(JSON.parse(this.get(`INDRA_CHAIN_PROVIDERS`))); } getEthProvider(chainId: number): providers.JsonRpcProvider | undefined { return this.providers.get(chainId); } getEthProviders(): providers.JsonRpcProvider[] { return Array.from(this.providers.values()); } getAddressBook(): AddressBook { return JSON.parse(this.get(`INDRA_CONTRACT_ADDRESSES`)); } getSupportedChains(): number[] { return ( Object.keys(JSON.parse(this.get("INDRA_CHAIN_PROVIDERS"))).map((k) => parseInt(k, 10)) || [] ); } getIndraChainProviders(): { [k: string]: string } { return JSON.parse(this.get("INDRA_CHAIN_PROVIDERS") || "{}"); } async getNetwork(chainId: number): Promise<providers.Network> { const provider = this.getEthProvider(chainId); if (!provider) { throw new Error(`Node is not configured for chain ${chainId}`); } const network = await provider.getNetwork(); network.chainId = chainId; // just in case we're using ganache which hardcodes it's chainId.. if (network.name === `unknown` && network.chainId === 1337) { network.name = `ganache`; } else if (network.chainId === 1) { network.name = `homestead`; } return network; } getContractAddresses(chainId: number): ContractAddresses { const ethAddresses = { [chainId]: {} } as any; const ethAddressBook = this.getAddressBook(); Object.keys(ethAddressBook[chainId]).forEach( (contract: string) => (ethAddresses[chainId][contract] = getAddress(ethAddressBook[chainId][contract].address)), ); return ethAddresses[chainId] as ContractAddresses; } async getTokenDecimals(chainId: number, providedAddress?: Address): Promise<number> { const address = providedAddress || (await this.getTokenAddress(chainId)); const tokenContract = new Contract(address, ConnextToken.abi, this.getSigner(chainId)); let decimals = DEFAULT_DECIMALS; try { decimals = await tokenContract.decimals(); } catch (e) { this.log.warn(`Could not retrieve decimals from token ${address}, using ${DEFAULT_DECIMALS}`); } return decimals; } getContractAddressBook(): ContractAddressBook { const ethAddresses = {}; const ethAddressBook = this.getAddressBook(); this.getSupportedChains().forEach((chainId) => { ethAddresses[chainId] = {}; Object.keys(ethAddressBook[chainId]).forEach((contractName) => { ethAddresses[chainId][contractName] = getAddress( ethAddressBook[chainId][contractName].address, ); }); }); return ethAddresses as ContractAddressBook; } getNetworkContexts(): NetworkContexts { const ethAddressBook = this.getAddressBook(); const supportedChains = this.getSupportedChains(); return supportedChains.reduce((contexts, chainId) => { contexts[chainId] = { contractAddresses: Object.keys(ethAddressBook[chainId]).reduce( (addresses, contractName) => { addresses[contractName] = getAddress(ethAddressBook[chainId][contractName].address); return addresses; }, {}, ), provider: this.getEthProvider(chainId), }; return contexts; }, {}); } getTokenAddress(chainId: number): string { const ethAddressBook = this.getAddressBook(); if (!ethAddressBook[chainId]) { throw new Error(`Chain ${chainId} is not supported`); } if (!ethAddressBook[chainId].Token) { throw new Error(`Chain ${chainId} does not contain any supported tokens`); } return getAddress(ethAddressBook[chainId].Token.address); } getAllowedSwaps(chainId: number): AllowedSwap[] { // configured tokens per chain in address book const addressBook = this.getAddressBook(); const chains = this.getSupportedChains(); const supportedTokens: { [chainId: number]: Address[] } = chains.reduce((tokens, chainId) => { if (!tokens[chainId]) { tokens[chainId] = [AddressZero]; } tokens[chainId].push(addressBook[chainId]?.Token?.address); return tokens; }, {}); if (!supportedTokens[chainId]) { this.log.warn(`There are no supported tokens for chain ${chainId}`); return []; } const priceOracleType = chainId.toString() === "1" ? PriceOracleTypes.UNISWAP : PriceOracleTypes.HARDCODED; let allowedSwaps: AllowedSwap[] = []; // allow token <> eth swaps per chain supportedTokens[chainId] .filter((token) => token !== AddressZero) .forEach((token) => { allowedSwaps.push({ from: token, to: AddressZero, priceOracleType, fromChainId: chainId, toChainId: chainId, }); allowedSwaps.push({ from: AddressZero, to: token, priceOracleType, fromChainId: chainId, toChainId: chainId, }); }); const extraSwaps: AllowedSwap[] = JSON.parse(this.get("INDRA_ALLOWED_SWAPS") || "[]"); allowedSwaps = allowedSwaps.concat( extraSwaps.map((swap) => { return { ...swap, fromChainId: parseInt(swap.fromChainId as any), toChainId: parseInt(swap.toChainId as any), }; }), ); return allowedSwaps; } getSupportedTokens(): { [chainId: number]: Address[] } { const addressBook = this.getAddressBook(); const chains = this.getSupportedChains(); const supportedTokens: { [chainId: number]: Address[] } = chains.reduce((tokens, chainId) => { if (!tokens[chainId]) { tokens[chainId] = [AddressZero]; } tokens[chainId].push(addressBook[chainId]?.Token?.address); return tokens; }, {}); const extraTokens: { [chainId: number]: Address[] } = JSON.parse( this.get("INDRA_SUPPORTED_TOKENS") || "{}", ); Object.keys(extraTokens).forEach((chainId) => { if (!supportedTokens[chainId]) { throw new Error(`Unsupported chainId in INDRA_SUPPORTED_TOKENS: ${chainId}`); } supportedTokens[chainId] = supportedTokens[chainId].concat(extraTokens[chainId]); }); return supportedTokens; } async getHardcodedRate(from: string, to: string): Promise<string | undefined> { if (from === AddressZero && to !== AddressZero) { return "100.0"; } if (from !== AddressZero && to === AddressZero) { return "0.01"; } return "1"; } // NOTE: assumes same signer accross chains getPublicIdentifier(): string { const [signer] = [...this.signers.values()]; return signer.publicIdentifier; } // NOTE: assumes same signer accross chains async getSignerAddress(): Promise<string> { const [signer] = [...this.signers.values()]; return signer.getAddress(); } getLogLevel(): number { return parseInt(this.get(`INDRA_LOG_LEVEL`) || `3`, 10); } isDevMode(): boolean { return this.get(`NODE_ENV`) !== `production`; } getMessagingConfig(): MessagingConfig { return { clusterId: this.get(`INDRA_NATS_CLUSTER_ID`), messagingUrl: (this.get(`INDRA_NATS_SERVERS`) || ``).split(`,`), privateKey: (this.get(`INDRA_NATS_JWT_SIGNER_PRIVATE_KEY`) || ``).replace(/\\n/g, "\n"), publicKey: (this.get(`INDRA_NATS_JWT_SIGNER_PUBLIC_KEY`) || ``).replace(/\\n/g, "\n"), token: this.get(`INDRA_NATS_TOKEN`), }; } getMessagingKey(): string { return `INDRA`; } getPort(): number { return parseInt(this.get(`INDRA_PORT`), 10); } getPostgresConfig(): PostgresConfig { return { database: this.get(`INDRA_PG_DATABASE`), host: this.get(`INDRA_PG_HOST`), password: this.get(`INDRA_PG_PASSWORD`), port: parseInt(this.get(`INDRA_PG_PORT`), 10), username: this.get(`INDRA_PG_USERNAME`), }; } getRedisUrl(): string { return this.get(`INDRA_REDIS_URL`); } getRebalancingServiceUrl(): string | undefined { return this.get(`INDRA_REBALANCING_SERVICE_URL`); } getAppCleanupInterval(): number { return parseInt(this.get(`INDRA_APP_CLEANUP_INTERVAL`) || "3600000"); } getDefaultRebalanceProfile(assetId: string = AddressZero): RebalanceProfile | undefined { if (assetId === AddressZero) { let defaultProfileEth = { collateralizeThreshold: parseEther(`0.05`), target: parseEther(`0.1`), reclaimThreshold: parseEther(`0.5`), }; try { const parsed = JSON.parse(this.get("INDRA_DEFAULT_REBALANCE_PROFILE_ETH")); if (parsed) { defaultProfileEth = { collateralizeThreshold: BigNumber.from(parsed.collateralizeThreshold), target: BigNumber.from(parsed.target), reclaimThreshold: BigNumber.from(parsed.reclaimThreshold), }; } } catch (e) {} return { assetId: AddressZero, channels: [], id: 0, ...defaultProfileEth, }; } let defaultProfileToken = { collateralizeThreshold: parseEther(`5`), target: parseEther(`20`), reclaimThreshold: parseEther(`100`), }; try { const parsed = JSON.parse(this.get("INDRA_DEFAULT_REBALANCE_PROFILE_TOKEN")); if (parsed) { defaultProfileToken = { collateralizeThreshold: BigNumber.from(parsed.collateralizeThreshold), target: BigNumber.from(parsed.target), reclaimThreshold: BigNumber.from(parsed.reclaimThreshold), }; } } catch (e) {} return { assetId, channels: [], id: 0, ...defaultProfileToken, }; } getZeroRebalanceProfile(assetId: string = AddressZero): RebalanceProfile | undefined { if (assetId === AddressZero) { return { assetId: AddressZero, channels: [], id: 0, collateralizeThreshold: Zero, target: Zero, reclaimThreshold: Zero, }; } return { assetId, channels: [], id: 0, collateralizeThreshold: Zero, target: Zero, reclaimThreshold: Zero, }; } async onModuleInit(): Promise<void> { for (const [providerMappedChain, provider] of [...this.providers.entries()]) { const actualChain = BigNumber.from(await provider.send("eth_chainId", [])).toNumber(); if (actualChain !== providerMappedChain) { throw new Error( `actualChain !== providerMappedChain, ${actualChain} !== ${providerMappedChain}`, ); } } // Make sure all signers are properly connected for (const [signerMappedChain, signer] of [...this.signers.entries()]) { const actualChain = await signer.getChainId(); if (actualChain !== signerMappedChain) { throw new Error( `actualChain !== signerMappedChain, ${actualChain} !== ${signerMappedChain}`, ); } await signer.connectProvider(this.getEthProvider(signerMappedChain)!); } } }
the_stack
import { AT, AstBuilder, SqrlKey, CompileState, Execution, Instance, sqrlInvariant, Ast, CustomCallAst, } from "sqrl"; import { parse } from "./parser/sqrlRedisParser"; import { invariant, removeIndent } from "sqrl-common"; import { CountArguments, TrendingArguments, AliasedFeature, Timespan, } from "./parser/sqrlRedis"; import { CountService } from "./Services"; const ENTITY_TYPE = "Counter"; const HOUR_MS = 3600 * 1000; const DAY_MS = HOUR_MS * 24; function dayDuration(days: number): Timespan { return { type: "duration", durationMs: days * DAY_MS, }; } const PREVIOUS_CONFIG: { [timespan: string]: { subtractLeft: Timespan; subtractRight: Timespan; allowNegativeValue: boolean; }; } = { // These counters extract what should always be a larger value from a // smaller one. If they are negative than the value should be ignored // (i.e. in the case of not enough data.) previousLastDay: { subtractLeft: dayDuration(2), subtractRight: dayDuration(1), allowNegativeValue: false, }, previousLastWeek: { subtractLeft: dayDuration(14), subtractRight: dayDuration(7), allowNegativeValue: false, }, // dayWeekAgo is internal only dayWeekAgo: { subtractLeft: dayDuration(8), subtractRight: dayDuration(7), allowNegativeValue: false, }, // These x-over-y counters can be negative, but should still be null in // the initial missing data cases. dayOverDay: { subtractLeft: dayDuration(1), subtractRight: { type: "previousLastDay" }, allowNegativeValue: true, }, dayOverWeek: { subtractLeft: dayDuration(1), subtractRight: { type: "dayWeekAgo" }, allowNegativeValue: true, }, weekOverWeek: { subtractLeft: dayDuration(7), subtractRight: { type: "previousLastWeek" }, allowNegativeValue: true, }, }; const TRENDING_CONFIG: { [timespan: string]: { current: Timespan; currentAndPrevious: Timespan; }; } = { dayOverDay: { current: dayDuration(1), currentAndPrevious: dayDuration(2), }, dayOverFullWeek: { current: dayDuration(1), currentAndPrevious: dayDuration(7), }, weekOverWeek: { current: dayDuration(7), currentAndPrevious: dayDuration(14), }, }; export interface CountServiceBumpProps { at: number; keys: SqrlKey[]; by: number; windowMs: number; } function interpretCountArgs( state: CompileState, sourceAst: Ast, args: CountArguments ) { const { whereAst, whereFeatures, whereTruth } = state.combineGlobalWhere( args.where ); const counterProps: { features: string[]; whereFeatures?: string[]; whereTruth?: string; sumFeature?: string; } = { features: args.features.map((feature: AliasedFeature) => feature.alias), whereFeatures, whereTruth, }; // Include sumFeature in the key if provided - otherwise we will // just bump by 1 so leave it out of key. let bumpByAst: Ast = AstBuilder.constant(1); if (args.sumFeature) { counterProps.sumFeature = args.sumFeature.value; bumpByAst = AstBuilder.call("_getBumpBy", [args.sumFeature]); } const { entityAst, entityId } = state.addHashedEntity( sourceAst, ENTITY_TYPE, counterProps ); const featuresAst = args.features.map((aliasFeature) => AstBuilder.feature(aliasFeature.feature.value) ); const featureString = featuresAst.map((ast) => ast.value).join("~"); const keyedCounterName = `${entityId.getIdString()}~${featureString}`; const keysAst = state.setGlobal( sourceAst, AstBuilder.call("_getKeyList", [entityAst, ...featuresAst]), `key(${keyedCounterName})` ); const hasAlias = args.features.some( (featureAst: AliasedFeature) => featureAst.feature.value !== featureAst.alias ); return { bumpByAst, hasAlias, keyedCounterName, keysAst, entityAst, entityId, whereAst, whereFeatures, whereTruth, }; } function getWindowMsForTimespan(timespan: Timespan): number | null { if (timespan.type === "duration") { return timespan.durationMs; } else if (timespan.type === "total") { return null; } else { throw new Error("Unknown duration for timespan type: " + timespan.type); } } function getNameForTimespan(timespan: Timespan): string { if (timespan.type === "duration") { let name = ""; let remaining = timespan.durationMs; if (remaining > DAY_MS) { name += Math.floor(remaining / DAY_MS).toString() + "D"; remaining = remaining % DAY_MS; } name += remaining.toString(); return name; } else { return timespan.type; } } export function ensureCounterBump( state: CompileState, sourceAst: Ast, args: CountArguments ) { const interpretResult = interpretCountArgs(state, sourceAst, args); const { hasAlias, whereAst, keyedCounterName, bumpByAst, keysAst, } = interpretResult; // [@todo: check] Only base the counter identity on features/where if (hasAlias) { return interpretResult; } const windowMs = getWindowMsForTimespan(args.timespan); const slotAst = state.setGlobal( sourceAst, AstBuilder.call("_bumpCount", [ AstBuilder.branch(whereAst, keysAst, AstBuilder.constant(null)), bumpByAst, AstBuilder.constant(windowMs), ]), `bump(${keyedCounterName}:${windowMs})` ); state.addStatement("SqrlCountStatements", slotAst); return interpretResult; } export function registerCountFunctions( instance: Instance, service: CountService ) { instance.registerSync( function _getBumpBy(bumpBy: number) { if (typeof bumpBy !== "number") { return null; } return bumpBy > 0 ? bumpBy : null; }, { args: [AT.feature], } ); instance.registerStatement( "SqrlCountStatements", async function _bumpCount(state, keys, by, windowMs) { if (keys === null || by === null) { return null; } state.manipulator.addCallback(async (ctx) => { await service.bump(ctx, state.getClockMs(), keys, windowMs, by); }); }, { allowNull: true, allowSqrlObjects: true, args: [AT.state, AT.any.array, AT.any, AT.any], } ); instance.register( function _fetchCountsFromDb(state: Execution, keys, windowMs) { if (keys === null) { return null; } return service.fetch(state.ctx, state.getClockMs(), keys, windowMs); }, { allowNull: true, allowSqrlObjects: true, args: [AT.state, AT.any, AT.any], } ); instance.register( async function _fetchTrendingDetails( state, keys, currentCounts, currentAndPreviousCounts, minEvents ) { if (!currentCounts || !currentAndPreviousCounts) { return []; } invariant( currentCounts.length === currentAndPreviousCounts.length && currentCounts.length === keys.length, "Mismatched current/previous trending counts." ); const rv = []; currentCounts.forEach((currentCount, i) => { const currentAndPreviousCount = currentAndPreviousCounts[i]; if ( currentCount === null || currentCount < minEvents || currentAndPreviousCount === null || currentAndPreviousCount < currentCount ) { return; } const key = keys[i]; invariant(key !== null, "Received null key for current count."); const previousCount = currentAndPreviousCount - currentCount; const magnitude = Math.log10(currentCount / Math.max(previousCount, 1)); if (magnitude >= 1) { rv.push({ key: key.featureValues, current: currentCount, previous: previousCount, delta: 2 * currentCount - currentAndPreviousCount, magnitude, }); } }); return rv; }, { args: [AT.state, AT.any, AT.any, AT.any, AT.any], allowSqrlObjects: true, } ); instance.registerCustom( function trending(state: CompileState, ast: CustomCallAst): Ast { const args: TrendingArguments = parse(ast.source, { startRule: "TrendingArguments", }); const { timespan } = args; sqrlInvariant( ast, timespan.type === "dayOverDay" || timespan.type === "weekOverWeek" || timespan.type === "dayOverFullWeek", "Invalid timespan for trending. Expecting `DAY OVER DAY` or `WEEK OVER WEEK` or `DAY OVER FULL WEEK`" ); const trendingConfig = TRENDING_CONFIG[timespan.type]; const currentCountArgs: CountArguments = { features: args.features, sumFeature: null, timespan: trendingConfig.current, where: args.where, }; const currentCountAst = databaseCountTransform( state, ast, currentCountArgs ); const currentAndPreviousCountAst = databaseCountTransform(state, ast, { ...currentCountArgs, timespan: trendingConfig.currentAndPrevious, }); const { keysAst } = interpretCountArgs(state, ast, currentCountArgs); return AstBuilder.call("_fetchTrendingDetails", [ keysAst, currentCountAst, currentAndPreviousCountAst, AstBuilder.constant(args.minEvents), ]); }, { argstring: "Feature[, ...] [WHERE Condition] [WITH MIN Count EVENTS] (Timespan)", docstring: removeIndent(` Returns values whose counts have gone up by an order of magnitude Timespans: DAY OVER DAY, DAY OVER WEEK, DAY OVER FULL WEEK `), } ); function databaseCountTransform( state: CompileState, sourceAst: Ast, args: CountArguments ): Ast { const { keysAst } = ensureCounterBump(state, sourceAst, args); const windowMs = getWindowMsForTimespan(args.timespan); return AstBuilder.call("_fetchCountsFromDb", [ keysAst, AstBuilder.constant(windowMs), ]); } function classifyCountTransform( state: CompileState, ast: CustomCallAst, args: CountArguments ) { const { hasAlias, keyedCounterName, whereAst } = interpretCountArgs( state, ast, args ); // Rewrite this count as a subtraction between other counts (whoah) if (PREVIOUS_CONFIG.hasOwnProperty(args.timespan.type)) { const previousConfig = PREVIOUS_CONFIG[args.timespan.type]; // Convert into a subtract(left, right) // We transform into calls to count() which in turn will get transformed // themselves. This is necessary because the previous config might // itself be a recursive count. // // weekOverWeek = lastWeek - previousLastWeek // = lastWeek - (lastTwoWeeks - lastWeek) // const resultAst = AstBuilder.call("_subtract", [ classifyCountTransform(state, ast, { ...args, timespan: previousConfig.subtractLeft, }), classifyCountTransform(state, ast, { ...args, timespan: previousConfig.subtractRight, }), ]); if (!previousConfig.allowNegativeValue) { const subtractionAst = state.setGlobal( ast, resultAst, `count(${args.timespan.type}:${keyedCounterName})` ); return AstBuilder.branch( // if result < 0 AstBuilder.call("_cmpL", [subtractionAst, AstBuilder.constant(0)]), // then null AstBuilder.constant(null), // else result subtractionAst ); } return resultAst; } const addAst = AstBuilder.branch( AstBuilder.and([whereAst, AstBuilder.feature("SqrlIsClassify")]), AstBuilder.constant(1), AstBuilder.constant(0) ); const resultAst = AstBuilder.call("_add", [ hasAlias ? AstBuilder.constant(0) : addAst, AstBuilder.call("max", [ AstBuilder.call("concat", [ AstBuilder.constant([0]), databaseCountTransform(state, ast, args), ]), ]), ]); return state.setGlobal( ast, resultAst, `count(${getNameForTimespan(args.timespan)}:${keyedCounterName})` ); } instance.registerCustom( function count(state: CompileState, ast: CustomCallAst): Ast { const args: CountArguments = parse(ast.source, { startRule: "CountArguments", }); return classifyCountTransform(state, ast, args); }, { argstring: "BY Feature[, ...] [WHERE Condition] [LAST Timespan]", docstring: removeIndent(` Returns the streaming count for the given window Timespans: LAST [X] SECONDS/MINUTES/HOURS/DAYS/WEEKS DAY OVER DAY, DAY OVER WEEK, WEEK OVER WEEK TOTAL `), } ); }
the_stack
// The point of subgroup is to do fan-out. It allows you to use a stream of // individual operations to feed an arbitrary set of subscriptions. // TODO: This utility class feels very internal. It might work better as a // stand-alone module. import * as I from './interfaces' import streamToIter, {Stream} from 'ministreamiterator' import err from './err' import {queryTypes, resultTypes} from './qrtypes' import {vEq, vCmp, V_EMPTY} from './version' import resolvable, { Resolvable } from '@josephg/resolvable' const splitFullVersions = (v: I.FullVersionRange): [I.FullVersion, I.FullVersion] => { const from: I.FullVersion = [] const to: I.FullVersion = [] for (let i = 0; i < v.length; i++) if (v[i]) { from[i] = v[i]!.from to[i] = v[i]!.to } return [from, to] } type BufferItem = { sourceIdx: number, fromV: I.Version, toV: I.Version, txns: I.TxnWithMeta<any>[] } type Sub<Val> = { q: I.Query | null // iter: I.Subscription, // When we get an operation, do we just send from the current version? Set // if SubscribeOpts.fromCurrent is set. // If fromCurrent is not set, this is the expected version for incoming operations. // This drives the state of the subscription: // // - If its null, we're waiting on fetch() and all the operations we see go into the buffer. // - If its 'current', we just pass all operations directly into the stream. // opsBuffer should be null. // - If this is a version, we're either waiting for catchup (ops go into // buffer) or we're ready and the ops are put straight into the stream. expectVersion: I.FullVersion | 'current' | null, // When the subscription is first opened, we buffer operations until catchup returns. opsBuffer: BufferItem[] | null, // Should the subscription be notified on every change, or just the ones // we're paying attention to? alwaysNotify: boolean, supportedTypes: Set<string> | null, // Do we need to store a local copy of the current subscription values? This // is needed if the subscriber doesn't support the op types that the // underlying store will emit. // TODO: Figure out a better way of deciding when we need this. trackValues: boolean, value?: any, // Stream attached to the returned subscription. stream: Stream<I.CatchupData<Val>>, id: number, // For debugging. } const isVersion = (expectVersion: I.FullVersion | 'current' | null): expectVersion is I.FullVersion => ( expectVersion !== 'current' && expectVersion != null ) let nextId = 1 interface Options<Val> { /** * The current version of the database. The first operation should use this as * its `fromVersion`. */ initialVersion?: I.FullVersion, /** * If supplied, start is called when the first subscription is created. * TODO: Currently unused by all consumers. Consider removing. */ // start?: (v?: I.FullVersion) => Promise<I.FullVersion>, /** * The store's fetch function, if it has one. Used when a subscription is created with no named version. */ fetch?: I.FetchFn<Val>, /** The store's catchup function, if it has one. Optional and rarely used. */ catchup?: I.CatchupFn<Val>, /** * The store's getOps function. This is used when a subscription attempts to * catch up from a known (named) version. * * This is optional but recommended. */ getOps?: I.GetOpsFn<Val>, } // TODO: I'm not entirely happy with the choice to use a class for this. export class SubGroup<Val> { private readonly allSubs = new Set<Sub<Val>>() private readonly opts: Options<Val> /** The last version we got from the store. Catchup *must* return at least this version. */ private storeVersion: I.FullVersion private start?: (v?: I.FullVersion) => Promise<I.FullVersion> private startP?: Resolvable<void> constructor(opts: Options<Val>) { this.opts = opts this.storeVersion = opts.initialVersion || [] // if (opts.start) { // this.start = opts.start // this.startP = resolvable() // } // Need at least one of these. if (opts.getOps == null && opts.catchup == null) { throw Error('Cannot attach subgroup to store without getOps or catchup function') } } setMinVersion(minVersion: I.FullVersion) { this.storeVersion = minVersion } async catchup(query: I.Query, opts: I.SubscribeOpts, trackValues: boolean): Promise<I.CatchupData<Val>> { // TODO: This should look at the aggregation options to decide if a fetch // would be the right thing to do. // // TODO: We should also catch VersionTooOldError out of catchup / getOps // and failover to calling fetch() directly. const {fromVersion} = opts if (fromVersion === 'current') { throw Error('Invalid call to catchup') } else if (fromVersion == null || trackValues) { // console.log('catchup with store.fetch()') if (!this.opts.fetch) { // This should be thrown in the call to .subscribe. throw new Error('Invalid state: Cannot catchup') } // Initialize with a full fetch. const {bakedQuery, results, versions} = await this.opts.fetch(query, {minVersion: this.storeVersion}) // console.log('catchup with full fetch to version', versions, results, opts) const [from, to] = splitFullVersions(versions) return { replace: { ...queryTypes[query.type].fetchToReplace((bakedQuery || query).q, results), versions: from, }, txns: [], toVersion: to, caughtUp: true, } } else if (this.opts.catchup) { // console.log('catchup with store.catchup()') // Use the provided catchup function to bring us up to date return await this.opts.catchup(query, fromVersion, { supportedTypes: opts.supportedTypes, raw: opts.raw, aggregate: opts.aggregate, bestEffort: opts.bestEffort, // limitDocs, limitBytes. }) } else { // console.log('catchup with store.getOps()') // Use getOps const getOps = this.opts.getOps! // _other is used for any other sources we run into in getOps. // const versions: I.FullVersionRange = {_other: {from:V_EMPTY, to: V_EMPTY}} const versions: I.FullVersionRange = fromVersion.map(v => (v == null ? null : {from:v, to:V_EMPTY})) const {ops: txns, versions: opVersions} = await getOps(query, versions, {bestEffort: opts.bestEffort}) // console.log('getOps returned versions', opVersions) const toVersion = splitFullVersions(opVersions)[1] return {txns, toVersion, caughtUp: true} } } /** * Called from stores when a mutation happens, to notify all created * subscriptions. * * @param sourceIdx The index (position) of the source in storeinfo for the * version that was updated * @param fromV The old version of the database before this update. This is * used to validate internal consistency. * @param txns A list of mutations that the store has suffered. */ // TODO: Consider rewriting this to accept a catchup object instead. onOp(sourceIdx: number, fromV: I.Version, txns: I.TxnWithMeta<Val>[]) { if (txns.length == 0) return const toV = txns[txns.length - 1].versions[sourceIdx] if (toV == null) throw Error('Invalid txn - does not change specified source') if (vCmp(fromV, toV) >= 0) throw Error('Invalid op - goes backwards in time') if (vCmp(this.storeVersion[sourceIdx]!, toV) >= 0) throw Error('Store sent repeated txn versions') this.storeVersion[sourceIdx] = toV // console.log('onOp', fromV, '->', toV) for (const sub of this.allSubs) { // console.log(sub.id, 'onOp version', sub.id, 'fv', fromV, 'tv', toV, 'buf', sub.opsBuffer, 'sub ev', sub.expectVersion, 'val', sub.value, 'txn', txn) // First filter out any op types we don't know about here // let _txn = sub.supportedTypes // ? resultTypes[type].filterSupportedOps(txn, resultingView, sub.supportedTypes) // : txn // console.log('sg onOp', fromV, toV, !!sub.opsBuffer) if (sub.opsBuffer) { // console.log('op -> opbuffer') sub.opsBuffer.push({sourceIdx: sourceIdx, fromV, toV, txns}) } else { if (sub.q == null) throw Error('Invalid state') if (isVersion(sub.expectVersion)) { const ev = sub.expectVersion[sourceIdx] // This can happen if you fetch / mutate and get a future-ish version, // then try to subscribe to that version before that version is // propogated through the subscription channel. This happens reliably // with the fdb unit tests. It can also happen if the store sends an // array of txn objects and you've subscribed to one of them. if (ev && !vEq(ev, V_EMPTY) && !vEq(ev, fromV)) { if (vCmp(ev, fromV) < 0) throw new Error('Internal error: Subscription has missed versions') else if (vCmp(ev, toV) >= 0) { // TODO: This can usually be ignored. Remove this warning before ship. console.warn('Warning: Internal version mismatch', sub.id, 'skip version', 'expect', ev, 'actual fromV', fromV, 'data', sub.value) continue } else { // ev is strictly between fromV and toV. Trim txns. // console.log('filter') txns = txns.filter(({versions}) => vCmp(ev, versions[sourceIdx]!) < 0) } // // throw Error(`Invalid version from source: from/to versions mismatch: ${sub.expectVersion[source]} != ${fromV}`) } sub.expectVersion[sourceIdx] = toV } const qtype = queryTypes[sub.q.type] const rtype = qtype.resultType // console.log('qtype', sub.q) // if (!qtype) throw Error('Missing type ' + sub.q.type) const txnsOut: I.TxnWithMeta<Val>[] = [] for (let i = 0; i < txns.length; i++) { const {txn} = txns[i] let localTxn = qtype.adaptTxn(txn, sub.q.q) if (localTxn != null && sub.trackValues) { // console.log('applyMut', sub.value, localTxn) if (rtype.applyMut) rtype.applyMut!(sub.value, localTxn) else (sub.value = rtype.apply(sub.value, localTxn)) localTxn = rtype.filterSupportedOps(localTxn, sub.value, sub.supportedTypes!) } if (localTxn != null) txnsOut.push({...txns[i], txn: localTxn}) } // console.log(sub.id, 'propogate op', localTxn, toV) // This is pretty verbose. Might make sense at some point to do a few MS of aggregation on these. const fullToV = [] fullToV[sourceIdx] = toV if (txnsOut.length || sub.alwaysNotify) sub.stream.append({ txns: txnsOut, toVersion: fullToV, caughtUp: true, }) } // console.log('sub', sub.id, 'ev', sub.expectVersion) } } /** * Create a new subscription in the subscription group, with the specified * query. */ create(this: SubGroup<Val>, query: I.Query, opts: I.SubscribeOpts = {}): I.Subscription<Val> { // console.log('create sub', query, opts) const {fromVersion} = opts if (query.type === I.QueryType.Range && fromVersion != null) { throw new err.UnsupportedTypeError('Can only subscribe to full range queries with no version specified') } if (this.opts.fetch == null && (opts.trackValues || fromVersion == null)) { // TODO: UnsupportedTypeError is too specific for this error type... throw new err.UnsupportedTypeError('Cannot subscribe with fromVersion unset on this store') } const fromCurrent = fromVersion === 'current' let qtype = queryTypes[query.type] const stream = streamToIter<I.CatchupData<Val>>(() => { // console.log(sub.id, 'sub closed') this.allSubs.delete(sub) }) var sub: Sub<Val> = { // Ugh this is twisty. We need the query to filter transactions as they // come in. But also, for range queries we want to use the baked version // of the query instead of the raw query. If catchup gives us // replacement data, we'll use the query that came along there - // although thats not quite accurate either. q: fromVersion != null ? query : null, alwaysNotify: opts.alwaysNotify || false, supportedTypes: opts.supportedTypes || null, trackValues: opts.trackValues || false, expectVersion: fromVersion || null, opsBuffer: fromCurrent ? null : [], stream, id: nextId++, } // console.log(sub.id, 'created sub', 'expect version', sub.expectVersion, 'fromCurrent', fromCurrent, 'q', query) this.allSubs.add(sub) if (sub.trackValues) { const rtype = qtype.resultType sub.value = rtype.create() } if (fromCurrent && this.start) throw Error('First subscription to an unstarted store must specify a version') // console.log('Creating sub', sub.id, 'fv', opts.fromVersion, sub.expectVersion, sub.opsBuffer) // TODO: Skip catchup if the subscription is >= this.storeVersion. ;(async () => { try { if (!fromCurrent) { const catchup = await this.catchup(query, opts, sub.trackValues) // debugger // So quite often if you're passing in a known version, this catchup // object will be empty. Is it still worth sending it? // - Upside: The client can depend on it to know when they're up to date // - Downside: Extra pointless work. // TODO: ^? // console.log('Got catchup', catchup) const {opsBuffer} = sub if (opsBuffer == null) throw Error('Invalid internal state in subgroup') const catchupVersion = catchup.toVersion if (catchup.replace) { // TODO: Is this right? qtype = queryTypes[catchup.replace.q.type] sub.q = { type: catchup.replace.q.type, q: qtype.updateQuery(sub.q == null ? null : sub.q.q, catchup.replace.q.q) } as I.Query if (sub.trackValues) { sub.value = qtype.resultType.updateResults(sub.value, catchup.replace.q, catchup.replace.with) // console.log('sub.value reset to', sub.value) } } // console.log('catchup -> ', catchupVersion, catchup, sub.expectVersion, sub.q, query.type) // Replay the operation buffer into the catchup txn for (let i = 0; i < opsBuffer.length; i++) { const {sourceIdx, fromV, toV, txns} = opsBuffer[i] // console.log('pop from opbuffer', source, {fromV, toV}, txn) const v = catchupVersion[sourceIdx] // If the buffered op is behind the catchup version, discard it and continue. if (v != null) { if (vCmp(toV, v) <= 0) continue else if (vCmp(fromV, v) > 0) throw new Error('Store catchup returned an old version in subGroup') } // console.log('adaptTxn', query.type, txn, sub.q!.q) for (let t = 0; t < txns.length; t++) { const {txn, meta} = txns[t] const filteredTxn = qtype.adaptTxn(txn, sub.q!.q) if (vCmp(v!, fromV) === 0) { const fv = [] fv[sourceIdx] = toV if (filteredTxn != null) catchup.txns.push({versions:fv, txn: filteredTxn, meta}) catchupVersion[sourceIdx] = toV if (sub.trackValues) { const rtype = qtype.resultType if (rtype.applyMut) rtype.applyMut!(sub.value, txn) else (sub.value = rtype.apply(sub.value, txn)) // console.log('sub value =>', sub.value, txn) } } else if (v != null) { // ... TODO: If the catchup fetched version is in between // console.log('v', v, 'fromV', fromV, 'toV', toV) throw Error('Invalid operation data - version span incoherent') } } } // Ok we've processed the buffer. Now check that the subscription // version always meets or exceeds the store version for (let si = 0; si < this.storeVersion.length; si++) { const cuv = catchupVersion[si] if (cuv && vCmp(cuv, this.storeVersion[si]!) < 0) { // console.log('cuv', cuv, this.storeVersion, opsBuffer) throw new Error('Store catchup returned an old version in subGroup') } } if (sub.expectVersion == null) sub.expectVersion = {...catchupVersion} else if (sub.expectVersion !== 'current') { for (let si = 0; si < catchupVersion.length; si++) { const v = catchupVersion[si] if (v != null) sub.expectVersion[si] = v } } sub.opsBuffer = null // Object.freeze(catchupVersion) // console.log('emitting catchup', catchup) stream.append(catchup) } } catch (err) { // Bubble up to create an exception in the client. console.warn(err) sub.stream.throw(err) } })() return stream.iter } } export default function makeSubGroup<Val>(opts: Options<Val>) { return new SubGroup(opts) }
the_stack
import {Watcher, RawValue, RawEAV, RawEAVC, maybeIntern, ObjectDiffs, createId, asJS} from "./watcher"; import {DOMWatcher, ElemInstance} from "./dom"; import {ID} from "../runtime/runtime"; export interface Instance extends HTMLElement {__element?: RawValue, __styles?: RawValue[], __sort?: RawValue, listeners?: {[event: string]: boolean}} export class HTMLWatcher extends DOMWatcher<Instance> { tagPrefix = "html"; _checkedRadios:{[name:string]: RawValue, [name:number]: RawValue} = {}; addExternalRoot(tag:string, element:HTMLElement) { let elemId = createId(); let eavs:RawEAV[] = [ [elemId, "tag", tag], [elemId, "tag", "html/root/external"] ]; this.instances[elemId] = element; this._sendEvent(eavs); } createInstance(id:RawValue, element:RawValue, tagname:RawValue):Instance { let elem:Instance if(tagname === "svg") elem = document.createElementNS("http://www.w3.org/2000/svg", tagname as string) as any; else elem = document.createElement(tagname as string); //elem.setAttribute("instance", ""+maybeIntern(id)); //elem.setAttribute("element", ""+maybeIntern(element)); elem.__element = element; elem.__styles = []; return elem; } getInstance(id:RawValue):Instance|undefined { return this.instances[id]; } createRoot(id:RawValue):Instance { let elem = this.instances[id]; if(!elem) throw new Error(`Orphaned instance '${id}'`); document.body.appendChild(elem); return elem; } addAttribute(instance:Instance, attribute:RawValue, value:RawValue|boolean):void { // @TODO: Error checking to ensure we don't double-set attributes. if(attribute == "value") { if(instance.classList.contains("html-autosize-input") && instance instanceof HTMLInputElement) { instance.size = (instance.value || "").length || 1; } (instance as HTMLInputElement).value = ""+value; } else if(attribute == "tag") { if(value === "html/autosize-input" && instance instanceof HTMLInputElement) { setImmediate(() => instance.size = (instance.value || "").length || 1); } else if(value === "html/trigger/focus" && instance instanceof HTMLInputElement) { setImmediate(() => instance.focus()); } else if(value === "html/trigger/blur" && instance instanceof HTMLInputElement) { setImmediate(() => instance.blur()); } else { instance.setAttribute(attribute, ""+value); } } else if(value === false) { instance.removeAttribute(attribute as string); } else { instance.setAttribute(attribute as string, ""+maybeIntern(value as RawValue)); } } removeAttribute(instance:Instance, attribute:RawValue, value:RawValue|boolean):void { // @TODO: Error checking to ensure we don't double-remove attributes or remove the wrong value. instance.removeAttribute(attribute as string); if(attribute === "value") { let input = instance as HTMLInputElement; if(input.value === value) input.value = ""; } } _updateURL(tagname = "url-change") { let eventId = createId(); let eavs:(RawEAV|RawEAVC)[] = [ [eventId, "tag", "html/event"], [eventId, "tag", `html/event/${tagname}`] ]; let hash = window.location.hash.slice(1); let ix = 1; for(let segment of hash.split("/")) { let segmentId = createId(); eavs.push( [eventId, "hash-segment", segmentId], [segmentId, "index", ix], [segmentId, "value", segment] ); ix += 1; } this._sendEvent(eavs); } //------------------------------------------------------------------ // Event handlers //------------------------------------------------------------------ _mouseEventHandler(tagname:string) { return (event:MouseEvent) => { let {target} = event; if(!this.isInstance(target)) return; let eventId = createId(); let eavs:(RawEAV|RawEAVC)[] = [ [eventId, "tag", "html/event"], [eventId, "tag", `html/event/${tagname}`], [eventId, "page-x", event.pageX], [eventId, "page-y", event.pageY], [eventId, "window-x", event.clientX], [eventId, "window-y", event.clientY], [eventId, "target", target.__element!] ]; let button = event.button; if(button === 0) eavs.push([eventId, "button", "left"]); else if(button === 2) eavs.push([eventId, "button", "right"]); else if(button === 1) eavs.push([eventId, "button", "middle"]); else if(button) eavs.push([eventId, "button", button]); let current:Element|null = target; let elemIds = []; let capturesContextMenu = false; while(current && this.isInstance(current)) { eavs.push([eventId, "element", current.__element!]); if(button === 2 && current.listeners && current.listeners["context-menu"] === true) { capturesContextMenu = true; } current = current.parentElement; } // @NOTE: You'll get a mousedown but no mouseup for a right click if you don't capture the context menu, // so we throw out the mousedown entirely in that case. :( if(button === 2 && !capturesContextMenu) return; if(eavs.length) this._sendEvent(eavs); }; } _captureContextMenuHandler() { return (event:MouseEvent) => { let captureContextMenu = false; let current:Element|null = event.target as Element; while(current && this.isInstance(current)) { if(current.listeners && current.listeners["context-menu"] === true) { captureContextMenu = true; } current = current.parentElement; } if(captureContextMenu && event.button === 2) { event.preventDefault(); } }; } _inputEventHandler(tagname:string) { return (event:Event) => { let target = event.target as (Instance & HTMLInputElement); let elementId = target.__element; if(elementId) { if(target.classList.contains("html-autosize-input")) { target.size = target.value.length || 1; } let eventId = createId(); let eavs:RawEAV[] = [ [eventId, "tag", "html/event"], [eventId, "tag", `html/event/${tagname}`], [eventId, "element", elementId], [eventId, "value", target.value] ]; if(eavs.length) this._sendEvent(eavs); } } } _changeEventHandler(tagname:string) { return (event:Event) => { let target = event.target as (Instance & HTMLInputElement); if(!(target instanceof HTMLInputElement)) return; if(target.type == "checkbox" || target.type == "radio") { let elementId = target.__element; if(elementId) { let eventId = createId(); let eavs:RawEAV[] = [ [eventId, "tag", "html/event"], [eventId, "tag", `html/event/${tagname}`], [eventId, "element", elementId], [eventId, "checked", ""+target.checked] ]; let name = target.name; if(target.type == "radio" && name !== undefined) { let prev = this._checkedRadios[name]; if(prev && prev !== target.__element) { // @NOTE: This is two events in one TX, a bit dangerous. let event2Id = createId(); eavs.push( [event2Id, "tag", "html/event"], [event2Id, "tag", `html/event/${tagname}`], [event2Id, "element", prev], [event2Id, "checked", "false"] ); } this._checkedRadios[name] = elementId; } if(eavs.length) this._sendEvent(eavs); } } } } _keyMap:{[key:number]: string|undefined} = { // Overrides to provide sane names for common control codes. 9: "tab", 13: "enter", 16: "shift", 17: "control", 18: "alt", 27: "escape", 37: "left", 38: "up", 39: "right", 40: "down", 91: "meta" } _keyEventHandler(tagname:string) { return (event:KeyboardEvent) => { if(event.repeat) return; let current:Element|null = event.target as Element; let code = event.keyCode; let key = this._keyMap[code]; let eventId = createId(); let eavs:(RawEAV|RawEAVC)[] = [ [eventId, "tag", "html/event"], [eventId, "tag", `html/event/${tagname}`], [eventId, "key-code", code] ]; if(key) eavs.push([eventId, "key", key]); while(current && this.isInstance(current)) { let elemId = current.__element!; eavs.push([eventId, "element", elemId]); current = current.parentElement; }; if(eavs.length)this._sendEvent(eavs); }; } _focusEventHandler(tagname:string) { return (event:FocusEvent) => { let target = event.target as (Instance & HTMLInputElement); let elementId = target.__element; if(elementId) { let eventId = createId(); let eavs:RawEAV[] = [ [eventId, "tag", "html/event"], [eventId, "tag", `html/event/${tagname}`], [eventId, "element", elementId] ]; if(target.value !== undefined) eavs.push([eventId, "value", target.value]); if(eavs.length) this._sendEvent(eavs); } } } _hoverEventHandler(tagname:string) { return (event:MouseEvent) => { let {target} = event; if(!this.isInstance(target)) return; let eavs:(RawEAV|RawEAVC)[] = []; let elemId = target.__element!; if(target.listeners && target.listeners["hover"]) { let eventId = createId(); eavs.push( [eventId, "tag", "html/event"], [eventId, "tag", `html/event/${tagname}`], [eventId, "element", elemId] ); } if(eavs.length) this._sendEvent(eavs); }; } _hashChangeHandler(tagname:string) { return (event:HashChangeEvent) => { this._updateURL(tagname); }; } //------------------------------------------------------------------ // Watcher handlers //------------------------------------------------------------------ exportListeners({adds, removes}:ObjectDiffs<{listener:string, elemId:ID, instanceId:RawValue}>) { for(let e of Object.keys(adds)) { let {listener, elemId, instanceId} = adds[e]; let instance = this.getInstance(instanceId)!; if(!instance.listeners) instance.listeners = {}; instance.listeners[listener] = true; } for(let e of Object.keys(removes)) { let {listener, elemId, instanceId} = removes[e]; let instance = this.getInstance(instanceId) if(!instance || !instance.listeners) continue; instance.listeners[listener] = false; } } //------------------------------------------------------------------ // Setup //------------------------------------------------------------------ setup() { if(typeof window === "undefined") return; this.tagPrefix = "html"; // @FIXME: hacky, due to inheritance chain evaluation order. super.setup(); this.program .bind("All html elements add their tags as classes", ({find, lib:{string}, record}) => { let element = find("html/element"); element.tag != "html/element" let klass = string.replace(element.tag, "/", "-"); return [ element.add("class", klass) ]; }); window.addEventListener("click", this._mouseEventHandler("click")); window.addEventListener("dblclick", this._mouseEventHandler("double-click")); window.addEventListener("mousedown", this._mouseEventHandler("mouse-down")); window.addEventListener("mouseup", this._mouseEventHandler("mouse-up")); window.addEventListener("contextmenu", this._captureContextMenuHandler()); window.addEventListener("input", this._inputEventHandler("change")); window.addEventListener("change", this._changeEventHandler("change")); window.addEventListener("keydown", this._keyEventHandler("key-down")); window.addEventListener("keyup", this._keyEventHandler("key-up")); window.addEventListener("focus", this._focusEventHandler("focus"), true); window.addEventListener("blur", this._focusEventHandler("blur"), true); document.body.addEventListener("mouseenter", this._hoverEventHandler("hover-in"), true); document.body.addEventListener("mouseleave", this._hoverEventHandler("hover-out"), true); window.addEventListener("hashchange", this._hashChangeHandler("url-change")); this.program .bind("Elements with no parents are roots.", ({find, record, lib, not}) => { let elem = find("html/element"); not(() => find("html/element", {children: elem})); return [ elem.add("tag", "html/root") ]; }) .bind("Create an instance for each child of an external root.", ({find, record, lib, not}) => { let elem = find("html/element"); let parent = find("html/root/external", {children: elem}); return [ record("html/instance", {element: elem, tagname: elem.tagname, parent}), parent.add("tag", "html/element") ]; }); this.program .commit("Remove html events.", ({find, choose}) => { let event = find("html/event"); return [event.remove()]; }) .bind("Inputs with an initial but no value use the initial.", ({find, choose}) => { let input = find("html/element", {tagname: "input"}); let [value] = choose(() => input.value, () => input.initial); return [input.add("value", value)] }) .commit("Apply input value changes.", ({find}) => { let {element, value} = find("html/event/change"); return [element.remove("value").add("value", value)]; }) .commit("Apply input checked changes.", ({find}) => { let {element, checked} = find("html/event/change"); return [element.remove("checked").add("checked", checked)]; }) .commit("When an element is entered, mark it hovered.", ({find, record}) => { let {element} = find("html/event/hover-in"); return [element.add("tag", "html/hovered")]; }) .commit("When an element is left, clear it's hovered.", ({find, record}) => { let {element} = find("html/event/hover-out"); return [element.remove("tag", "html/hovered")]; }) .watch("When an element is hoverable, it subscribes to mouseover/mouseout.", ({find, record}) => { let elemId = find("html/listener/hover"); let instanceId = find("html/instance", {element: elemId}); return [record({listener: "hover", elemId, instanceId})] }) .asObjects<{listener:string, elemId:ID, instanceId:RawValue}>((diffs) => this.exportListeners(diffs)) .watch("When an element listeners for context-menu, it prevents default on right click.", ({find, record}) => { let elemId = find("html/listener/context-menu"); let instanceId = find("html/instance", {element: elemId}); return [record({listener: "context-menu", elemId, instanceId})] }) .asObjects<{listener:string, elemId:ID, instanceId:RawValue}>((diffs) => this.exportListeners(diffs)) .commit("When the url changes, delete its previous segments.", ({find, record}) => { let change = find("html/event/url-change"); let url = find("html/url"); return [ url.remove("hash-segment"), url["hash-segment"].remove() ]; }) .commit("When the url changes, commit its new state.", ({find, lookup, record}) => { let change = find("html/event/url-change"); let {attribute, value} = lookup(change); attribute != "tag"; return [ record("html/url").add(attribute, value) ]; }); //setTimeout(() => this._updateURL(), 100); this._updateURL() } } Watcher.register("html", HTMLWatcher);
the_stack
import useEventListener from '@core/utils/useEventListener' import { arrayMove } from '@dnd-kit/sortable' import ComponentStore from '@store/componentStore' import styles from '@styles/dropzone.module.css' import classNames from 'classnames' import { observer } from 'mobx-react' import React, { useCallback, useEffect, useState } from 'react' import { useBeforeunload } from 'react-beforeunload' import { useDropzone } from 'react-dropzone' import { GlobalHotKeys } from 'react-hotkeys' import { v4 } from 'uuid' import { ElectronFile, FileTransformType, FileWithMetadata } from '~@types/fileTypes' import DraggableWrapper from './draggable' const { FileStore } = ComponentStore const { updateFiles, setDropzoneRef } = FileStore const createVideoThumbnail = (videoFile: File) => { const thumbnail = new Promise<{ preview: string videoMetadata?: { height: number width: number duration: number otherMetadata: any } }>((resolve, reject) => { try { const videoElement = document.createElement('video') const canPlay = videoElement.canPlayType(videoFile.type) if (!canPlay) { // reject(new Error('Does not support video type')) resolve({ preview: '/images/previews/videoPreview.png' }) } const snapImage = () => { const videoCanvas = document.createElement('canvas') videoCanvas.width = videoElement.videoWidth videoCanvas.height = videoElement.videoHeight // @ts-ignore videoCanvas .getContext('2d') .drawImage(videoElement, 0, 0, videoCanvas.width, videoCanvas.height) const img = videoCanvas.toDataURL() const success = img.length > 100000 if (success) { resolve({ preview: img, videoMetadata: { height: videoElement.videoHeight, width: videoElement.videoWidth, duration: videoElement.duration, otherMetadata: videoElement } }) } return success } const timeUpdate = () => { // console.info('Playing time update'); if (snapImage()) { videoElement.removeEventListener('timeupdate', timeUpdate) videoElement.pause() } } videoElement.addEventListener('loadeddata', () => { if (snapImage()) { videoElement.removeEventListener('timeupdate', timeUpdate) videoElement.pause() } }) const videoUrl = URL.createObjectURL( new Blob([videoFile], { type: videoFile.type }) ) videoElement.addEventListener('timeupdate', timeUpdate) videoElement.preload = 'metadata' videoElement.src = videoUrl videoElement.muted = true // @ts-ignore playsInline is supported by video elements videoElement.playsInline = true videoElement.play() } catch (err) { console.error(err) reject(new Error(err.message)) } }) return thumbnail } type DropzoneProps = { acceptedFiles?: string[] } const Dropzone = ({ acceptedFiles }: DropzoneProps) => { const [files, setFiles] = useState<Array<FileWithMetadata>>([]) const [scroll, setScroll] = useState(0) const [loading, setLoading] = useState(false) const dropzoneRef = React.useRef<HTMLDivElement | null>(null) const thumbnailRef = React.useRef<HTMLDivElement | null>(null) const { globalReset } = ComponentStore useBeforeunload(() => 'Your video will stop processing!') useEffect(() => { if (globalReset) { setFiles([]) } }, [globalReset]) useEffect(() => { setDropzoneRef(dropzoneRef) return () => { delete FileStore.dropzoneRef } }, []) const translateScroll = (e: WheelEvent) => { e.stopPropagation() document.body.style.overflowY = 'hidden' const maxScroll = thumbnailRef?.current?.scrollHeight || 500 if (e.deltaY < 0 && scroll > 0) { setScroll(s => s - 10) } else if (e.deltaY > 0 && scroll < maxScroll) { setScroll(s => s + 10) } if (thumbnailRef && thumbnailRef.current) { thumbnailRef.current.scrollTo({ top: scroll, behavior: 'smooth' }) } } useEventListener(dropzoneRef, 'wheel', translateScroll) const onDrop = useCallback(async acceptedFiles => { // Do something with the files const newFiles: Array<FileWithMetadata> = await Promise.all( acceptedFiles.map(async (file: ElectronFile) => { // TODO (rahul) Fix Promise waiting if (file.type.match('image')) { return { file, uuid: v4(), preview: URL.createObjectURL(file), path: file.path || '', customType: 'image' } } if (file.type.match('video')) { // Generate preview for Video try { const videoData = await createVideoThumbnail(file) return { file, uuid: v4(), preview: videoData.preview, path: file.path || '', customType: 'video', videoMetadata: videoData.videoMetadata } } catch (err) { return { file, uuid: v4(), preview: '', path: file.path || '', customType: 'video' } } } if (file.type.match('audio')) { return { file, uuid: v4(), preview: '/images/previews/audioPreview.png', customType: 'audio', path: file.path || '' } } return { file, preview: '', customType: 'other', path: file.path || '' } }) ) const transforms: FileTransformType[] = [] for (const newFile of newFiles) { const newTransform: FileTransformType = { type: newFile.customType, fileObj: newFile, state: 'Insert' } transforms.push(newTransform) } updateFiles(transforms) setFiles(f => f.concat(newFiles)) }, []) const handleDemoVideo = async (e: React.MouseEvent) => { setLoading(true) e.stopPropagation() const demoFile = await fetch('/modfyDemo.webm') const blob = await demoFile.blob() const file: File = new File([blob], 'modfyDemo.webm', { type: 'video/webm' }) const videoData = await createVideoThumbnail(file) const fileWithMetadata: FileWithMetadata = { file, uuid: v4(), preview: videoData.preview, customType: 'video', videoMetadata: videoData.videoMetadata } const newTransform: FileTransformType = { type: fileWithMetadata.customType, fileObj: fileWithMetadata, state: 'Insert' } updateFiles([newTransform]) setFiles(f => f.concat([fileWithMetadata])) setLoading(false) } /** * This function gets passed down to DraggableWrapper. * * It updates the local files state and dispatches the * move transform to the files store. */ const moveFiles = ( oldIndex: number, newIndex: number, file: FileWithMetadata ) => { setFiles(items => { updateFiles([ { type: file.customType, fileObj: file, state: 'Move', position: oldIndex, secondPosition: newIndex } ]) return arrayMove(items, oldIndex, newIndex) }) } const deleteFile = (index: number, file: FileWithMetadata) => { updateFiles([ { type: file.customType, fileObj: file, state: 'Delete', position: index } ]) setFiles(items => [...items.slice(0, index), ...items.slice(index + 1)]) } useEffect(() => { // This is breaking the previews // files.forEach(file => { // if (file.fileWithMetadata.preview) // URL.revokeObjectURL(file.fileWithMetadata.preview) // }) }, [files]) const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop, accept: acceptedFiles ?? ['video/*', 'image/*', 'audio/*'] }) const keyMap = { FILE_DRAWER: ['shift+f'] } const handlers = { FILE_DRAWER: (e?: KeyboardEvent) => { e?.preventDefault() document.getElementById('file-input')?.click() } } if (files.length === 0) { return ( <GlobalHotKeys keyMap={keyMap} handlers={handlers}> <div className={styles.previewWrapper}> <div className={classNames(styles.dropzone, 'dropzone-translate')} id="dropzone" {...getRootProps()}> <div className={styles.scrollableWrapper} ref={dropzoneRef}> <input id="file-input" {...getInputProps()} /> <div className="w-1/3 px-2"> <img alt="Video file svg" src="/images/upload.svg" /> </div> {isDragActive ? ( <p className="text-green-500">Drop the files here ...</p> ) : ( <p className="text-green-500"> <b>Click</b> or Drag to add files.{' '} </p> )} <button type="button" onClick={handleDemoVideo} disabled={loading} className="inline-flex z-20 items-center mt-10 px-4 py-2 border border-transparent shadow-sm text-base font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"> {loading ? ( <svg className="animate-spin h-5 w-5 mr-3 ..." viewBox="0 0 24 24" fill="currentColor"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> ) : null} Use a demo file {!loading ? ( <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" className="ml-3 -mr-1 h-5 w-5" stroke="currentColor"> <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 4v16M17 4v16M3 8h4m10 0h4M3 12h18M3 16h4m10 0h4M4 20h16a1 1 0 001-1V5a1 1 0 00-1-1H4a1 1 0 00-1 1v14a1 1 0 001 1z" /> </svg> ) : null} </button> </div> {/* @ts-ignore Styled JSX */} <style jsx> {` .dropzone { width: ${files.length > 0 ? '90%' : '100%'}; } `} </style> </div> </div> </GlobalHotKeys> ) } const handleDrop = (e: React.DragEvent<HTMLElement>) => { e.preventDefault() // Call the drop function to simulate the file being // dropped to the dropzone. onDrop( Array(e.dataTransfer.files.length) .fill(0) .map((_, idx) => e.dataTransfer.files.item(idx)) ) } return ( <GlobalHotKeys keyMap={keyMap} handlers={handlers}> <div className={styles.previewWrapper}> <div id="dropzone" style={{ cursor: 'default', borderRadius: '0.25rem' }} {...getRootProps()}> <div className={styles.scrollableWrapper} ref={dropzoneRef}> <input id="file-input" {...getInputProps()} /> </div> {/* @ts-ignore Styled JSX */} <style jsx> {` .dropzone { width: ${files.length > 0 ? '90%' : '100%'}; } `} </style> </div> <aside ref={thumbnailRef} className={styles.thumbsContainer} onDrop={e => handleDrop(e)}> <DraggableWrapper files={files} moveFiles={moveFiles} deleteFile={deleteFile} /> </aside> </div> </GlobalHotKeys> ) } export default observer(Dropzone)
the_stack
import { Evt } from "../lib"; //import { Evt as EvtNext } from "../lib/Evt"; import { id } from "../tools/typeSafety"; import { getPromiseAssertionApi } from "../tools/testing"; import { getHandlerPr } from "./getHandlerPr"; const { mustResolve, mustStayPending } = getPromiseAssertionApi(); type Circle = { type: "CIRCLE"; radius: number; }; type Square = { type: "SQUARE"; sideLength: number; }; type Shape = Circle | Square; const matchCircle = (shape: Shape): shape is Circle => shape.type === "CIRCLE"; type Resolve<T> = (value: T) => void; export class Deferred<T> { public readonly pr: Promise<T>; /** NOTE: Does not need to be called bound to instance*/ public readonly resolve: Resolve<T>; constructor() { let resolve!: Resolve<T>; this.pr = new Promise<T>( resolve_ => resolve = value => { this._hasResolved = true; resolve_(value); } ); this.resolve = resolve; } public _hasResolved = false; } const test = ( getSamples: () => { evtShape: Evt<Shape>; prCircle: Promise<Circle>; prRadius: Promise<number>; prBigCircle: Promise<Circle>; prBigShape: Promise<Shape>; } ) => { { const { evtShape, prCircle, prRadius, prBigCircle, prBigShape } = getSamples(); const smallCircle: Circle = { "type": "CIRCLE", "radius": 3 }; mustResolve({ "promise": prCircle, "expectedData": smallCircle }); mustResolve({ "promise": prRadius, "expectedData": smallCircle.radius }); mustStayPending(prBigCircle); mustStayPending(prBigShape); evtShape.post(smallCircle); } { const { evtShape, prCircle, prRadius, prBigCircle, prBigShape } = getSamples(); const bigCircle: Circle = { "type": "CIRCLE", "radius": 10000 }; mustResolve({ "promise": prCircle, "expectedData": bigCircle}); mustResolve({ "promise": prRadius, "expectedData": bigCircle.radius }); mustResolve({ "promise": prBigCircle, "expectedData": bigCircle }); mustResolve({ "promise": prBigShape, "expectedData": bigCircle }); evtShape.post(bigCircle); } { const { evtShape, prCircle, prRadius, prBigCircle, prBigShape } = getSamples(); const smallSquare: Square = { "type": "SQUARE", "sideLength": 1 }; mustStayPending(prCircle); mustStayPending(prRadius); mustStayPending(prBigCircle); mustStayPending(prBigShape); evtShape.post(smallSquare); } { const { evtShape, prCircle, prRadius, prBigCircle, prBigShape } = getSamples(); const bigSquare: Square = { "type": "SQUARE", "sideLength": 1000000 }; mustStayPending(prCircle); mustStayPending(prRadius); mustStayPending(prBigCircle); mustResolve({ "promise": prBigShape, "expectedData": bigSquare}); evtShape.post(bigSquare); } }; for (const methodName of ["$attachOnce", "$attach", "$attachOncePrepend", "$attachPrepend"] as any as [ "$attachOnce", //"$attach" //"$attachExtract" //"$attachOnceExtract", //"$attachPrepend", //"$attachOncePrepend" ]) { const higherOrder = (variant: "PROMISE" | "CALLBACK") => { return () => { const evtShape = new Evt<Shape>(); const dCircle = new Deferred<Circle>(); const prCircle = getHandlerPr( evtShape, () => evtShape[methodName]( shape => matchCircle(shape) ? [shape] : null, circle => dCircle.resolve(circle) )); const dRadius = new Deferred<number>(); const prRadius = getHandlerPr( evtShape, () => evtShape[methodName]( shape => shape.type === "CIRCLE" ? [shape.radius] : null, radius => dRadius.resolve(radius) )); const dBigCircle = new Deferred<Circle>(); const prBigCircle = getHandlerPr( evtShape, () => evtShape[methodName]( shape => shape.type === "CIRCLE" && shape.radius > 100 ? [shape] : null, bigCircle => dBigCircle.resolve(bigCircle) )); const dBigShape = new Deferred<Shape>(); const prBigShape = getHandlerPr( evtShape, () => evtShape[methodName]( shape => { switch (shape.type) { //NOTE: We have to give a hint to typescript on what we will return. case "SQUARE": return (shape.sideLength > 100) ? [id<Shape>(shape)] : null; case "CIRCLE": return (shape.radius > 100) ? [shape] : null; } }, shape => dBigShape.resolve(shape) )); switch (variant) { case "CALLBACK": return { evtShape, "prCircle": dCircle.pr, "prRadius": dRadius.pr, "prBigCircle": dBigCircle.pr, "prBigShape": dBigShape.pr }; case "PROMISE": return { evtShape, prCircle, prRadius, prBigCircle, prBigShape }; } }; }; test(higherOrder("PROMISE")); test(higherOrder("CALLBACK")); } /* for (const methodName of ["attachOnce", "attach", "attachOncePrepend", "attachPrepend"] as any as [ "attachOnce", //"attach" //"attachExtract" //"attachOnceExtract", //"attachPrepend", //"attachOncePrepend" ]) { const higherOrder = (variant: "PROMISE" | "CALLBACK") => { return () => { const evtShape = new EvtNext<Shape>(); const dCircle = new Deferred<Circle>(); const prCircle = evtShape[methodName]( shape => matchCircle(shape) ? [shape] : null, circle => dCircle.resolve(circle) ); id<Promise<Circle>>(prCircle); const dRadius = new Deferred<number>(); const prRadius = evtShape[methodName]( shape => shape.type === "CIRCLE" ? [shape.radius] : null, radius => dRadius.resolve(radius) ); id<Promise<number>>(prRadius); const dBigCircle = new Deferred<Circle>(); const prBigCircle = evtShape[methodName]( shape => shape.type === "CIRCLE" && shape.radius > 100 ? [shape] : null, bigCircle => dBigCircle.resolve(bigCircle) ); id<Promise<Circle>>(prBigCircle); const dBigShape = new Deferred<Shape>(); const prBigShape = evtShape[methodName]( shape => { switch (shape.type) { case "SQUARE": return (shape.sideLength > 100) ? [id<Shape>(shape)] : null; case "CIRCLE": return (shape.radius > 100) ? [shape] : null; } }, bigShape => dBigShape.resolve(bigShape) ); id<Promise<Shape>>(prBigShape); switch (variant) { case "CALLBACK": return { evtShape, "prCircle": dCircle.pr, "prRadius": dRadius.pr, "prBigCircle": dBigCircle.pr, "prBigShape": dBigShape.pr }; case "PROMISE": return { evtShape, prCircle, prRadius, prBigCircle, prBigShape }; } }; }; test(higherOrder("PROMISE")); test(higherOrder("CALLBACK")); } for (const methodName of ["attachOnce", "attach", "attachOncePrepend", "attachPrepend"] as any as [ "attachOnce", //"attach" //"attachExtract" //"attachOnceExtract", //"attachPrepend", //"attachOncePrepend" ]) { const higherOrder = (variant: "PROMISE" | "CALLBACK") => { return () => { const evtShape = new EvtNext<Shape>(); const dCircle = new Deferred<Circle>(); const prCircle = evtShape[methodName]( matchCircle, circle => dCircle.resolve(circle) ); const dRadius = new Deferred<number>(); const prRadius = evtShape[methodName]( matchCircle, circle => dRadius.resolve(circle.radius) ).then(({ radius }) => radius); const dBigCircle = new Deferred<Circle>(); const prBigCircle = evtShape[methodName]( shape => shape.type === "CIRCLE" && shape.radius > 100, bigCircle => { //Here big circle is a shape with ts 3.3.4 but it is not usable. dBigCircle.resolve(bigCircle as Circle); } ).then(bigCircle => id<Shape>(bigCircle) as Circle); const dBigShape = new Deferred<Shape>(); const prBigShape = evtShape[methodName]( shape => { switch (shape.type) { case "SQUARE": return (shape.sideLength > 100); case "CIRCLE": return (shape.radius > 100); } }, bigShape => { //Here big shape is a shape with ts 3.3.4 but it is not usable. dBigShape.resolve(bigShape as Shape) } ); switch (variant) { case "CALLBACK": return { evtShape, "prCircle": dCircle.pr, "prRadius": dRadius.pr, "prBigCircle": dBigCircle.pr, "prBigShape": dBigShape.pr }; case "PROMISE": return { evtShape, prCircle, prRadius, prBigCircle, prBigShape }; } }; }; test(higherOrder("PROMISE")); test(higherOrder("CALLBACK")); } */ setTimeout(() => console.log("PASS"), 0);
the_stack
import { Plan, PlanStep } from "pddl-workspace"; import { createPlanView, JsonDomainVizConfiguration, PlanView } from "pddl-gantt"; import { SearchTree } from "./tree"; import { StateChart } from "./charts"; import { getElementByIdOrThrow, State } from "./utils"; import { FinalStateData, PlanData } from 'model'; /** VS Code stub, so we can work with it in a type safe way. */ interface VsCodeApi { // eslint-disable-next-line @typescript-eslint/no-explicit-any postMessage(payload: any): void; } declare function postCommand(command: string): void; declare const acquireVsCodeApi: () => VsCodeApi; declare const vscode: VsCodeApi; /* implemented in baseWebview.js */ declare function onLoad(): void; let searchTree: SearchTree; window.addEventListener('message', event => { const message = event.data; // console.log("Message: " + message); switch (message.command) { case 'stateAdded': add(message.state, false); break; case 'stateUpdated': update(message.state); break; case 'debuggerState': showDebuggerOn(message.state.running === 'on', message.state.port); break; case 'showStatePlan': showStatePlan(message.state); break; case 'visualizeFinalState': showFinalState(message.state); break; case 'clear': clearStates(); break; case 'showAllStates': showAllStates(message.state); break; case 'showPlan': showPlan(message.state); // the message.state contains list of states actually break; case 'stateLog': showStateLogButton(message.state); break; default: console.log("Unexpected message: " + message.command); } }); /** * Creates a mock state * @param g mock state generation * @param id mock state ID * @param parentId mock state's parent ID * @param actionName creating action * @param earliestTime earliest state time * @param landmarks landmark facts satisfied in this state * @returns mock state */ function createMockState(g: number, id: number, parentId: number | undefined, actionName: string | undefined, earliestTime: number, landmarks?: number): State { return { g: g, id: id, origId: id.toString(), parentId: parentId, actionName: actionName, earliestTime: earliestTime, isGoal: false, landmarks: landmarks, totalMakespan: undefined }; } const mockStates = [ createMockState(0, 10, undefined, undefined, 0, 1), createMockState(1, 11, 10, 'drive start', .1, 2), createMockState(1, 12, 10, 'load start', .1, 2), createMockState(2, 13, 11, 'drive end', 2, 3), createMockState(3, 14, 13, 'unload start', 2.1, 3), ]; /** All states displayed. todo: should this be a map?*/ const states: State[] = []; /** Selected state ID or null if no state was selected yet. */ let selectedStateId: number | null; getElementByIdOrThrow("addMock").onclick = (): void => { if (mockStates.length === 0) { return; } const newState = mockStates.shift(); if (newState) { add(newState, false); } }; getElementByIdOrThrow("setVisitedOrWorseMock").onclick = (): void => { if (selectedStateId === null) { return; } const state = states[selectedStateId]; state.wasVisitedOrIsWorse = true; update(state); }; getElementByIdOrThrow("evaluateMock").onclick = (): void => { if (selectedStateId === null) { return; } const state = states[selectedStateId]; if (!state) { console.log('Selected state does not exist!'); return; } let h = 5; let totalMakespan = 5; let earliestTime = 0; if (state.parentId !== undefined) { const parentState = states[state.parentId]; h = parentState.h ?? 2 - Math.floor(Math.random() * 2); totalMakespan = parentState.totalMakespan ?? 1.5 + Math.floor(Math.random() * 1.5); earliestTime = parentState.earliestTime + Math.random() * 1.5; } state.h = h; state.totalMakespan = totalMakespan; state.earliestTime = earliestTime; update(state); }; getElementByIdOrThrow("deadEndMock").onclick = (): void => { if (selectedStateId === null) { return; } const state = states[selectedStateId]; if (!state) { console.log('Selected state does not exist!'); return; } state.h = Number.POSITIVE_INFINITY; state.totalMakespan = Number.POSITIVE_INFINITY; state.isDeadEnd = true; update(state); }; getElementByIdOrThrow("clearStatesMock").onclick = (): void => { clearStates(); }; getElementByIdOrThrow("planMock").onclick = (): void => { if (selectedStateId === null) { return; } let state: State | undefined = states[selectedStateId]; const planStates = []; while (state) { state.isPlan = true; planStates.push(state); const parentId: number | undefined = state.parentId; state = parentId !== undefined && parentId !== null ? states[parentId] : undefined; } showPlan(planStates); }; let stateChart: StateChart; let planViz: PlanView; /** * Adds state * @param newState state to add * @param batch batch-mode on/off * @returns {void} */ function add(newState: State, batch: boolean): void { searchTree.addStateToTree(newState, batch); stateChart.addStateToChart(newState, batch); states[newState.id] = newState; } /** * Updates state on the view * @param state state to update */ function update(state: State): void { stateChart.updateStateOnChart(state); searchTree.updateStateOnTree(state); if (selectedStateId === state.id) { stateChart.selectChartRow(state.id); } } /** * Highlight states that belong to plan * @param states state chain that form a plan */ function showPlan(states: State[]): void { searchTree.showPlanOnTree(states); } /** * Clear pre-existing states and show new ones * @param states states to display (instead of currently shown states) */ function showAllStates(states: State[]): void { clearStates(); for (const state of states) { add(state, true); } endBatch(); } function endBatch(): void { stateChart.endChartBatch(); searchTree.endTreeBatch(); } /** * State was selected * @param stateId state id or null to unselect */ function onStateSelected(stateId: number | null): void { if (selectedStateId === stateId) { return; } selectedStateId = stateId; stateChart.selectChartRow(stateId); searchTree.selectTreeNode(stateId); vscode?.postMessage({ command: 'stateSelected', stateId: stateId }); if (!vscode) { const statePlan = new Plan([ new PlanStep(.5, "hello world " + stateId, true, 1, 1) ]); showStatePlan({ plan: statePlan, width: 300 }); } } document.body.onload = (): void => initialize(); function initialize(): void { searchTree = new SearchTree(); searchTree.network.on('selectNode', function (nodeEvent) { if (nodeEvent.nodes.length > 0) { onStateSelected(nodeEvent.nodes[0]); } }); searchTree.network.on('deselectNode', function (nodeEvent) { if (nodeEvent.nodes.length > 0) { onStateSelected(nodeEvent.nodes[0]); } else { onStateSelected(null); } }); window.document.addEventListener('keydown', function (event) { navigate(event); }); window.onresize = function (): void { stateChart.unsubscribeChartEvents(); stateChart.reSizeChart(); stateChart.subscribeToChartEvents(); }; if (!vscode) { showDebuggerOn(false); } stateChart = new StateChart(onStateSelected); stateChart.subscribeToChartEvents(); planViz = createPlanView("statePlan", { displayWidth: 400, epsilon: 1e-3, disableLinePlots: true, onActionSelected: (actionName: string) => vscode?.postMessage({ "command": "revealAction", "action": actionName }), onHelpfulActionSelected: (helpfulAction: string) => navigateToChildOfSelectedState(helpfulAction), onFinalStateVisible: planView => requestFinalState(planView), }); getElementByIdOrThrow("mockMenu").style.visibility = vscode ? 'collapse' : 'visible'; onLoad(); } function clearStates(): void { console.log('clearing all states'); searchTree.clearTree(); stateChart.clearChart(); } const START_DEBUGGER_BUTTON_ID = "startDebuggerButton"; const STOP_DEBUGGER_BUTTON_ID = "stopDebuggerButton"; const CLEAR_DEBUGGER_BUTTON_ID = "restartDebuggerButton"; getElementByIdOrThrow(START_DEBUGGER_BUTTON_ID).onclick = (): void => startSearchDebugger(); function startSearchDebugger(): void { showDebuggerOn(true); postCommand('startDebugger'); } getElementByIdOrThrow(STOP_DEBUGGER_BUTTON_ID).onclick = (): void => stopSearchDebugger(); function stopSearchDebugger(): void { showDebuggerOn(false); postCommand('stopDebugger'); } getElementByIdOrThrow(CLEAR_DEBUGGER_BUTTON_ID).onclick = (): void => restartSearchDebugger(); function restartSearchDebugger(): void { postCommand('reset'); showStatePlan({ plan: new Plan([]), width: 300 }); clearStates(); } /** * Display debugger status * @param on debugger is active * @param port HTTP port the debugger is listening on */ function showDebuggerOn(on: boolean, port?: number): void { enableButton(!on, START_DEBUGGER_BUTTON_ID); enableButton(on, STOP_DEBUGGER_BUTTON_ID); enableButton(on, CLEAR_DEBUGGER_BUTTON_ID); if (port) { getElementByIdOrThrow(STOP_DEBUGGER_BUTTON_ID).title = "Search engine listener is running on port " + port + ". Click here to stop it."; } } /** * Enable/disable icon-based button. * @param enable enable/disable * @param buttonId button element ID */ function enableButton(enable: boolean, buttonId: string): void { const icon = getElementByIdOrThrow(buttonId); if (enable) { icon.classList.remove('disabled'); } else { icon.classList.add('disabled'); } } function showStatePlan(data: PlanData): void { const clonedPlan = Plan.clone(data.plan); const configuration = JsonDomainVizConfiguration.withCustomVisualizationScript( data.domainVisualizationConfiguration, data.customDomainVisualizationScript); planViz.showPlan(clonedPlan, configuration); } const shapeMap = new Map<string, string>(); shapeMap.set('h', 'hexagon'); shapeMap.set('b', 'box'); shapeMap.set('d', 'diamond'); shapeMap.set('s', 'star'); shapeMap.set('t', 'triangle'); shapeMap.set('h', 'hexagon'); shapeMap.set('q', 'square'); shapeMap.set('e', 'ellipse'); // eslint-disable-next-line @typescript-eslint/no-explicit-any function navigate(e: any): void { e = e || window.event; let newSelectedStateId: number | null; switch (e.key) { case "ArrowLeft": newSelectedStateId = e.shiftKey ? stateChart.navigateChart(-1) : searchTree.navigateTreeSiblings(-1); onStateSelected(newSelectedStateId); if (newSelectedStateId !== null) { e.cancelBubble = true; } break; case "ArrowRight": newSelectedStateId = e.shiftKey ? stateChart.navigateChart(+1) : searchTree.navigateTreeSiblings(+1); onStateSelected(newSelectedStateId); if (newSelectedStateId !== null) { e.cancelBubble = true; } break; case "ArrowUp": newSelectedStateId = searchTree.navigateTreeUp(); onStateSelected(newSelectedStateId); if (newSelectedStateId !== null) { e.cancelBubble = true; } break; case "ArrowDown": newSelectedStateId = searchTree.navigateTreeDown(); onStateSelected(newSelectedStateId); if (newSelectedStateId !== null) { e.cancelBubble = true; } break; case "f": searchTree.toggleAutoFit(); break; case "F": searchTree.fitTree(); break; } if (e.key in shapeMap) { searchTree.changeSelectedNodeShape(shapeMap.get(e.key)!); } if (Number.isFinite(parseInt(e.key))) { // digits are being typed const digit = parseInt(e.key); findingStateWithDigit(digit); } } let stateIdToFind = 0; /** Timeout for keyboard typing state ID. */ let stateFindingTimeout: NodeJS.Timeout | undefined; /** * Turns on state finding and appends a stateId digit. * @param digit of the state number to append */ function findingStateWithDigit(digit: number): void { stateIdToFind = stateIdToFind * 10 + digit; if (stateFindingTimeout) { clearTimeout(stateFindingTimeout); } stateFindingTimeout = setTimeout(() => findState(), 1000); } function findState(): void { try { onStateSelected(stateIdToFind); } catch (ex) { console.log("Cannot find find state with id " + stateIdToFind + ". Error: " + ex); } stateIdToFind = 0; } /** * Navigates to child * @param actionName action name * @todo this is called by the helpful action link on the relaxed plan display */ export function navigateToChildOfSelectedState(actionName: string): void { if (selectedStateId) { const newSelectedStateId = searchTree.navigateToChildState(selectedStateId, actionName); if (newSelectedStateId !== null) { onStateSelected(newSelectedStateId); } } } getElementByIdOrThrow("toggleStateLogButton").onclick = (): void => toggleStateLog(); function toggleStateLog(): void { postCommand('toggleStateLog'); } /** * Shows heuristic log path * @param logFilePath heuristic log path */ function showStateLogButton(logFilePath: string): void { const button = getElementByIdOrThrow("toggleStateLogButton"); if (logFilePath) { button.style.color = "green"; button.title = "State selection synchronized with log file file: " + logFilePath; } else { button.style.color = "red"; button.title = "State log file synchronization disabled. Click here to re-enable."; } } // eslint-disable-next-line @typescript-eslint/no-unused-vars function requestFinalState(_planView: PlanView): void { vscode?.postMessage({ 'command': 'finalStateDataRequest', 'stateId': selectedStateId }); } function showFinalState(data: FinalStateData): void { // check that the selected state is _still_ the same one as when the request was sent if (data.planIndex === selectedStateId) { planViz.showFinalState(data.finalState); } }
the_stack
import * as ArbitrationStrategyCollection from "../../../../../main/js/joynr/types/ArbitrationStrategyCollection"; import DiscoveryEntryWithMetaInfo from "../../../../../main/js/generated/joynr/types/DiscoveryEntryWithMetaInfo"; import ProviderScope from "../../../../../main/js/generated/joynr/types/ProviderScope"; import ProviderQos from "../../../../../main/js/generated/joynr/types/ProviderQos"; import CustomParameter from "../../../../../main/js/generated/joynr/types/CustomParameter"; import Version from "../../../../../main/js/generated/joynr/types/Version"; const expiryDateMs = Date.now() + 1e10; describe("libjoynr-js.joynr.types.ArbitrationStrategyCollection", () => { it("is defined and of correct type", () => { expect(ArbitrationStrategyCollection).toBeDefined(); expect(ArbitrationStrategyCollection).not.toBeNull(); expect(typeof ArbitrationStrategyCollection === "object").toBeTruthy(); }); it("has all required strategies of type function", () => { expect(ArbitrationStrategyCollection.Nothing).toBeDefined(); expect(ArbitrationStrategyCollection.HighestPriority).toBeDefined(); expect(ArbitrationStrategyCollection.Keyword).toBeDefined(); expect(ArbitrationStrategyCollection.LastSeen).toBeDefined(); expect(ArbitrationStrategyCollection.FixedParticipant).toBeDefined(); expect(typeof ArbitrationStrategyCollection.Nothing).toBe("function"); expect(typeof ArbitrationStrategyCollection.HighestPriority).toBe("function"); expect(typeof ArbitrationStrategyCollection.Keyword).toBe("function"); expect(typeof ArbitrationStrategyCollection.LastSeen).toBe("function"); expect(typeof ArbitrationStrategyCollection.FixedParticipant).toBe("function"); }); function getDiscoveryEntryWithMetaInfoForFixedParticipantId() { return [ new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), domain: "myDomain", interfaceName: "myInterfaceName", lastSeenDateMs: 111, qos: new ProviderQos({ customParameters: [], priority: 1, scope: ProviderScope.GLOBAL, supportsOnChangeSubscriptions: true }), participantId: "myFixedParticipantId", isLocal: false, publicKeyId: "", expiryDateMs }) ]; } function getDiscoveryEntryWithMetaInfoList() { return [ new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), domain: "KeywordmyDomain", interfaceName: "myInterfaceName", lastSeenDateMs: 111, qos: new ProviderQos({ customParameters: [], priority: 1, scope: ProviderScope.GLOBAL, supportsOnChangeSubscriptions: true }), participantId: "1", isLocal: false, publicKeyId: "", expiryDateMs }), new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), domain: "myDomain", interfaceName: "myInterfaceName", lastSeenDateMs: 333, qos: new ProviderQos({ customParameters: [], priority: 4, scope: ProviderScope.GLOBAL, supportsOnChangeSubscriptions: true }), participantId: "1", isLocal: false, publicKeyId: "", expiryDateMs }), new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), domain: "myWithKeywordDomain", interfaceName: "myInterfaceName", lastSeenDateMs: 222, qos: new ProviderQos({ customParameters: [ new CustomParameter({ name: "keyword", value: "myKeyword" }), new CustomParameter({ name: "thename", value: "theValue" }) ], priority: 3, scope: ProviderScope.GLOBAL, supportsOnChangeSubscriptions: true }), participantId: "1", isLocal: false, publicKeyId: "", expiryDateMs }), new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), domain: "myDomain", interfaceName: "myInterfaceNameKeyword", lastSeenDateMs: 555, qos: new ProviderQos({ customParameters: [ new CustomParameter({ name: "keyword", value: "wrongKeyword" }), new CustomParameter({ name: "theName", value: "theValue" }) ], priority: 5, scope: ProviderScope.GLOBAL, supportsOnChangeSubscriptions: true }), participantId: "1", isLocal: false, publicKeyId: "", expiryDateMs }), new DiscoveryEntryWithMetaInfo({ providerVersion: new Version({ majorVersion: 47, minorVersion: 11 }), domain: "myDomain", interfaceName: "myInterfaceName", lastSeenDateMs: 444, qos: new ProviderQos({ customParameters: [ new CustomParameter({ name: "keyword", value: "myKeyword" }), new CustomParameter({ name: "theName", value: "theValue" }) ], priority: 2, scope: ProviderScope.GLOBAL, supportsOnChangeSubscriptions: true }), participantId: "1", isLocal: false, publicKeyId: "", expiryDateMs }) ]; } it("Strategy 'Nothing' does nothing", () => { expect(ArbitrationStrategyCollection.Nothing(getDiscoveryEntryWithMetaInfoList())).toEqual( getDiscoveryEntryWithMetaInfoList() ); }); it("Strategy 'HighestPriority' includes all capability infos", () => { const discoveryEntryList = getDiscoveryEntryWithMetaInfoList(); let discoveryEntryId: any; const highestPriority = ArbitrationStrategyCollection.HighestPriority(discoveryEntryList); for (discoveryEntryId in discoveryEntryList) { if (discoveryEntryList.hasOwnProperty(discoveryEntryId)) { expect(highestPriority).toContain(discoveryEntryList[discoveryEntryId]); } } }); it("Strategy 'HighestPriority' sorts according to providerQos priority", () => { const highestPriority = ArbitrationStrategyCollection.HighestPriority(getDiscoveryEntryWithMetaInfoList()); let i: any; for (i = 0; i < highestPriority.length - 1; ++i) { expect(highestPriority[i].qos.priority).toBeGreaterThan(highestPriority[i + 1].qos.priority); } }); it("Strategy 'LastSeen' includes all capability infos", () => { const discoveryEntryList = getDiscoveryEntryWithMetaInfoList(); let discoveryEntryId: any; const latestSeen = ArbitrationStrategyCollection.LastSeen(discoveryEntryList); for (discoveryEntryId in discoveryEntryList) { if (discoveryEntryList.hasOwnProperty(discoveryEntryId)) { expect(latestSeen).toContain(discoveryEntryList[discoveryEntryId]); } } }); it("Strategy 'LastSeen' sorts according to lastSeenDateMs priority", () => { const lastSeen = ArbitrationStrategyCollection.LastSeen(getDiscoveryEntryWithMetaInfoList()); let i: any; for (i = 0; i < lastSeen.length - 1; ++i) { expect(lastSeen[i].lastSeenDateMs).toBeGreaterThan(lastSeen[i + 1].lastSeenDateMs); } }); it("Strategy 'FixedParticipantId' gets discovered capability based on fixed participantId", () => { const discoveredEntries = ArbitrationStrategyCollection.FixedParticipant( getDiscoveryEntryWithMetaInfoForFixedParticipantId() ); expect(discoveredEntries.length).toBe(1); expect(discoveredEntries[0].participantId).toBe("myFixedParticipantId"); expect(discoveredEntries[0].interfaceName).toBe("myInterfaceName"); }); it("Strategy 'Keyword' only includes capability infos that have the keyword Qos set to 'myKeyword'", () => { let discoveryEntryId: any; let qosId: any; let found: any; let qosParam: any; const keyword = "myKeyword"; const discoveryEntryList = getDiscoveryEntryWithMetaInfoList(); // The arbitrator only calls the strategy with the list // of capabillities, so Keyword should be tested with bind() // which however is not supported by PhantomJS 1 /* var arbitrationStrategy = ArbitrationStrategyCollection.Keyword.bind( undefined, keyword); var keywordCapInfoList = arbitrationStrategy(discoveryEntryList); */ const keywordCapInfoList = ArbitrationStrategyCollection.Keyword(keyword, discoveryEntryList); expect(keywordCapInfoList.length).toBe(2); for (discoveryEntryId in discoveryEntryList) { if (discoveryEntryList.hasOwnProperty(discoveryEntryId)) { const capInfo = discoveryEntryList[discoveryEntryId]; found = false; if (capInfo.qos.customParameters && Array.isArray(capInfo.qos.customParameters)) { for (qosId in capInfo.qos.customParameters) { if (capInfo.qos.customParameters.hasOwnProperty(qosId)) { qosParam = capInfo.qos.customParameters[qosId]; if (!found && qosParam && qosParam.value && qosParam.value === keyword) { found = true; } } } } if (found) { expect(keywordCapInfoList).toContain(capInfo); } else { expect(keywordCapInfoList).not.toContain(capInfo); } } } }); it("Strategy 'Keyword' only matches against CustomParameters with name 'keyword' and the right keyword", () => { const rightKeyword = "rightKeyword"; const rightName = "keyword"; const wrongName = "wrongName"; const wrongKeyword = "wrongKeyword"; // this object isn't a practical input. For the tests unnecessary keys got removed const discoveryEntryList = [ { domain: "correct", qos: { customParameters: [ new CustomParameter({ name: rightName, value: rightKeyword }) ] } }, { domain: "wrongName", qos: { customParameters: [ new CustomParameter({ name: wrongName, value: wrongKeyword }) ] } }, { domain: "wrongKeyword", qos: { customParameters: [ new CustomParameter({ name: rightName, value: wrongKeyword }) ] } }, { domain: "allWrong", qos: { customParameters: [ new CustomParameter({ name: wrongName, value: wrongKeyword }) ] } } ]; const keywordCapInfoList = ArbitrationStrategyCollection.Keyword(rightKeyword, discoveryEntryList as any); expect(keywordCapInfoList.length).toBe(1); expect(keywordCapInfoList[0].domain).toEqual("correct"); }); });
the_stack
// replace ` (\w*),(\d*),.*` by `export const $1 = $2;` // General errors export const ERROR_NO_ERROR = 0; export const ERROR_FAILED = 1; export const ERROR_SYS_ERROR = 2; export const ERROR_OUT_OF_MEMORY = 3; export const ERROR_INTERNAL = 4; export const ERROR_ILLEGAL_NUMBER = 5; export const ERROR_NUMERIC_OVERFLOW = 6; export const ERROR_ILLEGAL_OPTION = 7; export const ERROR_DEAD_PID = 8; export const ERROR_NOT_IMPLEMENTED = 9; export const ERROR_BAD_PARAMETER = 10; export const ERROR_FORBIDDEN = 11; export const ERROR_OUT_OF_MEMORY_MMAP = 12; export const ERROR_CORRUPTED_CSV = 13; export const ERROR_FILE_NOT_FOUND = 14; export const ERROR_CANNOT_WRITE_FILE = 15; export const ERROR_CANNOT_OVERWRITE_FILE = 16; export const ERROR_TYPE_ERROR = 17; export const ERROR_LOCK_TIMEOUT = 18; export const ERROR_CANNOT_CREATE_DIRECTORY = 19; export const ERROR_CANNOT_CREATE_TEMP_FILE = 20; export const ERROR_REQUEST_CANCELED = 21; export const ERROR_DEBUG = 22; export const ERROR_IP_ADDRESS_INVALID = 25; export const ERROR_FILE_EXISTS = 27; export const ERROR_LOCKED = 28; export const ERROR_DEADLOCK = 29; export const ERROR_SHUTTING_DOWN = 30; export const ERROR_ONLY_ENTERPRISE = 31; export const ERROR_RESOURCE_LIMIT = 32; export const ERROR_ARANGO_ICU_ERROR = 33; export const ERROR_CANNOT_READ_FILE = 34; export const ERROR_INCOMPATIBLE_VERSION = 35; export const ERROR_DISABLED = 36; // HTTP error status codes export const ERROR_HTTP_BAD_PARAMETER = 400; export const ERROR_HTTP_UNAUTHORIZED = 401; export const ERROR_HTTP_FORBIDDEN = 403; export const ERROR_HTTP_NOT_FOUND = 404; export const ERROR_HTTP_METHOD_NOT_ALLOWED = 405; export const ERROR_HTTP_NOT_ACCEPTABLE = 406; export const ERROR_HTTP_PRECONDITION_FAILED = 412; export const ERROR_HTTP_SERVER_ERROR = 500; export const ERROR_HTTP_SERVICE_UNAVAILABLE = 503; export const ERROR_HTTP_GATEWAY_TIMEOUT = 504; // HTTP processing errors export const ERROR_HTTP_CORRUPTED_JSON = 600; export const ERROR_HTTP_SUPERFLUOUS_SUFFICES = 601; // Internal ArangoDB storage errors // For errors that occur because of a programming error. export const ERROR_ARANGO_ILLEGAL_STATE = 1000; export const ERROR_ARANGO_DATAFILE_SEALED = 1002; export const ERROR_ARANGO_READ_ONLY = 1004; export const ERROR_ARANGO_DUPLICATE_IDENTIFIER = 1005; export const ERROR_ARANGO_DATAFILE_UNREADABLE = 1006; export const ERROR_ARANGO_DATAFILE_EMPTY = 1007; export const ERROR_ARANGO_RECOVERY = 1008; export const ERROR_ARANGO_DATAFILE_STATISTICS_NOT_FOUND = 1009; // External ArangoDB storage errors // For errors that occur because of an outside event. export const ERROR_ARANGO_CORRUPTED_DATAFILE = 1100; export const ERROR_ARANGO_ILLEGAL_PARAMETER_FILE = 1101; export const ERROR_ARANGO_CORRUPTED_COLLECTION = 1102; export const ERROR_ARANGO_MMAP_FAILED = 1103; export const ERROR_ARANGO_FILESYSTEM_FULL = 1104; export const ERROR_ARANGO_NO_JOURNAL = 1105; export const ERROR_ARANGO_DATAFILE_ALREADY_EXISTS = 1106; export const ERROR_ARANGO_DATADIR_LOCKED = 1107; export const ERROR_ARANGO_COLLECTION_DIRECTORY_ALREADY_EXISTS = 1108; export const ERROR_ARANGO_MSYNC_FAILED = 1109; export const ERROR_ARANGO_DATADIR_UNLOCKABLE = 1110; export const ERROR_ARANGO_SYNC_TIMEOUT = 1111; // General ArangoDB storage errors // For errors that occur when fulfilling a user request. export const ERROR_ARANGO_CONFLICT = 1200; export const ERROR_ARANGO_DATADIR_INVALID = 1201; export const ERROR_ARANGO_DOCUMENT_NOT_FOUND = 1202; export const ERROR_ARANGO_DATA_SOURCE_NOT_FOUND = 1203; export const ERROR_ARANGO_COLLECTION_PARAMETER_MISSING = 1204; export const ERROR_ARANGO_DOCUMENT_HANDLE_BAD = 1205; export const ERROR_ARANGO_MAXIMAL_SIZE_TOO_SMALL = 1206; export const ERROR_ARANGO_DUPLICATE_NAME = 1207; export const ERROR_ARANGO_ILLEGAL_NAME = 1208; export const ERROR_ARANGO_NO_INDEX = 1209; export const ERROR_ARANGO_UNIQUE_CONSTRAINT_VIOLATED = 1210; export const ERROR_ARANGO_INDEX_NOT_FOUND = 1212; export const ERROR_ARANGO_CROSS_COLLECTION_REQUEST = 1213; export const ERROR_ARANGO_INDEX_HANDLE_BAD = 1214; export const ERROR_ARANGO_DOCUMENT_TOO_LARGE = 1216; export const ERROR_ARANGO_COLLECTION_NOT_UNLOADED = 1217; export const ERROR_ARANGO_COLLECTION_TYPE_INVALID = 1218; export const ERROR_ARANGO_VALIDATION_FAILED = 1219; export const ERROR_ARANGO_ATTRIBUTE_PARSER_FAILED = 1220; export const ERROR_ARANGO_DOCUMENT_KEY_BAD = 1221; export const ERROR_ARANGO_DOCUMENT_KEY_UNEXPECTED = 1222; export const ERROR_ARANGO_DATADIR_NOT_WRITABLE = 1224; export const ERROR_ARANGO_OUT_OF_KEYS = 1225; export const ERROR_ARANGO_DOCUMENT_KEY_MISSING = 1226; export const ERROR_ARANGO_DOCUMENT_TYPE_INVALID = 1227; export const ERROR_ARANGO_DATABASE_NOT_FOUND = 1228; export const ERROR_ARANGO_DATABASE_NAME_INVALID = 1229; export const ERROR_ARANGO_USE_SYSTEM_DATABASE = 1230; export const ERROR_ARANGO_ENDPOINT_NOT_FOUND = 1231; export const ERROR_ARANGO_INVALID_KEY_GENERATOR = 1232; export const ERROR_ARANGO_INVALID_EDGE_ATTRIBUTE = 1233; export const ERROR_ARANGO_INDEX_DOCUMENT_ATTRIBUTE_MISSING = 1234; export const ERROR_ARANGO_INDEX_CREATION_FAILED = 1235; export const ERROR_ARANGO_WRITE_THROTTLE_TIMEOUT = 1236; export const ERROR_ARANGO_COLLECTION_TYPE_MISMATCH = 1237; export const ERROR_ARANGO_COLLECTION_NOT_LOADED = 1238; export const ERROR_ARANGO_DOCUMENT_REV_BAD = 1239; // Checked ArangoDB storage errors // For errors that occur but are anticipated. export const ERROR_ARANGO_DATAFILE_FULL = 1300; export const ERROR_ARANGO_EMPTY_DATADIR = 1301; export const ERROR_ARANGO_TRY_AGAIN = 1302; export const ERROR_ARANGO_BUSY = 1303; export const ERROR_ARANGO_MERGE_IN_PROGRESS = 1304; export const ERROR_ARANGO_IO_ERROR = 1305; // ArangoDB replication errors export const ERROR_REPLICATION_NO_RESPONSE = 1400; export const ERROR_REPLICATION_INVALID_RESPONSE = 1401; export const ERROR_REPLICATION_MASTER_ERROR = 1402; export const ERROR_REPLICATION_MASTER_INCOMPATIBLE = 1403; export const ERROR_REPLICATION_MASTER_CHANGE = 1404; export const ERROR_REPLICATION_LOOP = 1405; export const ERROR_REPLICATION_UNEXPECTED_MARKER = 1406; export const ERROR_REPLICATION_INVALID_APPLIER_STATE = 1407; export const ERROR_REPLICATION_UNEXPECTED_TRANSACTION = 1408; export const ERROR_REPLICATION_INVALID_APPLIER_CONFIGURATION = 1410; export const ERROR_REPLICATION_RUNNING = 1411; export const ERROR_REPLICATION_APPLIER_STOPPED = 1412; export const ERROR_REPLICATION_NO_START_TICK = 1413; export const ERROR_REPLICATION_START_TICK_NOT_PRESENT = 1414; export const ERROR_REPLICATION_WRONG_CHECKSUM = 1416; export const ERROR_REPLICATION_SHARD_NONEMPTY = 1417; // ArangoDB cluster errors export const ERROR_CLUSTER_NO_AGENCY = 1450; export const ERROR_CLUSTER_NO_COORDINATOR_HEADER = 1451; export const ERROR_CLUSTER_COULD_NOT_LOCK_PLAN = 1452; export const ERROR_CLUSTER_COLLECTION_ID_EXISTS = 1453; export const ERROR_CLUSTER_COULD_NOT_CREATE_COLLECTION_IN_PLAN = 1454; export const ERROR_CLUSTER_COULD_NOT_READ_CURRENT_VERSION = 1455; export const ERROR_CLUSTER_COULD_NOT_CREATE_COLLECTION = 1456; export const ERROR_CLUSTER_TIMEOUT = 1457; export const ERROR_CLUSTER_COULD_NOT_REMOVE_COLLECTION_IN_PLAN = 1458; export const ERROR_CLUSTER_COULD_NOT_REMOVE_COLLECTION_IN_CURRENT = 1459; export const ERROR_CLUSTER_COULD_NOT_CREATE_DATABASE_IN_PLAN = 1460; export const ERROR_CLUSTER_COULD_NOT_CREATE_DATABASE = 1461; export const ERROR_CLUSTER_COULD_NOT_REMOVE_DATABASE_IN_PLAN = 1462; export const ERROR_CLUSTER_COULD_NOT_REMOVE_DATABASE_IN_CURRENT = 1463; export const ERROR_CLUSTER_SHARD_GONE = 1464; export const ERROR_CLUSTER_CONNECTION_LOST = 1465; export const ERROR_CLUSTER_MUST_NOT_SPECIFY_KEY = 1466; export const ERROR_CLUSTER_GOT_CONTRADICTING_ANSWERS = 1467; export const ERROR_CLUSTER_NOT_ALL_SHARDING_ATTRIBUTES_GIVEN = 1468; export const ERROR_CLUSTER_MUST_NOT_CHANGE_SHARDING_ATTRIBUTES = 1469; export const ERROR_CLUSTER_UNSUPPORTED = 1470; export const ERROR_CLUSTER_ONLY_ON_COORDINATOR = 1471; export const ERROR_CLUSTER_READING_PLAN_AGENCY = 1472; export const ERROR_CLUSTER_COULD_NOT_TRUNCATE_COLLECTION = 1473; export const ERROR_CLUSTER_AQL_COMMUNICATION = 1474; export const ERROR_ARANGO_DOCUMENT_NOT_FOUND_OR_SHARDING_ATTRIBUTES_CHANGED = 1475; export const ERROR_CLUSTER_COULD_NOT_DETERMINE_ID = 1476; export const ERROR_CLUSTER_ONLY_ON_DBSERVER = 1477; export const ERROR_CLUSTER_BACKEND_UNAVAILABLE = 1478; export const ERROR_CLUSTER_UNKNOWN_CALLBACK_ENDPOINT = 1479; export const ERROR_CLUSTER_AGENCY_STRUCTURE_INVALID = 1480; export const ERROR_CLUSTER_AQL_COLLECTION_OUT_OF_SYNC = 1481; export const ERROR_CLUSTER_COULD_NOT_CREATE_INDEX_IN_PLAN = 1482; export const ERROR_CLUSTER_COULD_NOT_DROP_INDEX_IN_PLAN = 1483; export const ERROR_CLUSTER_CHAIN_OF_DISTRIBUTESHARDSLIKE = 1484; export const ERROR_CLUSTER_MUST_NOT_DROP_COLL_OTHER_DISTRIBUTESHARDSLIKE = 1485; export const ERROR_CLUSTER_UNKNOWN_DISTRIBUTESHARDSLIKE = 1486; export const ERROR_CLUSTER_INSUFFICIENT_DBSERVERS = 1487; export const ERROR_CLUSTER_COULD_NOT_DROP_FOLLOWER = 1488; export const ERROR_CLUSTER_SHARD_LEADER_REFUSES_REPLICATION = 1489; export const ERROR_CLUSTER_SHARD_FOLLOWER_REFUSES_OPERATION = 1490; export const ERROR_CLUSTER_SHARD_LEADER_RESIGNED = 1491; export const ERROR_CLUSTER_AGENCY_COMMUNICATION_FAILED = 1492; export const ERROR_CLUSTER_DISTRIBUTE_SHARDS_LIKE_REPLICATION_FACTOR = 1493; export const ERROR_CLUSTER_DISTRIBUTE_SHARDS_LIKE_NUMBER_OF_SHARDS = 1494; export const ERROR_CLUSTER_LEADERSHIP_CHALLENGE_ONGOING = 1495; export const ERROR_CLUSTER_NOT_LEADER = 1496; export const ERROR_CLUSTER_COULD_NOT_CREATE_VIEW_IN_PLAN = 1497; export const ERROR_CLUSTER_VIEW_ID_EXISTS = 1498; export const ERROR_CLUSTER_COULD_NOT_DROP_COLLECTION = 1499; // ArangoDB query errors export const ERROR_QUERY_KILLED = 1500; export const ERROR_QUERY_PARSE = 1501; export const ERROR_QUERY_EMPTY = 1502; export const ERROR_QUERY_SCRIPT = 1503; export const ERROR_QUERY_NUMBER_OUT_OF_RANGE = 1504; export const ERROR_QUERY_INVALID_GEO_VALUE = 1505; export const ERROR_QUERY_VARIABLE_NAME_INVALID = 1510; export const ERROR_QUERY_VARIABLE_REDECLARED = 1511; export const ERROR_QUERY_VARIABLE_NAME_UNKNOWN = 1512; export const ERROR_QUERY_COLLECTION_LOCK_FAILED = 1521; export const ERROR_QUERY_TOO_MANY_COLLECTIONS = 1522; export const ERROR_QUERY_DOCUMENT_ATTRIBUTE_REDECLARED = 1530; export const ERROR_QUERY_FUNCTION_NAME_UNKNOWN = 1540; export const ERROR_QUERY_FUNCTION_ARGUMENT_NUMBER_MISMATCH = 1541; export const ERROR_QUERY_FUNCTION_ARGUMENT_TYPE_MISMATCH = 1542; export const ERROR_QUERY_INVALID_REGEX = 1543; export const ERROR_QUERY_BIND_PARAMETERS_INVALID = 1550; export const ERROR_QUERY_BIND_PARAMETER_MISSING = 1551; export const ERROR_QUERY_BIND_PARAMETER_UNDECLARED = 1552; export const ERROR_QUERY_BIND_PARAMETER_TYPE = 1553; export const ERROR_QUERY_INVALID_LOGICAL_VALUE = 1560; export const ERROR_QUERY_INVALID_ARITHMETIC_VALUE = 1561; export const ERROR_QUERY_DIVISION_BY_ZERO = 1562; export const ERROR_QUERY_ARRAY_EXPECTED = 1563; export const ERROR_QUERY_FAIL_CALLED = 1569; export const ERROR_QUERY_GEO_INDEX_MISSING = 1570; export const ERROR_QUERY_FULLTEXT_INDEX_MISSING = 1571; export const ERROR_QUERY_INVALID_DATE_VALUE = 1572; export const ERROR_QUERY_MULTI_MODIFY = 1573; export const ERROR_QUERY_INVALID_AGGREGATE_EXPRESSION = 1574; export const ERROR_QUERY_COMPILE_TIME_OPTIONS = 1575; export const ERROR_QUERY_EXCEPTION_OPTIONS = 1576; export const ERROR_QUERY_DISALLOWED_DYNAMIC_CALL = 1578; export const ERROR_QUERY_ACCESS_AFTER_MODIFICATION = 1579; // AQL user function errors export const ERROR_QUERY_FUNCTION_INVALID_NAME = 1580; export const ERROR_QUERY_FUNCTION_INVALID_CODE = 1581; export const ERROR_QUERY_FUNCTION_NOT_FOUND = 1582; export const ERROR_QUERY_FUNCTION_RUNTIME_ERROR = 1583; // AQL query registry errors export const ERROR_QUERY_BAD_JSON_PLAN = 1590; export const ERROR_QUERY_NOT_FOUND = 1591; export const ERROR_QUERY_IN_USE = 1592; export const ERROR_QUERY_USER_ASSERT = 1593; export const ERROR_QUERY_USER_WARN = 1594; // ArangoDB cursor errors export const ERROR_CURSOR_NOT_FOUND = 1600; export const ERROR_CURSOR_BUSY = 1601; // ArangoDB transaction errors export const ERROR_TRANSACTION_INTERNAL = 1650; export const ERROR_TRANSACTION_NESTED = 1651; export const ERROR_TRANSACTION_UNREGISTERED_COLLECTION = 1652; export const ERROR_TRANSACTION_DISALLOWED_OPERATION = 1653; export const ERROR_TRANSACTION_ABORTED = 1654; // User management errors export const ERROR_USER_INVALID_NAME = 1700; export const ERROR_USER_INVALID_PASSWORD = 1701; export const ERROR_USER_DUPLICATE = 1702; export const ERROR_USER_NOT_FOUND = 1703; export const ERROR_USER_CHANGE_PASSWORD = 1704; export const ERROR_USER_EXTERNAL = 1705; // Service management errors (legacy) // These have been superceded by the Foxx management errors in public APIs. export const ERROR_SERVICE_INVALID_NAME = 1750; export const ERROR_SERVICE_INVALID_MOUNT = 1751; export const ERROR_SERVICE_DOWNLOAD_FAILED = 1752; export const ERROR_SERVICE_UPLOAD_FAILED = 1753; // LDAP errors export const ERROR_LDAP_CANNOT_INIT = 1800; export const ERROR_LDAP_CANNOT_SET_OPTION = 1801; export const ERROR_LDAP_CANNOT_BIND = 1802; export const ERROR_LDAP_CANNOT_UNBIND = 1803; export const ERROR_LDAP_CANNOT_SEARCH = 1804; export const ERROR_LDAP_CANNOT_START_TLS = 1805; export const ERROR_LDAP_FOUND_NO_OBJECTS = 1806; export const ERROR_LDAP_NOT_ONE_USER_FOUND = 1807; export const ERROR_LDAP_USER_NOT_IDENTIFIED = 1808; export const ERROR_LDAP_INVALID_MODE = 1820; // Task errors export const ERROR_TASK_INVALID_ID = 1850; export const ERROR_TASK_DUPLICATE_ID = 1851; export const ERROR_TASK_NOT_FOUND = 1852; // Graph / traversal errors export const ERROR_GRAPH_INVALID_GRAPH = 1901; export const ERROR_GRAPH_COULD_NOT_CREATE_GRAPH = 1902; export const ERROR_GRAPH_INVALID_VERTEX = 1903; export const ERROR_GRAPH_COULD_NOT_CREATE_VERTEX = 1904; export const ERROR_GRAPH_COULD_NOT_CHANGE_VERTEX = 1905; export const ERROR_GRAPH_INVALID_EDGE = 1906; export const ERROR_GRAPH_COULD_NOT_CREATE_EDGE = 1907; export const ERROR_GRAPH_COULD_NOT_CHANGE_EDGE = 1908; export const ERROR_GRAPH_TOO_MANY_ITERATIONS = 1909; export const ERROR_GRAPH_INVALID_FILTER_RESULT = 1910; export const ERROR_GRAPH_COLLECTION_MULTI_USE = 1920; export const ERROR_GRAPH_COLLECTION_USE_IN_MULTI_GRAPHS = 1921; export const ERROR_GRAPH_CREATE_MISSING_NAME = 1922; export const ERROR_GRAPH_CREATE_MALFORMED_EDGE_DEFINITION = 1923; export const ERROR_GRAPH_NOT_FOUND = 1924; export const ERROR_GRAPH_DUPLICATE = 1925; export const ERROR_GRAPH_VERTEX_COL_DOES_NOT_EXIST = 1926; export const ERROR_GRAPH_WRONG_COLLECTION_TYPE_VERTEX = 1927; export const ERROR_GRAPH_NOT_IN_ORPHAN_COLLECTION = 1928; export const ERROR_GRAPH_COLLECTION_USED_IN_EDGE_DEF = 1929; export const ERROR_GRAPH_EDGE_COLLECTION_NOT_USED = 1930; export const ERROR_GRAPH_NO_GRAPH_COLLECTION = 1932; export const ERROR_GRAPH_INVALID_EXAMPLE_ARRAY_OBJECT_STRING = 1933; export const ERROR_GRAPH_INVALID_EXAMPLE_ARRAY_OBJECT = 1934; export const ERROR_GRAPH_INVALID_NUMBER_OF_ARGUMENTS = 1935; export const ERROR_GRAPH_INVALID_PARAMETER = 1936; export const ERROR_GRAPH_INVALID_ID = 1937; export const ERROR_GRAPH_COLLECTION_USED_IN_ORPHANS = 1938; export const ERROR_GRAPH_EDGE_COL_DOES_NOT_EXIST = 1939; export const ERROR_GRAPH_EMPTY = 1940; export const ERROR_GRAPH_INTERNAL_DATA_CORRUPT = 1941; export const ERROR_GRAPH_INTERNAL_EDGE_COLLECTION_ALREADY_SET = 1942; export const ERROR_GRAPH_CREATE_MALFORMED_ORPHAN_LIST = 1943; export const ERROR_GRAPH_EDGE_DEFINITION_IS_DOCUMENT = 1944; // Session errors export const ERROR_SESSION_UNKNOWN = 1950; export const ERROR_SESSION_EXPIRED = 1951; // Simple Client errors export const SIMPLE_CLIENT_UNKNOWN_ERROR = 2000; export const SIMPLE_CLIENT_COULD_NOT_CONNECT = 2001; export const SIMPLE_CLIENT_COULD_NOT_WRITE = 2002; export const SIMPLE_CLIENT_COULD_NOT_READ = 2003; // Communicator errors export const COMMUNICATOR_REQUEST_ABORTED = 2100; export const COMMUNICATOR_DISABLED = 2101; // Foxx management errors export const ERROR_MALFORMED_MANIFEST_FILE = 3000; export const ERROR_INVALID_SERVICE_MANIFEST = 3001; export const ERROR_SERVICE_FILES_MISSING = 3002; export const ERROR_SERVICE_FILES_OUTDATED = 3003; export const ERROR_INVALID_FOXX_OPTIONS = 3004; export const ERROR_INVALID_MOUNTPOINT = 3007; export const ERROR_SERVICE_NOT_FOUND = 3009; export const ERROR_SERVICE_NEEDS_CONFIGURATION = 3010; export const ERROR_SERVICE_MOUNTPOINT_CONFLICT = 3011; export const ERROR_SERVICE_MANIFEST_NOT_FOUND = 3012; export const ERROR_SERVICE_OPTIONS_MALFORMED = 3013; export const ERROR_SERVICE_SOURCE_NOT_FOUND = 3014; export const ERROR_SERVICE_SOURCE_ERROR = 3015; export const ERROR_SERVICE_UNKNOWN_SCRIPT = 3016; // JavaScript module loader errors export const ERROR_MODULE_NOT_FOUND = 3100; export const ERROR_MODULE_SYNTAX_ERROR = 3101; export const ERROR_MODULE_FAILURE = 3103; // Enterprise errors export const ERROR_NO_SMART_COLLECTION = 4000; export const ERROR_NO_SMART_GRAPH_ATTRIBUTE = 4001; export const ERROR_CANNOT_DROP_SMART_COLLECTION = 4002; export const ERROR_KEY_MUST_BE_PREFIXED_WITH_SMART_GRAPH_ATTRIBUTE = 4003; export const ERROR_ILLEGAL_SMART_GRAPH_ATTRIBUTE = 4004; export const ERROR_SMART_GRAPH_ATTRIBUTE_MISMATCH = 4005; // Cluster repair errors export const ERROR_CLUSTER_REPAIRS_FAILED = 5000; export const ERROR_CLUSTER_REPAIRS_NOT_ENOUGH_HEALTHY = 5001; export const ERROR_CLUSTER_REPAIRS_REPLICATION_FACTOR_VIOLATED = 5002; export const ERROR_CLUSTER_REPAIRS_NO_DBSERVERS = 5003; export const ERROR_CLUSTER_REPAIRS_MISMATCHING_LEADERS = 5004; export const ERROR_CLUSTER_REPAIRS_MISMATCHING_FOLLOWERS = 5005; export const ERROR_CLUSTER_REPAIRS_INCONSISTENT_ATTRIBUTES = 5006; export const ERROR_CLUSTER_REPAIRS_MISMATCHING_SHARDS = 5007; export const ERROR_CLUSTER_REPAIRS_JOB_FAILED = 5008; export const ERROR_CLUSTER_REPAIRS_JOB_DISAPPEARED = 5009; export const ERROR_CLUSTER_REPAIRS_OPERATION_FAILED = 5010; // Agency errors export const ERROR_AGENCY_INQUIRY_SYNTAX = 20001; export const ERROR_AGENCY_INFORM_MUST_BE_OBJECT = 20011; export const ERROR_AGENCY_INFORM_MUST_CONTAIN_TERM = 20012; export const ERROR_AGENCY_INFORM_MUST_CONTAIN_ID = 20013; export const ERROR_AGENCY_INFORM_MUST_CONTAIN_ACTIVE = 20014; export const ERROR_AGENCY_INFORM_MUST_CONTAIN_POOL = 20015; export const ERROR_AGENCY_INFORM_MUST_CONTAIN_MIN_PING = 20016; export const ERROR_AGENCY_INFORM_MUST_CONTAIN_MAX_PING = 20017; export const ERROR_AGENCY_INFORM_MUST_CONTAIN_TIMEOUT_MULT = 20018; export const ERROR_AGENCY_INQUIRE_CLIENT_ID_MUST_BE_STRING = 20020; export const ERROR_AGENCY_CANNOT_REBUILD_DBS = 20021; // Supervision errors export const ERROR_SUPERVISION_GENERAL_FAILURE = 20501; // Dispatcher errors export const ERROR_DISPATCHER_IS_STOPPING = 21001; export const ERROR_QUEUE_UNKNOWN = 21002; export const ERROR_QUEUE_FULL = 21003; // Maintenance errors export const ERROR_ACTION_ALREADY_REGISTERED = 6001; export const ERROR_ACTION_OPERATION_UNABORTABLE = 6002; export const ERROR_ACTION_UNFINISHED = 6003; export const ERROR_NO_SUCH_ACTION = 6004;
the_stack
import { ProfessionName, ProfessionSector } from '../npc-generation/professions' import { EconomicIdeology, PoliticalIdeology } from '../town/townData' import { PoliticalSource, Town, TownRolls } from '../town/_common' import { Alignments, ClericDomains } from '../src/worldType' import { RaceName, GenderName, NPC, ThresholdTable, PartialRecord, Virtues } from '@lib' export type DeityRank = | 'leader' | 'greater deity' | 'intermediate deity' | 'lesser deity' | 'immortal' | 'demigod' | 'saint' interface Followers { /** * @example 'Zeus is followed by many, of all different race and creed.' */ description: string /** * Who actually worshipped the god? * @example Poseidon : 'Sailors' */ adherents?: string[] | Information[] /** * @example 'spear' * @usage 'In battle, his followers favour the ${favouredWeapon}' */ favouredWeapon: string /** * Days that are considered holy. */ holyDays: Information race?: RaceName // base?: Partial<NPC> /** * Certain groups might be excluded from following a deity. */ excluded?: Followers } export interface Pantheon { /** * The name of the patheon, without riders or indefinite articles. * @example 'Greek' * @usage "The `Greek` gods" */ name: string /** * The description of the whole pantheon. * @example 'The gods of Olympus make themselves known with the gentle lap of waves against the shores and the crash of the thunder among the cloud–enshrouded peaks. The thick boar–infested woods and the sere, olive–covered hillsides hold evidence of their passing. Every aspect of nature echoes with their presence, and they’ve made a place for themselves inside the human heart, too.' */ description: string /** * Origin stories! */ origin?: string /** * Who follows the pantheon? */ followers?: Followers gods: Deity[] meta?: { /** Who originally created this pantheon? */ author?: string /** If multiple people worked on this, add their names to the array. */ contributors?: string[] /** If you hold the copyright to the pantheon, you may list it here. Public domain pantheons (i.e. Norse, etc.) may be specified as public domain. */ license?: string /** If this pantheon is hosted online, link it here. */ repository?: string /** Helps troubleshoot any issues people may have if there's a version number. */ version?: number /** Any other information that you might care to tell the reader, such as an email address to contact them, etc. */ notes?: string } } export type DeityStatus = 'alive' | 'imprisoned' | 'dormant' | 'dead' | 'uncertain' export interface Deity { /** * @readonly * This makes tippy work. Keep it exactly like this. */ objectType: 'deity' /** * @readonly * Required for profiles. Keep it exactly like this. */ passageName: 'DeityProfile' /** * For sanity's sake, only one name is allowed so we can easily find the deity. If your deity has multiple names, you can add them to `aliases`, which it will be pulled from at random. */ name: string /** Needed to make the profiles work */ key: string /** * Some gods have died, or else have been imprisoned, or they have just retreated to dormancy. * Some people may still worship these gods, so their status is important. * Using the type is preferred, as it detects tense. * @example ```Baldr: 'dead'``` * @example ```Kronos: 'imprisoned'``` * @example ```Pan: 'uncertain'``` */ status: DeityStatus | string /** * Used to determine how likely a god is to be worshipped, either at the town level, or the NPC level. */ probabilityWeightings?: { economicIdeology?: PartialRecord<EconomicIdeology, number> politicalIdeology?: PartialRecord<PoliticalIdeology, number> politicalSource?: PartialRecord<PoliticalSource, number> rolls?: PartialRecord<TownRolls, number> /** * Some races are going to be more interested in certain gods than others. * Uses weighted probabilities (default for races ommitted is 10) * Can be turned off. */ race?: PartialRecord<RaceName, number> npc?: { /** * Some races are going to be more interested in certain gods than others. * @warn This _multiplies_ the probability. * Can be turned off. */ race?: PartialRecord<RaceName, number> /** * Generic catch-all function for NPCs trying to pick a god to follow. */ func?: (town: Town, npc: NPC) => void /** * If there's a Patron Deity of Cheesemakers in the Pantheon, it's pretty likely that the cheesemaker will worship that deity. */ profession?: PartialRecord<ProfessionName, number> /** * Profession sector is applied as well as Professions. */ professionSector?: PartialRecord<ProfessionSector, number> } } /** * For the deity with many names, use `aliases`. When an alias is used instead of the 'main' name, it will be specified that the deity is also known as `name`. * NOTE: This is when there are multiple names for the same god - if two cultures have similar gods it should be 'equivalent' * @example aliases: ['El', 'Anu', 'An', 'Thoru-el'] */ aliases: string[] /** * While Zeus and Jupiter are arguably the same god, Aphrodite and Ishtar are not, but there is a connection between them. * @example Aphrodite: ['Ishtar', 'Astarte'] */ equivalent?: string[] /** * All of the titles that a god might have. Will typically be used as a rider after the name. * @example ['Lord of the Skies', 'Ruler of All That He Sees'] * @usage 'Zeus, Lord of the Skies' */ titles: string[] /** * Trying to make rank more granular is just asking for trouble. * @default 'lesser deity' */ rank: DeityRank /** * Description of the deity overall. If omitted, description will be generated from the rest of the included data. */ description: string /** * Description of how the deity is depicted typically. Distinct from their `avatars`. * @usage '${deity.name} is depicted as ______' */ appearance: string /** * Just in case you have history that you want to cover. */ history: Information /** * For smart one-liners, or quotes about the deity. * Will be printed in a <blockquote> element. * If given an array, will be picked at random. * @example { * description: 'Bear up, my child, bear up; Zeus who oversees and directs all things is still mighty in heaven.', * author: 'Sophocles' * } */ quotes?: Quotation[] /** Any powers that you want to add. */ powers?: Information /** * Generic extra text. * @example [ * '<h4>Birth</h4>', 'The birth of Zeus was not your average birth.', * '<h4>Death</h4>', 'Zeus dies at the end of the film.' * ] */ paragraphs?: Information /** * The aspects that the deity manages. This does not mean that no other god has power over this area, just that the god shares in responsibility for the portfolio * @example Zeus: ['the skies', 'thunder and lightning', 'law and order', 'fate'] * @usage 'Zeus is God of `the skies`, `thunder and lightning`, `law and order`, and `fate`. */ portfolios: string[] /** * To assign whether to call them gods, goddesses, or deities, and use the correct pronouns. * @warn This is _not_ suggesting that they are always that gender. * Rather, it is the gender that people commonly would use when referring to the deity. * Loki, for example, famously gave birth to Sleipnir. * However, he still presents as male in most mythology. * Avatars can have different genders to their corresponding god. */ gender: GenderName /** * What race the god actually is, E.g. Vanir, Aesir, Jotunn * @default 'god' */ race: RaceName | string /** * The race the deity is or appears as. Demigods and mortals who ascended to be gods are 'Demigod' or 'RaceName' but are marked as a god or immortal in Rank * @default 'human' */ shape: RaceName | string /** * For the Norse Aesir/Vanir split */ faction?: string /** * For spirits and other things that shouldn't be called gods, goddesses, or deities. */ wordNoun?: string /** * Distinct from `portfolios`, Domains are used in 5th Edition Dungeons and Dragons to assign spells. */ domains: ClericDomains[] /** * For channel divinity spells and features. */ channelDivinity?: Information /** * Alignments, for those that are still stuck on 2nd Edition. */ alignment: Alignments /** * The equivalent of a deity's heraldry, an icon or symbol that represents them. Without any indefinite articles. * @example Zeus: 'fist full of lightning bolts' */ symbol?: string | string[] combat: Information /** * For things that the deity owns. */ possessions?: Information /** Some gods had planes/domain which they ruled * @example ```Odin: 'Valhalla'``` * @usage 'Hades resides in ______' */ realm?: string customImage?: URL followers: Partial<Followers> /** * If a deity particularly embodies a virtue or vice, it can be specified. * Expressed as a 0-100; values of lower than fifty being the opposite trait (i.e. `merciful: 2` means that they are very vindictive). * @example * Zeus: { * just: 70, * merciful: 20, * chaste: 80 * } */ personality: PartialRecord<Virtues, number> /** * Things that the god are associated with, e.g. Sacred plants and animals. */ associations?: { /** * A deity can have multiple different avatars, some more rare than others. */ avatars?: Avatar[] animals?: string[] plants?: string[] places?: string[] monsters?: string[] gems?: string[] colours?: string[] miscellaneous?: string[] } /** What is good to the worshipers of this deity? What do they believe? */ beliefs: Information /** What is verboten to the worshipers of this deity? What can they never do? */ heresies: Information /** * Some suggested blessings that might be bestowed by the deity. */ blessings: Information /** * Some suggested curses that might be cast by the deity. */ curses: Information /** * Who do the temple call their friends? */ allies: Information /** * Who are the enemies of the temple? */ enemies: Information /** * Who's their father? * @warn This is not bi-directional, as sometimes there are one-way relationships. */ relationships: Relationship[] /** * What words does the temple live by? Daily words that they use to remind themselves. */ maxims: Quotation[] } export interface Information { title?: string description?: string /** * If the children property is initialised as an empty array, that means that its parent won't be printed unless the description is filled in. * */ children?: Information[] | string[] opts?: { /** * When the object has the `title` property it defaults to `true`. * Otherwise, @default false * This is used when you want a header. * */ displayAsList: boolean /** * For the `title` tag. Only used when it's not in a list. * @default 'h3' */ element: HTMLElement suppressTitle: boolean } } interface Relationship { /** Will check to see if a deity matches the name provided. */ name: string relationship: string description?: string } interface Avatar extends Information { gender?: GenderName } interface Quotation extends Information { author?: string } export type PantheonTypes = 'greek' | 'norse' export type ReligionStrength = | 'fanatical true believer' | 'unshakingly devoted believer' | 'conspicuously faithful believer' | 'outspoken believer' | 'quiet true believer' | 'casual observer' | 'open-minded seeker' | 'cautious listener' | 'critical student' | 'outspoken cynic' | 'broken heretic' interface ReligionData { strength: ThresholdTable<ReligionStrength> pantheon: Record<string, Pantheon> abstractGod: string[] saint: string[] } export const religion: ReligionData = { strength: [ // npc.name is a _______ [100, 'fanatical true believer'], [90, 'unshakingly devoted believer'], [80, 'conspicuously faithful believer'], [70, 'outspoken believer'], [60, 'quiet true believer'], [50, 'casual observer'], [40, 'open-minded seeker'], [30, 'cautious listener'], [20, 'critical student'], [10, 'outspoken cynic'], [0, 'broken heretic'] ], abstractGod: [ 'Our Lady', 'Our Mother', 'the Ancient Flame', 'the Ancient Oak', 'the Autumn Singer', 'the Bat', 'the Battle-Lord', 'the Bear', 'the Beast', 'the Beast-Tamer', 'the Beast-Wife', 'the Beauty Queen', 'the Blood-Bringer', 'the Burning Man', 'the Crone', 'the Cruel King', 'the Dark Lady', 'the Dark Lord', 'the Dark Prophet', 'the Death Harbinger', 'the Doom Harbinger', 'the Doom-Maker', 'the Eagle', 'the Earth-Mother', 'the Earth-Queen', 'the Enemy', 'the Eternal Light', 'the Eternal Sage', 'the Fair Maiden', 'the Fatespinner', 'the Felled Tree', 'the Fire Dragon', 'the Forest Keeper', 'the Frog', 'the Gloom-Spider', 'the Goddess', 'the Grain-Grower', 'the Great Huntress', 'the Great Protector', 'the Great Smith', 'the Horned One', 'the Judge', 'the King Beneath the Waves', 'the Lawgiver', 'the Life-Keeper', 'the Life-Tree', "the Light's Son", 'the Magic-Maid', 'the Messenger', 'the Mighty Hunter', 'the Mighty One', 'the Mighty Warrior', 'the Mischief-Maker', 'the Moon-Witch', 'the Mountain Forger', 'the Night Queen', 'the Oathkeeper', 'the Oracle', 'the Prophet', 'the Sacred Grove', 'the Savior', 'the Scorpion', 'the Sea Dragon', 'the Sea God', 'the Sea Queen', 'the Seductress', 'the Shadow', 'the Shadowkeeper', 'the Shadow-Serpent', 'the Shield-Maiden', 'the Ship-Taker', 'the Sky Father', 'the Soothsayer', 'the Soul-Collector', 'the Soul-Eater', 'the Spider', 'the Spring Maiden', 'the Starfinder', 'the Stone Dragon', 'the Storm Dragon', 'the Storm King', 'the Storm-Bringer', 'the Summer Mistress', 'the Sunkeeper', 'the Sword-Prince', 'the Thief', 'the Tormenter', 'the Tree Spirit', 'the Undying Light', 'the Unnamed One', 'the Unyielding Tyrant', 'the Voice', 'the Wandering Rogue', 'the War-Maker', 'the Watcher', 'the Watchful Eye', 'the Wind King', 'the Winemaker', 'the Winter Lady', 'the Wolf' ], saint: [ 'Almar the Holy', 'Amaya the Seeress', 'Bahak the Preacher', 'Bahruz the Prophet', 'Lira the Flamekeeper', 'Mozar the Conqueror', 'Prince Tarunal', 'Queen Kalissa', 'Rahal the Sunsoul', 'Raham the Lightbringer', 'St. Aemilia', 'St. Albus', 'St. Anglos', 'St. Antonia', 'St. Antonus', 'St. Austyn', 'St. Bardo', 'St. Beatrix', 'St. Berta', 'St. Bettius', 'St. Bryenn', 'St. Buttercup', 'St. Carolo', 'St. Cedrick', 'St. Cordelia', 'St. Cowhan', 'St. Cumberbund', 'St. Dorys', 'St. Dreddos', 'St. Dwayn', 'St. Edwynna', 'St. Elayne', 'St. Falstyus', 'St. Farcas', 'St. Florenzo', 'St. Gabrella', 'St. Gaiorgus', 'St. Goodkynd', 'St. Hal', 'St. Halcincas', 'St. Haroldus', 'St. Hemingwar', 'St. Heraclora', 'St. Hermioninny', 'St. Hieronymus', 'St. Inigo', 'St. Jordyn', 'St. Katrynn', 'St. Lannus', 'St. Leo', 'St. Leryo', 'St. Londyn', 'St. Magio', 'St. Marius', 'St. Markuz', 'St. Martyn', 'St. Matromus', 'St. Morrsona', 'St. Morwayne', 'St. Murkel', 'St. Mychel', 'St. Nyneva', 'St. Paolo', 'St. Parrinus', 'St. Perseon', 'St. Petyr', 'St. Podryck', 'St. Polly', 'St. Pratchytt', 'St. Rawynn', 'St. Regus', 'St. Ricarddos', 'St. Roberts', 'St. Robinus', 'St. Rowhan', 'St. Rowlynna', 'St. Sansima', 'St. Sessimus', 'St. Severus', 'St. Stynebick', 'St. Symeon', 'St. Theseon', 'St. Thoryn', 'St. Tolkkyn', 'St. Twayn', 'St. Xavos', 'the Deliverer', 'the Doomcaller', 'the Doomsayer', 'the Lawgiver', 'the Oracle', 'the Prophet', 'the Savior', 'the Seeker', 'the Shadowseer', 'the Soothsayer', 'the Starwatcher', 'the Truthsayer', 'the Voice', 'Zefar the Sorcer' ], pantheon: { greek: { name: 'greek', description: 'The gods of Olympus make themselves known with the gentle lap of waves against the shores and the crash of the thunder among the cloud–enshrouded peaks. The thick boar–infested woods and the sere, olive–covered hillsides hold evidence of their passing. Every aspect of nature echoes with their presence, and they’ve made a place for themselves inside the human heart, too.', followers: { description: '', favouredWeapon: '', holyDays: { title: 'Holy Days', children: [] } }, gods: [ { // Zeus objectType: 'deity', passageName: 'DeityProfile', name: 'Zeus', key: 'Zeus', status: 'alive', titles: [ 'God of the Sky', 'Ruler of the Gods', 'The Thunderer', 'God of Refuge', 'Oathkeeper' ], aliases: [], rank: 'leader', description: 'Zeus is the leader of the Greek gods, and lives atop Mount Olympus, where he rules over the mortal world below.', appearance: 'Zeus is depicted as a regal, mature man with a sturdy figure and dark beard grasping a lightning bolt and wreathed in a crown of olive leaves.', history: { title: 'History' }, powers: { title: 'powers', children: [] }, quotes: [ { description: 'Bear up, my child, bear up; Zeus who oversees and directs all things is still mighty in heaven.', author: 'Sophocles' } ], portfolios: [ 'the skies', 'thunder and lightning', 'kings', 'law and order', 'fate', 'justice', 'moral conduct', 'guest-right' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'tempest', 'order' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: 'fist full of lightning bolts', combat: { title: 'Military Prowess', description: 'Zeus famously led the Greek gods in the battle against the Titans, and is a fearsome foe. He calls down electric energy and fashions them into mighty spears of lightning to hurl at his enemies.' }, probabilityWeightings: { politicalIdeology: { autocracy: 5, oligarchy: 3 }, politicalSource: { 'absolute monarchy': 6, 'constitutional monarchy': 3 }, race: { 'human': 20, 'half-elf': 5 } }, possessions: { title: 'Possessions', children: [ { title: 'Aegis', description: 'The Aegis bears the head of a Gorgon, and makes a terrible roaring sound in battle.' } ] }, realm: 'Olympus, where he rules over all.', followers: { description: 'Zeus is followed by many, of all different race and creed.', favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [ { title: 'earth', children: [ { title: 'January' }, { title: 'Thursday' } ] } ] } }, personality: { just: 70, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'eagle', 'bull' ], plants: [ 'oak tree', 'olive tree' ], monsters: [], gems: [], colours: ['yellow'], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [ { title: 'Oaths', description: 'A promise or an oath is a sacred bond that should not be broken.' } ] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Poseidon', relationship: 'brother' }, { name: 'Hades', relationship: 'brother' }, { name: 'Demeter', relationship: 'sister' }, { name: 'Athena', relationship: 'daughter' }, { name: 'Persephone', relationship: 'daughter' }, { name: 'Artemis', relationship: 'daughter' }, { name: 'Ares', relationship: 'son' }, { name: 'Apollo', relationship: 'son' } ], maxims: [ { title: '' } ] }, { // Poseidon objectType: 'deity', passageName: 'DeityProfile', name: 'Poseidon', key: 'Poseidon', status: 'alive', aliases: ['Neptune'], titles: [ 'God of the Sea and Earthquakes', 'Watcher', 'Shaker of the Earth', 'Horse Tender' ], rank: 'greater deity', description: 'Poseidon is the god of the Sea - all things underwater are under his purview', appearance: 'a mature man with a sturdy build and a dark beard holding a trident and a sea-creature encrusted boulder, simply crowned with a headband with a cloak draped around his arms.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'the sea', 'earthquakes', 'floods', 'drought', 'horses', 'fresh water' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'tempest' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Neutral', symbol: 'A trident and billowing cloak', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { primitivism: 3 }, politicalIdeology: { autocracy: 8, oligarchy: 5 }, politicalSource: { 'absolute monarchy': 5, 'constitutional monarchy': 5 }, race: { 'human': 20, 'half-elf': 5 } }, possessions: { title: 'Possessions', children: [ { title: 'Poseidon\'s Trident', description: 'Poseidon\'s trident was so powerful that it could shake the lands.' } ] }, realm: 'a palace underneath the sea, watching over the fishermen from below.', followers: { description: 'Poseidon is followed by many mariners, fishermen, and horse riders.', adherents: ['sailors', 'teamsters', 'fishermen', 'cavalry', 'farmers'], favouredWeapon: 'trident', holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'horse', 'dolphin', 'fish', 'bull' ], plants: [ 'pine tree', 'seaweed', 'wild celery' ], monsters: ['hippocampus'], gems: [], colours: ['blue'], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [ { title: 'smooth sailing', description: 'Poseidon will bless sailors and those that have earnt his favour with smooth passage.' }, { title: 'management of horses', description: 'As the Lord of Horses, Poseidon can calm equines as easily as he can enrage them.' } ] }, curses: { title: 'curses', children: [ { title: 'mad horses', description: 'As the Lord of Horses, Poseidon can enrage equines as easily as he can calm them.' }, { title: 'stormy seas', description: "Those that tempt Poseidon's wrath risk stormy seas on their next voyage." } ] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'brother' }, { name: 'Hades', relationship: 'brother' }, { name: 'Demeter', relationship: 'sister' }, { name: 'Hera', relationship: 'sister' }, { name: 'Hestia', relationship: 'sister' }, { name: 'Amphitrite', relationship: 'wife' } ], maxims: [ { title: '' } ] }, { // Hades objectType: 'deity', passageName: 'DeityProfile', name: 'Hades', key: 'Hades', status: 'alive', aliases: ['Pluto', 'Pluton', 'The Cthonic Zeus'], equivalent: ['Pluto'], // Pluto was originally a different god to Hades titles: [ 'God of the Dead', 'King of the Underworld', 'God of Wealth', 'Host of Many', 'The Impartial Binder', 'The invisible one' ], rank: 'greater deity', description: 'Hades is the god of the Dead and the first son of Kronos. However when He, Zeus and Poseidon were drawing lots for the division of the cosmos, Hades gained dominion of the Underworld, where he rules over the dead.', appearance: 'a dark-bearded, regal god, with a bird tipped sceptre with Cerebus seated by his throne.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'the underworld', 'the dead', 'funeral rites', 'right to be buried', 'fertile soil', 'precious metals', 'dreams from the dead', 'necromancy', 'curses' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'death', 'grave' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Lawful Evil', symbol: 'Helm of Hades', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { capitalism: 4 }, politicalIdeology: { kleptocracy: 5 }, politicalSource: { }, race: { dwarf: 20, tiefling: 30 } }, possessions: { title: 'Possessions', children: [ { title: 'Sceptre', description: 'A powerful relic that is able to create a passage between the worlds of the living and the dead' }, { title: 'Cap of Invisibility', description: 'A cap which can turn the wearer invisible' } ] }, realm: "the Underworld. As far below the earth as the heavens are above, Hades' realm is a dark and depressing place.", followers: { description: 'Hades, as the god of the dead, was a fearsome figure to those still living; in no hurry to meet him, they were reluctant to swear oaths in his name, and averted their faces when sacrificing to him. Since to many, simply to say the word "Hades" was frightening, euphemisms were pressed into use.', adherents: ['mourners', 'undertakers', 'necromancers', 'miners'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [ { title: 'second to last day of every month', description: 'Rituals are typically held on this day.' } ] } }, personality: { just: 90, merciful: -85, chaste: -20 }, associations: { avatars: [ // { // name: 'Ploutos', // appearance: undefined, // description: 'As Ploutos, Hades is the God of wealth and precious metals', // frequency: undefined, // powers: undefined // } ], animals: [ 'Screech-Owl', 'Serpents', // Not Sure 'Black-Rams' // Not Sure // Hades' Cattle? Not sure because it is specifically the cattle of Hades (Likewise Apollo has cattle that are his) ], plants: [ 'White Poplar', 'Mint', 'Cypress', 'Asphodel', 'Narcissus' ], monsters: [ 'Cerebus', 'The Erinyes' ], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [ { title: 'plenty from the earth', description: 'As the lord of the underworld, Hades has considerable wealth, and can bestow riches to those he deems worthy.' }, { title: 'the ability to go un-noticed', description: 'Hades can give those that wish to be unseen the power to avoid detection in the dark.' } ] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Poseidon', relationship: 'brother' }, { name: 'Zeus', relationship: 'brother' }, { name: 'Demeter', relationship: 'sister' }, { name: 'Hera', relationship: 'sister' }, { name: 'Hestia', relationship: 'sister' }, { name: 'Persephone', relationship: 'husband' } ], maxims: [ { title: '' } ] }, { // Aphrodite objectType: 'deity', passageName: 'DeityProfile', name: 'Aphrodite', key: 'Aphrodite', status: 'alive', aliases: ['Venus'], equivalent: ['Ishtar', 'Astarte'], titles: [ 'The Deviser', 'The Goddess for all folk', 'Smile-loving', 'The Goddess of Beauty', 'The Goddess of Sexuality', 'The Shapely', 'Killer of Men', 'Gravedigger', 'the Mother' ], rank: 'greater deity', description: 'Aphrodite is the goddess of love and scorns those who stay away from relationships. Her love can be a thing of beauty or a thing of terror and destruction.', appearance: 'Aphrodite is consistently portrayed as a nubile, infinitely desirable adult, having had no childhood.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'love', 'lovers', 'lust', 'sexuality', 'beauty', 'pleasure', 'procreation', 'prostitutes', 'love poetry' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'life', 'light', 'trickery', 'war' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Good', symbol: 'dove', combat: { title: 'Combat', children: [ { title: 'A Darker Side', description: 'While Aphrodite is most well known as the goddess of Love, she is also known as a goddess of War - especially by people like the Spartans.' } ] }, probabilityWeightings: { economicIdeology: { syndicalism: 4, primitivism: 8 }, politicalIdeology: { kleptocracy: 4, magocracy: 3 }, politicalSource: { }, race: { halfling: 20, tiefling: 15 } }, possessions: { title: 'Possessions', children: [ { title: 'Girdle', description: 'The Girdle inspires desire in all those who look upon the wearer' } ] }, realm: undefined, followers: { description: 'As the goddess of beauty and love the favour of Aphrodite was worshipped by all people, though especially by prostitutes.', adherents: ['everyone', 'prostitutes', 'warriors'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [ { title: 'the fourth day of every month', description: 'Rituals are typically held on this day.' } ] } }, personality: { just: 30, merciful: -85, chaste: -100 }, associations: { avatars: [ { title: 'Aphrodite Areia', description: 'Aphrodite Areia is a war-like aspect of Aphrodite. She appears clad in armour and bearing weapons and is worshipped by the Spartans and other war-loving people. Aphrodite is ready to use deciptive strategies, such as how she lured the Gigantes one by one into a cave for them to be murdered' } ], animals: [ 'dove', 'swan', 'goose', 'sparrow', 'swallow', 'dolphins', 'wryneck' // English name for Iynx ], plants: [ 'pomegranates', 'rose', 'myrtle', 'apple', 'poppy' ], monsters: ['nereids'], gems: [], colours: [], miscellaneous: ['conch shells'] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [ 'beauty' ] }, curses: { title: 'Curses', children: [ 'ugliness', 'unwashable stink' ] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' }, { name: 'Ares', relationship: 'lover' }, { name: 'Hephaestus', relationship: 'husband' }, { name: 'Hebe', relationship: 'sister' }, { name: 'Heracles', relationship: 'brother' }, { name: 'Persephone', relationship: 'sister' }, { name: 'Hermes', relationship: 'lover' }, { name: 'Dionysus', relationship: 'lover' }, { name: 'Poseidon', relationship: 'lover' } ], maxims: [ { title: '' } ] }, { // Artemis objectType: 'deity', passageName: 'DeityProfile', name: 'Artemis', key: 'Artemis', status: 'alive', aliases: ['Diana', 'Brauronia', 'Orthia'], equivalent: ['Selene', 'Britomartis', 'Dictynna', 'Eileithyial'], titles: [ 'Goddess of the Hunt', 'Goddess of the Beasts', 'Nurse of Children', 'Friend of Girls', 'Goddess of the Flocks and the Chase', 'The best advisor' ], rank: 'greater deity', description: 'Artemis is the goddess of the Hunt and young girls. She can change others into animals as punishment for transgressions against her and she demands appropriate respect from mortals.', appearance: 'a young woman wearing a short costume that leaves her legs free and wielding a bow with a quiver of arrows.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'hunting', 'the wilderness', 'wild animals', 'childbirth', 'chastity', 'sudden death and disease of girls', 'the moon', 'dawn', 'children', 'maidenhood', 'healing', 'ritual purification' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'nature', 'life', 'twilight' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral Good', symbol: 'bow and quiver of arrows', combat: { children: [ { title: 'A Dangerous Hunter', description: 'Artemis is quick to strike down those who offend her with animals and wild beasts. She is a dedicated huntress and will pursue her quarry until it is caught.' } ] }, probabilityWeightings: { economicIdeology: { feudalism: 2, primitivism: 6 }, politicalIdeology: { meritocracy: 4 }, politicalSource: { anarchy: 2 }, race: { 'elf': 40, 'half-elf': 20, 'halfling': 15 } }, possessions: { title: 'Possessions', children: [ { title: 'Bow of Artemis', description: 'The Bow of Artemis was forged by the Cyclopses' } ] }, realm: undefined, followers: { description: 'Artemis is worshipped by Hunters and Women, young girls could be expected to serve Artemis until they come of age.', adherents: ['hunters', 'young girls', 'expecting mothers', 'wild beings'], favouredWeapon: 'bow', holyDays: { title: 'Holy Days', children: [ { title: 'the sixth day of the week', description: 'Rituals are typically held on this day.' } ] } }, personality: { just: 50, merciful: -85, chaste: 100 }, associations: { avatars: [], animals: [ 'deer', 'bear', 'boar', 'heron', 'fresh-water fish', 'buzzard-hawk', 'guinea-fowl', 'partridge' ], plants: [ 'amaranth', 'asphodel', 'cypress', 'laurel', 'palm tree' ], monsters: ['nymphs', 'calydonian boar'], places: ['forests'], gems: [], colours: [], miscellaneous: ['lyre', 'torches', 'spears and nets'] }, beliefs: { title: 'beliefs', children: [ { title: 'chastity', description: 'Artemis and her followers value chastity above all else.' } ] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'Curses', children: [ { title: 'transformation into a wild animal', description: 'As goddess of the hunt, Artemis can transform those that wrong her into wild animas to be hunted.' } ] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' }, { name: 'Apollo', relationship: 'twin brother' } ], maxims: [ { title: '' } ] }, { // Apollo objectType: 'deity', passageName: 'DeityProfile', name: 'Apollo', key: 'Apollo', status: 'alive', aliases: ['Apollon'], titles: [ 'Of the Oracle', 'Shooter from Afar', 'the Healer', 'Averter of Harm', 'Of the Locusts' ], rank: 'greater deity', description: 'The twin brother of Artemis, Apollo is the inventor of music. Those that he loves and loses or those that he hates can find themselves transformed and immortalised as a part of nature. ', appearance: 'a handsome youth, beardless with long hair and holds either a lyre or a bow.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'music', 'prophecy', 'healing', 'archery', 'plague', 'sun', 'poetry', 'disease', 'sudden death and diseases of boys' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'light', 'knowledge', 'life' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: 'lyre', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 3 }, politicalIdeology: { meritocracy: 5, sophocracy: 5, theocracy: 3 }, politicalSource: { }, race: { halfling: 20, human: 5 } }, possessions: { title: 'Possessions', children: [ { title: 'The Lyre of Apollo', description: 'When Hermes was a baby, he stole a number of Apollo\'s Cattle and took them to a cave in the woods near Pylos. In the cave, he found a tortoise and killed it, then removed the insides. He used one of the cow\'s intestines and the tortoise shell and made the first lyre. \n Apollo eventually found Hermes, but fell in love with the sound the lyre made. Apollo gifted the cattle to Hermes in exchange for the lyre and forgave Hermes for stealing his cattle. ' }, { title: 'Bow of Apollo', description: 'The bow of Apollo fires arrows and plagues upon those who anger him' } ] }, realm: undefined, followers: { description: 'Oracles are often followers of Apollo, the Greatest of which is the Pythia of Delph, the high priestess of Apollo', adherents: ['musicians', 'oracles', 'doctors'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'swan', 'raven', 'python', 'wolves', 'dolphin', 'roe deer', 'cicada', 'hawk', 'crows', 'mouse' ], plants: [ 'laurel', 'larkspur', 'cypress' ], monsters: ['griffon'], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' }, { name: 'Artemis', relationship: 'twin sister' } ], maxims: [ { title: '' } ] }, { // Athena objectType: 'deity', passageName: 'DeityProfile', name: 'Athena', key: 'Athena', status: 'alive', aliases: ['Minerva', 'Athene'], equivalent: ['Minerva'], titles: [ 'The Warlike', 'Defender', 'Keeper of the City', 'The Contriver of Plans and Devices', 'The Maiden', 'Of Hospitality', 'Of the Head' ], rank: 'greater deity', description: 'Athena is a wise goddess and protects those that follow her. She does have the rage of a goddess, and affronts to her are paid back with divine retribution.', appearance: 'a stately woman wearing a helmet armed with a spear and Aegis', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'wisdom', 'good counsel', 'olives', 'weaving', 'battle strategy', 'pottery', 'sculpture', 'defense of towns', 'heroic endeavour', 'crafts', 'invention', 'art', 'knowledge' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'knowledge', 'order', 'war', 'trickery' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Lawful Good', symbol: ['Gorgoneion', 'Aegis'], combat: { title: 'combat', children: [] }, probabilityWeightings: { politicalIdeology: { militocracy: 5, meritocracy: 5, autocracy: 1 }, politicalSource: { 'absolute monarchy': 5, 'constitutional monarchy': 3 }, race: { human: 10, dwarf: 15, dragonborn: 15 } }, possessions: { title: 'Possessions', children: [ 'Aegis of Athena' ] }, realm: undefined, followers: { description: 'Athena is the goddess of Craftsment, Wisdom and Heroes.', adherents: ['craftsmen', 'heroes', 'academics', 'strategists'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 80, merciful: -80, chaste: 100 }, associations: { avatars: [], animals: [ 'owl', 'snake', 'rooster' ], plants: [ 'olive tree' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' } ], maxims: [ { title: '' } ] }, { // Dionysus objectType: 'deity', passageName: 'DeityProfile', name: 'Dionysus', key: 'Dionysus', status: 'alive', aliases: ['Bacchus'], equivalent: ['Zagreus', 'Iacchus', 'Liber'], titles: [ 'Of the Bacchic Frenzy', 'The Raging One', 'Of the Night', 'Of the Phallus', 'God of Wine', 'Of the Ivy', 'Twice-born', 'the Flesh-eater', 'the Giver of Wings', 'the Orphic One', 'of the Mysteries', 'the Blooming', 'the Warlike', 'the Singer', 'the Dying and Rising', 'the arriving one' ], rank: 'greater deity', description: 'Dionysus is the god of Wine and Theatre, his revelry is open to all. However, he has his dark side - he is the god of madness the anger of Dionysus is a terrifying thing', appearance: 'long haired youth, almost effeminate in appearance. He holds a staff topped with a pinecone and brings revelry with him', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'wine', 'vegetation', 'pleasure', 'festivity', 'madness', 'wild frenzy', 'orchards', 'ritual madness', 'grape-harvest', 'the vine', 'theatre', 'tragedy and comedy plays', 'religious ectasy', 'homosexuality', 'effeminacy', 'reincarnation', 'foreign gods' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'nature', 'life', 'trickery' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Neutral', symbol: 'Thyrsus', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 2, syndicalism: 3 }, politicalIdeology: { kleptocracy: 5, oligarchy: 5, autocracy: 1 }, politicalSource: { }, race: { halfling: 50, tiefling: 30, goblin: 15 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'Dionysus is a god of the people and youths. Those who value proper decorum and modesty are apallled at the revelry of the Bacchic crowds. Devotees of Dionysus may engage in the rending of animals with their bare hands', adherents: ['wine-makers', 'actors', 'farmers', 'revelers'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [ { title: 'Eighth Month of the Year', description: 'Rituals are typically held on this day.' } ] } }, personality: { just: 20, forgiving: 25, chaste: 10 // energetic: 'lazy', // generous: 'selfish', // honest: 'deceitful', // merciful: 'cruel', // modest: 'proud', // pious: 'worldly', // prudent: 'reckless', // temperate: 'indulgent', // trusting: 'suspicious', // valorous: 'cowardly' }, associations: { avatars: [], animals: [ 'bull', 'panther', 'lion', 'leopard', 'goat', 'serpent', 'donkey' ], plants: [ 'ivy', 'grapevine', 'bindweed', 'cinnamon', 'silver fir', 'pine tree' ], monsters: ['satyrs'], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' }, { name: 'Ariadne', relationship: 'wife' }, { name: 'Aphrodite', relationship: 'lover', description: 'Aphrodite bore Priapus by Dionysus.' } ], maxims: [ { title: '' } ] }, { // Demeter objectType: 'deity', passageName: 'DeityProfile', name: 'Demeter', key: 'Demeter', status: 'alive', aliases: [ 'Ceres', 'Deo' ], titles: [ 'Of the Grain', 'Law-Bringer', 'Of the Earth', 'Bearer of Fruit', 'Great Goddess', 'Of the Mysteries', 'Lovely Haired' ], rank: 'greater deity', description: 'Demeter is the goddess of Agriculture - her favour promised a bountiful harvest and more grain then could be eaten. However her anger promised frosts and famine.', appearance: 'a mature woman wearing a crown holding wheat in a cornocopia and a torch', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'agriculture', 'grain and bread', 'the Eleusinian mysteries', 'the harvest', 'fertility', 'sacred law', 'natural law', 'the afterlife' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'life' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral Good', symbol: 'cornucopia', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { communism: 5, syndicalism: 3 }, politicalIdeology: { magocracy: 5, theocracy: 4, oligarchy: 4 }, politicalSource: { }, race: { 'dwarf': 20, 'dragonborn': 15, 'half-elf': 15, 'elf': 15, 'tiefling': 15 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'As the goddess of Agriculture, Demeter has a dedictated following among anyone who farmed. She was also a major figure of worship in the Eleusinian mysteries, which promised a better afterlife to its followers.', adherents: ['farmers'], favouredWeapon: 'Sickle', holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'snake', 'pig', 'gecko', 'turtle-dove', 'crane' ], plants: [ 'wheat', 'barley', 'mint', 'poppy' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [ 'bountiful harvest', 'satiated appetite', 'a better afterlife' ] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Hades', relationship: 'brother' }, { name: 'Hera', relationship: 'sister' }, { name: 'Poseidon', relationship: 'brother' }, { name: 'Zeus', relationship: 'brother' }, { name: 'Persephone', relationship: 'daughter', description: 'Sired by Zeus.' } ], maxims: [ { title: '' } ] }, { // Hermes objectType: 'deity', passageName: 'DeityProfile', name: 'Hermes', key: 'Hermes', status: 'alive', aliases: ['Mercury'], titles: [ 'Keeper of the Flocks', 'Of the Market-Place', 'Of the Games', 'Translator', 'Slayer of Argos', 'Immortal Guide', 'Messenger of the Blessed', 'Messenger of the Gods', 'Of the Golden Wand', 'Full of Various Wiles', 'Giver of Good Things', 'Of Searchers', 'Guide of the Dead', 'Bringer of Peace', 'God of Merchants' ], rank: 'greater deity', description: 'Hermes is the hessenger of the gods and the personal messenger of Zeus. He brings the souls of the deceased to the edge of the underworld, where they are ferried deeper by the Cthonic gods', appearance: 'an athletic man wearing winged boots, full of energy. Ontop of his head is a helmet with two wings attached.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'herds and flocks', 'boundaries', 'animal husbandry', 'travellers', 'hospitality', 'roads', 'trade', 'thievery', 'cunning', 'deception', 'persuasion', 'heralds', 'messangers', 'diplomacy', 'language', 'writing', 'the home', 'luck', 'athletic contests', 'gymnasiums', 'astronomy', 'astrology', 'birds of omen', 'guiding the dead', // also known as Psychopomp 'sleep', 'rustic divination', 'rustic music', 'rustic fables' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'trickery', 'peace', 'grave' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Good', symbol: 'Caduceus ', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { capitalism: 5 }, politicalIdeology: { kleptocracy: 5, meritocracy: 5, technocracy: 8 }, politicalSource: { }, race: { halfling: 20, tiefling: 15 } }, possessions: { title: 'Possessions', children: [ { title: 'Talaria', description: 'Tarlaria is the name of a pair of winged boots forged by Hephaestus.' }, { title: 'Golden Blade', description: 'His weapon was a sword of gold, which killed Argos; lent to Perseus to kill Medusa.' }, { title: 'Winged Helm', description: "A Petasos with wings, Hermes' helmet was forged by Hephaestus." } ] }, realm: undefined, followers: { description: 'Hermes was the messenger of Zeus, and his followers were all those that valued speed. Additionally, travelers, traders, and thieves worshiped him.', adherents: ['thieves', 'traders', 'messengers', 'athletes', 'diplomats', 'travellers'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [ { title: 'earth', children: ['Wednesday'] } ] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'hare', 'ram', 'hawk', 'goat', 'tortoise', 'rooster' ], plants: [ 'crocus', 'strawberry-tree' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' }, { name: 'Aphroditus', relationship: 'father', description: 'Aphrodite gave birth to Hermaphroditus, or Aphroditus, the god of androgyny.' } ], maxims: [ { title: '' } ] }, { // Hera objectType: 'deity', passageName: 'DeityProfile', name: 'Hera', key: 'Hera', status: 'alive', titles: [ 'Queen of the Gods', 'Goddess of Kings and Empires', 'Goddess of Marriage', 'Whose Hand is Above', 'Of the Flowers' ], aliases: [], rank: 'greater deity', description: 'Hera is the Queen of the gods, forever tested by her husband Zeus. Unable to attack Zeus, her anger is often directed to his consorts or his children.', appearance: 'a beautiful woman wearing a crown and holding a royal, lotus-tipped sceptre', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'marriage', 'air', 'women', 'childbirth', 'family', 'sky', 'stars of heaven' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'order', 'trickery', 'life' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Neutral', symbol: ['diadem', 'scepter', 'pomegranate'], combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 3 }, politicalIdeology: { theocracy: 4, oligarchy: 4, autocracy: 5 }, race: { 'human': 20, 'half-elf': 15, 'tiefling': 15 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, adherents: ['women'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -20 }, associations: { avatars: [], animals: [ 'heifer', 'lion', 'cuckoo', 'peacock', 'panther' ], plants: [ 'pomegranate', 'lily', 'willow' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'consort' }, { name: 'Hades', relationship: 'brother' }, { name: 'Poseidon', relationship: 'brother' }, { name: 'Demeter', relationship: 'brother' }, { name: 'Ares', relationship: 'son' }, { name: 'Eris', relationship: 'daughter' }, { name: 'Athena', relationship: 'daughter' }, { name: 'Hebe', relationship: 'daughter' }, { name: 'Eileithyia', relationship: 'daughter' }, { name: 'Hephaestus', relationship: 'son', description: 'Hera gave birth to Hephaestus without male intervention.' } ], maxims: [ { title: '' } ] }, { // Ares objectType: 'deity', passageName: 'DeityProfile', name: 'Ares', key: 'Ares', status: 'alive', titles: [ 'Who rallies men', 'Destroyer of Men', 'Terrible', 'Warlike', 'Of the Golden Helm' ], aliases: [], rank: 'greater deity', description: '', appearance: 'always clad in armour, holding weapons and ready for battle. He can appear as the fresh-faced youth or the grizzeled veteran depending on his mood.', history: { title: 'history', children: [] }, powers: { children: [ { title: 'Odikinesis', description: 'Possessing the ability to manipulate feelings and emotions of war such as hate and rage, Ares would induce strife before battles.' }, { title: 'Strength', description: 'As a fighter, Ares excelled at all to do with physicality. ' } ] }, portfolios: [ 'war', 'battlelust', 'courage', 'civil order', 'brutality', 'violence', 'rage' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'war' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Evil', symbol: 'spear', combat: { title: 'Combat', children: [ { title: 'Bloodlust', description: 'As the God of War, Ares has plenty of experience in battle. In contrast to Athena, who is the goddess of tacticians, Ares represents a more brutal, carnal type of conquest.' } ] }, probabilityWeightings: { economicIdeology: { feudalism: 3, primitivism: 8 }, politicalIdeology: { militocracy: 9, oligarchy: 7, autocracy: 8 }, politicalSource: { anarchy: 8 }, race: { 'half-orc': 40, 'orc': 50, 'tiefling': 20, 'goblin': 30 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'Ares is the god of war and courage - cities and countries going to war would worship Ares before going into battle', adherents: ['warriors'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [ { title: 'earth', children: ['Tuesday'] } ] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'serpent', 'hound', 'boar', 'vulture', 'eagle-owl', 'woodpecker' ], plants: [], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' }, { name: 'Aphrodite', relationship: 'lover' } ], maxims: [ { title: '' } ] }, { // Hestia objectType: 'deity', passageName: 'DeityProfile', name: 'Hestia', key: 'Hestia', status: 'alive', aliases: ['Vesta'], titles: [ 'Daughter of lovely-haired Rhea', 'Daughter of Cronos', 'Rich in Blessings', 'Beloved' ], rank: 'greater deity', description: 'Hestia is the First-born child of Kronos and Rhea and the first to be swallowed by him. After Apollo and Poseidon vied for her hand in marriage she refused and chose to be an eternal virgin.', appearance: 'a beautiful veiled woman, with long dark hair', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'fire', 'family hearth', 'civic hearth', 'home', 'cooking', 'the sacrificial flame', 'sacrifices', 'sacred flame', 'domesticity', 'family', 'virginity', 'the state' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'life', 'light', 'peace' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral Good', symbol: 'hearth', combat: { title: 'Combat', children: [ { title: 'De-escalation', description: 'Hestia finds combat distasteful, and will try and defuse the situation before it gets out of hand.' } ] }, probabilityWeightings: { economicIdeology: { feudalism: 3, syndicalism: 3, communism: 2 }, politicalIdeology: { meritocracy: 4, sophocracy: 4, oligarchy: 4 }, race: { 'elf': 40, 'half-elf': 15 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85 }, associations: { avatars: [], animals: [ 'pig' ], plants: [ 'chaste-tree' ], monsters: [], gems: [], colours: ['green'], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'brother' } ], maxims: [ { title: '' } ] }, { // Hephaestus objectType: 'deity', passageName: 'DeityProfile', name: 'Hephaestus', key: 'Hephaestus', status: 'alive', titles: [ 'Glorius Craftsman', 'Famed Craftsman', 'Of many Crafts', 'Crooked-Foot', 'Of Bronze' ], aliases: [], rank: 'greater deity', description: '', appearance: 'bearded man with twisted legs', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'fire', 'blacksmiths', 'craftsmen', 'metalworking', 'forges', 'stone masonry', 'scultpure', 'technology', 'artisans', 'carpenters', 'metallurgy', 'volcanoes' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'knowledge', 'forge' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral Good', symbol: 'Hammer and Anvil', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 3, capitalism: 6 }, politicalIdeology: { technocracy: 10, autocracy: 5 }, race: { dwarf: 20, gnome: 45 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'Hephaestus is the god of the forge. He is worshipped by Craftsmen and his blessing gives them inspiration and skill,', adherents: ['smiths', 'craftsmen'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'donkey' ], plants: [], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [ 'inspiration', 'knowledge' ] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Persephone objectType: 'deity', passageName: 'DeityProfile', name: 'Persephone', key: 'Persephone', status: 'alive', aliases: ['Kore'], equivalent: ['Libera', 'Proserpina', 'Prosperina'], titles: [ 'Queen of the Underworld', 'Knowing One', 'Exacter of Justice', 'Of the Earth', 'Bringer of Fruit' ], rank: 'intermediate deity', description: '', appearance: 'a beautiful young maiden with fair skin. Her face is the epitome of young beauty. She is often shown in long, flowing clothing with a wreath of flowers around her head.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'spring', 'flowers', 'death', 'life', 'vegetation', 'fertility of plants', 'the Eleusinian Mysteries', 'the blessed afterlife' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'life', 'grave', 'death' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral Good', symbol: ['pomegranate', 'torch'], combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 3 }, politicalIdeology: { meritocracy: 2, oligarchy: 4, autocracy: 5 }, race: { 'halfling': 20, 'half-elf': 15, 'elf': 15 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'Persephone was a goddess of Spring and the Wife of Hades. Her favour might ensure a better afterlife for her worshippers.', adherents: ['farmers'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: 0, chaste: 75 }, associations: { avatars: [], animals: [ 'deer' ], plants: [ 'pomegranate', 'wheat', 'asphodel', 'flowers' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' } ], maxims: [ { title: '' } ] }, { // Hecate objectType: 'deity', passageName: 'DeityProfile', name: 'Hecate', key: 'Hecate', status: 'alive', titles: [ 'Worker from Afar', 'Of the Underworld', 'Nurse of Children', 'Who Attends', 'Leader of the Dogs', 'Three-bodied' ], aliases: [], rank: 'intermediate deity', description: '', appearance: 'a woman wearing a crown. Sometimes, she has three bodies, conjoined to one another.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'magic', 'night', 'ghosts', 'necromancy', 'boundaries', 'crossroads', 'herbs', 'poisonous plants' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'arcana', 'knowledge', 'trickery', 'twilight', 'death', 'nature' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Evil', symbol: undefined, combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 3 }, politicalIdeology: { magocracy: 8, oligarchy: 4, autocracy: 5 }, race: { human: 5, tiefling: 25 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'Hecate is a mysterious Goddess who is a master of the Arcane Arts and lives in the Underworld, her followers ask for her secret knowledge.', adherents: ['magic users', 'necromancers'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -20 }, associations: { avatars: [], animals: [ 'dogs', 'red mullet', 'serpent', 'polecat', 'frog', 'cow', 'horse', 'lion' ], plants: [ 'yew', 'oak', 'garlic', 'cypress', 'aconite', 'belladonna', 'dittany', 'mandrake' ], monsters: ['ghosts', 'Lampades'], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Nike objectType: 'deity', passageName: 'DeityProfile', name: 'Nike', key: 'Nike', status: 'alive', titles: ['Goddess of Victory', 'The Winged Goddess'], aliases: [], rank: 'lesser deity', description: '', appearance: 'an athletic woman with two large wings.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: ['victory', 'speed', 'strength'], gender: 'woman', shape: 'human', race: 'god', domains: [ 'war', 'peace' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Lawful Neutral', symbol: 'Winged Woman', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 3 }, politicalIdeology: { militocracy: 4, autocracy: 5 }, race: { 'human': 20, 'half-orc': 25, 'orc': 15 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'The Favour of Nike is a promise of victory, though it was rarely given without being earnt.', adherents: ['warriors'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -20 }, associations: { avatars: [], animals: [], plants: [ 'palm tree', 'bay tree' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Tyche objectType: 'deity', passageName: 'DeityProfile', name: 'Tyche', key: 'Tyche', status: 'alive', titles: ['Goddess of Fortune and Chance'], aliases: [], rank: 'lesser deity', description: '', appearance: 'a woman with a crown, often shown holding a horn of cornucopia.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: ['luck', 'chance', 'fate', 'providence', 'natural disasters'], gender: 'woman', shape: 'human', race: 'god', domains: [ 'trickery' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: undefined, combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 3, capitalism: 5 }, politicalIdeology: { meritocracy: 4, kleptocracy: 4 }, race: { halfling: 30, human: 5 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, adherents: ['gamblers'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -20 }, associations: { avatars: [], animals: [], plants: [], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Hebe objectType: 'deity', passageName: 'DeityProfile', name: 'Hebe', key: 'Hebe', status: 'alive', titles: [ 'Goddess of Eternal Youth', 'Daughter of Zeus', 'Wife of Hercules' ], aliases: [], rank: 'lesser deity', description: 'Hebe is the daughter of Zeus and Hera, as well as the Goddess of Youth. She served as the Cupbearer of the Gods, and was later married to Herakles, the protector of Olympus.', appearance: 'a woman in a sleeveless dress, with long brown hair.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'youth', 'forgiveness', 'mercy', 'brides' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'life' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral Good', symbol: ['Wine cup', 'eagle', 'ivy', 'fountain of youth', 'wings'], combat: { title: 'combat', children: [] }, probabilityWeightings: { race: { human: 5 } }, possessions: { title: 'possessions', children: [ { title: 'Fountain of Youth', description: 'Hebe was the protector of the Fountain of Youth.' } ] }, realm: undefined, followers: { description: 'As the bride of Heracles, Hebe was strongly associated with both brides and her husband in art and literature. Hebe was the patron of brides, due to being the daughter of Hera and the importance of her own wedding.', favouredWeapon: undefined, adherents: ['brides'], holyDays: { title: 'Holy Days', children: [ { title: 'earth', children: ['June'] } ] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'hen', 'eagle' ], plants: [ 'ivy', 'lettuce' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [ { title: 'Restored Youth', description: 'A power unique to Hebe, she was able to restore youth to mortals.' } ] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' }, { name: 'Hera', relationship: 'mother', description: 'Hebe helped Hera enter her chariot.' }, { name: 'Hercules', relationship: 'husband' }, { name: 'Ares', relationship: 'brother', description: 'Hebe drew baths for Ares.' } ], maxims: [ { title: '' } ] }, { // Pan objectType: 'deity', passageName: 'DeityProfile', name: 'Pan', key: 'Pan', status: 'uncertain', titles: [ 'The God of the Wild', 'Of the Pastures', 'Terrifying One', 'Of the Hunt' ], aliases: [], rank: 'intermediate deity', description: '', appearance: 'a satyr holding a set of Pan-pipes', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'the wild', 'nature', 'shephard', 'flocks', 'sexuality', 'hunters', 'panic' ], gender: 'man', shape: 'satyr', race: 'god', domains: [ 'nature', 'trickery' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Neutral', symbol: 'pan pipes', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { primitivism: 3 }, politicalIdeology: { kleptocracy: 4 }, race: { 'halfling': 30, 'gnome': 15, 'elf': 25, 'half-elf': 15 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, adherents: ['wild beings', 'hunters'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -100 }, associations: { avatars: [], animals: [ 'goat', 'tortoise' ], plants: [ 'corsican pine', 'water-reed', 'beech trees' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Asclepius objectType: 'deity', passageName: 'DeityProfile', name: 'Asclepius', key: 'Asclepius', status: 'alive', titles: [ 'God of Healing', 'Lover of the People' ], aliases: [], rank: 'lesser deity', description: 'Asclepius is the son of Apollo whose skill in medicine was so great he could ressurect the dead, he was struck down by Zeus. He was placed among the stars and now serves as the Physician for the gods', appearance: 'a man with a full beard in a simple himation robe.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'medicine', 'healing', 'rejuvination', 'doctors' ], gender: 'man', shape: 'human', race: 'demigod', domains: [ 'life', 'knowledge' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Lawful Good', symbol: 'Serpent-entwined staff', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { communism: 3 }, politicalIdeology: { sophocracy: 5, democracy: 4 }, race: { 'human': 20, 'elf': 15, 'half-elf': 15 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'Asclepius was so skiled in medicine that he could ressurect the dead, Healers and the Sick pray for his favour for skill and recovery', adherents: ['healers', 'the sick'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'snake' ], plants: [ 'milkweed' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Chiron objectType: 'deity', passageName: 'DeityProfile', name: 'Chiron', key: 'Chiron', status: 'alive', titles: [ 'Wisest of the Centaurs', 'The Teacher' ], aliases: [], rank: 'immortal', description: '', appearance: 'a centaur, though in some iterations his front legs are human legs.', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'teachers', 'surgeons' ], gender: 'man', shape: 'centaur', race: 'centaur', domains: [ 'knowledge', 'peace' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral Good', symbol: ['thread', 'serpent', 'bull'], combat: { title: 'combat', children: [] }, probabilityWeightings: { politicalIdeology: { theocracy: 4, sophocracy: 4, technocracy: 3 }, race: { dragonborn: 15, human: 5 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'Chiron is worshipped by Heroes and Centaurs alike for his wisdom and control.', adherents: ['teachers', 'centaurs', 'healers'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: 60, chaste: 90 }, associations: { avatars: [], animals: [], plants: [], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Hercules objectType: 'deity', passageName: 'DeityProfile', name: 'Heracles', key: 'Heracles', status: 'alive', aliases: ['Hercules'], titles: ['Divine Protector of Mankind'], rank: 'lesser deity', description: 'The Son of Zeus who famously completed 12 Labours, Heracles ascended to godhood and is known as the greatest of the Greek Heroes', appearance: 'a muscular man with a beard', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'mankind', 'gymnasium', 'strength', 'heroes' ], gender: 'man', shape: 'human', race: 'demigod', domains: [ 'war' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Good', symbol: 'olive-wood club and lion skin cape', combat: { title: 'combat', children: [] }, probabilityWeightings: { economicIdeology: { feudalism: 3 }, politicalIdeology: { autocracy: 1 }, politicalSource: { 'absolute monarchy': 10 }, race: { 'human': 20, 'half-orc': 35, 'orc': 20 } }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'Arguably the greatest of Heroes, Heracles is worshipped by mortals for his strength and fame', adherents: ['heroes', 'athletes', 'mortals'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'lion' ], plants: [ 'olive tree' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Zeus', relationship: 'father' } ], maxims: [ { title: '' } ] }, { // Ariadne objectType: 'deity', passageName: 'DeityProfile', name: 'Ariadne', key: 'Ariadne', status: 'alive', equivalent: ['Libera', 'Proserpina'], titles: ['Wife of Dionysus'], aliases: [], rank: 'immortal', description: '', appearance: 'a woman with a laurel crown', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'mazes', 'fertility', 'wine', 'seasonal agriculture' ], gender: 'woman', shape: 'human', race: 'human', domains: [ 'trickery', 'nature', 'life' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: undefined, combat: { title: 'combat', children: [] }, probabilityWeightings: { race: { halfling: 20, tiefling: 15 } }, possessions: { title: 'Possessions', children: [ 'The Thread of Ariadne' ] }, realm: undefined, followers: { description: undefined, adherents: ['farmers'], favouredWeapon: undefined, holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 50, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [], plants: [], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ { name: 'Dionysus', relationship: 'consort' } ], maxims: [ { title: '' } ] } ], meta: { author: 'unknown', contributors: ['ryceg', 'Dark07', 'Maha', 'GadgetBoy', 'Jen9C', 'Levendor', 'Wumbo'], license: 'public domain', repository: 'https://github.com/ryceg/Eigengrau-s-Essential-Establishment-Generator/blob/master/lib/religion/religion.ts#L580', version: 0.1, notes: 'Included as the default pantheon.' } }, norse: { name: 'norse', description: `Where the land plummets from the snowy hills into the icy fjords below, where the longboats draw up on to the beach, where the glaciers flow forward and retreat with every fall and spring—this is the land of the Vikings, the home of the Norse pantheon. It’s a brutal clime, and one that calls for brutal living. The warriors of the land have had to adapt to the harsh conditions in order to survive, but they haven’t been too twisted by the needs of their environment. Given the necessity of raiding for food and wealth, it’s surprising the mortals turned out as well as they did. Their powers reflect the need these warriors had for strong leadership and decisive action. Thus, they see their deities in every bend of a river, hear them in the crash of the thunder and the booming of the glaciers, and smell them in the smoke of a burning longhouse. The Norse pantheon includes two main families, the Aesir (deities of war and destiny) and the Vanir (gods of fertility and prosperity). Once enemies, these two families are now closely allied against their common enemies, the giants (including the gods Surtur and Thrym).`, followers: { description: '', favouredWeapon: '', holyDays: { title: 'Holy Days', children: [] } }, gods: [ { // Odin objectType: 'deity', passageName: 'DeityProfile', name: 'Odin', key: 'Odin', status: 'alive', titles: [ 'The Allfather', 'Lord of the Aesir', 'Flaming Eye', 'Battle Enhancer', 'Ancient One', 'Enemy of the Wolf', 'God of Burdens', 'Wise One', 'Spear god', 'Swift in Deciet', 'Wand Bearer', 'Teacher of Gods', 'Vistor of the Hanged', 'Father of Hosts', 'Raven God', 'The Hanging One', 'God of Victory' ], aliases: [], rank: 'leader', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'wisdom', 'death', 'royalty', 'the gallows', 'war', 'battle', 'victory', 'sorcery', 'poetry', 'frenzy', 'runic alphabet' ], gender: 'man', shape: 'human', race: 'god', faction: 'aesir', domains: [ 'knowledge', 'trickery', 'war', 'arcana' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Lawful Good', symbol: '', combat: { title: 'combat', children: [] }, possessions: { children: [ { title: 'Gungir', description: 'The spear Gungir is so well balanced it can hit any target, regardless of skill' }, { title: 'Draupnir', description: 'A gold ring which drips forth eight identical rings after nine days' } ] }, realm: 'Valhalla', followers: { description: undefined, favouredWeapon: '', holyDays: { title: 'Holy Days', children: [ { title: 'earth', children: ['Wednesday'] } ] } }, personality: { just: 70, merciful: -85, chaste: -20 }, associations: { avatars: [], animals: [ 'raven', 'wolf' ], plants: [ 'poppy' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Thor objectType: 'deity', passageName: 'DeityProfile', name: 'Thor', key: 'Thor', status: 'alive', titles: [ 'The one who Rides Alone', 'The one who Rules Alone', 'Protector of the Shrine', 'The Loud Weather God', 'The terrible', 'The Thunderer', 'Odinson', 'Strong-Spirit' ], aliases: [], rank: 'greater deity', description: 'Thor is the God of Lightning, Thunder and Storms. He is a god of Strength, yet he is also a god who protects the sacred groves and mankind.', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'strength', 'battle prowess', 'lightning', 'thunder', 'storms', 'sacred groves', 'the protection of mankind', 'harrowing', 'fertility' ], gender: 'man', shape: 'human', race: 'god', faction: 'aesir', domains: [ 'tempest', 'war', 'nature' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral Good', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'Possessions', children: [ { title: 'Jarngreipr ', description: 'the pair of gloves he needs to handle Mjolnir' }, { title: 'Mjolnir', description: 'The legendary hammer which summons thunderbolts and, in select cases, can ressurect the fallen. In its forging a mistake was made and the handle is short'// Don't think it returns - this is not Marvel }, { title: 'Megingjord', description: 'A belt doubles Thors mighty strength, allowing him to lift Mjolnir' } ] }, realm: undefined, followers: { description: undefined, favouredWeapon: 'hammer', holyDays: { title: 'Holy Days', children: [ { title: 'earth', children: ['Thursday'] } ] } }, personality: { just: 70, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [ 'goat'], plants: [ 'oak' ], places: [ 'groves', 'oak forests' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Loki objectType: 'deity', passageName: 'DeityProfile', name: 'Loki', key: 'Loki', status: 'alive', // unless he is bound to the stone with the snake above him - dunno about this titles: [ 'Tangler', 'Father of Lies', 'Roarer', 'The Sly One', 'Laufeys son', 'Thief of the Idunns apples', 'Hawks child', 'Betrayer of the Gods', 'The Bound God', 'He who has borne children' ], aliases: [], rank: 'greater deity', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'magic', 'mischief', 'deceit', 'thievery', 'chaos', 'change', 'temptation', 'shapeshifting' ], // Not fire, that is Logi, the Jotunn of Fire // Loki is a shapeshifter, but it is simpler to give his avatars the corresponding gender. // You probably didn't consciously notice that I just used the male pronouns for Loki. gender: 'man', shape: 'human', race: 'Jotunn', faction: 'aesir', domains: [ 'trickery' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Chaotic Evil', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 70, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [], plants: [ 'birch', 'mistletoe' ], monsters: ['Fenrir', 'Jormungandr'], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Frigga objectType: 'deity', passageName: 'DeityProfile', name: 'Frigg', key: 'Frigg', status: 'alive', aliases: [ 'Frigga' ], titles: [ 'Protectress', 'Queen of the Gods' ], rank: 'greater deity', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'prophecy', 'wisdom', 'the household', 'marriage', 'social bonds', 'rain', 'mists', 'fertility', 'birth', 'wetlands', 'protection', 'weaving' ], gender: 'woman', shape: 'human', race: 'god', faction: 'aesir', domains: [ 'knowledge', 'life' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [ { title: 'earth', children: ['Friday'] } ] } }, personality: { }, associations: { avatars: [], animals: [ 'waterfowl', 'ducks', 'geese' ], plants: [ 'linden' ], places: [ 'wetlands', 'swamps' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Freyr objectType: 'deity', passageName: 'DeityProfile', name: 'Freyr', key: 'Freyr', status: 'alive', aliases: ['Frey', 'Yngvi'], titles: [ 'the Lord', 'The Generous One', 'God of Sunlight', 'Sunbeam', 'Lord of Plenty', 'the Fruitful' ], rank: 'greater deity', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'religious kingship', 'virility', 'sunshine', 'peace', 'prosperity', 'fair weather', 'good harvest', 'rain', 'war' ], gender: 'man', shape: 'human', race: 'god', faction: 'vanir', domains: [ 'light', 'life', 'peace', 'nature', 'war' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'Possessions', children: [ { title: 'Gullinbursti', description: 'A golden boar' } ] }, realm: undefined, followers: { description: undefined, favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [] } }, personality: { }, associations: { avatars: [], animals: [ 'boar', 'stags' ], plants: [ 'crops' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Freyja objectType: 'deity', passageName: 'DeityProfile', name: 'Freyja', key: 'Freyja', status: 'alive', aliases: ['Freya', 'Freja'], titles: [ 'The Giver', 'Flaxen', 'One who makes the Sea Swll', 'Lady of the Slain', 'Noble Lady', 'Bright One', 'Goddess of the Vanir', 'Fair Tear Deity' ], rank: 'greater deity', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'love', 'marriage', 'prosperity', 'beauty', 'fertility', 'sex', 'war', 'gold', 'magic' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'life', 'arcana', 'war' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'possessions', children: [] }, realm: 'Folkvangr', followers: { description: undefined, favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [] } }, personality: { chaste: 30 }, associations: { avatars: [], animals: [ 'cat', 'lynx', 'falcon', 'boar' ], plants: [ '' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Bragi objectType: 'deity', passageName: 'DeityProfile', name: 'Bragi', key: 'Bragi', status: 'alive', titles: [ 'The long-bearded god', 'The husband of Idunn', 'First maker of Poetry', 'Son of Odin' ], aliases: [], rank: 'greater deity', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'skaldic poetry', 'wisdom' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'knowledge' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: 'the Skalds are the story tellers of the Jarl, and rarely go into battle. They recite stories of the great deeds of gods and men', favouredWeapon: 'harp', holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 70, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [], plants: [], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Sif objectType: 'deity', passageName: 'DeityProfile', name: 'Sif', key: 'Sif', status: 'alive', titles: [ 'The Prophetess Sibyl', 'The Fair-haired Deity', 'Loveliest of Women', 'The Wife of Thor', 'Mother of Ullr', 'Good Mother' ], aliases: [], rank: 'greater deity', description: '', appearance: 'a beautiful woman with a brilliant wig made of gold', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'harvest', 'autum', 'vitality', 'fertility', 'wedlock' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'nature' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [] } }, personality: { }, associations: { avatars: [], animals: [], plants: [ 'rowan' ], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Baldr objectType: 'deity', passageName: 'DeityProfile', name: 'Baldr', key: 'Baldr', status: 'dead', titles: [ 'the Bleeding God', 'Wisest of the Aesir', 'Fairest of the Aesir' ], aliases: [], rank: 'greater deity', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ 'beauty', 'light', 'peace', 'valour', 'joy', 'summer sun', 'purity' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'life', 'light', 'peace' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 70, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [], plants: ['scentless mayweed'], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Aegir objectType: 'deity', passageName: 'DeityProfile', name: 'Name', key: 'Name', status: 'alive', titles: [], aliases: [], rank: 'greater deity', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ '' ], gender: 'man', shape: 'human', race: 'god', domains: [ 'tempest' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 70, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [], plants: [], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] }, { // Hel objectType: 'deity', passageName: 'DeityProfile', name: 'Hel', key: 'Hel', status: 'alive', titles: [], aliases: [], rank: 'greater deity', description: '', appearance: '', history: { title: 'history', children: [] }, powers: { title: 'powers', children: [] }, portfolios: [ '' ], gender: 'woman', shape: 'human', race: 'god', domains: [ 'death', 'grave' ], channelDivinity: { title: 'Channel Divinity', children: [] }, alignment: 'Neutral', symbol: '', combat: { title: 'combat', children: [] }, possessions: { title: 'possessions', children: [] }, realm: undefined, followers: { description: undefined, favouredWeapon: 'spear', holyDays: { title: 'Holy Days', children: [] } }, personality: { just: 70, merciful: -85, chaste: -80 }, associations: { avatars: [], animals: [], plants: [], monsters: [], gems: [], colours: [], miscellaneous: [] }, beliefs: { title: 'beliefs', children: [] }, heresies: { title: 'heresies', children: [] }, blessings: { title: 'blessings', children: [] }, curses: { title: 'curses', children: [] }, allies: { title: 'allies', children: [] }, enemies: { title: 'enemies', children: [] }, relationships: [ ], maxims: [ { title: '' } ] } ] } } }
the_stack
import { Grid, LinearProgress, Typography, withStyles } from '@material-ui/core' import ErrorIcon from '@material-ui/icons/Error' import AsyncLock from 'async-lock' import { ipcRenderer } from 'electron' import { ipcRenderer as ipc } from 'electron-better-ipc' import electronLog from 'electron-log' import moment, { Moment } from 'moment' import * as React from 'react' import styled from 'styled-components' import { DownloadedThumbnailIpc, DownloadThumbnailIpcRequest } from '../../../shared' import { DOWNLOAD_THUMBNAIL_CHANNEL, GET_VIEW_DOWNLOAD_TIME, VIEW_DOWNLOAD_PROGRESS, VISIBILITY_CHANGE_ALERT_CHANNEL } from '../../../shared/IpcDefinitions' import ReloadButton from './ReloadButton' import StatusIconAndDialog from './StatusIcon' ipcRenderer.setMaxListeners(30) const log = electronLog.scope('thumbnail-component') interface IsSelectedStyleProps { readonly isSelected: boolean } /** * Styling for the image itself. */ const Image = styled.img` max-width: 100%; max-height: 100%; pointer-events: none; position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; ` /** * Clickable container which the image is in. */ const ImageContainer = styled.div<IsSelectedStyleProps>` --width: 200px; --height: calc((var(--width) * 3) / 5); width: var(--width); height: var(--height); background-color: black; border-radius: var(--image-border-radius); box-shadow: ${props => (!props.isSelected ? '0 3px 10px rgba(0, 0, 0, 0.3)' : 'none')}; transition: box-shadow var(--transition-time); overflow: hidden; position: relative; ` /** * Background of the image container which acts as a border. */ const ImageContainerBackground = styled.div<IsSelectedStyleProps>` background: ${props => (props.isSelected ? props.theme.colors.borderHighlight : 'transparent')}; border-radius: var(--image-border-radius); padding: 4px; box-shadow: ${props => (props.isSelected ? '0 3px 20px rgba(0, 0, 0, 0.5)' : 'none')}; transition: box-shadow var(--transition-time), background-color var(--transition-time); cursor: ${props => (props.isSelected ? 'default' : 'pointer')}; // Hide reload icon when not hovering #reload-icon { display: none; } &:hover #reload-icon { display: block; } ` /** * Name describing the thumbnail. */ const ThumbnailName = styled.p<IsSelectedStyleProps>` font-family: Roboto, sans-serif; font-size: 16px; font-weight: normal; letter-spacing: 0.15px; margin-bottom: 8px; text-shadow: ${props => !props.isSelected ? '0 3px 10px rgba(0, 0, 0, 0.4)' : '0 3px 20px rgba(0, 0, 0, 1)'}; ` /** * Container for the image and name. */ const ThumbnailContainer = styled.div<IsSelectedStyleProps>` --transition-time: 200ms; --image-border-radius: 10px; padding: 10px; transform: ${props => (props.isSelected ? 'scale(1.03)' : '')}; transition: transform var(--transition-time); user-select: none; ` enum ThumbnailLoadingState { loading, loaded, failed } const BottomProgress = withStyles({ root: { marginTop: 'calc(var(--height) - 6.62px)', height: '6.5px' }, colorPrimary: { backgroundColor: '#567d2e' }, barColorPrimary: { backgroundColor: '#96c267' } })(LinearProgress) const VerticalCenterContainer = styled.div` display: flex; justify-content: center; align-items: center; height: 100%; ` interface ImageSwitcherProps { src: string loadingState: ThumbnailLoadingState downloadingPercentage?: number } // eslint-disable-next-line consistent-return const ImageSwitcher: React.FC<ImageSwitcherProps> = props => { const { src, loadingState, downloadingPercentage } = props // eslint-disable-next-line default-case switch (loadingState) { case ThumbnailLoadingState.loading: return <BottomProgress /> case ThumbnailLoadingState.loaded: return ( <> <Image src={src} /> {downloadingPercentage !== undefined && ( <BottomProgress variant={downloadingPercentage === -1 ? 'indeterminate' : 'determinate'} value={downloadingPercentage} /> )} </> ) case ThumbnailLoadingState.failed: return ( <VerticalCenterContainer> <Grid container direction="column" alignItems="center"> <ErrorIcon color="disabled" fontSize="large" /> <Typography variant="body2" color="textSecondary"> Error downloading </Typography> </Grid> </VerticalCenterContainer> ) } } interface CachedImage { dataUrl: string expiration: Moment isBackup?: boolean timeTaken?: Moment etag?: string } const lock = new AsyncLock() interface ThumbnailProps { id: number src: string name: string description?: string updateInterval: number isSelected: (id: number) => boolean onClick: (id: number) => void onReloadView: () => void } interface ThumbnailState { b64Image?: string isBackup?: boolean timeTaken?: Moment timeDownloaded?: Moment loadingState: ThumbnailLoadingState cancelVisibilityChangeSub?: () => void cancelProgressChangeSub?: () => void downloadPercentage?: number } const thumbnailCache: { [key: number]: CachedImage | undefined } = {} export default class Thumbnail extends React.Component<ThumbnailProps, ThumbnailState> { constructor(props: ThumbnailProps) { super(props) this.state = { loadingState: ThumbnailLoadingState.loading } this.updateUnsafe = this.updateUnsafe.bind(this) this.update = this.update.bind(this) this.updateTimeDownloaded = this.updateTimeDownloaded.bind(this) } async componentDidMount(): Promise<void> { const cancelVisChange = ipc.answerMain<boolean>( VISIBILITY_CHANGE_ALERT_CHANNEL, visible => { if (visible) { this.update() } } ) const cancelProgressChange = ipc.answerMain<number | undefined>( `${VIEW_DOWNLOAD_PROGRESS}_${this.props.id}`, percentage => { // Delay before resetting to give time for background to change if (percentage === undefined) { setTimeout(() => { this.setState({ downloadPercentage: percentage }) }, 400) } else { this.setState({ downloadPercentage: percentage }) } } ) this.setState({ cancelVisibilityChangeSub: cancelVisChange, cancelProgressChangeSub: cancelProgressChange }) await this.update() } async componentWillUnmount(): Promise<void> { if (this.state.cancelVisibilityChangeSub !== undefined) { this.state.cancelVisibilityChangeSub() } if (this.state.cancelProgressChangeSub !== undefined) { this.state.cancelProgressChangeSub() } } /** * Update the time the image was last downloaded from main. */ private async updateTimeDownloaded(): Promise<void> { const timeDownloaded = await ipc.callMain<number, number | undefined>( GET_VIEW_DOWNLOAD_TIME, this.props.id ) if (timeDownloaded !== undefined) { this.setState({ timeDownloaded: moment(timeDownloaded) }) } } /** * Update the thumbnail with no concurrent locking mechanism. */ private async updateUnsafe(): Promise<void> { const cachedImage = thumbnailCache[this.props.id] ?? undefined // If no image in state, try to get from cache if (this.state.b64Image === undefined) { if (cachedImage !== undefined) { // Set the cached image this.setState({ loadingState: ThumbnailLoadingState.loaded, b64Image: cachedImage.dataUrl, isBackup: cachedImage.isBackup, timeTaken: cachedImage.timeTaken }) } else { // Set the loading animation this.setState({ loadingState: ThumbnailLoadingState.loading }) } } // If there's a cached image that's in date, it has already been set; nothing to do if (cachedImage !== undefined && moment.utc().diff(cachedImage.expiration, 'seconds') < 0) { return } // Fetch a new image const response = await ipc.callMain<DownloadThumbnailIpcRequest, DownloadedThumbnailIpc>( DOWNLOAD_THUMBNAIL_CHANNEL, { url: this.props.src, etag: cachedImage?.etag } ) const newExpiration = moment(moment.utc().add(5, 'minutes')) // If not modified, update expiration and exit if (response.isModified === false) { ;(cachedImage as CachedImage).expiration = newExpiration return } // If download failed, report and exit if (response.dataUrl === undefined) { this.setState({ loadingState: ThumbnailLoadingState.failed }) return } // Update cache and state const momentTaken = response.timeTaken !== undefined ? moment(response.timeTaken) : undefined thumbnailCache[this.props.id] = { dataUrl: response.dataUrl, expiration: newExpiration, etag: response.etag, isBackup: response.isBackup, timeTaken: momentTaken } this.setState({ loadingState: ThumbnailLoadingState.loaded, b64Image: response.dataUrl, isBackup: response.isBackup, timeTaken: momentTaken }) } /** * Update the thumbnail with a locking mechanism. */ async update(): Promise<void> { await lock.acquire(this.props.id.toString(), async () => { await this.updateUnsafe() }) } public render(): React.ReactNode { const { id, name, description, isSelected, onClick, onReloadView } = this.props const isSelectedValue = isSelected(id) return ( <ThumbnailContainer isSelected={isSelectedValue}> <ImageContainerBackground isSelected={isSelectedValue}> <ImageContainer isSelected={isSelectedValue} onClick={() => onClick(id)}> <StatusIconAndDialog viewTitle={name} viewDescription={description} updateInterval={this.props.updateInterval} downloaded={this.state.timeDownloaded} imageTaken={this.state.timeTaken} isBackup={this.state.isBackup} failed={this.state.loadingState === ThumbnailLoadingState.failed} onHover={this.updateTimeDownloaded} /> <ReloadButton onClick={() => { if (isSelectedValue) { onReloadView() this.update() } else { onClick(id) } }} /> <ImageSwitcher src={this.state.b64Image ?? ''} loadingState={this.state.loadingState} downloadingPercentage={ isSelectedValue ? this.state.downloadPercentage : undefined } /> </ImageContainer> </ImageContainerBackground> <ThumbnailName isSelected={isSelectedValue}>{name}</ThumbnailName> </ThumbnailContainer> ) } }
the_stack
import * as path from 'path'; import cloudProviders from './providers'; import { askForInput, confirm, logError, logInfo, pickOne, run } from './utils'; interface IOptions { 'skip-provision'?: boolean; } export default async (opts: IOptions) => { const question = 'Which cloud provider are you hosting with'; const provider = await pickOne(question, cloudProviders); if (!opts['skip-provision']) { switch (provider) { case 'minikube': { logInfo('Note: Minikube is for development purposes only.'); // Start minikube if it isn't running try { await run('minikube status'); } catch (error) { logInfo('Starting Minikube. This may take a minute.'); await run('minikube start'); } await run('minikube addons enable ingress'); await run('helm init --wait'); const { stdout: minikubeIP } = await run('minikube ip'); // Install traefik await run(` helm install stable/traefik \ --name traefik \ --namespace kube-system \ --set serviceType=NodePort \ --set dashboard.enabled=true \ --set dashboard.domain=traefik-ui.minikube `); const traefikHost = `${minikubeIP} traefik-ui.minikube`; logInfo( `Add "${traefikHost}" to your hosts file to access traefik's dashboard.` ); // Install docker registry await run('helm install stable/docker-registry'); if (await confirm('Install an example app on Minikube')) { const deployFile = path.resolve( __dirname, '../config/deployment-minikube.yaml' ); await run(`kubectl apply -f ${deployFile}`); const whoAmIHost = `${minikubeIP} whoami.minikube`; logInfo( `Add "${whoAmIHost}" to your hosts file to access example app.` ); } const completeMsg = 'Creation complete. It may take a few minutes for services to become available.'; logInfo(completeMsg); break; } case 'gcp': { // Check if we need to authenticate. try { const { stdout } = await run('gcloud auth list'); const isAuthenticated = stdout.indexOf('*') > -1; if (!isAuthenticated) { await run('gcloud auth login'); } } catch (error) { await run('gcloud auth login'); } const { stdout: projectId } = await run( 'gcloud config get-value project' ); await run('gcloud services enable container.googleapis.com'); // Check if we have an existing cluster let clusterExists = false; const { stdout: clusterData } = await run( 'gcloud container clusters list' ); if (clusterData.indexOf('snow-cluster') > -1) { clusterExists = true; } const createClusterCmd = ` gcloud beta container \ clusters create "snow-cluster" \ --zone "us-west1-b" \ --no-enable-basic-auth \ --cluster-version "1.10.9-gke.5" \ --image-type "COS" \ --machine-type "f1-micro" \ --disk-type "pd-standard" \ --disk-size "10" \ --default-max-pods-per-node "110" \ --num-nodes "3" \ --enable-cloud-logging \ --enable-cloud-monitoring \ --enable-ip-alias \ --network "projects/${projectId}/global/networks/default" \ --subnetwork "projects/${projectId}/regions/us-west1/subnetworks/default" \ --default-max-pods-per-node "110" \ --addons HorizontalPodAutoscaling,HttpLoadBalancing \ --enable-autoupgrade \ --enable-autorepair \ --scopes "https://www.googleapis.com/auth/devstorage.read_only","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/monitoring","https://www.googleapis.com/auth/service.management.readonly","https://www.googleapis.com/auth/servicecontrol","https://www.googleapis.com/auth/trace.append" \ `; if (!clusterExists) { await run(createClusterCmd); } break; } case 'digitalocean': { // Authenticate. logInfo('Obtain a Digital Ocean access token here: https://cloud.digitalocean.com/account/api/tokens'); const token = await askForInput( 'Enter your digital ocean access token' ); await run(`doctl auth init -t ${token}`); // Check if we have an existing cluster. let clusterExists = true; try { await run('doctl k8s cluster get snow-cluster', {silent: true}); } catch (e) { clusterExists = false; } const region = 'nyc1'; const name = 'snow-cluster'; if (!clusterExists) { // Create the cluster. logInfo('Creating cluster. This will take a few minutes...'); await run(` doctl k8s clusters create ${name} \ --region ${region} \ --version 1.13.1-do.2 \ --node-pool "name=node-pool-0;size=s-1vcpu-2gb;count=2" \ --wait `); } else { logInfo('Cluster exists.'); } await run(`kubectl config use-context do-${region}-${name}`); break; } case 'azure': { const resourceGroup = 'snow'; const clusterName = 'snow-cluster'; // Create the resource group. await run(` az group create -n ${resourceGroup} \ -l westus \ `); // Create the cluster. await run(` az aks create \ -n ${clusterName} \ -g ${resourceGroup} \ --no-ssh-key \ -k 1.14.5 \ --node-count 2 `); // Get credentials. await run(` az aks get-credentials \ -g ${resourceGroup} \ -n ${clusterName} `); break; } default: { logError('No valid cloud provider selected.'); } } } /* * Authentication complete * Cluster exists * kubeconfig has properly configured auth credentials * Now the fun part: time to set up Kubernetes! */ /* * Install helm with TLS. * https://medium.com/google-cloud/install-secure-helm-in-gke-254d520061f7 */ await run('helm init --client-only'); const BYTES = 2048; // Create Certificate Authority await run(`openssl genrsa -out $(helm home)/ca.key.pem ${BYTES}`); const config = ` [req]\\n req_extensions=v3_ca\\n distinguished_name=req_distinguished_name\\n [req_distinguished_name]\\n [ v3_ca ]\\n basicConstraints=critical,CA:TRUE\\n subjectKeyIdentifier=hash\\n authorityKeyIdentifier=keyid:always,issuer:always`; await run( ` openssl req \\ -config <(printf '${config}') \\ -key $(helm home)/ca.key.pem \\ -new \\ -x509 \\ -days 7300 \\ -sha256 \\ -out $(helm home)/ca.cert.pem \\ -extensions v3_ca \\ -subj "/C=US"`, { shell: '/bin/bash' } ); // Create credentials for tiller (server) await run(`openssl genrsa -out $(helm home)/tiller.key.pem ${BYTES}`); await run( ` openssl req \ -new \ -sha256 \ -key $(helm home)/tiller.key.pem \ -out $(helm home)/tiller.csr.pem \ -subj "/C=US/O=Snow/CN=tiller-server"`, { shell: '/bin/bash' } ); const tillerConfig = ` [SAN]\\n subjectAltName=IP:127.0.0.1`; await run( ` openssl x509 -req -days 365 \ -CA $(helm home)/ca.cert.pem \ -CAkey $(helm home)/ca.key.pem \ -CAcreateserial \ -in $(helm home)/tiller.csr.pem \ -out $(helm home)/tiller.cert.pem \ -extfile <(printf '${tillerConfig}') \ -extensions SAN`, { shell: '/bin/bash' } ); // Create credentials for helm (client) await run(`openssl genrsa -out $(helm home)/helm.key.pem ${BYTES}`); await run(` openssl req -new -sha256 \ -key $(helm home)/helm.key.pem \ -out $(helm home)/helm.csr.pem \ -subj "/C=US" `); await run(` openssl x509 -req -days 365 \ -CA $(helm home)/ca.cert.pem \ -CAkey $(helm home)/ca.key.pem \ -CAcreateserial \ -in $(helm home)/helm.csr.pem \ -out $(helm home)/helm.cert.pem `); // Create service account and clusterrolebinding await run(`kubectl create serviceaccount \ --namespace kube-system tiller `); await run(`kubectl create clusterrolebinding \ tiller-cluster-rule \ --clusterrole=cluster-admin \ --serviceaccount=kube-system:tiller `); // Install Helm w/ 'tiller' service account await run(` helm init \ --debug \ --tiller-tls \ --tiller-tls-cert $(helm home)/tiller.cert.pem \ --tiller-tls-key $(helm home)/tiller.key.pem \ --tiller-tls-verify \ --tls-ca-cert $(helm home)/ca.cert.pem \ --service-account tiller \ --wait `); // Verify helm installation await run(` helm ls --tls \ --tls-ca-cert $(helm home)/ca.cert.pem \ --tls-cert $(helm home)/helm.cert.pem \ --tls-key $(helm home)/helm.key.pem `); /** * * To remove helm: * * helm reset * --tls * --tls-ca-cert $(helm home)/ca.cert.pem * --tls-cert $(helm home)/helm.cert.pem * --tls-key $(helm home)/helm.key.pem */ // Install nginx ingress await run(` helm install stable/nginx-ingress \ --tls \ --tls-ca-cert $(helm home)/ca.cert.pem \ --tls-cert $(helm home)/helm.cert.pem \ --tls-key $(helm home)/helm.key.pem \ --namespace kube-system \ --name nginx-ingress \ --version 0.31.0 \ --set controller.ingressClass=nginx \ --set rbac.create=true `); /** * Cert-manager. We need to use an alpha release since it supports * certificate generation with SAN's with IP addresses. */ // Install the CustomResourceDefinition resources await run('kubectl apply -f https://raw.githubusercontent.com/jetstack/cert-manager/release-0.7/deploy/manifests/00-crds.yaml'); // Add new helm repo for 0.7.0 alpha release of cert-manager await run('helm repo add jetstack https://charts.jetstack.io'); // Create a new namespace for cert-manager await run('kubectl create namespace cert-manager'); // Label the cert-manager namespace to disable resource validation await run('kubectl label namespace cert-manager certmanager.k8s.io/disable-validation=true'); // Install cert-manager await run(` helm install jetstack/cert-manager \ --tls \ --tls-ca-cert $(helm home)/ca.cert.pem \ --tls-cert $(helm home)/helm.cert.pem \ --tls-key $(helm home)/helm.key.pem \ --version v0.7.0-alpha.1 \ --namespace cert-manager \ --name cert-manager \ --set ingressShim.defaultIssuerName=letsencrypt-prod \ --set ingressShim.defaultIssuerKind=ClusterIssuer \ --set webhook.enabled=false `); let email = await askForInput( 'Provide an email address for Let\'s Encrypt' ); while (!(await confirm(`Confirm email: "${email}"`))) { email = await askForInput('Provide an email address for Let\'s Encrypt'); } // Create cluster issuer await run(` cat <<EOF | kubectl create -f - { "apiVersion": "certmanager.k8s.io/v1alpha1", "kind": "ClusterIssuer", "metadata": { "name": "letsencrypt-prod", "namespace": "cert-manager" }, "spec": { "acme": { "email": "${email}", "http01": {}, "privateKeySecretRef": { "name": "letsencrypt-prod" }, "server": "https://acme-v02.api.letsencrypt.org/directory" } } } \nEOF`); // Create self-signed issuer await run(` cat <<EOF | kubectl create -f - { "apiVersion": "certmanager.k8s.io/v1alpha1", "kind": "ClusterIssuer", "metadata": { "name": "selfsigning-issuer" }, "spec": { "selfSigned": {} } } \nEOF`); // Create global ingress controller await run(` cat <<EOF | kubectl create -f - { "apiVersion": "extensions/v1beta1", "kind": "Ingress", "metadata": { "annotations": { "ingress.kubernetes.io/ssl-redirect": "true", "kubernetes.io/ingress.class": "nginx", "kubernetes.io/tls-acme": "true" }, "name": "snow-ingress" }, "spec": { "rules": [ { "host": "snow.cluster" } ] } } \nEOF`); // Create persistent storage for docker registry await run(` cat <<EOF | kubectl create -f - { "kind": "PersistentVolumeClaim", "apiVersion": "v1", "metadata": { "name": "docker-registry-pvc" }, "spec": { "accessModes": [ "ReadWriteOnce" ], "volumeMode": "Filesystem", "resources": { "requests": { "storage": "8Gi" } } } } \nEOF`); // Install docker registry await run(` helm install stable/docker-registry \ --tls \ --tls-ca-cert $(helm home)/ca.cert.pem \ --tls-cert $(helm home)/helm.cert.pem \ --tls-key $(helm home)/helm.key.pem \ --namespace default \ --name docker-registry \ --version 1.7.0 \ --set secrets.htpasswd='user:$2y$05$8nR6bYM2ZKR0tkmJ9KEVTeWVVk77sucXVwZQp2q49t6sR0Oip346C' \ --set persistence.enabled=true \ --set persistence.existingClaim='docker-registry-pvc' \ --set tlsSecretName='docker-reg-cert-secret' `); const {stdout: dockerIP} = await run('kubectl get service/docker-registry -o jsonpath={.spec.clusterIP}'); // Create certificate for docker registry await run(` cat <<EOF | kubectl create -f - { "apiVersion": "certmanager.k8s.io/v1alpha1", "kind": "Certificate", "metadata": { "name": "docker-reg-cert" }, "spec": { "secretName": "docker-reg-cert-secret", "commonName": "docker-registry.default.svc.cluster.local", "ipAddresses": ["${dockerIP}"], "isCA": true, "issuerRef": { "name": "selfsigning-issuer", "kind": "ClusterIssuer" } } } \nEOF`); /* * Copy certificate to node VMs daily (to stop the docker * daemon from throwing TLS errors when pulling images) * * You can't mount to a folder to a colon in it, so we copy * to a temp folder, rename tls.crt to tls.cert (to make the * docker daemon happy), and then place the files in a folder * expected by the daemon. */ await run(` cat <<EOF | kubectl create -f - { "kind": "DaemonSet", "apiVersion": "apps/v1", "metadata": { "name": "configure-docker" }, "spec": { "selector": { "matchLabels": { "name": "configure-docker" } }, "template": { "metadata": { "labels": { "name": "configure-docker" } }, "spec": { "volumes": [ { "name": "etc-folder", "hostPath": { "path": "/etc" } }, { "name": "secrets", "secret": { "secretName": "docker-reg-cert-secret" } } ], "containers": [ { "name": "configure-docker-container", "image": "alpine", "args": [ "sh", "-c", "${[ 'mkdir -p /dockertmp;', 'cp /dockercert/* /dockertmp;', 'cp /dockertmp/tls.crt /dockertmp/tls.cert;', `mkdir -p /node/etc/docker/certs.d/${dockerIP}:5000;`, `cp /dockertmp/* /node/etc/docker/certs.d/${dockerIP}:5000;`, 'sleep 86400;' ].join(' ')}" ], "volumeMounts": [ { "name": "etc-folder", "mountPath": "/node/etc" }, { "name": "secrets", "mountPath": "/dockercert" } ] } ] } } } } \nEOF `); // Create secret/regcred to store registry credentials await run(`kubectl create secret docker-registry regcred --docker-server=${dockerIP}:5000 --docker-username=user --docker-password=password`); // Create ConfigMap for credentials await run(` cat <<EOF | kubectl create -f - { "apiVersion": "v1", "kind": "ConfigMap", "metadata": { "name": "docker-config" }, "data": { "config.json": "{\\"auths\\":{\\"${dockerIP}:5000\\":{\\"username\\":\\"user\\",\\"password\\":\\"password\\"}}}" } } \nEOF `); logInfo('🎉 Cluster created! In a few moments, your cluster IP will be available.'); logInfo('🎉 Get it by running \'snow ip\'. Create a DNS \'A\' record for hostnames'); logInfo('🎉 you wish to point to your cluster.'); };
the_stack
import * as React from 'react'; import { Avatar, AvatarGroup, Backdrop, Badge, Breadcrumbs, Button, Calendar, Caption, Card, CardSubdued, CardHeader, CardBody, CardFooter, Chip, Checkbox, Column, DatePicker, Dropdown, EditableDropdown, TimePicker, MultiSlider, Heading, Icon, Input, InputMask, Label, Link, Legend, MetaList, MetricInput, Message, Paragraph, Radio, Row, Text, OutsideClick, ProgressBar, StatusHint, Pills, Spinner, Slider, RangeSlider, Subheading, Switch, Textarea, Toast, Popover, ChipInput, VerticalNav, HorizontalNav, Tooltip, Dialog, Modal, ModalHeader, ModalFooter, ModalBody, ModalDescription, FullscreenModal, Sidesheet, Collapsible, ChatMessage, EmptyState, Pagination, PlaceholderParagraph, Placeholder, EditableInput, ProgressRing, Stepper, DateRangePicker, TabsWrapper, Tab, Dropzone, FileUploader, FileUploaderList, Grid, GridCell, Table, List, InlineMessage, ChoiceList, } from './index'; // $ExpectType Element <Avatar className="mr-5" firstName="firstName" lastName="lastName" />; // $ExpectError Property 'age' does not exist on type <Avatar className="mr-5" firstName="firstName" lastName="lastName" age="d" />; // $ExpectType Element <AvatarGroup list={[ { firstName: 'John', lastName: 'Doe', }, ]} max={1} popoverOptions={{ on: 'click', dark: false }} />; // $ExpectType Element <Backdrop className="BackdropClass" open={false} zIndex={1000} />; // $ExpectType Element <Badge appearance="alert" subtle={false}> {'Failed'} </Badge>; // $ExpectError Type 'string' is not assignable to type 'boolean | undefined'. <Badge appearance="alert" subtle={''}> {'Failed'} </Badge>; // $ExpectType Element <Breadcrumbs list={[]} onClick={() => console.log('')} className="My-custom-style" />; // $ExpectError Type '{}' is missing the following properties from type 'Breadcrumb': label, link <Breadcrumbs list={[{}]} className="My-custom-style" />; // $ExpectType Element <Button appearance="primary" icon="get_app" iconAlign="left" size="regular" className="mr-2"> Download </Button>; // $ExpectError Type '"small"' is not assignable to type '"regular" | "tiny" | "large" | undefined'. <Button appearance="primary" icon="get_app" iconAlign="left" size="small" className="mr-2"> Download </Button>; // $ExpectType Element <Calendar date={new Date(2020, 2, 15)} disabledBefore={new Date(2020, 2, 10)} disabledAfter={new Date(2021, 2, 20)} size={'large'} view="year" events={{ '09/12/2021': true }} onDateChange={() => {}} rangePicker={true} jumpView={true} />; <Calendar // $ExpectError Type 'string' is not assignable to type 'Date | undefined'. date={''} disabledBefore={new Date(2020, 2, 10)} size={'large'} view="year" events={{ '09/12/2021': true }} onDateChange={() => {}} />; // $ExpectType Element <Card shadow="none" className="w-50" style={{ height: '250px' }}> <CardHeader className="CardHeaderClass"> <Heading size="s" appearance={'disabled'} className="mb-7"> Daily progress </Heading> </CardHeader> <CardBody className="CardBodyClass"> <Paragraph>campaign starts</Paragraph> <Row> <Column size="12" className="pt-4"> <Radio label="Send now" name="gender" value="Checkbox" defaultChecked={true} /> <Text weight="strong" small={true} appearance="disabled" className="ml-7"> Campaign will start immediately </Text> </Column> <Column size="12" className="py-4" sizeXS={'12'} sizeXL="4" sizeM="4"> <Radio label="Schedule for later" name="gender" value="Checkbox" /> <Text small={true} appearance="disabled" className="ml-7"> Campaign will not start immediately </Text> </Column> </Row> </CardBody> <CardSubdued border="top" className="ml-7"> Subdued section. </CardSubdued> <CardFooter withSeperator={false} className="justify-content-end"> <Button appearance="primary" className="ml-4"> Submit </Button> </CardFooter> </Card>; // $ExpectError Type '"red"' is not assignable to type '"dark" | "default" | "none" | "light" | "medium" | undefined'. <Card shadow="red" className="w-50" style={{ height: '250px' }}> <div className="p-8" /> </Card>; // $ExpectError Type 'string' is not assignable to type 'boolean | undefined'. <CardFooter withSeperator={''} className="justify-content-end"> Card footer </CardFooter>; // $ExpectType Element <Chip icon="icon" label="First Name" clearButton={false} disabled={false} type="action" name={'chip'} onClick={() => {}} onClose={() => {}} selected={false} />; <Chip icon="icon" label="First Name" clearButton={false} disabled={false} type="action" // $ExpectError Type 'null' is not assignable to type 'ReactText'. name={null} onClick={() => {}} onClose={() => {}} selected={false} />; // $ExpectType Element <Checkbox defaultChecked={true} helpText={'help text'} indeterminate={true} label="Innovaccer" value="Innovaccer" className="mt-5" onChange={() => {}} />; // $ExpectError Type 'number' is not assignable to type 'string | undefined'. <Checkbox helpText={1} indeterminate={true} label="Innovaccer" value="Innovaccer" onChange={() => {}} />; // $ExpectError Type '"20"' is not assignable to type '1 | 8 | 2 | 10 | "auto" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "10" | "11" | "12" | 3 | 4 | 5 | 6 | 7 | 9 | 11 | 12 | undefined'. <Column size="20" className="py-4" sizeXS={'12'} sizeXL="4" sizeM="4"></Column>; // $ExpectType Element <DatePicker date={new Date(2020, 2, 1)} view="date" withInput={true} closeOnSelect={true} inputFormat="dd/mm/yyyy" outputFormat="dd/mm/yyyy" jumpView={true} onDateChange={() => console.log('date')} firstDayOfWeek="monday" inputOptions={{ required: true, }} />; // $ExpectError Type '""' is not assignable to type '"dd/mm/yyyy" | "mm/dd/yyyy" | "yyyy/mm/dd" | "mm-dd-yyyy" | "dd-mm-yyyy" | "yyyy-mm-dd" | undefined'. <DatePicker date={new Date(2020, 2, 1)} outputFormat="" />; // $ExpectType Element <TimePicker inputFormat="hh:mm AM" outputFormat="hh:mm AM" onTimeChange={() => {}} time="3:30 AM" inputOptions={{ placeholderChar: '*', }} />; // $ExpectType Element <Dropdown menu={true} icon="expand_more" options={[ { label: 'Download All', value: 'Download All', }, ]} withCheckbox={true} className="w-25" placeholder="Select" optionType="WITH_ICON" staticLimit={100} inlineLabel="Status" maxWidth={130} align="right" withSearch={true} onChange={() => {}} onClose={() => {}} loading={true} />; // $ExpectError JSX attributes must only be assigned a non-empty 'expression'. <Dropdown menu={} icon="expand_more" loading={true} />; // $ExpectType Element <Icon className="mr-5" name="events" appearance="subtle" onClick={() => {}} size={24} />; // $ExpectType Element <Input name="input" className="mb-4" placeholder="Enter password" type={'password'} value={'value'} onChange={() => {}} onClear={() => {}} disabled={true} />; // $ExpectError Type '"submit"' is not assignable to type '"number" | "text" | "password" | "email" | "tel" | "url" | undefined'. <Input name="input" className="mb-4" placeholder="Enter password" type={'submit'} />; // $ExpectType Element <MetricInput size="regular" value="val" onChange={() => {}} name="input" disabled={false} readOnly={false} onClick={() => {}} placeholder="placeholder" prefix="#" suffix="$" icon="icon" error={false} />; // $ExpectError Type 'null' is not assignable to type 'string | undefined'. <MetricInput name="input" className="mb-4" placeholder="Enter password" type={'submit'} prefix={null} />; // $ExpectType Element <InputMask name="input" type="text" value="value" defaultValue="defaultValue" disabled={false} onChange={() => {}} placeholder="placeholder" inlineLabel="inlineLabel" size="tiny" icon="icon" required={true} error={false} caption="caption" info="info" mask={[/\d/, /\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/, ' ', /\d/, /\d/, /\d/, /\d/]} />; // $ExpectError Type 'string' is not assignable to type 'Mask'. <InputMask name="input" className="mb-4" placeholder="Enter password" mask="" />; // $ExpectType Element <Label required={true} className="mt-6" withInput={true}> Gender </Label>; // $ExpectType Element <Caption error={false} withInput={true} className={'FileItem-error'}> With Error </Caption>; // $ExpectType Element <Legend iconAppearance="secondary" labelAppearance="destructive"> Legend </Legend>; // $ExpectError Type '"none"' is not assignable to type '"link" | "subtle" | "success" | "default" | "disabled" | "destructive" | "white" | undefined'. <Legend iconAppearance="secondary" labelAppearance="none"> Legend </Legend>; // $ExpectType Element <EditableDropdown placeholder="placeholder" dropdownOptions={{ onChange: () => {}, options: [{ label: 'label1', value: 'value1' }], }} />; // $ExpectType Element <Link href="http://innovaccer.com" onClick={() => {}} appearance="subtle" size="tiny"> Link </Link>; // $ExpectType Element <Message title="title" actions={<div>action</div>} appearance="alert" description="Could not start verification. Please try again later." />; // $ExpectType Element <Message title="title" actions={<div>action</div>} appearance="alert" description="Could not start verification. Please try again later." />; // $ExpectType Element <MetaList seperator={true} list={[{ icon: 'assessment', label: 'Meta data' }]} />; // $ExpectType Element <MultiSlider onRangeChange={() => {}}> <MultiSlider.Handle value={0} fillAfter={true} /> <MultiSlider.Handle value={1} /> </MultiSlider>; // $ExpectType Element <OutsideClick className="d-inline-block" onOutsideClick={() => {}}> <Card className="d-flex align-items-center justify-content-center" style={{ height: 200, width: 200 }}> <Heading>Card</Heading> </Card> </OutsideClick>; // $ExpectType Element <ProgressBar value={50} max={100} />; // $ExpectType Element <StatusHint appearance="success">437 wil receive the message.</StatusHint>; // $ExpectType Element <Pills appearance="alert" subtle={false}> {'Pills'} </Pills>; // $ExpectType Element <Spinner size="small" appearance={'secondary'} data-test="DesignSystem-Button--Spinner" className="Button-spinner" />; // $ExpectType Element <Slider min={1} max={10} label="Controlled Slider" stepSize={0.1} labelStepSize={1} value={10} onChange={() => {}} className="mt-2" />; // $ExpectType Element <RangeSlider min={1} max={10} label="Controlled Slider" stepSize={0.1} labelStepSize={1} value={[2, 4]} onChange={() => {}} className="mt-2" />; // $ExpectType Element <Subheading appearance="subtle">Subheading</Subheading>; // $ExpectType Element <Switch defaultChecked={true} size="regular" disabled={false} checked={true} onChange={() => {}} />; // $ExpectType Element <Textarea name="comments" id="comments" className="w-25" placeholder="Enter your comments here" value="value" onChange={(e) => { console.log(e); }} rows={3} />; // $ExpectType Element <Toast appearance="alert" title="Campaign failed to run" message="Try to run again. If it continues to fail, please raise a ticket." actions={[ { label: 'Need Prior Auth', onClick: () => {}, }, ]} />; // $ExpectType Element <Popover position="bottom" on="click" trigger={<Button appearance="basic">Open Popup</Button>} dark={true} open={true}> <div style={{ width: 'var(--spacing-7)', height: 'var(--spacing-7)' }} /> </Popover>; // $ExpectType Element <ChipInput allowDuplicates={false} placeholder="placeholder" disabled={false} chipOptions={{ clearButton: true }} value={['1024', '80']} className="w-50" onChange={() => {}} />; // $ExpectType Element <VerticalNav menus={[ { name: 'received', label: 'Received', icon: 'call_received', subMenu: [ { name: 'to_dos.due', label: 'Due', count: 10, }, ], }, ]} expanded={true} active={{ name: 'data_exchange.reports', }} onClick={() => {}} autoCollapse={true} />; // $ExpectType Element <HorizontalNav className="w-100 justify-content-center" menus={[ { name: 'received', label: 'Received', icon: 'call_received', subMenu: [ { name: 'to_dos.due', label: 'Due', count: 10, }, ], }, ]} active={{ name: 'data_exchange.reports', }} onClick={() => {}} />; // $ExpectType Element <Tooltip tooltip="tooltip" position="top" appendToBody={true} triggerClass="w-100 overflow-hidden"> <Button>Button</Button> </Tooltip>; // $ExpectType Element <Dialog open={true} onClose={() => {}} dimension="small" primaryButtonAppearance="primary" secondaryButtonAppearance="success" heading="Heading" title="Description Title" description="Adding a subheading clearly indicates the hierarchy of the information." primaryButtonLabel="Primary" secondaryButtonLabel="Basic" />; // $ExpectType Element <Modal open={true} dimension="small" backdropClose={true}> <ModalHeader onClose={() => {}} heading="Heading" subHeading="Subheading" /> <ModalBody> <Text>Modal Body</Text> <ModalDescription title="Description Title" description="Adding a subheading clearly indicates the hierarchy of the information." /> <ModalDescription description="Card Sections include supporting text like an article summary or a restaurant description." /> </ModalBody> <ModalFooter open={true}> <Button appearance="basic" onClick={() => {}}> Basic </Button> <Button appearance="primary" className="ml-4" onClick={() => {}}> Primary </Button> </ModalFooter> </Modal>; // $ExpectType Element <Modal open={true} dimension="small" backdropClose={true}> <ModalHeader onClose={() => {}} heading="Heading" subHeading="Subheading" /> <ModalBody> <Text>Modal Body</Text> <ModalDescription title="Description Title" description="Adding a subheading clearly indicates the hierarchy of the information." /> <ModalDescription description="Card Sections include supporting text like an article summary or a restaurant description." /> </ModalBody> <ModalFooter open={true}> <Button appearance="basic" onClick={() => {}}> Basic </Button> <Button appearance="primary" className="ml-4" onClick={() => {}}> Primary </Button> </ModalFooter> </Modal>; // $ExpectType Element <FullscreenModal open={true} dimension="large" onClose={() => {}} headerOptions={{ heading: 'This is modal Heading', subHeading: 'This is modal subheading', }} footerOptions={{ actions: [ { children: 'Primary', appearance: 'primary', className: 'ml-4', onClick: () => {}, }, ], }} > <Text>Fullscreen Modal Body</Text> </FullscreenModal>; // $ExpectType Element <Sidesheet dimension="large" headerOptions={{ backIcon: false, heading: 'Heading', subHeading: 'Subheading', }} open={true} footerOptions={{ actions: [] }} />; // $ExpectType Element <Collapsible height="500px" expandedWidth={240} onToggle={() => {}} hoverable={false} expanded={true}> <div className="d-flex pt-4"> <Icon name="events" data-test="DesignSystem-Collapsible--Icon" /> </div> </Collapsible>; // $ExpectType Element <ChatMessage text="Message Text" type="incoming" typingText="Typing Text" statusOptions={{ type: 'sending', sendingText: 'Sending Text', }} />; // $ExpectType Element <EmptyState title="Unable to fetch data" description="Sorry there was a technical issue while getting this data. Please try again." imageSrc="/image" size="small" className="pb-6" > <Button icon="refresh" iconAlign="left" className="mt-3"> Reload </Button> </EmptyState>; // $ExpectType Element <Pagination type="basic" page={1} totalPages={50} onPageChange={(pageNo) => console.log(pageNo)} />; // $ExpectType Element <Placeholder withImage={false} round={true}> <PlaceholderParagraph className="ml-3" length="large" size="m" /> </Placeholder>; // $ExpectType Element <EditableInput placeholder="First Name" value="value" onChange={() => {}} error={true} errorMessage={'Error Message'} />; // $ExpectType Element <ProgressRing value={30} size="regular" max={100} />; // $ExpectType Element <Stepper steps={[ { label: 'Step', value: 'Step1', }, { label: 'Step', value: 'Step2', }, ]} active={1} completed={2} onChange={() => {}} />; // $ExpectType Element <DateRangePicker monthsInView={3} startDate={new Date(2019, 11, 3)} endDate={new Date(2020, 1, 11)} startInputOptions={{ caption: 'caption', error: true, required: true }} yearNav={2019} monthNav={11} withInput={true} onRangeChange={() => {}} inputOptions={{ placeholderChar: '#' }} />; // $ExpectType Element <TabsWrapper active={0} onTabChange={() => {}}> <Tab label="label" count={10} icon="icon" disabled={true}> Tab 1 </Tab> </TabsWrapper>; // $ExpectType Element <Dropzone formatLabel="Accepted formats: PDF, jpg" sizeLabel="Maximum size: 25 MB" onDrop={() => {}} disabled={false} className="mb-3" type="tight" sampleFileLink={ <Link href="http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf" download="Test.pdf" target="_blank" > Download sample file </Link> } />; // $ExpectType Element <Dropzone formatLabel="Accepted formats: PDF, jpg" sizeLabel="Maximum size: 25 MB" onDrop={() => {}} disabled={false} className="mb-3" type="tight" sampleFileLink={ <Link href="http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf" download="Test.pdf" target="_blank" > Download sample file </Link> } />; // $ExpectType Element <FileUploader sizeLabel="Maximum size: 25 MB" disabled={false} className="mb-3" multiple={true} title="title" sampleFileLink={ <Link href="http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf" download="Test.pdf" target="_blank" > Download sample file </Link> } formatLabel="Accepted formats: PDF, jpg, png" />; // $ExpectType Element <FileUploaderList onDelete={() => {}} onRetry={() => {}} fileList={[ { file: (File = { name: 'Audio File.mp3', size: '3 MB', type: 'audio', } as any), status: 'uploading', progress: 45, id: 1, }, ]} className="mt-4" />; // $ExpectType Element <Grid schema={[ { name: 'name', displayName: 'Name', width: '50%', }, ]} data={[ { name: 'Zara', gender: 'f', }, ]} withCheckbox={true} withPagination={true} updateSortingList={() => {}} sortingList={[{ name: 'name', type: 'desc' }]} />; // $ExpectType Element <GridCell schema={{ displayName: 'Name', name: 'name', cellType: 'WITH_META_LIST', }} data={{ name: 'Zara' }} loading={true} size="comfortable" rowIndex={1} colIndex={1} />; // $ExpectType Element <Table data={[ { className: 'align-baseline', properties: 'vertical-align: baseline ;', }, ]} schema={[ { name: 'className', displayName: 'ClassName', width: '50%', resizable: true, align: 'left', cellRenderer: (props: any) => { return ( <> <GridCell {...props} /> <Button title="Copy className to clipboard" appearance="transparent" icon="content_copy" onClick={() => {}} /> </> ); }, }, ]} size={'standard'} headerOptions={{ withSearch: true, }} showMenu={false} />; // $ExpectType Element <List data={[ { data: { title: 'Reminder for due lab tests', subTitle: 'ENG. +1 Hi [recipient.name]! Your (test) is overdue. Please get in touch with [recipient.PCPI...', }, }, ]} schema={[ { width: '100%', name: 'data', displayName: '', cellRenderer: () => { return ( <> <Paragraph> <Text weight="strong">title</Text> </Paragraph> </> ); }, }, ]} withHeader={true} headerOptions={{ withSearch: true, dynamicColumn: false, }} withPagination={true} pageSize={5} />; // $ExpectType Element <ChoiceList choices={[ { label: 'Male', name: 'gender', value: 'Male' }, { label: 'Female', name: 'gender', value: 'Female' }, { label: 'Other', name: 'gender', value: 'Other' }, ]} title="title" onChange={() => {}} />; // $ExpectType Element <InlineMessage appearance="info" description="Patient profile updated." />;
the_stack
import { ethers } from 'hardhat' import { assert, expect } from 'chai' import { evmRevert } from '../test-helpers/matchers' import { getUsers, Personas } from '../test-helpers/setup' import { BigNumber, Signer, BigNumberish } from 'ethers' import { LinkToken__factory as LinkTokenFactory } from '../../typechain/factories/LinkToken__factory' import { KeeperRegistry__factory as KeeperRegistryFactory } from '../../typechain/factories/KeeperRegistry__factory' import { MockV3Aggregator__factory as MockV3AggregatorFactory } from '../../typechain/factories/MockV3Aggregator__factory' import { UpkeepMock__factory as UpkeepMockFactory } from '../../typechain/factories/UpkeepMock__factory' import { UpkeepReverter__factory as UpkeepReverterFactory } from '../../typechain/factories/UpkeepReverter__factory' import { KeeperRegistry } from '../../typechain/KeeperRegistry' import { MockV3Aggregator } from '../../typechain/MockV3Aggregator' import { LinkToken } from '../../typechain/LinkToken' import { UpkeepMock } from '../../typechain/UpkeepMock' import { toWei } from '../test-helpers/helpers' async function getUpkeepID(tx: any) { const receipt = await tx.wait() return receipt.events[0].args.id } // ----------------------------------------------------------------------------------------------- // DEV: these *should* match the perform/check gas overhead values in the contract and on the node const PERFORM_GAS_OVERHEAD = BigNumber.from(90000) const CHECK_GAS_OVERHEAD = BigNumber.from(170000) // ----------------------------------------------------------------------------------------------- // Smart contract factories let linkTokenFactory: LinkTokenFactory let mockV3AggregatorFactory: MockV3AggregatorFactory let keeperRegistryFactory: KeeperRegistryFactory let upkeepMockFactory: UpkeepMockFactory let upkeepReverterFactory: UpkeepReverterFactory let personas: Personas before(async () => { personas = (await getUsers()).personas linkTokenFactory = await ethers.getContractFactory('LinkToken') // need full path because there are two contracts with name MockV3Aggregator mockV3AggregatorFactory = (await ethers.getContractFactory( 'src/v0.7/tests/MockV3Aggregator.sol:MockV3Aggregator', )) as unknown as MockV3AggregatorFactory keeperRegistryFactory = await ethers.getContractFactory('KeeperRegistry') upkeepMockFactory = await ethers.getContractFactory('UpkeepMock') upkeepReverterFactory = await ethers.getContractFactory('UpkeepReverter') }) describe('KeeperRegistry', () => { const linkEth = BigNumber.from(300000000) const gasWei = BigNumber.from(100) const linkDivisibility = BigNumber.from('1000000000000000000') const executeGas = BigNumber.from('100000') const paymentPremiumBase = BigNumber.from('1000000000') const paymentPremiumPPB = BigNumber.from('250000000') const flatFeeMicroLink = BigNumber.from(0) const blockCountPerTurn = BigNumber.from(3) const emptyBytes = '0x00' const zeroAddress = ethers.constants.AddressZero const extraGas = BigNumber.from('250000') const registryGasOverhead = BigNumber.from('80000') const stalenessSeconds = BigNumber.from(43820) const gasCeilingMultiplier = BigNumber.from(1) const maxCheckGas = BigNumber.from(20000000) const fallbackGasPrice = BigNumber.from(200) const fallbackLinkPrice = BigNumber.from(200000000) let owner: Signer let keeper1: Signer let keeper2: Signer let keeper3: Signer let nonkeeper: Signer let admin: Signer let payee1: Signer let payee2: Signer let payee3: Signer let linkToken: LinkToken let linkEthFeed: MockV3Aggregator let gasPriceFeed: MockV3Aggregator let registry: KeeperRegistry let mock: UpkeepMock let id: BigNumber let keepers: string[] let payees: string[] beforeEach(async () => { owner = personas.Default keeper1 = personas.Carol keeper2 = personas.Eddy keeper3 = personas.Nancy nonkeeper = personas.Ned admin = personas.Neil payee1 = personas.Nelly payee2 = personas.Norbert payee3 = personas.Nick keepers = [ await keeper1.getAddress(), await keeper2.getAddress(), await keeper3.getAddress(), ] payees = [ await payee1.getAddress(), await payee2.getAddress(), await payee3.getAddress(), ] linkToken = await linkTokenFactory.connect(owner).deploy() gasPriceFeed = await mockV3AggregatorFactory .connect(owner) .deploy(0, gasWei) linkEthFeed = await mockV3AggregatorFactory .connect(owner) .deploy(9, linkEth) registry = await keeperRegistryFactory .connect(owner) .deploy( linkToken.address, linkEthFeed.address, gasPriceFeed.address, paymentPremiumPPB, flatFeeMicroLink, blockCountPerTurn, maxCheckGas, stalenessSeconds, gasCeilingMultiplier, fallbackGasPrice, fallbackLinkPrice, ) mock = await upkeepMockFactory.deploy() await linkToken .connect(owner) .transfer(await keeper1.getAddress(), toWei('1000')) await linkToken .connect(owner) .transfer(await keeper2.getAddress(), toWei('1000')) await linkToken .connect(owner) .transfer(await keeper3.getAddress(), toWei('1000')) await registry.connect(owner).setKeepers(keepers, payees) const tx = await registry .connect(owner) .registerUpkeep( mock.address, executeGas, await admin.getAddress(), emptyBytes, ) id = await getUpkeepID(tx) }) const linkForGas = ( upkeepGasSpent: BigNumberish, premiumPPB?: BigNumberish, flatFee?: BigNumberish, ) => { premiumPPB = premiumPPB === undefined ? paymentPremiumPPB : premiumPPB flatFee = flatFee === undefined ? flatFeeMicroLink : flatFee const gasSpent = registryGasOverhead.add(BigNumber.from(upkeepGasSpent)) const base = gasWei.mul(gasSpent).mul(linkDivisibility).div(linkEth) const premium = base.mul(premiumPPB).div(paymentPremiumBase) const flatFeeJules = BigNumber.from(flatFee).mul('1000000000000') return base.add(premium).add(flatFeeJules) } describe('#setKeepers', () => { const IGNORE_ADDRESS = '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF' it('reverts when not called by the owner', async () => { await evmRevert( registry.connect(keeper1).setKeepers([], []), 'Only callable by owner', ) }) it('reverts when adding the same keeper twice', async () => { await evmRevert( registry .connect(owner) .setKeepers( [await keeper1.getAddress(), await keeper1.getAddress()], [await payee1.getAddress(), await payee1.getAddress()], ), 'cannot add keeper twice', ) }) it('reverts with different numbers of keepers/payees', async () => { await evmRevert( registry .connect(owner) .setKeepers( [await keeper1.getAddress(), await keeper2.getAddress()], [await payee1.getAddress()], ), 'address lists not the same length', ) await evmRevert( registry .connect(owner) .setKeepers( [await keeper1.getAddress()], [await payee1.getAddress(), await payee2.getAddress()], ), 'address lists not the same length', ) }) it('reverts if the payee is the zero address', async () => { await evmRevert( registry .connect(owner) .setKeepers( [await keeper1.getAddress(), await keeper2.getAddress()], [ await payee1.getAddress(), '0x0000000000000000000000000000000000000000', ], ), 'cannot set payee to the zero address', ) }) it('emits events for every keeper added and removed', async () => { const oldKeepers = [ await keeper1.getAddress(), await keeper2.getAddress(), ] const oldPayees = [await payee1.getAddress(), await payee2.getAddress()] await registry.connect(owner).setKeepers(oldKeepers, oldPayees) assert.deepEqual(oldKeepers, await registry.getKeeperList()) // remove keepers const newKeepers = [ await keeper2.getAddress(), await keeper3.getAddress(), ] const newPayees = [await payee2.getAddress(), await payee3.getAddress()] const tx = await registry.connect(owner).setKeepers(newKeepers, newPayees) assert.deepEqual(newKeepers, await registry.getKeeperList()) await expect(tx) .to.emit(registry, 'KeepersUpdated') .withArgs(newKeepers, newPayees) }) it('updates the keeper to inactive when removed', async () => { await registry.connect(owner).setKeepers(keepers, payees) await registry .connect(owner) .setKeepers( [await keeper1.getAddress(), await keeper3.getAddress()], [await payee1.getAddress(), await payee3.getAddress()], ) const added = await registry.getKeeperInfo(await keeper1.getAddress()) assert.isTrue(added.active) const removed = await registry.getKeeperInfo(await keeper2.getAddress()) assert.isFalse(removed.active) }) it('does not change the payee if IGNORE_ADDRESS is used as payee', async () => { const oldKeepers = [ await keeper1.getAddress(), await keeper2.getAddress(), ] const oldPayees = [await payee1.getAddress(), await payee2.getAddress()] await registry.connect(owner).setKeepers(oldKeepers, oldPayees) assert.deepEqual(oldKeepers, await registry.getKeeperList()) const newKeepers = [ await keeper2.getAddress(), await keeper3.getAddress(), ] const newPayees = [IGNORE_ADDRESS, await payee3.getAddress()] const tx = await registry.connect(owner).setKeepers(newKeepers, newPayees) assert.deepEqual(newKeepers, await registry.getKeeperList()) const ignored = await registry.getKeeperInfo(await keeper2.getAddress()) assert.equal(await payee2.getAddress(), ignored.payee) assert.equal(true, ignored.active) await expect(tx) .to.emit(registry, 'KeepersUpdated') .withArgs(newKeepers, newPayees) }) it('reverts if the owner changes the payee', async () => { await registry.connect(owner).setKeepers(keepers, payees) await evmRevert( registry .connect(owner) .setKeepers(keepers, [ await payee1.getAddress(), await payee2.getAddress(), await owner.getAddress(), ]), 'cannot change payee', ) }) }) describe('#registerUpkeep', () => { it('reverts if the target is not a contract', async () => { await evmRevert( registry .connect(owner) .registerUpkeep( zeroAddress, executeGas, await admin.getAddress(), emptyBytes, ), 'target is not a contract', ) }) it('reverts if called by a non-owner', async () => { await evmRevert( registry .connect(keeper1) .registerUpkeep( mock.address, executeGas, await admin.getAddress(), emptyBytes, ), 'Only callable by owner or registrar', ) }) it('reverts if execute gas is too low', async () => { await evmRevert( registry .connect(owner) .registerUpkeep( mock.address, 2299, await admin.getAddress(), emptyBytes, ), 'min gas is 2300', ) }) it('reverts if execute gas is too high', async () => { await evmRevert( registry .connect(owner) .registerUpkeep( mock.address, 5000001, await admin.getAddress(), emptyBytes, ), 'max gas is 5000000', ) }) it('creates a record of the registration', async () => { const tx = await registry .connect(owner) .registerUpkeep( mock.address, executeGas, await admin.getAddress(), emptyBytes, ) id = await getUpkeepID(tx) await expect(tx) .to.emit(registry, 'UpkeepRegistered') .withArgs(id, executeGas, await admin.getAddress()) const registration = await registry.getUpkeep(id) assert.equal(mock.address, registration.target) assert.equal(0, registration.balance.toNumber()) assert.equal(emptyBytes, registration.checkData) assert(registration.maxValidBlocknumber.eq('0xffffffffffffffff')) }) }) describe('#addFunds', () => { const amount = toWei('1') beforeEach(async () => { await linkToken.connect(keeper1).approve(registry.address, toWei('100')) }) it('reverts if the registration does not exist', async () => { await evmRevert( registry.connect(keeper1).addFunds(id.add(1), amount), 'upkeep must be active', ) }) it('adds to the balance of the registration', async () => { await registry.connect(keeper1).addFunds(id, amount) const registration = await registry.getUpkeep(id) assert.isTrue(amount.eq(registration.balance)) }) it('emits a log', async () => { const tx = await registry.connect(keeper1).addFunds(id, amount) await expect(tx) .to.emit(registry, 'FundsAdded') .withArgs(id, await keeper1.getAddress(), amount) }) it('reverts if the upkeep is canceled', async () => { await registry.connect(admin).cancelUpkeep(id) await evmRevert( registry.connect(keeper1).addFunds(id, amount), 'upkeep must be active', ) }) }) describe('#checkUpkeep', () => { it('reverts if the upkeep is not funded', async () => { await mock.setCanPerform(true) await mock.setCanCheck(true) await evmRevert( registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()), 'insufficient funds', ) }) context('when the registration is funded', () => { beforeEach(async () => { await linkToken.connect(keeper1).approve(registry.address, toWei('100')) await registry.connect(keeper1).addFunds(id, toWei('100')) }) it('reverts if executed', async () => { await mock.setCanPerform(true) await mock.setCanCheck(true) await evmRevert( registry.checkUpkeep(id, await keeper1.getAddress()), 'only for simulated backend', ) }) it('reverts if the specified keeper is not valid', async () => { await mock.setCanPerform(true) await mock.setCanCheck(true) await evmRevert( registry.checkUpkeep(id, await owner.getAddress()), 'only for simulated backend', ) }) context('and upkeep is not needed', () => { beforeEach(async () => { await mock.setCanCheck(false) }) it('reverts', async () => { await evmRevert( registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()), 'upkeep not needed', ) }) }) context('and the upkeep check fails', () => { beforeEach(async () => { const reverter = await upkeepReverterFactory.deploy() const tx = await registry .connect(owner) .registerUpkeep( reverter.address, 2500000, await admin.getAddress(), emptyBytes, ) id = await getUpkeepID(tx) await linkToken .connect(keeper1) .approve(registry.address, toWei('100')) await registry.connect(keeper1).addFunds(id, toWei('100')) }) it('reverts', async () => { await evmRevert( registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()), 'call to check target failed', ) }) }) context('and performing the upkeep simulation fails', () => { beforeEach(async () => { await mock.setCanCheck(true) await mock.setCanPerform(false) }) it('reverts', async () => { await evmRevert( registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()), 'call to perform upkeep failed', ) }) }) context('and upkeep check and perform simulations succeeds', () => { beforeEach(async () => { await mock.setCanCheck(true) await mock.setCanPerform(true) }) context('and the registry is paused', () => { beforeEach(async () => { await registry.connect(owner).pause() }) it('reverts', async () => { await evmRevert( registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()), 'Pausable: paused', ) await registry.connect(owner).unpause() await registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()) }) }) it('returns true with pricing info if the target can execute', async () => { const newGasMultiplier = BigNumber.from(10) await registry .connect(owner) .setConfig( paymentPremiumPPB, flatFeeMicroLink, blockCountPerTurn, maxCheckGas, stalenessSeconds, newGasMultiplier, fallbackGasPrice, fallbackLinkPrice, ) const response = await registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()) assert.isTrue(response.gasLimit.eq(executeGas)) assert.isTrue(response.linkEth.eq(linkEth)) assert.isTrue( response.adjustedGasWei.eq(gasWei.mul(newGasMultiplier)), ) assert.isTrue( response.maxLinkPayment.eq( linkForGas(executeGas.toNumber()).mul(newGasMultiplier), ), ) }) it('has a large enough gas overhead to cover upkeeps that use all their gas [ @skip-coverage ]', async () => { await mock.setCheckGasToBurn(maxCheckGas) await mock.setPerformGasToBurn(executeGas) const gas = maxCheckGas .add(executeGas) .add(PERFORM_GAS_OVERHEAD) .add(CHECK_GAS_OVERHEAD) await registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress(), { gasLimit: gas, }) }) }) }) }) describe('#performUpkeep', () => { let _lastKeeper = keeper1 async function getPerformPaymentAmount() { _lastKeeper = _lastKeeper === keeper1 ? keeper2 : keeper1 const before = ( await registry.getKeeperInfo(await _lastKeeper.getAddress()) ).balance await registry.connect(_lastKeeper).performUpkeep(id, '0x') const after = ( await registry.getKeeperInfo(await _lastKeeper.getAddress()) ).balance const difference = after.sub(before) return difference } it('reverts if the registration is not funded', async () => { await evmRevert( registry.connect(keeper2).performUpkeep(id, '0x'), 'insufficient funds', ) }) context('when the registration is funded', () => { beforeEach(async () => { await linkToken.connect(owner).approve(registry.address, toWei('100')) await registry.connect(owner).addFunds(id, toWei('100')) }) it('does not revert if the target cannot execute', async () => { const mockResponse = await mock .connect(zeroAddress) .callStatic.checkUpkeep('0x') assert.isFalse(mockResponse.callable) await registry.connect(keeper3).performUpkeep(id, '0x') }) it('returns false if the target cannot execute', async () => { const mockResponse = await mock .connect(zeroAddress) .callStatic.checkUpkeep('0x') assert.isFalse(mockResponse.callable) assert.isFalse( await registry.connect(keeper1).callStatic.performUpkeep(id, '0x'), ) }) it('returns true if called', async () => { await mock.setCanPerform(true) const response = await registry .connect(keeper1) .callStatic.performUpkeep(id, '0x') assert.isTrue(response) }) it('reverts if not enough gas supplied', async () => { await mock.setCanPerform(true) await evmRevert( registry .connect(keeper1) .performUpkeep(id, '0x', { gasLimit: BigNumber.from('120000') }), ) }) it('executes the data passed to the registry', async () => { await mock.setCanPerform(true) const performData = '0xc0ffeec0ffee' const tx = await registry .connect(keeper1) .performUpkeep(id, performData, { gasLimit: extraGas }) const receipt = await tx.wait() const eventLog = receipt?.events assert.equal(eventLog?.length, 2) assert.equal(eventLog?.[1].event, 'UpkeepPerformed') assert.equal(eventLog?.[1].args?.[0].toNumber(), id.toNumber()) assert.equal(eventLog?.[1].args?.[1], true) assert.equal(eventLog?.[1].args?.[2], await keeper1.getAddress()) assert.isNotEmpty(eventLog?.[1].args?.[3]) assert.equal(eventLog?.[1].args?.[4], performData) }) it('updates payment balances', async () => { const keeperBefore = await registry.getKeeperInfo( await keeper1.getAddress(), ) const registrationBefore = await registry.getUpkeep(id) const keeperLinkBefore = await linkToken.balanceOf( await keeper1.getAddress(), ) const registryLinkBefore = await linkToken.balanceOf(registry.address) // Do the thing await registry.connect(keeper1).performUpkeep(id, '0x') const keeperAfter = await registry.getKeeperInfo( await keeper1.getAddress(), ) const registrationAfter = await registry.getUpkeep(id) const keeperLinkAfter = await linkToken.balanceOf( await keeper1.getAddress(), ) const registryLinkAfter = await linkToken.balanceOf(registry.address) assert.isTrue(keeperAfter.balance.gt(keeperBefore.balance)) assert.isTrue(registrationBefore.balance.gt(registrationAfter.balance)) assert.isTrue(keeperLinkAfter.eq(keeperLinkBefore)) assert.isTrue(registryLinkBefore.eq(registryLinkAfter)) }) it('only pays for gas used [ @skip-coverage ]', async () => { const before = ( await registry.getKeeperInfo(await keeper1.getAddress()) ).balance const tx = await registry.connect(keeper1).performUpkeep(id, '0x') const receipt = await tx.wait() const after = (await registry.getKeeperInfo(await keeper1.getAddress())) .balance const max = linkForGas(executeGas.toNumber()) const totalTx = linkForGas(receipt.gasUsed.toNumber()) const difference = after.sub(before) assert.isTrue(max.gt(totalTx)) assert.isTrue(totalTx.gt(difference)) assert.isTrue(linkForGas(5700).lt(difference)) // exact number is flaky assert.isTrue(linkForGas(6000).gt(difference)) // instead test a range }) it('only pays at a rate up to the gas ceiling [ @skip-coverage ]', async () => { const multiplier = BigNumber.from(10) const gasPrice = BigNumber.from('1000000000') // 10M x the gas feed's rate await registry .connect(owner) .setConfig( paymentPremiumPPB, flatFeeMicroLink, blockCountPerTurn, maxCheckGas, stalenessSeconds, multiplier, fallbackGasPrice, fallbackLinkPrice, ) const before = ( await registry.getKeeperInfo(await keeper1.getAddress()) ).balance const tx = await registry .connect(keeper1) .performUpkeep(id, '0x', { gasPrice }) const receipt = await tx.wait() const after = (await registry.getKeeperInfo(await keeper1.getAddress())) .balance const max = linkForGas(executeGas).mul(multiplier) const totalTx = linkForGas(receipt.gasUsed).mul(multiplier) const difference = after.sub(before) assert.isTrue(max.gt(totalTx)) assert.isTrue(totalTx.gt(difference)) assert.isTrue(linkForGas(5700).mul(multiplier).lt(difference)) assert.isTrue(linkForGas(6000).mul(multiplier).gt(difference)) }) it('only pays as much as the node spent [ @skip-coverage ]', async () => { const multiplier = BigNumber.from(10) const gasPrice = BigNumber.from(200) // 2X the gas feed's rate const effectiveMultiplier = BigNumber.from(2) await registry .connect(owner) .setConfig( paymentPremiumPPB, flatFeeMicroLink, blockCountPerTurn, maxCheckGas, stalenessSeconds, multiplier, fallbackGasPrice, fallbackLinkPrice, ) const before = ( await registry.getKeeperInfo(await keeper1.getAddress()) ).balance const tx = await registry .connect(keeper1) .performUpkeep(id, '0x', { gasPrice }) const receipt = await tx.wait() const after = (await registry.getKeeperInfo(await keeper1.getAddress())) .balance const max = linkForGas(executeGas.toNumber()).mul(effectiveMultiplier) const totalTx = linkForGas(receipt.gasUsed).mul(effectiveMultiplier) const difference = after.sub(before) assert.isTrue(max.gt(totalTx)) assert.isTrue(totalTx.gt(difference)) assert.isTrue(linkForGas(5700).mul(effectiveMultiplier).lt(difference)) assert.isTrue(linkForGas(6000).mul(effectiveMultiplier).gt(difference)) }) it('pays the caller even if the target function fails', async () => { const tx = await registry .connect(owner) .registerUpkeep( mock.address, executeGas, await admin.getAddress(), emptyBytes, ) const id = await getUpkeepID(tx) await linkToken.connect(owner).approve(registry.address, toWei('100')) await registry.connect(owner).addFunds(id, toWei('100')) const keeperBalanceBefore = ( await registry.getKeeperInfo(await keeper1.getAddress()) ).balance // Do the thing await registry.connect(keeper1).performUpkeep(id, '0x') const keeperBalanceAfter = ( await registry.getKeeperInfo(await keeper1.getAddress()) ).balance assert.isTrue(keeperBalanceAfter.gt(keeperBalanceBefore)) }) it('reverts if called by a non-keeper', async () => { await evmRevert( registry.connect(nonkeeper).performUpkeep(id, '0x'), 'only active keepers', ) }) it('reverts if the upkeep has been canceled', async () => { await mock.setCanPerform(true) await registry.connect(owner).cancelUpkeep(id) await evmRevert( registry.connect(keeper1).performUpkeep(id, '0x'), 'invalid upkeep id', ) }) it('uses the fallback gas price if the feed price is stale [ @skip-coverage ]', async () => { const normalAmount = await getPerformPaymentAmount() const roundId = 99 const answer = 100 const updatedAt = 946684800 // New Years 2000 🥳 const startedAt = 946684799 await gasPriceFeed .connect(owner) .updateRoundData(roundId, answer, updatedAt, startedAt) const amountWithStaleFeed = await getPerformPaymentAmount() assert.isTrue(normalAmount.lt(amountWithStaleFeed)) }) it('uses the fallback gas price if the feed price is non-sensical [ @skip-coverage ]', async () => { const normalAmount = await getPerformPaymentAmount() const roundId = 99 const updatedAt = Math.floor(Date.now() / 1000) const startedAt = 946684799 await gasPriceFeed .connect(owner) .updateRoundData(roundId, -100, updatedAt, startedAt) const amountWithNegativeFeed = await getPerformPaymentAmount() await gasPriceFeed .connect(owner) .updateRoundData(roundId, 0, updatedAt, startedAt) const amountWithZeroFeed = await getPerformPaymentAmount() assert.isTrue(normalAmount.lt(amountWithNegativeFeed)) assert.isTrue(normalAmount.lt(amountWithZeroFeed)) }) it('uses the fallback if the link price feed is stale', async () => { const normalAmount = await getPerformPaymentAmount() const roundId = 99 const answer = 100 const updatedAt = 946684800 // New Years 2000 🥳 const startedAt = 946684799 await linkEthFeed .connect(owner) .updateRoundData(roundId, answer, updatedAt, startedAt) const amountWithStaleFeed = await getPerformPaymentAmount() assert.isTrue(normalAmount.lt(amountWithStaleFeed)) }) it('uses the fallback link price if the feed price is non-sensical', async () => { const normalAmount = await getPerformPaymentAmount() const roundId = 99 const updatedAt = Math.floor(Date.now() / 1000) const startedAt = 946684799 await linkEthFeed .connect(owner) .updateRoundData(roundId, -100, updatedAt, startedAt) const amountWithNegativeFeed = await getPerformPaymentAmount() await linkEthFeed .connect(owner) .updateRoundData(roundId, 0, updatedAt, startedAt) const amountWithZeroFeed = await getPerformPaymentAmount() assert.isTrue(normalAmount.lt(amountWithNegativeFeed)) assert.isTrue(normalAmount.lt(amountWithZeroFeed)) }) it('reverts if the same caller calls twice in a row', async () => { await registry.connect(keeper1).performUpkeep(id, '0x') await evmRevert( registry.connect(keeper1).performUpkeep(id, '0x'), 'keepers must take turns', ) await registry.connect(keeper2).performUpkeep(id, '0x') await evmRevert( registry.connect(keeper2).performUpkeep(id, '0x'), 'keepers must take turns', ) await registry.connect(keeper1).performUpkeep(id, '0x') }) it('has a large enough gas overhead to cover upkeeps that use all their gas [ @skip-coverage ]', async () => { await mock.setPerformGasToBurn(executeGas) await mock.setCanPerform(true) const gas = executeGas.add(PERFORM_GAS_OVERHEAD) const performData = '0xc0ffeec0ffee' const tx = await registry .connect(keeper1) .performUpkeep(id, performData, { gasLimit: gas }) const receipt = await tx.wait() const eventLog = receipt?.events assert.equal(eventLog?.length, 2) assert.equal(eventLog?.[1].event, 'UpkeepPerformed') assert.equal(eventLog?.[1].args?.[0].toNumber(), id.toNumber()) assert.equal(eventLog?.[1].args?.[1], true) assert.equal(eventLog?.[1].args?.[2], await keeper1.getAddress()) assert.isNotEmpty(eventLog?.[1].args?.[3]) assert.equal(eventLog?.[1].args?.[4], performData) }) }) }) describe('#withdrawFunds', () => { beforeEach(async () => { await linkToken.connect(keeper1).approve(registry.address, toWei('100')) await registry.connect(keeper1).addFunds(id, toWei('1')) }) it('reverts if called by anyone but the admin', async () => { await evmRevert( registry .connect(owner) .withdrawFunds(id.add(1).toNumber(), await payee1.getAddress()), 'only callable by admin', ) }) it('reverts if called on an uncanceled upkeep', async () => { await evmRevert( registry.connect(admin).withdrawFunds(id, await payee1.getAddress()), 'upkeep must be canceled', ) }) it('reverts if called with the 0 address', async () => { await evmRevert( registry.connect(admin).withdrawFunds(id, zeroAddress), 'cannot send to zero address', ) }) describe('after the registration is cancelled', () => { beforeEach(async () => { await registry.connect(owner).cancelUpkeep(id) }) it('moves the funds out and updates the balance', async () => { const payee1Before = await linkToken.balanceOf( await payee1.getAddress(), ) const registryBefore = await linkToken.balanceOf(registry.address) let registration = await registry.getUpkeep(id) assert.isTrue(toWei('1').eq(registration.balance)) await registry .connect(admin) .withdrawFunds(id, await payee1.getAddress()) const payee1After = await linkToken.balanceOf(await payee1.getAddress()) const registryAfter = await linkToken.balanceOf(registry.address) assert.isTrue(payee1Before.add(toWei('1')).eq(payee1After)) assert.isTrue(registryBefore.sub(toWei('1')).eq(registryAfter)) registration = await registry.getUpkeep(id) assert.equal(0, registration.balance.toNumber()) }) }) }) describe('#cancelUpkeep', () => { it('reverts if the ID is not valid', async () => { await evmRevert( registry.connect(owner).cancelUpkeep(id.add(1).toNumber()), 'too late to cancel upkeep', ) }) it('reverts if called by a non-owner/non-admin', async () => { await evmRevert( registry.connect(keeper1).cancelUpkeep(id), 'only owner or admin', ) }) describe('when called by the owner', async () => { it('sets the registration to invalid immediately', async () => { const tx = await registry.connect(owner).cancelUpkeep(id) const receipt = await tx.wait() const registration = await registry.getUpkeep(id) assert.equal( registration.maxValidBlocknumber.toNumber(), receipt.blockNumber, ) }) it('emits an event', async () => { const tx = await registry.connect(owner).cancelUpkeep(id) const receipt = await tx.wait() await expect(tx) .to.emit(registry, 'UpkeepCanceled') .withArgs(id, BigNumber.from(receipt.blockNumber)) }) it('updates the canceled registrations list', async () => { let canceled = await registry.callStatic.getCanceledUpkeepList() assert.deepEqual([], canceled) await registry.connect(owner).cancelUpkeep(id) canceled = await registry.callStatic.getCanceledUpkeepList() assert.deepEqual([id], canceled) }) it('immediately prevents upkeep', async () => { await registry.connect(owner).cancelUpkeep(id) await evmRevert( registry.connect(keeper2).performUpkeep(id, '0x'), 'invalid upkeep id', ) }) it('does not revert if reverts if called multiple times', async () => { await registry.connect(owner).cancelUpkeep(id) await evmRevert( registry.connect(owner).cancelUpkeep(id), 'too late to cancel upkeep', ) }) describe('when called by the owner when the admin has just canceled', () => { let oldExpiration: BigNumber beforeEach(async () => { await registry.connect(admin).cancelUpkeep(id) const registration = await registry.getUpkeep(id) oldExpiration = registration.maxValidBlocknumber }) it('allows the owner to cancel it more quickly', async () => { await registry.connect(owner).cancelUpkeep(id) const registration = await registry.getUpkeep(id) const newExpiration = registration.maxValidBlocknumber assert.isTrue(newExpiration.lt(oldExpiration)) }) }) }) describe('when called by the admin', async () => { const delay = 50 it('sets the registration to invalid in 50 blocks', async () => { const tx = await registry.connect(admin).cancelUpkeep(id) const receipt = await tx.wait() const registration = await registry.getUpkeep(id) assert.equal( registration.maxValidBlocknumber.toNumber(), receipt.blockNumber + 50, ) }) it('emits an event', async () => { const tx = await registry.connect(admin).cancelUpkeep(id) const receipt = await tx.wait() await expect(tx) .to.emit(registry, 'UpkeepCanceled') .withArgs(id, BigNumber.from(receipt.blockNumber + delay)) }) it('updates the canceled registrations list', async () => { let canceled = await registry.callStatic.getCanceledUpkeepList() assert.deepEqual([], canceled) await registry.connect(admin).cancelUpkeep(id) canceled = await registry.callStatic.getCanceledUpkeepList() assert.deepEqual([id], canceled) }) it('immediately prevents upkeep', async () => { await linkToken.connect(owner).approve(registry.address, toWei('100')) await registry.connect(owner).addFunds(id, toWei('100')) await registry.connect(admin).cancelUpkeep(id) await registry.connect(keeper2).performUpkeep(id, '0x') // still works for (let i = 0; i < delay; i++) { await ethers.provider.send('evm_mine', []) } await evmRevert( registry.connect(keeper2).performUpkeep(id, '0x'), 'invalid upkeep id', ) }) it('reverts if called again by the admin', async () => { await registry.connect(admin).cancelUpkeep(id) await evmRevert( registry.connect(admin).cancelUpkeep(id), 'too late to cancel upkeep', ) }) it('does not revert or double add the cancellation record if called by the owner immediately after', async () => { await registry.connect(admin).cancelUpkeep(id) await registry.connect(owner).cancelUpkeep(id) const canceled = await registry.callStatic.getCanceledUpkeepList() assert.deepEqual([id], canceled) }) it('reverts if called by the owner after the timeout', async () => { await registry.connect(admin).cancelUpkeep(id) for (let i = 0; i < delay; i++) { await ethers.provider.send('evm_mine', []) } await evmRevert( registry.connect(owner).cancelUpkeep(id), 'too late to cancel upkeep', ) }) }) }) describe('#withdrawPayment', () => { beforeEach(async () => { await linkToken.connect(owner).approve(registry.address, toWei('100')) await registry.connect(owner).addFunds(id, toWei('100')) await registry.connect(keeper1).performUpkeep(id, '0x') }) it('reverts if called by anyone but the payee', async () => { await evmRevert( registry .connect(payee2) .withdrawPayment( await keeper1.getAddress(), await nonkeeper.getAddress(), ), 'only callable by payee', ) }) it('reverts if called with the 0 address', async () => { await evmRevert( registry .connect(payee2) .withdrawPayment(await keeper1.getAddress(), zeroAddress), 'cannot send to zero address', ) }) it('updates the balances', async () => { const to = await nonkeeper.getAddress() const keeperBefore = ( await registry.getKeeperInfo(await keeper1.getAddress()) ).balance const registrationBefore = (await registry.getUpkeep(id)).balance const toLinkBefore = await linkToken.balanceOf(to) const registryLinkBefore = await linkToken.balanceOf(registry.address) //// Do the thing await registry .connect(payee1) .withdrawPayment(await keeper1.getAddress(), to) const keeperAfter = ( await registry.getKeeperInfo(await keeper1.getAddress()) ).balance const registrationAfter = (await registry.getUpkeep(id)).balance const toLinkAfter = await linkToken.balanceOf(to) const registryLinkAfter = await linkToken.balanceOf(registry.address) assert.isTrue(keeperAfter.eq(BigNumber.from(0))) assert.isTrue(registrationBefore.eq(registrationAfter)) assert.isTrue(toLinkBefore.add(keeperBefore).eq(toLinkAfter)) assert.isTrue(registryLinkBefore.sub(keeperBefore).eq(registryLinkAfter)) }) it('emits a log announcing the withdrawal', async () => { const balance = (await registry.getKeeperInfo(await keeper1.getAddress())) .balance const tx = await registry .connect(payee1) .withdrawPayment( await keeper1.getAddress(), await nonkeeper.getAddress(), ) await expect(tx) .to.emit(registry, 'PaymentWithdrawn') .withArgs( await keeper1.getAddress(), balance, await nonkeeper.getAddress(), await payee1.getAddress(), ) }) }) describe('#transferPayeeship', () => { it('reverts when called by anyone but the current payee', async () => { await evmRevert( registry .connect(payee2) .transferPayeeship( await keeper1.getAddress(), await payee2.getAddress(), ), 'only callable by payee', ) }) it('reverts when transferring to self', async () => { await evmRevert( registry .connect(payee1) .transferPayeeship( await keeper1.getAddress(), await payee1.getAddress(), ), 'cannot transfer to self', ) }) it('does not change the payee', async () => { await registry .connect(payee1) .transferPayeeship( await keeper1.getAddress(), await payee2.getAddress(), ) const info = await registry.getKeeperInfo(await keeper1.getAddress()) assert.equal(await payee1.getAddress(), info.payee) }) it('emits an event announcing the new payee', async () => { const tx = await registry .connect(payee1) .transferPayeeship( await keeper1.getAddress(), await payee2.getAddress(), ) await expect(tx) .to.emit(registry, 'PayeeshipTransferRequested') .withArgs( await keeper1.getAddress(), await payee1.getAddress(), await payee2.getAddress(), ) }) it('does not emit an event when called with the same proposal', async () => { await registry .connect(payee1) .transferPayeeship( await keeper1.getAddress(), await payee2.getAddress(), ) const tx = await registry .connect(payee1) .transferPayeeship( await keeper1.getAddress(), await payee2.getAddress(), ) const receipt = await tx.wait() assert.equal(0, receipt.logs.length) }) }) describe('#acceptPayeeship', () => { beforeEach(async () => { await registry .connect(payee1) .transferPayeeship( await keeper1.getAddress(), await payee2.getAddress(), ) }) it('reverts when called by anyone but the proposed payee', async () => { await evmRevert( registry.connect(payee1).acceptPayeeship(await keeper1.getAddress()), 'only callable by proposed payee', ) }) it('emits an event announcing the new payee', async () => { const tx = await registry .connect(payee2) .acceptPayeeship(await keeper1.getAddress()) await expect(tx) .to.emit(registry, 'PayeeshipTransferred') .withArgs( await keeper1.getAddress(), await payee1.getAddress(), await payee2.getAddress(), ) }) it('does change the payee', async () => { await registry.connect(payee2).acceptPayeeship(await keeper1.getAddress()) const info = await registry.getKeeperInfo(await keeper1.getAddress()) assert.equal(await payee2.getAddress(), info.payee) }) }) describe('#setConfig', () => { const payment = BigNumber.from(1) const flatFee = BigNumber.from(2) const checks = BigNumber.from(3) const staleness = BigNumber.from(4) const ceiling = BigNumber.from(5) const maxGas = BigNumber.from(6) const fbGasEth = BigNumber.from(7) const fbLinkEth = BigNumber.from(8) it('reverts when called by anyone but the proposed owner', async () => { await evmRevert( registry .connect(payee1) .setConfig( payment, flatFee, checks, maxGas, staleness, gasCeilingMultiplier, fbGasEth, fbLinkEth, ), 'Only callable by owner', ) }) it('updates the config', async () => { const old = await registry.getConfig() const oldFlatFee = await registry.getFlatFee() assert.isTrue(paymentPremiumPPB.eq(old.paymentPremiumPPB)) assert.isTrue(flatFeeMicroLink.eq(oldFlatFee)) assert.isTrue(blockCountPerTurn.eq(old.blockCountPerTurn)) assert.isTrue(stalenessSeconds.eq(old.stalenessSeconds)) assert.isTrue(gasCeilingMultiplier.eq(old.gasCeilingMultiplier)) await registry .connect(owner) .setConfig( payment, flatFee, checks, maxGas, staleness, ceiling, fbGasEth, fbLinkEth, ) const updated = await registry.getConfig() const newFlatFee = await registry.getFlatFee() assert.equal(updated.paymentPremiumPPB, payment.toNumber()) assert.equal(newFlatFee, flatFee.toNumber()) assert.equal(updated.blockCountPerTurn, checks.toNumber()) assert.equal(updated.stalenessSeconds, staleness.toNumber()) assert.equal(updated.gasCeilingMultiplier, ceiling.toNumber()) assert.equal(updated.checkGasLimit, maxGas.toNumber()) assert.equal(updated.fallbackGasPrice.toNumber(), fbGasEth.toNumber()) assert.equal(updated.fallbackLinkPrice.toNumber(), fbLinkEth.toNumber()) }) it('emits an event', async () => { const tx = await registry .connect(owner) .setConfig( payment, flatFee, checks, maxGas, staleness, ceiling, fbGasEth, fbLinkEth, ) await expect(tx) .to.emit(registry, 'ConfigSet') .withArgs( payment, checks, maxGas, staleness, ceiling, fbGasEth, fbLinkEth, ) }) }) describe('#onTokenTransfer', () => { const amount = toWei('1') it('reverts if not called by the LINK token', async () => { const data = ethers.utils.defaultAbiCoder.encode( ['uint256'], [id.toNumber().toString()], ) await evmRevert( registry .connect(keeper1) .onTokenTransfer(await keeper1.getAddress(), amount, data), 'only callable through LINK', ) }) it('reverts if not called with more or less than 32 bytes', async () => { const longData = ethers.utils.defaultAbiCoder.encode( ['uint256', 'uint256'], ['33', '34'], ) const shortData = '0x12345678' await evmRevert( linkToken .connect(owner) .transferAndCall(registry.address, amount, longData), ) await evmRevert( linkToken .connect(owner) .transferAndCall(registry.address, amount, shortData), ) }) it('reverts if the upkeep is canceled', async () => { await registry.connect(admin).cancelUpkeep(id) await evmRevert( registry.connect(keeper1).addFunds(id, amount), 'upkeep must be active', ) }) it('updates the funds of the job id passed', async () => { const data = ethers.utils.defaultAbiCoder.encode( ['uint256'], [id.toNumber().toString()], ) const before = (await registry.getUpkeep(id)).balance await linkToken .connect(owner) .transferAndCall(registry.address, amount, data) const after = (await registry.getUpkeep(id)).balance assert.isTrue(before.add(amount).eq(after)) }) }) describe('#recoverFunds', () => { const sent = toWei('7') beforeEach(async () => { await linkToken.connect(keeper1).approve(registry.address, toWei('100')) // add funds to upkeep 1 and perform and withdraw some payment const tx = await registry .connect(owner) .registerUpkeep( mock.address, executeGas, await admin.getAddress(), emptyBytes, ) const id1 = await getUpkeepID(tx) await registry.connect(keeper1).addFunds(id1, toWei('5')) await registry.connect(keeper1).performUpkeep(id1, '0x') await registry.connect(keeper2).performUpkeep(id1, '0x') await registry.connect(keeper3).performUpkeep(id1, '0x') await registry .connect(payee1) .withdrawPayment( await keeper1.getAddress(), await nonkeeper.getAddress(), ) // transfer funds directly to the registry await linkToken.connect(keeper1).transfer(registry.address, sent) // add funds to upkeep 2 and perform and withdraw some payment const tx2 = await registry .connect(owner) .registerUpkeep( mock.address, executeGas, await admin.getAddress(), emptyBytes, ) const id2 = await getUpkeepID(tx2) await registry.connect(keeper1).addFunds(id2, toWei('5')) await registry.connect(keeper1).performUpkeep(id2, '0x') await registry.connect(keeper2).performUpkeep(id2, '0x') await registry.connect(keeper3).performUpkeep(id2, '0x') await registry .connect(payee2) .withdrawPayment( await keeper2.getAddress(), await nonkeeper.getAddress(), ) // transfer funds using onTokenTransfer const data = ethers.utils.defaultAbiCoder.encode( ['uint256'], [id2.toNumber().toString()], ) await linkToken .connect(owner) .transferAndCall(registry.address, toWei('1'), data) // remove a keeper await registry .connect(owner) .setKeepers( [await keeper1.getAddress(), await keeper2.getAddress()], [await payee1.getAddress(), await payee2.getAddress()], ) // withdraw some funds await registry.connect(owner).cancelUpkeep(id1) await registry.connect(admin).withdrawFunds(id1, await admin.getAddress()) }) it('reverts if not called by owner', async () => { await evmRevert( registry.connect(keeper1).recoverFunds(), 'Only callable by owner', ) }) it('allows any funds that have been accidentally transfered to be moved', async () => { const balanceBefore = await linkToken.balanceOf(registry.address) await linkToken.balanceOf(registry.address) await registry.connect(owner).recoverFunds() const balanceAfter = await linkToken.balanceOf(registry.address) assert.isTrue(balanceBefore.eq(balanceAfter.add(sent))) }) }) describe('#pause', () => { it('reverts if called by a non-owner', async () => { await evmRevert( registry.connect(keeper1).pause(), 'Only callable by owner', ) }) it('marks the contract as paused', async () => { assert.isFalse(await registry.paused()) await registry.connect(owner).pause() assert.isTrue(await registry.paused()) }) }) describe('#unpause', () => { beforeEach(async () => { await registry.connect(owner).pause() }) it('reverts if called by a non-owner', async () => { await evmRevert( registry.connect(keeper1).unpause(), 'Only callable by owner', ) }) it('marks the contract as not paused', async () => { assert.isTrue(await registry.paused()) await registry.connect(owner).unpause() assert.isFalse(await registry.paused()) }) }) describe('#getMaxPaymentForGas', () => { const gasAmounts = [100000, 10000000] const premiums = [0, 250000000] const flatFees = [0, 1000000] it('calculates the max fee approptiately', async () => { for (let idx = 0; idx < gasAmounts.length; idx++) { const gas = gasAmounts[idx] for (let jdx = 0; jdx < premiums.length; jdx++) { const premium = premiums[jdx] for (let kdx = 0; kdx < flatFees.length; kdx++) { const flatFee = flatFees[kdx] await registry .connect(owner) .setConfig( premium, flatFee, blockCountPerTurn, maxCheckGas, stalenessSeconds, gasCeilingMultiplier, fallbackGasPrice, fallbackLinkPrice, ) const price = await registry.getMaxPaymentForGas(gas) expect(price).to.equal(linkForGas(gas, premium, flatFee)) } } } }) }) describe('#checkUpkeep / #performUpkeep', () => { const performData = '0xc0ffeec0ffee' const multiplier = BigNumber.from(10) const flatFee = BigNumber.from('100000') //0.1 LINK const callGasPrice = 1 it('uses the same minimum balance calculation [ @skip-coverage ]', async () => { await registry .connect(owner) .setConfig( paymentPremiumPPB, flatFee, blockCountPerTurn, maxCheckGas, stalenessSeconds, multiplier, fallbackGasPrice, fallbackLinkPrice, ) await linkToken.connect(owner).approve(registry.address, toWei('100')) const tx1 = await registry .connect(owner) .registerUpkeep( mock.address, executeGas, await admin.getAddress(), emptyBytes, ) const upkeepID1 = await getUpkeepID(tx1) const tx2 = await registry .connect(owner) .registerUpkeep( mock.address, executeGas, await admin.getAddress(), emptyBytes, ) const upkeepID2 = await getUpkeepID(tx2) await mock.setCanCheck(true) await mock.setCanPerform(true) // upkeep 1 is underfunded, 2 is funded const minBalance1 = (await registry.getMaxPaymentForGas(executeGas)).sub( 1, ) const minBalance2 = await registry.getMaxPaymentForGas(executeGas) await registry.connect(owner).addFunds(upkeepID1, minBalance1) await registry.connect(owner).addFunds(upkeepID2, minBalance2) // upkeep 1 check should revert, 2 should succeed await evmRevert( registry .connect(zeroAddress) .callStatic.checkUpkeep(upkeepID1, await keeper1.getAddress(), { gasPrice: callGasPrice, }), ) await registry .connect(zeroAddress) .callStatic.checkUpkeep(upkeepID2, await keeper1.getAddress(), { gasPrice: callGasPrice, }) // upkeep 1 perform should revert, 2 should succeed await evmRevert( registry .connect(keeper1) .performUpkeep(upkeepID1, performData, { gasLimit: extraGas }), 'insufficient funds', ) await registry .connect(keeper1) .performUpkeep(upkeepID2, performData, { gasLimit: extraGas }) }) }) describe('#getMinBalanceForUpkeep / #checkUpkeep', () => { it('calculates the minimum balance appropriately', async () => { const oneWei = BigNumber.from('1') await linkToken.connect(keeper1).approve(registry.address, toWei('100')) await mock.setCanCheck(true) await mock.setCanPerform(true) const minBalance = await registry.getMinBalanceForUpkeep(id) const tooLow = minBalance.sub(oneWei) await registry.connect(keeper1).addFunds(id, tooLow) await evmRevert( registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()), 'insufficient funds', ) await registry.connect(keeper1).addFunds(id, oneWei) await registry .connect(zeroAddress) .callStatic.checkUpkeep(id, await keeper1.getAddress()) }) }) })
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/projectsMappers"; import * as Parameters from "../models/parameters"; import { VisualStudioResourceProviderClientContext } from "../visualStudioResourceProviderClientContext"; /** Class representing a Projects. */ export class Projects { private readonly client: VisualStudioResourceProviderClientContext; /** * Create a Projects. * @param {VisualStudioResourceProviderClientContext} client Reference to the service client. */ constructor(client: VisualStudioResourceProviderClientContext) { this.client = client; } /** * Gets all Visual Studio Team Services project resources created in the specified Team Services * account. * @summary Projects_ListByResourceGroup * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param [options] The optional parameters * @returns Promise<Models.ProjectsListByResourceGroupResponse> */ listByResourceGroup(resourceGroupName: string, rootResourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsListByResourceGroupResponse>; /** * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param callback The callback */ listByResourceGroup(resourceGroupName: string, rootResourceName: string, callback: msRest.ServiceCallback<Models.ProjectResourceListResult>): void; /** * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param options The optional parameters * @param callback The callback */ listByResourceGroup(resourceGroupName: string, rootResourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectResourceListResult>): void; listByResourceGroup(resourceGroupName: string, rootResourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectResourceListResult>, callback?: msRest.ServiceCallback<Models.ProjectResourceListResult>): Promise<Models.ProjectsListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, rootResourceName, options }, listByResourceGroupOperationSpec, callback) as Promise<Models.ProjectsListByResourceGroupResponse>; } /** * Creates a Team Services project in the collection with the specified name. * 'VersionControlOption' and 'ProcessTemplateId' must be specified in the resource properties. * Valid values for VersionControlOption: Git, Tfvc. Valid values for ProcessTemplateId: * 6B724908-EF14-45CF-84F8-768B5384DA45, ADCC42AB-9882-485E-A3ED-7678F01F66BC, * 27450541-8E31-4150-9947-DC59F998FC01 (these IDs correspond to Scrum, Agile, and CMMI process * templates). * @summary Projects_Create * @param body The request data. * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param [options] The optional parameters * @returns Promise<Models.ProjectsCreateResponse> */ create(body: Models.ProjectResource, resourceGroupName: string, rootResourceName: string, resourceName: string, options?: Models.ProjectsCreateOptionalParams): Promise<Models.ProjectsCreateResponse> { return this.beginCreate(body,resourceGroupName,rootResourceName,resourceName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.ProjectsCreateResponse>; } /** * Gets the details of a Team Services project resource. * @summary Projects_Get * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param [options] The optional parameters * @returns Promise<Models.ProjectsGetResponse> */ get(resourceGroupName: string, rootResourceName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsGetResponse>; /** * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param callback The callback */ get(resourceGroupName: string, rootResourceName: string, resourceName: string, callback: msRest.ServiceCallback<Models.ProjectResource>): void; /** * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, rootResourceName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectResource>): void; get(resourceGroupName: string, rootResourceName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectResource>, callback?: msRest.ServiceCallback<Models.ProjectResource>): Promise<Models.ProjectsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, rootResourceName, resourceName, options }, getOperationSpec, callback) as Promise<Models.ProjectsGetResponse>; } /** * Updates the tags of the specified Team Services project. * @summary Projects_Update * @param resourceGroupName Name of the resource group within the Azure subscription. * @param body The request data. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param [options] The optional parameters * @returns Promise<Models.ProjectsUpdateResponse> */ update(resourceGroupName: string, body: Models.ProjectResource, rootResourceName: string, resourceName: string, options?: msRest.RequestOptionsBase): Promise<Models.ProjectsUpdateResponse>; /** * @param resourceGroupName Name of the resource group within the Azure subscription. * @param body The request data. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param callback The callback */ update(resourceGroupName: string, body: Models.ProjectResource, rootResourceName: string, resourceName: string, callback: msRest.ServiceCallback<Models.ProjectResource>): void; /** * @param resourceGroupName Name of the resource group within the Azure subscription. * @param body The request data. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, body: Models.ProjectResource, rootResourceName: string, resourceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectResource>): void; update(resourceGroupName: string, body: Models.ProjectResource, rootResourceName: string, resourceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectResource>, callback?: msRest.ServiceCallback<Models.ProjectResource>): Promise<Models.ProjectsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, body, rootResourceName, resourceName, options }, updateOperationSpec, callback) as Promise<Models.ProjectsUpdateResponse>; } /** * Gets the status of the project resource creation job. * @summary Projects_GetJobStatus * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param subContainerName This parameter should be set to the resourceName. * @param operation The operation type. The only supported value is 'put'. * @param [options] The optional parameters * @returns Promise<Models.ProjectsGetJobStatusResponse> */ getJobStatus(resourceGroupName: string, rootResourceName: string, resourceName: string, subContainerName: string, operation: string, options?: Models.ProjectsGetJobStatusOptionalParams): Promise<Models.ProjectsGetJobStatusResponse>; /** * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param subContainerName This parameter should be set to the resourceName. * @param operation The operation type. The only supported value is 'put'. * @param callback The callback */ getJobStatus(resourceGroupName: string, rootResourceName: string, resourceName: string, subContainerName: string, operation: string, callback: msRest.ServiceCallback<Models.ProjectResource>): void; /** * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param subContainerName This parameter should be set to the resourceName. * @param operation The operation type. The only supported value is 'put'. * @param options The optional parameters * @param callback The callback */ getJobStatus(resourceGroupName: string, rootResourceName: string, resourceName: string, subContainerName: string, operation: string, options: Models.ProjectsGetJobStatusOptionalParams, callback: msRest.ServiceCallback<Models.ProjectResource>): void; getJobStatus(resourceGroupName: string, rootResourceName: string, resourceName: string, subContainerName: string, operation: string, options?: Models.ProjectsGetJobStatusOptionalParams | msRest.ServiceCallback<Models.ProjectResource>, callback?: msRest.ServiceCallback<Models.ProjectResource>): Promise<Models.ProjectsGetJobStatusResponse> { return this.client.sendOperationRequest( { resourceGroupName, rootResourceName, resourceName, subContainerName, operation, options }, getJobStatusOperationSpec, callback) as Promise<Models.ProjectsGetJobStatusResponse>; } /** * Creates a Team Services project in the collection with the specified name. * 'VersionControlOption' and 'ProcessTemplateId' must be specified in the resource properties. * Valid values for VersionControlOption: Git, Tfvc. Valid values for ProcessTemplateId: * 6B724908-EF14-45CF-84F8-768B5384DA45, ADCC42AB-9882-485E-A3ED-7678F01F66BC, * 27450541-8E31-4150-9947-DC59F998FC01 (these IDs correspond to Scrum, Agile, and CMMI process * templates). * @summary Projects_Create * @param body The request data. * @param resourceGroupName Name of the resource group within the Azure subscription. * @param rootResourceName Name of the Team Services account. * @param resourceName Name of the Team Services project. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreate(body: Models.ProjectResource, resourceGroupName: string, rootResourceName: string, resourceName: string, options?: Models.ProjectsBeginCreateOptionalParams): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { body, resourceGroupName, rootResourceName, resourceName, options }, beginCreateOperationSpec, options); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.visualstudio/account/{rootResourceName}/project", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.rootResourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProjectResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.visualstudio/account/{rootResourceName}/project/{resourceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.rootResourceName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProjectResource }, 404: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.visualstudio/account/{rootResourceName}/project/{resourceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.rootResourceName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "body", mapper: { ...Mappers.ProjectResource, required: true } }, responses: { 200: { bodyMapper: Mappers.ProjectResource }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getJobStatusOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.visualstudio/account/{rootResourceName}/project/{resourceName}/subContainers/{subContainerName}/status", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.rootResourceName, Parameters.resourceName, Parameters.subContainerName ], queryParameters: [ Parameters.apiVersion, Parameters.operation, Parameters.jobId ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProjectResource }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.visualstudio/account/{rootResourceName}/project/{resourceName}", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.rootResourceName, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion, Parameters.validating ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "body", mapper: { ...Mappers.ProjectResource, required: true } }, responses: { 200: { bodyMapper: Mappers.ProjectResource }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import BitMatrix from '../../common/BitMatrix'; import ErrorCorrectionLevel from './ErrorCorrectionLevel'; import FormatInformation from './FormatInformation'; import ECBlocks from './ECBlocks'; import ECB from './ECB'; import FormatException from '../../FormatException'; import IllegalArgumentException from '../../IllegalArgumentException'; /** * See ISO 18004:2006 Annex D * * @author Sean Owen */ export default class Version { /** * See ISO 18004:2006 Annex D. * Element i represents the raw version bits that specify version i + 7 */ private static VERSION_DECODE_INFO = Int32Array.from([ 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6, 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78, 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683, 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB, 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250, 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B, 0x2542E, 0x26A64, 0x27541, 0x28C69]); /** * See ISO 18004:2006 6.5.1 Table 9 */ private static VERSIONS: Version[] = [ new Version(1, new Int32Array(0), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))), new Version(2, Int32Array.from([6, 18]), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))), new Version(3, Int32Array.from([6, 22]), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))), new Version(4, Int32Array.from([6, 26]), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))), new Version(5, Int32Array.from([6, 30]), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))), new Version(6, Int32Array.from([6, 34]), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))), new Version(7, Int32Array.from([6, 22, 38]), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))), new Version(8, Int32Array.from([6, 24, 42]), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))), new Version(9, Int32Array.from([6, 26, 46]), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))), new Version(10, Int32Array.from([6, 28, 50]), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))), new Version(11, Int32Array.from([6, 30, 54]), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))), new Version(12, Int32Array.from([6, 32, 58]), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))), new Version(13, Int32Array.from([6, 34, 62]), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))), new Version(14, Int32Array.from([6, 26, 46, 66]), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))), new Version(15, Int32Array.from([6, 26, 48, 70]), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))), new Version(16, Int32Array.from([6, 26, 50, 74]), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))), new Version(17, Int32Array.from([6, 30, 54, 78]), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))), new Version(18, Int32Array.from([6, 30, 56, 82]), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))), new Version(19, Int32Array.from([6, 30, 58, 86]), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))), new Version(20, Int32Array.from([6, 34, 62, 90]), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))), new Version(21, Int32Array.from([6, 28, 50, 72, 94]), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))), new Version(22, Int32Array.from([6, 26, 50, 74, 98]), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))), new Version(23, Int32Array.from([6, 30, 54, 78, 102]), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))), new Version(24, Int32Array.from([6, 28, 54, 80, 106]), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))), new Version(25, Int32Array.from([6, 32, 58, 84, 110]), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))), new Version(26, Int32Array.from([6, 30, 58, 86, 114]), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))), new Version(27, Int32Array.from([6, 34, 62, 90, 118]), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))), new Version(28, Int32Array.from([6, 26, 50, 74, 98, 122]), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))), new Version(29, Int32Array.from([6, 30, 54, 78, 102, 126]), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))), new Version(30, Int32Array.from([6, 26, 52, 78, 104, 130]), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))), new Version(31, Int32Array.from([6, 30, 56, 82, 108, 134]), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))), new Version(32, Int32Array.from([6, 34, 60, 86, 112, 138]), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))), new Version(33, Int32Array.from([6, 30, 58, 86, 114, 142]), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))), new Version(34, Int32Array.from([6, 34, 62, 90, 118, 146]), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))), new Version(35, Int32Array.from([6, 30, 54, 78, 102, 126, 150]), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))), new Version(36, Int32Array.from([6, 24, 50, 76, 102, 128, 154]), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))), new Version(37, Int32Array.from([6, 28, 54, 80, 106, 132, 158]), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))), new Version(38, Int32Array.from([6, 32, 58, 84, 110, 136, 162]), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))), new Version(39, Int32Array.from([6, 26, 54, 82, 110, 138, 166]), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))), new Version(40, Int32Array.from([6, 30, 58, 86, 114, 142, 170]), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16))) ]; private ecBlocks: ECBlocks[]; private totalCodewords: number; /*int*/ private constructor(private versionNumber: number /*int*/, private alignmentPatternCenters: Int32Array, ...ecBlocks: ECBlocks[]) { this.ecBlocks = ecBlocks; let total = 0; const ecCodewords = ecBlocks[0].getECCodewordsPerBlock(); const ecbArray: ECB[] = ecBlocks[0].getECBlocks(); for (const ecBlock of ecbArray) { total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords); } this.totalCodewords = total; } public getVersionNumber(): number /*int*/ { return this.versionNumber; } public getAlignmentPatternCenters(): Int32Array { return this.alignmentPatternCenters; } public getTotalCodewords(): number /*int*/ { return this.totalCodewords; } public getDimensionForVersion(): number /*int*/ { return 17 + 4 * this.versionNumber; } public getECBlocksForLevel(ecLevel: ErrorCorrectionLevel): ECBlocks { return this.ecBlocks[ecLevel.getValue()]; // TYPESCRIPTPORT: original was using ordinal, and using the order of levels as defined in ErrorCorrectionLevel enum (LMQH) // I will use the direct value from ErrorCorrectionLevelValues enum which in typescript goes to a number } /** * <p>Deduces version information purely from QR Code dimensions.</p> * * @param dimension dimension in modules * @return Version for a QR Code of that dimension * @throws FormatException if dimension is not 1 mod 4 */ public static getProvisionalVersionForDimension(dimension: number /*int*/): Version /*throws FormatException */ { if (dimension % 4 !== 1) { throw new FormatException(); } try { return this.getVersionForNumber((dimension - 17) / 4); } catch (ignored/*: IllegalArgumentException*/) { throw new FormatException(); } } public static getVersionForNumber(versionNumber: number /*int*/): Version { if (versionNumber < 1 || versionNumber > 40) { throw new IllegalArgumentException(); } return Version.VERSIONS[versionNumber - 1]; } public static decodeVersionInformation(versionBits: number /*int*/): Version { let bestDifference = Number.MAX_SAFE_INTEGER; let bestVersion = 0; for (let i = 0; i < Version.VERSION_DECODE_INFO.length; i++) { const targetVersion = Version.VERSION_DECODE_INFO[i]; // Do the version info bits match exactly? done. if (targetVersion === versionBits) { return Version.getVersionForNumber(i + 7); } // Otherwise see if this is the closest to a real version info bit string // we have seen so far const bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion); if (bitsDifference < bestDifference) { bestVersion = i + 7; bestDifference = bitsDifference; } } // We can tolerate up to 3 bits of error since no two version info codewords will // differ in less than 8 bits. if (bestDifference <= 3) { return Version.getVersionForNumber(bestVersion); } // If we didn't find a close enough match, fail return null; } /** * See ISO 18004:2006 Annex E */ public buildFunctionPattern(): BitMatrix { const dimension = this.getDimensionForVersion(); const bitMatrix = new BitMatrix(dimension); // Top left finder pattern + separator + format bitMatrix.setRegion(0, 0, 9, 9); // Top right finder pattern + separator + format bitMatrix.setRegion(dimension - 8, 0, 8, 9); // Bottom left finder pattern + separator + format bitMatrix.setRegion(0, dimension - 8, 9, 8); // Alignment patterns const max = this.alignmentPatternCenters.length; for (let x = 0; x < max; x++) { const i = this.alignmentPatternCenters[x] - 2; for (let y = 0; y < max; y++) { if ((x === 0 && (y === 0 || y === max - 1)) || (x === max - 1 && y === 0)) { // No alignment patterns near the three finder patterns continue; } bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5); } } // Vertical timing pattern bitMatrix.setRegion(6, 9, 1, dimension - 17); // Horizontal timing pattern bitMatrix.setRegion(9, 6, dimension - 17, 1); if (this.versionNumber > 6) { // Version info, top right bitMatrix.setRegion(dimension - 11, 0, 3, 6); // Version info, bottom left bitMatrix.setRegion(0, dimension - 11, 6, 3); } return bitMatrix; } /*@Override*/ public toString(): string { return '' + this.versionNumber; } }
the_stack
import axios, { AxiosRequestConfig, Method } from "axios"; import sha256 from "crypto-js/sha256"; import Hex from "crypto-js/enc-hex"; import lightningPayReq from "bolt11"; import HashKeySigner from "~/common/utils/signer"; import Connector, { SendPaymentArgs, SendPaymentResponse, CheckPaymentArgs, CheckPaymentResponse, GetInfoResponse, GetBalanceResponse, MakeInvoiceArgs, MakeInvoiceResponse, SignMessageArgs, SignMessageResponse, VerifyMessageArgs, VerifyMessageResponse, KeysendArgs, } from "./connector.interface"; import state from "../state"; import utils from "~/common/lib/utils"; interface Config { login: string; password: string; url: string; } export default class LndHub implements Connector { config: Config; access_token?: string; access_token_created?: number; refresh_token?: string; refresh_token_created?: number; noRetry?: boolean; constructor(config: Config) { this.config = config; } async init() { return this.authorize(); } unload() { return Promise.resolve(); } async getInfo(): Promise<GetInfoResponse> { const data = await this.request<{ alias: string }>( "GET", "/getinfo", undefined, {} ); return { data: { alias: data.alias, }, }; } async getBalance(): Promise<GetBalanceResponse> { const data = await this.request<{ BTC: { AvailableBalance: number } }>( "GET", "/balance", undefined, {} ); return { data: { balance: data.BTC.AvailableBalance, }, }; } async sendPayment(args: SendPaymentArgs): Promise<SendPaymentResponse> { const data = await this.request<{ error?: string; message: string; payment_error?: string; payment_hash: | { type: string; data: ArrayBuffer; } | string; payment_preimage: | { type: string; data: ArrayBuffer; } | string; payment_route?: { total_amt: number; total_fees: number }; }>("POST", "/payinvoice", { invoice: args.paymentRequest, }); if (data.error) { throw new Error(data.message); } if (data.payment_error) { throw new Error(data.payment_error); } if ( typeof data.payment_hash === "object" && data.payment_hash.type === "Buffer" ) { data.payment_hash = Buffer.from(data.payment_hash.data).toString("hex"); } if ( typeof data.payment_preimage === "object" && data.payment_preimage.type === "Buffer" ) { data.payment_preimage = Buffer.from(data.payment_preimage.data).toString( "hex" ); } // HACK! // some Lnbits extension that implement the LNDHub API do not return the route information. // to somewhat work around this we set a payment route and use the amount from the payment request. // lnbits needs to fix this and return proper route information with a total amount and fees if (!data.payment_route) { const paymentRequestDetails = lightningPayReq.decode(args.paymentRequest); const amountInSats = paymentRequestDetails.satoshis || 0; data.payment_route = { total_amt: amountInSats, total_fees: 0 }; } return { data: { preimage: data.payment_preimage as string, paymentHash: data.payment_hash as string, route: data.payment_route, }, }; } async keysend(args: KeysendArgs): Promise<SendPaymentResponse> { const data = await this.request<{ error: string; message: string; payment_error?: string; payment_hash: | { type: string; data: ArrayBuffer; } | string; payment_preimage: | { type: string; data: ArrayBuffer; } | string; payment_route: { total_amt: number; total_fees: number }; }>("POST", "/keysend", { destination: args.pubkey, amount: args.amount, customRecords: args.customRecords, }); if (data.error) { throw new Error(data.message); } if (data.payment_error) { throw new Error(data.payment_error); } if ( typeof data.payment_hash === "object" && data.payment_hash.type === "Buffer" ) { data.payment_hash = Buffer.from(data.payment_hash.data).toString("hex"); } if ( typeof data.payment_preimage === "object" && data.payment_preimage.type === "Buffer" ) { data.payment_preimage = Buffer.from(data.payment_preimage.data).toString( "hex" ); } return { data: { preimage: data.payment_preimage as string, paymentHash: data.payment_hash as string, route: data.payment_route, }, }; } async checkPayment(args: CheckPaymentArgs): Promise<CheckPaymentResponse> { const data = await this.request<{ paid: boolean }>( "GET", `/checkpayment/${args.paymentHash}`, undefined, {} ); return { data: { paid: data.paid, }, }; } signMessage(args: SignMessageArgs): Promise<SignMessageResponse> { // make sure we got the config to create a new key if (!this.config.url || !this.config.login || !this.config.password) { return Promise.reject(new Error("Missing config")); } if (!args.message) { return Promise.reject(new Error("Invalid message")); } let message: string | Uint8Array; message = sha256(args.message).toString(Hex); let keyHex = sha256( `lndhub://${this.config.login}:${this.config.password}` ).toString(Hex); const { settings } = state.getState(); if (settings.legacyLnurlAuth) { message = utils.stringToUint8Array(args.message); keyHex = sha256( `LBE-LNDHUB-${this.config.url}-${this.config.login}-${this.config.password}` ).toString(Hex); } if (!keyHex) { return Promise.reject(new Error("Could not create key")); } const signer = new HashKeySigner(keyHex); const signedMessageDERHex = signer.sign(message).toDER("hex"); // make sure we got some signed message if (!signedMessageDERHex) { return Promise.reject(new Error("Signing failed")); } return Promise.resolve({ data: { signature: signedMessageDERHex, }, }); } verifyMessage(args: VerifyMessageArgs): Promise<VerifyMessageResponse> { // create a signing key from the lndhub URL and the login/password combination let keyHex = sha256( `lndhub://${this.config.login}:${this.config.password}` ).toString(Hex); const { settings } = state.getState(); if (settings.legacyLnurlAuth) { keyHex = sha256( `LBE-LNDHUB-${this.config.url}-${this.config.login}-${this.config.password}` ).toString(Hex); } if (!keyHex) { return Promise.reject(new Error("Could not create key")); } const signer = new HashKeySigner(keyHex); return Promise.resolve({ data: { valid: signer.verify(args.message, args.signature), }, }); } async makeInvoice(args: MakeInvoiceArgs): Promise<MakeInvoiceResponse> { const data = await this.request<{ payment_request: string; r_hash: { type: string; data: ArrayBuffer } | string; }>("POST", "/addinvoice", { amt: args.amount, memo: args.memo, }); if (typeof data.r_hash === "object" && data.r_hash.type === "Buffer") { data.r_hash = Buffer.from(data.r_hash.data).toString("hex"); } return { data: { paymentRequest: data.payment_request, rHash: data.r_hash as string, }, }; } async authorize() { const headers = new Headers(); headers.append("Accept", "application/json"); headers.append("Access-Control-Allow-Origin", "*"); headers.append("Content-Type", "application/json"); return fetch(this.config.url + "/auth?type=auth", { method: "POST", headers: headers, body: JSON.stringify({ login: this.config.login, password: this.config.password, }), }) .then((response) => { if (response.ok) { return response.json(); } else { throw new Error("API error: " + response.status); } }) .then((json) => { if (json && json.error) { throw new Error( "API error: " + json.message + " (code " + json.code + ")" ); } if (!json.access_token || !json.refresh_token) { throw new Error("API unexpected response: " + JSON.stringify(json)); } this.refresh_token = json.refresh_token; this.access_token = json.access_token; this.refresh_token_created = +new Date(); this.access_token_created = +new Date(); return json; }); } async request<Type>( method: Method, path: string, args?: Record<string, unknown>, defaultValues?: Record<string, unknown> ): Promise<Type> { if (!this.access_token) { await this.authorize(); } const reqConfig: AxiosRequestConfig = { method, url: this.config.url + path, responseType: "json", headers: { Accept: "application/json", "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", Authorization: `Bearer ${this.access_token}`, }, }; if (method === "POST") { reqConfig.data = args; } else if (args !== undefined) { reqConfig.params = args; } let data; try { const res = await axios(reqConfig); data = res.data; } catch (e) { console.log(e); if (e instanceof Error) throw new Error(e.message); } if (data && data.error) { if (data.code * 1 === 1 && !this.noRetry) { try { await this.authorize(); } catch (e) { console.log(e); if (e instanceof Error) throw new Error(e.message); } this.noRetry = true; return this.request(method, path, args, defaultValues); } else { throw new Error(data.message); } } if (defaultValues) { data = Object.assign(Object.assign({}, defaultValues), data); } return data; } }
the_stack
import '@testing-library/jest-dom'; import React from 'react'; import { render, queryByAttribute, queryAllByAttribute, fireEvent } from '@testing-library/react'; import type { MemoryHistory} from '@umijs/runtime'; import { createMemoryHistory, Router } from '@umijs/runtime'; import { context as Context } from 'dumi/theme'; import SourceCode from '../builtins/SourceCode'; import Alert from '../builtins/Alert'; import Badge from '../builtins/Badge'; import Tree from '../builtins/Tree'; import Previewer from '../builtins/Previewer'; import API from '../builtins/API'; import Layout from '../layout'; let history: MemoryHistory; // mock history location which import from 'dumi' jest.mock('dumi', () => ({ history: { location: { pathname: '/' } }, })); describe('default theme', () => { history = createMemoryHistory({ initialEntries: ['/', '/en-US'], initialIndex: 0 }); const baseCtx = { title: 'test', locale: 'zh-CN', routes: [ { path: '/', title: '首页', meta: {}, }, { path: '/en-US', title: 'Home', meta: {}, }, ], config: { locales: [ { name: 'zh-CN', label: '中文' }, { name: 'en-US', label: 'English' }, ], menus: {}, navs: {}, title: 'test', logo: '/', mode: 'site' as 'doc' | 'site', repository: { branch: 'master' }, }, meta: {}, menu: [ { title: '分组', children: [ { title: 'English', path: '/en', }, ], }, ], nav: [ { path: '/', title: '首页', children: [], }, { title: '生态', children: [ { path: 'https://d.umijs.org', title: 'GitHub', children: [], }, ], }, ], base: '/', apis: { MultipleExports: { Other: [ { identifier: 'other', type: 'string', }, ], }, } }; const baseProps = { history, location: { ...history.location, query: {} }, match: { params: {}, isExact: true, path: '/', url: '/' }, route: { path: '/', routes: baseCtx.routes }, }; it('should render site home page', () => { const attrName = 'data-prefers-color'; document.documentElement.setAttribute(attrName, 'light'); localStorage.setItem('dumi:prefers-color', 'light'); const wrapper = ({ children }) => ( <Context.Provider value={{ ...baseCtx, meta: { title: 'test', hero: { title: 'Hero', desc: 'Hero Description', actions: [{ text: '开始', link: '/' }], }, features: [ { title: 'Feat', desc: 'Feature' }, { title: 'Feat2', link: '/' }, ], }, }} > {children} </Context.Provider> ); const { container, getAllByText, getByText } = render( <Router history={history}> <Layout {...baseProps}> <h1>Home Page</h1> </Layout> </Router>, { wrapper }, ); // expect navbar be rendered expect(getAllByText('首页')).not.toBeNull(); // expect content be rendered expect(getByText('Home Page')).not.toBeNull(); // expect hero be rendered expect(getByText('Hero')).not.toBeNull(); // expect features be rendered expect(getByText('Feature')).not.toBeNull(); expect(getByText('Feat2')).not.toBeNull(); // trigger mobile menu display queryByAttribute('class', container, '__dumi-default-navbar-toggle').click(); // expect sidemenu display for mobile expect(queryByAttribute('data-mobile-show', container, 'true')).not.toBeNull(); // expect dark render and click success const menu = queryByAttribute('class', container, '__dumi-default-menu'); const sunMenu = queryByAttribute('class', menu, '__dumi-default-dark-sun __dumi-default-dark-switch-active'); expect(sunMenu).not.toBeNull(); const moonMenu = queryByAttribute('class', container, '__dumi-default-dark-moon'); expect(moonMenu).not.toBeNull(); moonMenu.click(); expect(document.documentElement.getAttribute(attrName)).toEqual('dark'); expect(queryByAttribute('data-mobile-show', container, 'true')).toBeNull(); const navbar = queryByAttribute('class', container, '__dumi-default-navbar'); const moonNav = queryByAttribute('class', navbar, '__dumi-default-dark-moon __dumi-default-dark-switch-active'); moonNav.click(); expect(queryByAttribute('class', navbar, '__dumi-default-dark-switch __dumi-default-dark-switch-open')).not.toBeNull(); const switchList = queryByAttribute('class', navbar, '__dumi-default-dark-switch-list'); expect(switchList).not.toBeNull(); queryByAttribute('class', switchList, '__dumi-default-dark-sun').click(); expect(document.documentElement.getAttribute(attrName)).toEqual('light'); expect(queryByAttribute('class', navbar, '__dumi-default-dark-switch-list')).toBeNull(); expect(queryByAttribute('class', navbar, '__dumi-default-dark-switch __dumi-default-dark-switch-open')).toBeNull(); }); it('should render documentation page', async () => { const updatedTime = 1604026996000; const wrapper = ({ children }) => ( <Context.Provider value={{ ...baseCtx, meta: { title: 'test', slugs: [{ value: 'Slug A', heading: 'a', depth: 2 }], updatedTime, filePath: 'temp', }, }} > {children} </Context.Provider> ); const { getByText, getAllByText } = render( <Router history={history}> <Layout {...baseProps}> <h1>Doc</h1> </Layout> </Router>, { wrapper }, ); // expect slugs be rendered expect(getByText('Slug A')).not.toBeNull(); // expect footer date show expect(new Date(updatedTime).toLocaleString([], { hour12: false })).not.toBeNull(); // trigger locale change getAllByText('English')[0].click(); // expect location change expect(history.location.pathname).toEqual(baseCtx.routes[1].path); }); it('should render builtin components correctly', () => { const code = "console.log('Hello World!')"; const wrapper = ({ children }) => ( <Context.Provider value={{ ...baseCtx, meta: { title: 'test', slugs: [{ value: 'Slug A', heading: 'a', depth: 2 }], }, }} > {children} </Context.Provider> ); const { getByText, getByTitle, getAllByTitle, container } = render( <Router history={history}> <Layout {...baseProps}> <> <a href="" id="btn"> click </a> <SourceCode code={code} lang="javascript" /> <Alert type="info">Alert</Alert> <Badge type="info">Badge</Badge> <Tree> <ul> <li> 1 <small>test1</small> <ul> <li> 1-1 <small>test1-1</small> </li> </ul> </li> </ul> </Tree> <Previewer title="demo-1" identifier="demo-1" sources={{ _: { jsx: "export default () => 'JavaScript'", tsx: "export default () => 'TypeScript'", }, }} dependencies={{}} > <>demo-1 Content</> </Previewer> <Previewer title="demo-2" identifier="demo-2" sources={{ _: { jsx: "export default () => 'Main'", }, 'Other.jsx': { import: './Other.jsx', content: "export default () => 'Other'", }, }} dependencies={{}} > <>demo-2 Content</> </Previewer> <Previewer title="demo-3" identifier="demo-3" sources={{ _: { jsx: "export default () => 'Main'", }, 'Other.jsx': { import: './Other.jsx', content: "export default () => 'Other'", }, }} dependencies={{}} iframe={100} > <>demo-3 Content</> </Previewer> <API identifier="MultipleExports" export="Other" /> </> </Layout> </Router>, { wrapper }, ); // toggle side menu display fireEvent( container.querySelector('.__dumi-default-navbar-toggle'), new MouseEvent('click', { bubbles: true, cancelable: true, }), ); fireEvent( container.querySelector('#btn'), new MouseEvent('click', { bubbles: true, cancelable: true, }), ); // test tree render expect(queryAllByAttribute('class', container, '__dumi-site-tree-icon icon-minus-square').length).toBe(2); expect(queryAllByAttribute('class', container, '__dumi-site-tree-icon icon-folder-open').length).toBe(2); expect(queryAllByAttribute('class', container, '__dumi-site-tree-icon icon-file').length).toBe(1); expect(getByText('<root>')).toHaveClass('rc-tree-title'); expect(getByText('1')).toHaveClass('rc-tree-title'); expect(getByText('test1')).not.toBeNull(); getAllByTitle('<root>')[0].click(); expect(queryAllByAttribute('class', container, '__dumi-site-tree-icon icon-plus-square').length).toBe(1); expect(queryAllByAttribute('class', container, '__dumi-site-tree-icon icon-folder').length).toBe(1); // expect SourceCode highlight expect(getByText('console')).toHaveClass('token'); // expect Alert be rendered expect(getByText('Alert')).toHaveAttribute('type', 'info'); // expect Badge be rendered expect(getByText('Badge')).toHaveClass('__dumi-default-badge'); // expect Previewer be rendered expect(getByText('demo-1')).not.toBeNull(); // trigger source code display for demo-1 getAllByTitle('Toggle source code panel')[0].click(); // expect show TypeScript code default expect(getByText("'TypeScript'")).not.toBeNull(); // trigger source code display for demo-2 getAllByTitle('Toggle source code panel')[1].click(); // expect show code of main file expect(getByText("'Main'")).not.toBeNull(); // trigger file change getByText('Other.jsx').click(); // expect show code of main file expect(getByText("'Other'")).not.toBeNull(); // expect render iframe demo (container.querySelector('[data-iframe] button[role=refresh]') as HTMLElement).click(); expect(container.querySelector('[data-iframe]').innerHTML).not.toContain('demo-3 Content'); expect(container.querySelector('[data-iframe] iframe')).not.toBeNull(); expect((container.querySelector('[data-iframe] iframe') as HTMLElement).style.height).toEqual( '100px', ); // expect render API property expect(getByText('other', { selector: 'table td' })).not.toBeNull(); }); });
the_stack
import { Lang, NonEnLang } from '../../resources/languages'; // It's awkward to refer to these string keys, so name them as replaceSync[keys.sealKey]. export const syncKeys = { // Match Regexes, NetRegexes, and timeline constructions of seal log lines. // FIXME: This seal regex includes an optional second colon, as "0839::?"". // Once we have completely converted things for 6.0, // we should come back here and make the doubled colon non-optional. seal: '(?<=00:0839::?|00\\|[^|]*\\|0839\\|\\|)(.*) will be sealed off(?: in (?:[0-9]+ seconds)?)?', unseal: 'is no longer sealed', engage: 'Engage!', }; const textKeys = { // Match directions in replaceText // eg: `(N)`, `(SW)`, `(NE/NW)`, etc. E: '(?<= \\(|\\/)E(?=\\)|\\/)', N: '(?<= \\(|\\/)N(?=\\)|\\/)', S: '(?<= \\(|\\/)S(?=\\)|\\/)', W: '(?<= \\(|\\/)W(?=\\)|\\/)', NE: '(?<= \\(|\\/)NE(?=\\)|\\/)', NW: '(?<= \\(|\\/)NW(?=\\)|\\/)', SE: '(?<= \\(|\\/)SE(?=\\)|\\/)', SW: '(?<= \\(|\\/)SW(?=\\)|\\/)', // Match Roles in replaceText // eg: `(Tank)`, `(Healer)`, `(DPS)`, etc Tank: '(?<= \\(|\\/)Tanks?(?=\\)|\\/)', Healer: '(?<= \\(|\\/)Healers?(?=\\)|\\/)', DPS: '(?<= \\(|\\/)DPS(?=\\)|\\/)', // Match `--1--` style text. Number: '--(\\s*\\d+\\s*)--', }; export type CommonReplacement = { replaceSync: { [replaceKey: string]: { [key in Lang]?: string }; }; replaceText: { [replaceKey: string]: & { [key in NonEnLang]?: string; } & { // don't set this key, but allow us to ask if it exists en?: never; }; }; }; export const commonReplacement: CommonReplacement = { replaceSync: { [syncKeys.seal]: { en: '$1 will be sealed off', de: 'Noch 15 Sekunden, bis sich (?:(?:der|die|das) )?(?:Zugang zu(?:[rm]| den)? )?$1 schließt', fr: 'Fermeture d(?:e|u|es) $1 dans', ja: '$1の封鎖まであと', cn: '距$1被封锁还有', ko: '15초 후에 $1(?:이|가) 봉쇄됩니다', }, [syncKeys.unseal]: { en: 'is no longer sealed', de: 'öffnet sich (?:wieder|erneut)', fr: 'Ouverture ', ja: 'の封鎖が解かれた', cn: '的封锁解除了', ko: '의 봉쇄가 해제되었습니다', }, [syncKeys.engage]: { en: 'Engage!', de: 'Start!', fr: 'À l\'attaque', ja: '戦闘開始!', cn: '战斗开始!', ko: '전투 시작!', }, }, replaceText: { '--adds spawn--': { de: '--Adds erscheinen--', fr: '--Apparition d\'adds--', ja: '--雑魚出現--', cn: '--小怪出现--', ko: '--쫄 소환--', }, '--adds targetable--': { de: '--Adds anvisierbar--', fr: '--Adds ciblables--', ja: '--雑魚ターゲット可能--', cn: '--小怪可选中--', ko: '--쫄 타겟 가능--', }, '--center--': { de: '--Mitte--', fr: '--Centre--', ja: '--センター--', cn: '--中央--', ko: '--중앙--', }, '\\(center\\)': { de: '(Mitte)', fr: '(Centre)', ja: '(センター)', cn: '(中央)', ko: '(중앙)', }, '--clones appear--': { de: '--Klone erscheinen--', fr: '--Apparition des clones--', ja: '--幻影出現--', cn: '--幻影出现--', ko: '--분신 소환--', }, '--corner--': { de: '--Ecke--', fr: '--Coin--', ja: '--コーナー--', cn: '--角落--', ko: '--구석--', }, '--dps burn--': { de: '--DPS burn--', fr: '--Burn dps--', ja: '--火力出せ--', cn: '--转火--', ko: '--딜 체크--', }, '--east--': { de: '--Osten--', fr: '--Est--', ja: '--東--', cn: '--东--', ko: '--동쪽--', }, '\\(east\\)': { de: '(Osten)', fr: '(Est)', ja: '(東)', cn: '(东)', ko: '(동쪽)', }, 'Enrage': { de: 'Finalangriff', fr: 'Enrage', ja: '時間切れ', cn: '狂暴', ko: '전멸기', }, '--frozen--': { de: '--eingefroren--', fr: '--Gelé--', ja: '--凍結--', cn: '--冻结--', ko: '--빙결--', }, '--in--': { de: '--Rein--', fr: '--Intérieur--', ja: '--中--', cn: '--内--', ko: '--안--', }, '\\(In\\)': { de: '(Rein)', fr: '(Intérieur)', ja: '(中)', cn: '(内)', ko: '(안)', }, '\\(inner\\)': { de: '(innen)', fr: '(intérieur)', ja: '(中)', cn: '(内)', ko: '(안)', }, '--jump--': { de: '--Sprung--', fr: '--Saut--', ja: '--ジャンプ--', cn: '--跳--', ko: '--점프--', }, '--knockback--': { de: '--Rückstoß--', fr: '--Poussée--', ja: '--ノックバック--', cn: '--击退--', ko: '--넉백--', }, '--middle--': { de: '--Mitte--', fr: '--Milieu--', ja: '--中央--', cn: '--中间--', ko: '--중앙--', }, '\\(middle\\)': { de: '(Mitte)', fr: '(Milieu)', ja: '(中央)', cn: '(中间)', ko: '(중앙)', }, '--north--': { de: '--Norden--', fr: '--Nord--', ja: '--北--', cn: '--北--', ko: '--북쪽--', }, '\\(north\\)': { de: '(Norden)', fr: '(Nord)', ja: '(北)', cn: '(北)', ko: '(북쪽)', }, '--northeast--': { de: '--Nordosten--', fr: '--Nord-Est--', ja: '--北東--', cn: '--东北--', ko: '--북동--', }, '--northwest--': { de: '--Nordwesten--', fr: '--Nord-Ouest--', ja: '--北西--', cn: '--西北--', ko: '--북서--', }, '--out--': { de: '--Raus--', fr: '--Extérieur--', ja: '--外--', cn: '--外--', ko: '--밖--', }, '\\(Out\\)': { de: '(Raus)', fr: '(Extérieur)', ja: '(外)', cn: '(外)', ko: '(밖)', }, '\\(outer\\)': { de: '(außen)', fr: '(extérieur)', ja: '(外)', cn: '(外)', ko: '(밖)', }, '\\(outside\\)': { de: '(Draußen)', fr: '(À l\'extérieur)', ja: '(外)', cn: '(外面)', ko: '(바깥)', }, '--rotate--': { de: '--rotieren--', fr: '--rotation--', ja: '--回転--', cn: '--旋转--', ko: '--회전--', }, '--south--': { de: '--Süden--', fr: '--Sud--', ja: '--南--', cn: '--南--', ko: '--남쪽--', }, '\\(south\\)': { de: '(Süden)', fr: '(Sud)', ja: '(南)', cn: '(南)', ko: '(남쪽)', }, '--southeast--': { de: '--Südosten--', fr: '--Sud-Est--', ja: '--南東--', cn: '--东南--', ko: '--남동--', }, '--southwest--': { de: '--Südwesten--', fr: '--Sud-Ouest--', ja: '--南西--', cn: '--西南--', ko: '--남서--', }, '--split--': { de: '--teilen--', fr: '--division--', ja: '--分裂--', cn: '--分裂--', ko: '--분열--', }, '--stun--': { de: '--Betäubung--', fr: '--Étourdissement--', ja: '--スタン--', cn: '--击晕--', ko: '--기절--', }, '--sync--': { de: '--synchronisation--', fr: '--synchronisation--', ja: '--シンク--', cn: '--同步化--', ko: '--동기화--', }, '--([0-9]+x )?targetable--': { de: '--$1anvisierbar--', fr: '--$1ciblable--', ja: '--$1ターゲット可能--', cn: '--$1可选中--', ko: '--$1타겟 가능--', }, '--teleport--': { de: '--teleportation--', fr: '--téléportation--', ja: '--テレポート--', cn: '--传送--', ko: '--순간 이동--', }, '--untargetable--': { de: '--nich anvisierbar--', fr: '--non ciblable--', ja: '--ターゲット不可--', cn: '--无法选中--', ko: '--타겟 불가능--', }, '--west--': { de: '--Westen--', fr: '--Ouest--', ja: '--西--', cn: '--西--', ko: '--서쪽--', }, [textKeys.E]: { de: 'O', fr: 'E', ja: '東', cn: '东', ko: '동', }, [textKeys.N]: { de: 'N', fr: 'N', ja: '北', cn: '北', ko: '북', }, [textKeys.S]: { de: 'S', fr: 'S', ja: '南', cn: '南', ko: '남', }, [textKeys.W]: { de: 'W', fr: 'O', ja: '西', cn: '西', ko: '서', }, [textKeys.NE]: { de: 'NO', fr: 'NE', ja: '北東', cn: '东北', ko: '북동', }, [textKeys.NW]: { de: 'NW', fr: 'NO', ja: '北西', cn: '西北', ko: '북서', }, [textKeys.SE]: { de: 'SO', fr: 'SE', ja: '南東', cn: '东南', ko: '남동', }, [textKeys.SW]: { de: 'SW', fr: 'SO', ja: '南西', cn: '西南', ko: '남서', }, [textKeys.Tank]: { de: 'Tank', fr: 'Tank', ja: 'タンク', cn: '坦克', ko: '탱커', }, [textKeys.Healer]: { de: 'Heiler', fr: 'Healer', ja: 'ヒーラー', cn: '治疗', ko: '힐러', }, [textKeys.DPS]: { de: 'DPS', fr: 'DPS', ja: 'DPS', cn: 'DPS', ko: '딜러', }, [textKeys.Number]: { de: '--$1--', fr: '--$1--', ja: '--$1--', cn: '--$1--', ko: '--$1--', }, }, } as const; // Keys into commonReplacement objects that represent "partial" translations, // in the sense that even if it applies, there still needs to be another // translation for it to be complete. These keys should be exactly the same // as the keys from the commonReplacement block above. export const partialCommonReplacementKeys = [ // Because the zone name needs to be translated here, this is partial. syncKeys.seal, // Directions textKeys.E, textKeys.N, textKeys.S, textKeys.W, textKeys.NE, textKeys.NW, textKeys.SE, textKeys.SW, // Roles textKeys.Tank, textKeys.Healer, textKeys.DPS, ];
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Manages an Image Builder Image Pipeline. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.imagebuilder.ImagePipeline("example", { * imageRecipeArn: aws_imagebuilder_image_recipe.example.arn, * infrastructureConfigurationArn: aws_imagebuilder_infrastructure_configuration.example.arn, * schedule: { * scheduleExpression: "cron(0 0 * * ? *)", * }, * }); * ``` * * ## Import * * `aws_imagebuilder_image_pipeline` resources can be imported using the Amazon Resource Name (ARN), e.g. * * ```sh * $ pulumi import aws:imagebuilder/imagePipeline:ImagePipeline example arn:aws:imagebuilder:us-east-1:123456789012:image-pipeline/example * ``` */ export class ImagePipeline extends pulumi.CustomResource { /** * Get an existing ImagePipeline resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ImagePipelineState, opts?: pulumi.CustomResourceOptions): ImagePipeline { return new ImagePipeline(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:imagebuilder/imagePipeline:ImagePipeline'; /** * Returns true if the given object is an instance of ImagePipeline. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ImagePipeline { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ImagePipeline.__pulumiType; } /** * Amazon Resource Name (ARN) of the image pipeline. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * Date the image pipeline was created. */ public /*out*/ readonly dateCreated!: pulumi.Output<string>; /** * Date the image pipeline was last run. */ public /*out*/ readonly dateLastRun!: pulumi.Output<string>; /** * Date the image pipeline will run next. */ public /*out*/ readonly dateNextRun!: pulumi.Output<string>; /** * Date the image pipeline was updated. */ public /*out*/ readonly dateUpdated!: pulumi.Output<string>; /** * Description of the image pipeline. */ public readonly description!: pulumi.Output<string | undefined>; /** * Amazon Resource Name (ARN) of the Image Builder Distribution Configuration. */ public readonly distributionConfigurationArn!: pulumi.Output<string | undefined>; /** * Whether additional information about the image being created is collected. Defaults to `true`. */ public readonly enhancedImageMetadataEnabled!: pulumi.Output<boolean | undefined>; /** * Amazon Resource Name (ARN) of the Image Builder Infrastructure Recipe. */ public readonly imageRecipeArn!: pulumi.Output<string>; /** * Configuration block with image tests configuration. Detailed below. */ public readonly imageTestsConfiguration!: pulumi.Output<outputs.imagebuilder.ImagePipelineImageTestsConfiguration>; /** * Amazon Resource Name (ARN) of the Image Builder Infrastructure Configuration. */ public readonly infrastructureConfigurationArn!: pulumi.Output<string>; /** * Name of the image pipeline. */ public readonly name!: pulumi.Output<string>; /** * Platform of the image pipeline. */ public /*out*/ readonly platform!: pulumi.Output<string>; /** * Configuration block with schedule settings. Detailed below. */ public readonly schedule!: pulumi.Output<outputs.imagebuilder.ImagePipelineSchedule | undefined>; /** * Status of the image pipeline. Valid values are `DISABLED` and `ENABLED`. Defaults to `ENABLED`. */ public readonly status!: pulumi.Output<string | undefined>; /** * Key-value map of resource tags for the image pipeline. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Create a ImagePipeline resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ImagePipelineArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ImagePipelineArgs | ImagePipelineState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ImagePipelineState | undefined; inputs["arn"] = state ? state.arn : undefined; inputs["dateCreated"] = state ? state.dateCreated : undefined; inputs["dateLastRun"] = state ? state.dateLastRun : undefined; inputs["dateNextRun"] = state ? state.dateNextRun : undefined; inputs["dateUpdated"] = state ? state.dateUpdated : undefined; inputs["description"] = state ? state.description : undefined; inputs["distributionConfigurationArn"] = state ? state.distributionConfigurationArn : undefined; inputs["enhancedImageMetadataEnabled"] = state ? state.enhancedImageMetadataEnabled : undefined; inputs["imageRecipeArn"] = state ? state.imageRecipeArn : undefined; inputs["imageTestsConfiguration"] = state ? state.imageTestsConfiguration : undefined; inputs["infrastructureConfigurationArn"] = state ? state.infrastructureConfigurationArn : undefined; inputs["name"] = state ? state.name : undefined; inputs["platform"] = state ? state.platform : undefined; inputs["schedule"] = state ? state.schedule : undefined; inputs["status"] = state ? state.status : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; } else { const args = argsOrState as ImagePipelineArgs | undefined; if ((!args || args.imageRecipeArn === undefined) && !opts.urn) { throw new Error("Missing required property 'imageRecipeArn'"); } if ((!args || args.infrastructureConfigurationArn === undefined) && !opts.urn) { throw new Error("Missing required property 'infrastructureConfigurationArn'"); } inputs["description"] = args ? args.description : undefined; inputs["distributionConfigurationArn"] = args ? args.distributionConfigurationArn : undefined; inputs["enhancedImageMetadataEnabled"] = args ? args.enhancedImageMetadataEnabled : undefined; inputs["imageRecipeArn"] = args ? args.imageRecipeArn : undefined; inputs["imageTestsConfiguration"] = args ? args.imageTestsConfiguration : undefined; inputs["infrastructureConfigurationArn"] = args ? args.infrastructureConfigurationArn : undefined; inputs["name"] = args ? args.name : undefined; inputs["schedule"] = args ? args.schedule : undefined; inputs["status"] = args ? args.status : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["arn"] = undefined /*out*/; inputs["dateCreated"] = undefined /*out*/; inputs["dateLastRun"] = undefined /*out*/; inputs["dateNextRun"] = undefined /*out*/; inputs["dateUpdated"] = undefined /*out*/; inputs["platform"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ImagePipeline.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ImagePipeline resources. */ export interface ImagePipelineState { /** * Amazon Resource Name (ARN) of the image pipeline. */ arn?: pulumi.Input<string>; /** * Date the image pipeline was created. */ dateCreated?: pulumi.Input<string>; /** * Date the image pipeline was last run. */ dateLastRun?: pulumi.Input<string>; /** * Date the image pipeline will run next. */ dateNextRun?: pulumi.Input<string>; /** * Date the image pipeline was updated. */ dateUpdated?: pulumi.Input<string>; /** * Description of the image pipeline. */ description?: pulumi.Input<string>; /** * Amazon Resource Name (ARN) of the Image Builder Distribution Configuration. */ distributionConfigurationArn?: pulumi.Input<string>; /** * Whether additional information about the image being created is collected. Defaults to `true`. */ enhancedImageMetadataEnabled?: pulumi.Input<boolean>; /** * Amazon Resource Name (ARN) of the Image Builder Infrastructure Recipe. */ imageRecipeArn?: pulumi.Input<string>; /** * Configuration block with image tests configuration. Detailed below. */ imageTestsConfiguration?: pulumi.Input<inputs.imagebuilder.ImagePipelineImageTestsConfiguration>; /** * Amazon Resource Name (ARN) of the Image Builder Infrastructure Configuration. */ infrastructureConfigurationArn?: pulumi.Input<string>; /** * Name of the image pipeline. */ name?: pulumi.Input<string>; /** * Platform of the image pipeline. */ platform?: pulumi.Input<string>; /** * Configuration block with schedule settings. Detailed below. */ schedule?: pulumi.Input<inputs.imagebuilder.ImagePipelineSchedule>; /** * Status of the image pipeline. Valid values are `DISABLED` and `ENABLED`. Defaults to `ENABLED`. */ status?: pulumi.Input<string>; /** * Key-value map of resource tags for the image pipeline. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider . */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; } /** * The set of arguments for constructing a ImagePipeline resource. */ export interface ImagePipelineArgs { /** * Description of the image pipeline. */ description?: pulumi.Input<string>; /** * Amazon Resource Name (ARN) of the Image Builder Distribution Configuration. */ distributionConfigurationArn?: pulumi.Input<string>; /** * Whether additional information about the image being created is collected. Defaults to `true`. */ enhancedImageMetadataEnabled?: pulumi.Input<boolean>; /** * Amazon Resource Name (ARN) of the Image Builder Infrastructure Recipe. */ imageRecipeArn: pulumi.Input<string>; /** * Configuration block with image tests configuration. Detailed below. */ imageTestsConfiguration?: pulumi.Input<inputs.imagebuilder.ImagePipelineImageTestsConfiguration>; /** * Amazon Resource Name (ARN) of the Image Builder Infrastructure Configuration. */ infrastructureConfigurationArn: pulumi.Input<string>; /** * Name of the image pipeline. */ name?: pulumi.Input<string>; /** * Configuration block with schedule settings. Detailed below. */ schedule?: pulumi.Input<inputs.imagebuilder.ImagePipelineSchedule>; /** * Status of the image pipeline. Valid values are `DISABLED` and `ENABLED`. Defaults to `ENABLED`. */ status?: pulumi.Input<string>; /** * Key-value map of resource tags for the image pipeline. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import type { Observer } from 'rxjs'; import type { ProviderInterface, ProviderInterfaceCallback } from '@polkadot/rpc-provider/types'; import type { StorageKey, Vec } from '@polkadot/types'; import type { Hash } from '@polkadot/types/interfaces'; import type { AnyJson, Codec, DefinitionRpc, DefinitionRpcExt, DefinitionRpcSub, Registry } from '@polkadot/types/types'; import type { Memoized } from '@polkadot/util/types'; import type { RpcInterfaceMethod } from './types'; import { Observable, publishReplay, refCount } from 'rxjs'; import { rpcDefinitions } from '@polkadot/types'; import { assert, hexToU8a, isFunction, isNull, isUndefined, lazyMethod, logger, memoize, objectSpread, u8aToU8a } from '@polkadot/util'; import { drr, refCountDelay } from './util'; export { packageInfo } from './packageInfo'; export * from './util'; interface StorageChangeSetJSON { block: string; changes: [string, string | null][]; } const l = logger('rpc-core'); const EMPTY_META = { fallback: undefined, modifier: { isOptional: true }, type: { asMap: { linked: { isTrue: false } }, isMap: false } }; // utility method to create a nicely-formatted error /** @internal */ function logErrorMessage (method: string, { params, type }: DefinitionRpc, error: Error): void { const inputs = params.map(({ isOptional, name, type }): string => `${name}${isOptional ? '?' : ''}: ${type}` ).join(', '); l.error(`${method}(${inputs}): ${type}:: ${error.message}`); } function isTreatAsHex (key: StorageKey): boolean { // :code is problematic - it does not have the length attached, which is // unlike all other storage entries where it is indeed properly encoded return ['0x3a636f6465'].includes(key.toHex()); } /** * @name Rpc * @summary The API may use a HTTP or WebSockets provider. * @description It allows for querying a Polkadot Client Node. * WebSockets provider is recommended since HTTP provider only supports basic querying. * * ```mermaid * graph LR; * A[Api] --> |WebSockets| B[WsProvider]; * B --> |endpoint| C[ws://127.0.0.1:9944] * ``` * * @example * <BR> * * ```javascript * import Rpc from '@polkadot/rpc-core'; * import { WsProvider } from '@polkadot/rpc-provider/ws'; * * const provider = new WsProvider('ws://127.0.0.1:9944'); * const rpc = new Rpc(provider); * ``` */ export class RpcCore { #instanceId: string; #registryDefault: Registry; #getBlockRegistry?: (blockHash: Uint8Array) => Promise<{ registry: Registry }>; readonly #storageCache = new Map<string, string | null>(); public readonly mapping = new Map<string, DefinitionRpcExt>(); public readonly provider: ProviderInterface; public readonly sections: string[] = []; /** * @constructor * Default constructor for the Api Object * @param {ProviderInterface} provider An API provider using HTTP or WebSocket */ constructor (instanceId: string, registry: Registry, provider: ProviderInterface, userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>> = {}) { // eslint-disable-next-line @typescript-eslint/unbound-method assert(provider && isFunction(provider.send), 'Expected Provider to API create'); this.#instanceId = instanceId; this.#registryDefault = registry; this.provider = provider; const sectionNames = Object.keys(rpcDefinitions); // these are the base keys (i.e. part of jsonrpc) this.sections.push(...sectionNames); // decorate all interfaces, defined and user on this instance this.addUserInterfaces(userRpc); } /** * @description Returns the connected status of a provider */ public get isConnected (): boolean { return this.provider.isConnected; } /** * @description Manually connect from the attached provider */ public connect (): Promise<void> { return this.provider.connect(); } /** * @description Manually disconnect from the attached provider */ public disconnect (): Promise<void> { return this.provider.disconnect(); } /** * @description Sets a registry swap (typically from Api) */ public setRegistrySwap (registrySwap: (blockHash: Uint8Array) => Promise<{ registry: Registry }>): void { this.#getBlockRegistry = memoize(registrySwap, { getInstanceId: () => this.#instanceId }); } public addUserInterfaces (userRpc: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>): void { // add any extra user-defined sections this.sections.push(...Object.keys(userRpc).filter((k) => !this.sections.includes(k))); for (let s = 0; s < this.sections.length; s++) { const section = this.sections[s]; const defs = objectSpread<Record<string, DefinitionRpc | DefinitionRpcSub>>({}, rpcDefinitions[section as 'babe'], userRpc[section]); const methods = Object.keys(defs); for (let m = 0; m < methods.length; m++) { const method = methods[m]; const def = defs[method]; const jsonrpc = def.endpoint || `${section}_${method}`; if (!this.mapping.has(jsonrpc)) { const isSubscription = !!(def as DefinitionRpcSub).pubsub; if (!(this as Record<string, unknown>)[section]) { (this as Record<string, unknown>)[section] = {}; } this.mapping.set(jsonrpc, objectSpread({}, def, { isSubscription, jsonrpc, method, section })); lazyMethod(this[section as 'connect'], method, () => isSubscription ? this._createMethodSubscribe(section, method, def as DefinitionRpcSub) : this._createMethodSend(section, method, def) ); } } } } private _memomize (creator: <T> (isScale: boolean) => (...values: unknown[]) => Observable<T>, def: DefinitionRpc): Memoized<RpcInterfaceMethod> { const memoOpts = { getInstanceId: () => this.#instanceId }; const memoized = memoize(creator(true) as RpcInterfaceMethod, memoOpts); memoized.raw = memoize(creator(false), memoOpts); memoized.meta = def; return memoized; } private _formatResult <T> (isScale: boolean, registry: Registry, blockHash: string | Uint8Array | null | undefined, method: string, def: DefinitionRpc, params: Codec[], result: unknown): T { return isScale ? this._formatOutput(registry, blockHash, method, def, params, result) as unknown as T : result as T; } private _createMethodSend (section: string, method: string, def: DefinitionRpc): RpcInterfaceMethod { const rpcName = def.endpoint || `${section}_${method}`; const hashIndex = def.params.findIndex(({ isHistoric }) => isHistoric); let memoized: null | Memoized<RpcInterfaceMethod> = null; // execute the RPC call, doing a registry swap for historic as applicable const callWithRegistry = async <T> (isScale: boolean, values: unknown[]): Promise<T> => { const blockHash = hashIndex === -1 ? null : values[hashIndex] as (Uint8Array | string | null | undefined); const { registry } = isScale && blockHash && this.#getBlockRegistry ? await this.#getBlockRegistry(u8aToU8a(blockHash)) : { registry: this.#registryDefault }; const params = this._formatInputs(registry, null, def, values); const result = await this.provider.send<AnyJson>(rpcName, params.map((p) => p.toJSON()), !!blockHash); return this._formatResult(isScale, registry, blockHash, method, def, params, result); }; const creator = <T> (isScale: boolean) => (...values: unknown[]): Observable<T> => { const isDelayed = isScale && hashIndex !== -1 && !!values[hashIndex]; return new Observable((observer: Observer<T>): () => void => { callWithRegistry<T>(isScale, values) .then((value): void => { observer.next(value); observer.complete(); }) .catch((error: Error): void => { logErrorMessage(method, def, error); observer.error(error); observer.complete(); }); return (): void => { // delete old results from cache memoized?.unmemoize(...values); }; }).pipe( publishReplay(1), // create a Replay(1) isDelayed ? refCountDelay() // Unsubscribe after delay : refCount() ); }; memoized = this._memomize(creator, def); return memoized; } // create a subscriptor, it subscribes once and resolves with the id as subscribe private _createSubscriber ({ paramsJson, subName, subType, update }: { subType: string; subName: string; paramsJson: AnyJson[]; update: ProviderInterfaceCallback }, errorHandler: (error: Error) => void): Promise<number | string> { return new Promise((resolve, reject): void => { this.provider .subscribe(subType, subName, paramsJson, update) .then(resolve) .catch((error: Error): void => { errorHandler(error); reject(error); }); }); } private _createMethodSubscribe (section: string, method: string, def: DefinitionRpcSub): RpcInterfaceMethod { const [updateType, subMethod, unsubMethod] = def.pubsub; const subName = `${section}_${subMethod}`; const unsubName = `${section}_${unsubMethod}`; const subType = `${section}_${updateType}`; let memoized: null | Memoized<RpcInterfaceMethod> = null; const creator = <T> (isScale: boolean) => (...values: unknown[]): Observable<T> => { return new Observable((observer: Observer<T>): () => void => { // Have at least an empty promise, as used in the unsubscribe let subscriptionPromise: Promise<number | string | null> = Promise.resolve(null); const registry = this.#registryDefault; const errorHandler = (error: Error): void => { logErrorMessage(method, def, error); observer.error(error); }; try { const params = this._formatInputs(registry, null, def, values); const paramsJson = params.map((p) => p.toJSON()); const update = (error?: Error | null, result?: unknown): void => { if (error) { logErrorMessage(method, def, error); return; } try { observer.next(this._formatResult(isScale, registry, null, method, def, params, result)); } catch (error) { observer.error(error); } }; subscriptionPromise = this._createSubscriber({ paramsJson, subName, subType, update }, errorHandler); } catch (error) { errorHandler(error as Error); } // Teardown logic return (): void => { // Delete from cache, so old results don't hang around memoized?.unmemoize(...values); // Unsubscribe from provider subscriptionPromise .then((subscriptionId): Promise<boolean> => isNull(subscriptionId) ? Promise.resolve(false) : this.provider.unsubscribe(subType, unsubName, subscriptionId) ) .catch((error: Error) => logErrorMessage(method, def, error)); }; }).pipe(drr()); }; memoized = this._memomize(creator, def); return memoized; } private _formatInputs (registry: Registry, blockHash: Uint8Array | string | null | undefined, def: DefinitionRpc, inputs: unknown[]): Codec[] { const reqArgCount = def.params.filter(({ isOptional }) => !isOptional).length; const optText = reqArgCount === def.params.length ? '' : ` (${def.params.length - reqArgCount} optional)`; assert(inputs.length >= reqArgCount && inputs.length <= def.params.length, () => `Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`); return inputs.map((input, index): Codec => registry.createTypeUnsafe(def.params[index].type, [input], { blockHash }) ); } private _formatOutput (registry: Registry, blockHash: Uint8Array | string | null | undefined, method: string, rpc: DefinitionRpc, params: Codec[], result?: unknown): Codec | Codec[] { if (rpc.type === 'StorageData') { const key = params[0] as StorageKey; return this._formatStorageData(registry, blockHash, key, result as string); } else if (rpc.type === 'StorageChangeSet') { const keys = params[0] as Vec<StorageKey>; return keys ? this._formatStorageSet(registry, (result as StorageChangeSetJSON).block, keys, (result as StorageChangeSetJSON).changes) : registry.createType('StorageChangeSet', result); } else if (rpc.type === 'Vec<StorageChangeSet>') { const mapped = (result as StorageChangeSetJSON[]).map(({ block, changes }): [Hash, Codec[]] => [ registry.createType('Hash', block), this._formatStorageSet(registry, block, params[0] as Vec<StorageKey>, changes) ]); // we only query at a specific block, not a range - flatten return method === 'queryStorageAt' ? mapped[0][1] : mapped as unknown as Codec[]; } return registry.createTypeUnsafe(rpc.type, [result], { blockHash }); } private _formatStorageData (registry: Registry, blockHash: Uint8Array | string | null | undefined, key: StorageKey, value: string | null): Codec { const isEmpty = isNull(value); // we convert to Uint8Array since it maps to the raw encoding, all // data will be correctly encoded (incl. numbers, excl. :code) const input = isEmpty ? null : isTreatAsHex(key) ? value : u8aToU8a(value); return this._newType(registry, blockHash, key, input, isEmpty); } private _formatStorageSet (registry: Registry, blockHash: string, keys: Vec<StorageKey>, changes: [string, string | null][]): Codec[] { // For StorageChangeSet, the changes has the [key, value] mappings const withCache = keys.length !== 1; // multiple return values (via state.storage subscription), decode the values // one at a time, all based on the query types. Three values can be returned - // - Codec - There is a valid value, non-empty // - null - The storage key is empty return keys.reduce((results: Codec[], key: StorageKey, index): Codec[] => { results.push(this._formatStorageSetEntry(registry, blockHash, key, changes, withCache, index)); return results; }, []); } private _formatStorageSetEntry (registry: Registry, blockHash: string, key: StorageKey, changes: [string, string | null][], witCache: boolean, entryIndex: number): Codec { const hexKey = key.toHex(); const found = changes.find(([key]) => key === hexKey); // if we don't find the value, this is our fallback // - in the case of an array of values, fill the hole from the cache // - if a single result value, don't fill - it is not an update hole // - fallback to an empty option in all cases const value = isUndefined(found) ? (witCache && this.#storageCache.get(hexKey)) || null : found[1]; const isEmpty = isNull(value); const input = isEmpty || isTreatAsHex(key) ? value : u8aToU8a(value); // store the retrieved result - the only issue with this cache is that there is no // clearing of it, so very long running processes (not just a couple of hours, longer) // will increase memory beyond what is allowed. this.#storageCache.set(hexKey, value); return this._newType(registry, blockHash, key, input, isEmpty, entryIndex); } private _newType (registry: Registry, blockHash: Uint8Array | string | null | undefined, key: StorageKey, input: string | Uint8Array | null, isEmpty: boolean, entryIndex = -1): Codec { // single return value (via state.getStorage), decode the value based on the // outputType that we have specified. Fallback to Raw on nothing const type = key.outputType || 'Raw'; const meta = key.meta || EMPTY_META; const entryNum = entryIndex === -1 ? '' : ` entry ${entryIndex}:`; try { return registry.createTypeUnsafe(type, [ isEmpty ? meta.fallback ? hexToU8a(meta.fallback.toHex()) : undefined : meta.modifier.isOptional ? registry.createTypeUnsafe(type, [input], { blockHash, isPedantic: true }) : input ], { blockHash, isOptional: meta.modifier.isOptional, isPedantic: !meta.modifier.isOptional }); } catch (error) { throw new Error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}: ${(error as Error).message}`); } } }
the_stack
import { IDisposable } from '../common/disposable'; export namespace Cdp { export type integer = number; /** * Protocol API. */ export interface Api { readonly session: import('./connection').CDPSession; /** * Pauses events being sent through the aPI. */ pause(): void; /** * Resumes previously-paused events */ resume(): void; Accessibility: AccessibilityApi; Animation: AnimationApi; Audits: AuditsApi; BackgroundService: BackgroundServiceApi; Browser: BrowserApi; CacheStorage: CacheStorageApi; Cast: CastApi; Console: ConsoleApi; CSS: CSSApi; Database: DatabaseApi; Debugger: DebuggerApi; DeviceOrientation: DeviceOrientationApi; DOM: DOMApi; DOMDebugger: DOMDebuggerApi; DOMSnapshot: DOMSnapshotApi; DOMStorage: DOMStorageApi; Emulation: EmulationApi; Fetch: FetchApi; HeadlessExperimental: HeadlessExperimentalApi; HeapProfiler: HeapProfilerApi; IndexedDB: IndexedDBApi; Input: InputApi; Inspector: InspectorApi; IO: IOApi; JsDebug: JsDebugApi; LayerTree: LayerTreeApi; Log: LogApi; Media: MediaApi; Memory: MemoryApi; Network: NetworkApi; NodeRuntime: NodeRuntimeApi; NodeTracing: NodeTracingApi; NodeWorker: NodeWorkerApi; Overlay: OverlayApi; Page: PageApi; Performance: PerformanceApi; PerformanceTimeline: PerformanceTimelineApi; Profiler: ProfilerApi; Runtime: RuntimeApi; Schema: SchemaApi; Security: SecurityApi; ServiceWorker: ServiceWorkerApi; Storage: StorageApi; SystemInfo: SystemInfoApi; Target: TargetApi; Tethering: TetheringApi; Tracing: TracingApi; WebAudio: WebAudioApi; WebAuthn: WebAuthnApi; } /** * Methods and events of the 'Accessibility' domain. */ export interface AccessibilityApi { /** * Disables the accessibility domain. */ disable(params: Accessibility.DisableParams): Promise<Accessibility.DisableResult | undefined>; /** * Enables the accessibility domain which causes `AXNodeId`s to remain consistent between method calls. * This turns on accessibility for the page, which can impact performance until accessibility is disabled. */ enable(params: Accessibility.EnableParams): Promise<Accessibility.EnableResult | undefined>; /** * Fetches the accessibility node and partial accessibility tree for this DOM node, if it exists. */ getPartialAXTree( params: Accessibility.GetPartialAXTreeParams, ): Promise<Accessibility.GetPartialAXTreeResult | undefined>; /** * Fetches the entire accessibility tree for the root Document */ getFullAXTree( params: Accessibility.GetFullAXTreeParams, ): Promise<Accessibility.GetFullAXTreeResult | undefined>; /** * Fetches a particular accessibility node by AXNodeId. * Requires `enable()` to have been called previously. */ getChildAXNodes( params: Accessibility.GetChildAXNodesParams, ): Promise<Accessibility.GetChildAXNodesResult | undefined>; /** * Query a DOM node's accessibility subtree for accessible name and role. * This command computes the name and role for all nodes in the subtree, including those that are * ignored for accessibility, and returns those that mactch the specified name and role. If no DOM * node is specified, or the DOM node does not exist, the command returns an error. If neither * `accessibleName` or `role` is specified, it returns all the accessibility nodes in the subtree. */ queryAXTree( params: Accessibility.QueryAXTreeParams, ): Promise<Accessibility.QueryAXTreeResult | undefined>; } /** * Types of the 'Accessibility' domain. */ export namespace Accessibility { /** * Parameters of the 'Accessibility.disable' method. */ export interface DisableParams {} /** * Return value of the 'Accessibility.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Accessibility.enable' method. */ export interface EnableParams {} /** * Return value of the 'Accessibility.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Accessibility.getPartialAXTree' method. */ export interface GetPartialAXTreeParams { /** * Identifier of the node to get the partial accessibility tree for. */ nodeId?: DOM.NodeId; /** * Identifier of the backend node to get the partial accessibility tree for. */ backendNodeId?: DOM.BackendNodeId; /** * JavaScript object id of the node wrapper to get the partial accessibility tree for. */ objectId?: Runtime.RemoteObjectId; /** * Whether to fetch this nodes ancestors, siblings and children. Defaults to true. */ fetchRelatives?: boolean; } /** * Return value of the 'Accessibility.getPartialAXTree' method. */ export interface GetPartialAXTreeResult { /** * The `Accessibility.AXNode` for this DOM node, if it exists, plus its ancestors, siblings and * children, if requested. */ nodes: AXNode[]; } /** * Parameters of the 'Accessibility.getFullAXTree' method. */ export interface GetFullAXTreeParams { /** * The maximum depth at which descendants of the root node should be retrieved. * If omitted, the full tree is returned. */ depth?: integer; /** * Deprecated. This parameter has been renamed to `depth`. If depth is not provided, max_depth will be used. * @deprecated */ max_depth?: integer; /** * The frame for whose document the AX tree should be retrieved. * If omited, the root frame is used. */ frameId?: Page.FrameId; } /** * Return value of the 'Accessibility.getFullAXTree' method. */ export interface GetFullAXTreeResult { nodes: AXNode[]; } /** * Parameters of the 'Accessibility.getChildAXNodes' method. */ export interface GetChildAXNodesParams { id: AXNodeId; /** * The frame in whose document the node resides. * If omitted, the root frame is used. */ frameId?: Page.FrameId; } /** * Return value of the 'Accessibility.getChildAXNodes' method. */ export interface GetChildAXNodesResult { nodes: AXNode[]; } /** * Parameters of the 'Accessibility.queryAXTree' method. */ export interface QueryAXTreeParams { /** * Identifier of the node for the root to query. */ nodeId?: DOM.NodeId; /** * Identifier of the backend node for the root to query. */ backendNodeId?: DOM.BackendNodeId; /** * JavaScript object id of the node wrapper for the root to query. */ objectId?: Runtime.RemoteObjectId; /** * Find nodes with this computed name. */ accessibleName?: string; /** * Find nodes with this computed role. */ role?: string; } /** * Return value of the 'Accessibility.queryAXTree' method. */ export interface QueryAXTreeResult { /** * A list of `Accessibility.AXNode` matching the specified attributes, * including nodes that are ignored for accessibility. */ nodes: AXNode[]; } /** * Unique accessibility node identifier. */ export type AXNodeId = string; /** * Enum of possible property types. */ export type AXValueType = | 'boolean' | 'tristate' | 'booleanOrUndefined' | 'idref' | 'idrefList' | 'integer' | 'node' | 'nodeList' | 'number' | 'string' | 'computedString' | 'token' | 'tokenList' | 'domRelation' | 'role' | 'internalRole' | 'valueUndefined'; /** * Enum of possible property sources. */ export type AXValueSourceType = | 'attribute' | 'implicit' | 'style' | 'contents' | 'placeholder' | 'relatedElement'; /** * Enum of possible native property sources (as a subtype of a particular AXValueSourceType). */ export type AXValueNativeSourceType = | 'description' | 'figcaption' | 'label' | 'labelfor' | 'labelwrapped' | 'legend' | 'rubyannotation' | 'tablecaption' | 'title' | 'other'; /** * A single source for a computed AX property. */ export interface AXValueSource { /** * What type of source this is. */ type: AXValueSourceType; /** * The value of this property source. */ value?: AXValue; /** * The name of the relevant attribute, if any. */ attribute?: string; /** * The value of the relevant attribute, if any. */ attributeValue?: AXValue; /** * Whether this source is superseded by a higher priority source. */ superseded?: boolean; /** * The native markup source for this value, e.g. a <label> element. */ nativeSource?: AXValueNativeSourceType; /** * The value, such as a node or node list, of the native source. */ nativeSourceValue?: AXValue; /** * Whether the value for this property is invalid. */ invalid?: boolean; /** * Reason for the value being invalid, if it is. */ invalidReason?: string; } export interface AXRelatedNode { /** * The BackendNodeId of the related DOM node. */ backendDOMNodeId: DOM.BackendNodeId; /** * The IDRef value provided, if any. */ idref?: string; /** * The text alternative of this node in the current context. */ text?: string; } export interface AXProperty { /** * The name of this property. */ name: AXPropertyName; /** * The value of this property. */ value: AXValue; } /** * A single computed AX property. */ export interface AXValue { /** * The type of this value. */ type: AXValueType; /** * The computed value of this property. */ value?: any; /** * One or more related nodes, if applicable. */ relatedNodes?: AXRelatedNode[]; /** * The sources which contributed to the computation of this property. */ sources?: AXValueSource[]; } /** * Values of AXProperty name: * - from 'busy' to 'roledescription': states which apply to every AX node * - from 'live' to 'root': attributes which apply to nodes in live regions * - from 'autocomplete' to 'valuetext': attributes which apply to widgets * - from 'checked' to 'selected': states which apply to widgets * - from 'activedescendant' to 'owns' - relationships between elements other than parent/child/sibling. */ export type AXPropertyName = | 'busy' | 'disabled' | 'editable' | 'focusable' | 'focused' | 'hidden' | 'hiddenRoot' | 'invalid' | 'keyshortcuts' | 'settable' | 'roledescription' | 'live' | 'atomic' | 'relevant' | 'root' | 'autocomplete' | 'hasPopup' | 'level' | 'multiselectable' | 'orientation' | 'multiline' | 'readonly' | 'required' | 'valuemin' | 'valuemax' | 'valuetext' | 'checked' | 'expanded' | 'modal' | 'pressed' | 'selected' | 'activedescendant' | 'controls' | 'describedby' | 'details' | 'errormessage' | 'flowto' | 'labelledby' | 'owns'; /** * A node in the accessibility tree. */ export interface AXNode { /** * Unique identifier for this node. */ nodeId: AXNodeId; /** * Whether this node is ignored for accessibility */ ignored: boolean; /** * Collection of reasons why this node is hidden. */ ignoredReasons?: AXProperty[]; /** * This `Node`'s role, whether explicit or implicit. */ role?: AXValue; /** * The accessible name for this `Node`. */ name?: AXValue; /** * The accessible description for this `Node`. */ description?: AXValue; /** * The value for this `Node`. */ value?: AXValue; /** * All other properties */ properties?: AXProperty[]; /** * IDs for each of this node's child nodes. */ childIds?: AXNodeId[]; /** * The backend ID for the associated DOM node, if any. */ backendDOMNodeId?: DOM.BackendNodeId; } } /** * Methods and events of the 'Animation' domain. */ export interface AnimationApi { /** * Disables animation domain notifications. */ disable(params: Animation.DisableParams): Promise<Animation.DisableResult | undefined>; /** * Enables animation domain notifications. */ enable(params: Animation.EnableParams): Promise<Animation.EnableResult | undefined>; /** * Returns the current time of the an animation. */ getCurrentTime( params: Animation.GetCurrentTimeParams, ): Promise<Animation.GetCurrentTimeResult | undefined>; /** * Gets the playback rate of the document timeline. */ getPlaybackRate( params: Animation.GetPlaybackRateParams, ): Promise<Animation.GetPlaybackRateResult | undefined>; /** * Releases a set of animations to no longer be manipulated. */ releaseAnimations( params: Animation.ReleaseAnimationsParams, ): Promise<Animation.ReleaseAnimationsResult | undefined>; /** * Gets the remote object of the Animation. */ resolveAnimation( params: Animation.ResolveAnimationParams, ): Promise<Animation.ResolveAnimationResult | undefined>; /** * Seek a set of animations to a particular time within each animation. */ seekAnimations( params: Animation.SeekAnimationsParams, ): Promise<Animation.SeekAnimationsResult | undefined>; /** * Sets the paused state of a set of animations. */ setPaused(params: Animation.SetPausedParams): Promise<Animation.SetPausedResult | undefined>; /** * Sets the playback rate of the document timeline. */ setPlaybackRate( params: Animation.SetPlaybackRateParams, ): Promise<Animation.SetPlaybackRateResult | undefined>; /** * Sets the timing of an animation node. */ setTiming(params: Animation.SetTimingParams): Promise<Animation.SetTimingResult | undefined>; /** * Event for when an animation has been cancelled. */ on( event: 'animationCanceled', listener: (event: Animation.AnimationCanceledEvent) => void, ): IDisposable; /** * Event for each animation that has been created. */ on( event: 'animationCreated', listener: (event: Animation.AnimationCreatedEvent) => void, ): IDisposable; /** * Event for animation that has been started. */ on( event: 'animationStarted', listener: (event: Animation.AnimationStartedEvent) => void, ): IDisposable; } /** * Types of the 'Animation' domain. */ export namespace Animation { /** * Parameters of the 'Animation.disable' method. */ export interface DisableParams {} /** * Return value of the 'Animation.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Animation.enable' method. */ export interface EnableParams {} /** * Return value of the 'Animation.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Animation.getCurrentTime' method. */ export interface GetCurrentTimeParams { /** * Id of animation. */ id: string; } /** * Return value of the 'Animation.getCurrentTime' method. */ export interface GetCurrentTimeResult { /** * Current time of the page. */ currentTime: number; } /** * Parameters of the 'Animation.getPlaybackRate' method. */ export interface GetPlaybackRateParams {} /** * Return value of the 'Animation.getPlaybackRate' method. */ export interface GetPlaybackRateResult { /** * Playback rate for animations on page. */ playbackRate: number; } /** * Parameters of the 'Animation.releaseAnimations' method. */ export interface ReleaseAnimationsParams { /** * List of animation ids to seek. */ animations: string[]; } /** * Return value of the 'Animation.releaseAnimations' method. */ export interface ReleaseAnimationsResult {} /** * Parameters of the 'Animation.resolveAnimation' method. */ export interface ResolveAnimationParams { /** * Animation id. */ animationId: string; } /** * Return value of the 'Animation.resolveAnimation' method. */ export interface ResolveAnimationResult { /** * Corresponding remote object. */ remoteObject: Runtime.RemoteObject; } /** * Parameters of the 'Animation.seekAnimations' method. */ export interface SeekAnimationsParams { /** * List of animation ids to seek. */ animations: string[]; /** * Set the current time of each animation. */ currentTime: number; } /** * Return value of the 'Animation.seekAnimations' method. */ export interface SeekAnimationsResult {} /** * Parameters of the 'Animation.setPaused' method. */ export interface SetPausedParams { /** * Animations to set the pause state of. */ animations: string[]; /** * Paused state to set to. */ paused: boolean; } /** * Return value of the 'Animation.setPaused' method. */ export interface SetPausedResult {} /** * Parameters of the 'Animation.setPlaybackRate' method. */ export interface SetPlaybackRateParams { /** * Playback rate for animations on page */ playbackRate: number; } /** * Return value of the 'Animation.setPlaybackRate' method. */ export interface SetPlaybackRateResult {} /** * Parameters of the 'Animation.setTiming' method. */ export interface SetTimingParams { /** * Animation id. */ animationId: string; /** * Duration of the animation. */ duration: number; /** * Delay of the animation. */ delay: number; } /** * Return value of the 'Animation.setTiming' method. */ export interface SetTimingResult {} /** * Parameters of the 'Animation.animationCanceled' event. */ export interface AnimationCanceledEvent { /** * Id of the animation that was cancelled. */ id: string; } /** * Parameters of the 'Animation.animationCreated' event. */ export interface AnimationCreatedEvent { /** * Id of the animation that was created. */ id: string; } /** * Parameters of the 'Animation.animationStarted' event. */ export interface AnimationStartedEvent { /** * Animation that was started. */ animation: Animation; } /** * Animation instance. */ export interface Animation { /** * `Animation`'s id. */ id: string; /** * `Animation`'s name. */ name: string; /** * `Animation`'s internal paused state. */ pausedState: boolean; /** * `Animation`'s play state. */ playState: string; /** * `Animation`'s playback rate. */ playbackRate: number; /** * `Animation`'s start time. */ startTime: number; /** * `Animation`'s current time. */ currentTime: number; /** * Animation type of `Animation`. */ type: 'CSSTransition' | 'CSSAnimation' | 'WebAnimation'; /** * `Animation`'s source animation node. */ source?: AnimationEffect; /** * A unique ID for `Animation` representing the sources that triggered this CSS * animation/transition. */ cssId?: string; } /** * AnimationEffect instance */ export interface AnimationEffect { /** * `AnimationEffect`'s delay. */ delay: number; /** * `AnimationEffect`'s end delay. */ endDelay: number; /** * `AnimationEffect`'s iteration start. */ iterationStart: number; /** * `AnimationEffect`'s iterations. */ iterations: number; /** * `AnimationEffect`'s iteration duration. */ duration: number; /** * `AnimationEffect`'s playback direction. */ direction: string; /** * `AnimationEffect`'s fill mode. */ fill: string; /** * `AnimationEffect`'s target node. */ backendNodeId?: DOM.BackendNodeId; /** * `AnimationEffect`'s keyframes. */ keyframesRule?: KeyframesRule; /** * `AnimationEffect`'s timing function. */ easing: string; } /** * Keyframes Rule */ export interface KeyframesRule { /** * CSS keyframed animation's name. */ name?: string; /** * List of animation keyframes. */ keyframes: KeyframeStyle[]; } /** * Keyframe Style */ export interface KeyframeStyle { /** * Keyframe's time offset. */ offset: string; /** * `AnimationEffect`'s timing function. */ easing: string; } } /** * Methods and events of the 'Audits' domain. */ export interface AuditsApi { /** * Returns the response body and size if it were re-encoded with the specified settings. Only * applies to images. */ getEncodedResponse( params: Audits.GetEncodedResponseParams, ): Promise<Audits.GetEncodedResponseResult | undefined>; /** * Disables issues domain, prevents further issues from being reported to the client. */ disable(params: Audits.DisableParams): Promise<Audits.DisableResult | undefined>; /** * Enables issues domain, sends the issues collected so far to the client by means of the * `issueAdded` event. */ enable(params: Audits.EnableParams): Promise<Audits.EnableResult | undefined>; /** * Runs the contrast check for the target page. Found issues are reported * using Audits.issueAdded event. */ checkContrast( params: Audits.CheckContrastParams, ): Promise<Audits.CheckContrastResult | undefined>; on(event: 'issueAdded', listener: (event: Audits.IssueAddedEvent) => void): IDisposable; } /** * Types of the 'Audits' domain. */ export namespace Audits { /** * Parameters of the 'Audits.getEncodedResponse' method. */ export interface GetEncodedResponseParams { /** * Identifier of the network request to get content for. */ requestId: Network.RequestId; /** * The encoding to use. */ encoding: 'webp' | 'jpeg' | 'png'; /** * The quality of the encoding (0-1). (defaults to 1) */ quality?: number; /** * Whether to only return the size information (defaults to false). */ sizeOnly?: boolean; } /** * Return value of the 'Audits.getEncodedResponse' method. */ export interface GetEncodedResponseResult { /** * The encoded body as a base64 string. Omitted if sizeOnly is true. (Encoded as a base64 string when passed over JSON) */ body?: string; /** * Size before re-encoding. */ originalSize: integer; /** * Size after re-encoding. */ encodedSize: integer; } /** * Parameters of the 'Audits.disable' method. */ export interface DisableParams {} /** * Return value of the 'Audits.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Audits.enable' method. */ export interface EnableParams {} /** * Return value of the 'Audits.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Audits.checkContrast' method. */ export interface CheckContrastParams { /** * Whether to report WCAG AAA level issues. Default is false. */ reportAAA?: boolean; } /** * Return value of the 'Audits.checkContrast' method. */ export interface CheckContrastResult {} /** * Parameters of the 'Audits.issueAdded' event. */ export interface IssueAddedEvent { issue: InspectorIssue; } /** * Information about a cookie that is affected by an inspector issue. */ export interface AffectedCookie { /** * The following three properties uniquely identify a cookie */ name: string; path: string; domain: string; } /** * Information about a request that is affected by an inspector issue. */ export interface AffectedRequest { /** * The unique request id. */ requestId: Network.RequestId; url?: string; } /** * Information about the frame affected by an inspector issue. */ export interface AffectedFrame { frameId: Page.FrameId; } export type SameSiteCookieExclusionReason = | 'ExcludeSameSiteUnspecifiedTreatedAsLax' | 'ExcludeSameSiteNoneInsecure' | 'ExcludeSameSiteLax' | 'ExcludeSameSiteStrict' | 'ExcludeInvalidSameParty' | 'ExcludeSamePartyCrossPartyContext'; export type SameSiteCookieWarningReason = | 'WarnSameSiteUnspecifiedCrossSiteContext' | 'WarnSameSiteNoneInsecure' | 'WarnSameSiteUnspecifiedLaxAllowUnsafe' | 'WarnSameSiteStrictLaxDowngradeStrict' | 'WarnSameSiteStrictCrossDowngradeStrict' | 'WarnSameSiteStrictCrossDowngradeLax' | 'WarnSameSiteLaxCrossDowngradeStrict' | 'WarnSameSiteLaxCrossDowngradeLax'; export type SameSiteCookieOperation = 'SetCookie' | 'ReadCookie'; /** * This information is currently necessary, as the front-end has a difficult * time finding a specific cookie. With this, we can convey specific error * information without the cookie. */ export interface SameSiteCookieIssueDetails { /** * If AffectedCookie is not set then rawCookieLine contains the raw * Set-Cookie header string. This hints at a problem where the * cookie line is syntactically or semantically malformed in a way * that no valid cookie could be created. */ cookie?: AffectedCookie; rawCookieLine?: string; cookieWarningReasons: SameSiteCookieWarningReason[]; cookieExclusionReasons: SameSiteCookieExclusionReason[]; /** * Optionally identifies the site-for-cookies and the cookie url, which * may be used by the front-end as additional context. */ operation: SameSiteCookieOperation; siteForCookies?: string; cookieUrl?: string; request?: AffectedRequest; } export type MixedContentResolutionStatus = | 'MixedContentBlocked' | 'MixedContentAutomaticallyUpgraded' | 'MixedContentWarning'; export type MixedContentResourceType = | 'Audio' | 'Beacon' | 'CSPReport' | 'Download' | 'EventSource' | 'Favicon' | 'Font' | 'Form' | 'Frame' | 'Image' | 'Import' | 'Manifest' | 'Ping' | 'PluginData' | 'PluginResource' | 'Prefetch' | 'Resource' | 'Script' | 'ServiceWorker' | 'SharedWorker' | 'Stylesheet' | 'Track' | 'Video' | 'Worker' | 'XMLHttpRequest' | 'XSLT'; export interface MixedContentIssueDetails { /** * The type of resource causing the mixed content issue (css, js, iframe, * form,...). Marked as optional because it is mapped to from * blink::mojom::RequestContextType, which will be replaced * by network::mojom::RequestDestination */ resourceType?: MixedContentResourceType; /** * The way the mixed content issue is being resolved. */ resolutionStatus: MixedContentResolutionStatus; /** * The unsafe http url causing the mixed content issue. */ insecureURL: string; /** * The url responsible for the call to an unsafe url. */ mainResourceURL: string; /** * The mixed content request. * Does not always exist (e.g. for unsafe form submission urls). */ request?: AffectedRequest; /** * Optional because not every mixed content issue is necessarily linked to a frame. */ frame?: AffectedFrame; } /** * Enum indicating the reason a response has been blocked. These reasons are * refinements of the net error BLOCKED_BY_RESPONSE. */ export type BlockedByResponseReason = | 'CoepFrameResourceNeedsCoepHeader' | 'CoopSandboxedIFrameCannotNavigateToCoopPage' | 'CorpNotSameOrigin' | 'CorpNotSameOriginAfterDefaultedToSameOriginByCoep' | 'CorpNotSameSite'; /** * Details for a request that has been blocked with the BLOCKED_BY_RESPONSE * code. Currently only used for COEP/COOP, but may be extended to include * some CSP errors in the future. */ export interface BlockedByResponseIssueDetails { request: AffectedRequest; parentFrame?: AffectedFrame; blockedFrame?: AffectedFrame; reason: BlockedByResponseReason; } export type HeavyAdResolutionStatus = 'HeavyAdBlocked' | 'HeavyAdWarning'; export type HeavyAdReason = 'NetworkTotalLimit' | 'CpuTotalLimit' | 'CpuPeakLimit'; export interface HeavyAdIssueDetails { /** * The resolution status, either blocking the content or warning. */ resolution: HeavyAdResolutionStatus; /** * The reason the ad was blocked, total network or cpu or peak cpu. */ reason: HeavyAdReason; /** * The frame that was blocked. */ frame: AffectedFrame; } export type ContentSecurityPolicyViolationType = | 'kInlineViolation' | 'kEvalViolation' | 'kURLViolation' | 'kTrustedTypesSinkViolation' | 'kTrustedTypesPolicyViolation' | 'kWasmEvalViolation'; export interface SourceCodeLocation { scriptId?: Runtime.ScriptId; url: string; lineNumber: integer; columnNumber: integer; } export interface ContentSecurityPolicyIssueDetails { /** * The url not included in allowed sources. */ blockedURL?: string; /** * Specific directive that is violated, causing the CSP issue. */ violatedDirective: string; isReportOnly: boolean; contentSecurityPolicyViolationType: ContentSecurityPolicyViolationType; frameAncestor?: AffectedFrame; sourceCodeLocation?: SourceCodeLocation; violatingNodeId?: DOM.BackendNodeId; } export type SharedArrayBufferIssueType = 'TransferIssue' | 'CreationIssue'; /** * Details for a issue arising from an SAB being instantiated in, or * transferred to a context that is not cross-origin isolated. */ export interface SharedArrayBufferIssueDetails { sourceCodeLocation: SourceCodeLocation; isWarning: boolean; type: SharedArrayBufferIssueType; } export type TwaQualityEnforcementViolationType = | 'kHttpError' | 'kUnavailableOffline' | 'kDigitalAssetLinks'; export interface TrustedWebActivityIssueDetails { /** * The url that triggers the violation. */ url: string; violationType: TwaQualityEnforcementViolationType; httpStatusCode?: integer; /** * The package name of the Trusted Web Activity client app. This field is * only used when violation type is kDigitalAssetLinks. */ packageName?: string; /** * The signature of the Trusted Web Activity client app. This field is only * used when violation type is kDigitalAssetLinks. */ signature?: string; } export interface LowTextContrastIssueDetails { violatingNodeId: DOM.BackendNodeId; violatingNodeSelector: string; contrastRatio: number; thresholdAA: number; thresholdAAA: number; fontSize: string; fontWeight: string; } /** * Details for a CORS related issue, e.g. a warning or error related to * CORS RFC1918 enforcement. */ export interface CorsIssueDetails { corsErrorStatus: Network.CorsErrorStatus; isWarning: boolean; request: AffectedRequest; location?: SourceCodeLocation; initiatorOrigin?: string; resourceIPAddressSpace?: Network.IPAddressSpace; clientSecurityState?: Network.ClientSecurityState; } export type AttributionReportingIssueType = | 'PermissionPolicyDisabled' | 'InvalidAttributionSourceEventId' | 'InvalidAttributionData' | 'AttributionSourceUntrustworthyOrigin' | 'AttributionUntrustworthyOrigin' | 'AttributionTriggerDataTooLarge' | 'AttributionEventSourceTriggerDataTooLarge'; /** * Details for issues around "Attribution Reporting API" usage. * Explainer: https://github.com/WICG/conversion-measurement-api */ export interface AttributionReportingIssueDetails { violationType: AttributionReportingIssueType; frame?: AffectedFrame; request?: AffectedRequest; violatingNodeId?: DOM.BackendNodeId; invalidParameter?: string; } /** * Details for issues about documents in Quirks Mode * or Limited Quirks Mode that affects page layouting. */ export interface QuirksModeIssueDetails { /** * If false, it means the document's mode is "quirks" * instead of "limited-quirks". */ isLimitedQuirksMode: boolean; documentNodeId: DOM.BackendNodeId; url: string; frameId: Page.FrameId; loaderId: Network.LoaderId; } export interface NavigatorUserAgentIssueDetails { url: string; location?: SourceCodeLocation; } export interface WasmCrossOriginModuleSharingIssueDetails { wasmModuleUrl: string; sourceOrigin: string; targetOrigin: string; isWarning: boolean; } export type GenericIssueErrorType = 'CrossOriginPortalPostMessageError'; /** * Depending on the concrete errorType, different properties are set. */ export interface GenericIssueDetails { /** * Issues with the same errorType are aggregated in the frontend. */ errorType: GenericIssueErrorType; frameId?: Page.FrameId; } /** * A unique identifier for the type of issue. Each type may use one of the * optional fields in InspectorIssueDetails to convey more specific * information about the kind of issue. */ export type InspectorIssueCode = | 'SameSiteCookieIssue' | 'MixedContentIssue' | 'BlockedByResponseIssue' | 'HeavyAdIssue' | 'ContentSecurityPolicyIssue' | 'SharedArrayBufferIssue' | 'TrustedWebActivityIssue' | 'LowTextContrastIssue' | 'CorsIssue' | 'AttributionReportingIssue' | 'QuirksModeIssue' | 'NavigatorUserAgentIssue' | 'WasmCrossOriginModuleSharingIssue' | 'GenericIssue'; /** * This struct holds a list of optional fields with additional information * specific to the kind of issue. When adding a new issue code, please also * add a new optional field to this type. */ export interface InspectorIssueDetails { sameSiteCookieIssueDetails?: SameSiteCookieIssueDetails; mixedContentIssueDetails?: MixedContentIssueDetails; blockedByResponseIssueDetails?: BlockedByResponseIssueDetails; heavyAdIssueDetails?: HeavyAdIssueDetails; contentSecurityPolicyIssueDetails?: ContentSecurityPolicyIssueDetails; sharedArrayBufferIssueDetails?: SharedArrayBufferIssueDetails; twaQualityEnforcementDetails?: TrustedWebActivityIssueDetails; lowTextContrastIssueDetails?: LowTextContrastIssueDetails; corsIssueDetails?: CorsIssueDetails; attributionReportingIssueDetails?: AttributionReportingIssueDetails; quirksModeIssueDetails?: QuirksModeIssueDetails; navigatorUserAgentIssueDetails?: NavigatorUserAgentIssueDetails; wasmCrossOriginModuleSharingIssue?: WasmCrossOriginModuleSharingIssueDetails; genericIssueDetails?: GenericIssueDetails; } /** * A unique id for a DevTools inspector issue. Allows other entities (e.g. * exceptions, CDP message, console messages, etc.) to reference an issue. */ export type IssueId = string; /** * An inspector issue reported from the back-end. */ export interface InspectorIssue { code: InspectorIssueCode; details: InspectorIssueDetails; /** * A unique id for this issue. May be omitted if no other entity (e.g. * exception, CDP message, etc.) is referencing this issue. */ issueId?: IssueId; } } /** * Methods and events of the 'BackgroundService' domain. */ export interface BackgroundServiceApi { /** * Enables event updates for the service. */ startObserving( params: BackgroundService.StartObservingParams, ): Promise<BackgroundService.StartObservingResult | undefined>; /** * Disables event updates for the service. */ stopObserving( params: BackgroundService.StopObservingParams, ): Promise<BackgroundService.StopObservingResult | undefined>; /** * Set the recording state for the service. */ setRecording( params: BackgroundService.SetRecordingParams, ): Promise<BackgroundService.SetRecordingResult | undefined>; /** * Clears all stored data for the service. */ clearEvents( params: BackgroundService.ClearEventsParams, ): Promise<BackgroundService.ClearEventsResult | undefined>; /** * Called when the recording state for the service has been updated. */ on( event: 'recordingStateChanged', listener: (event: BackgroundService.RecordingStateChangedEvent) => void, ): IDisposable; /** * Called with all existing backgroundServiceEvents when enabled, and all new * events afterwards if enabled and recording. */ on( event: 'backgroundServiceEventReceived', listener: (event: BackgroundService.BackgroundServiceEventReceivedEvent) => void, ): IDisposable; } /** * Types of the 'BackgroundService' domain. */ export namespace BackgroundService { /** * Parameters of the 'BackgroundService.startObserving' method. */ export interface StartObservingParams { service: ServiceName; } /** * Return value of the 'BackgroundService.startObserving' method. */ export interface StartObservingResult {} /** * Parameters of the 'BackgroundService.stopObserving' method. */ export interface StopObservingParams { service: ServiceName; } /** * Return value of the 'BackgroundService.stopObserving' method. */ export interface StopObservingResult {} /** * Parameters of the 'BackgroundService.setRecording' method. */ export interface SetRecordingParams { shouldRecord: boolean; service: ServiceName; } /** * Return value of the 'BackgroundService.setRecording' method. */ export interface SetRecordingResult {} /** * Parameters of the 'BackgroundService.clearEvents' method. */ export interface ClearEventsParams { service: ServiceName; } /** * Return value of the 'BackgroundService.clearEvents' method. */ export interface ClearEventsResult {} /** * Parameters of the 'BackgroundService.recordingStateChanged' event. */ export interface RecordingStateChangedEvent { isRecording: boolean; service: ServiceName; } /** * Parameters of the 'BackgroundService.backgroundServiceEventReceived' event. */ export interface BackgroundServiceEventReceivedEvent { backgroundServiceEvent: BackgroundServiceEvent; } /** * The Background Service that will be associated with the commands/events. * Every Background Service operates independently, but they share the same * API. */ export type ServiceName = | 'backgroundFetch' | 'backgroundSync' | 'pushMessaging' | 'notifications' | 'paymentHandler' | 'periodicBackgroundSync'; /** * A key-value pair for additional event information to pass along. */ export interface EventMetadata { key: string; value: string; } export interface BackgroundServiceEvent { /** * Timestamp of the event (in seconds). */ timestamp: Network.TimeSinceEpoch; /** * The origin this event belongs to. */ origin: string; /** * The Service Worker ID that initiated the event. */ serviceWorkerRegistrationId: ServiceWorker.RegistrationID; /** * The Background Service this event belongs to. */ service: ServiceName; /** * A description of the event. */ eventName: string; /** * An identifier that groups related events together. */ instanceId: string; /** * A list of event-specific information. */ eventMetadata: EventMetadata[]; } } /** * Methods and events of the 'Browser' domain. */ export interface BrowserApi { /** * Set permission settings for given origin. */ setPermission( params: Browser.SetPermissionParams, ): Promise<Browser.SetPermissionResult | undefined>; /** * Grant specific permissions to the given origin and reject all others. */ grantPermissions( params: Browser.GrantPermissionsParams, ): Promise<Browser.GrantPermissionsResult | undefined>; /** * Reset all permission management for all origins. */ resetPermissions( params: Browser.ResetPermissionsParams, ): Promise<Browser.ResetPermissionsResult | undefined>; /** * Set the behavior when downloading a file. */ setDownloadBehavior( params: Browser.SetDownloadBehaviorParams, ): Promise<Browser.SetDownloadBehaviorResult | undefined>; /** * Cancel a download if in progress */ cancelDownload( params: Browser.CancelDownloadParams, ): Promise<Browser.CancelDownloadResult | undefined>; /** * Close browser gracefully. */ close(params: Browser.CloseParams): Promise<Browser.CloseResult | undefined>; /** * Crashes browser on the main thread. */ crash(params: Browser.CrashParams): Promise<Browser.CrashResult | undefined>; /** * Crashes GPU process. */ crashGpuProcess( params: Browser.CrashGpuProcessParams, ): Promise<Browser.CrashGpuProcessResult | undefined>; /** * Returns version information. */ getVersion(params: Browser.GetVersionParams): Promise<Browser.GetVersionResult | undefined>; /** * Returns the command line switches for the browser process if, and only if * --enable-automation is on the commandline. */ getBrowserCommandLine( params: Browser.GetBrowserCommandLineParams, ): Promise<Browser.GetBrowserCommandLineResult | undefined>; /** * Get Chrome histograms. */ getHistograms( params: Browser.GetHistogramsParams, ): Promise<Browser.GetHistogramsResult | undefined>; /** * Get a Chrome histogram by name. */ getHistogram( params: Browser.GetHistogramParams, ): Promise<Browser.GetHistogramResult | undefined>; /** * Get position and size of the browser window. */ getWindowBounds( params: Browser.GetWindowBoundsParams, ): Promise<Browser.GetWindowBoundsResult | undefined>; /** * Get the browser window that contains the devtools target. */ getWindowForTarget( params: Browser.GetWindowForTargetParams, ): Promise<Browser.GetWindowForTargetResult | undefined>; /** * Set position and/or size of the browser window. */ setWindowBounds( params: Browser.SetWindowBoundsParams, ): Promise<Browser.SetWindowBoundsResult | undefined>; /** * Set dock tile details, platform-specific. */ setDockTile(params: Browser.SetDockTileParams): Promise<Browser.SetDockTileResult | undefined>; /** * Invoke custom browser commands used by telemetry. */ executeBrowserCommand( params: Browser.ExecuteBrowserCommandParams, ): Promise<Browser.ExecuteBrowserCommandResult | undefined>; /** * Fired when page is about to start a download. */ on( event: 'downloadWillBegin', listener: (event: Browser.DownloadWillBeginEvent) => void, ): IDisposable; /** * Fired when download makes progress. Last call has |done| == true. */ on( event: 'downloadProgress', listener: (event: Browser.DownloadProgressEvent) => void, ): IDisposable; } /** * Types of the 'Browser' domain. */ export namespace Browser { /** * Parameters of the 'Browser.setPermission' method. */ export interface SetPermissionParams { /** * Descriptor of permission to override. */ permission: PermissionDescriptor; /** * Setting of the permission. */ setting: PermissionSetting; /** * Origin the permission applies to, all origins if not specified. */ origin?: string; /** * Context to override. When omitted, default browser context is used. */ browserContextId?: BrowserContextID; } /** * Return value of the 'Browser.setPermission' method. */ export interface SetPermissionResult {} /** * Parameters of the 'Browser.grantPermissions' method. */ export interface GrantPermissionsParams { permissions: PermissionType[]; /** * Origin the permission applies to, all origins if not specified. */ origin?: string; /** * BrowserContext to override permissions. When omitted, default browser context is used. */ browserContextId?: BrowserContextID; } /** * Return value of the 'Browser.grantPermissions' method. */ export interface GrantPermissionsResult {} /** * Parameters of the 'Browser.resetPermissions' method. */ export interface ResetPermissionsParams { /** * BrowserContext to reset permissions. When omitted, default browser context is used. */ browserContextId?: BrowserContextID; } /** * Return value of the 'Browser.resetPermissions' method. */ export interface ResetPermissionsResult {} /** * Parameters of the 'Browser.setDownloadBehavior' method. */ export interface SetDownloadBehaviorParams { /** * Whether to allow all or deny all download requests, or use default Chrome behavior if * available (otherwise deny). |allowAndName| allows download and names files according to * their dowmload guids. */ behavior: 'deny' | 'allow' | 'allowAndName' | 'default'; /** * BrowserContext to set download behavior. When omitted, default browser context is used. */ browserContextId?: BrowserContextID; /** * The default path to save downloaded files to. This is required if behavior is set to 'allow' * or 'allowAndName'. */ downloadPath?: string; /** * Whether to emit download events (defaults to false). */ eventsEnabled?: boolean; } /** * Return value of the 'Browser.setDownloadBehavior' method. */ export interface SetDownloadBehaviorResult {} /** * Parameters of the 'Browser.cancelDownload' method. */ export interface CancelDownloadParams { /** * Global unique identifier of the download. */ guid: string; /** * BrowserContext to perform the action in. When omitted, default browser context is used. */ browserContextId?: BrowserContextID; } /** * Return value of the 'Browser.cancelDownload' method. */ export interface CancelDownloadResult {} /** * Parameters of the 'Browser.close' method. */ export interface CloseParams {} /** * Return value of the 'Browser.close' method. */ export interface CloseResult {} /** * Parameters of the 'Browser.crash' method. */ export interface CrashParams {} /** * Return value of the 'Browser.crash' method. */ export interface CrashResult {} /** * Parameters of the 'Browser.crashGpuProcess' method. */ export interface CrashGpuProcessParams {} /** * Return value of the 'Browser.crashGpuProcess' method. */ export interface CrashGpuProcessResult {} /** * Parameters of the 'Browser.getVersion' method. */ export interface GetVersionParams {} /** * Return value of the 'Browser.getVersion' method. */ export interface GetVersionResult { /** * Protocol version. */ protocolVersion: string; /** * Product name. */ product: string; /** * Product revision. */ revision: string; /** * User-Agent. */ userAgent: string; /** * V8 version. */ jsVersion: string; } /** * Parameters of the 'Browser.getBrowserCommandLine' method. */ export interface GetBrowserCommandLineParams {} /** * Return value of the 'Browser.getBrowserCommandLine' method. */ export interface GetBrowserCommandLineResult { /** * Commandline parameters */ arguments: string[]; } /** * Parameters of the 'Browser.getHistograms' method. */ export interface GetHistogramsParams { /** * Requested substring in name. Only histograms which have query as a * substring in their name are extracted. An empty or absent query returns * all histograms. */ query?: string; /** * If true, retrieve delta since last call. */ delta?: boolean; } /** * Return value of the 'Browser.getHistograms' method. */ export interface GetHistogramsResult { /** * Histograms. */ histograms: Histogram[]; } /** * Parameters of the 'Browser.getHistogram' method. */ export interface GetHistogramParams { /** * Requested histogram name. */ name: string; /** * If true, retrieve delta since last call. */ delta?: boolean; } /** * Return value of the 'Browser.getHistogram' method. */ export interface GetHistogramResult { /** * Histogram. */ histogram: Histogram; } /** * Parameters of the 'Browser.getWindowBounds' method. */ export interface GetWindowBoundsParams { /** * Browser window id. */ windowId: WindowID; } /** * Return value of the 'Browser.getWindowBounds' method. */ export interface GetWindowBoundsResult { /** * Bounds information of the window. When window state is 'minimized', the restored window * position and size are returned. */ bounds: Bounds; } /** * Parameters of the 'Browser.getWindowForTarget' method. */ export interface GetWindowForTargetParams { /** * Devtools agent host id. If called as a part of the session, associated targetId is used. */ targetId?: Target.TargetID; } /** * Return value of the 'Browser.getWindowForTarget' method. */ export interface GetWindowForTargetResult { /** * Browser window id. */ windowId: WindowID; /** * Bounds information of the window. When window state is 'minimized', the restored window * position and size are returned. */ bounds: Bounds; } /** * Parameters of the 'Browser.setWindowBounds' method. */ export interface SetWindowBoundsParams { /** * Browser window id. */ windowId: WindowID; /** * New window bounds. The 'minimized', 'maximized' and 'fullscreen' states cannot be combined * with 'left', 'top', 'width' or 'height'. Leaves unspecified fields unchanged. */ bounds: Bounds; } /** * Return value of the 'Browser.setWindowBounds' method. */ export interface SetWindowBoundsResult {} /** * Parameters of the 'Browser.setDockTile' method. */ export interface SetDockTileParams { badgeLabel?: string; /** * Png encoded image. (Encoded as a base64 string when passed over JSON) */ image?: string; } /** * Return value of the 'Browser.setDockTile' method. */ export interface SetDockTileResult {} /** * Parameters of the 'Browser.executeBrowserCommand' method. */ export interface ExecuteBrowserCommandParams { commandId: BrowserCommandId; } /** * Return value of the 'Browser.executeBrowserCommand' method. */ export interface ExecuteBrowserCommandResult {} /** * Parameters of the 'Browser.downloadWillBegin' event. */ export interface DownloadWillBeginEvent { /** * Id of the frame that caused the download to begin. */ frameId: Page.FrameId; /** * Global unique identifier of the download. */ guid: string; /** * URL of the resource being downloaded. */ url: string; /** * Suggested file name of the resource (the actual name of the file saved on disk may differ). */ suggestedFilename: string; } /** * Parameters of the 'Browser.downloadProgress' event. */ export interface DownloadProgressEvent { /** * Global unique identifier of the download. */ guid: string; /** * Total expected bytes to download. */ totalBytes: number; /** * Total bytes received. */ receivedBytes: number; /** * Download status. */ state: 'inProgress' | 'completed' | 'canceled'; } export type BrowserContextID = string; export type WindowID = integer; /** * The state of the browser window. */ export type WindowState = 'normal' | 'minimized' | 'maximized' | 'fullscreen'; /** * Browser window bounds information */ export interface Bounds { /** * The offset from the left edge of the screen to the window in pixels. */ left?: integer; /** * The offset from the top edge of the screen to the window in pixels. */ top?: integer; /** * The window width in pixels. */ width?: integer; /** * The window height in pixels. */ height?: integer; /** * The window state. Default to normal. */ windowState?: WindowState; } export type PermissionType = | 'accessibilityEvents' | 'audioCapture' | 'backgroundSync' | 'backgroundFetch' | 'clipboardReadWrite' | 'clipboardSanitizedWrite' | 'displayCapture' | 'durableStorage' | 'flash' | 'geolocation' | 'midi' | 'midiSysex' | 'nfc' | 'notifications' | 'paymentHandler' | 'periodicBackgroundSync' | 'protectedMediaIdentifier' | 'sensors' | 'videoCapture' | 'videoCapturePanTiltZoom' | 'idleDetection' | 'wakeLockScreen' | 'wakeLockSystem'; export type PermissionSetting = 'granted' | 'denied' | 'prompt'; /** * Definition of PermissionDescriptor defined in the Permissions API: * https://w3c.github.io/permissions/#dictdef-permissiondescriptor. */ export interface PermissionDescriptor { /** * Name of permission. * See https://cs.chromium.org/chromium/src/third_party/blink/renderer/modules/permissions/permission_descriptor.idl for valid permission names. */ name: string; /** * For "midi" permission, may also specify sysex control. */ sysex?: boolean; /** * For "push" permission, may specify userVisibleOnly. * Note that userVisibleOnly = true is the only currently supported type. */ userVisibleOnly?: boolean; /** * For "clipboard" permission, may specify allowWithoutSanitization. */ allowWithoutSanitization?: boolean; /** * For "camera" permission, may specify panTiltZoom. */ panTiltZoom?: boolean; } /** * Browser command ids used by executeBrowserCommand. */ export type BrowserCommandId = 'openTabSearch' | 'closeTabSearch'; /** * Chrome histogram bucket. */ export interface Bucket { /** * Minimum value (inclusive). */ low: integer; /** * Maximum value (exclusive). */ high: integer; /** * Number of samples. */ count: integer; } /** * Chrome histogram. */ export interface Histogram { /** * Name. */ name: string; /** * Sum of sample values. */ sum: integer; /** * Total number of samples. */ count: integer; /** * Buckets. */ buckets: Bucket[]; } } /** * Methods and events of the 'CacheStorage' domain. */ export interface CacheStorageApi { /** * Deletes a cache. */ deleteCache( params: CacheStorage.DeleteCacheParams, ): Promise<CacheStorage.DeleteCacheResult | undefined>; /** * Deletes a cache entry. */ deleteEntry( params: CacheStorage.DeleteEntryParams, ): Promise<CacheStorage.DeleteEntryResult | undefined>; /** * Requests cache names. */ requestCacheNames( params: CacheStorage.RequestCacheNamesParams, ): Promise<CacheStorage.RequestCacheNamesResult | undefined>; /** * Fetches cache entry. */ requestCachedResponse( params: CacheStorage.RequestCachedResponseParams, ): Promise<CacheStorage.RequestCachedResponseResult | undefined>; /** * Requests data from cache. */ requestEntries( params: CacheStorage.RequestEntriesParams, ): Promise<CacheStorage.RequestEntriesResult | undefined>; } /** * Types of the 'CacheStorage' domain. */ export namespace CacheStorage { /** * Parameters of the 'CacheStorage.deleteCache' method. */ export interface DeleteCacheParams { /** * Id of cache for deletion. */ cacheId: CacheId; } /** * Return value of the 'CacheStorage.deleteCache' method. */ export interface DeleteCacheResult {} /** * Parameters of the 'CacheStorage.deleteEntry' method. */ export interface DeleteEntryParams { /** * Id of cache where the entry will be deleted. */ cacheId: CacheId; /** * URL spec of the request. */ request: string; } /** * Return value of the 'CacheStorage.deleteEntry' method. */ export interface DeleteEntryResult {} /** * Parameters of the 'CacheStorage.requestCacheNames' method. */ export interface RequestCacheNamesParams { /** * Security origin. */ securityOrigin: string; } /** * Return value of the 'CacheStorage.requestCacheNames' method. */ export interface RequestCacheNamesResult { /** * Caches for the security origin. */ caches: Cache[]; } /** * Parameters of the 'CacheStorage.requestCachedResponse' method. */ export interface RequestCachedResponseParams { /** * Id of cache that contains the entry. */ cacheId: CacheId; /** * URL spec of the request. */ requestURL: string; /** * headers of the request. */ requestHeaders: Header[]; } /** * Return value of the 'CacheStorage.requestCachedResponse' method. */ export interface RequestCachedResponseResult { /** * Response read from the cache. */ response: CachedResponse; } /** * Parameters of the 'CacheStorage.requestEntries' method. */ export interface RequestEntriesParams { /** * ID of cache to get entries from. */ cacheId: CacheId; /** * Number of records to skip. */ skipCount?: integer; /** * Number of records to fetch. */ pageSize?: integer; /** * If present, only return the entries containing this substring in the path */ pathFilter?: string; } /** * Return value of the 'CacheStorage.requestEntries' method. */ export interface RequestEntriesResult { /** * Array of object store data entries. */ cacheDataEntries: DataEntry[]; /** * Count of returned entries from this storage. If pathFilter is empty, it * is the count of all entries from this storage. */ returnCount: number; } /** * Unique identifier of the Cache object. */ export type CacheId = string; /** * type of HTTP response cached */ export type CachedResponseType = | 'basic' | 'cors' | 'default' | 'error' | 'opaqueResponse' | 'opaqueRedirect'; /** * Data entry. */ export interface DataEntry { /** * Request URL. */ requestURL: string; /** * Request method. */ requestMethod: string; /** * Request headers */ requestHeaders: Header[]; /** * Number of seconds since epoch. */ responseTime: number; /** * HTTP response status code. */ responseStatus: integer; /** * HTTP response status text. */ responseStatusText: string; /** * HTTP response type */ responseType: CachedResponseType; /** * Response headers */ responseHeaders: Header[]; } /** * Cache identifier. */ export interface Cache { /** * An opaque unique id of the cache. */ cacheId: CacheId; /** * Security origin of the cache. */ securityOrigin: string; /** * The name of the cache. */ cacheName: string; } export interface Header { name: string; value: string; } /** * Cached response */ export interface CachedResponse { /** * Entry content, base64-encoded. (Encoded as a base64 string when passed over JSON) */ body: string; } } /** * Methods and events of the 'Cast' domain. */ export interface CastApi { /** * Starts observing for sinks that can be used for tab mirroring, and if set, * sinks compatible with |presentationUrl| as well. When sinks are found, a * |sinksUpdated| event is fired. * Also starts observing for issue messages. When an issue is added or removed, * an |issueUpdated| event is fired. */ enable(params: Cast.EnableParams): Promise<Cast.EnableResult | undefined>; /** * Stops observing for sinks and issues. */ disable(params: Cast.DisableParams): Promise<Cast.DisableResult | undefined>; /** * Sets a sink to be used when the web page requests the browser to choose a * sink via Presentation API, Remote Playback API, or Cast SDK. */ setSinkToUse(params: Cast.SetSinkToUseParams): Promise<Cast.SetSinkToUseResult | undefined>; /** * Starts mirroring the tab to the sink. */ startTabMirroring( params: Cast.StartTabMirroringParams, ): Promise<Cast.StartTabMirroringResult | undefined>; /** * Stops the active Cast session on the sink. */ stopCasting(params: Cast.StopCastingParams): Promise<Cast.StopCastingResult | undefined>; /** * This is fired whenever the list of available sinks changes. A sink is a * device or a software surface that you can cast to. */ on(event: 'sinksUpdated', listener: (event: Cast.SinksUpdatedEvent) => void): IDisposable; /** * This is fired whenever the outstanding issue/error message changes. * |issueMessage| is empty if there is no issue. */ on(event: 'issueUpdated', listener: (event: Cast.IssueUpdatedEvent) => void): IDisposable; } /** * Types of the 'Cast' domain. */ export namespace Cast { /** * Parameters of the 'Cast.enable' method. */ export interface EnableParams { presentationUrl?: string; } /** * Return value of the 'Cast.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Cast.disable' method. */ export interface DisableParams {} /** * Return value of the 'Cast.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Cast.setSinkToUse' method. */ export interface SetSinkToUseParams { sinkName: string; } /** * Return value of the 'Cast.setSinkToUse' method. */ export interface SetSinkToUseResult {} /** * Parameters of the 'Cast.startTabMirroring' method. */ export interface StartTabMirroringParams { sinkName: string; } /** * Return value of the 'Cast.startTabMirroring' method. */ export interface StartTabMirroringResult {} /** * Parameters of the 'Cast.stopCasting' method. */ export interface StopCastingParams { sinkName: string; } /** * Return value of the 'Cast.stopCasting' method. */ export interface StopCastingResult {} /** * Parameters of the 'Cast.sinksUpdated' event. */ export interface SinksUpdatedEvent { sinks: Sink[]; } /** * Parameters of the 'Cast.issueUpdated' event. */ export interface IssueUpdatedEvent { issueMessage: string; } export interface Sink { name: string; id: string; /** * Text describing the current session. Present only if there is an active * session on the sink. */ session?: string; } } /** * Methods and events of the 'Console' domain. */ export interface ConsoleApi { /** * Does nothing. */ clearMessages( params: Console.ClearMessagesParams, ): Promise<Console.ClearMessagesResult | undefined>; /** * Disables console domain, prevents further console messages from being reported to the client. */ disable(params: Console.DisableParams): Promise<Console.DisableResult | undefined>; /** * Enables console domain, sends the messages collected so far to the client by means of the * `messageAdded` notification. */ enable(params: Console.EnableParams): Promise<Console.EnableResult | undefined>; /** * Issued when new console message is added. */ on(event: 'messageAdded', listener: (event: Console.MessageAddedEvent) => void): IDisposable; } /** * Types of the 'Console' domain. */ export namespace Console { /** * Parameters of the 'Console.clearMessages' method. */ export interface ClearMessagesParams {} /** * Return value of the 'Console.clearMessages' method. */ export interface ClearMessagesResult {} /** * Parameters of the 'Console.disable' method. */ export interface DisableParams {} /** * Return value of the 'Console.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Console.enable' method. */ export interface EnableParams {} /** * Return value of the 'Console.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Console.messageAdded' event. */ export interface MessageAddedEvent { /** * Console message that has been added. */ message: ConsoleMessage; } /** * Console message. */ export interface ConsoleMessage { /** * Message source. */ source: | 'xml' | 'javascript' | 'network' | 'console-api' | 'storage' | 'appcache' | 'rendering' | 'security' | 'other' | 'deprecation' | 'worker'; /** * Message severity. */ level: 'log' | 'warning' | 'error' | 'debug' | 'info'; /** * Message text. */ text: string; /** * URL of the message origin. */ url?: string; /** * Line number in the resource that generated this message (1-based). */ line?: integer; /** * Column number in the resource that generated this message (1-based). */ column?: integer; } } /** * Methods and events of the 'CSS' domain. */ export interface CSSApi { /** * Inserts a new rule with the given `ruleText` in a stylesheet with given `styleSheetId`, at the * position specified by `location`. */ addRule(params: CSS.AddRuleParams): Promise<CSS.AddRuleResult | undefined>; /** * Returns all class names from specified stylesheet. */ collectClassNames( params: CSS.CollectClassNamesParams, ): Promise<CSS.CollectClassNamesResult | undefined>; /** * Creates a new special "via-inspector" stylesheet in the frame with given `frameId`. */ createStyleSheet( params: CSS.CreateStyleSheetParams, ): Promise<CSS.CreateStyleSheetResult | undefined>; /** * Disables the CSS agent for the given page. */ disable(params: CSS.DisableParams): Promise<CSS.DisableResult | undefined>; /** * Enables the CSS agent for the given page. Clients should not assume that the CSS agent has been * enabled until the result of this command is received. */ enable(params: CSS.EnableParams): Promise<CSS.EnableResult | undefined>; /** * Ensures that the given node will have specified pseudo-classes whenever its style is computed by * the browser. */ forcePseudoState( params: CSS.ForcePseudoStateParams, ): Promise<CSS.ForcePseudoStateResult | undefined>; getBackgroundColors( params: CSS.GetBackgroundColorsParams, ): Promise<CSS.GetBackgroundColorsResult | undefined>; /** * Returns the computed style for a DOM node identified by `nodeId`. */ getComputedStyleForNode( params: CSS.GetComputedStyleForNodeParams, ): Promise<CSS.GetComputedStyleForNodeResult | undefined>; /** * Returns the styles defined inline (explicitly in the "style" attribute and implicitly, using DOM * attributes) for a DOM node identified by `nodeId`. */ getInlineStylesForNode( params: CSS.GetInlineStylesForNodeParams, ): Promise<CSS.GetInlineStylesForNodeResult | undefined>; /** * Returns requested styles for a DOM node identified by `nodeId`. */ getMatchedStylesForNode( params: CSS.GetMatchedStylesForNodeParams, ): Promise<CSS.GetMatchedStylesForNodeResult | undefined>; /** * Returns all media queries parsed by the rendering engine. */ getMediaQueries( params: CSS.GetMediaQueriesParams, ): Promise<CSS.GetMediaQueriesResult | undefined>; /** * Requests information about platform fonts which we used to render child TextNodes in the given * node. */ getPlatformFontsForNode( params: CSS.GetPlatformFontsForNodeParams, ): Promise<CSS.GetPlatformFontsForNodeResult | undefined>; /** * Returns the current textual content for a stylesheet. */ getStyleSheetText( params: CSS.GetStyleSheetTextParams, ): Promise<CSS.GetStyleSheetTextResult | undefined>; /** * Starts tracking the given computed styles for updates. The specified array of properties * replaces the one previously specified. Pass empty array to disable tracking. * Use takeComputedStyleUpdates to retrieve the list of nodes that had properties modified. * The changes to computed style properties are only tracked for nodes pushed to the front-end * by the DOM agent. If no changes to the tracked properties occur after the node has been pushed * to the front-end, no updates will be issued for the node. */ trackComputedStyleUpdates( params: CSS.TrackComputedStyleUpdatesParams, ): Promise<CSS.TrackComputedStyleUpdatesResult | undefined>; /** * Polls the next batch of computed style updates. */ takeComputedStyleUpdates( params: CSS.TakeComputedStyleUpdatesParams, ): Promise<CSS.TakeComputedStyleUpdatesResult | undefined>; /** * Find a rule with the given active property for the given node and set the new value for this * property */ setEffectivePropertyValueForNode( params: CSS.SetEffectivePropertyValueForNodeParams, ): Promise<CSS.SetEffectivePropertyValueForNodeResult | undefined>; /** * Modifies the keyframe rule key text. */ setKeyframeKey(params: CSS.SetKeyframeKeyParams): Promise<CSS.SetKeyframeKeyResult | undefined>; /** * Modifies the rule selector. */ setMediaText(params: CSS.SetMediaTextParams): Promise<CSS.SetMediaTextResult | undefined>; /** * Modifies the expression of a container query. */ setContainerQueryText( params: CSS.SetContainerQueryTextParams, ): Promise<CSS.SetContainerQueryTextResult | undefined>; /** * Modifies the rule selector. */ setRuleSelector( params: CSS.SetRuleSelectorParams, ): Promise<CSS.SetRuleSelectorResult | undefined>; /** * Sets the new stylesheet text. */ setStyleSheetText( params: CSS.SetStyleSheetTextParams, ): Promise<CSS.SetStyleSheetTextResult | undefined>; /** * Applies specified style edits one after another in the given order. */ setStyleTexts(params: CSS.SetStyleTextsParams): Promise<CSS.SetStyleTextsResult | undefined>; /** * Enables the selector recording. */ startRuleUsageTracking( params: CSS.StartRuleUsageTrackingParams, ): Promise<CSS.StartRuleUsageTrackingResult | undefined>; /** * Stop tracking rule usage and return the list of rules that were used since last call to * `takeCoverageDelta` (or since start of coverage instrumentation) */ stopRuleUsageTracking( params: CSS.StopRuleUsageTrackingParams, ): Promise<CSS.StopRuleUsageTrackingResult | undefined>; /** * Obtain list of rules that became used since last call to this method (or since start of coverage * instrumentation) */ takeCoverageDelta( params: CSS.TakeCoverageDeltaParams, ): Promise<CSS.TakeCoverageDeltaResult | undefined>; /** * Enables/disables rendering of local CSS fonts (enabled by default). */ setLocalFontsEnabled( params: CSS.SetLocalFontsEnabledParams, ): Promise<CSS.SetLocalFontsEnabledResult | undefined>; /** * Fires whenever a web font is updated. A non-empty font parameter indicates a successfully loaded * web font */ on(event: 'fontsUpdated', listener: (event: CSS.FontsUpdatedEvent) => void): IDisposable; /** * Fires whenever a MediaQuery result changes (for example, after a browser window has been * resized.) The current implementation considers only viewport-dependent media features. */ on( event: 'mediaQueryResultChanged', listener: (event: CSS.MediaQueryResultChangedEvent) => void, ): IDisposable; /** * Fired whenever an active document stylesheet is added. */ on(event: 'styleSheetAdded', listener: (event: CSS.StyleSheetAddedEvent) => void): IDisposable; /** * Fired whenever a stylesheet is changed as a result of the client operation. */ on( event: 'styleSheetChanged', listener: (event: CSS.StyleSheetChangedEvent) => void, ): IDisposable; /** * Fired whenever an active document stylesheet is removed. */ on( event: 'styleSheetRemoved', listener: (event: CSS.StyleSheetRemovedEvent) => void, ): IDisposable; } /** * Types of the 'CSS' domain. */ export namespace CSS { /** * Parameters of the 'CSS.addRule' method. */ export interface AddRuleParams { /** * The css style sheet identifier where a new rule should be inserted. */ styleSheetId: StyleSheetId; /** * The text of a new rule. */ ruleText: string; /** * Text position of a new rule in the target style sheet. */ location: SourceRange; } /** * Return value of the 'CSS.addRule' method. */ export interface AddRuleResult { /** * The newly created rule. */ rule: CSSRule; } /** * Parameters of the 'CSS.collectClassNames' method. */ export interface CollectClassNamesParams { styleSheetId: StyleSheetId; } /** * Return value of the 'CSS.collectClassNames' method. */ export interface CollectClassNamesResult { /** * Class name list. */ classNames: string[]; } /** * Parameters of the 'CSS.createStyleSheet' method. */ export interface CreateStyleSheetParams { /** * Identifier of the frame where "via-inspector" stylesheet should be created. */ frameId: Page.FrameId; } /** * Return value of the 'CSS.createStyleSheet' method. */ export interface CreateStyleSheetResult { /** * Identifier of the created "via-inspector" stylesheet. */ styleSheetId: StyleSheetId; } /** * Parameters of the 'CSS.disable' method. */ export interface DisableParams {} /** * Return value of the 'CSS.disable' method. */ export interface DisableResult {} /** * Parameters of the 'CSS.enable' method. */ export interface EnableParams {} /** * Return value of the 'CSS.enable' method. */ export interface EnableResult {} /** * Parameters of the 'CSS.forcePseudoState' method. */ export interface ForcePseudoStateParams { /** * The element id for which to force the pseudo state. */ nodeId: DOM.NodeId; /** * Element pseudo classes to force when computing the element's style. */ forcedPseudoClasses: string[]; } /** * Return value of the 'CSS.forcePseudoState' method. */ export interface ForcePseudoStateResult {} /** * Parameters of the 'CSS.getBackgroundColors' method. */ export interface GetBackgroundColorsParams { /** * Id of the node to get background colors for. */ nodeId: DOM.NodeId; } /** * Return value of the 'CSS.getBackgroundColors' method. */ export interface GetBackgroundColorsResult { /** * The range of background colors behind this element, if it contains any visible text. If no * visible text is present, this will be undefined. In the case of a flat background color, * this will consist of simply that color. In the case of a gradient, this will consist of each * of the color stops. For anything more complicated, this will be an empty array. Images will * be ignored (as if the image had failed to load). */ backgroundColors?: string[]; /** * The computed font size for this node, as a CSS computed value string (e.g. '12px'). */ computedFontSize?: string; /** * The computed font weight for this node, as a CSS computed value string (e.g. 'normal' or * '100'). */ computedFontWeight?: string; } /** * Parameters of the 'CSS.getComputedStyleForNode' method. */ export interface GetComputedStyleForNodeParams { nodeId: DOM.NodeId; } /** * Return value of the 'CSS.getComputedStyleForNode' method. */ export interface GetComputedStyleForNodeResult { /** * Computed style for the specified DOM node. */ computedStyle: CSSComputedStyleProperty[]; } /** * Parameters of the 'CSS.getInlineStylesForNode' method. */ export interface GetInlineStylesForNodeParams { nodeId: DOM.NodeId; } /** * Return value of the 'CSS.getInlineStylesForNode' method. */ export interface GetInlineStylesForNodeResult { /** * Inline style for the specified DOM node. */ inlineStyle?: CSSStyle; /** * Attribute-defined element style (e.g. resulting from "width=20 height=100%"). */ attributesStyle?: CSSStyle; } /** * Parameters of the 'CSS.getMatchedStylesForNode' method. */ export interface GetMatchedStylesForNodeParams { nodeId: DOM.NodeId; } /** * Return value of the 'CSS.getMatchedStylesForNode' method. */ export interface GetMatchedStylesForNodeResult { /** * Inline style for the specified DOM node. */ inlineStyle?: CSSStyle; /** * Attribute-defined element style (e.g. resulting from "width=20 height=100%"). */ attributesStyle?: CSSStyle; /** * CSS rules matching this node, from all applicable stylesheets. */ matchedCSSRules?: RuleMatch[]; /** * Pseudo style matches for this node. */ pseudoElements?: PseudoElementMatches[]; /** * A chain of inherited styles (from the immediate node parent up to the DOM tree root). */ inherited?: InheritedStyleEntry[]; /** * A list of CSS keyframed animations matching this node. */ cssKeyframesRules?: CSSKeyframesRule[]; } /** * Parameters of the 'CSS.getMediaQueries' method. */ export interface GetMediaQueriesParams {} /** * Return value of the 'CSS.getMediaQueries' method. */ export interface GetMediaQueriesResult { medias: CSSMedia[]; } /** * Parameters of the 'CSS.getPlatformFontsForNode' method. */ export interface GetPlatformFontsForNodeParams { nodeId: DOM.NodeId; } /** * Return value of the 'CSS.getPlatformFontsForNode' method. */ export interface GetPlatformFontsForNodeResult { /** * Usage statistics for every employed platform font. */ fonts: PlatformFontUsage[]; } /** * Parameters of the 'CSS.getStyleSheetText' method. */ export interface GetStyleSheetTextParams { styleSheetId: StyleSheetId; } /** * Return value of the 'CSS.getStyleSheetText' method. */ export interface GetStyleSheetTextResult { /** * The stylesheet text. */ text: string; } /** * Parameters of the 'CSS.trackComputedStyleUpdates' method. */ export interface TrackComputedStyleUpdatesParams { propertiesToTrack: CSSComputedStyleProperty[]; } /** * Return value of the 'CSS.trackComputedStyleUpdates' method. */ export interface TrackComputedStyleUpdatesResult {} /** * Parameters of the 'CSS.takeComputedStyleUpdates' method. */ export interface TakeComputedStyleUpdatesParams {} /** * Return value of the 'CSS.takeComputedStyleUpdates' method. */ export interface TakeComputedStyleUpdatesResult { /** * The list of node Ids that have their tracked computed styles updated */ nodeIds: DOM.NodeId[]; } /** * Parameters of the 'CSS.setEffectivePropertyValueForNode' method. */ export interface SetEffectivePropertyValueForNodeParams { /** * The element id for which to set property. */ nodeId: DOM.NodeId; propertyName: string; value: string; } /** * Return value of the 'CSS.setEffectivePropertyValueForNode' method. */ export interface SetEffectivePropertyValueForNodeResult {} /** * Parameters of the 'CSS.setKeyframeKey' method. */ export interface SetKeyframeKeyParams { styleSheetId: StyleSheetId; range: SourceRange; keyText: string; } /** * Return value of the 'CSS.setKeyframeKey' method. */ export interface SetKeyframeKeyResult { /** * The resulting key text after modification. */ keyText: Value; } /** * Parameters of the 'CSS.setMediaText' method. */ export interface SetMediaTextParams { styleSheetId: StyleSheetId; range: SourceRange; text: string; } /** * Return value of the 'CSS.setMediaText' method. */ export interface SetMediaTextResult { /** * The resulting CSS media rule after modification. */ media: CSSMedia; } /** * Parameters of the 'CSS.setContainerQueryText' method. */ export interface SetContainerQueryTextParams { styleSheetId: StyleSheetId; range: SourceRange; text: string; } /** * Return value of the 'CSS.setContainerQueryText' method. */ export interface SetContainerQueryTextResult { /** * The resulting CSS container query rule after modification. */ containerQuery: CSSContainerQuery; } /** * Parameters of the 'CSS.setRuleSelector' method. */ export interface SetRuleSelectorParams { styleSheetId: StyleSheetId; range: SourceRange; selector: string; } /** * Return value of the 'CSS.setRuleSelector' method. */ export interface SetRuleSelectorResult { /** * The resulting selector list after modification. */ selectorList: SelectorList; } /** * Parameters of the 'CSS.setStyleSheetText' method. */ export interface SetStyleSheetTextParams { styleSheetId: StyleSheetId; text: string; } /** * Return value of the 'CSS.setStyleSheetText' method. */ export interface SetStyleSheetTextResult { /** * URL of source map associated with script (if any). */ sourceMapURL?: string; } /** * Parameters of the 'CSS.setStyleTexts' method. */ export interface SetStyleTextsParams { edits: StyleDeclarationEdit[]; } /** * Return value of the 'CSS.setStyleTexts' method. */ export interface SetStyleTextsResult { /** * The resulting styles after modification. */ styles: CSSStyle[]; } /** * Parameters of the 'CSS.startRuleUsageTracking' method. */ export interface StartRuleUsageTrackingParams {} /** * Return value of the 'CSS.startRuleUsageTracking' method. */ export interface StartRuleUsageTrackingResult {} /** * Parameters of the 'CSS.stopRuleUsageTracking' method. */ export interface StopRuleUsageTrackingParams {} /** * Return value of the 'CSS.stopRuleUsageTracking' method. */ export interface StopRuleUsageTrackingResult { ruleUsage: RuleUsage[]; } /** * Parameters of the 'CSS.takeCoverageDelta' method. */ export interface TakeCoverageDeltaParams {} /** * Return value of the 'CSS.takeCoverageDelta' method. */ export interface TakeCoverageDeltaResult { coverage: RuleUsage[]; /** * Monotonically increasing time, in seconds. */ timestamp: number; } /** * Parameters of the 'CSS.setLocalFontsEnabled' method. */ export interface SetLocalFontsEnabledParams { /** * Whether rendering of local fonts is enabled. */ enabled: boolean; } /** * Return value of the 'CSS.setLocalFontsEnabled' method. */ export interface SetLocalFontsEnabledResult {} /** * Parameters of the 'CSS.fontsUpdated' event. */ export interface FontsUpdatedEvent { /** * The web font that has loaded. */ font?: FontFace; } /** * Parameters of the 'CSS.mediaQueryResultChanged' event. */ export interface MediaQueryResultChangedEvent {} /** * Parameters of the 'CSS.styleSheetAdded' event. */ export interface StyleSheetAddedEvent { /** * Added stylesheet metainfo. */ header: CSSStyleSheetHeader; } /** * Parameters of the 'CSS.styleSheetChanged' event. */ export interface StyleSheetChangedEvent { styleSheetId: StyleSheetId; } /** * Parameters of the 'CSS.styleSheetRemoved' event. */ export interface StyleSheetRemovedEvent { /** * Identifier of the removed stylesheet. */ styleSheetId: StyleSheetId; } export type StyleSheetId = string; /** * Stylesheet type: "injected" for stylesheets injected via extension, "user-agent" for user-agent * stylesheets, "inspector" for stylesheets created by the inspector (i.e. those holding the "via * inspector" rules), "regular" for regular stylesheets. */ export type StyleSheetOrigin = 'injected' | 'user-agent' | 'inspector' | 'regular'; /** * CSS rule collection for a single pseudo style. */ export interface PseudoElementMatches { /** * Pseudo element type. */ pseudoType: DOM.PseudoType; /** * Matches of CSS rules applicable to the pseudo style. */ matches: RuleMatch[]; } /** * Inherited CSS rule collection from ancestor node. */ export interface InheritedStyleEntry { /** * The ancestor node's inline style, if any, in the style inheritance chain. */ inlineStyle?: CSSStyle; /** * Matches of CSS rules matching the ancestor node in the style inheritance chain. */ matchedCSSRules: RuleMatch[]; } /** * Match data for a CSS rule. */ export interface RuleMatch { /** * CSS rule in the match. */ rule: CSSRule; /** * Matching selector indices in the rule's selectorList selectors (0-based). */ matchingSelectors: integer[]; } /** * Data for a simple selector (these are delimited by commas in a selector list). */ export interface Value { /** * Value text. */ text: string; /** * Value range in the underlying resource (if available). */ range?: SourceRange; } /** * Selector list data. */ export interface SelectorList { /** * Selectors in the list. */ selectors: Value[]; /** * Rule selector text. */ text: string; } /** * CSS stylesheet metainformation. */ export interface CSSStyleSheetHeader { /** * The stylesheet identifier. */ styleSheetId: StyleSheetId; /** * Owner frame identifier. */ frameId: Page.FrameId; /** * Stylesheet resource URL. Empty if this is a constructed stylesheet created using * new CSSStyleSheet() (but non-empty if this is a constructed sylesheet imported * as a CSS module script). */ sourceURL: string; /** * URL of source map associated with the stylesheet (if any). */ sourceMapURL?: string; /** * Stylesheet origin. */ origin: StyleSheetOrigin; /** * Stylesheet title. */ title: string; /** * The backend id for the owner node of the stylesheet. */ ownerNode?: DOM.BackendNodeId; /** * Denotes whether the stylesheet is disabled. */ disabled: boolean; /** * Whether the sourceURL field value comes from the sourceURL comment. */ hasSourceURL?: boolean; /** * Whether this stylesheet is created for STYLE tag by parser. This flag is not set for * document.written STYLE tags. */ isInline: boolean; /** * Whether this stylesheet is mutable. Inline stylesheets become mutable * after they have been modified via CSSOM API. * <link> element's stylesheets become mutable only if DevTools modifies them. * Constructed stylesheets (new CSSStyleSheet()) are mutable immediately after creation. */ isMutable: boolean; /** * True if this stylesheet is created through new CSSStyleSheet() or imported as a * CSS module script. */ isConstructed: boolean; /** * Line offset of the stylesheet within the resource (zero based). */ startLine: number; /** * Column offset of the stylesheet within the resource (zero based). */ startColumn: number; /** * Size of the content (in characters). */ length: number; /** * Line offset of the end of the stylesheet within the resource (zero based). */ endLine: number; /** * Column offset of the end of the stylesheet within the resource (zero based). */ endColumn: number; } /** * CSS rule representation. */ export interface CSSRule { /** * The css style sheet identifier (absent for user agent stylesheet and user-specified * stylesheet rules) this rule came from. */ styleSheetId?: StyleSheetId; /** * Rule selector data. */ selectorList: SelectorList; /** * Parent stylesheet's origin. */ origin: StyleSheetOrigin; /** * Associated style declaration. */ style: CSSStyle; /** * Media list array (for rules involving media queries). The array enumerates media queries * starting with the innermost one, going outwards. */ media?: CSSMedia[]; /** * Container query list array (for rules involving container queries). * The array enumerates container queries starting with the innermost one, going outwards. */ containerQueries?: CSSContainerQuery[]; } /** * CSS coverage information. */ export interface RuleUsage { /** * The css style sheet identifier (absent for user agent stylesheet and user-specified * stylesheet rules) this rule came from. */ styleSheetId: StyleSheetId; /** * Offset of the start of the rule (including selector) from the beginning of the stylesheet. */ startOffset: number; /** * Offset of the end of the rule body from the beginning of the stylesheet. */ endOffset: number; /** * Indicates whether the rule was actually used by some element in the page. */ used: boolean; } /** * Text range within a resource. All numbers are zero-based. */ export interface SourceRange { /** * Start line of range. */ startLine: integer; /** * Start column of range (inclusive). */ startColumn: integer; /** * End line of range */ endLine: integer; /** * End column of range (exclusive). */ endColumn: integer; } export interface ShorthandEntry { /** * Shorthand name. */ name: string; /** * Shorthand value. */ value: string; /** * Whether the property has "!important" annotation (implies `false` if absent). */ important?: boolean; } export interface CSSComputedStyleProperty { /** * Computed style property name. */ name: string; /** * Computed style property value. */ value: string; } /** * CSS style representation. */ export interface CSSStyle { /** * The css style sheet identifier (absent for user agent stylesheet and user-specified * stylesheet rules) this rule came from. */ styleSheetId?: StyleSheetId; /** * CSS properties in the style. */ cssProperties: CSSProperty[]; /** * Computed values for all shorthands found in the style. */ shorthandEntries: ShorthandEntry[]; /** * Style declaration text (if available). */ cssText?: string; /** * Style declaration range in the enclosing stylesheet (if available). */ range?: SourceRange; } /** * CSS property declaration data. */ export interface CSSProperty { /** * The property name. */ name: string; /** * The property value. */ value: string; /** * Whether the property has "!important" annotation (implies `false` if absent). */ important?: boolean; /** * Whether the property is implicit (implies `false` if absent). */ implicit?: boolean; /** * The full property text as specified in the style. */ text?: string; /** * Whether the property is understood by the browser (implies `true` if absent). */ parsedOk?: boolean; /** * Whether the property is disabled by the user (present for source-based properties only). */ disabled?: boolean; /** * The entire property range in the enclosing style declaration (if available). */ range?: SourceRange; } /** * CSS media rule descriptor. */ export interface CSSMedia { /** * Media query text. */ text: string; /** * Source of the media query: "mediaRule" if specified by a @media rule, "importRule" if * specified by an @import rule, "linkedSheet" if specified by a "media" attribute in a linked * stylesheet's LINK tag, "inlineSheet" if specified by a "media" attribute in an inline * stylesheet's STYLE tag. */ source: 'mediaRule' | 'importRule' | 'linkedSheet' | 'inlineSheet'; /** * URL of the document containing the media query description. */ sourceURL?: string; /** * The associated rule (@media or @import) header range in the enclosing stylesheet (if * available). */ range?: SourceRange; /** * Identifier of the stylesheet containing this object (if exists). */ styleSheetId?: StyleSheetId; /** * Array of media queries. */ mediaList?: MediaQuery[]; } /** * Media query descriptor. */ export interface MediaQuery { /** * Array of media query expressions. */ expressions: MediaQueryExpression[]; /** * Whether the media query condition is satisfied. */ active: boolean; } /** * Media query expression descriptor. */ export interface MediaQueryExpression { /** * Media query expression value. */ value: number; /** * Media query expression units. */ unit: string; /** * Media query expression feature. */ feature: string; /** * The associated range of the value text in the enclosing stylesheet (if available). */ valueRange?: SourceRange; /** * Computed length of media query expression (if applicable). */ computedLength?: number; } /** * CSS container query rule descriptor. */ export interface CSSContainerQuery { /** * Container query text. */ text: string; /** * The associated rule header range in the enclosing stylesheet (if * available). */ range?: SourceRange; /** * Identifier of the stylesheet containing this object (if exists). */ styleSheetId?: StyleSheetId; /** * Optional name for the container. */ name?: string; } /** * Information about amount of glyphs that were rendered with given font. */ export interface PlatformFontUsage { /** * Font's family name reported by platform. */ familyName: string; /** * Indicates if the font was downloaded or resolved locally. */ isCustomFont: boolean; /** * Amount of glyphs that were rendered with this font. */ glyphCount: number; } /** * Information about font variation axes for variable fonts */ export interface FontVariationAxis { /** * The font-variation-setting tag (a.k.a. "axis tag"). */ tag: string; /** * Human-readable variation name in the default language (normally, "en"). */ name: string; /** * The minimum value (inclusive) the font supports for this tag. */ minValue: number; /** * The maximum value (inclusive) the font supports for this tag. */ maxValue: number; /** * The default value. */ defaultValue: number; } /** * Properties of a web font: https://www.w3.org/TR/2008/REC-CSS2-20080411/fonts.html#font-descriptions * and additional information such as platformFontFamily and fontVariationAxes. */ export interface FontFace { /** * The font-family. */ fontFamily: string; /** * The font-style. */ fontStyle: string; /** * The font-variant. */ fontVariant: string; /** * The font-weight. */ fontWeight: string; /** * The font-stretch. */ fontStretch: string; /** * The unicode-range. */ unicodeRange: string; /** * The src. */ src: string; /** * The resolved platform font family */ platformFontFamily: string; /** * Available variation settings (a.k.a. "axes"). */ fontVariationAxes?: FontVariationAxis[]; } /** * CSS keyframes rule representation. */ export interface CSSKeyframesRule { /** * Animation name. */ animationName: Value; /** * List of keyframes. */ keyframes: CSSKeyframeRule[]; } /** * CSS keyframe rule representation. */ export interface CSSKeyframeRule { /** * The css style sheet identifier (absent for user agent stylesheet and user-specified * stylesheet rules) this rule came from. */ styleSheetId?: StyleSheetId; /** * Parent stylesheet's origin. */ origin: StyleSheetOrigin; /** * Associated key text. */ keyText: Value; /** * Associated style declaration. */ style: CSSStyle; } /** * A descriptor of operation to mutate style declaration text. */ export interface StyleDeclarationEdit { /** * The css style sheet identifier. */ styleSheetId: StyleSheetId; /** * The range of the style text in the enclosing stylesheet. */ range: SourceRange; /** * New style text. */ text: string; } } /** * Methods and events of the 'Database' domain. */ export interface DatabaseApi { /** * Disables database tracking, prevents database events from being sent to the client. */ disable(params: Database.DisableParams): Promise<Database.DisableResult | undefined>; /** * Enables database tracking, database events will now be delivered to the client. */ enable(params: Database.EnableParams): Promise<Database.EnableResult | undefined>; executeSQL(params: Database.ExecuteSQLParams): Promise<Database.ExecuteSQLResult | undefined>; getDatabaseTableNames( params: Database.GetDatabaseTableNamesParams, ): Promise<Database.GetDatabaseTableNamesResult | undefined>; on(event: 'addDatabase', listener: (event: Database.AddDatabaseEvent) => void): IDisposable; } /** * Types of the 'Database' domain. */ export namespace Database { /** * Parameters of the 'Database.disable' method. */ export interface DisableParams {} /** * Return value of the 'Database.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Database.enable' method. */ export interface EnableParams {} /** * Return value of the 'Database.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Database.executeSQL' method. */ export interface ExecuteSQLParams { databaseId: DatabaseId; query: string; } /** * Return value of the 'Database.executeSQL' method. */ export interface ExecuteSQLResult { columnNames?: string[]; values?: any[]; sqlError?: Error; } /** * Parameters of the 'Database.getDatabaseTableNames' method. */ export interface GetDatabaseTableNamesParams { databaseId: DatabaseId; } /** * Return value of the 'Database.getDatabaseTableNames' method. */ export interface GetDatabaseTableNamesResult { tableNames: string[]; } /** * Parameters of the 'Database.addDatabase' event. */ export interface AddDatabaseEvent { database: Database; } /** * Unique identifier of Database object. */ export type DatabaseId = string; /** * Database object. */ export interface Database { /** * Database ID. */ id: DatabaseId; /** * Database domain. */ domain: string; /** * Database name. */ name: string; /** * Database version. */ version: string; } /** * Database error. */ export interface Error { /** * Error message. */ message: string; /** * Error code. */ code: integer; } } /** * Methods and events of the 'Debugger' domain. */ export interface DebuggerApi { /** * Continues execution until specific location is reached. */ continueToLocation( params: Debugger.ContinueToLocationParams, ): Promise<Debugger.ContinueToLocationResult | undefined>; /** * Disables debugger for given page. */ disable(params: Debugger.DisableParams): Promise<Debugger.DisableResult | undefined>; /** * Enables debugger for the given page. Clients should not assume that the debugging has been * enabled until the result for this command is received. */ enable(params: Debugger.EnableParams): Promise<Debugger.EnableResult | undefined>; /** * Evaluates expression on a given call frame. */ evaluateOnCallFrame( params: Debugger.EvaluateOnCallFrameParams, ): Promise<Debugger.EvaluateOnCallFrameResult | undefined>; /** * Returns possible locations for breakpoint. scriptId in start and end range locations should be * the same. */ getPossibleBreakpoints( params: Debugger.GetPossibleBreakpointsParams, ): Promise<Debugger.GetPossibleBreakpointsResult | undefined>; /** * Returns source for the script with given id. */ getScriptSource( params: Debugger.GetScriptSourceParams, ): Promise<Debugger.GetScriptSourceResult | undefined>; /** * This command is deprecated. Use getScriptSource instead. * @deprecated */ getWasmBytecode( params: Debugger.GetWasmBytecodeParams, ): Promise<Debugger.GetWasmBytecodeResult | undefined>; /** * Returns stack trace with given `stackTraceId`. */ getStackTrace( params: Debugger.GetStackTraceParams, ): Promise<Debugger.GetStackTraceResult | undefined>; /** * Stops on the next JavaScript statement. */ pause(params: Debugger.PauseParams): Promise<Debugger.PauseResult | undefined>; /** * undefined * @deprecated */ pauseOnAsyncCall( params: Debugger.PauseOnAsyncCallParams, ): Promise<Debugger.PauseOnAsyncCallResult | undefined>; /** * Removes JavaScript breakpoint. */ removeBreakpoint( params: Debugger.RemoveBreakpointParams, ): Promise<Debugger.RemoveBreakpointResult | undefined>; /** * Restarts particular call frame from the beginning. * @deprecated */ restartFrame( params: Debugger.RestartFrameParams, ): Promise<Debugger.RestartFrameResult | undefined>; /** * Resumes JavaScript execution. */ resume(params: Debugger.ResumeParams): Promise<Debugger.ResumeResult | undefined>; /** * Searches for given string in script content. */ searchInContent( params: Debugger.SearchInContentParams, ): Promise<Debugger.SearchInContentResult | undefined>; /** * Enables or disables async call stacks tracking. */ setAsyncCallStackDepth( params: Debugger.SetAsyncCallStackDepthParams, ): Promise<Debugger.SetAsyncCallStackDepthResult | undefined>; /** * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in * scripts with url matching one of the patterns. VM will try to leave blackboxed script by * performing 'step in' several times, finally resorting to 'step out' if unsuccessful. */ setBlackboxPatterns( params: Debugger.SetBlackboxPatternsParams, ): Promise<Debugger.SetBlackboxPatternsResult | undefined>; /** * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted * scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. * Positions array contains positions where blackbox state is changed. First interval isn't * blackboxed. Array should be sorted. */ setBlackboxedRanges( params: Debugger.SetBlackboxedRangesParams, ): Promise<Debugger.SetBlackboxedRangesResult | undefined>; /** * Sets JavaScript breakpoint at a given location. */ setBreakpoint( params: Debugger.SetBreakpointParams, ): Promise<Debugger.SetBreakpointResult | undefined>; /** * Sets instrumentation breakpoint. */ setInstrumentationBreakpoint( params: Debugger.SetInstrumentationBreakpointParams, ): Promise<Debugger.SetInstrumentationBreakpointResult | undefined>; /** * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this * command is issued, all existing parsed scripts will have breakpoints resolved and returned in * `locations` property. Further matching script parsing will result in subsequent * `breakpointResolved` events issued. This logical breakpoint will survive page reloads. */ setBreakpointByUrl( params: Debugger.SetBreakpointByUrlParams, ): Promise<Debugger.SetBreakpointByUrlResult | undefined>; /** * Sets JavaScript breakpoint before each call to the given function. * If another function was created from the same source as a given one, * calling it will also trigger the breakpoint. */ setBreakpointOnFunctionCall( params: Debugger.SetBreakpointOnFunctionCallParams, ): Promise<Debugger.SetBreakpointOnFunctionCallResult | undefined>; /** * Activates / deactivates all breakpoints on the page. */ setBreakpointsActive( params: Debugger.SetBreakpointsActiveParams, ): Promise<Debugger.SetBreakpointsActiveResult | undefined>; /** * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or * no exceptions. Initial pause on exceptions state is `none`. */ setPauseOnExceptions( params: Debugger.SetPauseOnExceptionsParams, ): Promise<Debugger.SetPauseOnExceptionsResult | undefined>; /** * Changes return value in top frame. Available only at return break position. */ setReturnValue( params: Debugger.SetReturnValueParams, ): Promise<Debugger.SetReturnValueResult | undefined>; /** * Edits JavaScript source live. */ setScriptSource( params: Debugger.SetScriptSourceParams, ): Promise<Debugger.SetScriptSourceResult | undefined>; /** * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). */ setSkipAllPauses( params: Debugger.SetSkipAllPausesParams, ): Promise<Debugger.SetSkipAllPausesResult | undefined>; /** * Changes value of variable in a callframe. Object-based scopes are not supported and must be * mutated manually. */ setVariableValue( params: Debugger.SetVariableValueParams, ): Promise<Debugger.SetVariableValueResult | undefined>; /** * Steps into the function call. */ stepInto(params: Debugger.StepIntoParams): Promise<Debugger.StepIntoResult | undefined>; /** * Steps out of the function call. */ stepOut(params: Debugger.StepOutParams): Promise<Debugger.StepOutResult | undefined>; /** * Steps over the statement. */ stepOver(params: Debugger.StepOverParams): Promise<Debugger.StepOverResult | undefined>; /** * Fired when breakpoint is resolved to an actual script and location. */ on( event: 'breakpointResolved', listener: (event: Debugger.BreakpointResolvedEvent) => void, ): IDisposable; /** * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. */ on(event: 'paused', listener: (event: Debugger.PausedEvent) => void): IDisposable; /** * Fired when the virtual machine resumed execution. */ on(event: 'resumed', listener: (event: Debugger.ResumedEvent) => void): IDisposable; /** * Fired when virtual machine fails to parse the script. */ on( event: 'scriptFailedToParse', listener: (event: Debugger.ScriptFailedToParseEvent) => void, ): IDisposable; /** * Fired when virtual machine parses script. This event is also fired for all known and uncollected * scripts upon enabling debugger. */ on(event: 'scriptParsed', listener: (event: Debugger.ScriptParsedEvent) => void): IDisposable; } /** * Types of the 'Debugger' domain. */ export namespace Debugger { /** * Parameters of the 'Debugger.continueToLocation' method. */ export interface ContinueToLocationParams { /** * Location to continue to. */ location: Location; targetCallFrames?: 'any' | 'current'; } /** * Return value of the 'Debugger.continueToLocation' method. */ export interface ContinueToLocationResult {} /** * Parameters of the 'Debugger.disable' method. */ export interface DisableParams {} /** * Return value of the 'Debugger.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Debugger.enable' method. */ export interface EnableParams { /** * The maximum size in bytes of collected scripts (not referenced by other heap objects) * the debugger can hold. Puts no limit if parameter is omitted. */ maxScriptsCacheSize?: number; } /** * Return value of the 'Debugger.enable' method. */ export interface EnableResult { /** * Unique identifier of the debugger. */ debuggerId: Runtime.UniqueDebuggerId; } /** * Parameters of the 'Debugger.evaluateOnCallFrame' method. */ export interface EvaluateOnCallFrameParams { /** * Call frame identifier to evaluate on. */ callFrameId: CallFrameId; /** * Expression to evaluate. */ expression: string; /** * String object group name to put result into (allows rapid releasing resulting object handles * using `releaseObjectGroup`). */ objectGroup?: string; /** * Specifies whether command line API should be available to the evaluated expression, defaults * to false. */ includeCommandLineAPI?: boolean; /** * In silent mode exceptions thrown during evaluation are not reported and do not pause * execution. Overrides `setPauseOnException` state. */ silent?: boolean; /** * Whether the result is expected to be a JSON object that should be sent by value. */ returnByValue?: boolean; /** * Whether preview should be generated for the result. */ generatePreview?: boolean; /** * Whether to throw an exception if side effect cannot be ruled out during evaluation. */ throwOnSideEffect?: boolean; /** * Terminate execution after timing out (number of milliseconds). */ timeout?: Runtime.TimeDelta; } /** * Return value of the 'Debugger.evaluateOnCallFrame' method. */ export interface EvaluateOnCallFrameResult { /** * Object wrapper for the evaluation result. */ result: Runtime.RemoteObject; /** * Exception details. */ exceptionDetails?: Runtime.ExceptionDetails; } /** * Parameters of the 'Debugger.getPossibleBreakpoints' method. */ export interface GetPossibleBreakpointsParams { /** * Start of range to search possible breakpoint locations in. */ start: Location; /** * End of range to search possible breakpoint locations in (excluding). When not specified, end * of scripts is used as end of range. */ end?: Location; /** * Only consider locations which are in the same (non-nested) function as start. */ restrictToFunction?: boolean; } /** * Return value of the 'Debugger.getPossibleBreakpoints' method. */ export interface GetPossibleBreakpointsResult { /** * List of the possible breakpoint locations. */ locations: BreakLocation[]; } /** * Parameters of the 'Debugger.getScriptSource' method. */ export interface GetScriptSourceParams { /** * Id of the script to get source for. */ scriptId: Runtime.ScriptId; } /** * Return value of the 'Debugger.getScriptSource' method. */ export interface GetScriptSourceResult { /** * Script source (empty in case of Wasm bytecode). */ scriptSource: string; /** * Wasm bytecode. (Encoded as a base64 string when passed over JSON) */ bytecode?: string; } /** * Parameters of the 'Debugger.getWasmBytecode' method. */ export interface GetWasmBytecodeParams { /** * Id of the Wasm script to get source for. */ scriptId: Runtime.ScriptId; } /** * Return value of the 'Debugger.getWasmBytecode' method. */ export interface GetWasmBytecodeResult { /** * Script source. (Encoded as a base64 string when passed over JSON) */ bytecode: string; } /** * Parameters of the 'Debugger.getStackTrace' method. */ export interface GetStackTraceParams { stackTraceId: Runtime.StackTraceId; } /** * Return value of the 'Debugger.getStackTrace' method. */ export interface GetStackTraceResult { stackTrace: Runtime.StackTrace; } /** * Parameters of the 'Debugger.pause' method. */ export interface PauseParams {} /** * Return value of the 'Debugger.pause' method. */ export interface PauseResult {} /** * Parameters of the 'Debugger.pauseOnAsyncCall' method. */ export interface PauseOnAsyncCallParams { /** * Debugger will pause when async call with given stack trace is started. */ parentStackTraceId: Runtime.StackTraceId; } /** * Return value of the 'Debugger.pauseOnAsyncCall' method. */ export interface PauseOnAsyncCallResult {} /** * Parameters of the 'Debugger.removeBreakpoint' method. */ export interface RemoveBreakpointParams { breakpointId: BreakpointId; } /** * Return value of the 'Debugger.removeBreakpoint' method. */ export interface RemoveBreakpointResult {} /** * Parameters of the 'Debugger.restartFrame' method. */ export interface RestartFrameParams { /** * Call frame identifier to evaluate on. */ callFrameId: CallFrameId; } /** * Return value of the 'Debugger.restartFrame' method. */ export interface RestartFrameResult { /** * New stack trace. */ callFrames: CallFrame[]; /** * Async stack trace, if any. */ asyncStackTrace?: Runtime.StackTrace; /** * Async stack trace, if any. */ asyncStackTraceId?: Runtime.StackTraceId; } /** * Parameters of the 'Debugger.resume' method. */ export interface ResumeParams { /** * Set to true to terminate execution upon resuming execution. In contrast * to Runtime.terminateExecution, this will allows to execute further * JavaScript (i.e. via evaluation) until execution of the paused code * is actually resumed, at which point termination is triggered. * If execution is currently not paused, this parameter has no effect. */ terminateOnResume?: boolean; } /** * Return value of the 'Debugger.resume' method. */ export interface ResumeResult {} /** * Parameters of the 'Debugger.searchInContent' method. */ export interface SearchInContentParams { /** * Id of the script to search in. */ scriptId: Runtime.ScriptId; /** * String to search for. */ query: string; /** * If true, search is case sensitive. */ caseSensitive?: boolean; /** * If true, treats string parameter as regex. */ isRegex?: boolean; } /** * Return value of the 'Debugger.searchInContent' method. */ export interface SearchInContentResult { /** * List of search matches. */ result: SearchMatch[]; } /** * Parameters of the 'Debugger.setAsyncCallStackDepth' method. */ export interface SetAsyncCallStackDepthParams { /** * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async * call stacks (default). */ maxDepth: integer; } /** * Return value of the 'Debugger.setAsyncCallStackDepth' method. */ export interface SetAsyncCallStackDepthResult {} /** * Parameters of the 'Debugger.setBlackboxPatterns' method. */ export interface SetBlackboxPatternsParams { /** * Array of regexps that will be used to check script url for blackbox state. */ patterns: string[]; } /** * Return value of the 'Debugger.setBlackboxPatterns' method. */ export interface SetBlackboxPatternsResult {} /** * Parameters of the 'Debugger.setBlackboxedRanges' method. */ export interface SetBlackboxedRangesParams { /** * Id of the script. */ scriptId: Runtime.ScriptId; positions: ScriptPosition[]; } /** * Return value of the 'Debugger.setBlackboxedRanges' method. */ export interface SetBlackboxedRangesResult {} /** * Parameters of the 'Debugger.setBreakpoint' method. */ export interface SetBreakpointParams { /** * Location to set breakpoint in. */ location: Location; /** * Expression to use as a breakpoint condition. When specified, debugger will only stop on the * breakpoint if this expression evaluates to true. */ condition?: string; } /** * Return value of the 'Debugger.setBreakpoint' method. */ export interface SetBreakpointResult { /** * Id of the created breakpoint for further reference. */ breakpointId: BreakpointId; /** * Location this breakpoint resolved into. */ actualLocation: Location; } /** * Parameters of the 'Debugger.setInstrumentationBreakpoint' method. */ export interface SetInstrumentationBreakpointParams { /** * Instrumentation name. */ instrumentation: 'beforeScriptExecution' | 'beforeScriptWithSourceMapExecution'; } /** * Return value of the 'Debugger.setInstrumentationBreakpoint' method. */ export interface SetInstrumentationBreakpointResult { /** * Id of the created breakpoint for further reference. */ breakpointId: BreakpointId; } /** * Parameters of the 'Debugger.setBreakpointByUrl' method. */ export interface SetBreakpointByUrlParams { /** * Line number to set breakpoint at. */ lineNumber: integer; /** * URL of the resources to set breakpoint on. */ url?: string; /** * Regex pattern for the URLs of the resources to set breakpoints on. Either `url` or * `urlRegex` must be specified. */ urlRegex?: string; /** * Script hash of the resources to set breakpoint on. */ scriptHash?: string; /** * Offset in the line to set breakpoint at. */ columnNumber?: integer; /** * Expression to use as a breakpoint condition. When specified, debugger will only stop on the * breakpoint if this expression evaluates to true. */ condition?: string; } /** * Return value of the 'Debugger.setBreakpointByUrl' method. */ export interface SetBreakpointByUrlResult { /** * Id of the created breakpoint for further reference. */ breakpointId: BreakpointId; /** * List of the locations this breakpoint resolved into upon addition. */ locations: Location[]; } /** * Parameters of the 'Debugger.setBreakpointOnFunctionCall' method. */ export interface SetBreakpointOnFunctionCallParams { /** * Function object id. */ objectId: Runtime.RemoteObjectId; /** * Expression to use as a breakpoint condition. When specified, debugger will * stop on the breakpoint if this expression evaluates to true. */ condition?: string; } /** * Return value of the 'Debugger.setBreakpointOnFunctionCall' method. */ export interface SetBreakpointOnFunctionCallResult { /** * Id of the created breakpoint for further reference. */ breakpointId: BreakpointId; } /** * Parameters of the 'Debugger.setBreakpointsActive' method. */ export interface SetBreakpointsActiveParams { /** * New value for breakpoints active state. */ active: boolean; } /** * Return value of the 'Debugger.setBreakpointsActive' method. */ export interface SetBreakpointsActiveResult {} /** * Parameters of the 'Debugger.setPauseOnExceptions' method. */ export interface SetPauseOnExceptionsParams { /** * Pause on exceptions mode. */ state: 'none' | 'uncaught' | 'all'; } /** * Return value of the 'Debugger.setPauseOnExceptions' method. */ export interface SetPauseOnExceptionsResult {} /** * Parameters of the 'Debugger.setReturnValue' method. */ export interface SetReturnValueParams { /** * New return value. */ newValue: Runtime.CallArgument; } /** * Return value of the 'Debugger.setReturnValue' method. */ export interface SetReturnValueResult {} /** * Parameters of the 'Debugger.setScriptSource' method. */ export interface SetScriptSourceParams { /** * Id of the script to edit. */ scriptId: Runtime.ScriptId; /** * New content of the script. */ scriptSource: string; /** * If true the change will not actually be applied. Dry run may be used to get result * description without actually modifying the code. */ dryRun?: boolean; } /** * Return value of the 'Debugger.setScriptSource' method. */ export interface SetScriptSourceResult { /** * New stack trace in case editing has happened while VM was stopped. */ callFrames?: CallFrame[]; /** * Whether current call stack was modified after applying the changes. */ stackChanged?: boolean; /** * Async stack trace, if any. */ asyncStackTrace?: Runtime.StackTrace; /** * Async stack trace, if any. */ asyncStackTraceId?: Runtime.StackTraceId; /** * Exception details if any. */ exceptionDetails?: Runtime.ExceptionDetails; } /** * Parameters of the 'Debugger.setSkipAllPauses' method. */ export interface SetSkipAllPausesParams { /** * New value for skip pauses state. */ skip: boolean; } /** * Return value of the 'Debugger.setSkipAllPauses' method. */ export interface SetSkipAllPausesResult {} /** * Parameters of the 'Debugger.setVariableValue' method. */ export interface SetVariableValueParams { /** * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' * scope types are allowed. Other scopes could be manipulated manually. */ scopeNumber: integer; /** * Variable name. */ variableName: string; /** * New variable value. */ newValue: Runtime.CallArgument; /** * Id of callframe that holds variable. */ callFrameId: CallFrameId; } /** * Return value of the 'Debugger.setVariableValue' method. */ export interface SetVariableValueResult {} /** * Parameters of the 'Debugger.stepInto' method. */ export interface StepIntoParams { /** * Debugger will pause on the execution of the first async task which was scheduled * before next pause. */ breakOnAsyncCall?: boolean; /** * The skipList specifies location ranges that should be skipped on step into. */ skipList?: LocationRange[]; } /** * Return value of the 'Debugger.stepInto' method. */ export interface StepIntoResult {} /** * Parameters of the 'Debugger.stepOut' method. */ export interface StepOutParams {} /** * Return value of the 'Debugger.stepOut' method. */ export interface StepOutResult {} /** * Parameters of the 'Debugger.stepOver' method. */ export interface StepOverParams { /** * The skipList specifies location ranges that should be skipped on step over. */ skipList?: LocationRange[]; } /** * Return value of the 'Debugger.stepOver' method. */ export interface StepOverResult {} /** * Parameters of the 'Debugger.breakpointResolved' event. */ export interface BreakpointResolvedEvent { /** * Breakpoint unique identifier. */ breakpointId: BreakpointId; /** * Actual breakpoint location. */ location: Location; } /** * Parameters of the 'Debugger.paused' event. */ export interface PausedEvent { /** * Call stack the virtual machine stopped on. */ callFrames: CallFrame[]; /** * Pause reason. */ reason: | 'ambiguous' | 'assert' | 'CSPViolation' | 'debugCommand' | 'DOM' | 'EventListener' | 'exception' | 'instrumentation' | 'OOM' | 'other' | 'promiseRejection' | 'XHR'; /** * Object containing break-specific auxiliary properties. */ data?: any; /** * Hit breakpoints IDs */ hitBreakpoints?: string[]; /** * Async stack trace, if any. */ asyncStackTrace?: Runtime.StackTrace; /** * Async stack trace, if any. */ asyncStackTraceId?: Runtime.StackTraceId; /** * Never present, will be removed. * @deprecated */ asyncCallStackTraceId?: Runtime.StackTraceId; } /** * Parameters of the 'Debugger.resumed' event. */ export interface ResumedEvent {} /** * Parameters of the 'Debugger.scriptFailedToParse' event. */ export interface ScriptFailedToParseEvent { /** * Identifier of the script parsed. */ scriptId: Runtime.ScriptId; /** * URL or name of the script parsed (if any). */ url: string; /** * Line offset of the script within the resource with given URL (for script tags). */ startLine: integer; /** * Column offset of the script within the resource with given URL. */ startColumn: integer; /** * Last line of the script. */ endLine: integer; /** * Length of the last line of the script. */ endColumn: integer; /** * Specifies script creation context. */ executionContextId: Runtime.ExecutionContextId; /** * Content hash of the script. */ hash: string; /** * Embedder-specific auxiliary data. */ executionContextAuxData?: any; /** * URL of source map associated with script (if any). */ sourceMapURL?: string; /** * True, if this script has sourceURL. */ hasSourceURL?: boolean; /** * True, if this script is ES6 module. */ isModule?: boolean; /** * This script length. */ length?: integer; /** * JavaScript top stack frame of where the script parsed event was triggered if available. */ stackTrace?: Runtime.StackTrace; /** * If the scriptLanguage is WebAssembly, the code section offset in the module. */ codeOffset?: integer; /** * The language of the script. */ scriptLanguage?: Debugger.ScriptLanguage; /** * The name the embedder supplied for this script. */ embedderName?: string; } /** * Parameters of the 'Debugger.scriptParsed' event. */ export interface ScriptParsedEvent { /** * Identifier of the script parsed. */ scriptId: Runtime.ScriptId; /** * URL or name of the script parsed (if any). */ url: string; /** * Line offset of the script within the resource with given URL (for script tags). */ startLine: integer; /** * Column offset of the script within the resource with given URL. */ startColumn: integer; /** * Last line of the script. */ endLine: integer; /** * Length of the last line of the script. */ endColumn: integer; /** * Specifies script creation context. */ executionContextId: Runtime.ExecutionContextId; /** * Content hash of the script. */ hash: string; /** * Embedder-specific auxiliary data. */ executionContextAuxData?: any; /** * True, if this script is generated as a result of the live edit operation. */ isLiveEdit?: boolean; /** * URL of source map associated with script (if any). */ sourceMapURL?: string; /** * True, if this script has sourceURL. */ hasSourceURL?: boolean; /** * True, if this script is ES6 module. */ isModule?: boolean; /** * This script length. */ length?: integer; /** * JavaScript top stack frame of where the script parsed event was triggered if available. */ stackTrace?: Runtime.StackTrace; /** * If the scriptLanguage is WebAssembly, the code section offset in the module. */ codeOffset?: integer; /** * The language of the script. */ scriptLanguage?: Debugger.ScriptLanguage; /** * If the scriptLanguage is WebASsembly, the source of debug symbols for the module. */ debugSymbols?: Debugger.DebugSymbols; /** * The name the embedder supplied for this script. */ embedderName?: string; } /** * Breakpoint identifier. */ export type BreakpointId = string; /** * Call frame identifier. */ export type CallFrameId = string; /** * Location in the source code. */ export interface Location { /** * Script identifier as reported in the `Debugger.scriptParsed`. */ scriptId: Runtime.ScriptId; /** * Line number in the script (0-based). */ lineNumber: integer; /** * Column number in the script (0-based). */ columnNumber?: integer; } /** * Location in the source code. */ export interface ScriptPosition { lineNumber: integer; columnNumber: integer; } /** * Location range within one script. */ export interface LocationRange { scriptId: Runtime.ScriptId; start: ScriptPosition; end: ScriptPosition; } /** * JavaScript call frame. Array of call frames form the call stack. */ export interface CallFrame { /** * Call frame identifier. This identifier is only valid while the virtual machine is paused. */ callFrameId: CallFrameId; /** * Name of the JavaScript function called on this call frame. */ functionName: string; /** * Location in the source code. */ functionLocation?: Location; /** * Location in the source code. */ location: Location; /** * JavaScript script name or url. */ url: string; /** * Scope chain for this call frame. */ scopeChain: Scope[]; /** * `this` object for this call frame. */ this: Runtime.RemoteObject; /** * The value being returned, if the function is at return point. */ returnValue?: Runtime.RemoteObject; } /** * Scope description. */ export interface Scope { /** * Scope type. */ type: | 'global' | 'local' | 'with' | 'closure' | 'catch' | 'block' | 'script' | 'eval' | 'module' | 'wasm-expression-stack'; /** * Object representing the scope. For `global` and `with` scopes it represents the actual * object; for the rest of the scopes, it is artificial transient object enumerating scope * variables as its properties. */ object: Runtime.RemoteObject; name?: string; /** * Location in the source code where scope starts */ startLocation?: Location; /** * Location in the source code where scope ends */ endLocation?: Location; } /** * Search match for resource. */ export interface SearchMatch { /** * Line number in resource content. */ lineNumber: number; /** * Line with match content. */ lineContent: string; } export interface BreakLocation { /** * Script identifier as reported in the `Debugger.scriptParsed`. */ scriptId: Runtime.ScriptId; /** * Line number in the script (0-based). */ lineNumber: integer; /** * Column number in the script (0-based). */ columnNumber?: integer; type?: 'debuggerStatement' | 'call' | 'return'; } /** * Enum of possible script languages. */ export type ScriptLanguage = 'JavaScript' | 'WebAssembly'; /** * Debug symbols available for a wasm script. */ export interface DebugSymbols { /** * Type of the debug symbols. */ type: 'None' | 'SourceMap' | 'EmbeddedDWARF' | 'ExternalDWARF'; /** * URL of the external symbol source. */ externalURL?: string; } } /** * Methods and events of the 'DeviceOrientation' domain. */ export interface DeviceOrientationApi { /** * Clears the overridden Device Orientation. */ clearDeviceOrientationOverride( params: DeviceOrientation.ClearDeviceOrientationOverrideParams, ): Promise<DeviceOrientation.ClearDeviceOrientationOverrideResult | undefined>; /** * Overrides the Device Orientation. */ setDeviceOrientationOverride( params: DeviceOrientation.SetDeviceOrientationOverrideParams, ): Promise<DeviceOrientation.SetDeviceOrientationOverrideResult | undefined>; } /** * Types of the 'DeviceOrientation' domain. */ export namespace DeviceOrientation { /** * Parameters of the 'DeviceOrientation.clearDeviceOrientationOverride' method. */ export interface ClearDeviceOrientationOverrideParams {} /** * Return value of the 'DeviceOrientation.clearDeviceOrientationOverride' method. */ export interface ClearDeviceOrientationOverrideResult {} /** * Parameters of the 'DeviceOrientation.setDeviceOrientationOverride' method. */ export interface SetDeviceOrientationOverrideParams { /** * Mock alpha */ alpha: number; /** * Mock beta */ beta: number; /** * Mock gamma */ gamma: number; } /** * Return value of the 'DeviceOrientation.setDeviceOrientationOverride' method. */ export interface SetDeviceOrientationOverrideResult {} } /** * Methods and events of the 'DOM' domain. */ export interface DOMApi { /** * Collects class names for the node with given id and all of it's child nodes. */ collectClassNamesFromSubtree( params: DOM.CollectClassNamesFromSubtreeParams, ): Promise<DOM.CollectClassNamesFromSubtreeResult | undefined>; /** * Creates a deep copy of the specified node and places it into the target container before the * given anchor. */ copyTo(params: DOM.CopyToParams): Promise<DOM.CopyToResult | undefined>; /** * Describes node given its id, does not require domain to be enabled. Does not start tracking any * objects, can be used for automation. */ describeNode(params: DOM.DescribeNodeParams): Promise<DOM.DescribeNodeResult | undefined>; /** * Scrolls the specified rect of the given node into view if not already visible. * Note: exactly one between nodeId, backendNodeId and objectId should be passed * to identify the node. */ scrollIntoViewIfNeeded( params: DOM.ScrollIntoViewIfNeededParams, ): Promise<DOM.ScrollIntoViewIfNeededResult | undefined>; /** * Disables DOM agent for the given page. */ disable(params: DOM.DisableParams): Promise<DOM.DisableResult | undefined>; /** * Discards search results from the session with the given id. `getSearchResults` should no longer * be called for that search. */ discardSearchResults( params: DOM.DiscardSearchResultsParams, ): Promise<DOM.DiscardSearchResultsResult | undefined>; /** * Enables DOM agent for the given page. */ enable(params: DOM.EnableParams): Promise<DOM.EnableResult | undefined>; /** * Focuses the given element. */ focus(params: DOM.FocusParams): Promise<DOM.FocusResult | undefined>; /** * Returns attributes for the specified node. */ getAttributes(params: DOM.GetAttributesParams): Promise<DOM.GetAttributesResult | undefined>; /** * Returns boxes for the given node. */ getBoxModel(params: DOM.GetBoxModelParams): Promise<DOM.GetBoxModelResult | undefined>; /** * Returns quads that describe node position on the page. This method * might return multiple quads for inline nodes. */ getContentQuads( params: DOM.GetContentQuadsParams, ): Promise<DOM.GetContentQuadsResult | undefined>; /** * Returns the root DOM node (and optionally the subtree) to the caller. */ getDocument(params: DOM.GetDocumentParams): Promise<DOM.GetDocumentResult | undefined>; /** * Returns the root DOM node (and optionally the subtree) to the caller. * Deprecated, as it is not designed to work well with the rest of the DOM agent. * Use DOMSnapshot.captureSnapshot instead. * @deprecated */ getFlattenedDocument( params: DOM.GetFlattenedDocumentParams, ): Promise<DOM.GetFlattenedDocumentResult | undefined>; /** * Finds nodes with a given computed style in a subtree. */ getNodesForSubtreeByStyle( params: DOM.GetNodesForSubtreeByStyleParams, ): Promise<DOM.GetNodesForSubtreeByStyleResult | undefined>; /** * Returns node id at given location. Depending on whether DOM domain is enabled, nodeId is * either returned or not. */ getNodeForLocation( params: DOM.GetNodeForLocationParams, ): Promise<DOM.GetNodeForLocationResult | undefined>; /** * Returns node's HTML markup. */ getOuterHTML(params: DOM.GetOuterHTMLParams): Promise<DOM.GetOuterHTMLResult | undefined>; /** * Returns the id of the nearest ancestor that is a relayout boundary. */ getRelayoutBoundary( params: DOM.GetRelayoutBoundaryParams, ): Promise<DOM.GetRelayoutBoundaryResult | undefined>; /** * Returns search results from given `fromIndex` to given `toIndex` from the search with the given * identifier. */ getSearchResults( params: DOM.GetSearchResultsParams, ): Promise<DOM.GetSearchResultsResult | undefined>; /** * Hides any highlight. */ hideHighlight(params: DOM.HideHighlightParams): Promise<DOM.HideHighlightResult | undefined>; /** * Highlights DOM node. */ highlightNode(params: DOM.HighlightNodeParams): Promise<DOM.HighlightNodeResult | undefined>; /** * Highlights given rectangle. */ highlightRect(params: DOM.HighlightRectParams): Promise<DOM.HighlightRectResult | undefined>; /** * Marks last undoable state. */ markUndoableState( params: DOM.MarkUndoableStateParams, ): Promise<DOM.MarkUndoableStateResult | undefined>; /** * Moves node into the new container, places it before the given anchor. */ moveTo(params: DOM.MoveToParams): Promise<DOM.MoveToResult | undefined>; /** * Searches for a given string in the DOM tree. Use `getSearchResults` to access search results or * `cancelSearch` to end this search session. */ performSearch(params: DOM.PerformSearchParams): Promise<DOM.PerformSearchResult | undefined>; /** * Requests that the node is sent to the caller given its path. // FIXME, use XPath */ pushNodeByPathToFrontend( params: DOM.PushNodeByPathToFrontendParams, ): Promise<DOM.PushNodeByPathToFrontendResult | undefined>; /** * Requests that a batch of nodes is sent to the caller given their backend node ids. */ pushNodesByBackendIdsToFrontend( params: DOM.PushNodesByBackendIdsToFrontendParams, ): Promise<DOM.PushNodesByBackendIdsToFrontendResult | undefined>; /** * Executes `querySelector` on a given node. */ querySelector(params: DOM.QuerySelectorParams): Promise<DOM.QuerySelectorResult | undefined>; /** * Executes `querySelectorAll` on a given node. */ querySelectorAll( params: DOM.QuerySelectorAllParams, ): Promise<DOM.QuerySelectorAllResult | undefined>; /** * Re-does the last undone action. */ redo(params: DOM.RedoParams): Promise<DOM.RedoResult | undefined>; /** * Removes attribute with given name from an element with given id. */ removeAttribute( params: DOM.RemoveAttributeParams, ): Promise<DOM.RemoveAttributeResult | undefined>; /** * Removes node with given id. */ removeNode(params: DOM.RemoveNodeParams): Promise<DOM.RemoveNodeResult | undefined>; /** * Requests that children of the node with given id are returned to the caller in form of * `setChildNodes` events where not only immediate children are retrieved, but all children down to * the specified depth. */ requestChildNodes( params: DOM.RequestChildNodesParams, ): Promise<DOM.RequestChildNodesResult | undefined>; /** * Requests that the node is sent to the caller given the JavaScript node object reference. All * nodes that form the path from the node to the root are also sent to the client as a series of * `setChildNodes` notifications. */ requestNode(params: DOM.RequestNodeParams): Promise<DOM.RequestNodeResult | undefined>; /** * Resolves the JavaScript node object for a given NodeId or BackendNodeId. */ resolveNode(params: DOM.ResolveNodeParams): Promise<DOM.ResolveNodeResult | undefined>; /** * Sets attribute for an element with given id. */ setAttributeValue( params: DOM.SetAttributeValueParams, ): Promise<DOM.SetAttributeValueResult | undefined>; /** * Sets attributes on element with given id. This method is useful when user edits some existing * attribute value and types in several attribute name/value pairs. */ setAttributesAsText( params: DOM.SetAttributesAsTextParams, ): Promise<DOM.SetAttributesAsTextResult | undefined>; /** * Sets files for the given file input element. */ setFileInputFiles( params: DOM.SetFileInputFilesParams, ): Promise<DOM.SetFileInputFilesResult | undefined>; /** * Sets if stack traces should be captured for Nodes. See `Node.getNodeStackTraces`. Default is disabled. */ setNodeStackTracesEnabled( params: DOM.SetNodeStackTracesEnabledParams, ): Promise<DOM.SetNodeStackTracesEnabledResult | undefined>; /** * Gets stack traces associated with a Node. As of now, only provides stack trace for Node creation. */ getNodeStackTraces( params: DOM.GetNodeStackTracesParams, ): Promise<DOM.GetNodeStackTracesResult | undefined>; /** * Returns file information for the given * File wrapper. */ getFileInfo(params: DOM.GetFileInfoParams): Promise<DOM.GetFileInfoResult | undefined>; /** * Enables console to refer to the node with given id via $x (see Command Line API for more details * $x functions). */ setInspectedNode( params: DOM.SetInspectedNodeParams, ): Promise<DOM.SetInspectedNodeResult | undefined>; /** * Sets node name for a node with given id. */ setNodeName(params: DOM.SetNodeNameParams): Promise<DOM.SetNodeNameResult | undefined>; /** * Sets node value for a node with given id. */ setNodeValue(params: DOM.SetNodeValueParams): Promise<DOM.SetNodeValueResult | undefined>; /** * Sets node HTML markup, returns new node id. */ setOuterHTML(params: DOM.SetOuterHTMLParams): Promise<DOM.SetOuterHTMLResult | undefined>; /** * Undoes the last performed action. */ undo(params: DOM.UndoParams): Promise<DOM.UndoResult | undefined>; /** * Returns iframe node that owns iframe with the given domain. */ getFrameOwner(params: DOM.GetFrameOwnerParams): Promise<DOM.GetFrameOwnerResult | undefined>; /** * Returns the container of the given node based on container query conditions. * If containerName is given, it will find the nearest container with a matching name; * otherwise it will find the nearest container regardless of its container name. */ getContainerForNode( params: DOM.GetContainerForNodeParams, ): Promise<DOM.GetContainerForNodeResult | undefined>; /** * Returns the descendants of a container query container that have * container queries against this container. */ getQueryingDescendantsForContainer( params: DOM.GetQueryingDescendantsForContainerParams, ): Promise<DOM.GetQueryingDescendantsForContainerResult | undefined>; /** * Fired when `Element`'s attribute is modified. */ on( event: 'attributeModified', listener: (event: DOM.AttributeModifiedEvent) => void, ): IDisposable; /** * Fired when `Element`'s attribute is removed. */ on( event: 'attributeRemoved', listener: (event: DOM.AttributeRemovedEvent) => void, ): IDisposable; /** * Mirrors `DOMCharacterDataModified` event. */ on( event: 'characterDataModified', listener: (event: DOM.CharacterDataModifiedEvent) => void, ): IDisposable; /** * Fired when `Container`'s child node count has changed. */ on( event: 'childNodeCountUpdated', listener: (event: DOM.ChildNodeCountUpdatedEvent) => void, ): IDisposable; /** * Mirrors `DOMNodeInserted` event. */ on( event: 'childNodeInserted', listener: (event: DOM.ChildNodeInsertedEvent) => void, ): IDisposable; /** * Mirrors `DOMNodeRemoved` event. */ on( event: 'childNodeRemoved', listener: (event: DOM.ChildNodeRemovedEvent) => void, ): IDisposable; /** * Called when distribution is changed. */ on( event: 'distributedNodesUpdated', listener: (event: DOM.DistributedNodesUpdatedEvent) => void, ): IDisposable; /** * Fired when `Document` has been totally updated. Node ids are no longer valid. */ on(event: 'documentUpdated', listener: (event: DOM.DocumentUpdatedEvent) => void): IDisposable; /** * Fired when `Element`'s inline style is modified via a CSS property modification. */ on( event: 'inlineStyleInvalidated', listener: (event: DOM.InlineStyleInvalidatedEvent) => void, ): IDisposable; /** * Called when a pseudo element is added to an element. */ on( event: 'pseudoElementAdded', listener: (event: DOM.PseudoElementAddedEvent) => void, ): IDisposable; /** * Called when a pseudo element is removed from an element. */ on( event: 'pseudoElementRemoved', listener: (event: DOM.PseudoElementRemovedEvent) => void, ): IDisposable; /** * Fired when backend wants to provide client with the missing DOM structure. This happens upon * most of the calls requesting node ids. */ on(event: 'setChildNodes', listener: (event: DOM.SetChildNodesEvent) => void): IDisposable; /** * Called when shadow root is popped from the element. */ on( event: 'shadowRootPopped', listener: (event: DOM.ShadowRootPoppedEvent) => void, ): IDisposable; /** * Called when shadow root is pushed into the element. */ on( event: 'shadowRootPushed', listener: (event: DOM.ShadowRootPushedEvent) => void, ): IDisposable; } /** * Types of the 'DOM' domain. */ export namespace DOM { /** * Parameters of the 'DOM.collectClassNamesFromSubtree' method. */ export interface CollectClassNamesFromSubtreeParams { /** * Id of the node to collect class names. */ nodeId: NodeId; } /** * Return value of the 'DOM.collectClassNamesFromSubtree' method. */ export interface CollectClassNamesFromSubtreeResult { /** * Class name list. */ classNames: string[]; } /** * Parameters of the 'DOM.copyTo' method. */ export interface CopyToParams { /** * Id of the node to copy. */ nodeId: NodeId; /** * Id of the element to drop the copy into. */ targetNodeId: NodeId; /** * Drop the copy before this node (if absent, the copy becomes the last child of * `targetNodeId`). */ insertBeforeNodeId?: NodeId; } /** * Return value of the 'DOM.copyTo' method. */ export interface CopyToResult { /** * Id of the node clone. */ nodeId: NodeId; } /** * Parameters of the 'DOM.describeNode' method. */ export interface DescribeNodeParams { /** * Identifier of the node. */ nodeId?: NodeId; /** * Identifier of the backend node. */ backendNodeId?: BackendNodeId; /** * JavaScript object id of the node wrapper. */ objectId?: Runtime.RemoteObjectId; /** * The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the * entire subtree or provide an integer larger than 0. */ depth?: integer; /** * Whether or not iframes and shadow roots should be traversed when returning the subtree * (default is false). */ pierce?: boolean; } /** * Return value of the 'DOM.describeNode' method. */ export interface DescribeNodeResult { /** * Node description. */ node: Node; } /** * Parameters of the 'DOM.scrollIntoViewIfNeeded' method. */ export interface ScrollIntoViewIfNeededParams { /** * Identifier of the node. */ nodeId?: NodeId; /** * Identifier of the backend node. */ backendNodeId?: BackendNodeId; /** * JavaScript object id of the node wrapper. */ objectId?: Runtime.RemoteObjectId; /** * The rect to be scrolled into view, relative to the node's border box, in CSS pixels. * When omitted, center of the node will be used, similar to Element.scrollIntoView. */ rect?: Rect; } /** * Return value of the 'DOM.scrollIntoViewIfNeeded' method. */ export interface ScrollIntoViewIfNeededResult {} /** * Parameters of the 'DOM.disable' method. */ export interface DisableParams {} /** * Return value of the 'DOM.disable' method. */ export interface DisableResult {} /** * Parameters of the 'DOM.discardSearchResults' method. */ export interface DiscardSearchResultsParams { /** * Unique search session identifier. */ searchId: string; } /** * Return value of the 'DOM.discardSearchResults' method. */ export interface DiscardSearchResultsResult {} /** * Parameters of the 'DOM.enable' method. */ export interface EnableParams {} /** * Return value of the 'DOM.enable' method. */ export interface EnableResult {} /** * Parameters of the 'DOM.focus' method. */ export interface FocusParams { /** * Identifier of the node. */ nodeId?: NodeId; /** * Identifier of the backend node. */ backendNodeId?: BackendNodeId; /** * JavaScript object id of the node wrapper. */ objectId?: Runtime.RemoteObjectId; } /** * Return value of the 'DOM.focus' method. */ export interface FocusResult {} /** * Parameters of the 'DOM.getAttributes' method. */ export interface GetAttributesParams { /** * Id of the node to retrieve attibutes for. */ nodeId: NodeId; } /** * Return value of the 'DOM.getAttributes' method. */ export interface GetAttributesResult { /** * An interleaved array of node attribute names and values. */ attributes: string[]; } /** * Parameters of the 'DOM.getBoxModel' method. */ export interface GetBoxModelParams { /** * Identifier of the node. */ nodeId?: NodeId; /** * Identifier of the backend node. */ backendNodeId?: BackendNodeId; /** * JavaScript object id of the node wrapper. */ objectId?: Runtime.RemoteObjectId; } /** * Return value of the 'DOM.getBoxModel' method. */ export interface GetBoxModelResult { /** * Box model for the node. */ model: BoxModel; } /** * Parameters of the 'DOM.getContentQuads' method. */ export interface GetContentQuadsParams { /** * Identifier of the node. */ nodeId?: NodeId; /** * Identifier of the backend node. */ backendNodeId?: BackendNodeId; /** * JavaScript object id of the node wrapper. */ objectId?: Runtime.RemoteObjectId; } /** * Return value of the 'DOM.getContentQuads' method. */ export interface GetContentQuadsResult { /** * Quads that describe node layout relative to viewport. */ quads: Quad[]; } /** * Parameters of the 'DOM.getDocument' method. */ export interface GetDocumentParams { /** * The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the * entire subtree or provide an integer larger than 0. */ depth?: integer; /** * Whether or not iframes and shadow roots should be traversed when returning the subtree * (default is false). */ pierce?: boolean; } /** * Return value of the 'DOM.getDocument' method. */ export interface GetDocumentResult { /** * Resulting node. */ root: Node; } /** * Parameters of the 'DOM.getFlattenedDocument' method. */ export interface GetFlattenedDocumentParams { /** * The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the * entire subtree or provide an integer larger than 0. */ depth?: integer; /** * Whether or not iframes and shadow roots should be traversed when returning the subtree * (default is false). */ pierce?: boolean; } /** * Return value of the 'DOM.getFlattenedDocument' method. */ export interface GetFlattenedDocumentResult { /** * Resulting node. */ nodes: Node[]; } /** * Parameters of the 'DOM.getNodesForSubtreeByStyle' method. */ export interface GetNodesForSubtreeByStyleParams { /** * Node ID pointing to the root of a subtree. */ nodeId: NodeId; /** * The style to filter nodes by (includes nodes if any of properties matches). */ computedStyles: CSSComputedStyleProperty[]; /** * Whether or not iframes and shadow roots in the same target should be traversed when returning the * results (default is false). */ pierce?: boolean; } /** * Return value of the 'DOM.getNodesForSubtreeByStyle' method. */ export interface GetNodesForSubtreeByStyleResult { /** * Resulting nodes. */ nodeIds: NodeId[]; } /** * Parameters of the 'DOM.getNodeForLocation' method. */ export interface GetNodeForLocationParams { /** * X coordinate. */ x: integer; /** * Y coordinate. */ y: integer; /** * False to skip to the nearest non-UA shadow root ancestor (default: false). */ includeUserAgentShadowDOM?: boolean; /** * Whether to ignore pointer-events: none on elements and hit test them. */ ignorePointerEventsNone?: boolean; } /** * Return value of the 'DOM.getNodeForLocation' method. */ export interface GetNodeForLocationResult { /** * Resulting node. */ backendNodeId: BackendNodeId; /** * Frame this node belongs to. */ frameId: Page.FrameId; /** * Id of the node at given coordinates, only when enabled and requested document. */ nodeId?: NodeId; } /** * Parameters of the 'DOM.getOuterHTML' method. */ export interface GetOuterHTMLParams { /** * Identifier of the node. */ nodeId?: NodeId; /** * Identifier of the backend node. */ backendNodeId?: BackendNodeId; /** * JavaScript object id of the node wrapper. */ objectId?: Runtime.RemoteObjectId; } /** * Return value of the 'DOM.getOuterHTML' method. */ export interface GetOuterHTMLResult { /** * Outer HTML markup. */ outerHTML: string; } /** * Parameters of the 'DOM.getRelayoutBoundary' method. */ export interface GetRelayoutBoundaryParams { /** * Id of the node. */ nodeId: NodeId; } /** * Return value of the 'DOM.getRelayoutBoundary' method. */ export interface GetRelayoutBoundaryResult { /** * Relayout boundary node id for the given node. */ nodeId: NodeId; } /** * Parameters of the 'DOM.getSearchResults' method. */ export interface GetSearchResultsParams { /** * Unique search session identifier. */ searchId: string; /** * Start index of the search result to be returned. */ fromIndex: integer; /** * End index of the search result to be returned. */ toIndex: integer; } /** * Return value of the 'DOM.getSearchResults' method. */ export interface GetSearchResultsResult { /** * Ids of the search result nodes. */ nodeIds: NodeId[]; } /** * Parameters of the 'DOM.hideHighlight' method. */ export interface HideHighlightParams {} /** * Return value of the 'DOM.hideHighlight' method. */ export interface HideHighlightResult {} /** * Parameters of the 'DOM.highlightNode' method. */ export interface HighlightNodeParams {} /** * Return value of the 'DOM.highlightNode' method. */ export interface HighlightNodeResult {} /** * Parameters of the 'DOM.highlightRect' method. */ export interface HighlightRectParams {} /** * Return value of the 'DOM.highlightRect' method. */ export interface HighlightRectResult {} /** * Parameters of the 'DOM.markUndoableState' method. */ export interface MarkUndoableStateParams {} /** * Return value of the 'DOM.markUndoableState' method. */ export interface MarkUndoableStateResult {} /** * Parameters of the 'DOM.moveTo' method. */ export interface MoveToParams { /** * Id of the node to move. */ nodeId: NodeId; /** * Id of the element to drop the moved node into. */ targetNodeId: NodeId; /** * Drop node before this one (if absent, the moved node becomes the last child of * `targetNodeId`). */ insertBeforeNodeId?: NodeId; } /** * Return value of the 'DOM.moveTo' method. */ export interface MoveToResult { /** * New id of the moved node. */ nodeId: NodeId; } /** * Parameters of the 'DOM.performSearch' method. */ export interface PerformSearchParams { /** * Plain text or query selector or XPath search query. */ query: string; /** * True to search in user agent shadow DOM. */ includeUserAgentShadowDOM?: boolean; } /** * Return value of the 'DOM.performSearch' method. */ export interface PerformSearchResult { /** * Unique search session identifier. */ searchId: string; /** * Number of search results. */ resultCount: integer; } /** * Parameters of the 'DOM.pushNodeByPathToFrontend' method. */ export interface PushNodeByPathToFrontendParams { /** * Path to node in the proprietary format. */ path: string; } /** * Return value of the 'DOM.pushNodeByPathToFrontend' method. */ export interface PushNodeByPathToFrontendResult { /** * Id of the node for given path. */ nodeId: NodeId; } /** * Parameters of the 'DOM.pushNodesByBackendIdsToFrontend' method. */ export interface PushNodesByBackendIdsToFrontendParams { /** * The array of backend node ids. */ backendNodeIds: BackendNodeId[]; } /** * Return value of the 'DOM.pushNodesByBackendIdsToFrontend' method. */ export interface PushNodesByBackendIdsToFrontendResult { /** * The array of ids of pushed nodes that correspond to the backend ids specified in * backendNodeIds. */ nodeIds: NodeId[]; } /** * Parameters of the 'DOM.querySelector' method. */ export interface QuerySelectorParams { /** * Id of the node to query upon. */ nodeId: NodeId; /** * Selector string. */ selector: string; } /** * Return value of the 'DOM.querySelector' method. */ export interface QuerySelectorResult { /** * Query selector result. */ nodeId: NodeId; } /** * Parameters of the 'DOM.querySelectorAll' method. */ export interface QuerySelectorAllParams { /** * Id of the node to query upon. */ nodeId: NodeId; /** * Selector string. */ selector: string; } /** * Return value of the 'DOM.querySelectorAll' method. */ export interface QuerySelectorAllResult { /** * Query selector result. */ nodeIds: NodeId[]; } /** * Parameters of the 'DOM.redo' method. */ export interface RedoParams {} /** * Return value of the 'DOM.redo' method. */ export interface RedoResult {} /** * Parameters of the 'DOM.removeAttribute' method. */ export interface RemoveAttributeParams { /** * Id of the element to remove attribute from. */ nodeId: NodeId; /** * Name of the attribute to remove. */ name: string; } /** * Return value of the 'DOM.removeAttribute' method. */ export interface RemoveAttributeResult {} /** * Parameters of the 'DOM.removeNode' method. */ export interface RemoveNodeParams { /** * Id of the node to remove. */ nodeId: NodeId; } /** * Return value of the 'DOM.removeNode' method. */ export interface RemoveNodeResult {} /** * Parameters of the 'DOM.requestChildNodes' method. */ export interface RequestChildNodesParams { /** * Id of the node to get children for. */ nodeId: NodeId; /** * The maximum depth at which children should be retrieved, defaults to 1. Use -1 for the * entire subtree or provide an integer larger than 0. */ depth?: integer; /** * Whether or not iframes and shadow roots should be traversed when returning the sub-tree * (default is false). */ pierce?: boolean; } /** * Return value of the 'DOM.requestChildNodes' method. */ export interface RequestChildNodesResult {} /** * Parameters of the 'DOM.requestNode' method. */ export interface RequestNodeParams { /** * JavaScript object id to convert into node. */ objectId: Runtime.RemoteObjectId; } /** * Return value of the 'DOM.requestNode' method. */ export interface RequestNodeResult { /** * Node id for given object. */ nodeId: NodeId; } /** * Parameters of the 'DOM.resolveNode' method. */ export interface ResolveNodeParams { /** * Id of the node to resolve. */ nodeId?: NodeId; /** * Backend identifier of the node to resolve. */ backendNodeId?: DOM.BackendNodeId; /** * Symbolic group name that can be used to release multiple objects. */ objectGroup?: string; /** * Execution context in which to resolve the node. */ executionContextId?: Runtime.ExecutionContextId; } /** * Return value of the 'DOM.resolveNode' method. */ export interface ResolveNodeResult { /** * JavaScript object wrapper for given node. */ object: Runtime.RemoteObject; } /** * Parameters of the 'DOM.setAttributeValue' method. */ export interface SetAttributeValueParams { /** * Id of the element to set attribute for. */ nodeId: NodeId; /** * Attribute name. */ name: string; /** * Attribute value. */ value: string; } /** * Return value of the 'DOM.setAttributeValue' method. */ export interface SetAttributeValueResult {} /** * Parameters of the 'DOM.setAttributesAsText' method. */ export interface SetAttributesAsTextParams { /** * Id of the element to set attributes for. */ nodeId: NodeId; /** * Text with a number of attributes. Will parse this text using HTML parser. */ text: string; /** * Attribute name to replace with new attributes derived from text in case text parsed * successfully. */ name?: string; } /** * Return value of the 'DOM.setAttributesAsText' method. */ export interface SetAttributesAsTextResult {} /** * Parameters of the 'DOM.setFileInputFiles' method. */ export interface SetFileInputFilesParams { /** * Array of file paths to set. */ files: string[]; /** * Identifier of the node. */ nodeId?: NodeId; /** * Identifier of the backend node. */ backendNodeId?: BackendNodeId; /** * JavaScript object id of the node wrapper. */ objectId?: Runtime.RemoteObjectId; } /** * Return value of the 'DOM.setFileInputFiles' method. */ export interface SetFileInputFilesResult {} /** * Parameters of the 'DOM.setNodeStackTracesEnabled' method. */ export interface SetNodeStackTracesEnabledParams { /** * Enable or disable. */ enable: boolean; } /** * Return value of the 'DOM.setNodeStackTracesEnabled' method. */ export interface SetNodeStackTracesEnabledResult {} /** * Parameters of the 'DOM.getNodeStackTraces' method. */ export interface GetNodeStackTracesParams { /** * Id of the node to get stack traces for. */ nodeId: NodeId; } /** * Return value of the 'DOM.getNodeStackTraces' method. */ export interface GetNodeStackTracesResult { /** * Creation stack trace, if available. */ creation?: Runtime.StackTrace; } /** * Parameters of the 'DOM.getFileInfo' method. */ export interface GetFileInfoParams { /** * JavaScript object id of the node wrapper. */ objectId: Runtime.RemoteObjectId; } /** * Return value of the 'DOM.getFileInfo' method. */ export interface GetFileInfoResult { path: string; } /** * Parameters of the 'DOM.setInspectedNode' method. */ export interface SetInspectedNodeParams { /** * DOM node id to be accessible by means of $x command line API. */ nodeId: NodeId; } /** * Return value of the 'DOM.setInspectedNode' method. */ export interface SetInspectedNodeResult {} /** * Parameters of the 'DOM.setNodeName' method. */ export interface SetNodeNameParams { /** * Id of the node to set name for. */ nodeId: NodeId; /** * New node's name. */ name: string; } /** * Return value of the 'DOM.setNodeName' method. */ export interface SetNodeNameResult { /** * New node's id. */ nodeId: NodeId; } /** * Parameters of the 'DOM.setNodeValue' method. */ export interface SetNodeValueParams { /** * Id of the node to set value for. */ nodeId: NodeId; /** * New node's value. */ value: string; } /** * Return value of the 'DOM.setNodeValue' method. */ export interface SetNodeValueResult {} /** * Parameters of the 'DOM.setOuterHTML' method. */ export interface SetOuterHTMLParams { /** * Id of the node to set markup for. */ nodeId: NodeId; /** * Outer HTML markup to set. */ outerHTML: string; } /** * Return value of the 'DOM.setOuterHTML' method. */ export interface SetOuterHTMLResult {} /** * Parameters of the 'DOM.undo' method. */ export interface UndoParams {} /** * Return value of the 'DOM.undo' method. */ export interface UndoResult {} /** * Parameters of the 'DOM.getFrameOwner' method. */ export interface GetFrameOwnerParams { frameId: Page.FrameId; } /** * Return value of the 'DOM.getFrameOwner' method. */ export interface GetFrameOwnerResult { /** * Resulting node. */ backendNodeId: BackendNodeId; /** * Id of the node at given coordinates, only when enabled and requested document. */ nodeId?: NodeId; } /** * Parameters of the 'DOM.getContainerForNode' method. */ export interface GetContainerForNodeParams { nodeId: NodeId; containerName?: string; } /** * Return value of the 'DOM.getContainerForNode' method. */ export interface GetContainerForNodeResult { /** * The container node for the given node, or null if not found. */ nodeId?: NodeId; } /** * Parameters of the 'DOM.getQueryingDescendantsForContainer' method. */ export interface GetQueryingDescendantsForContainerParams { /** * Id of the container node to find querying descendants from. */ nodeId: NodeId; } /** * Return value of the 'DOM.getQueryingDescendantsForContainer' method. */ export interface GetQueryingDescendantsForContainerResult { /** * Descendant nodes with container queries against the given container. */ nodeIds: NodeId[]; } /** * Parameters of the 'DOM.attributeModified' event. */ export interface AttributeModifiedEvent { /** * Id of the node that has changed. */ nodeId: NodeId; /** * Attribute name. */ name: string; /** * Attribute value. */ value: string; } /** * Parameters of the 'DOM.attributeRemoved' event. */ export interface AttributeRemovedEvent { /** * Id of the node that has changed. */ nodeId: NodeId; /** * A ttribute name. */ name: string; } /** * Parameters of the 'DOM.characterDataModified' event. */ export interface CharacterDataModifiedEvent { /** * Id of the node that has changed. */ nodeId: NodeId; /** * New text value. */ characterData: string; } /** * Parameters of the 'DOM.childNodeCountUpdated' event. */ export interface ChildNodeCountUpdatedEvent { /** * Id of the node that has changed. */ nodeId: NodeId; /** * New node count. */ childNodeCount: integer; } /** * Parameters of the 'DOM.childNodeInserted' event. */ export interface ChildNodeInsertedEvent { /** * Id of the node that has changed. */ parentNodeId: NodeId; /** * If of the previous siblint. */ previousNodeId: NodeId; /** * Inserted node data. */ node: Node; } /** * Parameters of the 'DOM.childNodeRemoved' event. */ export interface ChildNodeRemovedEvent { /** * Parent id. */ parentNodeId: NodeId; /** * Id of the node that has been removed. */ nodeId: NodeId; } /** * Parameters of the 'DOM.distributedNodesUpdated' event. */ export interface DistributedNodesUpdatedEvent { /** * Insertion point where distributed nodes were updated. */ insertionPointId: NodeId; /** * Distributed nodes for given insertion point. */ distributedNodes: BackendNode[]; } /** * Parameters of the 'DOM.documentUpdated' event. */ export interface DocumentUpdatedEvent {} /** * Parameters of the 'DOM.inlineStyleInvalidated' event. */ export interface InlineStyleInvalidatedEvent { /** * Ids of the nodes for which the inline styles have been invalidated. */ nodeIds: NodeId[]; } /** * Parameters of the 'DOM.pseudoElementAdded' event. */ export interface PseudoElementAddedEvent { /** * Pseudo element's parent element id. */ parentId: NodeId; /** * The added pseudo element. */ pseudoElement: Node; } /** * Parameters of the 'DOM.pseudoElementRemoved' event. */ export interface PseudoElementRemovedEvent { /** * Pseudo element's parent element id. */ parentId: NodeId; /** * The removed pseudo element id. */ pseudoElementId: NodeId; } /** * Parameters of the 'DOM.setChildNodes' event. */ export interface SetChildNodesEvent { /** * Parent node id to populate with children. */ parentId: NodeId; /** * Child nodes array. */ nodes: Node[]; } /** * Parameters of the 'DOM.shadowRootPopped' event. */ export interface ShadowRootPoppedEvent { /** * Host element id. */ hostId: NodeId; /** * Shadow root id. */ rootId: NodeId; } /** * Parameters of the 'DOM.shadowRootPushed' event. */ export interface ShadowRootPushedEvent { /** * Host element id. */ hostId: NodeId; /** * Shadow root. */ root: Node; } /** * Unique DOM node identifier. */ export type NodeId = integer; /** * Unique DOM node identifier used to reference a node that may not have been pushed to the * front-end. */ export type BackendNodeId = integer; /** * Backend node with a friendly name. */ export interface BackendNode { /** * `Node`'s nodeType. */ nodeType: integer; /** * `Node`'s nodeName. */ nodeName: string; backendNodeId: BackendNodeId; } /** * Pseudo element type. */ export type PseudoType = | 'first-line' | 'first-letter' | 'before' | 'after' | 'marker' | 'backdrop' | 'selection' | 'target-text' | 'spelling-error' | 'grammar-error' | 'highlight' | 'first-line-inherited' | 'scrollbar' | 'scrollbar-thumb' | 'scrollbar-button' | 'scrollbar-track' | 'scrollbar-track-piece' | 'scrollbar-corner' | 'resizer' | 'input-list-button'; /** * Shadow root type. */ export type ShadowRootType = 'user-agent' | 'open' | 'closed'; /** * Document compatibility mode. */ export type CompatibilityMode = 'QuirksMode' | 'LimitedQuirksMode' | 'NoQuirksMode'; /** * DOM interaction is implemented in terms of mirror objects that represent the actual DOM nodes. * DOMNode is a base node mirror type. */ export interface Node { /** * Node identifier that is passed into the rest of the DOM messages as the `nodeId`. Backend * will only push node with given `id` once. It is aware of all requested nodes and will only * fire DOM events for nodes known to the client. */ nodeId: NodeId; /** * The id of the parent node if any. */ parentId?: NodeId; /** * The BackendNodeId for this node. */ backendNodeId: BackendNodeId; /** * `Node`'s nodeType. */ nodeType: integer; /** * `Node`'s nodeName. */ nodeName: string; /** * `Node`'s localName. */ localName: string; /** * `Node`'s nodeValue. */ nodeValue: string; /** * Child count for `Container` nodes. */ childNodeCount?: integer; /** * Child nodes of this node when requested with children. */ children?: Node[]; /** * Attributes of the `Element` node in the form of flat array `[name1, value1, name2, value2]`. */ attributes?: string[]; /** * Document URL that `Document` or `FrameOwner` node points to. */ documentURL?: string; /** * Base URL that `Document` or `FrameOwner` node uses for URL completion. */ baseURL?: string; /** * `DocumentType`'s publicId. */ publicId?: string; /** * `DocumentType`'s systemId. */ systemId?: string; /** * `DocumentType`'s internalSubset. */ internalSubset?: string; /** * `Document`'s XML version in case of XML documents. */ xmlVersion?: string; /** * `Attr`'s name. */ name?: string; /** * `Attr`'s value. */ value?: string; /** * Pseudo element type for this node. */ pseudoType?: PseudoType; /** * Shadow root type. */ shadowRootType?: ShadowRootType; /** * Frame ID for frame owner elements. */ frameId?: Page.FrameId; /** * Content document for frame owner elements. */ contentDocument?: Node; /** * Shadow root list for given element host. */ shadowRoots?: Node[]; /** * Content document fragment for template elements. */ templateContent?: Node; /** * Pseudo elements associated with this node. */ pseudoElements?: Node[]; /** * Deprecated, as the HTML Imports API has been removed (crbug.com/937746). * This property used to return the imported document for the HTMLImport links. * The property is always undefined now. * @deprecated */ importedDocument?: Node; /** * Distributed nodes for given insertion point. */ distributedNodes?: BackendNode[]; /** * Whether the node is SVG. */ isSVG?: boolean; compatibilityMode?: CompatibilityMode; } /** * A structure holding an RGBA color. */ export interface RGBA { /** * The red component, in the [0-255] range. */ r: integer; /** * The green component, in the [0-255] range. */ g: integer; /** * The blue component, in the [0-255] range. */ b: integer; /** * The alpha component, in the [0-1] range (default: 1). */ a?: number; } /** * An array of quad vertices, x immediately followed by y for each point, points clock-wise. */ export type Quad = number[]; /** * Box model. */ export interface BoxModel { /** * Content box */ content: Quad; /** * Padding box */ padding: Quad; /** * Border box */ border: Quad; /** * Margin box */ margin: Quad; /** * Node width */ width: integer; /** * Node height */ height: integer; /** * Shape outside coordinates */ shapeOutside?: ShapeOutsideInfo; } /** * CSS Shape Outside details. */ export interface ShapeOutsideInfo { /** * Shape bounds */ bounds: Quad; /** * Shape coordinate details */ shape: any[]; /** * Margin shape bounds */ marginShape: any[]; } /** * Rectangle. */ export interface Rect { /** * X coordinate */ x: number; /** * Y coordinate */ y: number; /** * Rectangle width */ width: number; /** * Rectangle height */ height: number; } export interface CSSComputedStyleProperty { /** * Computed style property name. */ name: string; /** * Computed style property value. */ value: string; } } /** * Methods and events of the 'DOMDebugger' domain. */ export interface DOMDebuggerApi { /** * Returns event listeners of the given object. */ getEventListeners( params: DOMDebugger.GetEventListenersParams, ): Promise<DOMDebugger.GetEventListenersResult | undefined>; /** * Removes DOM breakpoint that was set using `setDOMBreakpoint`. */ removeDOMBreakpoint( params: DOMDebugger.RemoveDOMBreakpointParams, ): Promise<DOMDebugger.RemoveDOMBreakpointResult | undefined>; /** * Removes breakpoint on particular DOM event. */ removeEventListenerBreakpoint( params: DOMDebugger.RemoveEventListenerBreakpointParams, ): Promise<DOMDebugger.RemoveEventListenerBreakpointResult | undefined>; /** * Removes breakpoint on particular native event. */ removeInstrumentationBreakpoint( params: DOMDebugger.RemoveInstrumentationBreakpointParams, ): Promise<DOMDebugger.RemoveInstrumentationBreakpointResult | undefined>; /** * Removes breakpoint from XMLHttpRequest. */ removeXHRBreakpoint( params: DOMDebugger.RemoveXHRBreakpointParams, ): Promise<DOMDebugger.RemoveXHRBreakpointResult | undefined>; /** * Sets breakpoint on particular CSP violations. */ setBreakOnCSPViolation( params: DOMDebugger.SetBreakOnCSPViolationParams, ): Promise<DOMDebugger.SetBreakOnCSPViolationResult | undefined>; /** * Sets breakpoint on particular operation with DOM. */ setDOMBreakpoint( params: DOMDebugger.SetDOMBreakpointParams, ): Promise<DOMDebugger.SetDOMBreakpointResult | undefined>; /** * Sets breakpoint on particular DOM event. */ setEventListenerBreakpoint( params: DOMDebugger.SetEventListenerBreakpointParams, ): Promise<DOMDebugger.SetEventListenerBreakpointResult | undefined>; /** * Sets breakpoint on particular native event. */ setInstrumentationBreakpoint( params: DOMDebugger.SetInstrumentationBreakpointParams, ): Promise<DOMDebugger.SetInstrumentationBreakpointResult | undefined>; /** * Sets breakpoint on XMLHttpRequest. */ setXHRBreakpoint( params: DOMDebugger.SetXHRBreakpointParams, ): Promise<DOMDebugger.SetXHRBreakpointResult | undefined>; } /** * Types of the 'DOMDebugger' domain. */ export namespace DOMDebugger { /** * Parameters of the 'DOMDebugger.getEventListeners' method. */ export interface GetEventListenersParams { /** * Identifier of the object to return listeners for. */ objectId: Runtime.RemoteObjectId; /** * The maximum depth at which Node children should be retrieved, defaults to 1. Use -1 for the * entire subtree or provide an integer larger than 0. */ depth?: integer; /** * Whether or not iframes and shadow roots should be traversed when returning the subtree * (default is false). Reports listeners for all contexts if pierce is enabled. */ pierce?: boolean; } /** * Return value of the 'DOMDebugger.getEventListeners' method. */ export interface GetEventListenersResult { /** * Array of relevant listeners. */ listeners: EventListener[]; } /** * Parameters of the 'DOMDebugger.removeDOMBreakpoint' method. */ export interface RemoveDOMBreakpointParams { /** * Identifier of the node to remove breakpoint from. */ nodeId: DOM.NodeId; /** * Type of the breakpoint to remove. */ type: DOMBreakpointType; } /** * Return value of the 'DOMDebugger.removeDOMBreakpoint' method. */ export interface RemoveDOMBreakpointResult {} /** * Parameters of the 'DOMDebugger.removeEventListenerBreakpoint' method. */ export interface RemoveEventListenerBreakpointParams { /** * Event name. */ eventName: string; /** * EventTarget interface name. */ targetName?: string; } /** * Return value of the 'DOMDebugger.removeEventListenerBreakpoint' method. */ export interface RemoveEventListenerBreakpointResult {} /** * Parameters of the 'DOMDebugger.removeInstrumentationBreakpoint' method. */ export interface RemoveInstrumentationBreakpointParams { /** * Instrumentation name to stop on. */ eventName: string; } /** * Return value of the 'DOMDebugger.removeInstrumentationBreakpoint' method. */ export interface RemoveInstrumentationBreakpointResult {} /** * Parameters of the 'DOMDebugger.removeXHRBreakpoint' method. */ export interface RemoveXHRBreakpointParams { /** * Resource URL substring. */ url: string; } /** * Return value of the 'DOMDebugger.removeXHRBreakpoint' method. */ export interface RemoveXHRBreakpointResult {} /** * Parameters of the 'DOMDebugger.setBreakOnCSPViolation' method. */ export interface SetBreakOnCSPViolationParams { /** * CSP Violations to stop upon. */ violationTypes: CSPViolationType[]; } /** * Return value of the 'DOMDebugger.setBreakOnCSPViolation' method. */ export interface SetBreakOnCSPViolationResult {} /** * Parameters of the 'DOMDebugger.setDOMBreakpoint' method. */ export interface SetDOMBreakpointParams { /** * Identifier of the node to set breakpoint on. */ nodeId: DOM.NodeId; /** * Type of the operation to stop upon. */ type: DOMBreakpointType; } /** * Return value of the 'DOMDebugger.setDOMBreakpoint' method. */ export interface SetDOMBreakpointResult {} /** * Parameters of the 'DOMDebugger.setEventListenerBreakpoint' method. */ export interface SetEventListenerBreakpointParams { /** * DOM Event name to stop on (any DOM event will do). */ eventName: string; /** * EventTarget interface name to stop on. If equal to `"*"` or not provided, will stop on any * EventTarget. */ targetName?: string; } /** * Return value of the 'DOMDebugger.setEventListenerBreakpoint' method. */ export interface SetEventListenerBreakpointResult {} /** * Parameters of the 'DOMDebugger.setInstrumentationBreakpoint' method. */ export interface SetInstrumentationBreakpointParams { /** * Instrumentation name to stop on. */ eventName: string; } /** * Return value of the 'DOMDebugger.setInstrumentationBreakpoint' method. */ export interface SetInstrumentationBreakpointResult {} /** * Parameters of the 'DOMDebugger.setXHRBreakpoint' method. */ export interface SetXHRBreakpointParams { /** * Resource URL substring. All XHRs having this substring in the URL will get stopped upon. */ url: string; } /** * Return value of the 'DOMDebugger.setXHRBreakpoint' method. */ export interface SetXHRBreakpointResult {} /** * DOM breakpoint type. */ export type DOMBreakpointType = 'subtree-modified' | 'attribute-modified' | 'node-removed'; /** * CSP Violation type. */ export type CSPViolationType = 'trustedtype-sink-violation' | 'trustedtype-policy-violation'; /** * Object event listener. */ export interface EventListener { /** * `EventListener`'s type. */ type: string; /** * `EventListener`'s useCapture. */ useCapture: boolean; /** * `EventListener`'s passive flag. */ passive: boolean; /** * `EventListener`'s once flag. */ once: boolean; /** * Script id of the handler code. */ scriptId: Runtime.ScriptId; /** * Line number in the script (0-based). */ lineNumber: integer; /** * Column number in the script (0-based). */ columnNumber: integer; /** * Event handler function value. */ handler?: Runtime.RemoteObject; /** * Event original handler function value. */ originalHandler?: Runtime.RemoteObject; /** * Node the listener is added to (if any). */ backendNodeId?: DOM.BackendNodeId; } } /** * Methods and events of the 'DOMSnapshot' domain. */ export interface DOMSnapshotApi { /** * Disables DOM snapshot agent for the given page. */ disable(params: DOMSnapshot.DisableParams): Promise<DOMSnapshot.DisableResult | undefined>; /** * Enables DOM snapshot agent for the given page. */ enable(params: DOMSnapshot.EnableParams): Promise<DOMSnapshot.EnableResult | undefined>; /** * Returns a document snapshot, including the full DOM tree of the root node (including iframes, * template contents, and imported documents) in a flattened array, as well as layout and * white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is * flattened. * @deprecated */ getSnapshot( params: DOMSnapshot.GetSnapshotParams, ): Promise<DOMSnapshot.GetSnapshotResult | undefined>; /** * Returns a document snapshot, including the full DOM tree of the root node (including iframes, * template contents, and imported documents) in a flattened array, as well as layout and * white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is * flattened. */ captureSnapshot( params: DOMSnapshot.CaptureSnapshotParams, ): Promise<DOMSnapshot.CaptureSnapshotResult | undefined>; } /** * Types of the 'DOMSnapshot' domain. */ export namespace DOMSnapshot { /** * Parameters of the 'DOMSnapshot.disable' method. */ export interface DisableParams {} /** * Return value of the 'DOMSnapshot.disable' method. */ export interface DisableResult {} /** * Parameters of the 'DOMSnapshot.enable' method. */ export interface EnableParams {} /** * Return value of the 'DOMSnapshot.enable' method. */ export interface EnableResult {} /** * Parameters of the 'DOMSnapshot.getSnapshot' method. */ export interface GetSnapshotParams { /** * Whitelist of computed styles to return. */ computedStyleWhitelist: string[]; /** * Whether or not to retrieve details of DOM listeners (default false). */ includeEventListeners?: boolean; /** * Whether to determine and include the paint order index of LayoutTreeNodes (default false). */ includePaintOrder?: boolean; /** * Whether to include UA shadow tree in the snapshot (default false). */ includeUserAgentShadowTree?: boolean; } /** * Return value of the 'DOMSnapshot.getSnapshot' method. */ export interface GetSnapshotResult { /** * The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document. */ domNodes: DOMNode[]; /** * The nodes in the layout tree. */ layoutTreeNodes: LayoutTreeNode[]; /** * Whitelisted ComputedStyle properties for each node in the layout tree. */ computedStyles: ComputedStyle[]; } /** * Parameters of the 'DOMSnapshot.captureSnapshot' method. */ export interface CaptureSnapshotParams { /** * Whitelist of computed styles to return. */ computedStyles: string[]; /** * Whether to include layout object paint orders into the snapshot. */ includePaintOrder?: boolean; /** * Whether to include DOM rectangles (offsetRects, clientRects, scrollRects) into the snapshot */ includeDOMRects?: boolean; /** * Whether to include blended background colors in the snapshot (default: false). * Blended background color is achieved by blending background colors of all elements * that overlap with the current element. */ includeBlendedBackgroundColors?: boolean; /** * Whether to include text color opacity in the snapshot (default: false). * An element might have the opacity property set that affects the text color of the element. * The final text color opacity is computed based on the opacity of all overlapping elements. */ includeTextColorOpacities?: boolean; } /** * Return value of the 'DOMSnapshot.captureSnapshot' method. */ export interface CaptureSnapshotResult { /** * The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document. */ documents: DocumentSnapshot[]; /** * Shared string table that all string properties refer to with indexes. */ strings: string[]; } /** * A Node in the DOM tree. */ export interface DOMNode { /** * `Node`'s nodeType. */ nodeType: integer; /** * `Node`'s nodeName. */ nodeName: string; /** * `Node`'s nodeValue. */ nodeValue: string; /** * Only set for textarea elements, contains the text value. */ textValue?: string; /** * Only set for input elements, contains the input's associated text value. */ inputValue?: string; /** * Only set for radio and checkbox input elements, indicates if the element has been checked */ inputChecked?: boolean; /** * Only set for option elements, indicates if the element has been selected */ optionSelected?: boolean; /** * `Node`'s id, corresponds to DOM.Node.backendNodeId. */ backendNodeId: DOM.BackendNodeId; /** * The indexes of the node's child nodes in the `domNodes` array returned by `getSnapshot`, if * any. */ childNodeIndexes?: integer[]; /** * Attributes of an `Element` node. */ attributes?: NameValue[]; /** * Indexes of pseudo elements associated with this node in the `domNodes` array returned by * `getSnapshot`, if any. */ pseudoElementIndexes?: integer[]; /** * The index of the node's related layout tree node in the `layoutTreeNodes` array returned by * `getSnapshot`, if any. */ layoutNodeIndex?: integer; /** * Document URL that `Document` or `FrameOwner` node points to. */ documentURL?: string; /** * Base URL that `Document` or `FrameOwner` node uses for URL completion. */ baseURL?: string; /** * Only set for documents, contains the document's content language. */ contentLanguage?: string; /** * Only set for documents, contains the document's character set encoding. */ documentEncoding?: string; /** * `DocumentType` node's publicId. */ publicId?: string; /** * `DocumentType` node's systemId. */ systemId?: string; /** * Frame ID for frame owner elements and also for the document node. */ frameId?: Page.FrameId; /** * The index of a frame owner element's content document in the `domNodes` array returned by * `getSnapshot`, if any. */ contentDocumentIndex?: integer; /** * Type of a pseudo element node. */ pseudoType?: DOM.PseudoType; /** * Shadow root type. */ shadowRootType?: DOM.ShadowRootType; /** * Whether this DOM node responds to mouse clicks. This includes nodes that have had click * event listeners attached via JavaScript as well as anchor tags that naturally navigate when * clicked. */ isClickable?: boolean; /** * Details of the node's event listeners, if any. */ eventListeners?: DOMDebugger.EventListener[]; /** * The selected url for nodes with a srcset attribute. */ currentSourceURL?: string; /** * The url of the script (if any) that generates this node. */ originURL?: string; /** * Scroll offsets, set when this node is a Document. */ scrollOffsetX?: number; scrollOffsetY?: number; } /** * Details of post layout rendered text positions. The exact layout should not be regarded as * stable and may change between versions. */ export interface InlineTextBox { /** * The bounding box in document coordinates. Note that scroll offset of the document is ignored. */ boundingBox: DOM.Rect; /** * The starting index in characters, for this post layout textbox substring. Characters that * would be represented as a surrogate pair in UTF-16 have length 2. */ startCharacterIndex: integer; /** * The number of characters in this post layout textbox substring. Characters that would be * represented as a surrogate pair in UTF-16 have length 2. */ numCharacters: integer; } /** * Details of an element in the DOM tree with a LayoutObject. */ export interface LayoutTreeNode { /** * The index of the related DOM node in the `domNodes` array returned by `getSnapshot`. */ domNodeIndex: integer; /** * The bounding box in document coordinates. Note that scroll offset of the document is ignored. */ boundingBox: DOM.Rect; /** * Contents of the LayoutText, if any. */ layoutText?: string; /** * The post-layout inline text nodes, if any. */ inlineTextNodes?: InlineTextBox[]; /** * Index into the `computedStyles` array returned by `getSnapshot`. */ styleIndex?: integer; /** * Global paint order index, which is determined by the stacking order of the nodes. Nodes * that are painted together will have the same index. Only provided if includePaintOrder in * getSnapshot was true. */ paintOrder?: integer; /** * Set to true to indicate the element begins a new stacking context. */ isStackingContext?: boolean; } /** * A subset of the full ComputedStyle as defined by the request whitelist. */ export interface ComputedStyle { /** * Name/value pairs of computed style properties. */ properties: NameValue[]; } /** * A name/value pair. */ export interface NameValue { /** * Attribute/property name. */ name: string; /** * Attribute/property value. */ value: string; } /** * Index of the string in the strings table. */ export type StringIndex = integer; /** * Index of the string in the strings table. */ export type ArrayOfStrings = StringIndex[]; /** * Data that is only present on rare nodes. */ export interface RareStringData { index: integer[]; value: StringIndex[]; } export interface RareBooleanData { index: integer[]; } export interface RareIntegerData { index: integer[]; value: integer[]; } export type Rectangle = number[]; /** * Document snapshot. */ export interface DocumentSnapshot { /** * Document URL that `Document` or `FrameOwner` node points to. */ documentURL: StringIndex; /** * Document title. */ title: StringIndex; /** * Base URL that `Document` or `FrameOwner` node uses for URL completion. */ baseURL: StringIndex; /** * Contains the document's content language. */ contentLanguage: StringIndex; /** * Contains the document's character set encoding. */ encodingName: StringIndex; /** * `DocumentType` node's publicId. */ publicId: StringIndex; /** * `DocumentType` node's systemId. */ systemId: StringIndex; /** * Frame ID for frame owner elements and also for the document node. */ frameId: StringIndex; /** * A table with dom nodes. */ nodes: NodeTreeSnapshot; /** * The nodes in the layout tree. */ layout: LayoutTreeSnapshot; /** * The post-layout inline text nodes. */ textBoxes: TextBoxSnapshot; /** * Horizontal scroll offset. */ scrollOffsetX?: number; /** * Vertical scroll offset. */ scrollOffsetY?: number; /** * Document content width. */ contentWidth?: number; /** * Document content height. */ contentHeight?: number; } /** * Table containing nodes. */ export interface NodeTreeSnapshot { /** * Parent node index. */ parentIndex?: integer[]; /** * `Node`'s nodeType. */ nodeType?: integer[]; /** * Type of the shadow root the `Node` is in. String values are equal to the `ShadowRootType` enum. */ shadowRootType?: RareStringData; /** * `Node`'s nodeName. */ nodeName?: StringIndex[]; /** * `Node`'s nodeValue. */ nodeValue?: StringIndex[]; /** * `Node`'s id, corresponds to DOM.Node.backendNodeId. */ backendNodeId?: DOM.BackendNodeId[]; /** * Attributes of an `Element` node. Flatten name, value pairs. */ attributes?: ArrayOfStrings[]; /** * Only set for textarea elements, contains the text value. */ textValue?: RareStringData; /** * Only set for input elements, contains the input's associated text value. */ inputValue?: RareStringData; /** * Only set for radio and checkbox input elements, indicates if the element has been checked */ inputChecked?: RareBooleanData; /** * Only set for option elements, indicates if the element has been selected */ optionSelected?: RareBooleanData; /** * The index of the document in the list of the snapshot documents. */ contentDocumentIndex?: RareIntegerData; /** * Type of a pseudo element node. */ pseudoType?: RareStringData; /** * Whether this DOM node responds to mouse clicks. This includes nodes that have had click * event listeners attached via JavaScript as well as anchor tags that naturally navigate when * clicked. */ isClickable?: RareBooleanData; /** * The selected url for nodes with a srcset attribute. */ currentSourceURL?: RareStringData; /** * The url of the script (if any) that generates this node. */ originURL?: RareStringData; } /** * Table of details of an element in the DOM tree with a LayoutObject. */ export interface LayoutTreeSnapshot { /** * Index of the corresponding node in the `NodeTreeSnapshot` array returned by `captureSnapshot`. */ nodeIndex: integer[]; /** * Array of indexes specifying computed style strings, filtered according to the `computedStyles` parameter passed to `captureSnapshot`. */ styles: ArrayOfStrings[]; /** * The absolute position bounding box. */ bounds: Rectangle[]; /** * Contents of the LayoutText, if any. */ text: StringIndex[]; /** * Stacking context information. */ stackingContexts: RareBooleanData; /** * Global paint order index, which is determined by the stacking order of the nodes. Nodes * that are painted together will have the same index. Only provided if includePaintOrder in * captureSnapshot was true. */ paintOrders?: integer[]; /** * The offset rect of nodes. Only available when includeDOMRects is set to true */ offsetRects?: Rectangle[]; /** * The scroll rect of nodes. Only available when includeDOMRects is set to true */ scrollRects?: Rectangle[]; /** * The client rect of nodes. Only available when includeDOMRects is set to true */ clientRects?: Rectangle[]; /** * The list of background colors that are blended with colors of overlapping elements. */ blendedBackgroundColors?: StringIndex[]; /** * The list of computed text opacities. */ textColorOpacities?: number[]; } /** * Table of details of the post layout rendered text positions. The exact layout should not be regarded as * stable and may change between versions. */ export interface TextBoxSnapshot { /** * Index of the layout tree node that owns this box collection. */ layoutIndex: integer[]; /** * The absolute position bounding box. */ bounds: Rectangle[]; /** * The starting index in characters, for this post layout textbox substring. Characters that * would be represented as a surrogate pair in UTF-16 have length 2. */ start: integer[]; /** * The number of characters in this post layout textbox substring. Characters that would be * represented as a surrogate pair in UTF-16 have length 2. */ length: integer[]; } } /** * Methods and events of the 'DOMStorage' domain. */ export interface DOMStorageApi { clear(params: DOMStorage.ClearParams): Promise<DOMStorage.ClearResult | undefined>; /** * Disables storage tracking, prevents storage events from being sent to the client. */ disable(params: DOMStorage.DisableParams): Promise<DOMStorage.DisableResult | undefined>; /** * Enables storage tracking, storage events will now be delivered to the client. */ enable(params: DOMStorage.EnableParams): Promise<DOMStorage.EnableResult | undefined>; getDOMStorageItems( params: DOMStorage.GetDOMStorageItemsParams, ): Promise<DOMStorage.GetDOMStorageItemsResult | undefined>; removeDOMStorageItem( params: DOMStorage.RemoveDOMStorageItemParams, ): Promise<DOMStorage.RemoveDOMStorageItemResult | undefined>; setDOMStorageItem( params: DOMStorage.SetDOMStorageItemParams, ): Promise<DOMStorage.SetDOMStorageItemResult | undefined>; on( event: 'domStorageItemAdded', listener: (event: DOMStorage.DomStorageItemAddedEvent) => void, ): IDisposable; on( event: 'domStorageItemRemoved', listener: (event: DOMStorage.DomStorageItemRemovedEvent) => void, ): IDisposable; on( event: 'domStorageItemUpdated', listener: (event: DOMStorage.DomStorageItemUpdatedEvent) => void, ): IDisposable; on( event: 'domStorageItemsCleared', listener: (event: DOMStorage.DomStorageItemsClearedEvent) => void, ): IDisposable; } /** * Types of the 'DOMStorage' domain. */ export namespace DOMStorage { /** * Parameters of the 'DOMStorage.clear' method. */ export interface ClearParams { storageId: StorageId; } /** * Return value of the 'DOMStorage.clear' method. */ export interface ClearResult {} /** * Parameters of the 'DOMStorage.disable' method. */ export interface DisableParams {} /** * Return value of the 'DOMStorage.disable' method. */ export interface DisableResult {} /** * Parameters of the 'DOMStorage.enable' method. */ export interface EnableParams {} /** * Return value of the 'DOMStorage.enable' method. */ export interface EnableResult {} /** * Parameters of the 'DOMStorage.getDOMStorageItems' method. */ export interface GetDOMStorageItemsParams { storageId: StorageId; } /** * Return value of the 'DOMStorage.getDOMStorageItems' method. */ export interface GetDOMStorageItemsResult { entries: Item[]; } /** * Parameters of the 'DOMStorage.removeDOMStorageItem' method. */ export interface RemoveDOMStorageItemParams { storageId: StorageId; key: string; } /** * Return value of the 'DOMStorage.removeDOMStorageItem' method. */ export interface RemoveDOMStorageItemResult {} /** * Parameters of the 'DOMStorage.setDOMStorageItem' method. */ export interface SetDOMStorageItemParams { storageId: StorageId; key: string; value: string; } /** * Return value of the 'DOMStorage.setDOMStorageItem' method. */ export interface SetDOMStorageItemResult {} /** * Parameters of the 'DOMStorage.domStorageItemAdded' event. */ export interface DomStorageItemAddedEvent { storageId: StorageId; key: string; newValue: string; } /** * Parameters of the 'DOMStorage.domStorageItemRemoved' event. */ export interface DomStorageItemRemovedEvent { storageId: StorageId; key: string; } /** * Parameters of the 'DOMStorage.domStorageItemUpdated' event. */ export interface DomStorageItemUpdatedEvent { storageId: StorageId; key: string; oldValue: string; newValue: string; } /** * Parameters of the 'DOMStorage.domStorageItemsCleared' event. */ export interface DomStorageItemsClearedEvent { storageId: StorageId; } /** * DOM Storage identifier. */ export interface StorageId { /** * Security origin for the storage. */ securityOrigin: string; /** * Whether the storage is local storage (not session storage). */ isLocalStorage: boolean; } /** * DOM Storage item. */ export type Item = string[]; } /** * Methods and events of the 'Emulation' domain. */ export interface EmulationApi { /** * Tells whether emulation is supported. */ canEmulate(params: Emulation.CanEmulateParams): Promise<Emulation.CanEmulateResult | undefined>; /** * Clears the overridden device metrics. */ clearDeviceMetricsOverride( params: Emulation.ClearDeviceMetricsOverrideParams, ): Promise<Emulation.ClearDeviceMetricsOverrideResult | undefined>; /** * Clears the overridden Geolocation Position and Error. */ clearGeolocationOverride( params: Emulation.ClearGeolocationOverrideParams, ): Promise<Emulation.ClearGeolocationOverrideResult | undefined>; /** * Requests that page scale factor is reset to initial values. */ resetPageScaleFactor( params: Emulation.ResetPageScaleFactorParams, ): Promise<Emulation.ResetPageScaleFactorResult | undefined>; /** * Enables or disables simulating a focused and active page. */ setFocusEmulationEnabled( params: Emulation.SetFocusEmulationEnabledParams, ): Promise<Emulation.SetFocusEmulationEnabledResult | undefined>; /** * Automatically render all web contents using a dark theme. */ setAutoDarkModeOverride( params: Emulation.SetAutoDarkModeOverrideParams, ): Promise<Emulation.SetAutoDarkModeOverrideResult | undefined>; /** * Enables CPU throttling to emulate slow CPUs. */ setCPUThrottlingRate( params: Emulation.SetCPUThrottlingRateParams, ): Promise<Emulation.SetCPUThrottlingRateResult | undefined>; /** * Sets or clears an override of the default background color of the frame. This override is used * if the content does not specify one. */ setDefaultBackgroundColorOverride( params: Emulation.SetDefaultBackgroundColorOverrideParams, ): Promise<Emulation.SetDefaultBackgroundColorOverrideResult | undefined>; /** * Overrides the values of device screen dimensions (window.screen.width, window.screen.height, * window.innerWidth, window.innerHeight, and "device-width"/"device-height"-related CSS media * query results). */ setDeviceMetricsOverride( params: Emulation.SetDeviceMetricsOverrideParams, ): Promise<Emulation.SetDeviceMetricsOverrideResult | undefined>; setScrollbarsHidden( params: Emulation.SetScrollbarsHiddenParams, ): Promise<Emulation.SetScrollbarsHiddenResult | undefined>; setDocumentCookieDisabled( params: Emulation.SetDocumentCookieDisabledParams, ): Promise<Emulation.SetDocumentCookieDisabledResult | undefined>; setEmitTouchEventsForMouse( params: Emulation.SetEmitTouchEventsForMouseParams, ): Promise<Emulation.SetEmitTouchEventsForMouseResult | undefined>; /** * Emulates the given media type or media feature for CSS media queries. */ setEmulatedMedia( params: Emulation.SetEmulatedMediaParams, ): Promise<Emulation.SetEmulatedMediaResult | undefined>; /** * Emulates the given vision deficiency. */ setEmulatedVisionDeficiency( params: Emulation.SetEmulatedVisionDeficiencyParams, ): Promise<Emulation.SetEmulatedVisionDeficiencyResult | undefined>; /** * Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position * unavailable. */ setGeolocationOverride( params: Emulation.SetGeolocationOverrideParams, ): Promise<Emulation.SetGeolocationOverrideResult | undefined>; /** * Overrides the Idle state. */ setIdleOverride( params: Emulation.SetIdleOverrideParams, ): Promise<Emulation.SetIdleOverrideResult | undefined>; /** * Clears Idle state overrides. */ clearIdleOverride( params: Emulation.ClearIdleOverrideParams, ): Promise<Emulation.ClearIdleOverrideResult | undefined>; /** * Overrides value returned by the javascript navigator object. * @deprecated */ setNavigatorOverrides( params: Emulation.SetNavigatorOverridesParams, ): Promise<Emulation.SetNavigatorOverridesResult | undefined>; /** * Sets a specified page scale factor. */ setPageScaleFactor( params: Emulation.SetPageScaleFactorParams, ): Promise<Emulation.SetPageScaleFactorResult | undefined>; /** * Switches script execution in the page. */ setScriptExecutionDisabled( params: Emulation.SetScriptExecutionDisabledParams, ): Promise<Emulation.SetScriptExecutionDisabledResult | undefined>; /** * Enables touch on platforms which do not support them. */ setTouchEmulationEnabled( params: Emulation.SetTouchEmulationEnabledParams, ): Promise<Emulation.SetTouchEmulationEnabledResult | undefined>; /** * Turns on virtual time for all frames (replacing real-time with a synthetic time source) and sets * the current virtual time policy. Note this supersedes any previous time budget. */ setVirtualTimePolicy( params: Emulation.SetVirtualTimePolicyParams, ): Promise<Emulation.SetVirtualTimePolicyResult | undefined>; /** * Overrides default host system locale with the specified one. */ setLocaleOverride( params: Emulation.SetLocaleOverrideParams, ): Promise<Emulation.SetLocaleOverrideResult | undefined>; /** * Overrides default host system timezone with the specified one. */ setTimezoneOverride( params: Emulation.SetTimezoneOverrideParams, ): Promise<Emulation.SetTimezoneOverrideResult | undefined>; /** * Resizes the frame/viewport of the page. Note that this does not affect the frame's container * (e.g. browser window). Can be used to produce screenshots of the specified size. Not supported * on Android. * @deprecated */ setVisibleSize( params: Emulation.SetVisibleSizeParams, ): Promise<Emulation.SetVisibleSizeResult | undefined>; setDisabledImageTypes( params: Emulation.SetDisabledImageTypesParams, ): Promise<Emulation.SetDisabledImageTypesResult | undefined>; /** * Allows overriding user agent with the given string. */ setUserAgentOverride( params: Emulation.SetUserAgentOverrideParams, ): Promise<Emulation.SetUserAgentOverrideResult | undefined>; /** * Notification sent after the virtual time budget for the current VirtualTimePolicy has run out. */ on( event: 'virtualTimeBudgetExpired', listener: (event: Emulation.VirtualTimeBudgetExpiredEvent) => void, ): IDisposable; } /** * Types of the 'Emulation' domain. */ export namespace Emulation { /** * Parameters of the 'Emulation.canEmulate' method. */ export interface CanEmulateParams {} /** * Return value of the 'Emulation.canEmulate' method. */ export interface CanEmulateResult { /** * True if emulation is supported. */ result: boolean; } /** * Parameters of the 'Emulation.clearDeviceMetricsOverride' method. */ export interface ClearDeviceMetricsOverrideParams {} /** * Return value of the 'Emulation.clearDeviceMetricsOverride' method. */ export interface ClearDeviceMetricsOverrideResult {} /** * Parameters of the 'Emulation.clearGeolocationOverride' method. */ export interface ClearGeolocationOverrideParams {} /** * Return value of the 'Emulation.clearGeolocationOverride' method. */ export interface ClearGeolocationOverrideResult {} /** * Parameters of the 'Emulation.resetPageScaleFactor' method. */ export interface ResetPageScaleFactorParams {} /** * Return value of the 'Emulation.resetPageScaleFactor' method. */ export interface ResetPageScaleFactorResult {} /** * Parameters of the 'Emulation.setFocusEmulationEnabled' method. */ export interface SetFocusEmulationEnabledParams { /** * Whether to enable to disable focus emulation. */ enabled: boolean; } /** * Return value of the 'Emulation.setFocusEmulationEnabled' method. */ export interface SetFocusEmulationEnabledResult {} /** * Parameters of the 'Emulation.setAutoDarkModeOverride' method. */ export interface SetAutoDarkModeOverrideParams { /** * Whether to enable or disable automatic dark mode. * If not specified, any existing override will be cleared. */ enabled?: boolean; } /** * Return value of the 'Emulation.setAutoDarkModeOverride' method. */ export interface SetAutoDarkModeOverrideResult {} /** * Parameters of the 'Emulation.setCPUThrottlingRate' method. */ export interface SetCPUThrottlingRateParams { /** * Throttling rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc). */ rate: number; } /** * Return value of the 'Emulation.setCPUThrottlingRate' method. */ export interface SetCPUThrottlingRateResult {} /** * Parameters of the 'Emulation.setDefaultBackgroundColorOverride' method. */ export interface SetDefaultBackgroundColorOverrideParams { /** * RGBA of the default background color. If not specified, any existing override will be * cleared. */ color?: DOM.RGBA; } /** * Return value of the 'Emulation.setDefaultBackgroundColorOverride' method. */ export interface SetDefaultBackgroundColorOverrideResult {} /** * Parameters of the 'Emulation.setDeviceMetricsOverride' method. */ export interface SetDeviceMetricsOverrideParams { /** * Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override. */ width: integer; /** * Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override. */ height: integer; /** * Overriding device scale factor value. 0 disables the override. */ deviceScaleFactor: number; /** * Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text * autosizing and more. */ mobile: boolean; /** * Scale to apply to resulting view image. */ scale?: number; /** * Overriding screen width value in pixels (minimum 0, maximum 10000000). */ screenWidth?: integer; /** * Overriding screen height value in pixels (minimum 0, maximum 10000000). */ screenHeight?: integer; /** * Overriding view X position on screen in pixels (minimum 0, maximum 10000000). */ positionX?: integer; /** * Overriding view Y position on screen in pixels (minimum 0, maximum 10000000). */ positionY?: integer; /** * Do not set visible view size, rely upon explicit setVisibleSize call. */ dontSetVisibleSize?: boolean; /** * Screen orientation override. */ screenOrientation?: ScreenOrientation; /** * If set, the visible area of the page will be overridden to this viewport. This viewport * change is not observed by the page, e.g. viewport-relative elements do not change positions. */ viewport?: Page.Viewport; /** * If set, the display feature of a multi-segment screen. If not set, multi-segment support * is turned-off. */ displayFeature?: DisplayFeature; } /** * Return value of the 'Emulation.setDeviceMetricsOverride' method. */ export interface SetDeviceMetricsOverrideResult {} /** * Parameters of the 'Emulation.setScrollbarsHidden' method. */ export interface SetScrollbarsHiddenParams { /** * Whether scrollbars should be always hidden. */ hidden: boolean; } /** * Return value of the 'Emulation.setScrollbarsHidden' method. */ export interface SetScrollbarsHiddenResult {} /** * Parameters of the 'Emulation.setDocumentCookieDisabled' method. */ export interface SetDocumentCookieDisabledParams { /** * Whether document.coookie API should be disabled. */ disabled: boolean; } /** * Return value of the 'Emulation.setDocumentCookieDisabled' method. */ export interface SetDocumentCookieDisabledResult {} /** * Parameters of the 'Emulation.setEmitTouchEventsForMouse' method. */ export interface SetEmitTouchEventsForMouseParams { /** * Whether touch emulation based on mouse input should be enabled. */ enabled: boolean; /** * Touch/gesture events configuration. Default: current platform. */ configuration?: 'mobile' | 'desktop'; } /** * Return value of the 'Emulation.setEmitTouchEventsForMouse' method. */ export interface SetEmitTouchEventsForMouseResult {} /** * Parameters of the 'Emulation.setEmulatedMedia' method. */ export interface SetEmulatedMediaParams { /** * Media type to emulate. Empty string disables the override. */ media?: string; /** * Media features to emulate. */ features?: MediaFeature[]; } /** * Return value of the 'Emulation.setEmulatedMedia' method. */ export interface SetEmulatedMediaResult {} /** * Parameters of the 'Emulation.setEmulatedVisionDeficiency' method. */ export interface SetEmulatedVisionDeficiencyParams { /** * Vision deficiency to emulate. */ type: | 'none' | 'achromatopsia' | 'blurredVision' | 'deuteranopia' | 'protanopia' | 'tritanopia'; } /** * Return value of the 'Emulation.setEmulatedVisionDeficiency' method. */ export interface SetEmulatedVisionDeficiencyResult {} /** * Parameters of the 'Emulation.setGeolocationOverride' method. */ export interface SetGeolocationOverrideParams { /** * Mock latitude */ latitude?: number; /** * Mock longitude */ longitude?: number; /** * Mock accuracy */ accuracy?: number; } /** * Return value of the 'Emulation.setGeolocationOverride' method. */ export interface SetGeolocationOverrideResult {} /** * Parameters of the 'Emulation.setIdleOverride' method. */ export interface SetIdleOverrideParams { /** * Mock isUserActive */ isUserActive: boolean; /** * Mock isScreenUnlocked */ isScreenUnlocked: boolean; } /** * Return value of the 'Emulation.setIdleOverride' method. */ export interface SetIdleOverrideResult {} /** * Parameters of the 'Emulation.clearIdleOverride' method. */ export interface ClearIdleOverrideParams {} /** * Return value of the 'Emulation.clearIdleOverride' method. */ export interface ClearIdleOverrideResult {} /** * Parameters of the 'Emulation.setNavigatorOverrides' method. */ export interface SetNavigatorOverridesParams { /** * The platform navigator.platform should return. */ platform: string; } /** * Return value of the 'Emulation.setNavigatorOverrides' method. */ export interface SetNavigatorOverridesResult {} /** * Parameters of the 'Emulation.setPageScaleFactor' method. */ export interface SetPageScaleFactorParams { /** * Page scale factor. */ pageScaleFactor: number; } /** * Return value of the 'Emulation.setPageScaleFactor' method. */ export interface SetPageScaleFactorResult {} /** * Parameters of the 'Emulation.setScriptExecutionDisabled' method. */ export interface SetScriptExecutionDisabledParams { /** * Whether script execution should be disabled in the page. */ value: boolean; } /** * Return value of the 'Emulation.setScriptExecutionDisabled' method. */ export interface SetScriptExecutionDisabledResult {} /** * Parameters of the 'Emulation.setTouchEmulationEnabled' method. */ export interface SetTouchEmulationEnabledParams { /** * Whether the touch event emulation should be enabled. */ enabled: boolean; /** * Maximum touch points supported. Defaults to one. */ maxTouchPoints?: integer; } /** * Return value of the 'Emulation.setTouchEmulationEnabled' method. */ export interface SetTouchEmulationEnabledResult {} /** * Parameters of the 'Emulation.setVirtualTimePolicy' method. */ export interface SetVirtualTimePolicyParams { policy: VirtualTimePolicy; /** * If set, after this many virtual milliseconds have elapsed virtual time will be paused and a * virtualTimeBudgetExpired event is sent. */ budget?: number; /** * If set this specifies the maximum number of tasks that can be run before virtual is forced * forwards to prevent deadlock. */ maxVirtualTimeTaskStarvationCount?: integer; /** * If set the virtual time policy change should be deferred until any frame starts navigating. * Note any previous deferred policy change is superseded. */ waitForNavigation?: boolean; /** * If set, base::Time::Now will be overridden to initially return this value. */ initialVirtualTime?: Network.TimeSinceEpoch; } /** * Return value of the 'Emulation.setVirtualTimePolicy' method. */ export interface SetVirtualTimePolicyResult { /** * Absolute timestamp at which virtual time was first enabled (up time in milliseconds). */ virtualTimeTicksBase: number; } /** * Parameters of the 'Emulation.setLocaleOverride' method. */ export interface SetLocaleOverrideParams { /** * ICU style C locale (e.g. "en_US"). If not specified or empty, disables the override and * restores default host system locale. */ locale?: string; } /** * Return value of the 'Emulation.setLocaleOverride' method. */ export interface SetLocaleOverrideResult {} /** * Parameters of the 'Emulation.setTimezoneOverride' method. */ export interface SetTimezoneOverrideParams { /** * The timezone identifier. If empty, disables the override and * restores default host system timezone. */ timezoneId: string; } /** * Return value of the 'Emulation.setTimezoneOverride' method. */ export interface SetTimezoneOverrideResult {} /** * Parameters of the 'Emulation.setVisibleSize' method. */ export interface SetVisibleSizeParams { /** * Frame width (DIP). */ width: integer; /** * Frame height (DIP). */ height: integer; } /** * Return value of the 'Emulation.setVisibleSize' method. */ export interface SetVisibleSizeResult {} /** * Parameters of the 'Emulation.setDisabledImageTypes' method. */ export interface SetDisabledImageTypesParams { /** * Image types to disable. */ imageTypes: DisabledImageType[]; } /** * Return value of the 'Emulation.setDisabledImageTypes' method. */ export interface SetDisabledImageTypesResult {} /** * Parameters of the 'Emulation.setUserAgentOverride' method. */ export interface SetUserAgentOverrideParams { /** * User agent to use. */ userAgent: string; /** * Browser langugage to emulate. */ acceptLanguage?: string; /** * The platform navigator.platform should return. */ platform?: string; /** * To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData */ userAgentMetadata?: UserAgentMetadata; } /** * Return value of the 'Emulation.setUserAgentOverride' method. */ export interface SetUserAgentOverrideResult {} /** * Parameters of the 'Emulation.virtualTimeBudgetExpired' event. */ export interface VirtualTimeBudgetExpiredEvent {} /** * Screen orientation. */ export interface ScreenOrientation { /** * Orientation type. */ type: 'portraitPrimary' | 'portraitSecondary' | 'landscapePrimary' | 'landscapeSecondary'; /** * Orientation angle. */ angle: integer; } export interface DisplayFeature { /** * Orientation of a display feature in relation to screen */ orientation: 'vertical' | 'horizontal'; /** * The offset from the screen origin in either the x (for vertical * orientation) or y (for horizontal orientation) direction. */ offset: integer; /** * A display feature may mask content such that it is not physically * displayed - this length along with the offset describes this area. * A display feature that only splits content will have a 0 mask_length. */ maskLength: integer; } export interface MediaFeature { name: string; value: string; } /** * advance: If the scheduler runs out of immediate work, the virtual time base may fast forward to * allow the next delayed task (if any) to run; pause: The virtual time base may not advance; * pauseIfNetworkFetchesPending: The virtual time base may not advance if there are any pending * resource fetches. */ export type VirtualTimePolicy = 'advance' | 'pause' | 'pauseIfNetworkFetchesPending'; /** * Used to specify User Agent Cient Hints to emulate. See https://wicg.github.io/ua-client-hints */ export interface UserAgentBrandVersion { brand: string; version: string; } /** * Used to specify User Agent Cient Hints to emulate. See https://wicg.github.io/ua-client-hints * Missing optional values will be filled in by the target with what it would normally use. */ export interface UserAgentMetadata { brands?: UserAgentBrandVersion[]; fullVersion?: string; platform: string; platformVersion: string; architecture: string; model: string; mobile: boolean; } /** * Enum of image types that can be disabled. */ export type DisabledImageType = 'avif' | 'jxl' | 'webp'; } /** * Methods and events of the 'Fetch' domain. */ export interface FetchApi { /** * Disables the fetch domain. */ disable(params: Fetch.DisableParams): Promise<Fetch.DisableResult | undefined>; /** * Enables issuing of requestPaused events. A request will be paused until client * calls one of failRequest, fulfillRequest or continueRequest/continueWithAuth. */ enable(params: Fetch.EnableParams): Promise<Fetch.EnableResult | undefined>; /** * Causes the request to fail with specified reason. */ failRequest(params: Fetch.FailRequestParams): Promise<Fetch.FailRequestResult | undefined>; /** * Provides response to the request. */ fulfillRequest( params: Fetch.FulfillRequestParams, ): Promise<Fetch.FulfillRequestResult | undefined>; /** * Continues the request, optionally modifying some of its parameters. */ continueRequest( params: Fetch.ContinueRequestParams, ): Promise<Fetch.ContinueRequestResult | undefined>; /** * Continues a request supplying authChallengeResponse following authRequired event. */ continueWithAuth( params: Fetch.ContinueWithAuthParams, ): Promise<Fetch.ContinueWithAuthResult | undefined>; /** * Continues loading of the paused response, optionally modifying the * response headers. If either responseCode or headers are modified, all of them * must be present. */ continueResponse( params: Fetch.ContinueResponseParams, ): Promise<Fetch.ContinueResponseResult | undefined>; /** * Causes the body of the response to be received from the server and * returned as a single string. May only be issued for a request that * is paused in the Response stage and is mutually exclusive with * takeResponseBodyForInterceptionAsStream. Calling other methods that * affect the request or disabling fetch domain before body is received * results in an undefined behavior. */ getResponseBody( params: Fetch.GetResponseBodyParams, ): Promise<Fetch.GetResponseBodyResult | undefined>; /** * Returns a handle to the stream representing the response body. * The request must be paused in the HeadersReceived stage. * Note that after this command the request can't be continued * as is -- client either needs to cancel it or to provide the * response body. * The stream only supports sequential read, IO.read will fail if the position * is specified. * This method is mutually exclusive with getResponseBody. * Calling other methods that affect the request or disabling fetch * domain before body is received results in an undefined behavior. */ takeResponseBodyAsStream( params: Fetch.TakeResponseBodyAsStreamParams, ): Promise<Fetch.TakeResponseBodyAsStreamResult | undefined>; /** * Issued when the domain is enabled and the request URL matches the * specified filter. The request is paused until the client responds * with one of continueRequest, failRequest or fulfillRequest. * The stage of the request can be determined by presence of responseErrorReason * and responseStatusCode -- the request is at the response stage if either * of these fields is present and in the request stage otherwise. */ on(event: 'requestPaused', listener: (event: Fetch.RequestPausedEvent) => void): IDisposable; /** * Issued when the domain is enabled with handleAuthRequests set to true. * The request is paused until client responds with continueWithAuth. */ on(event: 'authRequired', listener: (event: Fetch.AuthRequiredEvent) => void): IDisposable; } /** * Types of the 'Fetch' domain. */ export namespace Fetch { /** * Parameters of the 'Fetch.disable' method. */ export interface DisableParams {} /** * Return value of the 'Fetch.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Fetch.enable' method. */ export interface EnableParams { /** * If specified, only requests matching any of these patterns will produce * fetchRequested event and will be paused until clients response. If not set, * all requests will be affected. */ patterns?: RequestPattern[]; /** * If true, authRequired events will be issued and requests will be paused * expecting a call to continueWithAuth. */ handleAuthRequests?: boolean; } /** * Return value of the 'Fetch.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Fetch.failRequest' method. */ export interface FailRequestParams { /** * An id the client received in requestPaused event. */ requestId: RequestId; /** * Causes the request to fail with the given reason. */ errorReason: Network.ErrorReason; } /** * Return value of the 'Fetch.failRequest' method. */ export interface FailRequestResult {} /** * Parameters of the 'Fetch.fulfillRequest' method. */ export interface FulfillRequestParams { /** * An id the client received in requestPaused event. */ requestId: RequestId; /** * An HTTP response code. */ responseCode: integer; /** * Response headers. */ responseHeaders?: HeaderEntry[]; /** * Alternative way of specifying response headers as a \0-separated * series of name: value pairs. Prefer the above method unless you * need to represent some non-UTF8 values that can't be transmitted * over the protocol as text. (Encoded as a base64 string when passed over JSON) */ binaryResponseHeaders?: string; /** * A response body. If absent, original response body will be used if * the request is intercepted at the response stage and empty body * will be used if the request is intercepted at the request stage. (Encoded as a base64 string when passed over JSON) */ body?: string; /** * A textual representation of responseCode. * If absent, a standard phrase matching responseCode is used. */ responsePhrase?: string; } /** * Return value of the 'Fetch.fulfillRequest' method. */ export interface FulfillRequestResult {} /** * Parameters of the 'Fetch.continueRequest' method. */ export interface ContinueRequestParams { /** * An id the client received in requestPaused event. */ requestId: RequestId; /** * If set, the request url will be modified in a way that's not observable by page. */ url?: string; /** * If set, the request method is overridden. */ method?: string; /** * If set, overrides the post data in the request. (Encoded as a base64 string when passed over JSON) */ postData?: string; /** * If set, overrides the request headers. */ headers?: HeaderEntry[]; /** * If set, overrides response interception behavior for this request. */ interceptResponse?: boolean; } /** * Return value of the 'Fetch.continueRequest' method. */ export interface ContinueRequestResult {} /** * Parameters of the 'Fetch.continueWithAuth' method. */ export interface ContinueWithAuthParams { /** * An id the client received in authRequired event. */ requestId: RequestId; /** * Response to with an authChallenge. */ authChallengeResponse: AuthChallengeResponse; } /** * Return value of the 'Fetch.continueWithAuth' method. */ export interface ContinueWithAuthResult {} /** * Parameters of the 'Fetch.continueResponse' method. */ export interface ContinueResponseParams { /** * An id the client received in requestPaused event. */ requestId: RequestId; /** * An HTTP response code. If absent, original response code will be used. */ responseCode?: integer; /** * A textual representation of responseCode. * If absent, a standard phrase matching responseCode is used. */ responsePhrase?: string; /** * Response headers. If absent, original response headers will be used. */ responseHeaders?: HeaderEntry[]; /** * Alternative way of specifying response headers as a \0-separated * series of name: value pairs. Prefer the above method unless you * need to represent some non-UTF8 values that can't be transmitted * over the protocol as text. (Encoded as a base64 string when passed over JSON) */ binaryResponseHeaders?: string; } /** * Return value of the 'Fetch.continueResponse' method. */ export interface ContinueResponseResult {} /** * Parameters of the 'Fetch.getResponseBody' method. */ export interface GetResponseBodyParams { /** * Identifier for the intercepted request to get body for. */ requestId: RequestId; } /** * Return value of the 'Fetch.getResponseBody' method. */ export interface GetResponseBodyResult { /** * Response body. */ body: string; /** * True, if content was sent as base64. */ base64Encoded: boolean; } /** * Parameters of the 'Fetch.takeResponseBodyAsStream' method. */ export interface TakeResponseBodyAsStreamParams { requestId: RequestId; } /** * Return value of the 'Fetch.takeResponseBodyAsStream' method. */ export interface TakeResponseBodyAsStreamResult { stream: IO.StreamHandle; } /** * Parameters of the 'Fetch.requestPaused' event. */ export interface RequestPausedEvent { /** * Each request the page makes will have a unique id. */ requestId: RequestId; /** * The details of the request. */ request: Network.Request; /** * The id of the frame that initiated the request. */ frameId: Page.FrameId; /** * How the requested resource will be used. */ resourceType: Network.ResourceType; /** * Response error if intercepted at response stage. */ responseErrorReason?: Network.ErrorReason; /** * Response code if intercepted at response stage. */ responseStatusCode?: integer; /** * Response status text if intercepted at response stage. */ responseStatusText?: string; /** * Response headers if intercepted at the response stage. */ responseHeaders?: HeaderEntry[]; /** * If the intercepted request had a corresponding Network.requestWillBeSent event fired for it, * then this networkId will be the same as the requestId present in the requestWillBeSent event. */ networkId?: RequestId; } /** * Parameters of the 'Fetch.authRequired' event. */ export interface AuthRequiredEvent { /** * Each request the page makes will have a unique id. */ requestId: RequestId; /** * The details of the request. */ request: Network.Request; /** * The id of the frame that initiated the request. */ frameId: Page.FrameId; /** * How the requested resource will be used. */ resourceType: Network.ResourceType; /** * Details of the Authorization Challenge encountered. * If this is set, client should respond with continueRequest that * contains AuthChallengeResponse. */ authChallenge: AuthChallenge; } /** * Unique request identifier. */ export type RequestId = string; /** * Stages of the request to handle. Request will intercept before the request is * sent. Response will intercept after the response is received (but before response * body is received). */ export type RequestStage = 'Request' | 'Response'; export interface RequestPattern { /** * Wildcards (`'*'` -> zero or more, `'?'` -> exactly one) are allowed. Escape character is * backslash. Omitting is equivalent to `"*"`. */ urlPattern?: string; /** * If set, only requests for matching resource types will be intercepted. */ resourceType?: Network.ResourceType; /** * Stage at which to begin intercepting requests. Default is Request. */ requestStage?: RequestStage; } /** * Response HTTP header entry */ export interface HeaderEntry { name: string; value: string; } /** * Authorization challenge for HTTP status code 401 or 407. */ export interface AuthChallenge { /** * Source of the authentication challenge. */ source?: 'Server' | 'Proxy'; /** * Origin of the challenger. */ origin: string; /** * The authentication scheme used, such as basic or digest */ scheme: string; /** * The realm of the challenge. May be empty. */ realm: string; } /** * Response to an AuthChallenge. */ export interface AuthChallengeResponse { /** * The decision on what to do in response to the authorization challenge. Default means * deferring to the default behavior of the net stack, which will likely either the Cancel * authentication or display a popup dialog box. */ response: 'Default' | 'CancelAuth' | 'ProvideCredentials'; /** * The username to provide, possibly empty. Should only be set if response is * ProvideCredentials. */ username?: string; /** * The password to provide, possibly empty. Should only be set if response is * ProvideCredentials. */ password?: string; } } /** * Methods and events of the 'HeadlessExperimental' domain. */ export interface HeadlessExperimentalApi { /** * Sends a BeginFrame to the target and returns when the frame was completed. Optionally captures a * screenshot from the resulting frame. Requires that the target was created with enabled * BeginFrameControl. Designed for use with --run-all-compositor-stages-before-draw, see also * https://goo.gl/3zHXhB for more background. */ beginFrame( params: HeadlessExperimental.BeginFrameParams, ): Promise<HeadlessExperimental.BeginFrameResult | undefined>; /** * Disables headless events for the target. */ disable( params: HeadlessExperimental.DisableParams, ): Promise<HeadlessExperimental.DisableResult | undefined>; /** * Enables headless events for the target. */ enable( params: HeadlessExperimental.EnableParams, ): Promise<HeadlessExperimental.EnableResult | undefined>; /** * Issued when the target starts or stops needing BeginFrames. * Deprecated. Issue beginFrame unconditionally instead and use result from * beginFrame to detect whether the frames were suppressed. * @deprecated */ on( event: 'needsBeginFramesChanged', listener: (event: HeadlessExperimental.NeedsBeginFramesChangedEvent) => void, ): IDisposable; } /** * Types of the 'HeadlessExperimental' domain. */ export namespace HeadlessExperimental { /** * Parameters of the 'HeadlessExperimental.beginFrame' method. */ export interface BeginFrameParams { /** * Timestamp of this BeginFrame in Renderer TimeTicks (milliseconds of uptime). If not set, * the current time will be used. */ frameTimeTicks?: number; /** * The interval between BeginFrames that is reported to the compositor, in milliseconds. * Defaults to a 60 frames/second interval, i.e. about 16.666 milliseconds. */ interval?: number; /** * Whether updates should not be committed and drawn onto the display. False by default. If * true, only side effects of the BeginFrame will be run, such as layout and animations, but * any visual updates may not be visible on the display or in screenshots. */ noDisplayUpdates?: boolean; /** * If set, a screenshot of the frame will be captured and returned in the response. Otherwise, * no screenshot will be captured. Note that capturing a screenshot can fail, for example, * during renderer initialization. In such a case, no screenshot data will be returned. */ screenshot?: ScreenshotParams; } /** * Return value of the 'HeadlessExperimental.beginFrame' method. */ export interface BeginFrameResult { /** * Whether the BeginFrame resulted in damage and, thus, a new frame was committed to the * display. Reported for diagnostic uses, may be removed in the future. */ hasDamage: boolean; /** * Base64-encoded image data of the screenshot, if one was requested and successfully taken. (Encoded as a base64 string when passed over JSON) */ screenshotData?: string; } /** * Parameters of the 'HeadlessExperimental.disable' method. */ export interface DisableParams {} /** * Return value of the 'HeadlessExperimental.disable' method. */ export interface DisableResult {} /** * Parameters of the 'HeadlessExperimental.enable' method. */ export interface EnableParams {} /** * Return value of the 'HeadlessExperimental.enable' method. */ export interface EnableResult {} /** * Parameters of the 'HeadlessExperimental.needsBeginFramesChanged' event. */ export interface NeedsBeginFramesChangedEvent { /** * True if BeginFrames are needed, false otherwise. */ needsBeginFrames: boolean; } /** * Encoding options for a screenshot. */ export interface ScreenshotParams { /** * Image compression format (defaults to png). */ format?: 'jpeg' | 'png'; /** * Compression quality from range [0..100] (jpeg only). */ quality?: integer; } } /** * Methods and events of the 'HeapProfiler' domain. */ export interface HeapProfilerApi { /** * Enables console to refer to the node with given id via $x (see Command Line API for more details * $x functions). */ addInspectedHeapObject( params: HeapProfiler.AddInspectedHeapObjectParams, ): Promise<HeapProfiler.AddInspectedHeapObjectResult | undefined>; collectGarbage( params: HeapProfiler.CollectGarbageParams, ): Promise<HeapProfiler.CollectGarbageResult | undefined>; disable(params: HeapProfiler.DisableParams): Promise<HeapProfiler.DisableResult | undefined>; enable(params: HeapProfiler.EnableParams): Promise<HeapProfiler.EnableResult | undefined>; getHeapObjectId( params: HeapProfiler.GetHeapObjectIdParams, ): Promise<HeapProfiler.GetHeapObjectIdResult | undefined>; getObjectByHeapObjectId( params: HeapProfiler.GetObjectByHeapObjectIdParams, ): Promise<HeapProfiler.GetObjectByHeapObjectIdResult | undefined>; getSamplingProfile( params: HeapProfiler.GetSamplingProfileParams, ): Promise<HeapProfiler.GetSamplingProfileResult | undefined>; startSampling( params: HeapProfiler.StartSamplingParams, ): Promise<HeapProfiler.StartSamplingResult | undefined>; startTrackingHeapObjects( params: HeapProfiler.StartTrackingHeapObjectsParams, ): Promise<HeapProfiler.StartTrackingHeapObjectsResult | undefined>; stopSampling( params: HeapProfiler.StopSamplingParams, ): Promise<HeapProfiler.StopSamplingResult | undefined>; stopTrackingHeapObjects( params: HeapProfiler.StopTrackingHeapObjectsParams, ): Promise<HeapProfiler.StopTrackingHeapObjectsResult | undefined>; takeHeapSnapshot( params: HeapProfiler.TakeHeapSnapshotParams, ): Promise<HeapProfiler.TakeHeapSnapshotResult | undefined>; on( event: 'addHeapSnapshotChunk', listener: (event: HeapProfiler.AddHeapSnapshotChunkEvent) => void, ): IDisposable; /** * If heap objects tracking has been started then backend may send update for one or more fragments */ on( event: 'heapStatsUpdate', listener: (event: HeapProfiler.HeapStatsUpdateEvent) => void, ): IDisposable; /** * If heap objects tracking has been started then backend regularly sends a current value for last * seen object id and corresponding timestamp. If the were changes in the heap since last event * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. */ on( event: 'lastSeenObjectId', listener: (event: HeapProfiler.LastSeenObjectIdEvent) => void, ): IDisposable; on( event: 'reportHeapSnapshotProgress', listener: (event: HeapProfiler.ReportHeapSnapshotProgressEvent) => void, ): IDisposable; on( event: 'resetProfiles', listener: (event: HeapProfiler.ResetProfilesEvent) => void, ): IDisposable; } /** * Types of the 'HeapProfiler' domain. */ export namespace HeapProfiler { /** * Parameters of the 'HeapProfiler.addInspectedHeapObject' method. */ export interface AddInspectedHeapObjectParams { /** * Heap snapshot object id to be accessible by means of $x command line API. */ heapObjectId: HeapSnapshotObjectId; } /** * Return value of the 'HeapProfiler.addInspectedHeapObject' method. */ export interface AddInspectedHeapObjectResult {} /** * Parameters of the 'HeapProfiler.collectGarbage' method. */ export interface CollectGarbageParams {} /** * Return value of the 'HeapProfiler.collectGarbage' method. */ export interface CollectGarbageResult {} /** * Parameters of the 'HeapProfiler.disable' method. */ export interface DisableParams {} /** * Return value of the 'HeapProfiler.disable' method. */ export interface DisableResult {} /** * Parameters of the 'HeapProfiler.enable' method. */ export interface EnableParams {} /** * Return value of the 'HeapProfiler.enable' method. */ export interface EnableResult {} /** * Parameters of the 'HeapProfiler.getHeapObjectId' method. */ export interface GetHeapObjectIdParams { /** * Identifier of the object to get heap object id for. */ objectId: Runtime.RemoteObjectId; } /** * Return value of the 'HeapProfiler.getHeapObjectId' method. */ export interface GetHeapObjectIdResult { /** * Id of the heap snapshot object corresponding to the passed remote object id. */ heapSnapshotObjectId: HeapSnapshotObjectId; } /** * Parameters of the 'HeapProfiler.getObjectByHeapObjectId' method. */ export interface GetObjectByHeapObjectIdParams { objectId: HeapSnapshotObjectId; /** * Symbolic group name that can be used to release multiple objects. */ objectGroup?: string; } /** * Return value of the 'HeapProfiler.getObjectByHeapObjectId' method. */ export interface GetObjectByHeapObjectIdResult { /** * Evaluation result. */ result: Runtime.RemoteObject; } /** * Parameters of the 'HeapProfiler.getSamplingProfile' method. */ export interface GetSamplingProfileParams {} /** * Return value of the 'HeapProfiler.getSamplingProfile' method. */ export interface GetSamplingProfileResult { /** * Return the sampling profile being collected. */ profile: SamplingHeapProfile; } /** * Parameters of the 'HeapProfiler.startSampling' method. */ export interface StartSamplingParams { /** * Average sample interval in bytes. Poisson distribution is used for the intervals. The * default value is 32768 bytes. */ samplingInterval?: number; } /** * Return value of the 'HeapProfiler.startSampling' method. */ export interface StartSamplingResult {} /** * Parameters of the 'HeapProfiler.startTrackingHeapObjects' method. */ export interface StartTrackingHeapObjectsParams { trackAllocations?: boolean; } /** * Return value of the 'HeapProfiler.startTrackingHeapObjects' method. */ export interface StartTrackingHeapObjectsResult {} /** * Parameters of the 'HeapProfiler.stopSampling' method. */ export interface StopSamplingParams {} /** * Return value of the 'HeapProfiler.stopSampling' method. */ export interface StopSamplingResult { /** * Recorded sampling heap profile. */ profile: SamplingHeapProfile; } /** * Parameters of the 'HeapProfiler.stopTrackingHeapObjects' method. */ export interface StopTrackingHeapObjectsParams { /** * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken * when the tracking is stopped. */ reportProgress?: boolean; treatGlobalObjectsAsRoots?: boolean; /** * If true, numerical values are included in the snapshot */ captureNumericValue?: boolean; } /** * Return value of the 'HeapProfiler.stopTrackingHeapObjects' method. */ export interface StopTrackingHeapObjectsResult {} /** * Parameters of the 'HeapProfiler.takeHeapSnapshot' method. */ export interface TakeHeapSnapshotParams { /** * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. */ reportProgress?: boolean; /** * If true, a raw snapshot without artificial roots will be generated */ treatGlobalObjectsAsRoots?: boolean; /** * If true, numerical values are included in the snapshot */ captureNumericValue?: boolean; } /** * Return value of the 'HeapProfiler.takeHeapSnapshot' method. */ export interface TakeHeapSnapshotResult {} /** * Parameters of the 'HeapProfiler.addHeapSnapshotChunk' event. */ export interface AddHeapSnapshotChunkEvent { chunk: string; } /** * Parameters of the 'HeapProfiler.heapStatsUpdate' event. */ export interface HeapStatsUpdateEvent { /** * An array of triplets. Each triplet describes a fragment. The first integer is the fragment * index, the second integer is a total count of objects for the fragment, the third integer is * a total size of the objects for the fragment. */ statsUpdate: integer[]; } /** * Parameters of the 'HeapProfiler.lastSeenObjectId' event. */ export interface LastSeenObjectIdEvent { lastSeenObjectId: integer; timestamp: number; } /** * Parameters of the 'HeapProfiler.reportHeapSnapshotProgress' event. */ export interface ReportHeapSnapshotProgressEvent { done: integer; total: integer; finished?: boolean; } /** * Parameters of the 'HeapProfiler.resetProfiles' event. */ export interface ResetProfilesEvent {} /** * Heap snapshot object id. */ export type HeapSnapshotObjectId = string; /** * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. */ export interface SamplingHeapProfileNode { /** * Function location. */ callFrame: Runtime.CallFrame; /** * Allocations size in bytes for the node excluding children. */ selfSize: number; /** * Node id. Ids are unique across all profiles collected between startSampling and stopSampling. */ id: integer; /** * Child nodes. */ children: SamplingHeapProfileNode[]; } /** * A single sample from a sampling profile. */ export interface SamplingHeapProfileSample { /** * Allocation size in bytes attributed to the sample. */ size: number; /** * Id of the corresponding profile tree node. */ nodeId: integer; /** * Time-ordered sample ordinal number. It is unique across all profiles retrieved * between startSampling and stopSampling. */ ordinal: number; } /** * Sampling profile. */ export interface SamplingHeapProfile { head: SamplingHeapProfileNode; samples: SamplingHeapProfileSample[]; } } /** * Methods and events of the 'IndexedDB' domain. */ export interface IndexedDBApi { /** * Clears all entries from an object store. */ clearObjectStore( params: IndexedDB.ClearObjectStoreParams, ): Promise<IndexedDB.ClearObjectStoreResult | undefined>; /** * Deletes a database. */ deleteDatabase( params: IndexedDB.DeleteDatabaseParams, ): Promise<IndexedDB.DeleteDatabaseResult | undefined>; /** * Delete a range of entries from an object store */ deleteObjectStoreEntries( params: IndexedDB.DeleteObjectStoreEntriesParams, ): Promise<IndexedDB.DeleteObjectStoreEntriesResult | undefined>; /** * Disables events from backend. */ disable(params: IndexedDB.DisableParams): Promise<IndexedDB.DisableResult | undefined>; /** * Enables events from backend. */ enable(params: IndexedDB.EnableParams): Promise<IndexedDB.EnableResult | undefined>; /** * Requests data from object store or index. */ requestData( params: IndexedDB.RequestDataParams, ): Promise<IndexedDB.RequestDataResult | undefined>; /** * Gets metadata of an object store */ getMetadata( params: IndexedDB.GetMetadataParams, ): Promise<IndexedDB.GetMetadataResult | undefined>; /** * Requests database with given name in given frame. */ requestDatabase( params: IndexedDB.RequestDatabaseParams, ): Promise<IndexedDB.RequestDatabaseResult | undefined>; /** * Requests database names for given security origin. */ requestDatabaseNames( params: IndexedDB.RequestDatabaseNamesParams, ): Promise<IndexedDB.RequestDatabaseNamesResult | undefined>; } /** * Types of the 'IndexedDB' domain. */ export namespace IndexedDB { /** * Parameters of the 'IndexedDB.clearObjectStore' method. */ export interface ClearObjectStoreParams { /** * Security origin. */ securityOrigin: string; /** * Database name. */ databaseName: string; /** * Object store name. */ objectStoreName: string; } /** * Return value of the 'IndexedDB.clearObjectStore' method. */ export interface ClearObjectStoreResult {} /** * Parameters of the 'IndexedDB.deleteDatabase' method. */ export interface DeleteDatabaseParams { /** * Security origin. */ securityOrigin: string; /** * Database name. */ databaseName: string; } /** * Return value of the 'IndexedDB.deleteDatabase' method. */ export interface DeleteDatabaseResult {} /** * Parameters of the 'IndexedDB.deleteObjectStoreEntries' method. */ export interface DeleteObjectStoreEntriesParams { securityOrigin: string; databaseName: string; objectStoreName: string; /** * Range of entry keys to delete */ keyRange: KeyRange; } /** * Return value of the 'IndexedDB.deleteObjectStoreEntries' method. */ export interface DeleteObjectStoreEntriesResult {} /** * Parameters of the 'IndexedDB.disable' method. */ export interface DisableParams {} /** * Return value of the 'IndexedDB.disable' method. */ export interface DisableResult {} /** * Parameters of the 'IndexedDB.enable' method. */ export interface EnableParams {} /** * Return value of the 'IndexedDB.enable' method. */ export interface EnableResult {} /** * Parameters of the 'IndexedDB.requestData' method. */ export interface RequestDataParams { /** * Security origin. */ securityOrigin: string; /** * Database name. */ databaseName: string; /** * Object store name. */ objectStoreName: string; /** * Index name, empty string for object store data requests. */ indexName: string; /** * Number of records to skip. */ skipCount: integer; /** * Number of records to fetch. */ pageSize: integer; /** * Key range. */ keyRange?: KeyRange; } /** * Return value of the 'IndexedDB.requestData' method. */ export interface RequestDataResult { /** * Array of object store data entries. */ objectStoreDataEntries: DataEntry[]; /** * If true, there are more entries to fetch in the given range. */ hasMore: boolean; } /** * Parameters of the 'IndexedDB.getMetadata' method. */ export interface GetMetadataParams { /** * Security origin. */ securityOrigin: string; /** * Database name. */ databaseName: string; /** * Object store name. */ objectStoreName: string; } /** * Return value of the 'IndexedDB.getMetadata' method. */ export interface GetMetadataResult { /** * the entries count */ entriesCount: number; /** * the current value of key generator, to become the next inserted * key into the object store. Valid if objectStore.autoIncrement * is true. */ keyGeneratorValue: number; } /** * Parameters of the 'IndexedDB.requestDatabase' method. */ export interface RequestDatabaseParams { /** * Security origin. */ securityOrigin: string; /** * Database name. */ databaseName: string; } /** * Return value of the 'IndexedDB.requestDatabase' method. */ export interface RequestDatabaseResult { /** * Database with an array of object stores. */ databaseWithObjectStores: DatabaseWithObjectStores; } /** * Parameters of the 'IndexedDB.requestDatabaseNames' method. */ export interface RequestDatabaseNamesParams { /** * Security origin. */ securityOrigin: string; } /** * Return value of the 'IndexedDB.requestDatabaseNames' method. */ export interface RequestDatabaseNamesResult { /** * Database names for origin. */ databaseNames: string[]; } /** * Database with an array of object stores. */ export interface DatabaseWithObjectStores { /** * Database name. */ name: string; /** * Database version (type is not 'integer', as the standard * requires the version number to be 'unsigned long long') */ version: number; /** * Object stores in this database. */ objectStores: ObjectStore[]; } /** * Object store. */ export interface ObjectStore { /** * Object store name. */ name: string; /** * Object store key path. */ keyPath: KeyPath; /** * If true, object store has auto increment flag set. */ autoIncrement: boolean; /** * Indexes in this object store. */ indexes: ObjectStoreIndex[]; } /** * Object store index. */ export interface ObjectStoreIndex { /** * Index name. */ name: string; /** * Index key path. */ keyPath: KeyPath; /** * If true, index is unique. */ unique: boolean; /** * If true, index allows multiple entries for a key. */ multiEntry: boolean; } /** * Key. */ export interface Key { /** * Key type. */ type: 'number' | 'string' | 'date' | 'array'; /** * Number value. */ number?: number; /** * String value. */ string?: string; /** * Date value. */ date?: number; /** * Array value. */ array?: Key[]; } /** * Key range. */ export interface KeyRange { /** * Lower bound. */ lower?: Key; /** * Upper bound. */ upper?: Key; /** * If true lower bound is open. */ lowerOpen: boolean; /** * If true upper bound is open. */ upperOpen: boolean; } /** * Data entry. */ export interface DataEntry { /** * Key object. */ key: Runtime.RemoteObject; /** * Primary key object. */ primaryKey: Runtime.RemoteObject; /** * Value object. */ value: Runtime.RemoteObject; } /** * Key path. */ export interface KeyPath { /** * Key path type. */ type: 'null' | 'string' | 'array'; /** * String value. */ string?: string; /** * Array value. */ array?: string[]; } } /** * Methods and events of the 'Input' domain. */ export interface InputApi { /** * Dispatches a drag event into the page. */ dispatchDragEvent( params: Input.DispatchDragEventParams, ): Promise<Input.DispatchDragEventResult | undefined>; /** * Dispatches a key event to the page. */ dispatchKeyEvent( params: Input.DispatchKeyEventParams, ): Promise<Input.DispatchKeyEventResult | undefined>; /** * This method emulates inserting text that doesn't come from a key press, * for example an emoji keyboard or an IME. */ insertText(params: Input.InsertTextParams): Promise<Input.InsertTextResult | undefined>; /** * This method sets the current candidate text for ime. * Use imeCommitComposition to commit the final text. * Use imeSetComposition with empty string as text to cancel composition. */ imeSetComposition( params: Input.ImeSetCompositionParams, ): Promise<Input.ImeSetCompositionResult | undefined>; /** * Dispatches a mouse event to the page. */ dispatchMouseEvent( params: Input.DispatchMouseEventParams, ): Promise<Input.DispatchMouseEventResult | undefined>; /** * Dispatches a touch event to the page. */ dispatchTouchEvent( params: Input.DispatchTouchEventParams, ): Promise<Input.DispatchTouchEventResult | undefined>; /** * Emulates touch event from the mouse event parameters. */ emulateTouchFromMouseEvent( params: Input.EmulateTouchFromMouseEventParams, ): Promise<Input.EmulateTouchFromMouseEventResult | undefined>; /** * Ignores input events (useful while auditing page). */ setIgnoreInputEvents( params: Input.SetIgnoreInputEventsParams, ): Promise<Input.SetIgnoreInputEventsResult | undefined>; /** * Prevents default drag and drop behavior and instead emits `Input.dragIntercepted` events. * Drag and drop behavior can be directly controlled via `Input.dispatchDragEvent`. */ setInterceptDrags( params: Input.SetInterceptDragsParams, ): Promise<Input.SetInterceptDragsResult | undefined>; /** * Synthesizes a pinch gesture over a time period by issuing appropriate touch events. */ synthesizePinchGesture( params: Input.SynthesizePinchGestureParams, ): Promise<Input.SynthesizePinchGestureResult | undefined>; /** * Synthesizes a scroll gesture over a time period by issuing appropriate touch events. */ synthesizeScrollGesture( params: Input.SynthesizeScrollGestureParams, ): Promise<Input.SynthesizeScrollGestureResult | undefined>; /** * Synthesizes a tap gesture over a time period by issuing appropriate touch events. */ synthesizeTapGesture( params: Input.SynthesizeTapGestureParams, ): Promise<Input.SynthesizeTapGestureResult | undefined>; /** * Emitted only when `Input.setInterceptDrags` is enabled. Use this data with `Input.dispatchDragEvent` to * restore normal drag and drop behavior. */ on( event: 'dragIntercepted', listener: (event: Input.DragInterceptedEvent) => void, ): IDisposable; } /** * Types of the 'Input' domain. */ export namespace Input { /** * Parameters of the 'Input.dispatchDragEvent' method. */ export interface DispatchDragEventParams { /** * Type of the drag event. */ type: 'dragEnter' | 'dragOver' | 'drop' | 'dragCancel'; /** * X coordinate of the event relative to the main frame's viewport in CSS pixels. */ x: number; /** * Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to * the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. */ y: number; data: DragData; /** * Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 * (default: 0). */ modifiers?: integer; } /** * Return value of the 'Input.dispatchDragEvent' method. */ export interface DispatchDragEventResult {} /** * Parameters of the 'Input.dispatchKeyEvent' method. */ export interface DispatchKeyEventParams { /** * Type of the key event. */ type: 'keyDown' | 'keyUp' | 'rawKeyDown' | 'char'; /** * Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 * (default: 0). */ modifiers?: integer; /** * Time at which the event occurred. */ timestamp?: TimeSinceEpoch; /** * Text as generated by processing a virtual key code with a keyboard layout. Not needed for * for `keyUp` and `rawKeyDown` events (default: "") */ text?: string; /** * Text that would have been generated by the keyboard if no modifiers were pressed (except for * shift). Useful for shortcut (accelerator) key handling (default: ""). */ unmodifiedText?: string; /** * Unique key identifier (e.g., 'U+0041') (default: ""). */ keyIdentifier?: string; /** * Unique DOM defined string value for each physical key (e.g., 'KeyA') (default: ""). */ code?: string; /** * Unique DOM defined string value describing the meaning of the key in the context of active * modifiers, keyboard layout, etc (e.g., 'AltGr') (default: ""). */ key?: string; /** * Windows virtual key code (default: 0). */ windowsVirtualKeyCode?: integer; /** * Native virtual key code (default: 0). */ nativeVirtualKeyCode?: integer; /** * Whether the event was generated from auto repeat (default: false). */ autoRepeat?: boolean; /** * Whether the event was generated from the keypad (default: false). */ isKeypad?: boolean; /** * Whether the event was a system key event (default: false). */ isSystemKey?: boolean; /** * Whether the event was from the left or right side of the keyboard. 1=Left, 2=Right (default: * 0). */ location?: integer; /** * Editing commands to send with the key event (e.g., 'selectAll') (default: []). * These are related to but not equal the command names used in `document.execCommand` and NSStandardKeyBindingResponding. * See https://source.chromium.org/chromium/chromium/src/+/master:third_party/blink/renderer/core/editing/commands/editor_command_names.h for valid command names. */ commands?: string[]; } /** * Return value of the 'Input.dispatchKeyEvent' method. */ export interface DispatchKeyEventResult {} /** * Parameters of the 'Input.insertText' method. */ export interface InsertTextParams { /** * The text to insert. */ text: string; } /** * Return value of the 'Input.insertText' method. */ export interface InsertTextResult {} /** * Parameters of the 'Input.imeSetComposition' method. */ export interface ImeSetCompositionParams { /** * The text to insert */ text: string; /** * selection start */ selectionStart: integer; /** * selection end */ selectionEnd: integer; /** * replacement start */ replacementStart?: integer; /** * replacement end */ replacementEnd?: integer; } /** * Return value of the 'Input.imeSetComposition' method. */ export interface ImeSetCompositionResult {} /** * Parameters of the 'Input.dispatchMouseEvent' method. */ export interface DispatchMouseEventParams { /** * Type of the mouse event. */ type: 'mousePressed' | 'mouseReleased' | 'mouseMoved' | 'mouseWheel'; /** * X coordinate of the event relative to the main frame's viewport in CSS pixels. */ x: number; /** * Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to * the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. */ y: number; /** * Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 * (default: 0). */ modifiers?: integer; /** * Time at which the event occurred. */ timestamp?: TimeSinceEpoch; /** * Mouse button (default: "none"). */ button?: MouseButton; /** * A number indicating which buttons are pressed on the mouse when a mouse event is triggered. * Left=1, Right=2, Middle=4, Back=8, Forward=16, None=0. */ buttons?: integer; /** * Number of times the mouse button was clicked (default: 0). */ clickCount?: integer; /** * The normalized pressure, which has a range of [0,1] (default: 0). */ force?: number; /** * The normalized tangential pressure, which has a range of [-1,1] (default: 0). */ tangentialPressure?: number; /** * The plane angle between the Y-Z plane and the plane containing both the stylus axis and the Y axis, in degrees of the range [-90,90], a positive tiltX is to the right (default: 0). */ tiltX?: integer; /** * The plane angle between the X-Z plane and the plane containing both the stylus axis and the X axis, in degrees of the range [-90,90], a positive tiltY is towards the user (default: 0). */ tiltY?: integer; /** * The clockwise rotation of a pen stylus around its own major axis, in degrees in the range [0,359] (default: 0). */ twist?: integer; /** * X delta in CSS pixels for mouse wheel event (default: 0). */ deltaX?: number; /** * Y delta in CSS pixels for mouse wheel event (default: 0). */ deltaY?: number; /** * Pointer type (default: "mouse"). */ pointerType?: 'mouse' | 'pen'; } /** * Return value of the 'Input.dispatchMouseEvent' method. */ export interface DispatchMouseEventResult {} /** * Parameters of the 'Input.dispatchTouchEvent' method. */ export interface DispatchTouchEventParams { /** * Type of the touch event. TouchEnd and TouchCancel must not contain any touch points, while * TouchStart and TouchMove must contains at least one. */ type: 'touchStart' | 'touchEnd' | 'touchMove' | 'touchCancel'; /** * Active touch points on the touch device. One event per any changed point (compared to * previous touch event in a sequence) is generated, emulating pressing/moving/releasing points * one by one. */ touchPoints: TouchPoint[]; /** * Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 * (default: 0). */ modifiers?: integer; /** * Time at which the event occurred. */ timestamp?: TimeSinceEpoch; } /** * Return value of the 'Input.dispatchTouchEvent' method. */ export interface DispatchTouchEventResult {} /** * Parameters of the 'Input.emulateTouchFromMouseEvent' method. */ export interface EmulateTouchFromMouseEventParams { /** * Type of the mouse event. */ type: 'mousePressed' | 'mouseReleased' | 'mouseMoved' | 'mouseWheel'; /** * X coordinate of the mouse pointer in DIP. */ x: integer; /** * Y coordinate of the mouse pointer in DIP. */ y: integer; /** * Mouse button. Only "none", "left", "right" are supported. */ button: MouseButton; /** * Time at which the event occurred (default: current time). */ timestamp?: TimeSinceEpoch; /** * X delta in DIP for mouse wheel event (default: 0). */ deltaX?: number; /** * Y delta in DIP for mouse wheel event (default: 0). */ deltaY?: number; /** * Bit field representing pressed modifier keys. Alt=1, Ctrl=2, Meta/Command=4, Shift=8 * (default: 0). */ modifiers?: integer; /** * Number of times the mouse button was clicked (default: 0). */ clickCount?: integer; } /** * Return value of the 'Input.emulateTouchFromMouseEvent' method. */ export interface EmulateTouchFromMouseEventResult {} /** * Parameters of the 'Input.setIgnoreInputEvents' method. */ export interface SetIgnoreInputEventsParams { /** * Ignores input events processing when set to true. */ ignore: boolean; } /** * Return value of the 'Input.setIgnoreInputEvents' method. */ export interface SetIgnoreInputEventsResult {} /** * Parameters of the 'Input.setInterceptDrags' method. */ export interface SetInterceptDragsParams { enabled: boolean; } /** * Return value of the 'Input.setInterceptDrags' method. */ export interface SetInterceptDragsResult {} /** * Parameters of the 'Input.synthesizePinchGesture' method. */ export interface SynthesizePinchGestureParams { /** * X coordinate of the start of the gesture in CSS pixels. */ x: number; /** * Y coordinate of the start of the gesture in CSS pixels. */ y: number; /** * Relative scale factor after zooming (>1.0 zooms in, <1.0 zooms out). */ scaleFactor: number; /** * Relative pointer speed in pixels per second (default: 800). */ relativeSpeed?: integer; /** * Which type of input events to be generated (default: 'default', which queries the platform * for the preferred input type). */ gestureSourceType?: GestureSourceType; } /** * Return value of the 'Input.synthesizePinchGesture' method. */ export interface SynthesizePinchGestureResult {} /** * Parameters of the 'Input.synthesizeScrollGesture' method. */ export interface SynthesizeScrollGestureParams { /** * X coordinate of the start of the gesture in CSS pixels. */ x: number; /** * Y coordinate of the start of the gesture in CSS pixels. */ y: number; /** * The distance to scroll along the X axis (positive to scroll left). */ xDistance?: number; /** * The distance to scroll along the Y axis (positive to scroll up). */ yDistance?: number; /** * The number of additional pixels to scroll back along the X axis, in addition to the given * distance. */ xOverscroll?: number; /** * The number of additional pixels to scroll back along the Y axis, in addition to the given * distance. */ yOverscroll?: number; /** * Prevent fling (default: true). */ preventFling?: boolean; /** * Swipe speed in pixels per second (default: 800). */ speed?: integer; /** * Which type of input events to be generated (default: 'default', which queries the platform * for the preferred input type). */ gestureSourceType?: GestureSourceType; /** * The number of times to repeat the gesture (default: 0). */ repeatCount?: integer; /** * The number of milliseconds delay between each repeat. (default: 250). */ repeatDelayMs?: integer; /** * The name of the interaction markers to generate, if not empty (default: ""). */ interactionMarkerName?: string; } /** * Return value of the 'Input.synthesizeScrollGesture' method. */ export interface SynthesizeScrollGestureResult {} /** * Parameters of the 'Input.synthesizeTapGesture' method. */ export interface SynthesizeTapGestureParams { /** * X coordinate of the start of the gesture in CSS pixels. */ x: number; /** * Y coordinate of the start of the gesture in CSS pixels. */ y: number; /** * Duration between touchdown and touchup events in ms (default: 50). */ duration?: integer; /** * Number of times to perform the tap (e.g. 2 for double tap, default: 1). */ tapCount?: integer; /** * Which type of input events to be generated (default: 'default', which queries the platform * for the preferred input type). */ gestureSourceType?: GestureSourceType; } /** * Return value of the 'Input.synthesizeTapGesture' method. */ export interface SynthesizeTapGestureResult {} /** * Parameters of the 'Input.dragIntercepted' event. */ export interface DragInterceptedEvent { data: DragData; } export interface TouchPoint { /** * X coordinate of the event relative to the main frame's viewport in CSS pixels. */ x: number; /** * Y coordinate of the event relative to the main frame's viewport in CSS pixels. 0 refers to * the top of the viewport and Y increases as it proceeds towards the bottom of the viewport. */ y: number; /** * X radius of the touch area (default: 1.0). */ radiusX?: number; /** * Y radius of the touch area (default: 1.0). */ radiusY?: number; /** * Rotation angle (default: 0.0). */ rotationAngle?: number; /** * Force (default: 1.0). */ force?: number; /** * The normalized tangential pressure, which has a range of [-1,1] (default: 0). */ tangentialPressure?: number; /** * The plane angle between the Y-Z plane and the plane containing both the stylus axis and the Y axis, in degrees of the range [-90,90], a positive tiltX is to the right (default: 0) */ tiltX?: integer; /** * The plane angle between the X-Z plane and the plane containing both the stylus axis and the X axis, in degrees of the range [-90,90], a positive tiltY is towards the user (default: 0). */ tiltY?: integer; /** * The clockwise rotation of a pen stylus around its own major axis, in degrees in the range [0,359] (default: 0). */ twist?: integer; /** * Identifier used to track touch sources between events, must be unique within an event. */ id?: number; } export type GestureSourceType = 'default' | 'touch' | 'mouse'; export type MouseButton = 'none' | 'left' | 'middle' | 'right' | 'back' | 'forward'; /** * UTC time in seconds, counted from January 1, 1970. */ export type TimeSinceEpoch = number; export interface DragDataItem { /** * Mime type of the dragged data. */ mimeType: string; /** * Depending of the value of `mimeType`, it contains the dragged link, * text, HTML markup or any other data. */ data: string; /** * Title associated with a link. Only valid when `mimeType` == "text/uri-list". */ title?: string; /** * Stores the base URL for the contained markup. Only valid when `mimeType` * == "text/html". */ baseURL?: string; } export interface DragData { items: DragDataItem[]; /** * List of filenames that should be included when dropping */ files?: string[]; /** * Bit field representing allowed drag operations. Copy = 1, Link = 2, Move = 16 */ dragOperationsMask: integer; } } /** * Methods and events of the 'Inspector' domain. */ export interface InspectorApi { /** * Disables inspector domain notifications. */ disable(params: Inspector.DisableParams): Promise<Inspector.DisableResult | undefined>; /** * Enables inspector domain notifications. */ enable(params: Inspector.EnableParams): Promise<Inspector.EnableResult | undefined>; /** * Fired when remote debugging connection is about to be terminated. Contains detach reason. */ on(event: 'detached', listener: (event: Inspector.DetachedEvent) => void): IDisposable; /** * Fired when debugging target has crashed */ on( event: 'targetCrashed', listener: (event: Inspector.TargetCrashedEvent) => void, ): IDisposable; /** * Fired when debugging target has reloaded after crash */ on( event: 'targetReloadedAfterCrash', listener: (event: Inspector.TargetReloadedAfterCrashEvent) => void, ): IDisposable; } /** * Types of the 'Inspector' domain. */ export namespace Inspector { /** * Parameters of the 'Inspector.disable' method. */ export interface DisableParams {} /** * Return value of the 'Inspector.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Inspector.enable' method. */ export interface EnableParams {} /** * Return value of the 'Inspector.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Inspector.detached' event. */ export interface DetachedEvent { /** * The reason why connection has been terminated. */ reason: string; } /** * Parameters of the 'Inspector.targetCrashed' event. */ export interface TargetCrashedEvent {} /** * Parameters of the 'Inspector.targetReloadedAfterCrash' event. */ export interface TargetReloadedAfterCrashEvent {} } /** * Methods and events of the 'IO' domain. */ export interface IOApi { /** * Close the stream, discard any temporary backing storage. */ close(params: IO.CloseParams): Promise<IO.CloseResult | undefined>; /** * Read a chunk of the stream */ read(params: IO.ReadParams): Promise<IO.ReadResult | undefined>; /** * Return UUID of Blob object specified by a remote object id. */ resolveBlob(params: IO.ResolveBlobParams): Promise<IO.ResolveBlobResult | undefined>; } /** * Types of the 'IO' domain. */ export namespace IO { /** * Parameters of the 'IO.close' method. */ export interface CloseParams { /** * Handle of the stream to close. */ handle: StreamHandle; } /** * Return value of the 'IO.close' method. */ export interface CloseResult {} /** * Parameters of the 'IO.read' method. */ export interface ReadParams { /** * Handle of the stream to read. */ handle: StreamHandle; /** * Seek to the specified offset before reading (if not specificed, proceed with offset * following the last read). Some types of streams may only support sequential reads. */ offset?: integer; /** * Maximum number of bytes to read (left upon the agent discretion if not specified). */ size?: integer; } /** * Return value of the 'IO.read' method. */ export interface ReadResult { /** * Set if the data is base64-encoded */ base64Encoded?: boolean; /** * Data that were read. */ data: string; /** * Set if the end-of-file condition occurred while reading. */ eof: boolean; } /** * Parameters of the 'IO.resolveBlob' method. */ export interface ResolveBlobParams { /** * Object id of a Blob object wrapper. */ objectId: Runtime.RemoteObjectId; } /** * Return value of the 'IO.resolveBlob' method. */ export interface ResolveBlobResult { /** * UUID of the specified Blob. */ uuid: string; } /** * This is either obtained from another method or specified as `blob:&lt;uuid&gt;` where * `&lt;uuid&gt` is an UUID of a Blob. */ export type StreamHandle = string; } /** * Methods and events of the 'JsDebug' domain. */ export interface JsDebugApi { /** * Subscribes to the given CDP event(s). Events will not be sent through the * connection unless you subscribe to them */ subscribe(params: JsDebug.SubscribeParams): Promise<JsDebug.SubscribeResult | undefined>; } /** * Types of the 'JsDebug' domain. */ export namespace JsDebug { /** * Parameters of the 'JsDebug.subscribe' method. */ export interface SubscribeParams { /** * List of events to subscribe to. Supports wildcards, for example * you can subscribe to `Debugger.scriptParsed` or `Debugger.*` */ events: string[]; } /** * Return value of the 'JsDebug.subscribe' method. */ export interface SubscribeResult {} } /** * Methods and events of the 'LayerTree' domain. */ export interface LayerTreeApi { /** * Provides the reasons why the given layer was composited. */ compositingReasons( params: LayerTree.CompositingReasonsParams, ): Promise<LayerTree.CompositingReasonsResult | undefined>; /** * Disables compositing tree inspection. */ disable(params: LayerTree.DisableParams): Promise<LayerTree.DisableResult | undefined>; /** * Enables compositing tree inspection. */ enable(params: LayerTree.EnableParams): Promise<LayerTree.EnableResult | undefined>; /** * Returns the snapshot identifier. */ loadSnapshot( params: LayerTree.LoadSnapshotParams, ): Promise<LayerTree.LoadSnapshotResult | undefined>; /** * Returns the layer snapshot identifier. */ makeSnapshot( params: LayerTree.MakeSnapshotParams, ): Promise<LayerTree.MakeSnapshotResult | undefined>; profileSnapshot( params: LayerTree.ProfileSnapshotParams, ): Promise<LayerTree.ProfileSnapshotResult | undefined>; /** * Releases layer snapshot captured by the back-end. */ releaseSnapshot( params: LayerTree.ReleaseSnapshotParams, ): Promise<LayerTree.ReleaseSnapshotResult | undefined>; /** * Replays the layer snapshot and returns the resulting bitmap. */ replaySnapshot( params: LayerTree.ReplaySnapshotParams, ): Promise<LayerTree.ReplaySnapshotResult | undefined>; /** * Replays the layer snapshot and returns canvas log. */ snapshotCommandLog( params: LayerTree.SnapshotCommandLogParams, ): Promise<LayerTree.SnapshotCommandLogResult | undefined>; on(event: 'layerPainted', listener: (event: LayerTree.LayerPaintedEvent) => void): IDisposable; on( event: 'layerTreeDidChange', listener: (event: LayerTree.LayerTreeDidChangeEvent) => void, ): IDisposable; } /** * Types of the 'LayerTree' domain. */ export namespace LayerTree { /** * Parameters of the 'LayerTree.compositingReasons' method. */ export interface CompositingReasonsParams { /** * The id of the layer for which we want to get the reasons it was composited. */ layerId: LayerId; } /** * Return value of the 'LayerTree.compositingReasons' method. */ export interface CompositingReasonsResult { /** * A list of strings specifying reasons for the given layer to become composited. * @deprecated */ compositingReasons: string[]; /** * A list of strings specifying reason IDs for the given layer to become composited. */ compositingReasonIds: string[]; } /** * Parameters of the 'LayerTree.disable' method. */ export interface DisableParams {} /** * Return value of the 'LayerTree.disable' method. */ export interface DisableResult {} /** * Parameters of the 'LayerTree.enable' method. */ export interface EnableParams {} /** * Return value of the 'LayerTree.enable' method. */ export interface EnableResult {} /** * Parameters of the 'LayerTree.loadSnapshot' method. */ export interface LoadSnapshotParams { /** * An array of tiles composing the snapshot. */ tiles: PictureTile[]; } /** * Return value of the 'LayerTree.loadSnapshot' method. */ export interface LoadSnapshotResult { /** * The id of the snapshot. */ snapshotId: SnapshotId; } /** * Parameters of the 'LayerTree.makeSnapshot' method. */ export interface MakeSnapshotParams { /** * The id of the layer. */ layerId: LayerId; } /** * Return value of the 'LayerTree.makeSnapshot' method. */ export interface MakeSnapshotResult { /** * The id of the layer snapshot. */ snapshotId: SnapshotId; } /** * Parameters of the 'LayerTree.profileSnapshot' method. */ export interface ProfileSnapshotParams { /** * The id of the layer snapshot. */ snapshotId: SnapshotId; /** * The maximum number of times to replay the snapshot (1, if not specified). */ minRepeatCount?: integer; /** * The minimum duration (in seconds) to replay the snapshot. */ minDuration?: number; /** * The clip rectangle to apply when replaying the snapshot. */ clipRect?: DOM.Rect; } /** * Return value of the 'LayerTree.profileSnapshot' method. */ export interface ProfileSnapshotResult { /** * The array of paint profiles, one per run. */ timings: PaintProfile[]; } /** * Parameters of the 'LayerTree.releaseSnapshot' method. */ export interface ReleaseSnapshotParams { /** * The id of the layer snapshot. */ snapshotId: SnapshotId; } /** * Return value of the 'LayerTree.releaseSnapshot' method. */ export interface ReleaseSnapshotResult {} /** * Parameters of the 'LayerTree.replaySnapshot' method. */ export interface ReplaySnapshotParams { /** * The id of the layer snapshot. */ snapshotId: SnapshotId; /** * The first step to replay from (replay from the very start if not specified). */ fromStep?: integer; /** * The last step to replay to (replay till the end if not specified). */ toStep?: integer; /** * The scale to apply while replaying (defaults to 1). */ scale?: number; } /** * Return value of the 'LayerTree.replaySnapshot' method. */ export interface ReplaySnapshotResult { /** * A data: URL for resulting image. */ dataURL: string; } /** * Parameters of the 'LayerTree.snapshotCommandLog' method. */ export interface SnapshotCommandLogParams { /** * The id of the layer snapshot. */ snapshotId: SnapshotId; } /** * Return value of the 'LayerTree.snapshotCommandLog' method. */ export interface SnapshotCommandLogResult { /** * The array of canvas function calls. */ commandLog: any[]; } /** * Parameters of the 'LayerTree.layerPainted' event. */ export interface LayerPaintedEvent { /** * The id of the painted layer. */ layerId: LayerId; /** * Clip rectangle. */ clip: DOM.Rect; } /** * Parameters of the 'LayerTree.layerTreeDidChange' event. */ export interface LayerTreeDidChangeEvent { /** * Layer tree, absent if not in the comspositing mode. */ layers?: Layer[]; } /** * Unique Layer identifier. */ export type LayerId = string; /** * Unique snapshot identifier. */ export type SnapshotId = string; /** * Rectangle where scrolling happens on the main thread. */ export interface ScrollRect { /** * Rectangle itself. */ rect: DOM.Rect; /** * Reason for rectangle to force scrolling on the main thread */ type: 'RepaintsOnScroll' | 'TouchEventHandler' | 'WheelEventHandler'; } /** * Sticky position constraints. */ export interface StickyPositionConstraint { /** * Layout rectangle of the sticky element before being shifted */ stickyBoxRect: DOM.Rect; /** * Layout rectangle of the containing block of the sticky element */ containingBlockRect: DOM.Rect; /** * The nearest sticky layer that shifts the sticky box */ nearestLayerShiftingStickyBox?: LayerId; /** * The nearest sticky layer that shifts the containing block */ nearestLayerShiftingContainingBlock?: LayerId; } /** * Serialized fragment of layer picture along with its offset within the layer. */ export interface PictureTile { /** * Offset from owning layer left boundary */ x: number; /** * Offset from owning layer top boundary */ y: number; /** * Base64-encoded snapshot data. (Encoded as a base64 string when passed over JSON) */ picture: string; } /** * Information about a compositing layer. */ export interface Layer { /** * The unique id for this layer. */ layerId: LayerId; /** * The id of parent (not present for root). */ parentLayerId?: LayerId; /** * The backend id for the node associated with this layer. */ backendNodeId?: DOM.BackendNodeId; /** * Offset from parent layer, X coordinate. */ offsetX: number; /** * Offset from parent layer, Y coordinate. */ offsetY: number; /** * Layer width. */ width: number; /** * Layer height. */ height: number; /** * Transformation matrix for layer, default is identity matrix */ transform?: number[]; /** * Transform anchor point X, absent if no transform specified */ anchorX?: number; /** * Transform anchor point Y, absent if no transform specified */ anchorY?: number; /** * Transform anchor point Z, absent if no transform specified */ anchorZ?: number; /** * Indicates how many time this layer has painted. */ paintCount: integer; /** * Indicates whether this layer hosts any content, rather than being used for * transform/scrolling purposes only. */ drawsContent: boolean; /** * Set if layer is not visible. */ invisible?: boolean; /** * Rectangles scrolling on main thread only. */ scrollRects?: ScrollRect[]; /** * Sticky position constraint information */ stickyPositionConstraint?: StickyPositionConstraint; } /** * Array of timings, one per paint step. */ export type PaintProfile = number[]; } /** * Methods and events of the 'Log' domain. */ export interface LogApi { /** * Clears the log. */ clear(params: Log.ClearParams): Promise<Log.ClearResult | undefined>; /** * Disables log domain, prevents further log entries from being reported to the client. */ disable(params: Log.DisableParams): Promise<Log.DisableResult | undefined>; /** * Enables log domain, sends the entries collected so far to the client by means of the * `entryAdded` notification. */ enable(params: Log.EnableParams): Promise<Log.EnableResult | undefined>; /** * start violation reporting. */ startViolationsReport( params: Log.StartViolationsReportParams, ): Promise<Log.StartViolationsReportResult | undefined>; /** * Stop violation reporting. */ stopViolationsReport( params: Log.StopViolationsReportParams, ): Promise<Log.StopViolationsReportResult | undefined>; /** * Issued when new message was logged. */ on(event: 'entryAdded', listener: (event: Log.EntryAddedEvent) => void): IDisposable; } /** * Types of the 'Log' domain. */ export namespace Log { /** * Parameters of the 'Log.clear' method. */ export interface ClearParams {} /** * Return value of the 'Log.clear' method. */ export interface ClearResult {} /** * Parameters of the 'Log.disable' method. */ export interface DisableParams {} /** * Return value of the 'Log.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Log.enable' method. */ export interface EnableParams {} /** * Return value of the 'Log.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Log.startViolationsReport' method. */ export interface StartViolationsReportParams { /** * Configuration for violations. */ config: ViolationSetting[]; } /** * Return value of the 'Log.startViolationsReport' method. */ export interface StartViolationsReportResult {} /** * Parameters of the 'Log.stopViolationsReport' method. */ export interface StopViolationsReportParams {} /** * Return value of the 'Log.stopViolationsReport' method. */ export interface StopViolationsReportResult {} /** * Parameters of the 'Log.entryAdded' event. */ export interface EntryAddedEvent { /** * The entry. */ entry: LogEntry; } /** * Log entry. */ export interface LogEntry { /** * Log entry source. */ source: | 'xml' | 'javascript' | 'network' | 'storage' | 'appcache' | 'rendering' | 'security' | 'deprecation' | 'worker' | 'violation' | 'intervention' | 'recommendation' | 'other'; /** * Log entry severity. */ level: 'verbose' | 'info' | 'warning' | 'error'; /** * Logged text. */ text: string; category?: 'cors'; /** * Timestamp when this entry was added. */ timestamp: Runtime.Timestamp; /** * URL of the resource if known. */ url?: string; /** * Line number in the resource. */ lineNumber?: integer; /** * JavaScript stack trace. */ stackTrace?: Runtime.StackTrace; /** * Identifier of the network request associated with this entry. */ networkRequestId?: Network.RequestId; /** * Identifier of the worker associated with this entry. */ workerId?: string; /** * Call arguments. */ args?: Runtime.RemoteObject[]; } /** * Violation configuration setting. */ export interface ViolationSetting { /** * Violation type. */ name: | 'longTask' | 'longLayout' | 'blockedEvent' | 'blockedParser' | 'discouragedAPIUse' | 'handler' | 'recurringHandler'; /** * Time threshold to trigger upon. */ threshold: number; } } /** * Methods and events of the 'Media' domain. */ export interface MediaApi { /** * Enables the Media domain */ enable(params: Media.EnableParams): Promise<Media.EnableResult | undefined>; /** * Disables the Media domain. */ disable(params: Media.DisableParams): Promise<Media.DisableResult | undefined>; /** * This can be called multiple times, and can be used to set / override / * remove player properties. A null propValue indicates removal. */ on( event: 'playerPropertiesChanged', listener: (event: Media.PlayerPropertiesChangedEvent) => void, ): IDisposable; /** * Send events as a list, allowing them to be batched on the browser for less * congestion. If batched, events must ALWAYS be in chronological order. */ on( event: 'playerEventsAdded', listener: (event: Media.PlayerEventsAddedEvent) => void, ): IDisposable; /** * Send a list of any messages that need to be delivered. */ on( event: 'playerMessagesLogged', listener: (event: Media.PlayerMessagesLoggedEvent) => void, ): IDisposable; /** * Send a list of any errors that need to be delivered. */ on( event: 'playerErrorsRaised', listener: (event: Media.PlayerErrorsRaisedEvent) => void, ): IDisposable; /** * Called whenever a player is created, or when a new agent joins and receives * a list of active players. If an agent is restored, it will receive the full * list of player ids and all events again. */ on(event: 'playersCreated', listener: (event: Media.PlayersCreatedEvent) => void): IDisposable; } /** * Types of the 'Media' domain. */ export namespace Media { /** * Parameters of the 'Media.enable' method. */ export interface EnableParams {} /** * Return value of the 'Media.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Media.disable' method. */ export interface DisableParams {} /** * Return value of the 'Media.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Media.playerPropertiesChanged' event. */ export interface PlayerPropertiesChangedEvent { playerId: PlayerId; properties: PlayerProperty[]; } /** * Parameters of the 'Media.playerEventsAdded' event. */ export interface PlayerEventsAddedEvent { playerId: PlayerId; events: PlayerEvent[]; } /** * Parameters of the 'Media.playerMessagesLogged' event. */ export interface PlayerMessagesLoggedEvent { playerId: PlayerId; messages: PlayerMessage[]; } /** * Parameters of the 'Media.playerErrorsRaised' event. */ export interface PlayerErrorsRaisedEvent { playerId: PlayerId; errors: PlayerError[]; } /** * Parameters of the 'Media.playersCreated' event. */ export interface PlayersCreatedEvent { players: PlayerId[]; } /** * Players will get an ID that is unique within the agent context. */ export type PlayerId = string; export type Timestamp = number; /** * Have one type per entry in MediaLogRecord::Type * Corresponds to kMessage */ export interface PlayerMessage { /** * Keep in sync with MediaLogMessageLevel * We are currently keeping the message level 'error' separate from the * PlayerError type because right now they represent different things, * this one being a DVLOG(ERROR) style log message that gets printed * based on what log level is selected in the UI, and the other is a * representation of a media::PipelineStatus object. Soon however we're * going to be moving away from using PipelineStatus for errors and * introducing a new error type which should hopefully let us integrate * the error log level into the PlayerError type. */ level: 'error' | 'warning' | 'info' | 'debug'; message: string; } /** * Corresponds to kMediaPropertyChange */ export interface PlayerProperty { name: string; value: string; } /** * Corresponds to kMediaEventTriggered */ export interface PlayerEvent { timestamp: Timestamp; value: string; } /** * Corresponds to kMediaError */ export interface PlayerError { type: 'pipeline_error' | 'media_error'; /** * When this switches to using media::Status instead of PipelineStatus * we can remove "errorCode" and replace it with the fields from * a Status instance. This also seems like a duplicate of the error * level enum - there is a todo bug to have that level removed and * use this instead. (crbug.com/1068454) */ errorCode: string; } } /** * Methods and events of the 'Memory' domain. */ export interface MemoryApi { getDOMCounters( params: Memory.GetDOMCountersParams, ): Promise<Memory.GetDOMCountersResult | undefined>; prepareForLeakDetection( params: Memory.PrepareForLeakDetectionParams, ): Promise<Memory.PrepareForLeakDetectionResult | undefined>; /** * Simulate OomIntervention by purging V8 memory. */ forciblyPurgeJavaScriptMemory( params: Memory.ForciblyPurgeJavaScriptMemoryParams, ): Promise<Memory.ForciblyPurgeJavaScriptMemoryResult | undefined>; /** * Enable/disable suppressing memory pressure notifications in all processes. */ setPressureNotificationsSuppressed( params: Memory.SetPressureNotificationsSuppressedParams, ): Promise<Memory.SetPressureNotificationsSuppressedResult | undefined>; /** * Simulate a memory pressure notification in all processes. */ simulatePressureNotification( params: Memory.SimulatePressureNotificationParams, ): Promise<Memory.SimulatePressureNotificationResult | undefined>; /** * Start collecting native memory profile. */ startSampling( params: Memory.StartSamplingParams, ): Promise<Memory.StartSamplingResult | undefined>; /** * Stop collecting native memory profile. */ stopSampling(params: Memory.StopSamplingParams): Promise<Memory.StopSamplingResult | undefined>; /** * Retrieve native memory allocations profile * collected since renderer process startup. */ getAllTimeSamplingProfile( params: Memory.GetAllTimeSamplingProfileParams, ): Promise<Memory.GetAllTimeSamplingProfileResult | undefined>; /** * Retrieve native memory allocations profile * collected since browser process startup. */ getBrowserSamplingProfile( params: Memory.GetBrowserSamplingProfileParams, ): Promise<Memory.GetBrowserSamplingProfileResult | undefined>; /** * Retrieve native memory allocations profile collected since last * `startSampling` call. */ getSamplingProfile( params: Memory.GetSamplingProfileParams, ): Promise<Memory.GetSamplingProfileResult | undefined>; } /** * Types of the 'Memory' domain. */ export namespace Memory { /** * Parameters of the 'Memory.getDOMCounters' method. */ export interface GetDOMCountersParams {} /** * Return value of the 'Memory.getDOMCounters' method. */ export interface GetDOMCountersResult { documents: integer; nodes: integer; jsEventListeners: integer; } /** * Parameters of the 'Memory.prepareForLeakDetection' method. */ export interface PrepareForLeakDetectionParams {} /** * Return value of the 'Memory.prepareForLeakDetection' method. */ export interface PrepareForLeakDetectionResult {} /** * Parameters of the 'Memory.forciblyPurgeJavaScriptMemory' method. */ export interface ForciblyPurgeJavaScriptMemoryParams {} /** * Return value of the 'Memory.forciblyPurgeJavaScriptMemory' method. */ export interface ForciblyPurgeJavaScriptMemoryResult {} /** * Parameters of the 'Memory.setPressureNotificationsSuppressed' method. */ export interface SetPressureNotificationsSuppressedParams { /** * If true, memory pressure notifications will be suppressed. */ suppressed: boolean; } /** * Return value of the 'Memory.setPressureNotificationsSuppressed' method. */ export interface SetPressureNotificationsSuppressedResult {} /** * Parameters of the 'Memory.simulatePressureNotification' method. */ export interface SimulatePressureNotificationParams { /** * Memory pressure level of the notification. */ level: PressureLevel; } /** * Return value of the 'Memory.simulatePressureNotification' method. */ export interface SimulatePressureNotificationResult {} /** * Parameters of the 'Memory.startSampling' method. */ export interface StartSamplingParams { /** * Average number of bytes between samples. */ samplingInterval?: integer; /** * Do not randomize intervals between samples. */ suppressRandomness?: boolean; } /** * Return value of the 'Memory.startSampling' method. */ export interface StartSamplingResult {} /** * Parameters of the 'Memory.stopSampling' method. */ export interface StopSamplingParams {} /** * Return value of the 'Memory.stopSampling' method. */ export interface StopSamplingResult {} /** * Parameters of the 'Memory.getAllTimeSamplingProfile' method. */ export interface GetAllTimeSamplingProfileParams {} /** * Return value of the 'Memory.getAllTimeSamplingProfile' method. */ export interface GetAllTimeSamplingProfileResult { profile: SamplingProfile; } /** * Parameters of the 'Memory.getBrowserSamplingProfile' method. */ export interface GetBrowserSamplingProfileParams {} /** * Return value of the 'Memory.getBrowserSamplingProfile' method. */ export interface GetBrowserSamplingProfileResult { profile: SamplingProfile; } /** * Parameters of the 'Memory.getSamplingProfile' method. */ export interface GetSamplingProfileParams {} /** * Return value of the 'Memory.getSamplingProfile' method. */ export interface GetSamplingProfileResult { profile: SamplingProfile; } /** * Memory pressure level. */ export type PressureLevel = 'moderate' | 'critical'; /** * Heap profile sample. */ export interface SamplingProfileNode { /** * Size of the sampled allocation. */ size: number; /** * Total bytes attributed to this sample. */ total: number; /** * Execution stack at the point of allocation. */ stack: string[]; } /** * Array of heap profile samples. */ export interface SamplingProfile { samples: SamplingProfileNode[]; modules: Module[]; } /** * Executable module information */ export interface Module { /** * Name of the module. */ name: string; /** * UUID of the module. */ uuid: string; /** * Base address where the module is loaded into memory. Encoded as a decimal * or hexadecimal (0x prefixed) string. */ baseAddress: string; /** * Size of the module in bytes. */ size: number; } } /** * Methods and events of the 'Network' domain. */ export interface NetworkApi { /** * Sets a list of content encodings that will be accepted. Empty list means no encoding is accepted. */ setAcceptedEncodings( params: Network.SetAcceptedEncodingsParams, ): Promise<Network.SetAcceptedEncodingsResult | undefined>; /** * Clears accepted encodings set by setAcceptedEncodings */ clearAcceptedEncodingsOverride( params: Network.ClearAcceptedEncodingsOverrideParams, ): Promise<Network.ClearAcceptedEncodingsOverrideResult | undefined>; /** * Tells whether clearing browser cache is supported. * @deprecated */ canClearBrowserCache( params: Network.CanClearBrowserCacheParams, ): Promise<Network.CanClearBrowserCacheResult | undefined>; /** * Tells whether clearing browser cookies is supported. * @deprecated */ canClearBrowserCookies( params: Network.CanClearBrowserCookiesParams, ): Promise<Network.CanClearBrowserCookiesResult | undefined>; /** * Tells whether emulation of network conditions is supported. * @deprecated */ canEmulateNetworkConditions( params: Network.CanEmulateNetworkConditionsParams, ): Promise<Network.CanEmulateNetworkConditionsResult | undefined>; /** * Clears browser cache. */ clearBrowserCache( params: Network.ClearBrowserCacheParams, ): Promise<Network.ClearBrowserCacheResult | undefined>; /** * Clears browser cookies. */ clearBrowserCookies( params: Network.ClearBrowserCookiesParams, ): Promise<Network.ClearBrowserCookiesResult | undefined>; /** * Response to Network.requestIntercepted which either modifies the request to continue with any * modifications, or blocks it, or completes it with the provided response bytes. If a network * fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted * event will be sent with the same InterceptionId. * Deprecated, use Fetch.continueRequest, Fetch.fulfillRequest and Fetch.failRequest instead. * @deprecated */ continueInterceptedRequest( params: Network.ContinueInterceptedRequestParams, ): Promise<Network.ContinueInterceptedRequestResult | undefined>; /** * Deletes browser cookies with matching name and url or domain/path pair. */ deleteCookies( params: Network.DeleteCookiesParams, ): Promise<Network.DeleteCookiesResult | undefined>; /** * Disables network tracking, prevents network events from being sent to the client. */ disable(params: Network.DisableParams): Promise<Network.DisableResult | undefined>; /** * Activates emulation of network conditions. */ emulateNetworkConditions( params: Network.EmulateNetworkConditionsParams, ): Promise<Network.EmulateNetworkConditionsResult | undefined>; /** * Enables network tracking, network events will now be delivered to the client. */ enable(params: Network.EnableParams): Promise<Network.EnableResult | undefined>; /** * Returns all browser cookies. Depending on the backend support, will return detailed cookie * information in the `cookies` field. */ getAllCookies( params: Network.GetAllCookiesParams, ): Promise<Network.GetAllCookiesResult | undefined>; /** * Returns the DER-encoded certificate. */ getCertificate( params: Network.GetCertificateParams, ): Promise<Network.GetCertificateResult | undefined>; /** * Returns all browser cookies for the current URL. Depending on the backend support, will return * detailed cookie information in the `cookies` field. */ getCookies(params: Network.GetCookiesParams): Promise<Network.GetCookiesResult | undefined>; /** * Returns content served for the given request. */ getResponseBody( params: Network.GetResponseBodyParams, ): Promise<Network.GetResponseBodyResult | undefined>; /** * Returns post data sent with the request. Returns an error when no data was sent with the request. */ getRequestPostData( params: Network.GetRequestPostDataParams, ): Promise<Network.GetRequestPostDataResult | undefined>; /** * Returns content served for the given currently intercepted request. */ getResponseBodyForInterception( params: Network.GetResponseBodyForInterceptionParams, ): Promise<Network.GetResponseBodyForInterceptionResult | undefined>; /** * Returns a handle to the stream representing the response body. Note that after this command, * the intercepted request can't be continued as is -- you either need to cancel it or to provide * the response body. The stream only supports sequential read, IO.read will fail if the position * is specified. */ takeResponseBodyForInterceptionAsStream( params: Network.TakeResponseBodyForInterceptionAsStreamParams, ): Promise<Network.TakeResponseBodyForInterceptionAsStreamResult | undefined>; /** * This method sends a new XMLHttpRequest which is identical to the original one. The following * parameters should be identical: method, url, async, request body, extra headers, withCredentials * attribute, user, password. */ replayXHR(params: Network.ReplayXHRParams): Promise<Network.ReplayXHRResult | undefined>; /** * Searches for given string in response content. */ searchInResponseBody( params: Network.SearchInResponseBodyParams, ): Promise<Network.SearchInResponseBodyResult | undefined>; /** * Blocks URLs from loading. */ setBlockedURLs( params: Network.SetBlockedURLsParams, ): Promise<Network.SetBlockedURLsResult | undefined>; /** * Toggles ignoring of service worker for each request. */ setBypassServiceWorker( params: Network.SetBypassServiceWorkerParams, ): Promise<Network.SetBypassServiceWorkerResult | undefined>; /** * Toggles ignoring cache for each request. If `true`, cache will not be used. */ setCacheDisabled( params: Network.SetCacheDisabledParams, ): Promise<Network.SetCacheDisabledResult | undefined>; /** * Sets a cookie with the given cookie data; may overwrite equivalent cookies if they exist. */ setCookie(params: Network.SetCookieParams): Promise<Network.SetCookieResult | undefined>; /** * Sets given cookies. */ setCookies(params: Network.SetCookiesParams): Promise<Network.SetCookiesResult | undefined>; /** * Specifies whether to always send extra HTTP headers with the requests from this page. */ setExtraHTTPHeaders( params: Network.SetExtraHTTPHeadersParams, ): Promise<Network.SetExtraHTTPHeadersResult | undefined>; /** * Specifies whether to attach a page script stack id in requests */ setAttachDebugStack( params: Network.SetAttachDebugStackParams, ): Promise<Network.SetAttachDebugStackResult | undefined>; /** * Sets the requests to intercept that match the provided patterns and optionally resource types. * Deprecated, please use Fetch.enable instead. * @deprecated */ setRequestInterception( params: Network.SetRequestInterceptionParams, ): Promise<Network.SetRequestInterceptionResult | undefined>; /** * Allows overriding user agent with the given string. */ setUserAgentOverride( params: Network.SetUserAgentOverrideParams, ): Promise<Network.SetUserAgentOverrideResult | undefined>; /** * Returns information about the COEP/COOP isolation status. */ getSecurityIsolationStatus( params: Network.GetSecurityIsolationStatusParams, ): Promise<Network.GetSecurityIsolationStatusResult | undefined>; /** * Enables tracking for the Reporting API, events generated by the Reporting API will now be delivered to the client. * Enabling triggers 'reportingApiReportAdded' for all existing reports. */ enableReportingApi( params: Network.EnableReportingApiParams, ): Promise<Network.EnableReportingApiResult | undefined>; /** * Fetches the resource and returns the content. */ loadNetworkResource( params: Network.LoadNetworkResourceParams, ): Promise<Network.LoadNetworkResourceResult | undefined>; /** * Fired when data chunk was received over the network. */ on(event: 'dataReceived', listener: (event: Network.DataReceivedEvent) => void): IDisposable; /** * Fired when EventSource message is received. */ on( event: 'eventSourceMessageReceived', listener: (event: Network.EventSourceMessageReceivedEvent) => void, ): IDisposable; /** * Fired when HTTP request has failed to load. */ on(event: 'loadingFailed', listener: (event: Network.LoadingFailedEvent) => void): IDisposable; /** * Fired when HTTP request has finished loading. */ on( event: 'loadingFinished', listener: (event: Network.LoadingFinishedEvent) => void, ): IDisposable; /** * Details of an intercepted HTTP request, which must be either allowed, blocked, modified or * mocked. * Deprecated, use Fetch.requestPaused instead. * @deprecated */ on( event: 'requestIntercepted', listener: (event: Network.RequestInterceptedEvent) => void, ): IDisposable; /** * Fired if request ended up loading from cache. */ on( event: 'requestServedFromCache', listener: (event: Network.RequestServedFromCacheEvent) => void, ): IDisposable; /** * Fired when page is about to send HTTP request. */ on( event: 'requestWillBeSent', listener: (event: Network.RequestWillBeSentEvent) => void, ): IDisposable; /** * Fired when resource loading priority is changed */ on( event: 'resourceChangedPriority', listener: (event: Network.ResourceChangedPriorityEvent) => void, ): IDisposable; /** * Fired when a signed exchange was received over the network */ on( event: 'signedExchangeReceived', listener: (event: Network.SignedExchangeReceivedEvent) => void, ): IDisposable; /** * Fired when HTTP response is available. */ on( event: 'responseReceived', listener: (event: Network.ResponseReceivedEvent) => void, ): IDisposable; /** * Fired when WebSocket is closed. */ on( event: 'webSocketClosed', listener: (event: Network.WebSocketClosedEvent) => void, ): IDisposable; /** * Fired upon WebSocket creation. */ on( event: 'webSocketCreated', listener: (event: Network.WebSocketCreatedEvent) => void, ): IDisposable; /** * Fired when WebSocket message error occurs. */ on( event: 'webSocketFrameError', listener: (event: Network.WebSocketFrameErrorEvent) => void, ): IDisposable; /** * Fired when WebSocket message is received. */ on( event: 'webSocketFrameReceived', listener: (event: Network.WebSocketFrameReceivedEvent) => void, ): IDisposable; /** * Fired when WebSocket message is sent. */ on( event: 'webSocketFrameSent', listener: (event: Network.WebSocketFrameSentEvent) => void, ): IDisposable; /** * Fired when WebSocket handshake response becomes available. */ on( event: 'webSocketHandshakeResponseReceived', listener: (event: Network.WebSocketHandshakeResponseReceivedEvent) => void, ): IDisposable; /** * Fired when WebSocket is about to initiate handshake. */ on( event: 'webSocketWillSendHandshakeRequest', listener: (event: Network.WebSocketWillSendHandshakeRequestEvent) => void, ): IDisposable; /** * Fired upon WebTransport creation. */ on( event: 'webTransportCreated', listener: (event: Network.WebTransportCreatedEvent) => void, ): IDisposable; /** * Fired when WebTransport handshake is finished. */ on( event: 'webTransportConnectionEstablished', listener: (event: Network.WebTransportConnectionEstablishedEvent) => void, ): IDisposable; /** * Fired when WebTransport is disposed. */ on( event: 'webTransportClosed', listener: (event: Network.WebTransportClosedEvent) => void, ): IDisposable; /** * Fired when additional information about a requestWillBeSent event is available from the * network stack. Not every requestWillBeSent event will have an additional * requestWillBeSentExtraInfo fired for it, and there is no guarantee whether requestWillBeSent * or requestWillBeSentExtraInfo will be fired first for the same request. */ on( event: 'requestWillBeSentExtraInfo', listener: (event: Network.RequestWillBeSentExtraInfoEvent) => void, ): IDisposable; /** * Fired when additional information about a responseReceived event is available from the network * stack. Not every responseReceived event will have an additional responseReceivedExtraInfo for * it, and responseReceivedExtraInfo may be fired before or after responseReceived. */ on( event: 'responseReceivedExtraInfo', listener: (event: Network.ResponseReceivedExtraInfoEvent) => void, ): IDisposable; /** * Fired exactly once for each Trust Token operation. Depending on * the type of the operation and whether the operation succeeded or * failed, the event is fired before the corresponding request was sent * or after the response was received. */ on( event: 'trustTokenOperationDone', listener: (event: Network.TrustTokenOperationDoneEvent) => void, ): IDisposable; /** * Fired once when parsing the .wbn file has succeeded. * The event contains the information about the web bundle contents. */ on( event: 'subresourceWebBundleMetadataReceived', listener: (event: Network.SubresourceWebBundleMetadataReceivedEvent) => void, ): IDisposable; /** * Fired once when parsing the .wbn file has failed. */ on( event: 'subresourceWebBundleMetadataError', listener: (event: Network.SubresourceWebBundleMetadataErrorEvent) => void, ): IDisposable; /** * Fired when handling requests for resources within a .wbn file. * Note: this will only be fired for resources that are requested by the webpage. */ on( event: 'subresourceWebBundleInnerResponseParsed', listener: (event: Network.SubresourceWebBundleInnerResponseParsedEvent) => void, ): IDisposable; /** * Fired when request for resources within a .wbn file failed. */ on( event: 'subresourceWebBundleInnerResponseError', listener: (event: Network.SubresourceWebBundleInnerResponseErrorEvent) => void, ): IDisposable; /** * Is sent whenever a new report is added. * And after 'enableReportingApi' for all existing reports. */ on( event: 'reportingApiReportAdded', listener: (event: Network.ReportingApiReportAddedEvent) => void, ): IDisposable; on( event: 'reportingApiReportUpdated', listener: (event: Network.ReportingApiReportUpdatedEvent) => void, ): IDisposable; } /** * Types of the 'Network' domain. */ export namespace Network { /** * Parameters of the 'Network.setAcceptedEncodings' method. */ export interface SetAcceptedEncodingsParams { /** * List of accepted content encodings. */ encodings: ContentEncoding[]; } /** * Return value of the 'Network.setAcceptedEncodings' method. */ export interface SetAcceptedEncodingsResult {} /** * Parameters of the 'Network.clearAcceptedEncodingsOverride' method. */ export interface ClearAcceptedEncodingsOverrideParams {} /** * Return value of the 'Network.clearAcceptedEncodingsOverride' method. */ export interface ClearAcceptedEncodingsOverrideResult {} /** * Parameters of the 'Network.canClearBrowserCache' method. */ export interface CanClearBrowserCacheParams {} /** * Return value of the 'Network.canClearBrowserCache' method. */ export interface CanClearBrowserCacheResult { /** * True if browser cache can be cleared. */ result: boolean; } /** * Parameters of the 'Network.canClearBrowserCookies' method. */ export interface CanClearBrowserCookiesParams {} /** * Return value of the 'Network.canClearBrowserCookies' method. */ export interface CanClearBrowserCookiesResult { /** * True if browser cookies can be cleared. */ result: boolean; } /** * Parameters of the 'Network.canEmulateNetworkConditions' method. */ export interface CanEmulateNetworkConditionsParams {} /** * Return value of the 'Network.canEmulateNetworkConditions' method. */ export interface CanEmulateNetworkConditionsResult { /** * True if emulation of network conditions is supported. */ result: boolean; } /** * Parameters of the 'Network.clearBrowserCache' method. */ export interface ClearBrowserCacheParams {} /** * Return value of the 'Network.clearBrowserCache' method. */ export interface ClearBrowserCacheResult {} /** * Parameters of the 'Network.clearBrowserCookies' method. */ export interface ClearBrowserCookiesParams {} /** * Return value of the 'Network.clearBrowserCookies' method. */ export interface ClearBrowserCookiesResult {} /** * Parameters of the 'Network.continueInterceptedRequest' method. */ export interface ContinueInterceptedRequestParams { interceptionId: InterceptionId; /** * If set this causes the request to fail with the given reason. Passing `Aborted` for requests * marked with `isNavigationRequest` also cancels the navigation. Must not be set in response * to an authChallenge. */ errorReason?: ErrorReason; /** * If set the requests completes using with the provided base64 encoded raw response, including * HTTP status line and headers etc... Must not be set in response to an authChallenge. (Encoded as a base64 string when passed over JSON) */ rawResponse?: string; /** * If set the request url will be modified in a way that's not observable by page. Must not be * set in response to an authChallenge. */ url?: string; /** * If set this allows the request method to be overridden. Must not be set in response to an * authChallenge. */ method?: string; /** * If set this allows postData to be set. Must not be set in response to an authChallenge. */ postData?: string; /** * If set this allows the request headers to be changed. Must not be set in response to an * authChallenge. */ headers?: Headers; /** * Response to a requestIntercepted with an authChallenge. Must not be set otherwise. */ authChallengeResponse?: AuthChallengeResponse; } /** * Return value of the 'Network.continueInterceptedRequest' method. */ export interface ContinueInterceptedRequestResult {} /** * Parameters of the 'Network.deleteCookies' method. */ export interface DeleteCookiesParams { /** * Name of the cookies to remove. */ name: string; /** * If specified, deletes all the cookies with the given name where domain and path match * provided URL. */ url?: string; /** * If specified, deletes only cookies with the exact domain. */ domain?: string; /** * If specified, deletes only cookies with the exact path. */ path?: string; } /** * Return value of the 'Network.deleteCookies' method. */ export interface DeleteCookiesResult {} /** * Parameters of the 'Network.disable' method. */ export interface DisableParams {} /** * Return value of the 'Network.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Network.emulateNetworkConditions' method. */ export interface EmulateNetworkConditionsParams { /** * True to emulate internet disconnection. */ offline: boolean; /** * Minimum latency from request sent to response headers received (ms). */ latency: number; /** * Maximal aggregated download throughput (bytes/sec). -1 disables download throttling. */ downloadThroughput: number; /** * Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling. */ uploadThroughput: number; /** * Connection type if known. */ connectionType?: ConnectionType; } /** * Return value of the 'Network.emulateNetworkConditions' method. */ export interface EmulateNetworkConditionsResult {} /** * Parameters of the 'Network.enable' method. */ export interface EnableParams { /** * Buffer size in bytes to use when preserving network payloads (XHRs, etc). */ maxTotalBufferSize?: integer; /** * Per-resource buffer size in bytes to use when preserving network payloads (XHRs, etc). */ maxResourceBufferSize?: integer; /** * Longest post body size (in bytes) that would be included in requestWillBeSent notification */ maxPostDataSize?: integer; } /** * Return value of the 'Network.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Network.getAllCookies' method. */ export interface GetAllCookiesParams {} /** * Return value of the 'Network.getAllCookies' method. */ export interface GetAllCookiesResult { /** * Array of cookie objects. */ cookies: Cookie[]; } /** * Parameters of the 'Network.getCertificate' method. */ export interface GetCertificateParams { /** * Origin to get certificate for. */ origin: string; } /** * Return value of the 'Network.getCertificate' method. */ export interface GetCertificateResult { tableNames: string[]; } /** * Parameters of the 'Network.getCookies' method. */ export interface GetCookiesParams { /** * The list of URLs for which applicable cookies will be fetched. * If not specified, it's assumed to be set to the list containing * the URLs of the page and all of its subframes. */ urls?: string[]; } /** * Return value of the 'Network.getCookies' method. */ export interface GetCookiesResult { /** * Array of cookie objects. */ cookies: Cookie[]; } /** * Parameters of the 'Network.getResponseBody' method. */ export interface GetResponseBodyParams { /** * Identifier of the network request to get content for. */ requestId: RequestId; } /** * Return value of the 'Network.getResponseBody' method. */ export interface GetResponseBodyResult { /** * Response body. */ body: string; /** * True, if content was sent as base64. */ base64Encoded: boolean; } /** * Parameters of the 'Network.getRequestPostData' method. */ export interface GetRequestPostDataParams { /** * Identifier of the network request to get content for. */ requestId: RequestId; } /** * Return value of the 'Network.getRequestPostData' method. */ export interface GetRequestPostDataResult { /** * Request body string, omitting files from multipart requests */ postData: string; } /** * Parameters of the 'Network.getResponseBodyForInterception' method. */ export interface GetResponseBodyForInterceptionParams { /** * Identifier for the intercepted request to get body for. */ interceptionId: InterceptionId; } /** * Return value of the 'Network.getResponseBodyForInterception' method. */ export interface GetResponseBodyForInterceptionResult { /** * Response body. */ body: string; /** * True, if content was sent as base64. */ base64Encoded: boolean; } /** * Parameters of the 'Network.takeResponseBodyForInterceptionAsStream' method. */ export interface TakeResponseBodyForInterceptionAsStreamParams { interceptionId: InterceptionId; } /** * Return value of the 'Network.takeResponseBodyForInterceptionAsStream' method. */ export interface TakeResponseBodyForInterceptionAsStreamResult { stream: IO.StreamHandle; } /** * Parameters of the 'Network.replayXHR' method. */ export interface ReplayXHRParams { /** * Identifier of XHR to replay. */ requestId: RequestId; } /** * Return value of the 'Network.replayXHR' method. */ export interface ReplayXHRResult {} /** * Parameters of the 'Network.searchInResponseBody' method. */ export interface SearchInResponseBodyParams { /** * Identifier of the network response to search. */ requestId: RequestId; /** * String to search for. */ query: string; /** * If true, search is case sensitive. */ caseSensitive?: boolean; /** * If true, treats string parameter as regex. */ isRegex?: boolean; } /** * Return value of the 'Network.searchInResponseBody' method. */ export interface SearchInResponseBodyResult { /** * List of search matches. */ result: Debugger.SearchMatch[]; } /** * Parameters of the 'Network.setBlockedURLs' method. */ export interface SetBlockedURLsParams { /** * URL patterns to block. Wildcards ('*') are allowed. */ urls: string[]; } /** * Return value of the 'Network.setBlockedURLs' method. */ export interface SetBlockedURLsResult {} /** * Parameters of the 'Network.setBypassServiceWorker' method. */ export interface SetBypassServiceWorkerParams { /** * Bypass service worker and load from network. */ bypass: boolean; } /** * Return value of the 'Network.setBypassServiceWorker' method. */ export interface SetBypassServiceWorkerResult {} /** * Parameters of the 'Network.setCacheDisabled' method. */ export interface SetCacheDisabledParams { /** * Cache disabled state. */ cacheDisabled: boolean; } /** * Return value of the 'Network.setCacheDisabled' method. */ export interface SetCacheDisabledResult {} /** * Parameters of the 'Network.setCookie' method. */ export interface SetCookieParams { /** * Cookie name. */ name: string; /** * Cookie value. */ value: string; /** * The request-URI to associate with the setting of the cookie. This value can affect the * default domain, path, source port, and source scheme values of the created cookie. */ url?: string; /** * Cookie domain. */ domain?: string; /** * Cookie path. */ path?: string; /** * True if cookie is secure. */ secure?: boolean; /** * True if cookie is http-only. */ httpOnly?: boolean; /** * Cookie SameSite type. */ sameSite?: CookieSameSite; /** * Cookie expiration date, session cookie if not set */ expires?: TimeSinceEpoch; /** * Cookie Priority type. */ priority?: CookiePriority; /** * True if cookie is SameParty. */ sameParty?: boolean; /** * Cookie source scheme type. */ sourceScheme?: CookieSourceScheme; /** * Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. * An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. * This is a temporary ability and it will be removed in the future. */ sourcePort?: integer; } /** * Return value of the 'Network.setCookie' method. */ export interface SetCookieResult { /** * Always set to true. If an error occurs, the response indicates protocol error. * @deprecated */ success: boolean; } /** * Parameters of the 'Network.setCookies' method. */ export interface SetCookiesParams { /** * Cookies to be set. */ cookies: CookieParam[]; } /** * Return value of the 'Network.setCookies' method. */ export interface SetCookiesResult {} /** * Parameters of the 'Network.setExtraHTTPHeaders' method. */ export interface SetExtraHTTPHeadersParams { /** * Map with extra HTTP headers. */ headers: Headers; } /** * Return value of the 'Network.setExtraHTTPHeaders' method. */ export interface SetExtraHTTPHeadersResult {} /** * Parameters of the 'Network.setAttachDebugStack' method. */ export interface SetAttachDebugStackParams { /** * Whether to attach a page script stack for debugging purpose. */ enabled: boolean; } /** * Return value of the 'Network.setAttachDebugStack' method. */ export interface SetAttachDebugStackResult {} /** * Parameters of the 'Network.setRequestInterception' method. */ export interface SetRequestInterceptionParams { /** * Requests matching any of these patterns will be forwarded and wait for the corresponding * continueInterceptedRequest call. */ patterns: RequestPattern[]; } /** * Return value of the 'Network.setRequestInterception' method. */ export interface SetRequestInterceptionResult {} /** * Parameters of the 'Network.setUserAgentOverride' method. */ export interface SetUserAgentOverrideParams { /** * User agent to use. */ userAgent: string; /** * Browser langugage to emulate. */ acceptLanguage?: string; /** * The platform navigator.platform should return. */ platform?: string; /** * To be sent in Sec-CH-UA-* headers and returned in navigator.userAgentData */ userAgentMetadata?: Emulation.UserAgentMetadata; } /** * Return value of the 'Network.setUserAgentOverride' method. */ export interface SetUserAgentOverrideResult {} /** * Parameters of the 'Network.getSecurityIsolationStatus' method. */ export interface GetSecurityIsolationStatusParams { /** * If no frameId is provided, the status of the target is provided. */ frameId?: Page.FrameId; } /** * Return value of the 'Network.getSecurityIsolationStatus' method. */ export interface GetSecurityIsolationStatusResult { status: SecurityIsolationStatus; } /** * Parameters of the 'Network.enableReportingApi' method. */ export interface EnableReportingApiParams { /** * Whether to enable or disable events for the Reporting API */ enable: boolean; } /** * Return value of the 'Network.enableReportingApi' method. */ export interface EnableReportingApiResult {} /** * Parameters of the 'Network.loadNetworkResource' method. */ export interface LoadNetworkResourceParams { /** * Frame id to get the resource for. Mandatory for frame targets, and * should be omitted for worker targets. */ frameId?: Page.FrameId; /** * URL of the resource to get content for. */ url: string; /** * Options for the request. */ options: LoadNetworkResourceOptions; } /** * Return value of the 'Network.loadNetworkResource' method. */ export interface LoadNetworkResourceResult { resource: LoadNetworkResourcePageResult; } /** * Parameters of the 'Network.dataReceived' event. */ export interface DataReceivedEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * Data chunk length. */ dataLength: integer; /** * Actual bytes received (might be less than dataLength for compressed encodings). */ encodedDataLength: integer; } /** * Parameters of the 'Network.eventSourceMessageReceived' event. */ export interface EventSourceMessageReceivedEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * Message type. */ eventName: string; /** * Message identifier. */ eventId: string; /** * Message content. */ data: string; } /** * Parameters of the 'Network.loadingFailed' event. */ export interface LoadingFailedEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * Resource type. */ type: ResourceType; /** * User friendly error message. */ errorText: string; /** * True if loading was canceled. */ canceled?: boolean; /** * The reason why loading was blocked, if any. */ blockedReason?: BlockedReason; /** * The reason why loading was blocked by CORS, if any. */ corsErrorStatus?: CorsErrorStatus; } /** * Parameters of the 'Network.loadingFinished' event. */ export interface LoadingFinishedEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * Total number of bytes received for this request. */ encodedDataLength: number; /** * Set when 1) response was blocked by Cross-Origin Read Blocking and also * 2) this needs to be reported to the DevTools console. */ shouldReportCorbBlocking?: boolean; } /** * Parameters of the 'Network.requestIntercepted' event. */ export interface RequestInterceptedEvent { /** * Each request the page makes will have a unique id, however if any redirects are encountered * while processing that fetch, they will be reported with the same id as the original fetch. * Likewise if HTTP authentication is needed then the same fetch id will be used. */ interceptionId: InterceptionId; request: Request; /** * The id of the frame that initiated the request. */ frameId: Page.FrameId; /** * How the requested resource will be used. */ resourceType: ResourceType; /** * Whether this is a navigation request, which can abort the navigation completely. */ isNavigationRequest: boolean; /** * Set if the request is a navigation that will result in a download. * Only present after response is received from the server (i.e. HeadersReceived stage). */ isDownload?: boolean; /** * Redirect location, only sent if a redirect was intercepted. */ redirectUrl?: string; /** * Details of the Authorization Challenge encountered. If this is set then * continueInterceptedRequest must contain an authChallengeResponse. */ authChallenge?: AuthChallenge; /** * Response error if intercepted at response stage or if redirect occurred while intercepting * request. */ responseErrorReason?: ErrorReason; /** * Response code if intercepted at response stage or if redirect occurred while intercepting * request or auth retry occurred. */ responseStatusCode?: integer; /** * Response headers if intercepted at the response stage or if redirect occurred while * intercepting request or auth retry occurred. */ responseHeaders?: Headers; /** * If the intercepted request had a corresponding requestWillBeSent event fired for it, then * this requestId will be the same as the requestId present in the requestWillBeSent event. */ requestId?: RequestId; } /** * Parameters of the 'Network.requestServedFromCache' event. */ export interface RequestServedFromCacheEvent { /** * Request identifier. */ requestId: RequestId; } /** * Parameters of the 'Network.requestWillBeSent' event. */ export interface RequestWillBeSentEvent { /** * Request identifier. */ requestId: RequestId; /** * Loader identifier. Empty string if the request is fetched from worker. */ loaderId: LoaderId; /** * URL of the document this request is loaded for. */ documentURL: string; /** * Request data. */ request: Request; /** * Timestamp. */ timestamp: MonotonicTime; /** * Timestamp. */ wallTime: TimeSinceEpoch; /** * Request initiator. */ initiator: Initiator; /** * In the case that redirectResponse is populated, this flag indicates whether * requestWillBeSentExtraInfo and responseReceivedExtraInfo events will be or were emitted * for the request which was just redirected. */ redirectHasExtraInfo: boolean; /** * Redirect response data. */ redirectResponse?: Response; /** * Type of this resource. */ type?: ResourceType; /** * Frame identifier. */ frameId?: Page.FrameId; /** * Whether the request is initiated by a user gesture. Defaults to false. */ hasUserGesture?: boolean; } /** * Parameters of the 'Network.resourceChangedPriority' event. */ export interface ResourceChangedPriorityEvent { /** * Request identifier. */ requestId: RequestId; /** * New priority */ newPriority: ResourcePriority; /** * Timestamp. */ timestamp: MonotonicTime; } /** * Parameters of the 'Network.signedExchangeReceived' event. */ export interface SignedExchangeReceivedEvent { /** * Request identifier. */ requestId: RequestId; /** * Information about the signed exchange response. */ info: SignedExchangeInfo; } /** * Parameters of the 'Network.responseReceived' event. */ export interface ResponseReceivedEvent { /** * Request identifier. */ requestId: RequestId; /** * Loader identifier. Empty string if the request is fetched from worker. */ loaderId: LoaderId; /** * Timestamp. */ timestamp: MonotonicTime; /** * Resource type. */ type: ResourceType; /** * Response data. */ response: Response; /** * Indicates whether requestWillBeSentExtraInfo and responseReceivedExtraInfo events will be * or were emitted for this request. */ hasExtraInfo: boolean; /** * Frame identifier. */ frameId?: Page.FrameId; } /** * Parameters of the 'Network.webSocketClosed' event. */ export interface WebSocketClosedEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; } /** * Parameters of the 'Network.webSocketCreated' event. */ export interface WebSocketCreatedEvent { /** * Request identifier. */ requestId: RequestId; /** * WebSocket request URL. */ url: string; /** * Request initiator. */ initiator?: Initiator; } /** * Parameters of the 'Network.webSocketFrameError' event. */ export interface WebSocketFrameErrorEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * WebSocket error message. */ errorMessage: string; } /** * Parameters of the 'Network.webSocketFrameReceived' event. */ export interface WebSocketFrameReceivedEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * WebSocket response data. */ response: WebSocketFrame; } /** * Parameters of the 'Network.webSocketFrameSent' event. */ export interface WebSocketFrameSentEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * WebSocket response data. */ response: WebSocketFrame; } /** * Parameters of the 'Network.webSocketHandshakeResponseReceived' event. */ export interface WebSocketHandshakeResponseReceivedEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * WebSocket response data. */ response: WebSocketResponse; } /** * Parameters of the 'Network.webSocketWillSendHandshakeRequest' event. */ export interface WebSocketWillSendHandshakeRequestEvent { /** * Request identifier. */ requestId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; /** * UTC Timestamp. */ wallTime: TimeSinceEpoch; /** * WebSocket request data. */ request: WebSocketRequest; } /** * Parameters of the 'Network.webTransportCreated' event. */ export interface WebTransportCreatedEvent { /** * WebTransport identifier. */ transportId: RequestId; /** * WebTransport request URL. */ url: string; /** * Timestamp. */ timestamp: MonotonicTime; /** * Request initiator. */ initiator?: Initiator; } /** * Parameters of the 'Network.webTransportConnectionEstablished' event. */ export interface WebTransportConnectionEstablishedEvent { /** * WebTransport identifier. */ transportId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; } /** * Parameters of the 'Network.webTransportClosed' event. */ export interface WebTransportClosedEvent { /** * WebTransport identifier. */ transportId: RequestId; /** * Timestamp. */ timestamp: MonotonicTime; } /** * Parameters of the 'Network.requestWillBeSentExtraInfo' event. */ export interface RequestWillBeSentExtraInfoEvent { /** * Request identifier. Used to match this information to an existing requestWillBeSent event. */ requestId: RequestId; /** * A list of cookies potentially associated to the requested URL. This includes both cookies sent with * the request and the ones not sent; the latter are distinguished by having blockedReason field set. */ associatedCookies: BlockedCookieWithReason[]; /** * Raw request headers as they will be sent over the wire. */ headers: Headers; /** * Connection timing information for the request. */ connectTiming: ConnectTiming; /** * The client security state set for the request. */ clientSecurityState?: ClientSecurityState; } /** * Parameters of the 'Network.responseReceivedExtraInfo' event. */ export interface ResponseReceivedExtraInfoEvent { /** * Request identifier. Used to match this information to another responseReceived event. */ requestId: RequestId; /** * A list of cookies which were not stored from the response along with the corresponding * reasons for blocking. The cookies here may not be valid due to syntax errors, which * are represented by the invalid cookie line string instead of a proper cookie. */ blockedCookies: BlockedSetCookieWithReason[]; /** * Raw response headers as they were received over the wire. */ headers: Headers; /** * The IP address space of the resource. The address space can only be determined once the transport * established the connection, so we can't send it in `requestWillBeSentExtraInfo`. */ resourceIPAddressSpace: IPAddressSpace; /** * The status code of the response. This is useful in cases the request failed and no responseReceived * event is triggered, which is the case for, e.g., CORS errors. This is also the correct status code * for cached requests, where the status in responseReceived is a 200 and this will be 304. */ statusCode: integer; /** * Raw response header text as it was received over the wire. The raw text may not always be * available, such as in the case of HTTP/2 or QUIC. */ headersText?: string; } /** * Parameters of the 'Network.trustTokenOperationDone' event. */ export interface TrustTokenOperationDoneEvent { /** * Detailed success or error status of the operation. * 'AlreadyExists' also signifies a successful operation, as the result * of the operation already exists und thus, the operation was abort * preemptively (e.g. a cache hit). */ status: | 'Ok' | 'InvalidArgument' | 'FailedPrecondition' | 'ResourceExhausted' | 'AlreadyExists' | 'Unavailable' | 'BadResponse' | 'InternalError' | 'UnknownError' | 'FulfilledLocally'; type: TrustTokenOperationType; requestId: RequestId; /** * Top level origin. The context in which the operation was attempted. */ topLevelOrigin?: string; /** * Origin of the issuer in case of a "Issuance" or "Redemption" operation. */ issuerOrigin?: string; /** * The number of obtained Trust Tokens on a successful "Issuance" operation. */ issuedTokenCount?: integer; } /** * Parameters of the 'Network.subresourceWebBundleMetadataReceived' event. */ export interface SubresourceWebBundleMetadataReceivedEvent { /** * Request identifier. Used to match this information to another event. */ requestId: RequestId; /** * A list of URLs of resources in the subresource Web Bundle. */ urls: string[]; } /** * Parameters of the 'Network.subresourceWebBundleMetadataError' event. */ export interface SubresourceWebBundleMetadataErrorEvent { /** * Request identifier. Used to match this information to another event. */ requestId: RequestId; /** * Error message */ errorMessage: string; } /** * Parameters of the 'Network.subresourceWebBundleInnerResponseParsed' event. */ export interface SubresourceWebBundleInnerResponseParsedEvent { /** * Request identifier of the subresource request */ innerRequestId: RequestId; /** * URL of the subresource resource. */ innerRequestURL: string; /** * Bundle request identifier. Used to match this information to another event. * This made be absent in case when the instrumentation was enabled only * after webbundle was parsed. */ bundleRequestId?: RequestId; } /** * Parameters of the 'Network.subresourceWebBundleInnerResponseError' event. */ export interface SubresourceWebBundleInnerResponseErrorEvent { /** * Request identifier of the subresource request */ innerRequestId: RequestId; /** * URL of the subresource resource. */ innerRequestURL: string; /** * Error message */ errorMessage: string; /** * Bundle request identifier. Used to match this information to another event. * This made be absent in case when the instrumentation was enabled only * after webbundle was parsed. */ bundleRequestId?: RequestId; } /** * Parameters of the 'Network.reportingApiReportAdded' event. */ export interface ReportingApiReportAddedEvent { report: ReportingApiReport; } /** * Parameters of the 'Network.reportingApiReportUpdated' event. */ export interface ReportingApiReportUpdatedEvent { report: ReportingApiReport; } /** * Resource type as it was perceived by the rendering engine. */ export type ResourceType = | 'Document' | 'Stylesheet' | 'Image' | 'Media' | 'Font' | 'Script' | 'TextTrack' | 'XHR' | 'Fetch' | 'EventSource' | 'WebSocket' | 'Manifest' | 'SignedExchange' | 'Ping' | 'CSPViolationReport' | 'Preflight' | 'Other'; /** * Unique loader identifier. */ export type LoaderId = string; /** * Unique request identifier. */ export type RequestId = string; /** * Unique intercepted request identifier. */ export type InterceptionId = string; /** * Network level fetch failure reason. */ export type ErrorReason = | 'Failed' | 'Aborted' | 'TimedOut' | 'AccessDenied' | 'ConnectionClosed' | 'ConnectionReset' | 'ConnectionRefused' | 'ConnectionAborted' | 'ConnectionFailed' | 'NameNotResolved' | 'InternetDisconnected' | 'AddressUnreachable' | 'BlockedByClient' | 'BlockedByResponse'; /** * UTC time in seconds, counted from January 1, 1970. */ export type TimeSinceEpoch = number; /** * Monotonically increasing time in seconds since an arbitrary point in the past. */ export type MonotonicTime = number; /** * Request / response headers as keys / values of JSON object. */ export interface Headers { [key: string]: any; } /** * The underlying connection technology that the browser is supposedly using. */ export type ConnectionType = | 'none' | 'cellular2g' | 'cellular3g' | 'cellular4g' | 'bluetooth' | 'ethernet' | 'wifi' | 'wimax' | 'other'; /** * Represents the cookie's 'SameSite' status: * https://tools.ietf.org/html/draft-west-first-party-cookies */ export type CookieSameSite = 'Strict' | 'Lax' | 'None'; /** * Represents the cookie's 'Priority' status: * https://tools.ietf.org/html/draft-west-cookie-priority-00 */ export type CookiePriority = 'Low' | 'Medium' | 'High'; /** * Represents the source scheme of the origin that originally set the cookie. * A value of "Unset" allows protocol clients to emulate legacy cookie scope for the scheme. * This is a temporary ability and it will be removed in the future. */ export type CookieSourceScheme = 'Unset' | 'NonSecure' | 'Secure'; /** * Timing information for the request. */ export interface ResourceTiming { /** * Timing's requestTime is a baseline in seconds, while the other numbers are ticks in * milliseconds relatively to this requestTime. */ requestTime: number; /** * Started resolving proxy. */ proxyStart: number; /** * Finished resolving proxy. */ proxyEnd: number; /** * Started DNS address resolve. */ dnsStart: number; /** * Finished DNS address resolve. */ dnsEnd: number; /** * Started connecting to the remote host. */ connectStart: number; /** * Connected to the remote host. */ connectEnd: number; /** * Started SSL handshake. */ sslStart: number; /** * Finished SSL handshake. */ sslEnd: number; /** * Started running ServiceWorker. */ workerStart: number; /** * Finished Starting ServiceWorker. */ workerReady: number; /** * Started fetch event. */ workerFetchStart: number; /** * Settled fetch event respondWith promise. */ workerRespondWithSettled: number; /** * Started sending request. */ sendStart: number; /** * Finished sending request. */ sendEnd: number; /** * Time the server started pushing request. */ pushStart: number; /** * Time the server finished pushing request. */ pushEnd: number; /** * Finished receiving response headers. */ receiveHeadersEnd: number; } /** * Loading priority of a resource request. */ export type ResourcePriority = 'VeryLow' | 'Low' | 'Medium' | 'High' | 'VeryHigh'; /** * Post data entry for HTTP request */ export interface PostDataEntry { bytes?: string; } /** * HTTP request data. */ export interface Request { /** * Request URL (without fragment). */ url: string; /** * Fragment of the requested URL starting with hash, if present. */ urlFragment?: string; /** * HTTP request method. */ method: string; /** * HTTP request headers. */ headers: Headers; /** * HTTP POST request data. */ postData?: string; /** * True when the request has POST data. Note that postData might still be omitted when this flag is true when the data is too long. */ hasPostData?: boolean; /** * Request body elements. This will be converted from base64 to binary */ postDataEntries?: PostDataEntry[]; /** * The mixed content type of the request. */ mixedContentType?: Security.MixedContentType; /** * Priority of the resource request at the time request is sent. */ initialPriority: ResourcePriority; /** * The referrer policy of the request, as defined in https://www.w3.org/TR/referrer-policy/ */ referrerPolicy: | 'unsafe-url' | 'no-referrer-when-downgrade' | 'no-referrer' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin'; /** * Whether is loaded via link preload. */ isLinkPreload?: boolean; /** * Set for requests when the TrustToken API is used. Contains the parameters * passed by the developer (e.g. via "fetch") as understood by the backend. */ trustTokenParams?: TrustTokenParams; /** * True if this resource request is considered to be the 'same site' as the * request correspondinfg to the main frame. */ isSameSite?: boolean; } /** * Details of a signed certificate timestamp (SCT). */ export interface SignedCertificateTimestamp { /** * Validation status. */ status: string; /** * Origin. */ origin: string; /** * Log name / description. */ logDescription: string; /** * Log ID. */ logId: string; /** * Issuance date. */ timestamp: TimeSinceEpoch; /** * Hash algorithm. */ hashAlgorithm: string; /** * Signature algorithm. */ signatureAlgorithm: string; /** * Signature data. */ signatureData: string; } /** * Security details about a request. */ export interface SecurityDetails { /** * Protocol name (e.g. "TLS 1.2" or "QUIC"). */ protocol: string; /** * Key Exchange used by the connection, or the empty string if not applicable. */ keyExchange: string; /** * (EC)DH group used by the connection, if applicable. */ keyExchangeGroup?: string; /** * Cipher name. */ cipher: string; /** * TLS MAC. Note that AEAD ciphers do not have separate MACs. */ mac?: string; /** * Certificate ID value. */ certificateId: Security.CertificateId; /** * Certificate subject name. */ subjectName: string; /** * Subject Alternative Name (SAN) DNS names and IP addresses. */ sanList: string[]; /** * Name of the issuing CA. */ issuer: string; /** * Certificate valid from date. */ validFrom: TimeSinceEpoch; /** * Certificate valid to (expiration) date */ validTo: TimeSinceEpoch; /** * List of signed certificate timestamps (SCTs). */ signedCertificateTimestampList: SignedCertificateTimestamp[]; /** * Whether the request complied with Certificate Transparency policy */ certificateTransparencyCompliance: CertificateTransparencyCompliance; } /** * Whether the request complied with Certificate Transparency policy. */ export type CertificateTransparencyCompliance = 'unknown' | 'not-compliant' | 'compliant'; /** * The reason why request was blocked. */ export type BlockedReason = | 'other' | 'csp' | 'mixed-content' | 'origin' | 'inspector' | 'subresource-filter' | 'content-type' | 'coep-frame-resource-needs-coep-header' | 'coop-sandboxed-iframe-cannot-navigate-to-coop-page' | 'corp-not-same-origin' | 'corp-not-same-origin-after-defaulted-to-same-origin-by-coep' | 'corp-not-same-site'; /** * The reason why request was blocked. */ export type CorsError = | 'DisallowedByMode' | 'InvalidResponse' | 'WildcardOriginNotAllowed' | 'MissingAllowOriginHeader' | 'MultipleAllowOriginValues' | 'InvalidAllowOriginValue' | 'AllowOriginMismatch' | 'InvalidAllowCredentials' | 'CorsDisabledScheme' | 'PreflightInvalidStatus' | 'PreflightDisallowedRedirect' | 'PreflightWildcardOriginNotAllowed' | 'PreflightMissingAllowOriginHeader' | 'PreflightMultipleAllowOriginValues' | 'PreflightInvalidAllowOriginValue' | 'PreflightAllowOriginMismatch' | 'PreflightInvalidAllowCredentials' | 'PreflightMissingAllowExternal' | 'PreflightInvalidAllowExternal' | 'InvalidAllowMethodsPreflightResponse' | 'InvalidAllowHeadersPreflightResponse' | 'MethodDisallowedByPreflightResponse' | 'HeaderDisallowedByPreflightResponse' | 'RedirectContainsCredentials' | 'InsecurePrivateNetwork' | 'InvalidPrivateNetworkAccess' | 'UnexpectedPrivateNetworkAccess' | 'NoCorsRedirectModeNotFollow'; export interface CorsErrorStatus { corsError: CorsError; failedParameter: string; } /** * Source of serviceworker response. */ export type ServiceWorkerResponseSource = | 'cache-storage' | 'http-cache' | 'fallback-code' | 'network'; /** * Determines what type of Trust Token operation is executed and * depending on the type, some additional parameters. The values * are specified in third_party/blink/renderer/core/fetch/trust_token.idl. */ export interface TrustTokenParams { type: TrustTokenOperationType; /** * Only set for "token-redemption" type and determine whether * to request a fresh SRR or use a still valid cached SRR. */ refreshPolicy: 'UseCached' | 'Refresh'; /** * Origins of issuers from whom to request tokens or redemption * records. */ issuers?: string[]; } export type TrustTokenOperationType = 'Issuance' | 'Redemption' | 'Signing'; /** * HTTP response data. */ export interface Response { /** * Response URL. This URL can be different from CachedResource.url in case of redirect. */ url: string; /** * HTTP response status code. */ status: integer; /** * HTTP response status text. */ statusText: string; /** * HTTP response headers. */ headers: Headers; /** * HTTP response headers text. This has been replaced by the headers in Network.responseReceivedExtraInfo. * @deprecated */ headersText?: string; /** * Resource mimeType as determined by the browser. */ mimeType: string; /** * Refined HTTP request headers that were actually transmitted over the network. */ requestHeaders?: Headers; /** * HTTP request headers text. This has been replaced by the headers in Network.requestWillBeSentExtraInfo. * @deprecated */ requestHeadersText?: string; /** * Specifies whether physical connection was actually reused for this request. */ connectionReused: boolean; /** * Physical connection id that was actually used for this request. */ connectionId: number; /** * Remote IP address. */ remoteIPAddress?: string; /** * Remote port. */ remotePort?: integer; /** * Specifies that the request was served from the disk cache. */ fromDiskCache?: boolean; /** * Specifies that the request was served from the ServiceWorker. */ fromServiceWorker?: boolean; /** * Specifies that the request was served from the prefetch cache. */ fromPrefetchCache?: boolean; /** * Total number of bytes received for this request so far. */ encodedDataLength: number; /** * Timing information for the given request. */ timing?: ResourceTiming; /** * Response source of response from ServiceWorker. */ serviceWorkerResponseSource?: ServiceWorkerResponseSource; /** * The time at which the returned response was generated. */ responseTime?: TimeSinceEpoch; /** * Cache Storage Cache Name. */ cacheStorageCacheName?: string; /** * Protocol used to fetch this request. */ protocol?: string; /** * Security state of the request resource. */ securityState: Security.SecurityState; /** * Security details for the request. */ securityDetails?: SecurityDetails; } /** * WebSocket request data. */ export interface WebSocketRequest { /** * HTTP request headers. */ headers: Headers; } /** * WebSocket response data. */ export interface WebSocketResponse { /** * HTTP response status code. */ status: integer; /** * HTTP response status text. */ statusText: string; /** * HTTP response headers. */ headers: Headers; /** * HTTP response headers text. */ headersText?: string; /** * HTTP request headers. */ requestHeaders?: Headers; /** * HTTP request headers text. */ requestHeadersText?: string; } /** * WebSocket message data. This represents an entire WebSocket message, not just a fragmented frame as the name suggests. */ export interface WebSocketFrame { /** * WebSocket message opcode. */ opcode: number; /** * WebSocket message mask. */ mask: boolean; /** * WebSocket message payload data. * If the opcode is 1, this is a text message and payloadData is a UTF-8 string. * If the opcode isn't 1, then payloadData is a base64 encoded string representing binary data. */ payloadData: string; } /** * Information about the cached resource. */ export interface CachedResource { /** * Resource URL. This is the url of the original network request. */ url: string; /** * Type of this resource. */ type: ResourceType; /** * Cached response data. */ response?: Response; /** * Cached response body size. */ bodySize: number; } /** * Information about the request initiator. */ export interface Initiator { /** * Type of this initiator. */ type: 'parser' | 'script' | 'preload' | 'SignedExchange' | 'preflight' | 'other'; /** * Initiator JavaScript stack trace, set for Script only. */ stack?: Runtime.StackTrace; /** * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. */ url?: string; /** * Initiator line number, set for Parser type or for Script type (when script is importing * module) (0-based). */ lineNumber?: number; /** * Initiator column number, set for Parser type or for Script type (when script is importing * module) (0-based). */ columnNumber?: number; /** * Set if another request triggered this request (e.g. preflight). */ requestId?: RequestId; } /** * Cookie object */ export interface Cookie { /** * Cookie name. */ name: string; /** * Cookie value. */ value: string; /** * Cookie domain. */ domain: string; /** * Cookie path. */ path: string; /** * Cookie expiration date as the number of seconds since the UNIX epoch. */ expires: number; /** * Cookie size. */ size: integer; /** * True if cookie is http-only. */ httpOnly: boolean; /** * True if cookie is secure. */ secure: boolean; /** * True in case of session cookie. */ session: boolean; /** * Cookie SameSite type. */ sameSite?: CookieSameSite; /** * Cookie Priority */ priority: CookiePriority; /** * True if cookie is SameParty. */ sameParty: boolean; /** * Cookie source scheme type. */ sourceScheme: CookieSourceScheme; /** * Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. * An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. * This is a temporary ability and it will be removed in the future. */ sourcePort: integer; } /** * Types of reasons why a cookie may not be stored from a response. */ export type SetCookieBlockedReason = | 'SecureOnly' | 'SameSiteStrict' | 'SameSiteLax' | 'SameSiteUnspecifiedTreatedAsLax' | 'SameSiteNoneInsecure' | 'UserPreferences' | 'SyntaxError' | 'SchemeNotSupported' | 'OverwriteSecure' | 'InvalidDomain' | 'InvalidPrefix' | 'UnknownError' | 'SchemefulSameSiteStrict' | 'SchemefulSameSiteLax' | 'SchemefulSameSiteUnspecifiedTreatedAsLax' | 'SamePartyFromCrossPartyContext' | 'SamePartyConflictsWithOtherAttributes' | 'NameValuePairExceedsMaxSize'; /** * Types of reasons why a cookie may not be sent with a request. */ export type CookieBlockedReason = | 'SecureOnly' | 'NotOnPath' | 'DomainMismatch' | 'SameSiteStrict' | 'SameSiteLax' | 'SameSiteUnspecifiedTreatedAsLax' | 'SameSiteNoneInsecure' | 'UserPreferences' | 'UnknownError' | 'SchemefulSameSiteStrict' | 'SchemefulSameSiteLax' | 'SchemefulSameSiteUnspecifiedTreatedAsLax' | 'SamePartyFromCrossPartyContext' | 'NameValuePairExceedsMaxSize'; /** * A cookie which was not stored from a response with the corresponding reason. */ export interface BlockedSetCookieWithReason { /** * The reason(s) this cookie was blocked. */ blockedReasons: SetCookieBlockedReason[]; /** * The string representing this individual cookie as it would appear in the header. * This is not the entire "cookie" or "set-cookie" header which could have multiple cookies. */ cookieLine: string; /** * The cookie object which represents the cookie which was not stored. It is optional because * sometimes complete cookie information is not available, such as in the case of parsing * errors. */ cookie?: Cookie; } /** * A cookie with was not sent with a request with the corresponding reason. */ export interface BlockedCookieWithReason { /** * The reason(s) the cookie was blocked. */ blockedReasons: CookieBlockedReason[]; /** * The cookie object representing the cookie which was not sent. */ cookie: Cookie; } /** * Cookie parameter object */ export interface CookieParam { /** * Cookie name. */ name: string; /** * Cookie value. */ value: string; /** * The request-URI to associate with the setting of the cookie. This value can affect the * default domain, path, source port, and source scheme values of the created cookie. */ url?: string; /** * Cookie domain. */ domain?: string; /** * Cookie path. */ path?: string; /** * True if cookie is secure. */ secure?: boolean; /** * True if cookie is http-only. */ httpOnly?: boolean; /** * Cookie SameSite type. */ sameSite?: CookieSameSite; /** * Cookie expiration date, session cookie if not set */ expires?: TimeSinceEpoch; /** * Cookie Priority. */ priority?: CookiePriority; /** * True if cookie is SameParty. */ sameParty?: boolean; /** * Cookie source scheme type. */ sourceScheme?: CookieSourceScheme; /** * Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port. * An unspecified port value allows protocol clients to emulate legacy cookie scope for the port. * This is a temporary ability and it will be removed in the future. */ sourcePort?: integer; } /** * Authorization challenge for HTTP status code 401 or 407. */ export interface AuthChallenge { /** * Source of the authentication challenge. */ source?: 'Server' | 'Proxy'; /** * Origin of the challenger. */ origin: string; /** * The authentication scheme used, such as basic or digest */ scheme: string; /** * The realm of the challenge. May be empty. */ realm: string; } /** * Response to an AuthChallenge. */ export interface AuthChallengeResponse { /** * The decision on what to do in response to the authorization challenge. Default means * deferring to the default behavior of the net stack, which will likely either the Cancel * authentication or display a popup dialog box. */ response: 'Default' | 'CancelAuth' | 'ProvideCredentials'; /** * The username to provide, possibly empty. Should only be set if response is * ProvideCredentials. */ username?: string; /** * The password to provide, possibly empty. Should only be set if response is * ProvideCredentials. */ password?: string; } /** * Stages of the interception to begin intercepting. Request will intercept before the request is * sent. Response will intercept after the response is received. */ export type InterceptionStage = 'Request' | 'HeadersReceived'; /** * Request pattern for interception. */ export interface RequestPattern { /** * Wildcards (`'*'` -> zero or more, `'?'` -> exactly one) are allowed. Escape character is * backslash. Omitting is equivalent to `"*"`. */ urlPattern?: string; /** * If set, only requests for matching resource types will be intercepted. */ resourceType?: ResourceType; /** * Stage at which to begin intercepting requests. Default is Request. */ interceptionStage?: InterceptionStage; } /** * Information about a signed exchange signature. * https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#rfc.section.3.1 */ export interface SignedExchangeSignature { /** * Signed exchange signature label. */ label: string; /** * The hex string of signed exchange signature. */ signature: string; /** * Signed exchange signature integrity. */ integrity: string; /** * Signed exchange signature cert Url. */ certUrl?: string; /** * The hex string of signed exchange signature cert sha256. */ certSha256?: string; /** * Signed exchange signature validity Url. */ validityUrl: string; /** * Signed exchange signature date. */ date: integer; /** * Signed exchange signature expires. */ expires: integer; /** * The encoded certificates. */ certificates?: string[]; } /** * Information about a signed exchange header. * https://wicg.github.io/webpackage/draft-yasskin-httpbis-origin-signed-exchanges-impl.html#cbor-representation */ export interface SignedExchangeHeader { /** * Signed exchange request URL. */ requestUrl: string; /** * Signed exchange response code. */ responseCode: integer; /** * Signed exchange response headers. */ responseHeaders: Headers; /** * Signed exchange response signature. */ signatures: SignedExchangeSignature[]; /** * Signed exchange header integrity hash in the form of "sha256-<base64-hash-value>". */ headerIntegrity: string; } /** * Field type for a signed exchange related error. */ export type SignedExchangeErrorField = | 'signatureSig' | 'signatureIntegrity' | 'signatureCertUrl' | 'signatureCertSha256' | 'signatureValidityUrl' | 'signatureTimestamps'; /** * Information about a signed exchange response. */ export interface SignedExchangeError { /** * Error message. */ message: string; /** * The index of the signature which caused the error. */ signatureIndex?: integer; /** * The field which caused the error. */ errorField?: SignedExchangeErrorField; } /** * Information about a signed exchange response. */ export interface SignedExchangeInfo { /** * The outer response of signed HTTP exchange which was received from network. */ outerResponse: Response; /** * Information about the signed exchange header. */ header?: SignedExchangeHeader; /** * Security details for the signed exchange header. */ securityDetails?: SecurityDetails; /** * Errors occurred while handling the signed exchagne. */ errors?: SignedExchangeError[]; } /** * List of content encodings supported by the backend. */ export type ContentEncoding = 'deflate' | 'gzip' | 'br'; export type PrivateNetworkRequestPolicy = | 'Allow' | 'BlockFromInsecureToMorePrivate' | 'WarnFromInsecureToMorePrivate' | 'PreflightBlock' | 'PreflightWarn'; export type IPAddressSpace = 'Local' | 'Private' | 'Public' | 'Unknown'; export interface ConnectTiming { /** * Timing's requestTime is a baseline in seconds, while the other numbers are ticks in * milliseconds relatively to this requestTime. Matches ResourceTiming's requestTime for * the same request (but not for redirected requests). */ requestTime: number; } export interface ClientSecurityState { initiatorIsSecureContext: boolean; initiatorIPAddressSpace: IPAddressSpace; privateNetworkRequestPolicy: PrivateNetworkRequestPolicy; } export type CrossOriginOpenerPolicyValue = | 'SameOrigin' | 'SameOriginAllowPopups' | 'UnsafeNone' | 'SameOriginPlusCoep'; export interface CrossOriginOpenerPolicyStatus { value: CrossOriginOpenerPolicyValue; reportOnlyValue: CrossOriginOpenerPolicyValue; reportingEndpoint?: string; reportOnlyReportingEndpoint?: string; } export type CrossOriginEmbedderPolicyValue = 'None' | 'Credentialless' | 'RequireCorp'; export interface CrossOriginEmbedderPolicyStatus { value: CrossOriginEmbedderPolicyValue; reportOnlyValue: CrossOriginEmbedderPolicyValue; reportingEndpoint?: string; reportOnlyReportingEndpoint?: string; } export interface SecurityIsolationStatus { coop?: CrossOriginOpenerPolicyStatus; coep?: CrossOriginEmbedderPolicyStatus; } /** * The status of a Reporting API report. */ export type ReportStatus = 'Queued' | 'Pending' | 'MarkedForRemoval' | 'Success'; export type ReportId = string; /** * An object representing a report generated by the Reporting API. */ export interface ReportingApiReport { id: ReportId; /** * The URL of the document that triggered the report. */ initiatorUrl: string; /** * The name of the endpoint group that should be used to deliver the report. */ destination: string; /** * The type of the report (specifies the set of data that is contained in the report body). */ type: string; /** * When the report was generated. */ timestamp: Network.TimeSinceEpoch; /** * How many uploads deep the related request was. */ depth: integer; /** * The number of delivery attempts made so far, not including an active attempt. */ completedAttempts: integer; body: any; status: ReportStatus; } /** * An object providing the result of a network resource load. */ export interface LoadNetworkResourcePageResult { success: boolean; /** * Optional values used for error reporting. */ netError?: number; netErrorName?: string; httpStatusCode?: number; /** * If successful, one of the following two fields holds the result. */ stream?: IO.StreamHandle; /** * Response headers. */ headers?: Network.Headers; } /** * An options object that may be extended later to better support CORS, * CORB and streaming. */ export interface LoadNetworkResourceOptions { disableCache: boolean; includeCredentials: boolean; } } /** * Methods and events of the 'NodeRuntime' domain. */ export interface NodeRuntimeApi { /** * Enable the `NodeRuntime.waitingForDisconnect`. */ notifyWhenWaitingForDisconnect( params: NodeRuntime.NotifyWhenWaitingForDisconnectParams, ): Promise<NodeRuntime.NotifyWhenWaitingForDisconnectResult | undefined>; /** * This event is fired instead of `Runtime.executionContextDestroyed` when * enabled. * It is fired when the Node process finished all code execution and is * waiting for all frontends to disconnect. */ on( event: 'waitingForDisconnect', listener: (event: NodeRuntime.WaitingForDisconnectEvent) => void, ): IDisposable; } /** * Types of the 'NodeRuntime' domain. */ export namespace NodeRuntime { /** * Parameters of the 'NodeRuntime.notifyWhenWaitingForDisconnect' method. */ export interface NotifyWhenWaitingForDisconnectParams { enabled: boolean; } /** * Return value of the 'NodeRuntime.notifyWhenWaitingForDisconnect' method. */ export interface NotifyWhenWaitingForDisconnectResult {} /** * Parameters of the 'NodeRuntime.waitingForDisconnect' event. */ export interface WaitingForDisconnectEvent {} } /** * Methods and events of the 'NodeTracing' domain. */ export interface NodeTracingApi { /** * Gets supported tracing categories. */ getCategories( params: NodeTracing.GetCategoriesParams, ): Promise<NodeTracing.GetCategoriesResult | undefined>; /** * Start trace events collection. */ start(params: NodeTracing.StartParams): Promise<NodeTracing.StartResult | undefined>; /** * Stop trace events collection. Remaining collected events will be sent as a sequence of * dataCollected events followed by tracingComplete event. */ stop(params: NodeTracing.StopParams): Promise<NodeTracing.StopResult | undefined>; /** * Contains an bucket of collected trace events. */ on( event: 'dataCollected', listener: (event: NodeTracing.DataCollectedEvent) => void, ): IDisposable; /** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were * delivered via dataCollected events. */ on( event: 'tracingComplete', listener: (event: NodeTracing.TracingCompleteEvent) => void, ): IDisposable; } /** * Types of the 'NodeTracing' domain. */ export namespace NodeTracing { /** * Parameters of the 'NodeTracing.getCategories' method. */ export interface GetCategoriesParams {} /** * Return value of the 'NodeTracing.getCategories' method. */ export interface GetCategoriesResult { /** * A list of supported tracing categories. */ categories: string[]; } /** * Parameters of the 'NodeTracing.start' method. */ export interface StartParams { traceConfig: TraceConfig; } /** * Return value of the 'NodeTracing.start' method. */ export interface StartResult {} /** * Parameters of the 'NodeTracing.stop' method. */ export interface StopParams {} /** * Return value of the 'NodeTracing.stop' method. */ export interface StopResult {} /** * Parameters of the 'NodeTracing.dataCollected' event. */ export interface DataCollectedEvent { value: any[]; } /** * Parameters of the 'NodeTracing.tracingComplete' event. */ export interface TracingCompleteEvent {} export interface TraceConfig { /** * Controls how the trace buffer stores data. */ recordMode?: 'recordUntilFull' | 'recordContinuously' | 'recordAsMuchAsPossible'; /** * Included category filters. */ includedCategories: string[]; } } /** * Methods and events of the 'NodeWorker' domain. */ export interface NodeWorkerApi { /** * Sends protocol message over session with given id. */ sendMessageToWorker( params: NodeWorker.SendMessageToWorkerParams, ): Promise<NodeWorker.SendMessageToWorkerResult | undefined>; /** * Instructs the inspector to attach to running workers. Will also attach to new workers * as they start */ enable(params: NodeWorker.EnableParams): Promise<NodeWorker.EnableResult | undefined>; /** * Detaches from all running workers and disables attaching to new workers as they are started. */ disable(params: NodeWorker.DisableParams): Promise<NodeWorker.DisableResult | undefined>; /** * Detached from the worker with given sessionId. */ detach(params: NodeWorker.DetachParams): Promise<NodeWorker.DetachResult | undefined>; /** * Issued when attached to a worker. */ on( event: 'attachedToWorker', listener: (event: NodeWorker.AttachedToWorkerEvent) => void, ): IDisposable; /** * Issued when detached from the worker. */ on( event: 'detachedFromWorker', listener: (event: NodeWorker.DetachedFromWorkerEvent) => void, ): IDisposable; /** * Notifies about a new protocol message received from the session * (session ID is provided in attachedToWorker notification). */ on( event: 'receivedMessageFromWorker', listener: (event: NodeWorker.ReceivedMessageFromWorkerEvent) => void, ): IDisposable; } /** * Types of the 'NodeWorker' domain. */ export namespace NodeWorker { /** * Parameters of the 'NodeWorker.sendMessageToWorker' method. */ export interface SendMessageToWorkerParams { message: string; /** * Identifier of the session. */ sessionId: SessionID; } /** * Return value of the 'NodeWorker.sendMessageToWorker' method. */ export interface SendMessageToWorkerResult {} /** * Parameters of the 'NodeWorker.enable' method. */ export interface EnableParams { /** * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` * message to run them. */ waitForDebuggerOnStart: boolean; } /** * Return value of the 'NodeWorker.enable' method. */ export interface EnableResult {} /** * Parameters of the 'NodeWorker.disable' method. */ export interface DisableParams {} /** * Return value of the 'NodeWorker.disable' method. */ export interface DisableResult {} /** * Parameters of the 'NodeWorker.detach' method. */ export interface DetachParams { sessionId: SessionID; } /** * Return value of the 'NodeWorker.detach' method. */ export interface DetachResult {} /** * Parameters of the 'NodeWorker.attachedToWorker' event. */ export interface AttachedToWorkerEvent { /** * Identifier assigned to the session used to send/receive messages. */ sessionId: SessionID; workerInfo: WorkerInfo; waitingForDebugger: boolean; } /** * Parameters of the 'NodeWorker.detachedFromWorker' event. */ export interface DetachedFromWorkerEvent { /** * Detached session identifier. */ sessionId: SessionID; } /** * Parameters of the 'NodeWorker.receivedMessageFromWorker' event. */ export interface ReceivedMessageFromWorkerEvent { /** * Identifier of a session which sends a message. */ sessionId: SessionID; message: string; } export type WorkerID = string; /** * Unique identifier of attached debugging session. */ export type SessionID = string; export interface WorkerInfo { workerId: WorkerID; type: string; title: string; url: string; } } /** * Methods and events of the 'Overlay' domain. */ export interface OverlayApi { /** * Disables domain notifications. */ disable(params: Overlay.DisableParams): Promise<Overlay.DisableResult | undefined>; /** * Enables domain notifications. */ enable(params: Overlay.EnableParams): Promise<Overlay.EnableResult | undefined>; /** * For testing. */ getHighlightObjectForTest( params: Overlay.GetHighlightObjectForTestParams, ): Promise<Overlay.GetHighlightObjectForTestResult | undefined>; /** * For Persistent Grid testing. */ getGridHighlightObjectsForTest( params: Overlay.GetGridHighlightObjectsForTestParams, ): Promise<Overlay.GetGridHighlightObjectsForTestResult | undefined>; /** * For Source Order Viewer testing. */ getSourceOrderHighlightObjectForTest( params: Overlay.GetSourceOrderHighlightObjectForTestParams, ): Promise<Overlay.GetSourceOrderHighlightObjectForTestResult | undefined>; /** * Hides any highlight. */ hideHighlight( params: Overlay.HideHighlightParams, ): Promise<Overlay.HideHighlightResult | undefined>; /** * Highlights owner element of the frame with given id. * Deprecated: Doesn't work reliablity and cannot be fixed due to process * separatation (the owner node might be in a different process). Determine * the owner node in the client and use highlightNode. * @deprecated */ highlightFrame( params: Overlay.HighlightFrameParams, ): Promise<Overlay.HighlightFrameResult | undefined>; /** * Highlights DOM node with given id or with the given JavaScript object wrapper. Either nodeId or * objectId must be specified. */ highlightNode( params: Overlay.HighlightNodeParams, ): Promise<Overlay.HighlightNodeResult | undefined>; /** * Highlights given quad. Coordinates are absolute with respect to the main frame viewport. */ highlightQuad( params: Overlay.HighlightQuadParams, ): Promise<Overlay.HighlightQuadResult | undefined>; /** * Highlights given rectangle. Coordinates are absolute with respect to the main frame viewport. */ highlightRect( params: Overlay.HighlightRectParams, ): Promise<Overlay.HighlightRectResult | undefined>; /** * Highlights the source order of the children of the DOM node with given id or with the given * JavaScript object wrapper. Either nodeId or objectId must be specified. */ highlightSourceOrder( params: Overlay.HighlightSourceOrderParams, ): Promise<Overlay.HighlightSourceOrderResult | undefined>; /** * Enters the 'inspect' mode. In this mode, elements that user is hovering over are highlighted. * Backend then generates 'inspectNodeRequested' event upon element selection. */ setInspectMode( params: Overlay.SetInspectModeParams, ): Promise<Overlay.SetInspectModeResult | undefined>; /** * Highlights owner element of all frames detected to be ads. */ setShowAdHighlights( params: Overlay.SetShowAdHighlightsParams, ): Promise<Overlay.SetShowAdHighlightsResult | undefined>; setPausedInDebuggerMessage( params: Overlay.SetPausedInDebuggerMessageParams, ): Promise<Overlay.SetPausedInDebuggerMessageResult | undefined>; /** * Requests that backend shows debug borders on layers */ setShowDebugBorders( params: Overlay.SetShowDebugBordersParams, ): Promise<Overlay.SetShowDebugBordersResult | undefined>; /** * Requests that backend shows the FPS counter */ setShowFPSCounter( params: Overlay.SetShowFPSCounterParams, ): Promise<Overlay.SetShowFPSCounterResult | undefined>; /** * Highlight multiple elements with the CSS Grid overlay. */ setShowGridOverlays( params: Overlay.SetShowGridOverlaysParams, ): Promise<Overlay.SetShowGridOverlaysResult | undefined>; setShowFlexOverlays( params: Overlay.SetShowFlexOverlaysParams, ): Promise<Overlay.SetShowFlexOverlaysResult | undefined>; setShowScrollSnapOverlays( params: Overlay.SetShowScrollSnapOverlaysParams, ): Promise<Overlay.SetShowScrollSnapOverlaysResult | undefined>; setShowContainerQueryOverlays( params: Overlay.SetShowContainerQueryOverlaysParams, ): Promise<Overlay.SetShowContainerQueryOverlaysResult | undefined>; /** * Requests that backend shows paint rectangles */ setShowPaintRects( params: Overlay.SetShowPaintRectsParams, ): Promise<Overlay.SetShowPaintRectsResult | undefined>; /** * Requests that backend shows layout shift regions */ setShowLayoutShiftRegions( params: Overlay.SetShowLayoutShiftRegionsParams, ): Promise<Overlay.SetShowLayoutShiftRegionsResult | undefined>; /** * Requests that backend shows scroll bottleneck rects */ setShowScrollBottleneckRects( params: Overlay.SetShowScrollBottleneckRectsParams, ): Promise<Overlay.SetShowScrollBottleneckRectsResult | undefined>; /** * Requests that backend shows hit-test borders on layers */ setShowHitTestBorders( params: Overlay.SetShowHitTestBordersParams, ): Promise<Overlay.SetShowHitTestBordersResult | undefined>; /** * Request that backend shows an overlay with web vital metrics. */ setShowWebVitals( params: Overlay.SetShowWebVitalsParams, ): Promise<Overlay.SetShowWebVitalsResult | undefined>; /** * Paints viewport size upon main frame resize. */ setShowViewportSizeOnResize( params: Overlay.SetShowViewportSizeOnResizeParams, ): Promise<Overlay.SetShowViewportSizeOnResizeResult | undefined>; /** * Add a dual screen device hinge */ setShowHinge( params: Overlay.SetShowHingeParams, ): Promise<Overlay.SetShowHingeResult | undefined>; /** * Show elements in isolation mode with overlays. */ setShowIsolatedElements( params: Overlay.SetShowIsolatedElementsParams, ): Promise<Overlay.SetShowIsolatedElementsResult | undefined>; /** * Fired when the node should be inspected. This happens after call to `setInspectMode` or when * user manually inspects an element. */ on( event: 'inspectNodeRequested', listener: (event: Overlay.InspectNodeRequestedEvent) => void, ): IDisposable; /** * Fired when the node should be highlighted. This happens after call to `setInspectMode`. */ on( event: 'nodeHighlightRequested', listener: (event: Overlay.NodeHighlightRequestedEvent) => void, ): IDisposable; /** * Fired when user asks to capture screenshot of some area on the page. */ on( event: 'screenshotRequested', listener: (event: Overlay.ScreenshotRequestedEvent) => void, ): IDisposable; /** * Fired when user cancels the inspect mode. */ on( event: 'inspectModeCanceled', listener: (event: Overlay.InspectModeCanceledEvent) => void, ): IDisposable; } /** * Types of the 'Overlay' domain. */ export namespace Overlay { /** * Parameters of the 'Overlay.disable' method. */ export interface DisableParams {} /** * Return value of the 'Overlay.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Overlay.enable' method. */ export interface EnableParams {} /** * Return value of the 'Overlay.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Overlay.getHighlightObjectForTest' method. */ export interface GetHighlightObjectForTestParams { /** * Id of the node to get highlight object for. */ nodeId: DOM.NodeId; /** * Whether to include distance info. */ includeDistance?: boolean; /** * Whether to include style info. */ includeStyle?: boolean; /** * The color format to get config with (default: hex). */ colorFormat?: ColorFormat; /** * Whether to show accessibility info (default: true). */ showAccessibilityInfo?: boolean; } /** * Return value of the 'Overlay.getHighlightObjectForTest' method. */ export interface GetHighlightObjectForTestResult { /** * Highlight data for the node. */ highlight: any; } /** * Parameters of the 'Overlay.getGridHighlightObjectsForTest' method. */ export interface GetGridHighlightObjectsForTestParams { /** * Ids of the node to get highlight object for. */ nodeIds: DOM.NodeId[]; } /** * Return value of the 'Overlay.getGridHighlightObjectsForTest' method. */ export interface GetGridHighlightObjectsForTestResult { /** * Grid Highlight data for the node ids provided. */ highlights: any; } /** * Parameters of the 'Overlay.getSourceOrderHighlightObjectForTest' method. */ export interface GetSourceOrderHighlightObjectForTestParams { /** * Id of the node to highlight. */ nodeId: DOM.NodeId; } /** * Return value of the 'Overlay.getSourceOrderHighlightObjectForTest' method. */ export interface GetSourceOrderHighlightObjectForTestResult { /** * Source order highlight data for the node id provided. */ highlight: any; } /** * Parameters of the 'Overlay.hideHighlight' method. */ export interface HideHighlightParams {} /** * Return value of the 'Overlay.hideHighlight' method. */ export interface HideHighlightResult {} /** * Parameters of the 'Overlay.highlightFrame' method. */ export interface HighlightFrameParams { /** * Identifier of the frame to highlight. */ frameId: Page.FrameId; /** * The content box highlight fill color (default: transparent). */ contentColor?: DOM.RGBA; /** * The content box highlight outline color (default: transparent). */ contentOutlineColor?: DOM.RGBA; } /** * Return value of the 'Overlay.highlightFrame' method. */ export interface HighlightFrameResult {} /** * Parameters of the 'Overlay.highlightNode' method. */ export interface HighlightNodeParams { /** * A descriptor for the highlight appearance. */ highlightConfig: HighlightConfig; /** * Identifier of the node to highlight. */ nodeId?: DOM.NodeId; /** * Identifier of the backend node to highlight. */ backendNodeId?: DOM.BackendNodeId; /** * JavaScript object id of the node to be highlighted. */ objectId?: Runtime.RemoteObjectId; /** * Selectors to highlight relevant nodes. */ selector?: string; } /** * Return value of the 'Overlay.highlightNode' method. */ export interface HighlightNodeResult {} /** * Parameters of the 'Overlay.highlightQuad' method. */ export interface HighlightQuadParams { /** * Quad to highlight */ quad: DOM.Quad; /** * The highlight fill color (default: transparent). */ color?: DOM.RGBA; /** * The highlight outline color (default: transparent). */ outlineColor?: DOM.RGBA; } /** * Return value of the 'Overlay.highlightQuad' method. */ export interface HighlightQuadResult {} /** * Parameters of the 'Overlay.highlightRect' method. */ export interface HighlightRectParams { /** * X coordinate */ x: integer; /** * Y coordinate */ y: integer; /** * Rectangle width */ width: integer; /** * Rectangle height */ height: integer; /** * The highlight fill color (default: transparent). */ color?: DOM.RGBA; /** * The highlight outline color (default: transparent). */ outlineColor?: DOM.RGBA; } /** * Return value of the 'Overlay.highlightRect' method. */ export interface HighlightRectResult {} /** * Parameters of the 'Overlay.highlightSourceOrder' method. */ export interface HighlightSourceOrderParams { /** * A descriptor for the appearance of the overlay drawing. */ sourceOrderConfig: SourceOrderConfig; /** * Identifier of the node to highlight. */ nodeId?: DOM.NodeId; /** * Identifier of the backend node to highlight. */ backendNodeId?: DOM.BackendNodeId; /** * JavaScript object id of the node to be highlighted. */ objectId?: Runtime.RemoteObjectId; } /** * Return value of the 'Overlay.highlightSourceOrder' method. */ export interface HighlightSourceOrderResult {} /** * Parameters of the 'Overlay.setInspectMode' method. */ export interface SetInspectModeParams { /** * Set an inspection mode. */ mode: InspectMode; /** * A descriptor for the highlight appearance of hovered-over nodes. May be omitted if `enabled * == false`. */ highlightConfig?: HighlightConfig; } /** * Return value of the 'Overlay.setInspectMode' method. */ export interface SetInspectModeResult {} /** * Parameters of the 'Overlay.setShowAdHighlights' method. */ export interface SetShowAdHighlightsParams { /** * True for showing ad highlights */ show: boolean; } /** * Return value of the 'Overlay.setShowAdHighlights' method. */ export interface SetShowAdHighlightsResult {} /** * Parameters of the 'Overlay.setPausedInDebuggerMessage' method. */ export interface SetPausedInDebuggerMessageParams { /** * The message to display, also triggers resume and step over controls. */ message?: string; } /** * Return value of the 'Overlay.setPausedInDebuggerMessage' method. */ export interface SetPausedInDebuggerMessageResult {} /** * Parameters of the 'Overlay.setShowDebugBorders' method. */ export interface SetShowDebugBordersParams { /** * True for showing debug borders */ show: boolean; } /** * Return value of the 'Overlay.setShowDebugBorders' method. */ export interface SetShowDebugBordersResult {} /** * Parameters of the 'Overlay.setShowFPSCounter' method. */ export interface SetShowFPSCounterParams { /** * True for showing the FPS counter */ show: boolean; } /** * Return value of the 'Overlay.setShowFPSCounter' method. */ export interface SetShowFPSCounterResult {} /** * Parameters of the 'Overlay.setShowGridOverlays' method. */ export interface SetShowGridOverlaysParams { /** * An array of node identifiers and descriptors for the highlight appearance. */ gridNodeHighlightConfigs: GridNodeHighlightConfig[]; } /** * Return value of the 'Overlay.setShowGridOverlays' method. */ export interface SetShowGridOverlaysResult {} /** * Parameters of the 'Overlay.setShowFlexOverlays' method. */ export interface SetShowFlexOverlaysParams { /** * An array of node identifiers and descriptors for the highlight appearance. */ flexNodeHighlightConfigs: FlexNodeHighlightConfig[]; } /** * Return value of the 'Overlay.setShowFlexOverlays' method. */ export interface SetShowFlexOverlaysResult {} /** * Parameters of the 'Overlay.setShowScrollSnapOverlays' method. */ export interface SetShowScrollSnapOverlaysParams { /** * An array of node identifiers and descriptors for the highlight appearance. */ scrollSnapHighlightConfigs: ScrollSnapHighlightConfig[]; } /** * Return value of the 'Overlay.setShowScrollSnapOverlays' method. */ export interface SetShowScrollSnapOverlaysResult {} /** * Parameters of the 'Overlay.setShowContainerQueryOverlays' method. */ export interface SetShowContainerQueryOverlaysParams { /** * An array of node identifiers and descriptors for the highlight appearance. */ containerQueryHighlightConfigs: ContainerQueryHighlightConfig[]; } /** * Return value of the 'Overlay.setShowContainerQueryOverlays' method. */ export interface SetShowContainerQueryOverlaysResult {} /** * Parameters of the 'Overlay.setShowPaintRects' method. */ export interface SetShowPaintRectsParams { /** * True for showing paint rectangles */ result: boolean; } /** * Return value of the 'Overlay.setShowPaintRects' method. */ export interface SetShowPaintRectsResult {} /** * Parameters of the 'Overlay.setShowLayoutShiftRegions' method. */ export interface SetShowLayoutShiftRegionsParams { /** * True for showing layout shift regions */ result: boolean; } /** * Return value of the 'Overlay.setShowLayoutShiftRegions' method. */ export interface SetShowLayoutShiftRegionsResult {} /** * Parameters of the 'Overlay.setShowScrollBottleneckRects' method. */ export interface SetShowScrollBottleneckRectsParams { /** * True for showing scroll bottleneck rects */ show: boolean; } /** * Return value of the 'Overlay.setShowScrollBottleneckRects' method. */ export interface SetShowScrollBottleneckRectsResult {} /** * Parameters of the 'Overlay.setShowHitTestBorders' method. */ export interface SetShowHitTestBordersParams { /** * True for showing hit-test borders */ show: boolean; } /** * Return value of the 'Overlay.setShowHitTestBorders' method. */ export interface SetShowHitTestBordersResult {} /** * Parameters of the 'Overlay.setShowWebVitals' method. */ export interface SetShowWebVitalsParams { show: boolean; } /** * Return value of the 'Overlay.setShowWebVitals' method. */ export interface SetShowWebVitalsResult {} /** * Parameters of the 'Overlay.setShowViewportSizeOnResize' method. */ export interface SetShowViewportSizeOnResizeParams { /** * Whether to paint size or not. */ show: boolean; } /** * Return value of the 'Overlay.setShowViewportSizeOnResize' method. */ export interface SetShowViewportSizeOnResizeResult {} /** * Parameters of the 'Overlay.setShowHinge' method. */ export interface SetShowHingeParams { /** * hinge data, null means hideHinge */ hingeConfig?: HingeConfig; } /** * Return value of the 'Overlay.setShowHinge' method. */ export interface SetShowHingeResult {} /** * Parameters of the 'Overlay.setShowIsolatedElements' method. */ export interface SetShowIsolatedElementsParams { /** * An array of node identifiers and descriptors for the highlight appearance. */ isolatedElementHighlightConfigs: IsolatedElementHighlightConfig[]; } /** * Return value of the 'Overlay.setShowIsolatedElements' method. */ export interface SetShowIsolatedElementsResult {} /** * Parameters of the 'Overlay.inspectNodeRequested' event. */ export interface InspectNodeRequestedEvent { /** * Id of the node to inspect. */ backendNodeId: DOM.BackendNodeId; } /** * Parameters of the 'Overlay.nodeHighlightRequested' event. */ export interface NodeHighlightRequestedEvent { nodeId: DOM.NodeId; } /** * Parameters of the 'Overlay.screenshotRequested' event. */ export interface ScreenshotRequestedEvent { /** * Viewport to capture, in device independent pixels (dip). */ viewport: Page.Viewport; } /** * Parameters of the 'Overlay.inspectModeCanceled' event. */ export interface InspectModeCanceledEvent {} /** * Configuration data for drawing the source order of an elements children. */ export interface SourceOrderConfig { /** * the color to outline the givent element in. */ parentOutlineColor: DOM.RGBA; /** * the color to outline the child elements in. */ childOutlineColor: DOM.RGBA; } /** * Configuration data for the highlighting of Grid elements. */ export interface GridHighlightConfig { /** * Whether the extension lines from grid cells to the rulers should be shown (default: false). */ showGridExtensionLines?: boolean; /** * Show Positive line number labels (default: false). */ showPositiveLineNumbers?: boolean; /** * Show Negative line number labels (default: false). */ showNegativeLineNumbers?: boolean; /** * Show area name labels (default: false). */ showAreaNames?: boolean; /** * Show line name labels (default: false). */ showLineNames?: boolean; /** * Show track size labels (default: false). */ showTrackSizes?: boolean; /** * The grid container border highlight color (default: transparent). */ gridBorderColor?: DOM.RGBA; /** * The cell border color (default: transparent). Deprecated, please use rowLineColor and columnLineColor instead. * @deprecated */ cellBorderColor?: DOM.RGBA; /** * The row line color (default: transparent). */ rowLineColor?: DOM.RGBA; /** * The column line color (default: transparent). */ columnLineColor?: DOM.RGBA; /** * Whether the grid border is dashed (default: false). */ gridBorderDash?: boolean; /** * Whether the cell border is dashed (default: false). Deprecated, please us rowLineDash and columnLineDash instead. * @deprecated */ cellBorderDash?: boolean; /** * Whether row lines are dashed (default: false). */ rowLineDash?: boolean; /** * Whether column lines are dashed (default: false). */ columnLineDash?: boolean; /** * The row gap highlight fill color (default: transparent). */ rowGapColor?: DOM.RGBA; /** * The row gap hatching fill color (default: transparent). */ rowHatchColor?: DOM.RGBA; /** * The column gap highlight fill color (default: transparent). */ columnGapColor?: DOM.RGBA; /** * The column gap hatching fill color (default: transparent). */ columnHatchColor?: DOM.RGBA; /** * The named grid areas border color (Default: transparent). */ areaBorderColor?: DOM.RGBA; /** * The grid container background color (Default: transparent). */ gridBackgroundColor?: DOM.RGBA; } /** * Configuration data for the highlighting of Flex container elements. */ export interface FlexContainerHighlightConfig { /** * The style of the container border */ containerBorder?: LineStyle; /** * The style of the separator between lines */ lineSeparator?: LineStyle; /** * The style of the separator between items */ itemSeparator?: LineStyle; /** * Style of content-distribution space on the main axis (justify-content). */ mainDistributedSpace?: BoxStyle; /** * Style of content-distribution space on the cross axis (align-content). */ crossDistributedSpace?: BoxStyle; /** * Style of empty space caused by row gaps (gap/row-gap). */ rowGapSpace?: BoxStyle; /** * Style of empty space caused by columns gaps (gap/column-gap). */ columnGapSpace?: BoxStyle; /** * Style of the self-alignment line (align-items). */ crossAlignment?: LineStyle; } /** * Configuration data for the highlighting of Flex item elements. */ export interface FlexItemHighlightConfig { /** * Style of the box representing the item's base size */ baseSizeBox?: BoxStyle; /** * Style of the border around the box representing the item's base size */ baseSizeBorder?: LineStyle; /** * Style of the arrow representing if the item grew or shrank */ flexibilityArrow?: LineStyle; } /** * Style information for drawing a line. */ export interface LineStyle { /** * The color of the line (default: transparent) */ color?: DOM.RGBA; /** * The line pattern (default: solid) */ pattern?: 'dashed' | 'dotted'; } /** * Style information for drawing a box. */ export interface BoxStyle { /** * The background color for the box (default: transparent) */ fillColor?: DOM.RGBA; /** * The hatching color for the box (default: transparent) */ hatchColor?: DOM.RGBA; } export type ContrastAlgorithm = 'aa' | 'aaa' | 'apca'; /** * Configuration data for the highlighting of page elements. */ export interface HighlightConfig { /** * Whether the node info tooltip should be shown (default: false). */ showInfo?: boolean; /** * Whether the node styles in the tooltip (default: false). */ showStyles?: boolean; /** * Whether the rulers should be shown (default: false). */ showRulers?: boolean; /** * Whether the a11y info should be shown (default: true). */ showAccessibilityInfo?: boolean; /** * Whether the extension lines from node to the rulers should be shown (default: false). */ showExtensionLines?: boolean; /** * The content box highlight fill color (default: transparent). */ contentColor?: DOM.RGBA; /** * The padding highlight fill color (default: transparent). */ paddingColor?: DOM.RGBA; /** * The border highlight fill color (default: transparent). */ borderColor?: DOM.RGBA; /** * The margin highlight fill color (default: transparent). */ marginColor?: DOM.RGBA; /** * The event target element highlight fill color (default: transparent). */ eventTargetColor?: DOM.RGBA; /** * The shape outside fill color (default: transparent). */ shapeColor?: DOM.RGBA; /** * The shape margin fill color (default: transparent). */ shapeMarginColor?: DOM.RGBA; /** * The grid layout color (default: transparent). */ cssGridColor?: DOM.RGBA; /** * The color format used to format color styles (default: hex). */ colorFormat?: ColorFormat; /** * The grid layout highlight configuration (default: all transparent). */ gridHighlightConfig?: GridHighlightConfig; /** * The flex container highlight configuration (default: all transparent). */ flexContainerHighlightConfig?: FlexContainerHighlightConfig; /** * The flex item highlight configuration (default: all transparent). */ flexItemHighlightConfig?: FlexItemHighlightConfig; /** * The contrast algorithm to use for the contrast ratio (default: aa). */ contrastAlgorithm?: ContrastAlgorithm; /** * The container query container highlight configuration (default: all transparent). */ containerQueryContainerHighlightConfig?: ContainerQueryContainerHighlightConfig; } export type ColorFormat = 'rgb' | 'hsl' | 'hex'; /** * Configurations for Persistent Grid Highlight */ export interface GridNodeHighlightConfig { /** * A descriptor for the highlight appearance. */ gridHighlightConfig: GridHighlightConfig; /** * Identifier of the node to highlight. */ nodeId: DOM.NodeId; } export interface FlexNodeHighlightConfig { /** * A descriptor for the highlight appearance of flex containers. */ flexContainerHighlightConfig: FlexContainerHighlightConfig; /** * Identifier of the node to highlight. */ nodeId: DOM.NodeId; } export interface ScrollSnapContainerHighlightConfig { /** * The style of the snapport border (default: transparent) */ snapportBorder?: LineStyle; /** * The style of the snap area border (default: transparent) */ snapAreaBorder?: LineStyle; /** * The margin highlight fill color (default: transparent). */ scrollMarginColor?: DOM.RGBA; /** * The padding highlight fill color (default: transparent). */ scrollPaddingColor?: DOM.RGBA; } export interface ScrollSnapHighlightConfig { /** * A descriptor for the highlight appearance of scroll snap containers. */ scrollSnapContainerHighlightConfig: ScrollSnapContainerHighlightConfig; /** * Identifier of the node to highlight. */ nodeId: DOM.NodeId; } /** * Configuration for dual screen hinge */ export interface HingeConfig { /** * A rectangle represent hinge */ rect: DOM.Rect; /** * The content box highlight fill color (default: a dark color). */ contentColor?: DOM.RGBA; /** * The content box highlight outline color (default: transparent). */ outlineColor?: DOM.RGBA; } export interface ContainerQueryHighlightConfig { /** * A descriptor for the highlight appearance of container query containers. */ containerQueryContainerHighlightConfig: ContainerQueryContainerHighlightConfig; /** * Identifier of the container node to highlight. */ nodeId: DOM.NodeId; } export interface ContainerQueryContainerHighlightConfig { /** * The style of the container border. */ containerBorder?: LineStyle; /** * The style of the descendants' borders. */ descendantBorder?: LineStyle; } export interface IsolatedElementHighlightConfig { /** * A descriptor for the highlight appearance of an element in isolation mode. */ isolationModeHighlightConfig: IsolationModeHighlightConfig; /** * Identifier of the isolated element to highlight. */ nodeId: DOM.NodeId; } export interface IsolationModeHighlightConfig { /** * The fill color of the resizers (default: transparent). */ resizerColor?: DOM.RGBA; /** * The fill color for resizer handles (default: transparent). */ resizerHandleColor?: DOM.RGBA; /** * The fill color for the mask covering non-isolated elements (default: transparent). */ maskColor?: DOM.RGBA; } export type InspectMode = | 'searchForNode' | 'searchForUAShadowDOM' | 'captureAreaScreenshot' | 'showDistances' | 'none'; } /** * Methods and events of the 'Page' domain. */ export interface PageApi { /** * Deprecated, please use addScriptToEvaluateOnNewDocument instead. * @deprecated */ addScriptToEvaluateOnLoad( params: Page.AddScriptToEvaluateOnLoadParams, ): Promise<Page.AddScriptToEvaluateOnLoadResult | undefined>; /** * Evaluates given script in every frame upon creation (before loading frame's scripts). */ addScriptToEvaluateOnNewDocument( params: Page.AddScriptToEvaluateOnNewDocumentParams, ): Promise<Page.AddScriptToEvaluateOnNewDocumentResult | undefined>; /** * Brings page to front (activates tab). */ bringToFront(params: Page.BringToFrontParams): Promise<Page.BringToFrontResult | undefined>; /** * Capture page screenshot. */ captureScreenshot( params: Page.CaptureScreenshotParams, ): Promise<Page.CaptureScreenshotResult | undefined>; /** * Returns a snapshot of the page as a string. For MHTML format, the serialization includes * iframes, shadow DOM, external resources, and element-inline styles. */ captureSnapshot( params: Page.CaptureSnapshotParams, ): Promise<Page.CaptureSnapshotResult | undefined>; /** * Clears the overridden device metrics. * @deprecated */ clearDeviceMetricsOverride( params: Page.ClearDeviceMetricsOverrideParams, ): Promise<Page.ClearDeviceMetricsOverrideResult | undefined>; /** * Clears the overridden Device Orientation. * @deprecated */ clearDeviceOrientationOverride( params: Page.ClearDeviceOrientationOverrideParams, ): Promise<Page.ClearDeviceOrientationOverrideResult | undefined>; /** * Clears the overridden Geolocation Position and Error. * @deprecated */ clearGeolocationOverride( params: Page.ClearGeolocationOverrideParams, ): Promise<Page.ClearGeolocationOverrideResult | undefined>; /** * Creates an isolated world for the given frame. */ createIsolatedWorld( params: Page.CreateIsolatedWorldParams, ): Promise<Page.CreateIsolatedWorldResult | undefined>; /** * Deletes browser cookie with given name, domain and path. * @deprecated */ deleteCookie(params: Page.DeleteCookieParams): Promise<Page.DeleteCookieResult | undefined>; /** * Disables page domain notifications. */ disable(params: Page.DisableParams): Promise<Page.DisableResult | undefined>; /** * Enables page domain notifications. */ enable(params: Page.EnableParams): Promise<Page.EnableResult | undefined>; getAppManifest( params: Page.GetAppManifestParams, ): Promise<Page.GetAppManifestResult | undefined>; getInstallabilityErrors( params: Page.GetInstallabilityErrorsParams, ): Promise<Page.GetInstallabilityErrorsResult | undefined>; getManifestIcons( params: Page.GetManifestIconsParams, ): Promise<Page.GetManifestIconsResult | undefined>; /** * Returns the unique (PWA) app id. * Only returns values if the feature flag 'WebAppEnableManifestId' is enabled */ getAppId(params: Page.GetAppIdParams): Promise<Page.GetAppIdResult | undefined>; /** * Returns all browser cookies. Depending on the backend support, will return detailed cookie * information in the `cookies` field. * @deprecated */ getCookies(params: Page.GetCookiesParams): Promise<Page.GetCookiesResult | undefined>; /** * Returns present frame tree structure. */ getFrameTree(params: Page.GetFrameTreeParams): Promise<Page.GetFrameTreeResult | undefined>; /** * Returns metrics relating to the layouting of the page, such as viewport bounds/scale. */ getLayoutMetrics( params: Page.GetLayoutMetricsParams, ): Promise<Page.GetLayoutMetricsResult | undefined>; /** * Returns navigation history for the current page. */ getNavigationHistory( params: Page.GetNavigationHistoryParams, ): Promise<Page.GetNavigationHistoryResult | undefined>; /** * Resets navigation history for the current page. */ resetNavigationHistory( params: Page.ResetNavigationHistoryParams, ): Promise<Page.ResetNavigationHistoryResult | undefined>; /** * Returns content of the given resource. */ getResourceContent( params: Page.GetResourceContentParams, ): Promise<Page.GetResourceContentResult | undefined>; /** * Returns present frame / resource tree structure. */ getResourceTree( params: Page.GetResourceTreeParams, ): Promise<Page.GetResourceTreeResult | undefined>; /** * Accepts or dismisses a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload). */ handleJavaScriptDialog( params: Page.HandleJavaScriptDialogParams, ): Promise<Page.HandleJavaScriptDialogResult | undefined>; /** * Navigates current page to the given URL. */ navigate(params: Page.NavigateParams): Promise<Page.NavigateResult | undefined>; /** * Navigates current page to the given history entry. */ navigateToHistoryEntry( params: Page.NavigateToHistoryEntryParams, ): Promise<Page.NavigateToHistoryEntryResult | undefined>; /** * Print page as PDF. */ printToPDF(params: Page.PrintToPDFParams): Promise<Page.PrintToPDFResult | undefined>; /** * Reloads given page optionally ignoring the cache. */ reload(params: Page.ReloadParams): Promise<Page.ReloadResult | undefined>; /** * Deprecated, please use removeScriptToEvaluateOnNewDocument instead. * @deprecated */ removeScriptToEvaluateOnLoad( params: Page.RemoveScriptToEvaluateOnLoadParams, ): Promise<Page.RemoveScriptToEvaluateOnLoadResult | undefined>; /** * Removes given script from the list. */ removeScriptToEvaluateOnNewDocument( params: Page.RemoveScriptToEvaluateOnNewDocumentParams, ): Promise<Page.RemoveScriptToEvaluateOnNewDocumentResult | undefined>; /** * Acknowledges that a screencast frame has been received by the frontend. */ screencastFrameAck( params: Page.ScreencastFrameAckParams, ): Promise<Page.ScreencastFrameAckResult | undefined>; /** * Searches for given string in resource content. */ searchInResource( params: Page.SearchInResourceParams, ): Promise<Page.SearchInResourceResult | undefined>; /** * Enable Chrome's experimental ad filter on all sites. */ setAdBlockingEnabled( params: Page.SetAdBlockingEnabledParams, ): Promise<Page.SetAdBlockingEnabledResult | undefined>; /** * Enable page Content Security Policy by-passing. */ setBypassCSP(params: Page.SetBypassCSPParams): Promise<Page.SetBypassCSPResult | undefined>; /** * Get Permissions Policy state on given frame. */ getPermissionsPolicyState( params: Page.GetPermissionsPolicyStateParams, ): Promise<Page.GetPermissionsPolicyStateResult | undefined>; /** * Get Origin Trials on given frame. */ getOriginTrials( params: Page.GetOriginTrialsParams, ): Promise<Page.GetOriginTrialsResult | undefined>; /** * Overrides the values of device screen dimensions (window.screen.width, window.screen.height, * window.innerWidth, window.innerHeight, and "device-width"/"device-height"-related CSS media * query results). * @deprecated */ setDeviceMetricsOverride( params: Page.SetDeviceMetricsOverrideParams, ): Promise<Page.SetDeviceMetricsOverrideResult | undefined>; /** * Overrides the Device Orientation. * @deprecated */ setDeviceOrientationOverride( params: Page.SetDeviceOrientationOverrideParams, ): Promise<Page.SetDeviceOrientationOverrideResult | undefined>; /** * Set generic font families. */ setFontFamilies( params: Page.SetFontFamiliesParams, ): Promise<Page.SetFontFamiliesResult | undefined>; /** * Set default font sizes. */ setFontSizes(params: Page.SetFontSizesParams): Promise<Page.SetFontSizesResult | undefined>; /** * Sets given markup as the document's HTML. */ setDocumentContent( params: Page.SetDocumentContentParams, ): Promise<Page.SetDocumentContentResult | undefined>; /** * Set the behavior when downloading a file. * @deprecated */ setDownloadBehavior( params: Page.SetDownloadBehaviorParams, ): Promise<Page.SetDownloadBehaviorResult | undefined>; /** * Overrides the Geolocation Position or Error. Omitting any of the parameters emulates position * unavailable. * @deprecated */ setGeolocationOverride( params: Page.SetGeolocationOverrideParams, ): Promise<Page.SetGeolocationOverrideResult | undefined>; /** * Controls whether page will emit lifecycle events. */ setLifecycleEventsEnabled( params: Page.SetLifecycleEventsEnabledParams, ): Promise<Page.SetLifecycleEventsEnabledResult | undefined>; /** * Toggles mouse event-based touch event emulation. * @deprecated */ setTouchEmulationEnabled( params: Page.SetTouchEmulationEnabledParams, ): Promise<Page.SetTouchEmulationEnabledResult | undefined>; /** * Starts sending each frame using the `screencastFrame` event. */ startScreencast( params: Page.StartScreencastParams, ): Promise<Page.StartScreencastResult | undefined>; /** * Force the page stop all navigations and pending resource fetches. */ stopLoading(params: Page.StopLoadingParams): Promise<Page.StopLoadingResult | undefined>; /** * Crashes renderer on the IO thread, generates minidumps. */ crash(params: Page.CrashParams): Promise<Page.CrashResult | undefined>; /** * Tries to close page, running its beforeunload hooks, if any. */ close(params: Page.CloseParams): Promise<Page.CloseResult | undefined>; /** * Tries to update the web lifecycle state of the page. * It will transition the page to the given state according to: * https://github.com/WICG/web-lifecycle/ */ setWebLifecycleState( params: Page.SetWebLifecycleStateParams, ): Promise<Page.SetWebLifecycleStateResult | undefined>; /** * Stops sending each frame in the `screencastFrame`. */ stopScreencast( params: Page.StopScreencastParams, ): Promise<Page.StopScreencastResult | undefined>; /** * Requests backend to produce compilation cache for the specified scripts. * `scripts` are appeneded to the list of scripts for which the cache * would be produced. The list may be reset during page navigation. * When script with a matching URL is encountered, the cache is optionally * produced upon backend discretion, based on internal heuristics. * See also: `Page.compilationCacheProduced`. */ produceCompilationCache( params: Page.ProduceCompilationCacheParams, ): Promise<Page.ProduceCompilationCacheResult | undefined>; /** * Seeds compilation cache for given url. Compilation cache does not survive * cross-process navigation. */ addCompilationCache( params: Page.AddCompilationCacheParams, ): Promise<Page.AddCompilationCacheResult | undefined>; /** * Clears seeded compilation cache. */ clearCompilationCache( params: Page.ClearCompilationCacheParams, ): Promise<Page.ClearCompilationCacheResult | undefined>; /** * Generates a report for testing. */ generateTestReport( params: Page.GenerateTestReportParams, ): Promise<Page.GenerateTestReportResult | undefined>; /** * Pauses page execution. Can be resumed using generic Runtime.runIfWaitingForDebugger. */ waitForDebugger( params: Page.WaitForDebuggerParams, ): Promise<Page.WaitForDebuggerResult | undefined>; /** * Intercept file chooser requests and transfer control to protocol clients. * When file chooser interception is enabled, native file chooser dialog is not shown. * Instead, a protocol event `Page.fileChooserOpened` is emitted. */ setInterceptFileChooserDialog( params: Page.SetInterceptFileChooserDialogParams, ): Promise<Page.SetInterceptFileChooserDialogResult | undefined>; on( event: 'domContentEventFired', listener: (event: Page.DomContentEventFiredEvent) => void, ): IDisposable; /** * Emitted only when `page.interceptFileChooser` is enabled. */ on( event: 'fileChooserOpened', listener: (event: Page.FileChooserOpenedEvent) => void, ): IDisposable; /** * Fired when frame has been attached to its parent. */ on(event: 'frameAttached', listener: (event: Page.FrameAttachedEvent) => void): IDisposable; /** * Fired when frame no longer has a scheduled navigation. * @deprecated */ on( event: 'frameClearedScheduledNavigation', listener: (event: Page.FrameClearedScheduledNavigationEvent) => void, ): IDisposable; /** * Fired when frame has been detached from its parent. */ on(event: 'frameDetached', listener: (event: Page.FrameDetachedEvent) => void): IDisposable; /** * Fired once navigation of the frame has completed. Frame is now associated with the new loader. */ on(event: 'frameNavigated', listener: (event: Page.FrameNavigatedEvent) => void): IDisposable; /** * Fired when opening document to write to. */ on(event: 'documentOpened', listener: (event: Page.DocumentOpenedEvent) => void): IDisposable; on(event: 'frameResized', listener: (event: Page.FrameResizedEvent) => void): IDisposable; /** * Fired when a renderer-initiated navigation is requested. * Navigation may still be cancelled after the event is issued. */ on( event: 'frameRequestedNavigation', listener: (event: Page.FrameRequestedNavigationEvent) => void, ): IDisposable; /** * Fired when frame schedules a potential navigation. * @deprecated */ on( event: 'frameScheduledNavigation', listener: (event: Page.FrameScheduledNavigationEvent) => void, ): IDisposable; /** * Fired when frame has started loading. */ on( event: 'frameStartedLoading', listener: (event: Page.FrameStartedLoadingEvent) => void, ): IDisposable; /** * Fired when frame has stopped loading. */ on( event: 'frameStoppedLoading', listener: (event: Page.FrameStoppedLoadingEvent) => void, ): IDisposable; /** * Fired when page is about to start a download. * Deprecated. Use Browser.downloadWillBegin instead. * @deprecated */ on( event: 'downloadWillBegin', listener: (event: Page.DownloadWillBeginEvent) => void, ): IDisposable; /** * Fired when download makes progress. Last call has |done| == true. * Deprecated. Use Browser.downloadProgress instead. * @deprecated */ on( event: 'downloadProgress', listener: (event: Page.DownloadProgressEvent) => void, ): IDisposable; /** * Fired when interstitial page was hidden */ on( event: 'interstitialHidden', listener: (event: Page.InterstitialHiddenEvent) => void, ): IDisposable; /** * Fired when interstitial page was shown */ on( event: 'interstitialShown', listener: (event: Page.InterstitialShownEvent) => void, ): IDisposable; /** * Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) has been * closed. */ on( event: 'javascriptDialogClosed', listener: (event: Page.JavascriptDialogClosedEvent) => void, ): IDisposable; /** * Fired when a JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload) is about to * open. */ on( event: 'javascriptDialogOpening', listener: (event: Page.JavascriptDialogOpeningEvent) => void, ): IDisposable; /** * Fired for top level page lifecycle events such as navigation, load, paint, etc. */ on(event: 'lifecycleEvent', listener: (event: Page.LifecycleEventEvent) => void): IDisposable; /** * Fired for failed bfcache history navigations if BackForwardCache feature is enabled. Do * not assume any ordering with the Page.frameNavigated event. This event is fired only for * main-frame history navigation where the document changes (non-same-document navigations), * when bfcache navigation fails. */ on( event: 'backForwardCacheNotUsed', listener: (event: Page.BackForwardCacheNotUsedEvent) => void, ): IDisposable; on(event: 'loadEventFired', listener: (event: Page.LoadEventFiredEvent) => void): IDisposable; /** * Fired when same-document navigation happens, e.g. due to history API usage or anchor navigation. */ on( event: 'navigatedWithinDocument', listener: (event: Page.NavigatedWithinDocumentEvent) => void, ): IDisposable; /** * Compressed image data requested by the `startScreencast`. */ on(event: 'screencastFrame', listener: (event: Page.ScreencastFrameEvent) => void): IDisposable; /** * Fired when the page with currently enabled screencast was shown or hidden `. */ on( event: 'screencastVisibilityChanged', listener: (event: Page.ScreencastVisibilityChangedEvent) => void, ): IDisposable; /** * Fired when a new window is going to be opened, via window.open(), link click, form submission, * etc. */ on(event: 'windowOpen', listener: (event: Page.WindowOpenEvent) => void): IDisposable; /** * Issued for every compilation cache generated. Is only available * if Page.setGenerateCompilationCache is enabled. */ on( event: 'compilationCacheProduced', listener: (event: Page.CompilationCacheProducedEvent) => void, ): IDisposable; } /** * Types of the 'Page' domain. */ export namespace Page { /** * Parameters of the 'Page.addScriptToEvaluateOnLoad' method. */ export interface AddScriptToEvaluateOnLoadParams { scriptSource: string; } /** * Return value of the 'Page.addScriptToEvaluateOnLoad' method. */ export interface AddScriptToEvaluateOnLoadResult { /** * Identifier of the added script. */ identifier: ScriptIdentifier; } /** * Parameters of the 'Page.addScriptToEvaluateOnNewDocument' method. */ export interface AddScriptToEvaluateOnNewDocumentParams { source: string; /** * If specified, creates an isolated world with the given name and evaluates given script in it. * This world name will be used as the ExecutionContextDescription::name when the corresponding * event is emitted. */ worldName?: string; /** * Specifies whether command line API should be available to the script, defaults * to false. */ includeCommandLineAPI?: boolean; } /** * Return value of the 'Page.addScriptToEvaluateOnNewDocument' method. */ export interface AddScriptToEvaluateOnNewDocumentResult { /** * Identifier of the added script. */ identifier: ScriptIdentifier; } /** * Parameters of the 'Page.bringToFront' method. */ export interface BringToFrontParams {} /** * Return value of the 'Page.bringToFront' method. */ export interface BringToFrontResult {} /** * Parameters of the 'Page.captureScreenshot' method. */ export interface CaptureScreenshotParams { /** * Image compression format (defaults to png). */ format?: 'jpeg' | 'png' | 'webp'; /** * Compression quality from range [0..100] (jpeg only). */ quality?: integer; /** * Capture the screenshot of a given region only. */ clip?: Viewport; /** * Capture the screenshot from the surface, rather than the view. Defaults to true. */ fromSurface?: boolean; /** * Capture the screenshot beyond the viewport. Defaults to false. */ captureBeyondViewport?: boolean; } /** * Return value of the 'Page.captureScreenshot' method. */ export interface CaptureScreenshotResult { /** * Base64-encoded image data. (Encoded as a base64 string when passed over JSON) */ data: string; } /** * Parameters of the 'Page.captureSnapshot' method. */ export interface CaptureSnapshotParams { /** * Format (defaults to mhtml). */ format?: 'mhtml'; } /** * Return value of the 'Page.captureSnapshot' method. */ export interface CaptureSnapshotResult { /** * Serialized page data. */ data: string; } /** * Parameters of the 'Page.clearDeviceMetricsOverride' method. */ export interface ClearDeviceMetricsOverrideParams {} /** * Return value of the 'Page.clearDeviceMetricsOverride' method. */ export interface ClearDeviceMetricsOverrideResult {} /** * Parameters of the 'Page.clearDeviceOrientationOverride' method. */ export interface ClearDeviceOrientationOverrideParams {} /** * Return value of the 'Page.clearDeviceOrientationOverride' method. */ export interface ClearDeviceOrientationOverrideResult {} /** * Parameters of the 'Page.clearGeolocationOverride' method. */ export interface ClearGeolocationOverrideParams {} /** * Return value of the 'Page.clearGeolocationOverride' method. */ export interface ClearGeolocationOverrideResult {} /** * Parameters of the 'Page.createIsolatedWorld' method. */ export interface CreateIsolatedWorldParams { /** * Id of the frame in which the isolated world should be created. */ frameId: FrameId; /** * An optional name which is reported in the Execution Context. */ worldName?: string; /** * Whether or not universal access should be granted to the isolated world. This is a powerful * option, use with caution. */ grantUniveralAccess?: boolean; } /** * Return value of the 'Page.createIsolatedWorld' method. */ export interface CreateIsolatedWorldResult { /** * Execution context of the isolated world. */ executionContextId: Runtime.ExecutionContextId; } /** * Parameters of the 'Page.deleteCookie' method. */ export interface DeleteCookieParams { /** * Name of the cookie to remove. */ cookieName: string; /** * URL to match cooke domain and path. */ url: string; } /** * Return value of the 'Page.deleteCookie' method. */ export interface DeleteCookieResult {} /** * Parameters of the 'Page.disable' method. */ export interface DisableParams {} /** * Return value of the 'Page.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Page.enable' method. */ export interface EnableParams {} /** * Return value of the 'Page.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Page.getAppManifest' method. */ export interface GetAppManifestParams {} /** * Return value of the 'Page.getAppManifest' method. */ export interface GetAppManifestResult { /** * Manifest location. */ url: string; errors: AppManifestError[]; /** * Manifest content. */ data?: string; /** * Parsed manifest properties */ parsed?: AppManifestParsedProperties; } /** * Parameters of the 'Page.getInstallabilityErrors' method. */ export interface GetInstallabilityErrorsParams {} /** * Return value of the 'Page.getInstallabilityErrors' method. */ export interface GetInstallabilityErrorsResult { installabilityErrors: InstallabilityError[]; } /** * Parameters of the 'Page.getManifestIcons' method. */ export interface GetManifestIconsParams {} /** * Return value of the 'Page.getManifestIcons' method. */ export interface GetManifestIconsResult { primaryIcon?: string; } /** * Parameters of the 'Page.getAppId' method. */ export interface GetAppIdParams {} /** * Return value of the 'Page.getAppId' method. */ export interface GetAppIdResult { /** * App id, either from manifest's id attribute or computed from start_url */ appId?: string; /** * Recommendation for manifest's id attribute to match current id computed from start_url */ recommendedId?: string; } /** * Parameters of the 'Page.getCookies' method. */ export interface GetCookiesParams {} /** * Return value of the 'Page.getCookies' method. */ export interface GetCookiesResult { /** * Array of cookie objects. */ cookies: Network.Cookie[]; } /** * Parameters of the 'Page.getFrameTree' method. */ export interface GetFrameTreeParams {} /** * Return value of the 'Page.getFrameTree' method. */ export interface GetFrameTreeResult { /** * Present frame tree structure. */ frameTree: FrameTree; } /** * Parameters of the 'Page.getLayoutMetrics' method. */ export interface GetLayoutMetricsParams {} /** * Return value of the 'Page.getLayoutMetrics' method. */ export interface GetLayoutMetricsResult { /** * Deprecated metrics relating to the layout viewport. Can be in DP or in CSS pixels depending on the `enable-use-zoom-for-dsf` flag. Use `cssLayoutViewport` instead. * @deprecated */ layoutViewport: LayoutViewport; /** * Deprecated metrics relating to the visual viewport. Can be in DP or in CSS pixels depending on the `enable-use-zoom-for-dsf` flag. Use `cssVisualViewport` instead. * @deprecated */ visualViewport: VisualViewport; /** * Deprecated size of scrollable area. Can be in DP or in CSS pixels depending on the `enable-use-zoom-for-dsf` flag. Use `cssContentSize` instead. * @deprecated */ contentSize: DOM.Rect; /** * Metrics relating to the layout viewport in CSS pixels. */ cssLayoutViewport: LayoutViewport; /** * Metrics relating to the visual viewport in CSS pixels. */ cssVisualViewport: VisualViewport; /** * Size of scrollable area in CSS pixels. */ cssContentSize: DOM.Rect; } /** * Parameters of the 'Page.getNavigationHistory' method. */ export interface GetNavigationHistoryParams {} /** * Return value of the 'Page.getNavigationHistory' method. */ export interface GetNavigationHistoryResult { /** * Index of the current navigation history entry. */ currentIndex: integer; /** * Array of navigation history entries. */ entries: NavigationEntry[]; } /** * Parameters of the 'Page.resetNavigationHistory' method. */ export interface ResetNavigationHistoryParams {} /** * Return value of the 'Page.resetNavigationHistory' method. */ export interface ResetNavigationHistoryResult {} /** * Parameters of the 'Page.getResourceContent' method. */ export interface GetResourceContentParams { /** * Frame id to get resource for. */ frameId: FrameId; /** * URL of the resource to get content for. */ url: string; } /** * Return value of the 'Page.getResourceContent' method. */ export interface GetResourceContentResult { /** * Resource content. */ content: string; /** * True, if content was served as base64. */ base64Encoded: boolean; } /** * Parameters of the 'Page.getResourceTree' method. */ export interface GetResourceTreeParams {} /** * Return value of the 'Page.getResourceTree' method. */ export interface GetResourceTreeResult { /** * Present frame / resource tree structure. */ frameTree: FrameResourceTree; } /** * Parameters of the 'Page.handleJavaScriptDialog' method. */ export interface HandleJavaScriptDialogParams { /** * Whether to accept or dismiss the dialog. */ accept: boolean; /** * The text to enter into the dialog prompt before accepting. Used only if this is a prompt * dialog. */ promptText?: string; } /** * Return value of the 'Page.handleJavaScriptDialog' method. */ export interface HandleJavaScriptDialogResult {} /** * Parameters of the 'Page.navigate' method. */ export interface NavigateParams { /** * URL to navigate the page to. */ url: string; /** * Referrer URL. */ referrer?: string; /** * Intended transition type. */ transitionType?: TransitionType; /** * Frame id to navigate, if not specified navigates the top frame. */ frameId?: FrameId; /** * Referrer-policy used for the navigation. */ referrerPolicy?: ReferrerPolicy; } /** * Return value of the 'Page.navigate' method. */ export interface NavigateResult { /** * Frame id that has navigated (or failed to navigate) */ frameId: FrameId; /** * Loader identifier. */ loaderId?: Network.LoaderId; /** * User friendly error message, present if and only if navigation has failed. */ errorText?: string; } /** * Parameters of the 'Page.navigateToHistoryEntry' method. */ export interface NavigateToHistoryEntryParams { /** * Unique id of the entry to navigate to. */ entryId: integer; } /** * Return value of the 'Page.navigateToHistoryEntry' method. */ export interface NavigateToHistoryEntryResult {} /** * Parameters of the 'Page.printToPDF' method. */ export interface PrintToPDFParams { /** * Paper orientation. Defaults to false. */ landscape?: boolean; /** * Display header and footer. Defaults to false. */ displayHeaderFooter?: boolean; /** * Print background graphics. Defaults to false. */ printBackground?: boolean; /** * Scale of the webpage rendering. Defaults to 1. */ scale?: number; /** * Paper width in inches. Defaults to 8.5 inches. */ paperWidth?: number; /** * Paper height in inches. Defaults to 11 inches. */ paperHeight?: number; /** * Top margin in inches. Defaults to 1cm (~0.4 inches). */ marginTop?: number; /** * Bottom margin in inches. Defaults to 1cm (~0.4 inches). */ marginBottom?: number; /** * Left margin in inches. Defaults to 1cm (~0.4 inches). */ marginLeft?: number; /** * Right margin in inches. Defaults to 1cm (~0.4 inches). */ marginRight?: number; /** * Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means * print all pages. */ pageRanges?: string; /** * Whether to silently ignore invalid but successfully parsed page ranges, such as '3-2'. * Defaults to false. */ ignoreInvalidPageRanges?: boolean; /** * HTML template for the print header. Should be valid HTML markup with following * classes used to inject printing values into them: * - `date`: formatted print date * - `title`: document title * - `url`: document location * - `pageNumber`: current page number * - `totalPages`: total pages in the document * * For example, `<span class=title></span>` would generate span containing the title. */ headerTemplate?: string; /** * HTML template for the print footer. Should use the same format as the `headerTemplate`. */ footerTemplate?: string; /** * Whether or not to prefer page size as defined by css. Defaults to false, * in which case the content will be scaled to fit the paper size. */ preferCSSPageSize?: boolean; /** * return as stream */ transferMode?: 'ReturnAsBase64' | 'ReturnAsStream'; } /** * Return value of the 'Page.printToPDF' method. */ export interface PrintToPDFResult { /** * Base64-encoded pdf data. Empty if |returnAsStream| is specified. (Encoded as a base64 string when passed over JSON) */ data: string; /** * A handle of the stream that holds resulting PDF data. */ stream?: IO.StreamHandle; } /** * Parameters of the 'Page.reload' method. */ export interface ReloadParams { /** * If true, browser cache is ignored (as if the user pressed Shift+refresh). */ ignoreCache?: boolean; /** * If set, the script will be injected into all frames of the inspected page after reload. * Argument will be ignored if reloading dataURL origin. */ scriptToEvaluateOnLoad?: string; } /** * Return value of the 'Page.reload' method. */ export interface ReloadResult {} /** * Parameters of the 'Page.removeScriptToEvaluateOnLoad' method. */ export interface RemoveScriptToEvaluateOnLoadParams { identifier: ScriptIdentifier; } /** * Return value of the 'Page.removeScriptToEvaluateOnLoad' method. */ export interface RemoveScriptToEvaluateOnLoadResult {} /** * Parameters of the 'Page.removeScriptToEvaluateOnNewDocument' method. */ export interface RemoveScriptToEvaluateOnNewDocumentParams { identifier: ScriptIdentifier; } /** * Return value of the 'Page.removeScriptToEvaluateOnNewDocument' method. */ export interface RemoveScriptToEvaluateOnNewDocumentResult {} /** * Parameters of the 'Page.screencastFrameAck' method. */ export interface ScreencastFrameAckParams { /** * Frame number. */ sessionId: integer; } /** * Return value of the 'Page.screencastFrameAck' method. */ export interface ScreencastFrameAckResult {} /** * Parameters of the 'Page.searchInResource' method. */ export interface SearchInResourceParams { /** * Frame id for resource to search in. */ frameId: FrameId; /** * URL of the resource to search in. */ url: string; /** * String to search for. */ query: string; /** * If true, search is case sensitive. */ caseSensitive?: boolean; /** * If true, treats string parameter as regex. */ isRegex?: boolean; } /** * Return value of the 'Page.searchInResource' method. */ export interface SearchInResourceResult { /** * List of search matches. */ result: Debugger.SearchMatch[]; } /** * Parameters of the 'Page.setAdBlockingEnabled' method. */ export interface SetAdBlockingEnabledParams { /** * Whether to block ads. */ enabled: boolean; } /** * Return value of the 'Page.setAdBlockingEnabled' method. */ export interface SetAdBlockingEnabledResult {} /** * Parameters of the 'Page.setBypassCSP' method. */ export interface SetBypassCSPParams { /** * Whether to bypass page CSP. */ enabled: boolean; } /** * Return value of the 'Page.setBypassCSP' method. */ export interface SetBypassCSPResult {} /** * Parameters of the 'Page.getPermissionsPolicyState' method. */ export interface GetPermissionsPolicyStateParams { frameId: FrameId; } /** * Return value of the 'Page.getPermissionsPolicyState' method. */ export interface GetPermissionsPolicyStateResult { states: PermissionsPolicyFeatureState[]; } /** * Parameters of the 'Page.getOriginTrials' method. */ export interface GetOriginTrialsParams { frameId: FrameId; } /** * Return value of the 'Page.getOriginTrials' method. */ export interface GetOriginTrialsResult { originTrials: OriginTrial[]; } /** * Parameters of the 'Page.setDeviceMetricsOverride' method. */ export interface SetDeviceMetricsOverrideParams { /** * Overriding width value in pixels (minimum 0, maximum 10000000). 0 disables the override. */ width: integer; /** * Overriding height value in pixels (minimum 0, maximum 10000000). 0 disables the override. */ height: integer; /** * Overriding device scale factor value. 0 disables the override. */ deviceScaleFactor: number; /** * Whether to emulate mobile device. This includes viewport meta tag, overlay scrollbars, text * autosizing and more. */ mobile: boolean; /** * Scale to apply to resulting view image. */ scale?: number; /** * Overriding screen width value in pixels (minimum 0, maximum 10000000). */ screenWidth?: integer; /** * Overriding screen height value in pixels (minimum 0, maximum 10000000). */ screenHeight?: integer; /** * Overriding view X position on screen in pixels (minimum 0, maximum 10000000). */ positionX?: integer; /** * Overriding view Y position on screen in pixels (minimum 0, maximum 10000000). */ positionY?: integer; /** * Do not set visible view size, rely upon explicit setVisibleSize call. */ dontSetVisibleSize?: boolean; /** * Screen orientation override. */ screenOrientation?: Emulation.ScreenOrientation; /** * The viewport dimensions and scale. If not set, the override is cleared. */ viewport?: Viewport; } /** * Return value of the 'Page.setDeviceMetricsOverride' method. */ export interface SetDeviceMetricsOverrideResult {} /** * Parameters of the 'Page.setDeviceOrientationOverride' method. */ export interface SetDeviceOrientationOverrideParams { /** * Mock alpha */ alpha: number; /** * Mock beta */ beta: number; /** * Mock gamma */ gamma: number; } /** * Return value of the 'Page.setDeviceOrientationOverride' method. */ export interface SetDeviceOrientationOverrideResult {} /** * Parameters of the 'Page.setFontFamilies' method. */ export interface SetFontFamiliesParams { /** * Specifies font families to set. If a font family is not specified, it won't be changed. */ fontFamilies: FontFamilies; } /** * Return value of the 'Page.setFontFamilies' method. */ export interface SetFontFamiliesResult {} /** * Parameters of the 'Page.setFontSizes' method. */ export interface SetFontSizesParams { /** * Specifies font sizes to set. If a font size is not specified, it won't be changed. */ fontSizes: FontSizes; } /** * Return value of the 'Page.setFontSizes' method. */ export interface SetFontSizesResult {} /** * Parameters of the 'Page.setDocumentContent' method. */ export interface SetDocumentContentParams { /** * Frame id to set HTML for. */ frameId: FrameId; /** * HTML content to set. */ html: string; } /** * Return value of the 'Page.setDocumentContent' method. */ export interface SetDocumentContentResult {} /** * Parameters of the 'Page.setDownloadBehavior' method. */ export interface SetDownloadBehaviorParams { /** * Whether to allow all or deny all download requests, or use default Chrome behavior if * available (otherwise deny). */ behavior: 'deny' | 'allow' | 'default'; /** * The default path to save downloaded files to. This is required if behavior is set to 'allow' */ downloadPath?: string; } /** * Return value of the 'Page.setDownloadBehavior' method. */ export interface SetDownloadBehaviorResult {} /** * Parameters of the 'Page.setGeolocationOverride' method. */ export interface SetGeolocationOverrideParams { /** * Mock latitude */ latitude?: number; /** * Mock longitude */ longitude?: number; /** * Mock accuracy */ accuracy?: number; } /** * Return value of the 'Page.setGeolocationOverride' method. */ export interface SetGeolocationOverrideResult {} /** * Parameters of the 'Page.setLifecycleEventsEnabled' method. */ export interface SetLifecycleEventsEnabledParams { /** * If true, starts emitting lifecycle events. */ enabled: boolean; } /** * Return value of the 'Page.setLifecycleEventsEnabled' method. */ export interface SetLifecycleEventsEnabledResult {} /** * Parameters of the 'Page.setTouchEmulationEnabled' method. */ export interface SetTouchEmulationEnabledParams { /** * Whether the touch event emulation should be enabled. */ enabled: boolean; /** * Touch/gesture events configuration. Default: current platform. */ configuration?: 'mobile' | 'desktop'; } /** * Return value of the 'Page.setTouchEmulationEnabled' method. */ export interface SetTouchEmulationEnabledResult {} /** * Parameters of the 'Page.startScreencast' method. */ export interface StartScreencastParams { /** * Image compression format. */ format?: 'jpeg' | 'png'; /** * Compression quality from range [0..100]. */ quality?: integer; /** * Maximum screenshot width. */ maxWidth?: integer; /** * Maximum screenshot height. */ maxHeight?: integer; /** * Send every n-th frame. */ everyNthFrame?: integer; } /** * Return value of the 'Page.startScreencast' method. */ export interface StartScreencastResult {} /** * Parameters of the 'Page.stopLoading' method. */ export interface StopLoadingParams {} /** * Return value of the 'Page.stopLoading' method. */ export interface StopLoadingResult {} /** * Parameters of the 'Page.crash' method. */ export interface CrashParams {} /** * Return value of the 'Page.crash' method. */ export interface CrashResult {} /** * Parameters of the 'Page.close' method. */ export interface CloseParams {} /** * Return value of the 'Page.close' method. */ export interface CloseResult {} /** * Parameters of the 'Page.setWebLifecycleState' method. */ export interface SetWebLifecycleStateParams { /** * Target lifecycle state */ state: 'frozen' | 'active'; } /** * Return value of the 'Page.setWebLifecycleState' method. */ export interface SetWebLifecycleStateResult {} /** * Parameters of the 'Page.stopScreencast' method. */ export interface StopScreencastParams {} /** * Return value of the 'Page.stopScreencast' method. */ export interface StopScreencastResult {} /** * Parameters of the 'Page.produceCompilationCache' method. */ export interface ProduceCompilationCacheParams { scripts: CompilationCacheParams[]; } /** * Return value of the 'Page.produceCompilationCache' method. */ export interface ProduceCompilationCacheResult {} /** * Parameters of the 'Page.addCompilationCache' method. */ export interface AddCompilationCacheParams { url: string; /** * Base64-encoded data (Encoded as a base64 string when passed over JSON) */ data: string; } /** * Return value of the 'Page.addCompilationCache' method. */ export interface AddCompilationCacheResult {} /** * Parameters of the 'Page.clearCompilationCache' method. */ export interface ClearCompilationCacheParams {} /** * Return value of the 'Page.clearCompilationCache' method. */ export interface ClearCompilationCacheResult {} /** * Parameters of the 'Page.generateTestReport' method. */ export interface GenerateTestReportParams { /** * Message to be displayed in the report. */ message: string; /** * Specifies the endpoint group to deliver the report to. */ group?: string; } /** * Return value of the 'Page.generateTestReport' method. */ export interface GenerateTestReportResult {} /** * Parameters of the 'Page.waitForDebugger' method. */ export interface WaitForDebuggerParams {} /** * Return value of the 'Page.waitForDebugger' method. */ export interface WaitForDebuggerResult {} /** * Parameters of the 'Page.setInterceptFileChooserDialog' method. */ export interface SetInterceptFileChooserDialogParams { enabled: boolean; } /** * Return value of the 'Page.setInterceptFileChooserDialog' method. */ export interface SetInterceptFileChooserDialogResult {} /** * Parameters of the 'Page.domContentEventFired' event. */ export interface DomContentEventFiredEvent { timestamp: Network.MonotonicTime; } /** * Parameters of the 'Page.fileChooserOpened' event. */ export interface FileChooserOpenedEvent { /** * Id of the frame containing input node. */ frameId: FrameId; /** * Input node id. */ backendNodeId: DOM.BackendNodeId; /** * Input mode. */ mode: 'selectSingle' | 'selectMultiple'; } /** * Parameters of the 'Page.frameAttached' event. */ export interface FrameAttachedEvent { /** * Id of the frame that has been attached. */ frameId: FrameId; /** * Parent frame identifier. */ parentFrameId: FrameId; /** * JavaScript stack trace of when frame was attached, only set if frame initiated from script. */ stack?: Runtime.StackTrace; } /** * Parameters of the 'Page.frameClearedScheduledNavigation' event. */ export interface FrameClearedScheduledNavigationEvent { /** * Id of the frame that has cleared its scheduled navigation. */ frameId: FrameId; } /** * Parameters of the 'Page.frameDetached' event. */ export interface FrameDetachedEvent { /** * Id of the frame that has been detached. */ frameId: FrameId; reason: 'remove' | 'swap'; } /** * Parameters of the 'Page.frameNavigated' event. */ export interface FrameNavigatedEvent { /** * Frame object. */ frame: Frame; type: NavigationType; } /** * Parameters of the 'Page.documentOpened' event. */ export interface DocumentOpenedEvent { /** * Frame object. */ frame: Frame; } /** * Parameters of the 'Page.frameResized' event. */ export interface FrameResizedEvent {} /** * Parameters of the 'Page.frameRequestedNavigation' event. */ export interface FrameRequestedNavigationEvent { /** * Id of the frame that is being navigated. */ frameId: FrameId; /** * The reason for the navigation. */ reason: ClientNavigationReason; /** * The destination URL for the requested navigation. */ url: string; /** * The disposition for the navigation. */ disposition: ClientNavigationDisposition; } /** * Parameters of the 'Page.frameScheduledNavigation' event. */ export interface FrameScheduledNavigationEvent { /** * Id of the frame that has scheduled a navigation. */ frameId: FrameId; /** * Delay (in seconds) until the navigation is scheduled to begin. The navigation is not * guaranteed to start. */ delay: number; /** * The reason for the navigation. */ reason: ClientNavigationReason; /** * The destination URL for the scheduled navigation. */ url: string; } /** * Parameters of the 'Page.frameStartedLoading' event. */ export interface FrameStartedLoadingEvent { /** * Id of the frame that has started loading. */ frameId: FrameId; } /** * Parameters of the 'Page.frameStoppedLoading' event. */ export interface FrameStoppedLoadingEvent { /** * Id of the frame that has stopped loading. */ frameId: FrameId; } /** * Parameters of the 'Page.downloadWillBegin' event. */ export interface DownloadWillBeginEvent { /** * Id of the frame that caused download to begin. */ frameId: FrameId; /** * Global unique identifier of the download. */ guid: string; /** * URL of the resource being downloaded. */ url: string; /** * Suggested file name of the resource (the actual name of the file saved on disk may differ). */ suggestedFilename: string; } /** * Parameters of the 'Page.downloadProgress' event. */ export interface DownloadProgressEvent { /** * Global unique identifier of the download. */ guid: string; /** * Total expected bytes to download. */ totalBytes: number; /** * Total bytes received. */ receivedBytes: number; /** * Download status. */ state: 'inProgress' | 'completed' | 'canceled'; } /** * Parameters of the 'Page.interstitialHidden' event. */ export interface InterstitialHiddenEvent {} /** * Parameters of the 'Page.interstitialShown' event. */ export interface InterstitialShownEvent {} /** * Parameters of the 'Page.javascriptDialogClosed' event. */ export interface JavascriptDialogClosedEvent { /** * Whether dialog was confirmed. */ result: boolean; /** * User input in case of prompt. */ userInput: string; } /** * Parameters of the 'Page.javascriptDialogOpening' event. */ export interface JavascriptDialogOpeningEvent { /** * Frame url. */ url: string; /** * Message that will be displayed by the dialog. */ message: string; /** * Dialog type. */ type: DialogType; /** * True iff browser is capable showing or acting on the given dialog. When browser has no * dialog handler for given target, calling alert while Page domain is engaged will stall * the page execution. Execution can be resumed via calling Page.handleJavaScriptDialog. */ hasBrowserHandler: boolean; /** * Default dialog prompt. */ defaultPrompt?: string; } /** * Parameters of the 'Page.lifecycleEvent' event. */ export interface LifecycleEventEvent { /** * Id of the frame. */ frameId: FrameId; /** * Loader identifier. Empty string if the request is fetched from worker. */ loaderId: Network.LoaderId; name: string; timestamp: Network.MonotonicTime; } /** * Parameters of the 'Page.backForwardCacheNotUsed' event. */ export interface BackForwardCacheNotUsedEvent { /** * The loader id for the associated navgation. */ loaderId: Network.LoaderId; /** * The frame id of the associated frame. */ frameId: FrameId; /** * Array of reasons why the page could not be cached. This must not be empty. */ notRestoredExplanations: BackForwardCacheNotRestoredExplanation[]; } /** * Parameters of the 'Page.loadEventFired' event. */ export interface LoadEventFiredEvent { timestamp: Network.MonotonicTime; } /** * Parameters of the 'Page.navigatedWithinDocument' event. */ export interface NavigatedWithinDocumentEvent { /** * Id of the frame. */ frameId: FrameId; /** * Frame's new url. */ url: string; } /** * Parameters of the 'Page.screencastFrame' event. */ export interface ScreencastFrameEvent { /** * Base64-encoded compressed image. (Encoded as a base64 string when passed over JSON) */ data: string; /** * Screencast frame metadata. */ metadata: ScreencastFrameMetadata; /** * Frame number. */ sessionId: integer; } /** * Parameters of the 'Page.screencastVisibilityChanged' event. */ export interface ScreencastVisibilityChangedEvent { /** * True if the page is visible. */ visible: boolean; } /** * Parameters of the 'Page.windowOpen' event. */ export interface WindowOpenEvent { /** * The URL for the new window. */ url: string; /** * Window name. */ windowName: string; /** * An array of enabled window features. */ windowFeatures: string[]; /** * Whether or not it was triggered by user gesture. */ userGesture: boolean; } /** * Parameters of the 'Page.compilationCacheProduced' event. */ export interface CompilationCacheProducedEvent { url: string; /** * Base64-encoded data (Encoded as a base64 string when passed over JSON) */ data: string; } /** * Unique frame identifier. */ export type FrameId = string; /** * Indicates whether a frame has been identified as an ad. */ export type AdFrameType = 'none' | 'child' | 'root'; export type AdFrameExplanation = 'ParentIsAd' | 'CreatedByAdScript' | 'MatchedBlockingRule'; /** * Indicates whether a frame has been identified as an ad and why. */ export interface AdFrameStatus { adFrameType: AdFrameType; explanations?: AdFrameExplanation[]; } /** * Indicates whether the frame is a secure context and why it is the case. */ export type SecureContextType = | 'Secure' | 'SecureLocalhost' | 'InsecureScheme' | 'InsecureAncestor'; /** * Indicates whether the frame is cross-origin isolated and why it is the case. */ export type CrossOriginIsolatedContextType = | 'Isolated' | 'NotIsolated' | 'NotIsolatedFeatureDisabled'; export type GatedAPIFeatures = | 'SharedArrayBuffers' | 'SharedArrayBuffersTransferAllowed' | 'PerformanceMeasureMemory' | 'PerformanceProfile'; /** * All Permissions Policy features. This enum should match the one defined * in third_party/blink/renderer/core/permissions_policy/permissions_policy_features.json5. */ export type PermissionsPolicyFeature = | 'accelerometer' | 'ambient-light-sensor' | 'attribution-reporting' | 'autoplay' | 'camera' | 'ch-dpr' | 'ch-device-memory' | 'ch-downlink' | 'ch-ect' | 'ch-prefers-color-scheme' | 'ch-rtt' | 'ch-ua' | 'ch-ua-arch' | 'ch-ua-bitness' | 'ch-ua-platform' | 'ch-ua-model' | 'ch-ua-mobile' | 'ch-ua-full-version' | 'ch-ua-platform-version' | 'ch-ua-reduced' | 'ch-viewport-height' | 'ch-viewport-width' | 'ch-width' | 'clipboard-read' | 'clipboard-write' | 'cross-origin-isolated' | 'direct-sockets' | 'display-capture' | 'document-domain' | 'encrypted-media' | 'execution-while-out-of-viewport' | 'execution-while-not-rendered' | 'focus-without-user-activation' | 'fullscreen' | 'frobulate' | 'gamepad' | 'geolocation' | 'gyroscope' | 'hid' | 'idle-detection' | 'interest-cohort' | 'keyboard-map' | 'magnetometer' | 'microphone' | 'midi' | 'otp-credentials' | 'payment' | 'picture-in-picture' | 'publickey-credentials-get' | 'screen-wake-lock' | 'serial' | 'shared-autofill' | 'storage-access-api' | 'sync-xhr' | 'trust-token-redemption' | 'usb' | 'vertical-scroll' | 'web-share' | 'window-placement' | 'xr-spatial-tracking'; /** * Reason for a permissions policy feature to be disabled. */ export type PermissionsPolicyBlockReason = 'Header' | 'IframeAttribute'; export interface PermissionsPolicyBlockLocator { frameId: FrameId; blockReason: PermissionsPolicyBlockReason; } export interface PermissionsPolicyFeatureState { feature: PermissionsPolicyFeature; allowed: boolean; locator?: PermissionsPolicyBlockLocator; } /** * Origin Trial(https://www.chromium.org/blink/origin-trials) support. * Status for an Origin Trial token. */ export type OriginTrialTokenStatus = | 'Success' | 'NotSupported' | 'Insecure' | 'Expired' | 'WrongOrigin' | 'InvalidSignature' | 'Malformed' | 'WrongVersion' | 'FeatureDisabled' | 'TokenDisabled' | 'FeatureDisabledForUser' | 'UnknownTrial'; /** * Status for an Origin Trial. */ export type OriginTrialStatus = | 'Enabled' | 'ValidTokenNotProvided' | 'OSNotSupported' | 'TrialNotAllowed'; export type OriginTrialUsageRestriction = 'None' | 'Subset'; export interface OriginTrialToken { origin: string; matchSubDomains: boolean; trialName: string; expiryTime: Network.TimeSinceEpoch; isThirdParty: boolean; usageRestriction: OriginTrialUsageRestriction; } export interface OriginTrialTokenWithStatus { rawTokenText: string; /** * `parsedToken` is present only when the token is extractable and * parsable. */ parsedToken?: OriginTrialToken; status: OriginTrialTokenStatus; } export interface OriginTrial { trialName: string; status: OriginTrialStatus; tokensWithStatus: OriginTrialTokenWithStatus[]; } /** * Information about the Frame on the page. */ export interface Frame { /** * Frame unique identifier. */ id: FrameId; /** * Parent frame identifier. */ parentId?: FrameId; /** * Identifier of the loader associated with this frame. */ loaderId: Network.LoaderId; /** * Frame's name as specified in the tag. */ name?: string; /** * Frame document's URL without fragment. */ url: string; /** * Frame document's URL fragment including the '#'. */ urlFragment?: string; /** * Frame document's registered domain, taking the public suffixes list into account. * Extracted from the Frame's url. * Example URLs: http://www.google.com/file.html -> "google.com" * http://a.b.co.uk/file.html -> "b.co.uk" */ domainAndRegistry: string; /** * Frame document's security origin. */ securityOrigin: string; /** * Frame document's mimeType as determined by the browser. */ mimeType: string; /** * If the frame failed to load, this contains the URL that could not be loaded. Note that unlike url above, this URL may contain a fragment. */ unreachableUrl?: string; /** * Indicates whether this frame was tagged as an ad and why. */ adFrameStatus?: AdFrameStatus; /** * Indicates whether the main document is a secure context and explains why that is the case. */ secureContextType: SecureContextType; /** * Indicates whether this is a cross origin isolated context. */ crossOriginIsolatedContextType: CrossOriginIsolatedContextType; /** * Indicated which gated APIs / features are available. */ gatedAPIFeatures: GatedAPIFeatures[]; } /** * Information about the Resource on the page. */ export interface FrameResource { /** * Resource URL. */ url: string; /** * Type of this resource. */ type: Network.ResourceType; /** * Resource mimeType as determined by the browser. */ mimeType: string; /** * last-modified timestamp as reported by server. */ lastModified?: Network.TimeSinceEpoch; /** * Resource content size. */ contentSize?: number; /** * True if the resource failed to load. */ failed?: boolean; /** * True if the resource was canceled during loading. */ canceled?: boolean; } /** * Information about the Frame hierarchy along with their cached resources. */ export interface FrameResourceTree { /** * Frame information for this tree item. */ frame: Frame; /** * Child frames. */ childFrames?: FrameResourceTree[]; /** * Information about frame resources. */ resources: FrameResource[]; } /** * Information about the Frame hierarchy. */ export interface FrameTree { /** * Frame information for this tree item. */ frame: Frame; /** * Child frames. */ childFrames?: FrameTree[]; } /** * Unique script identifier. */ export type ScriptIdentifier = string; /** * Transition type. */ export type TransitionType = | 'link' | 'typed' | 'address_bar' | 'auto_bookmark' | 'auto_subframe' | 'manual_subframe' | 'generated' | 'auto_toplevel' | 'form_submit' | 'reload' | 'keyword' | 'keyword_generated' | 'other'; /** * Navigation history entry. */ export interface NavigationEntry { /** * Unique id of the navigation history entry. */ id: integer; /** * URL of the navigation history entry. */ url: string; /** * URL that the user typed in the url bar. */ userTypedURL: string; /** * Title of the navigation history entry. */ title: string; /** * Transition type. */ transitionType: TransitionType; } /** * Screencast frame metadata. */ export interface ScreencastFrameMetadata { /** * Top offset in DIP. */ offsetTop: number; /** * Page scale factor. */ pageScaleFactor: number; /** * Device screen width in DIP. */ deviceWidth: number; /** * Device screen height in DIP. */ deviceHeight: number; /** * Position of horizontal scroll in CSS pixels. */ scrollOffsetX: number; /** * Position of vertical scroll in CSS pixels. */ scrollOffsetY: number; /** * Frame swap timestamp. */ timestamp?: Network.TimeSinceEpoch; } /** * Javascript dialog type. */ export type DialogType = 'alert' | 'confirm' | 'prompt' | 'beforeunload'; /** * Error while paring app manifest. */ export interface AppManifestError { /** * Error message. */ message: string; /** * If criticial, this is a non-recoverable parse error. */ critical: integer; /** * Error line. */ line: integer; /** * Error column. */ column: integer; } /** * Parsed app manifest properties. */ export interface AppManifestParsedProperties { /** * Computed scope value */ scope: string; } /** * Layout viewport position and dimensions. */ export interface LayoutViewport { /** * Horizontal offset relative to the document (CSS pixels). */ pageX: integer; /** * Vertical offset relative to the document (CSS pixels). */ pageY: integer; /** * Width (CSS pixels), excludes scrollbar if present. */ clientWidth: integer; /** * Height (CSS pixels), excludes scrollbar if present. */ clientHeight: integer; } /** * Visual viewport position, dimensions, and scale. */ export interface VisualViewport { /** * Horizontal offset relative to the layout viewport (CSS pixels). */ offsetX: number; /** * Vertical offset relative to the layout viewport (CSS pixels). */ offsetY: number; /** * Horizontal offset relative to the document (CSS pixels). */ pageX: number; /** * Vertical offset relative to the document (CSS pixels). */ pageY: number; /** * Width (CSS pixels), excludes scrollbar if present. */ clientWidth: number; /** * Height (CSS pixels), excludes scrollbar if present. */ clientHeight: number; /** * Scale relative to the ideal viewport (size at width=device-width). */ scale: number; /** * Page zoom factor (CSS to device independent pixels ratio). */ zoom?: number; } /** * Viewport for capturing screenshot. */ export interface Viewport { /** * X offset in device independent pixels (dip). */ x: number; /** * Y offset in device independent pixels (dip). */ y: number; /** * Rectangle width in device independent pixels (dip). */ width: number; /** * Rectangle height in device independent pixels (dip). */ height: number; /** * Page scale factor. */ scale: number; } /** * Generic font families collection. */ export interface FontFamilies { /** * The standard font-family. */ standard?: string; /** * The fixed font-family. */ fixed?: string; /** * The serif font-family. */ serif?: string; /** * The sansSerif font-family. */ sansSerif?: string; /** * The cursive font-family. */ cursive?: string; /** * The fantasy font-family. */ fantasy?: string; /** * The pictograph font-family. */ pictograph?: string; } /** * Default font sizes. */ export interface FontSizes { /** * Default standard font size. */ standard?: integer; /** * Default fixed font size. */ fixed?: integer; } export type ClientNavigationReason = | 'formSubmissionGet' | 'formSubmissionPost' | 'httpHeaderRefresh' | 'scriptInitiated' | 'metaTagRefresh' | 'pageBlockInterstitial' | 'reload' | 'anchorClick'; export type ClientNavigationDisposition = 'currentTab' | 'newTab' | 'newWindow' | 'download'; export interface InstallabilityErrorArgument { /** * Argument name (e.g. name:'minimum-icon-size-in-pixels'). */ name: string; /** * Argument value (e.g. value:'64'). */ value: string; } /** * The installability error */ export interface InstallabilityError { /** * The error id (e.g. 'manifest-missing-suitable-icon'). */ errorId: string; /** * The list of error arguments (e.g. {name:'minimum-icon-size-in-pixels', value:'64'}). */ errorArguments: InstallabilityErrorArgument[]; } /** * The referring-policy used for the navigation. */ export type ReferrerPolicy = | 'noReferrer' | 'noReferrerWhenDowngrade' | 'origin' | 'originWhenCrossOrigin' | 'sameOrigin' | 'strictOrigin' | 'strictOriginWhenCrossOrigin' | 'unsafeUrl'; /** * Per-script compilation cache parameters for `Page.produceCompilationCache` */ export interface CompilationCacheParams { /** * The URL of the script to produce a compilation cache entry for. */ url: string; /** * A hint to the backend whether eager compilation is recommended. * (the actual compilation mode used is upon backend discretion). */ eager?: boolean; } /** * The type of a frameNavigated event. */ export type NavigationType = 'Navigation' | 'BackForwardCacheRestore'; /** * List of not restored reasons for back-forward cache. */ export type BackForwardCacheNotRestoredReason = | 'NotMainFrame' | 'BackForwardCacheDisabled' | 'RelatedActiveContentsExist' | 'HTTPStatusNotOK' | 'SchemeNotHTTPOrHTTPS' | 'Loading' | 'WasGrantedMediaAccess' | 'DisableForRenderFrameHostCalled' | 'DomainNotAllowed' | 'HTTPMethodNotGET' | 'SubframeIsNavigating' | 'Timeout' | 'CacheLimit' | 'JavaScriptExecution' | 'RendererProcessKilled' | 'RendererProcessCrashed' | 'GrantedMediaStreamAccess' | 'SchedulerTrackedFeatureUsed' | 'ConflictingBrowsingInstance' | 'CacheFlushed' | 'ServiceWorkerVersionActivation' | 'SessionRestored' | 'ServiceWorkerPostMessage' | 'EnteredBackForwardCacheBeforeServiceWorkerHostAdded' | 'RenderFrameHostReused_SameSite' | 'RenderFrameHostReused_CrossSite' | 'ServiceWorkerClaim' | 'IgnoreEventAndEvict' | 'HaveInnerContents' | 'TimeoutPuttingInCache' | 'BackForwardCacheDisabledByLowMemory' | 'BackForwardCacheDisabledByCommandLine' | 'NetworkRequestDatapipeDrainedAsBytesConsumer' | 'NetworkRequestRedirected' | 'NetworkRequestTimeout' | 'NetworkExceedsBufferLimit' | 'NavigationCancelledWhileRestoring' | 'NotMostRecentNavigationEntry' | 'BackForwardCacheDisabledForPrerender' | 'UserAgentOverrideDiffers' | 'ForegroundCacheLimit' | 'BrowsingInstanceNotSwapped' | 'BackForwardCacheDisabledForDelegate' | 'OptInUnloadHeaderNotPresent' | 'UnloadHandlerExistsInMainFrame' | 'UnloadHandlerExistsInSubFrame' | 'ServiceWorkerUnregistration' | 'CacheControlNoStore' | 'CacheControlNoStoreCookieModified' | 'CacheControlNoStoreHTTPOnlyCookieModified' | 'NoResponseHead' | 'Unknown' | 'ActivationNavigationsDisallowedForBug1234857' | 'WebSocket' | 'WebTransport' | 'WebRTC' | 'MainResourceHasCacheControlNoStore' | 'MainResourceHasCacheControlNoCache' | 'SubresourceHasCacheControlNoStore' | 'SubresourceHasCacheControlNoCache' | 'ContainsPlugins' | 'DocumentLoaded' | 'DedicatedWorkerOrWorklet' | 'OutstandingNetworkRequestOthers' | 'OutstandingIndexedDBTransaction' | 'RequestedNotificationsPermission' | 'RequestedMIDIPermission' | 'RequestedAudioCapturePermission' | 'RequestedVideoCapturePermission' | 'RequestedBackForwardCacheBlockedSensors' | 'RequestedBackgroundWorkPermission' | 'BroadcastChannel' | 'IndexedDBConnection' | 'WebXR' | 'SharedWorker' | 'WebLocks' | 'WebHID' | 'WebShare' | 'RequestedStorageAccessGrant' | 'WebNfc' | 'OutstandingNetworkRequestFetch' | 'OutstandingNetworkRequestXHR' | 'AppBanner' | 'Printing' | 'WebDatabase' | 'PictureInPicture' | 'Portal' | 'SpeechRecognizer' | 'IdleManager' | 'PaymentManager' | 'SpeechSynthesis' | 'KeyboardLock' | 'WebOTPService' | 'OutstandingNetworkRequestDirectSocket' | 'InjectedJavascript' | 'InjectedStyleSheet' | 'Dummy' | 'ContentSecurityHandler' | 'ContentWebAuthenticationAPI' | 'ContentFileChooser' | 'ContentSerial' | 'ContentFileSystemAccess' | 'ContentMediaDevicesDispatcherHost' | 'ContentWebBluetooth' | 'ContentWebUSB' | 'ContentMediaSession' | 'ContentMediaSessionService' | 'EmbedderPopupBlockerTabHelper' | 'EmbedderSafeBrowsingTriggeredPopupBlocker' | 'EmbedderSafeBrowsingThreatDetails' | 'EmbedderAppBannerManager' | 'EmbedderDomDistillerViewerSource' | 'EmbedderDomDistillerSelfDeletingRequestDelegate' | 'EmbedderOomInterventionTabHelper' | 'EmbedderOfflinePage' | 'EmbedderChromePasswordManagerClientBindCredentialManager' | 'EmbedderPermissionRequestManager' | 'EmbedderModalDialog' | 'EmbedderExtensions' | 'EmbedderExtensionMessaging' | 'EmbedderExtensionMessagingForOpenPort' | 'EmbedderExtensionSentMessageToCachedFrame'; /** * Types of not restored reasons for back-forward cache. */ export type BackForwardCacheNotRestoredReasonType = | 'SupportPending' | 'PageSupportNeeded' | 'Circumstantial'; export interface BackForwardCacheNotRestoredExplanation { /** * Type of the reason */ type: BackForwardCacheNotRestoredReasonType; /** * Not restored reason */ reason: BackForwardCacheNotRestoredReason; } } /** * Methods and events of the 'Performance' domain. */ export interface PerformanceApi { /** * Disable collecting and reporting metrics. */ disable(params: Performance.DisableParams): Promise<Performance.DisableResult | undefined>; /** * Enable collecting and reporting metrics. */ enable(params: Performance.EnableParams): Promise<Performance.EnableResult | undefined>; /** * Sets time domain to use for collecting and reporting duration metrics. * Note that this must be called before enabling metrics collection. Calling * this method while metrics collection is enabled returns an error. * @deprecated */ setTimeDomain( params: Performance.SetTimeDomainParams, ): Promise<Performance.SetTimeDomainResult | undefined>; /** * Retrieve current values of run-time metrics. */ getMetrics( params: Performance.GetMetricsParams, ): Promise<Performance.GetMetricsResult | undefined>; /** * Current values of the metrics. */ on(event: 'metrics', listener: (event: Performance.MetricsEvent) => void): IDisposable; } /** * Types of the 'Performance' domain. */ export namespace Performance { /** * Parameters of the 'Performance.disable' method. */ export interface DisableParams {} /** * Return value of the 'Performance.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Performance.enable' method. */ export interface EnableParams { /** * Time domain to use for collecting and reporting duration metrics. */ timeDomain?: 'timeTicks' | 'threadTicks'; } /** * Return value of the 'Performance.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Performance.setTimeDomain' method. */ export interface SetTimeDomainParams { /** * Time domain */ timeDomain: 'timeTicks' | 'threadTicks'; } /** * Return value of the 'Performance.setTimeDomain' method. */ export interface SetTimeDomainResult {} /** * Parameters of the 'Performance.getMetrics' method. */ export interface GetMetricsParams {} /** * Return value of the 'Performance.getMetrics' method. */ export interface GetMetricsResult { /** * Current values for run-time metrics. */ metrics: Metric[]; } /** * Parameters of the 'Performance.metrics' event. */ export interface MetricsEvent { /** * Current values of the metrics. */ metrics: Metric[]; /** * Timestamp title. */ title: string; } /** * Run-time execution metric. */ export interface Metric { /** * Metric name. */ name: string; /** * Metric value. */ value: number; } } /** * Methods and events of the 'PerformanceTimeline' domain. */ export interface PerformanceTimelineApi { /** * Previously buffered events would be reported before method returns. * See also: timelineEventAdded */ enable( params: PerformanceTimeline.EnableParams, ): Promise<PerformanceTimeline.EnableResult | undefined>; /** * Sent when a performance timeline event is added. See reportPerformanceTimeline method. */ on( event: 'timelineEventAdded', listener: (event: PerformanceTimeline.TimelineEventAddedEvent) => void, ): IDisposable; } /** * Types of the 'PerformanceTimeline' domain. */ export namespace PerformanceTimeline { /** * Parameters of the 'PerformanceTimeline.enable' method. */ export interface EnableParams { /** * The types of event to report, as specified in * https://w3c.github.io/performance-timeline/#dom-performanceentry-entrytype * The specified filter overrides any previous filters, passing empty * filter disables recording. * Note that not all types exposed to the web platform are currently supported. */ eventTypes: string[]; } /** * Return value of the 'PerformanceTimeline.enable' method. */ export interface EnableResult {} /** * Parameters of the 'PerformanceTimeline.timelineEventAdded' event. */ export interface TimelineEventAddedEvent { event: TimelineEvent; } /** * See https://github.com/WICG/LargestContentfulPaint and largest_contentful_paint.idl */ export interface LargestContentfulPaint { renderTime: Network.TimeSinceEpoch; loadTime: Network.TimeSinceEpoch; /** * The number of pixels being painted. */ size: number; /** * The id attribute of the element, if available. */ elementId?: string; /** * The URL of the image (may be trimmed). */ url?: string; nodeId?: DOM.BackendNodeId; } export interface LayoutShiftAttribution { previousRect: DOM.Rect; currentRect: DOM.Rect; nodeId?: DOM.BackendNodeId; } /** * See https://wicg.github.io/layout-instability/#sec-layout-shift and layout_shift.idl */ export interface LayoutShift { /** * Score increment produced by this event. */ value: number; hadRecentInput: boolean; lastInputTime: Network.TimeSinceEpoch; sources: LayoutShiftAttribution[]; } export interface TimelineEvent { /** * Identifies the frame that this event is related to. Empty for non-frame targets. */ frameId: Page.FrameId; /** * The event type, as specified in https://w3c.github.io/performance-timeline/#dom-performanceentry-entrytype * This determines which of the optional "details" fiedls is present. */ type: string; /** * Name may be empty depending on the type. */ name: string; /** * Time in seconds since Epoch, monotonically increasing within document lifetime. */ time: Network.TimeSinceEpoch; /** * Event duration, if applicable. */ duration?: number; lcpDetails?: LargestContentfulPaint; layoutShiftDetails?: LayoutShift; } } /** * Methods and events of the 'Profiler' domain. */ export interface ProfilerApi { disable(params: Profiler.DisableParams): Promise<Profiler.DisableResult | undefined>; enable(params: Profiler.EnableParams): Promise<Profiler.EnableResult | undefined>; /** * Collect coverage data for the current isolate. The coverage data may be incomplete due to * garbage collection. */ getBestEffortCoverage( params: Profiler.GetBestEffortCoverageParams, ): Promise<Profiler.GetBestEffortCoverageResult | undefined>; /** * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. */ setSamplingInterval( params: Profiler.SetSamplingIntervalParams, ): Promise<Profiler.SetSamplingIntervalResult | undefined>; start(params: Profiler.StartParams): Promise<Profiler.StartResult | undefined>; /** * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code * coverage may be incomplete. Enabling prevents running optimized code and resets execution * counters. */ startPreciseCoverage( params: Profiler.StartPreciseCoverageParams, ): Promise<Profiler.StartPreciseCoverageResult | undefined>; /** * Enable type profile. */ startTypeProfile( params: Profiler.StartTypeProfileParams, ): Promise<Profiler.StartTypeProfileResult | undefined>; stop(params: Profiler.StopParams): Promise<Profiler.StopResult | undefined>; /** * Disable precise code coverage. Disabling releases unnecessary execution count records and allows * executing optimized code. */ stopPreciseCoverage( params: Profiler.StopPreciseCoverageParams, ): Promise<Profiler.StopPreciseCoverageResult | undefined>; /** * Disable type profile. Disabling releases type profile data collected so far. */ stopTypeProfile( params: Profiler.StopTypeProfileParams, ): Promise<Profiler.StopTypeProfileResult | undefined>; /** * Collect coverage data for the current isolate, and resets execution counters. Precise code * coverage needs to have started. */ takePreciseCoverage( params: Profiler.TakePreciseCoverageParams, ): Promise<Profiler.TakePreciseCoverageResult | undefined>; /** * Collect type profile. */ takeTypeProfile( params: Profiler.TakeTypeProfileParams, ): Promise<Profiler.TakeTypeProfileResult | undefined>; on( event: 'consoleProfileFinished', listener: (event: Profiler.ConsoleProfileFinishedEvent) => void, ): IDisposable; /** * Sent when new profile recording is started using console.profile() call. */ on( event: 'consoleProfileStarted', listener: (event: Profiler.ConsoleProfileStartedEvent) => void, ): IDisposable; /** * Reports coverage delta since the last poll (either from an event like this, or from * `takePreciseCoverage` for the current isolate. May only be sent if precise code * coverage has been started. This event can be trigged by the embedder to, for example, * trigger collection of coverage data immediately at a certain point in time. */ on( event: 'preciseCoverageDeltaUpdate', listener: (event: Profiler.PreciseCoverageDeltaUpdateEvent) => void, ): IDisposable; } /** * Types of the 'Profiler' domain. */ export namespace Profiler { /** * Parameters of the 'Profiler.disable' method. */ export interface DisableParams {} /** * Return value of the 'Profiler.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Profiler.enable' method. */ export interface EnableParams {} /** * Return value of the 'Profiler.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Profiler.getBestEffortCoverage' method. */ export interface GetBestEffortCoverageParams {} /** * Return value of the 'Profiler.getBestEffortCoverage' method. */ export interface GetBestEffortCoverageResult { /** * Coverage data for the current isolate. */ result: ScriptCoverage[]; } /** * Parameters of the 'Profiler.setSamplingInterval' method. */ export interface SetSamplingIntervalParams { /** * New sampling interval in microseconds. */ interval: integer; } /** * Return value of the 'Profiler.setSamplingInterval' method. */ export interface SetSamplingIntervalResult {} /** * Parameters of the 'Profiler.start' method. */ export interface StartParams {} /** * Return value of the 'Profiler.start' method. */ export interface StartResult {} /** * Parameters of the 'Profiler.startPreciseCoverage' method. */ export interface StartPreciseCoverageParams { /** * Collect accurate call counts beyond simple 'covered' or 'not covered'. */ callCount?: boolean; /** * Collect block-based coverage. */ detailed?: boolean; /** * Allow the backend to send updates on its own initiative */ allowTriggeredUpdates?: boolean; } /** * Return value of the 'Profiler.startPreciseCoverage' method. */ export interface StartPreciseCoverageResult { /** * Monotonically increasing time (in seconds) when the coverage update was taken in the backend. */ timestamp: number; } /** * Parameters of the 'Profiler.startTypeProfile' method. */ export interface StartTypeProfileParams {} /** * Return value of the 'Profiler.startTypeProfile' method. */ export interface StartTypeProfileResult {} /** * Parameters of the 'Profiler.stop' method. */ export interface StopParams {} /** * Return value of the 'Profiler.stop' method. */ export interface StopResult { /** * Recorded profile. */ profile: Profile; } /** * Parameters of the 'Profiler.stopPreciseCoverage' method. */ export interface StopPreciseCoverageParams {} /** * Return value of the 'Profiler.stopPreciseCoverage' method. */ export interface StopPreciseCoverageResult {} /** * Parameters of the 'Profiler.stopTypeProfile' method. */ export interface StopTypeProfileParams {} /** * Return value of the 'Profiler.stopTypeProfile' method. */ export interface StopTypeProfileResult {} /** * Parameters of the 'Profiler.takePreciseCoverage' method. */ export interface TakePreciseCoverageParams {} /** * Return value of the 'Profiler.takePreciseCoverage' method. */ export interface TakePreciseCoverageResult { /** * Coverage data for the current isolate. */ result: ScriptCoverage[]; /** * Monotonically increasing time (in seconds) when the coverage update was taken in the backend. */ timestamp: number; } /** * Parameters of the 'Profiler.takeTypeProfile' method. */ export interface TakeTypeProfileParams {} /** * Return value of the 'Profiler.takeTypeProfile' method. */ export interface TakeTypeProfileResult { /** * Type profile for all scripts since startTypeProfile() was turned on. */ result: ScriptTypeProfile[]; } /** * Parameters of the 'Profiler.consoleProfileFinished' event. */ export interface ConsoleProfileFinishedEvent { id: string; /** * Location of console.profileEnd(). */ location: Debugger.Location; profile: Profile; /** * Profile title passed as an argument to console.profile(). */ title?: string; } /** * Parameters of the 'Profiler.consoleProfileStarted' event. */ export interface ConsoleProfileStartedEvent { id: string; /** * Location of console.profile(). */ location: Debugger.Location; /** * Profile title passed as an argument to console.profile(). */ title?: string; } /** * Parameters of the 'Profiler.preciseCoverageDeltaUpdate' event. */ export interface PreciseCoverageDeltaUpdateEvent { /** * Monotonically increasing time (in seconds) when the coverage update was taken in the backend. */ timestamp: number; /** * Identifier for distinguishing coverage events. */ occasion: string; /** * Coverage data for the current isolate. */ result: ScriptCoverage[]; } /** * Profile node. Holds callsite information, execution statistics and child nodes. */ export interface ProfileNode { /** * Unique id of the node. */ id: integer; /** * Function location. */ callFrame: Runtime.CallFrame; /** * Number of samples where this node was on top of the call stack. */ hitCount?: integer; /** * Child node ids. */ children?: integer[]; /** * The reason of being not optimized. The function may be deoptimized or marked as don't * optimize. */ deoptReason?: string; /** * An array of source position ticks. */ positionTicks?: PositionTickInfo[]; } /** * Profile. */ export interface Profile { /** * The list of profile nodes. First item is the root node. */ nodes: ProfileNode[]; /** * Profiling start timestamp in microseconds. */ startTime: number; /** * Profiling end timestamp in microseconds. */ endTime: number; /** * Ids of samples top nodes. */ samples?: integer[]; /** * Time intervals between adjacent samples in microseconds. The first delta is relative to the * profile startTime. */ timeDeltas?: integer[]; } /** * Specifies a number of samples attributed to a certain source position. */ export interface PositionTickInfo { /** * Source line number (1-based). */ line: integer; /** * Number of samples attributed to the source line. */ ticks: integer; } /** * Coverage data for a source range. */ export interface CoverageRange { /** * JavaScript script source offset for the range start. */ startOffset: integer; /** * JavaScript script source offset for the range end. */ endOffset: integer; /** * Collected execution count of the source range. */ count: integer; } /** * Coverage data for a JavaScript function. */ export interface FunctionCoverage { /** * JavaScript function name. */ functionName: string; /** * Source ranges inside the function with coverage data. */ ranges: CoverageRange[]; /** * Whether coverage data for this function has block granularity. */ isBlockCoverage: boolean; } /** * Coverage data for a JavaScript script. */ export interface ScriptCoverage { /** * JavaScript script id. */ scriptId: Runtime.ScriptId; /** * JavaScript script name or url. */ url: string; /** * Functions contained in the script that has coverage data. */ functions: FunctionCoverage[]; } /** * Describes a type collected during runtime. */ export interface TypeObject { /** * Name of a type collected with type profiling. */ name: string; } /** * Source offset and types for a parameter or return value. */ export interface TypeProfileEntry { /** * Source offset of the parameter or end of function for return values. */ offset: integer; /** * The types for this parameter or return value. */ types: TypeObject[]; } /** * Type profile data collected during runtime for a JavaScript script. */ export interface ScriptTypeProfile { /** * JavaScript script id. */ scriptId: Runtime.ScriptId; /** * JavaScript script name or url. */ url: string; /** * Type profile entries for parameters and return values of the functions in the script. */ entries: TypeProfileEntry[]; } } /** * Methods and events of the 'Runtime' domain. */ export interface RuntimeApi { /** * Add handler to promise with given promise object id. */ awaitPromise( params: Runtime.AwaitPromiseParams, ): Promise<Runtime.AwaitPromiseResult | undefined>; /** * Calls function with given declaration on the given object. Object group of the result is * inherited from the target object. */ callFunctionOn( params: Runtime.CallFunctionOnParams, ): Promise<Runtime.CallFunctionOnResult | undefined>; /** * Compiles expression. */ compileScript( params: Runtime.CompileScriptParams, ): Promise<Runtime.CompileScriptResult | undefined>; /** * Disables reporting of execution contexts creation. */ disable(params: Runtime.DisableParams): Promise<Runtime.DisableResult | undefined>; /** * Discards collected exceptions and console API calls. */ discardConsoleEntries( params: Runtime.DiscardConsoleEntriesParams, ): Promise<Runtime.DiscardConsoleEntriesResult | undefined>; /** * Enables reporting of execution contexts creation by means of `executionContextCreated` event. * When the reporting gets enabled the event will be sent immediately for each existing execution * context. */ enable(params: Runtime.EnableParams): Promise<Runtime.EnableResult | undefined>; /** * Evaluates expression on global object. */ evaluate(params: Runtime.EvaluateParams): Promise<Runtime.EvaluateResult | undefined>; /** * Returns the isolate id. */ getIsolateId( params: Runtime.GetIsolateIdParams, ): Promise<Runtime.GetIsolateIdResult | undefined>; /** * Returns the JavaScript heap usage. * It is the total usage of the corresponding isolate not scoped to a particular Runtime. */ getHeapUsage( params: Runtime.GetHeapUsageParams, ): Promise<Runtime.GetHeapUsageResult | undefined>; /** * Returns properties of a given object. Object group of the result is inherited from the target * object. */ getProperties( params: Runtime.GetPropertiesParams, ): Promise<Runtime.GetPropertiesResult | undefined>; /** * Returns all let, const and class variables from global scope. */ globalLexicalScopeNames( params: Runtime.GlobalLexicalScopeNamesParams, ): Promise<Runtime.GlobalLexicalScopeNamesResult | undefined>; queryObjects( params: Runtime.QueryObjectsParams, ): Promise<Runtime.QueryObjectsResult | undefined>; /** * Releases remote object with given id. */ releaseObject( params: Runtime.ReleaseObjectParams, ): Promise<Runtime.ReleaseObjectResult | undefined>; /** * Releases all remote objects that belong to a given group. */ releaseObjectGroup( params: Runtime.ReleaseObjectGroupParams, ): Promise<Runtime.ReleaseObjectGroupResult | undefined>; /** * Tells inspected instance to run if it was waiting for debugger to attach. */ runIfWaitingForDebugger( params: Runtime.RunIfWaitingForDebuggerParams, ): Promise<Runtime.RunIfWaitingForDebuggerResult | undefined>; /** * Runs script with given id in a given context. */ runScript(params: Runtime.RunScriptParams): Promise<Runtime.RunScriptResult | undefined>; /** * Enables or disables async call stacks tracking. */ setAsyncCallStackDepth( params: Runtime.SetAsyncCallStackDepthParams, ): Promise<Runtime.SetAsyncCallStackDepthResult | undefined>; setCustomObjectFormatterEnabled( params: Runtime.SetCustomObjectFormatterEnabledParams, ): Promise<Runtime.SetCustomObjectFormatterEnabledResult | undefined>; setMaxCallStackSizeToCapture( params: Runtime.SetMaxCallStackSizeToCaptureParams, ): Promise<Runtime.SetMaxCallStackSizeToCaptureResult | undefined>; /** * Terminate current or next JavaScript execution. * Will cancel the termination when the outer-most script execution ends. */ terminateExecution( params: Runtime.TerminateExecutionParams, ): Promise<Runtime.TerminateExecutionResult | undefined>; /** * If executionContextId is empty, adds binding with the given name on the * global objects of all inspected contexts, including those created later, * bindings survive reloads. * Binding function takes exactly one argument, this argument should be string, * in case of any other input, function throws an exception. * Each binding function call produces Runtime.bindingCalled notification. */ addBinding(params: Runtime.AddBindingParams): Promise<Runtime.AddBindingResult | undefined>; /** * This method does not remove binding function from global object but * unsubscribes current runtime agent from Runtime.bindingCalled notifications. */ removeBinding( params: Runtime.RemoveBindingParams, ): Promise<Runtime.RemoveBindingResult | undefined>; /** * Notification is issued every time when binding is called. */ on(event: 'bindingCalled', listener: (event: Runtime.BindingCalledEvent) => void): IDisposable; /** * Issued when console API was called. */ on( event: 'consoleAPICalled', listener: (event: Runtime.ConsoleAPICalledEvent) => void, ): IDisposable; /** * Issued when unhandled exception was revoked. */ on( event: 'exceptionRevoked', listener: (event: Runtime.ExceptionRevokedEvent) => void, ): IDisposable; /** * Issued when exception was thrown and unhandled. */ on( event: 'exceptionThrown', listener: (event: Runtime.ExceptionThrownEvent) => void, ): IDisposable; /** * Issued when new execution context is created. */ on( event: 'executionContextCreated', listener: (event: Runtime.ExecutionContextCreatedEvent) => void, ): IDisposable; /** * Issued when execution context is destroyed. */ on( event: 'executionContextDestroyed', listener: (event: Runtime.ExecutionContextDestroyedEvent) => void, ): IDisposable; /** * Issued when all executionContexts were cleared in browser */ on( event: 'executionContextsCleared', listener: (event: Runtime.ExecutionContextsClearedEvent) => void, ): IDisposable; /** * Issued when object should be inspected (for example, as a result of inspect() command line API * call). */ on( event: 'inspectRequested', listener: (event: Runtime.InspectRequestedEvent) => void, ): IDisposable; } /** * Types of the 'Runtime' domain. */ export namespace Runtime { /** * Parameters of the 'Runtime.awaitPromise' method. */ export interface AwaitPromiseParams { /** * Identifier of the promise. */ promiseObjectId: RemoteObjectId; /** * Whether the result is expected to be a JSON object that should be sent by value. */ returnByValue?: boolean; /** * Whether preview should be generated for the result. */ generatePreview?: boolean; } /** * Return value of the 'Runtime.awaitPromise' method. */ export interface AwaitPromiseResult { /** * Promise result. Will contain rejected value if promise was rejected. */ result: RemoteObject; /** * Exception details if stack strace is available. */ exceptionDetails?: ExceptionDetails; } /** * Parameters of the 'Runtime.callFunctionOn' method. */ export interface CallFunctionOnParams { /** * Declaration of the function to call. */ functionDeclaration: string; /** * Identifier of the object to call function on. Either objectId or executionContextId should * be specified. */ objectId?: RemoteObjectId; /** * Call arguments. All call arguments must belong to the same JavaScript world as the target * object. */ arguments?: CallArgument[]; /** * In silent mode exceptions thrown during evaluation are not reported and do not pause * execution. Overrides `setPauseOnException` state. */ silent?: boolean; /** * Whether the result is expected to be a JSON object which should be sent by value. */ returnByValue?: boolean; /** * Whether preview should be generated for the result. */ generatePreview?: boolean; /** * Whether execution should be treated as initiated by user in the UI. */ userGesture?: boolean; /** * Whether execution should `await` for resulting value and return once awaited promise is * resolved. */ awaitPromise?: boolean; /** * Specifies execution context which global object will be used to call function on. Either * executionContextId or objectId should be specified. */ executionContextId?: ExecutionContextId; /** * Symbolic group name that can be used to release multiple objects. If objectGroup is not * specified and objectId is, objectGroup will be inherited from object. */ objectGroup?: string; /** * Whether to throw an exception if side effect cannot be ruled out during evaluation. */ throwOnSideEffect?: boolean; } /** * Return value of the 'Runtime.callFunctionOn' method. */ export interface CallFunctionOnResult { /** * Call result. */ result: RemoteObject; /** * Exception details. */ exceptionDetails?: ExceptionDetails; } /** * Parameters of the 'Runtime.compileScript' method. */ export interface CompileScriptParams { /** * Expression to compile. */ expression: string; /** * Source url to be set for the script. */ sourceURL: string; /** * Specifies whether the compiled script should be persisted. */ persistScript: boolean; /** * Specifies in which execution context to perform script run. If the parameter is omitted the * evaluation will be performed in the context of the inspected page. */ executionContextId?: ExecutionContextId; } /** * Return value of the 'Runtime.compileScript' method. */ export interface CompileScriptResult { /** * Id of the script. */ scriptId?: ScriptId; /** * Exception details. */ exceptionDetails?: ExceptionDetails; } /** * Parameters of the 'Runtime.disable' method. */ export interface DisableParams {} /** * Return value of the 'Runtime.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Runtime.discardConsoleEntries' method. */ export interface DiscardConsoleEntriesParams {} /** * Return value of the 'Runtime.discardConsoleEntries' method. */ export interface DiscardConsoleEntriesResult {} /** * Parameters of the 'Runtime.enable' method. */ export interface EnableParams {} /** * Return value of the 'Runtime.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Runtime.evaluate' method. */ export interface EvaluateParams { /** * Expression to evaluate. */ expression: string; /** * Symbolic group name that can be used to release multiple objects. */ objectGroup?: string; /** * Determines whether Command Line API should be available during the evaluation. */ includeCommandLineAPI?: boolean; /** * In silent mode exceptions thrown during evaluation are not reported and do not pause * execution. Overrides `setPauseOnException` state. */ silent?: boolean; /** * Specifies in which execution context to perform evaluation. If the parameter is omitted the * evaluation will be performed in the context of the inspected page. * This is mutually exclusive with `uniqueContextId`, which offers an * alternative way to identify the execution context that is more reliable * in a multi-process environment. */ contextId?: ExecutionContextId; /** * Whether the result is expected to be a JSON object that should be sent by value. */ returnByValue?: boolean; /** * Whether preview should be generated for the result. */ generatePreview?: boolean; /** * Whether execution should be treated as initiated by user in the UI. */ userGesture?: boolean; /** * Whether execution should `await` for resulting value and return once awaited promise is * resolved. */ awaitPromise?: boolean; /** * Whether to throw an exception if side effect cannot be ruled out during evaluation. * This implies `disableBreaks` below. */ throwOnSideEffect?: boolean; /** * Terminate execution after timing out (number of milliseconds). */ timeout?: TimeDelta; /** * Disable breakpoints during execution. */ disableBreaks?: boolean; /** * Setting this flag to true enables `let` re-declaration and top-level `await`. * Note that `let` variables can only be re-declared if they originate from * `replMode` themselves. */ replMode?: boolean; /** * The Content Security Policy (CSP) for the target might block 'unsafe-eval' * which includes eval(), Function(), setTimeout() and setInterval() * when called with non-callable arguments. This flag bypasses CSP for this * evaluation and allows unsafe-eval. Defaults to true. */ allowUnsafeEvalBlockedByCSP?: boolean; /** * An alternative way to specify the execution context to evaluate in. * Compared to contextId that may be reused across processes, this is guaranteed to be * system-unique, so it can be used to prevent accidental evaluation of the expression * in context different than intended (e.g. as a result of navigation across process * boundaries). * This is mutually exclusive with `contextId`. */ uniqueContextId?: string; } /** * Return value of the 'Runtime.evaluate' method. */ export interface EvaluateResult { /** * Evaluation result. */ result: RemoteObject; /** * Exception details. */ exceptionDetails?: ExceptionDetails; } /** * Parameters of the 'Runtime.getIsolateId' method. */ export interface GetIsolateIdParams {} /** * Return value of the 'Runtime.getIsolateId' method. */ export interface GetIsolateIdResult { /** * The isolate id. */ id: string; } /** * Parameters of the 'Runtime.getHeapUsage' method. */ export interface GetHeapUsageParams {} /** * Return value of the 'Runtime.getHeapUsage' method. */ export interface GetHeapUsageResult { /** * Used heap size in bytes. */ usedSize: number; /** * Allocated heap size in bytes. */ totalSize: number; } /** * Parameters of the 'Runtime.getProperties' method. */ export interface GetPropertiesParams { /** * Identifier of the object to return properties for. */ objectId: RemoteObjectId; /** * If true, returns properties belonging only to the element itself, not to its prototype * chain. */ ownProperties?: boolean; /** * If true, returns accessor properties (with getter/setter) only; internal properties are not * returned either. */ accessorPropertiesOnly?: boolean; /** * Whether preview should be generated for the results. */ generatePreview?: boolean; /** * If true, returns non-indexed properties only. */ nonIndexedPropertiesOnly?: boolean; } /** * Return value of the 'Runtime.getProperties' method. */ export interface GetPropertiesResult { /** * Object properties. */ result: PropertyDescriptor[]; /** * Internal object properties (only of the element itself). */ internalProperties?: InternalPropertyDescriptor[]; /** * Object private properties. */ privateProperties?: PrivatePropertyDescriptor[]; /** * Exception details. */ exceptionDetails?: ExceptionDetails; } /** * Parameters of the 'Runtime.globalLexicalScopeNames' method. */ export interface GlobalLexicalScopeNamesParams { /** * Specifies in which execution context to lookup global scope variables. */ executionContextId?: ExecutionContextId; } /** * Return value of the 'Runtime.globalLexicalScopeNames' method. */ export interface GlobalLexicalScopeNamesResult { names: string[]; } /** * Parameters of the 'Runtime.queryObjects' method. */ export interface QueryObjectsParams { /** * Identifier of the prototype to return objects for. */ prototypeObjectId: RemoteObjectId; /** * Symbolic group name that can be used to release the results. */ objectGroup?: string; } /** * Return value of the 'Runtime.queryObjects' method. */ export interface QueryObjectsResult { /** * Array with objects. */ objects: RemoteObject; } /** * Parameters of the 'Runtime.releaseObject' method. */ export interface ReleaseObjectParams { /** * Identifier of the object to release. */ objectId: RemoteObjectId; } /** * Return value of the 'Runtime.releaseObject' method. */ export interface ReleaseObjectResult {} /** * Parameters of the 'Runtime.releaseObjectGroup' method. */ export interface ReleaseObjectGroupParams { /** * Symbolic object group name. */ objectGroup: string; } /** * Return value of the 'Runtime.releaseObjectGroup' method. */ export interface ReleaseObjectGroupResult {} /** * Parameters of the 'Runtime.runIfWaitingForDebugger' method. */ export interface RunIfWaitingForDebuggerParams {} /** * Return value of the 'Runtime.runIfWaitingForDebugger' method. */ export interface RunIfWaitingForDebuggerResult {} /** * Parameters of the 'Runtime.runScript' method. */ export interface RunScriptParams { /** * Id of the script to run. */ scriptId: ScriptId; /** * Specifies in which execution context to perform script run. If the parameter is omitted the * evaluation will be performed in the context of the inspected page. */ executionContextId?: ExecutionContextId; /** * Symbolic group name that can be used to release multiple objects. */ objectGroup?: string; /** * In silent mode exceptions thrown during evaluation are not reported and do not pause * execution. Overrides `setPauseOnException` state. */ silent?: boolean; /** * Determines whether Command Line API should be available during the evaluation. */ includeCommandLineAPI?: boolean; /** * Whether the result is expected to be a JSON object which should be sent by value. */ returnByValue?: boolean; /** * Whether preview should be generated for the result. */ generatePreview?: boolean; /** * Whether execution should `await` for resulting value and return once awaited promise is * resolved. */ awaitPromise?: boolean; } /** * Return value of the 'Runtime.runScript' method. */ export interface RunScriptResult { /** * Run result. */ result: RemoteObject; /** * Exception details. */ exceptionDetails?: ExceptionDetails; } /** * Parameters of the 'Runtime.setAsyncCallStackDepth' method. */ export interface SetAsyncCallStackDepthParams { /** * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async * call stacks (default). */ maxDepth: integer; } /** * Return value of the 'Runtime.setAsyncCallStackDepth' method. */ export interface SetAsyncCallStackDepthResult {} /** * Parameters of the 'Runtime.setCustomObjectFormatterEnabled' method. */ export interface SetCustomObjectFormatterEnabledParams { enabled: boolean; } /** * Return value of the 'Runtime.setCustomObjectFormatterEnabled' method. */ export interface SetCustomObjectFormatterEnabledResult {} /** * Parameters of the 'Runtime.setMaxCallStackSizeToCapture' method. */ export interface SetMaxCallStackSizeToCaptureParams { size: integer; } /** * Return value of the 'Runtime.setMaxCallStackSizeToCapture' method. */ export interface SetMaxCallStackSizeToCaptureResult {} /** * Parameters of the 'Runtime.terminateExecution' method. */ export interface TerminateExecutionParams {} /** * Return value of the 'Runtime.terminateExecution' method. */ export interface TerminateExecutionResult {} /** * Parameters of the 'Runtime.addBinding' method. */ export interface AddBindingParams { name: string; /** * If specified, the binding would only be exposed to the specified * execution context. If omitted and `executionContextName` is not set, * the binding is exposed to all execution contexts of the target. * This parameter is mutually exclusive with `executionContextName`. * Deprecated in favor of `executionContextName` due to an unclear use case * and bugs in implementation (crbug.com/1169639). `executionContextId` will be * removed in the future. * @deprecated */ executionContextId?: ExecutionContextId; /** * If specified, the binding is exposed to the executionContext with * matching name, even for contexts created after the binding is added. * See also `ExecutionContext.name` and `worldName` parameter to * `Page.addScriptToEvaluateOnNewDocument`. * This parameter is mutually exclusive with `executionContextId`. */ executionContextName?: string; } /** * Return value of the 'Runtime.addBinding' method. */ export interface AddBindingResult {} /** * Parameters of the 'Runtime.removeBinding' method. */ export interface RemoveBindingParams { name: string; } /** * Return value of the 'Runtime.removeBinding' method. */ export interface RemoveBindingResult {} /** * Parameters of the 'Runtime.bindingCalled' event. */ export interface BindingCalledEvent { name: string; payload: string; /** * Identifier of the context where the call was made. */ executionContextId: ExecutionContextId; } /** * Parameters of the 'Runtime.consoleAPICalled' event. */ export interface ConsoleAPICalledEvent { /** * Type of the call. */ type: | 'log' | 'debug' | 'info' | 'error' | 'warning' | 'dir' | 'dirxml' | 'table' | 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | 'profile' | 'profileEnd' | 'count' | 'timeEnd'; /** * Call arguments. */ args: RemoteObject[]; /** * Identifier of the context where the call was made. */ executionContextId: ExecutionContextId; /** * Call timestamp. */ timestamp: Timestamp; /** * Stack trace captured when the call was made. The async stack chain is automatically reported for * the following call types: `assert`, `error`, `trace`, `warning`. For other types the async call * chain can be retrieved using `Debugger.getStackTrace` and `stackTrace.parentId` field. */ stackTrace?: StackTrace; /** * Console context descriptor for calls on non-default console context (not console.*): * 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call * on named context. */ context?: string; } /** * Parameters of the 'Runtime.exceptionRevoked' event. */ export interface ExceptionRevokedEvent { /** * Reason describing why exception was revoked. */ reason: string; /** * The id of revoked exception, as reported in `exceptionThrown`. */ exceptionId: integer; } /** * Parameters of the 'Runtime.exceptionThrown' event. */ export interface ExceptionThrownEvent { /** * Timestamp of the exception. */ timestamp: Timestamp; exceptionDetails: ExceptionDetails; } /** * Parameters of the 'Runtime.executionContextCreated' event. */ export interface ExecutionContextCreatedEvent { /** * A newly created execution context. */ context: ExecutionContextDescription; } /** * Parameters of the 'Runtime.executionContextDestroyed' event. */ export interface ExecutionContextDestroyedEvent { /** * Id of the destroyed context */ executionContextId: ExecutionContextId; } /** * Parameters of the 'Runtime.executionContextsCleared' event. */ export interface ExecutionContextsClearedEvent {} /** * Parameters of the 'Runtime.inspectRequested' event. */ export interface InspectRequestedEvent { object: RemoteObject; hints: any; /** * Identifier of the context where the call was made. */ executionContextId?: ExecutionContextId; } /** * Unique script identifier. */ export type ScriptId = string; /** * Unique object identifier. */ export type RemoteObjectId = string; /** * Primitive value which cannot be JSON-stringified. Includes values `-0`, `NaN`, `Infinity`, * `-Infinity`, and bigint literals. */ export type UnserializableValue = string; /** * Mirror object referencing original JavaScript object. */ export interface RemoteObject { /** * Object type. */ type: | 'object' | 'function' | 'undefined' | 'string' | 'number' | 'boolean' | 'symbol' | 'bigint'; /** * Object subtype hint. Specified for `object` type values only. * NOTE: If you change anything here, make sure to also update * `subtype` in `ObjectPreview` and `PropertyPreview` below. */ subtype?: | 'array' | 'null' | 'node' | 'regexp' | 'date' | 'map' | 'set' | 'weakmap' | 'weakset' | 'iterator' | 'generator' | 'error' | 'proxy' | 'promise' | 'typedarray' | 'arraybuffer' | 'dataview' | 'webassemblymemory' | 'wasmvalue'; /** * Object class (constructor) name. Specified for `object` type values only. */ className?: string; /** * Remote object value in case of primitive values or JSON values (if it was requested). */ value?: any; /** * Primitive value which can not be JSON-stringified does not have `value`, but gets this * property. */ unserializableValue?: UnserializableValue; /** * String representation of the object. */ description?: string; /** * Unique object identifier (for non-primitive values). */ objectId?: RemoteObjectId; /** * Preview containing abbreviated property values. Specified for `object` type values only. */ preview?: ObjectPreview; customPreview?: CustomPreview; } export interface CustomPreview { /** * The JSON-stringified result of formatter.header(object, config) call. * It contains json ML array that represents RemoteObject. */ header: string; /** * If formatter returns true as a result of formatter.hasBody call then bodyGetterId will * contain RemoteObjectId for the function that returns result of formatter.body(object, config) call. * The result value is json ML array. */ bodyGetterId?: RemoteObjectId; } /** * Object containing abbreviated remote object value. */ export interface ObjectPreview { /** * Object type. */ type: | 'object' | 'function' | 'undefined' | 'string' | 'number' | 'boolean' | 'symbol' | 'bigint'; /** * Object subtype hint. Specified for `object` type values only. */ subtype?: | 'array' | 'null' | 'node' | 'regexp' | 'date' | 'map' | 'set' | 'weakmap' | 'weakset' | 'iterator' | 'generator' | 'error' | 'proxy' | 'promise' | 'typedarray' | 'arraybuffer' | 'dataview' | 'webassemblymemory' | 'wasmvalue'; /** * String representation of the object. */ description?: string; /** * True iff some of the properties or entries of the original object did not fit. */ overflow: boolean; /** * List of the properties. */ properties: PropertyPreview[]; /** * List of the entries. Specified for `map` and `set` subtype values only. */ entries?: EntryPreview[]; } export interface PropertyPreview { /** * Property name. */ name: string; /** * Object type. Accessor means that the property itself is an accessor property. */ type: | 'object' | 'function' | 'undefined' | 'string' | 'number' | 'boolean' | 'symbol' | 'accessor' | 'bigint'; /** * User-friendly property value string. */ value?: string; /** * Nested value preview. */ valuePreview?: ObjectPreview; /** * Object subtype hint. Specified for `object` type values only. */ subtype?: | 'array' | 'null' | 'node' | 'regexp' | 'date' | 'map' | 'set' | 'weakmap' | 'weakset' | 'iterator' | 'generator' | 'error' | 'proxy' | 'promise' | 'typedarray' | 'arraybuffer' | 'dataview' | 'webassemblymemory' | 'wasmvalue'; } export interface EntryPreview { /** * Preview of the key. Specified for map-like collection entries. */ key?: ObjectPreview; /** * Preview of the value. */ value: ObjectPreview; } /** * Object property descriptor. */ export interface PropertyDescriptor { /** * Property name or symbol description. */ name: string; /** * The value associated with the property. */ value?: RemoteObject; /** * True if the value associated with the property may be changed (data descriptors only). */ writable?: boolean; /** * A function which serves as a getter for the property, or `undefined` if there is no getter * (accessor descriptors only). */ get?: RemoteObject; /** * A function which serves as a setter for the property, or `undefined` if there is no setter * (accessor descriptors only). */ set?: RemoteObject; /** * True if the type of this property descriptor may be changed and if the property may be * deleted from the corresponding object. */ configurable: boolean; /** * True if this property shows up during enumeration of the properties on the corresponding * object. */ enumerable: boolean; /** * True if the result was thrown during the evaluation. */ wasThrown?: boolean; /** * True if the property is owned for the object. */ isOwn?: boolean; /** * Property symbol object, if the property is of the `symbol` type. */ symbol?: RemoteObject; } /** * Object internal property descriptor. This property isn't normally visible in JavaScript code. */ export interface InternalPropertyDescriptor { /** * Conventional property name. */ name: string; /** * The value associated with the property. */ value?: RemoteObject; } /** * Object private field descriptor. */ export interface PrivatePropertyDescriptor { /** * Private property name. */ name: string; /** * The value associated with the private property. */ value?: RemoteObject; /** * A function which serves as a getter for the private property, * or `undefined` if there is no getter (accessor descriptors only). */ get?: RemoteObject; /** * A function which serves as a setter for the private property, * or `undefined` if there is no setter (accessor descriptors only). */ set?: RemoteObject; } /** * Represents function call argument. Either remote object id `objectId`, primitive `value`, * unserializable primitive value or neither of (for undefined) them should be specified. */ export interface CallArgument { /** * Primitive value or serializable javascript object. */ value?: any; /** * Primitive value which can not be JSON-stringified. */ unserializableValue?: UnserializableValue; /** * Remote object handle. */ objectId?: RemoteObjectId; } /** * Id of an execution context. */ export type ExecutionContextId = integer; /** * Description of an isolated world. */ export interface ExecutionContextDescription { /** * Unique id of the execution context. It can be used to specify in which execution context * script evaluation should be performed. */ id: ExecutionContextId; /** * Execution context origin. */ origin: string; /** * Human readable name describing given context. */ name: string; /** * A system-unique execution context identifier. Unlike the id, this is unique across * multiple processes, so can be reliably used to identify specific context while backend * performs a cross-process navigation. */ uniqueId: string; /** * Embedder-specific auxiliary data. */ auxData?: any; } /** * Detailed information about exception (or error) that was thrown during script compilation or * execution. */ export interface ExceptionDetails { /** * Exception id. */ exceptionId: integer; /** * Exception text, which should be used together with exception object when available. */ text: string; /** * Line number of the exception location (0-based). */ lineNumber: integer; /** * Column number of the exception location (0-based). */ columnNumber: integer; /** * Script ID of the exception location. */ scriptId?: ScriptId; /** * URL of the exception location, to be used when the script was not reported. */ url?: string; /** * JavaScript stack trace if available. */ stackTrace?: StackTrace; /** * Exception object if available. */ exception?: RemoteObject; /** * Identifier of the context where exception happened. */ executionContextId?: ExecutionContextId; /** * Dictionary with entries of meta data that the client associated * with this exception, such as information about associated network * requests, etc. */ exceptionMetaData?: any; } /** * Number of milliseconds since epoch. */ export type Timestamp = number; /** * Number of milliseconds. */ export type TimeDelta = number; /** * Stack entry for runtime errors and assertions. */ export interface CallFrame { /** * JavaScript function name. */ functionName: string; /** * JavaScript script id. */ scriptId: ScriptId; /** * JavaScript script name or url. */ url: string; /** * JavaScript script line number (0-based). */ lineNumber: integer; /** * JavaScript script column number (0-based). */ columnNumber: integer; } /** * Call frames for assertions or error messages. */ export interface StackTrace { /** * String label of this stack trace. For async traces this may be a name of the function that * initiated the async call. */ description?: string; /** * JavaScript function name. */ callFrames: CallFrame[]; /** * Asynchronous JavaScript stack trace that preceded this stack, if available. */ parent?: StackTrace; /** * Asynchronous JavaScript stack trace that preceded this stack, if available. */ parentId?: StackTraceId; } /** * Unique identifier of current debugger. */ export type UniqueDebuggerId = string; /** * If `debuggerId` is set stack trace comes from another debugger and can be resolved there. This * allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages. */ export interface StackTraceId { id: string; debuggerId?: UniqueDebuggerId; } } /** * Methods and events of the 'Schema' domain. */ export interface SchemaApi { /** * Returns supported domains. */ getDomains(params: Schema.GetDomainsParams): Promise<Schema.GetDomainsResult | undefined>; } /** * Types of the 'Schema' domain. */ export namespace Schema { /** * Parameters of the 'Schema.getDomains' method. */ export interface GetDomainsParams {} /** * Return value of the 'Schema.getDomains' method. */ export interface GetDomainsResult { /** * List of supported domains. */ domains: Domain[]; } /** * Description of the protocol domain. */ export interface Domain { /** * Domain name. */ name: string; /** * Domain version. */ version: string; } } /** * Methods and events of the 'Security' domain. */ export interface SecurityApi { /** * Disables tracking security state changes. */ disable(params: Security.DisableParams): Promise<Security.DisableResult | undefined>; /** * Enables tracking security state changes. */ enable(params: Security.EnableParams): Promise<Security.EnableResult | undefined>; /** * Enable/disable whether all certificate errors should be ignored. */ setIgnoreCertificateErrors( params: Security.SetIgnoreCertificateErrorsParams, ): Promise<Security.SetIgnoreCertificateErrorsResult | undefined>; /** * Handles a certificate error that fired a certificateError event. * @deprecated */ handleCertificateError( params: Security.HandleCertificateErrorParams, ): Promise<Security.HandleCertificateErrorResult | undefined>; /** * Enable/disable overriding certificate errors. If enabled, all certificate error events need to * be handled by the DevTools client and should be answered with `handleCertificateError` commands. * @deprecated */ setOverrideCertificateErrors( params: Security.SetOverrideCertificateErrorsParams, ): Promise<Security.SetOverrideCertificateErrorsResult | undefined>; /** * There is a certificate error. If overriding certificate errors is enabled, then it should be * handled with the `handleCertificateError` command. Note: this event does not fire if the * certificate error has been allowed internally. Only one client per target should override * certificate errors at the same time. * @deprecated */ on( event: 'certificateError', listener: (event: Security.CertificateErrorEvent) => void, ): IDisposable; /** * The security state of the page changed. */ on( event: 'visibleSecurityStateChanged', listener: (event: Security.VisibleSecurityStateChangedEvent) => void, ): IDisposable; /** * The security state of the page changed. */ on( event: 'securityStateChanged', listener: (event: Security.SecurityStateChangedEvent) => void, ): IDisposable; } /** * Types of the 'Security' domain. */ export namespace Security { /** * Parameters of the 'Security.disable' method. */ export interface DisableParams {} /** * Return value of the 'Security.disable' method. */ export interface DisableResult {} /** * Parameters of the 'Security.enable' method. */ export interface EnableParams {} /** * Return value of the 'Security.enable' method. */ export interface EnableResult {} /** * Parameters of the 'Security.setIgnoreCertificateErrors' method. */ export interface SetIgnoreCertificateErrorsParams { /** * If true, all certificate errors will be ignored. */ ignore: boolean; } /** * Return value of the 'Security.setIgnoreCertificateErrors' method. */ export interface SetIgnoreCertificateErrorsResult {} /** * Parameters of the 'Security.handleCertificateError' method. */ export interface HandleCertificateErrorParams { /** * The ID of the event. */ eventId: integer; /** * The action to take on the certificate error. */ action: CertificateErrorAction; } /** * Return value of the 'Security.handleCertificateError' method. */ export interface HandleCertificateErrorResult {} /** * Parameters of the 'Security.setOverrideCertificateErrors' method. */ export interface SetOverrideCertificateErrorsParams { /** * If true, certificate errors will be overridden. */ override: boolean; } /** * Return value of the 'Security.setOverrideCertificateErrors' method. */ export interface SetOverrideCertificateErrorsResult {} /** * Parameters of the 'Security.certificateError' event. */ export interface CertificateErrorEvent { /** * The ID of the event. */ eventId: integer; /** * The type of the error. */ errorType: string; /** * The url that was requested. */ requestURL: string; } /** * Parameters of the 'Security.visibleSecurityStateChanged' event. */ export interface VisibleSecurityStateChangedEvent { /** * Security state information about the page. */ visibleSecurityState: VisibleSecurityState; } /** * Parameters of the 'Security.securityStateChanged' event. */ export interface SecurityStateChangedEvent { /** * Security state. */ securityState: SecurityState; /** * True if the page was loaded over cryptographic transport such as HTTPS. * @deprecated */ schemeIsCryptographic: boolean; /** * List of explanations for the security state. If the overall security state is `insecure` or * `warning`, at least one corresponding explanation should be included. */ explanations: SecurityStateExplanation[]; /** * Information about insecure content on the page. * @deprecated */ insecureContentStatus: InsecureContentStatus; /** * Overrides user-visible description of the state. */ summary?: string; } /** * An internal certificate ID value. */ export type CertificateId = integer; /** * A description of mixed content (HTTP resources on HTTPS pages), as defined by * https://www.w3.org/TR/mixed-content/#categories */ export type MixedContentType = 'blockable' | 'optionally-blockable' | 'none'; /** * The security level of a page or resource. */ export type SecurityState = | 'unknown' | 'neutral' | 'insecure' | 'secure' | 'info' | 'insecure-broken'; /** * Details about the security state of the page certificate. */ export interface CertificateSecurityState { /** * Protocol name (e.g. "TLS 1.2" or "QUIC"). */ protocol: string; /** * Key Exchange used by the connection, or the empty string if not applicable. */ keyExchange: string; /** * (EC)DH group used by the connection, if applicable. */ keyExchangeGroup?: string; /** * Cipher name. */ cipher: string; /** * TLS MAC. Note that AEAD ciphers do not have separate MACs. */ mac?: string; /** * Page certificate. */ certificate: string[]; /** * Certificate subject name. */ subjectName: string; /** * Name of the issuing CA. */ issuer: string; /** * Certificate valid from date. */ validFrom: Network.TimeSinceEpoch; /** * Certificate valid to (expiration) date */ validTo: Network.TimeSinceEpoch; /** * The highest priority network error code, if the certificate has an error. */ certificateNetworkError?: string; /** * True if the certificate uses a weak signature aglorithm. */ certificateHasWeakSignature: boolean; /** * True if the certificate has a SHA1 signature in the chain. */ certificateHasSha1Signature: boolean; /** * True if modern SSL */ modernSSL: boolean; /** * True if the connection is using an obsolete SSL protocol. */ obsoleteSslProtocol: boolean; /** * True if the connection is using an obsolete SSL key exchange. */ obsoleteSslKeyExchange: boolean; /** * True if the connection is using an obsolete SSL cipher. */ obsoleteSslCipher: boolean; /** * True if the connection is using an obsolete SSL signature. */ obsoleteSslSignature: boolean; } export type SafetyTipStatus = 'badReputation' | 'lookalike'; export interface SafetyTipInfo { /** * Describes whether the page triggers any safety tips or reputation warnings. Default is unknown. */ safetyTipStatus: SafetyTipStatus; /** * The URL the safety tip suggested ("Did you mean?"). Only filled in for lookalike matches. */ safeUrl?: string; } /** * Security state information about the page. */ export interface VisibleSecurityState { /** * The security level of the page. */ securityState: SecurityState; /** * Security state details about the page certificate. */ certificateSecurityState?: CertificateSecurityState; /** * The type of Safety Tip triggered on the page. Note that this field will be set even if the Safety Tip UI was not actually shown. */ safetyTipInfo?: SafetyTipInfo; /** * Array of security state issues ids. */ securityStateIssueIds: string[]; } /** * An explanation of an factor contributing to the security state. */ export interface SecurityStateExplanation { /** * Security state representing the severity of the factor being explained. */ securityState: SecurityState; /** * Title describing the type of factor. */ title: string; /** * Short phrase describing the type of factor. */ summary: string; /** * Full text explanation of the factor. */ description: string; /** * The type of mixed content described by the explanation. */ mixedContentType: MixedContentType; /** * Page certificate. */ certificate: string[]; /** * Recommendations to fix any issues. */ recommendations?: string[]; } /** * Information about insecure content on the page. * @deprecated */ export interface InsecureContentStatus { /** * Always false. */ ranMixedContent: boolean; /** * Always false. */ displayedMixedContent: boolean; /** * Always false. */ containedMixedForm: boolean; /** * Always false. */ ranContentWithCertErrors: boolean; /** * Always false. */ displayedContentWithCertErrors: boolean; /** * Always set to unknown. */ ranInsecureContentStyle: SecurityState; /** * Always set to unknown. */ displayedInsecureContentStyle: SecurityState; } /** * The action to take when a certificate error occurs. continue will continue processing the * request and cancel will cancel the request. */ export type CertificateErrorAction = 'continue' | 'cancel'; } /** * Methods and events of the 'ServiceWorker' domain. */ export interface ServiceWorkerApi { deliverPushMessage( params: ServiceWorker.DeliverPushMessageParams, ): Promise<ServiceWorker.DeliverPushMessageResult | undefined>; disable(params: ServiceWorker.DisableParams): Promise<ServiceWorker.DisableResult | undefined>; dispatchSyncEvent( params: ServiceWorker.DispatchSyncEventParams, ): Promise<ServiceWorker.DispatchSyncEventResult | undefined>; dispatchPeriodicSyncEvent( params: ServiceWorker.DispatchPeriodicSyncEventParams, ): Promise<ServiceWorker.DispatchPeriodicSyncEventResult | undefined>; enable(params: ServiceWorker.EnableParams): Promise<ServiceWorker.EnableResult | undefined>; inspectWorker( params: ServiceWorker.InspectWorkerParams, ): Promise<ServiceWorker.InspectWorkerResult | undefined>; setForceUpdateOnPageLoad( params: ServiceWorker.SetForceUpdateOnPageLoadParams, ): Promise<ServiceWorker.SetForceUpdateOnPageLoadResult | undefined>; skipWaiting( params: ServiceWorker.SkipWaitingParams, ): Promise<ServiceWorker.SkipWaitingResult | undefined>; startWorker( params: ServiceWorker.StartWorkerParams, ): Promise<ServiceWorker.StartWorkerResult | undefined>; stopAllWorkers( params: ServiceWorker.StopAllWorkersParams, ): Promise<ServiceWorker.StopAllWorkersResult | undefined>; stopWorker( params: ServiceWorker.StopWorkerParams, ): Promise<ServiceWorker.StopWorkerResult | undefined>; unregister( params: ServiceWorker.UnregisterParams, ): Promise<ServiceWorker.UnregisterResult | undefined>; updateRegistration( params: ServiceWorker.UpdateRegistrationParams, ): Promise<ServiceWorker.UpdateRegistrationResult | undefined>; on( event: 'workerErrorReported', listener: (event: ServiceWorker.WorkerErrorReportedEvent) => void, ): IDisposable; on( event: 'workerRegistrationUpdated', listener: (event: ServiceWorker.WorkerRegistrationUpdatedEvent) => void, ): IDisposable; on( event: 'workerVersionUpdated', listener: (event: ServiceWorker.WorkerVersionUpdatedEvent) => void, ): IDisposable; } /** * Types of the 'ServiceWorker' domain. */ export namespace ServiceWorker { /** * Parameters of the 'ServiceWorker.deliverPushMessage' method. */ export interface DeliverPushMessageParams { origin: string; registrationId: RegistrationID; data: string; } /** * Return value of the 'ServiceWorker.deliverPushMessage' method. */ export interface DeliverPushMessageResult {} /** * Parameters of the 'ServiceWorker.disable' method. */ export interface DisableParams {} /** * Return value of the 'ServiceWorker.disable' method. */ export interface DisableResult {} /** * Parameters of the 'ServiceWorker.dispatchSyncEvent' method. */ export interface DispatchSyncEventParams { origin: string; registrationId: RegistrationID; tag: string; lastChance: boolean; } /** * Return value of the 'ServiceWorker.dispatchSyncEvent' method. */ export interface DispatchSyncEventResult {} /** * Parameters of the 'ServiceWorker.dispatchPeriodicSyncEvent' method. */ export interface DispatchPeriodicSyncEventParams { origin: string; registrationId: RegistrationID; tag: string; } /** * Return value of the 'ServiceWorker.dispatchPeriodicSyncEvent' method. */ export interface DispatchPeriodicSyncEventResult {} /** * Parameters of the 'ServiceWorker.enable' method. */ export interface EnableParams {} /** * Return value of the 'ServiceWorker.enable' method. */ export interface EnableResult {} /** * Parameters of the 'ServiceWorker.inspectWorker' method. */ export interface InspectWorkerParams { versionId: string; } /** * Return value of the 'ServiceWorker.inspectWorker' method. */ export interface InspectWorkerResult {} /** * Parameters of the 'ServiceWorker.setForceUpdateOnPageLoad' method. */ export interface SetForceUpdateOnPageLoadParams { forceUpdateOnPageLoad: boolean; } /** * Return value of the 'ServiceWorker.setForceUpdateOnPageLoad' method. */ export interface SetForceUpdateOnPageLoadResult {} /** * Parameters of the 'ServiceWorker.skipWaiting' method. */ export interface SkipWaitingParams { scopeURL: string; } /** * Return value of the 'ServiceWorker.skipWaiting' method. */ export interface SkipWaitingResult {} /** * Parameters of the 'ServiceWorker.startWorker' method. */ export interface StartWorkerParams { scopeURL: string; } /** * Return value of the 'ServiceWorker.startWorker' method. */ export interface StartWorkerResult {} /** * Parameters of the 'ServiceWorker.stopAllWorkers' method. */ export interface StopAllWorkersParams {} /** * Return value of the 'ServiceWorker.stopAllWorkers' method. */ export interface StopAllWorkersResult {} /** * Parameters of the 'ServiceWorker.stopWorker' method. */ export interface StopWorkerParams { versionId: string; } /** * Return value of the 'ServiceWorker.stopWorker' method. */ export interface StopWorkerResult {} /** * Parameters of the 'ServiceWorker.unregister' method. */ export interface UnregisterParams { scopeURL: string; } /** * Return value of the 'ServiceWorker.unregister' method. */ export interface UnregisterResult {} /** * Parameters of the 'ServiceWorker.updateRegistration' method. */ export interface UpdateRegistrationParams { scopeURL: string; } /** * Return value of the 'ServiceWorker.updateRegistration' method. */ export interface UpdateRegistrationResult {} /** * Parameters of the 'ServiceWorker.workerErrorReported' event. */ export interface WorkerErrorReportedEvent { errorMessage: ServiceWorkerErrorMessage; } /** * Parameters of the 'ServiceWorker.workerRegistrationUpdated' event. */ export interface WorkerRegistrationUpdatedEvent { registrations: ServiceWorkerRegistration[]; } /** * Parameters of the 'ServiceWorker.workerVersionUpdated' event. */ export interface WorkerVersionUpdatedEvent { versions: ServiceWorkerVersion[]; } export type RegistrationID = string; /** * ServiceWorker registration. */ export interface ServiceWorkerRegistration { registrationId: RegistrationID; scopeURL: string; isDeleted: boolean; } export type ServiceWorkerVersionRunningStatus = 'stopped' | 'starting' | 'running' | 'stopping'; export type ServiceWorkerVersionStatus = | 'new' | 'installing' | 'installed' | 'activating' | 'activated' | 'redundant'; /** * ServiceWorker version. */ export interface ServiceWorkerVersion { versionId: string; registrationId: RegistrationID; scriptURL: string; runningStatus: ServiceWorkerVersionRunningStatus; status: ServiceWorkerVersionStatus; /** * The Last-Modified header value of the main script. */ scriptLastModified?: number; /** * The time at which the response headers of the main script were received from the server. * For cached script it is the last time the cache entry was validated. */ scriptResponseTime?: number; controlledClients?: Target.TargetID[]; targetId?: Target.TargetID; } /** * ServiceWorker error message. */ export interface ServiceWorkerErrorMessage { errorMessage: string; registrationId: RegistrationID; versionId: string; sourceURL: string; lineNumber: integer; columnNumber: integer; } } /** * Methods and events of the 'Storage' domain. */ export interface StorageApi { /** * Clears storage for origin. */ clearDataForOrigin( params: Storage.ClearDataForOriginParams, ): Promise<Storage.ClearDataForOriginResult | undefined>; /** * Returns all browser cookies. */ getCookies(params: Storage.GetCookiesParams): Promise<Storage.GetCookiesResult | undefined>; /** * Sets given cookies. */ setCookies(params: Storage.SetCookiesParams): Promise<Storage.SetCookiesResult | undefined>; /** * Clears cookies. */ clearCookies( params: Storage.ClearCookiesParams, ): Promise<Storage.ClearCookiesResult | undefined>; /** * Returns usage and quota in bytes. */ getUsageAndQuota( params: Storage.GetUsageAndQuotaParams, ): Promise<Storage.GetUsageAndQuotaResult | undefined>; /** * Override quota for the specified origin */ overrideQuotaForOrigin( params: Storage.OverrideQuotaForOriginParams, ): Promise<Storage.OverrideQuotaForOriginResult | undefined>; /** * Registers origin to be notified when an update occurs to its cache storage list. */ trackCacheStorageForOrigin( params: Storage.TrackCacheStorageForOriginParams, ): Promise<Storage.TrackCacheStorageForOriginResult | undefined>; /** * Registers origin to be notified when an update occurs to its IndexedDB. */ trackIndexedDBForOrigin( params: Storage.TrackIndexedDBForOriginParams, ): Promise<Storage.TrackIndexedDBForOriginResult | undefined>; /** * Unregisters origin from receiving notifications for cache storage. */ untrackCacheStorageForOrigin( params: Storage.UntrackCacheStorageForOriginParams, ): Promise<Storage.UntrackCacheStorageForOriginResult | undefined>; /** * Unregisters origin from receiving notifications for IndexedDB. */ untrackIndexedDBForOrigin( params: Storage.UntrackIndexedDBForOriginParams, ): Promise<Storage.UntrackIndexedDBForOriginResult | undefined>; /** * Returns the number of stored Trust Tokens per issuer for the * current browsing context. */ getTrustTokens( params: Storage.GetTrustTokensParams, ): Promise<Storage.GetTrustTokensResult | undefined>; /** * Removes all Trust Tokens issued by the provided issuerOrigin. * Leaves other stored data, including the issuer's Redemption Records, intact. */ clearTrustTokens( params: Storage.ClearTrustTokensParams, ): Promise<Storage.ClearTrustTokensResult | undefined>; /** * A cache's contents have been modified. */ on( event: 'cacheStorageContentUpdated', listener: (event: Storage.CacheStorageContentUpdatedEvent) => void, ): IDisposable; /** * A cache has been added/deleted. */ on( event: 'cacheStorageListUpdated', listener: (event: Storage.CacheStorageListUpdatedEvent) => void, ): IDisposable; /** * The origin's IndexedDB object store has been modified. */ on( event: 'indexedDBContentUpdated', listener: (event: Storage.IndexedDBContentUpdatedEvent) => void, ): IDisposable; /** * The origin's IndexedDB database list has been modified. */ on( event: 'indexedDBListUpdated', listener: (event: Storage.IndexedDBListUpdatedEvent) => void, ): IDisposable; } /** * Types of the 'Storage' domain. */ export namespace Storage { /** * Parameters of the 'Storage.clearDataForOrigin' method. */ export interface ClearDataForOriginParams { /** * Security origin. */ origin: string; /** * Comma separated list of StorageType to clear. */ storageTypes: string; } /** * Return value of the 'Storage.clearDataForOrigin' method. */ export interface ClearDataForOriginResult {} /** * Parameters of the 'Storage.getCookies' method. */ export interface GetCookiesParams { /** * Browser context to use when called on the browser endpoint. */ browserContextId?: Browser.BrowserContextID; } /** * Return value of the 'Storage.getCookies' method. */ export interface GetCookiesResult { /** * Array of cookie objects. */ cookies: Network.Cookie[]; } /** * Parameters of the 'Storage.setCookies' method. */ export interface SetCookiesParams { /** * Cookies to be set. */ cookies: Network.CookieParam[]; /** * Browser context to use when called on the browser endpoint. */ browserContextId?: Browser.BrowserContextID; } /** * Return value of the 'Storage.setCookies' method. */ export interface SetCookiesResult {} /** * Parameters of the 'Storage.clearCookies' method. */ export interface ClearCookiesParams { /** * Browser context to use when called on the browser endpoint. */ browserContextId?: Browser.BrowserContextID; } /** * Return value of the 'Storage.clearCookies' method. */ export interface ClearCookiesResult {} /** * Parameters of the 'Storage.getUsageAndQuota' method. */ export interface GetUsageAndQuotaParams { /** * Security origin. */ origin: string; } /** * Return value of the 'Storage.getUsageAndQuota' method. */ export interface GetUsageAndQuotaResult { /** * Storage usage (bytes). */ usage: number; /** * Storage quota (bytes). */ quota: number; /** * Whether or not the origin has an active storage quota override */ overrideActive: boolean; /** * Storage usage per type (bytes). */ usageBreakdown: UsageForType[]; } /** * Parameters of the 'Storage.overrideQuotaForOrigin' method. */ export interface OverrideQuotaForOriginParams { /** * Security origin. */ origin: string; /** * The quota size (in bytes) to override the original quota with. * If this is called multiple times, the overridden quota will be equal to * the quotaSize provided in the final call. If this is called without * specifying a quotaSize, the quota will be reset to the default value for * the specified origin. If this is called multiple times with different * origins, the override will be maintained for each origin until it is * disabled (called without a quotaSize). */ quotaSize?: number; } /** * Return value of the 'Storage.overrideQuotaForOrigin' method. */ export interface OverrideQuotaForOriginResult {} /** * Parameters of the 'Storage.trackCacheStorageForOrigin' method. */ export interface TrackCacheStorageForOriginParams { /** * Security origin. */ origin: string; } /** * Return value of the 'Storage.trackCacheStorageForOrigin' method. */ export interface TrackCacheStorageForOriginResult {} /** * Parameters of the 'Storage.trackIndexedDBForOrigin' method. */ export interface TrackIndexedDBForOriginParams { /** * Security origin. */ origin: string; } /** * Return value of the 'Storage.trackIndexedDBForOrigin' method. */ export interface TrackIndexedDBForOriginResult {} /** * Parameters of the 'Storage.untrackCacheStorageForOrigin' method. */ export interface UntrackCacheStorageForOriginParams { /** * Security origin. */ origin: string; } /** * Return value of the 'Storage.untrackCacheStorageForOrigin' method. */ export interface UntrackCacheStorageForOriginResult {} /** * Parameters of the 'Storage.untrackIndexedDBForOrigin' method. */ export interface UntrackIndexedDBForOriginParams { /** * Security origin. */ origin: string; } /** * Return value of the 'Storage.untrackIndexedDBForOrigin' method. */ export interface UntrackIndexedDBForOriginResult {} /** * Parameters of the 'Storage.getTrustTokens' method. */ export interface GetTrustTokensParams {} /** * Return value of the 'Storage.getTrustTokens' method. */ export interface GetTrustTokensResult { tokens: TrustTokens[]; } /** * Parameters of the 'Storage.clearTrustTokens' method. */ export interface ClearTrustTokensParams { issuerOrigin: string; } /** * Return value of the 'Storage.clearTrustTokens' method. */ export interface ClearTrustTokensResult { /** * True if any tokens were deleted, false otherwise. */ didDeleteTokens: boolean; } /** * Parameters of the 'Storage.cacheStorageContentUpdated' event. */ export interface CacheStorageContentUpdatedEvent { /** * Origin to update. */ origin: string; /** * Name of cache in origin. */ cacheName: string; } /** * Parameters of the 'Storage.cacheStorageListUpdated' event. */ export interface CacheStorageListUpdatedEvent { /** * Origin to update. */ origin: string; } /** * Parameters of the 'Storage.indexedDBContentUpdated' event. */ export interface IndexedDBContentUpdatedEvent { /** * Origin to update. */ origin: string; /** * Database to update. */ databaseName: string; /** * ObjectStore to update. */ objectStoreName: string; } /** * Parameters of the 'Storage.indexedDBListUpdated' event. */ export interface IndexedDBListUpdatedEvent { /** * Origin to update. */ origin: string; } /** * Enum of possible storage types. */ export type StorageType = | 'appcache' | 'cookies' | 'file_systems' | 'indexeddb' | 'local_storage' | 'shader_cache' | 'websql' | 'service_workers' | 'cache_storage' | 'all' | 'other'; /** * Usage for a storage type. */ export interface UsageForType { /** * Name of storage type. */ storageType: StorageType; /** * Storage usage (bytes). */ usage: number; } /** * Pair of issuer origin and number of available (signed, but not used) Trust * Tokens from that issuer. */ export interface TrustTokens { issuerOrigin: string; count: number; } } /** * Methods and events of the 'SystemInfo' domain. */ export interface SystemInfoApi { /** * Returns information about the system. */ getInfo(params: SystemInfo.GetInfoParams): Promise<SystemInfo.GetInfoResult | undefined>; /** * Returns information about all running processes. */ getProcessInfo( params: SystemInfo.GetProcessInfoParams, ): Promise<SystemInfo.GetProcessInfoResult | undefined>; } /** * Types of the 'SystemInfo' domain. */ export namespace SystemInfo { /** * Parameters of the 'SystemInfo.getInfo' method. */ export interface GetInfoParams {} /** * Return value of the 'SystemInfo.getInfo' method. */ export interface GetInfoResult { /** * Information about the GPUs on the system. */ gpu: GPUInfo; /** * A platform-dependent description of the model of the machine. On Mac OS, this is, for * example, 'MacBookPro'. Will be the empty string if not supported. */ modelName: string; /** * A platform-dependent description of the version of the machine. On Mac OS, this is, for * example, '10.1'. Will be the empty string if not supported. */ modelVersion: string; /** * The command line string used to launch the browser. Will be the empty string if not * supported. */ commandLine: string; } /** * Parameters of the 'SystemInfo.getProcessInfo' method. */ export interface GetProcessInfoParams {} /** * Return value of the 'SystemInfo.getProcessInfo' method. */ export interface GetProcessInfoResult { /** * An array of process info blocks. */ processInfo: ProcessInfo[]; } /** * Describes a single graphics processor (GPU). */ export interface GPUDevice { /** * PCI ID of the GPU vendor, if available; 0 otherwise. */ vendorId: number; /** * PCI ID of the GPU device, if available; 0 otherwise. */ deviceId: number; /** * Sub sys ID of the GPU, only available on Windows. */ subSysId?: number; /** * Revision of the GPU, only available on Windows. */ revision?: number; /** * String description of the GPU vendor, if the PCI ID is not available. */ vendorString: string; /** * String description of the GPU device, if the PCI ID is not available. */ deviceString: string; /** * String description of the GPU driver vendor. */ driverVendor: string; /** * String description of the GPU driver version. */ driverVersion: string; } /** * Describes the width and height dimensions of an entity. */ export interface Size { /** * Width in pixels. */ width: integer; /** * Height in pixels. */ height: integer; } /** * Describes a supported video decoding profile with its associated minimum and * maximum resolutions. */ export interface VideoDecodeAcceleratorCapability { /** * Video codec profile that is supported, e.g. VP9 Profile 2. */ profile: string; /** * Maximum video dimensions in pixels supported for this |profile|. */ maxResolution: Size; /** * Minimum video dimensions in pixels supported for this |profile|. */ minResolution: Size; } /** * Describes a supported video encoding profile with its associated maximum * resolution and maximum framerate. */ export interface VideoEncodeAcceleratorCapability { /** * Video codec profile that is supported, e.g H264 Main. */ profile: string; /** * Maximum video dimensions in pixels supported for this |profile|. */ maxResolution: Size; /** * Maximum encoding framerate in frames per second supported for this * |profile|, as fraction's numerator and denominator, e.g. 24/1 fps, * 24000/1001 fps, etc. */ maxFramerateNumerator: integer; maxFramerateDenominator: integer; } /** * YUV subsampling type of the pixels of a given image. */ export type SubsamplingFormat = 'yuv420' | 'yuv422' | 'yuv444'; /** * Image format of a given image. */ export type ImageType = 'jpeg' | 'webp' | 'unknown'; /** * Describes a supported image decoding profile with its associated minimum and * maximum resolutions and subsampling. */ export interface ImageDecodeAcceleratorCapability { /** * Image coded, e.g. Jpeg. */ imageType: ImageType; /** * Maximum supported dimensions of the image in pixels. */ maxDimensions: Size; /** * Minimum supported dimensions of the image in pixels. */ minDimensions: Size; /** * Optional array of supported subsampling formats, e.g. 4:2:0, if known. */ subsamplings: SubsamplingFormat[]; } /** * Provides information about the GPU(s) on the system. */ export interface GPUInfo { /** * The graphics devices on the system. Element 0 is the primary GPU. */ devices: GPUDevice[]; /** * An optional dictionary of additional GPU related attributes. */ auxAttributes?: any; /** * An optional dictionary of graphics features and their status. */ featureStatus?: any; /** * An optional array of GPU driver bug workarounds. */ driverBugWorkarounds: string[]; /** * Supported accelerated video decoding capabilities. */ videoDecoding: VideoDecodeAcceleratorCapability[]; /** * Supported accelerated video encoding capabilities. */ videoEncoding: VideoEncodeAcceleratorCapability[]; /** * Supported accelerated image decoding capabilities. */ imageDecoding: ImageDecodeAcceleratorCapability[]; } /** * Represents process info. */ export interface ProcessInfo { /** * Specifies process type. */ type: string; /** * Specifies process id. */ id: integer; /** * Specifies cumulative CPU usage in seconds across all threads of the * process since the process start. */ cpuTime: number; } } /** * Methods and events of the 'Target' domain. */ export interface TargetApi { /** * Activates (focuses) the target. */ activateTarget( params: Target.ActivateTargetParams, ): Promise<Target.ActivateTargetResult | undefined>; /** * Attaches to the target with given id. */ attachToTarget( params: Target.AttachToTargetParams, ): Promise<Target.AttachToTargetResult | undefined>; /** * Attaches to the browser target, only uses flat sessionId mode. */ attachToBrowserTarget( params: Target.AttachToBrowserTargetParams, ): Promise<Target.AttachToBrowserTargetResult | undefined>; /** * Closes the target. If the target is a page that gets closed too. */ closeTarget(params: Target.CloseTargetParams): Promise<Target.CloseTargetResult | undefined>; /** * Inject object to the target's main frame that provides a communication * channel with browser target. * * Injected object will be available as `window[bindingName]`. * * The object has the follwing API: * - `binding.send(json)` - a method to send messages over the remote debugging protocol * - `binding.onmessage = json => handleMessage(json)` - a callback that will be called for the protocol notifications and command responses. */ exposeDevToolsProtocol( params: Target.ExposeDevToolsProtocolParams, ): Promise<Target.ExposeDevToolsProtocolResult | undefined>; /** * Creates a new empty BrowserContext. Similar to an incognito profile but you can have more than * one. */ createBrowserContext( params: Target.CreateBrowserContextParams, ): Promise<Target.CreateBrowserContextResult | undefined>; /** * Returns all browser contexts created with `Target.createBrowserContext` method. */ getBrowserContexts( params: Target.GetBrowserContextsParams, ): Promise<Target.GetBrowserContextsResult | undefined>; /** * Creates a new page. */ createTarget(params: Target.CreateTargetParams): Promise<Target.CreateTargetResult | undefined>; /** * Detaches session with given id. */ detachFromTarget( params: Target.DetachFromTargetParams, ): Promise<Target.DetachFromTargetResult | undefined>; /** * Deletes a BrowserContext. All the belonging pages will be closed without calling their * beforeunload hooks. */ disposeBrowserContext( params: Target.DisposeBrowserContextParams, ): Promise<Target.DisposeBrowserContextResult | undefined>; /** * Returns information about a target. */ getTargetInfo( params: Target.GetTargetInfoParams, ): Promise<Target.GetTargetInfoResult | undefined>; /** * Retrieves a list of available targets. */ getTargets(params: Target.GetTargetsParams): Promise<Target.GetTargetsResult | undefined>; /** * Sends protocol message over session with given id. * Consider using flat mode instead; see commands attachToTarget, setAutoAttach, * and crbug.com/991325. * @deprecated */ sendMessageToTarget( params: Target.SendMessageToTargetParams, ): Promise<Target.SendMessageToTargetResult | undefined>; /** * Controls whether to automatically attach to new targets which are considered to be related to * this one. When turned on, attaches to all existing related targets as well. When turned off, * automatically detaches from all currently attached targets. * This also clears all targets added by `autoAttachRelated` from the list of targets to watch * for creation of related targets. */ setAutoAttach( params: Target.SetAutoAttachParams, ): Promise<Target.SetAutoAttachResult | undefined>; /** * Adds the specified target to the list of targets that will be monitored for any related target * creation (such as child frames, child workers and new versions of service worker) and reported * through `attachedToTarget`. The specified target is also auto-attached. * This cancels the effect of any previous `setAutoAttach` and is also cancelled by subsequent * `setAutoAttach`. Only available at the Browser target. */ autoAttachRelated( params: Target.AutoAttachRelatedParams, ): Promise<Target.AutoAttachRelatedResult | undefined>; /** * Controls whether to discover available targets and notify via * `targetCreated/targetInfoChanged/targetDestroyed` events. */ setDiscoverTargets( params: Target.SetDiscoverTargetsParams, ): Promise<Target.SetDiscoverTargetsResult | undefined>; /** * Enables target discovery for the specified locations, when `setDiscoverTargets` was set to * `true`. */ setRemoteLocations( params: Target.SetRemoteLocationsParams, ): Promise<Target.SetRemoteLocationsResult | undefined>; /** * Issued when attached to target because of auto-attach or `attachToTarget` command. */ on( event: 'attachedToTarget', listener: (event: Target.AttachedToTargetEvent) => void, ): IDisposable; /** * Issued when detached from target for any reason (including `detachFromTarget` command). Can be * issued multiple times per target if multiple sessions have been attached to it. */ on( event: 'detachedFromTarget', listener: (event: Target.DetachedFromTargetEvent) => void, ): IDisposable; /** * Notifies about a new protocol message received from the session (as reported in * `attachedToTarget` event). */ on( event: 'receivedMessageFromTarget', listener: (event: Target.ReceivedMessageFromTargetEvent) => void, ): IDisposable; /** * Issued when a possible inspection target is created. */ on(event: 'targetCreated', listener: (event: Target.TargetCreatedEvent) => void): IDisposable; /** * Issued when a target is destroyed. */ on( event: 'targetDestroyed', listener: (event: Target.TargetDestroyedEvent) => void, ): IDisposable; /** * Issued when a target has crashed. */ on(event: 'targetCrashed', listener: (event: Target.TargetCrashedEvent) => void): IDisposable; /** * Issued when some information about a target has changed. This only happens between * `targetCreated` and `targetDestroyed`. */ on( event: 'targetInfoChanged', listener: (event: Target.TargetInfoChangedEvent) => void, ): IDisposable; } /** * Types of the 'Target' domain. */ export namespace Target { /** * Parameters of the 'Target.activateTarget' method. */ export interface ActivateTargetParams { targetId: TargetID; } /** * Return value of the 'Target.activateTarget' method. */ export interface ActivateTargetResult {} /** * Parameters of the 'Target.attachToTarget' method. */ export interface AttachToTargetParams { targetId: TargetID; /** * Enables "flat" access to the session via specifying sessionId attribute in the commands. * We plan to make this the default, deprecate non-flattened mode, * and eventually retire it. See crbug.com/991325. */ flatten?: boolean; } /** * Return value of the 'Target.attachToTarget' method. */ export interface AttachToTargetResult { /** * Id assigned to the session. */ sessionId: SessionID; } /** * Parameters of the 'Target.attachToBrowserTarget' method. */ export interface AttachToBrowserTargetParams {} /** * Return value of the 'Target.attachToBrowserTarget' method. */ export interface AttachToBrowserTargetResult { /** * Id assigned to the session. */ sessionId: SessionID; } /** * Parameters of the 'Target.closeTarget' method. */ export interface CloseTargetParams { targetId: TargetID; } /** * Return value of the 'Target.closeTarget' method. */ export interface CloseTargetResult { /** * Always set to true. If an error occurs, the response indicates protocol error. * @deprecated */ success: boolean; } /** * Parameters of the 'Target.exposeDevToolsProtocol' method. */ export interface ExposeDevToolsProtocolParams { targetId: TargetID; /** * Binding name, 'cdp' if not specified. */ bindingName?: string; } /** * Return value of the 'Target.exposeDevToolsProtocol' method. */ export interface ExposeDevToolsProtocolResult {} /** * Parameters of the 'Target.createBrowserContext' method. */ export interface CreateBrowserContextParams { /** * If specified, disposes this context when debugging session disconnects. */ disposeOnDetach?: boolean; /** * Proxy server, similar to the one passed to --proxy-server */ proxyServer?: string; /** * Proxy bypass list, similar to the one passed to --proxy-bypass-list */ proxyBypassList?: string; } /** * Return value of the 'Target.createBrowserContext' method. */ export interface CreateBrowserContextResult { /** * The id of the context created. */ browserContextId: Browser.BrowserContextID; } /** * Parameters of the 'Target.getBrowserContexts' method. */ export interface GetBrowserContextsParams {} /** * Return value of the 'Target.getBrowserContexts' method. */ export interface GetBrowserContextsResult { /** * An array of browser context ids. */ browserContextIds: Browser.BrowserContextID[]; } /** * Parameters of the 'Target.createTarget' method. */ export interface CreateTargetParams { /** * The initial URL the page will be navigated to. An empty string indicates about:blank. */ url: string; /** * Frame width in DIP (headless chrome only). */ width?: integer; /** * Frame height in DIP (headless chrome only). */ height?: integer; /** * The browser context to create the page in. */ browserContextId?: Browser.BrowserContextID; /** * Whether BeginFrames for this target will be controlled via DevTools (headless chrome only, * not supported on MacOS yet, false by default). */ enableBeginFrameControl?: boolean; /** * Whether to create a new Window or Tab (chrome-only, false by default). */ newWindow?: boolean; /** * Whether to create the target in background or foreground (chrome-only, * false by default). */ background?: boolean; } /** * Return value of the 'Target.createTarget' method. */ export interface CreateTargetResult { /** * The id of the page opened. */ targetId: TargetID; } /** * Parameters of the 'Target.detachFromTarget' method. */ export interface DetachFromTargetParams { /** * Session to detach. */ sessionId?: SessionID; /** * Deprecated. * @deprecated */ targetId?: TargetID; } /** * Return value of the 'Target.detachFromTarget' method. */ export interface DetachFromTargetResult {} /** * Parameters of the 'Target.disposeBrowserContext' method. */ export interface DisposeBrowserContextParams { browserContextId: Browser.BrowserContextID; } /** * Return value of the 'Target.disposeBrowserContext' method. */ export interface DisposeBrowserContextResult {} /** * Parameters of the 'Target.getTargetInfo' method. */ export interface GetTargetInfoParams { targetId?: TargetID; } /** * Return value of the 'Target.getTargetInfo' method. */ export interface GetTargetInfoResult { targetInfo: TargetInfo; } /** * Parameters of the 'Target.getTargets' method. */ export interface GetTargetsParams {} /** * Return value of the 'Target.getTargets' method. */ export interface GetTargetsResult { /** * The list of targets. */ targetInfos: TargetInfo[]; } /** * Parameters of the 'Target.sendMessageToTarget' method. */ export interface SendMessageToTargetParams { message: string; /** * Identifier of the session. */ sessionId?: SessionID; /** * Deprecated. * @deprecated */ targetId?: TargetID; } /** * Return value of the 'Target.sendMessageToTarget' method. */ export interface SendMessageToTargetResult {} /** * Parameters of the 'Target.setAutoAttach' method. */ export interface SetAutoAttachParams { /** * Whether to auto-attach to related targets. */ autoAttach: boolean; /** * Whether to pause new targets when attaching to them. Use `Runtime.runIfWaitingForDebugger` * to run paused targets. */ waitForDebuggerOnStart: boolean; /** * Enables "flat" access to the session via specifying sessionId attribute in the commands. * We plan to make this the default, deprecate non-flattened mode, * and eventually retire it. See crbug.com/991325. */ flatten?: boolean; } /** * Return value of the 'Target.setAutoAttach' method. */ export interface SetAutoAttachResult {} /** * Parameters of the 'Target.autoAttachRelated' method. */ export interface AutoAttachRelatedParams { targetId: TargetID; /** * Whether to pause new targets when attaching to them. Use `Runtime.runIfWaitingForDebugger` * to run paused targets. */ waitForDebuggerOnStart: boolean; } /** * Return value of the 'Target.autoAttachRelated' method. */ export interface AutoAttachRelatedResult {} /** * Parameters of the 'Target.setDiscoverTargets' method. */ export interface SetDiscoverTargetsParams { /** * Whether to discover available targets. */ discover: boolean; } /** * Return value of the 'Target.setDiscoverTargets' method. */ export interface SetDiscoverTargetsResult {} /** * Parameters of the 'Target.setRemoteLocations' method. */ export interface SetRemoteLocationsParams { /** * List of remote locations. */ locations: RemoteLocation[]; } /** * Return value of the 'Target.setRemoteLocations' method. */ export interface SetRemoteLocationsResult {} /** * Parameters of the 'Target.attachedToTarget' event. */ export interface AttachedToTargetEvent { /** * Identifier assigned to the session used to send/receive messages. */ sessionId: SessionID; targetInfo: TargetInfo; waitingForDebugger: boolean; } /** * Parameters of the 'Target.detachedFromTarget' event. */ export interface DetachedFromTargetEvent { /** * Detached session identifier. */ sessionId: SessionID; /** * Deprecated. * @deprecated */ targetId?: TargetID; } /** * Parameters of the 'Target.receivedMessageFromTarget' event. */ export interface ReceivedMessageFromTargetEvent { /** * Identifier of a session which sends a message. */ sessionId: SessionID; message: string; /** * Deprecated. * @deprecated */ targetId?: TargetID; } /** * Parameters of the 'Target.targetCreated' event. */ export interface TargetCreatedEvent { targetInfo: TargetInfo; } /** * Parameters of the 'Target.targetDestroyed' event. */ export interface TargetDestroyedEvent { targetId: TargetID; } /** * Parameters of the 'Target.targetCrashed' event. */ export interface TargetCrashedEvent { targetId: TargetID; /** * Termination status type. */ status: string; /** * Termination error code. */ errorCode: integer; } /** * Parameters of the 'Target.targetInfoChanged' event. */ export interface TargetInfoChangedEvent { targetInfo: TargetInfo; } export type TargetID = string; /** * Unique identifier of attached debugging session. */ export type SessionID = string; export interface TargetInfo { targetId: TargetID; type: string; title: string; url: string; /** * Whether the target has an attached client. */ attached: boolean; /** * Opener target Id */ openerId?: TargetID; /** * Whether the target has access to the originating window. */ canAccessOpener: boolean; /** * Frame id of originating window (is only set if target has an opener). */ openerFrameId?: Page.FrameId; browserContextId?: Browser.BrowserContextID; } export interface RemoteLocation { host: string; port: integer; } } /** * Methods and events of the 'Tethering' domain. */ export interface TetheringApi { /** * Request browser port binding. */ bind(params: Tethering.BindParams): Promise<Tethering.BindResult | undefined>; /** * Request browser port unbinding. */ unbind(params: Tethering.UnbindParams): Promise<Tethering.UnbindResult | undefined>; /** * Informs that port was successfully bound and got a specified connection id. */ on(event: 'accepted', listener: (event: Tethering.AcceptedEvent) => void): IDisposable; } /** * Types of the 'Tethering' domain. */ export namespace Tethering { /** * Parameters of the 'Tethering.bind' method. */ export interface BindParams { /** * Port number to bind. */ port: integer; } /** * Return value of the 'Tethering.bind' method. */ export interface BindResult {} /** * Parameters of the 'Tethering.unbind' method. */ export interface UnbindParams { /** * Port number to unbind. */ port: integer; } /** * Return value of the 'Tethering.unbind' method. */ export interface UnbindResult {} /** * Parameters of the 'Tethering.accepted' event. */ export interface AcceptedEvent { /** * Port number that was successfully bound. */ port: integer; /** * Connection id to be used. */ connectionId: string; } } /** * Methods and events of the 'Tracing' domain. */ export interface TracingApi { /** * Stop trace events collection. */ end(params: Tracing.EndParams): Promise<Tracing.EndResult | undefined>; /** * Gets supported tracing categories. */ getCategories( params: Tracing.GetCategoriesParams, ): Promise<Tracing.GetCategoriesResult | undefined>; /** * Record a clock sync marker in the trace. */ recordClockSyncMarker( params: Tracing.RecordClockSyncMarkerParams, ): Promise<Tracing.RecordClockSyncMarkerResult | undefined>; /** * Request a global memory dump. */ requestMemoryDump( params: Tracing.RequestMemoryDumpParams, ): Promise<Tracing.RequestMemoryDumpResult | undefined>; /** * Start trace events collection. */ start(params: Tracing.StartParams): Promise<Tracing.StartResult | undefined>; on(event: 'bufferUsage', listener: (event: Tracing.BufferUsageEvent) => void): IDisposable; /** * Contains an bucket of collected trace events. When tracing is stopped collected events will be * send as a sequence of dataCollected events followed by tracingComplete event. */ on(event: 'dataCollected', listener: (event: Tracing.DataCollectedEvent) => void): IDisposable; /** * Signals that tracing is stopped and there is no trace buffers pending flush, all data were * delivered via dataCollected events. */ on( event: 'tracingComplete', listener: (event: Tracing.TracingCompleteEvent) => void, ): IDisposable; } /** * Types of the 'Tracing' domain. */ export namespace Tracing { /** * Parameters of the 'Tracing.end' method. */ export interface EndParams {} /** * Return value of the 'Tracing.end' method. */ export interface EndResult {} /** * Parameters of the 'Tracing.getCategories' method. */ export interface GetCategoriesParams {} /** * Return value of the 'Tracing.getCategories' method. */ export interface GetCategoriesResult { /** * A list of supported tracing categories. */ categories: string[]; } /** * Parameters of the 'Tracing.recordClockSyncMarker' method. */ export interface RecordClockSyncMarkerParams { /** * The ID of this clock sync marker */ syncId: string; } /** * Return value of the 'Tracing.recordClockSyncMarker' method. */ export interface RecordClockSyncMarkerResult {} /** * Parameters of the 'Tracing.requestMemoryDump' method. */ export interface RequestMemoryDumpParams { /** * Enables more deterministic results by forcing garbage collection */ deterministic?: boolean; /** * Specifies level of details in memory dump. Defaults to "detailed". */ levelOfDetail?: MemoryDumpLevelOfDetail; } /** * Return value of the 'Tracing.requestMemoryDump' method. */ export interface RequestMemoryDumpResult { /** * GUID of the resulting global memory dump. */ dumpGuid: string; /** * True iff the global memory dump succeeded. */ success: boolean; } /** * Parameters of the 'Tracing.start' method. */ export interface StartParams { /** * Category/tag filter * @deprecated */ categories?: string; /** * Tracing options * @deprecated */ options?: string; /** * If set, the agent will issue bufferUsage events at this interval, specified in milliseconds */ bufferUsageReportingInterval?: number; /** * Whether to report trace events as series of dataCollected events or to save trace to a * stream (defaults to `ReportEvents`). */ transferMode?: 'ReportEvents' | 'ReturnAsStream'; /** * Trace data format to use. This only applies when using `ReturnAsStream` * transfer mode (defaults to `json`). */ streamFormat?: StreamFormat; /** * Compression format to use. This only applies when using `ReturnAsStream` * transfer mode (defaults to `none`) */ streamCompression?: StreamCompression; traceConfig?: TraceConfig; /** * Base64-encoded serialized perfetto.protos.TraceConfig protobuf message * When specified, the parameters `categories`, `options`, `traceConfig` * are ignored. (Encoded as a base64 string when passed over JSON) */ perfettoConfig?: string; /** * Backend type (defaults to `auto`) */ tracingBackend?: TracingBackend; } /** * Return value of the 'Tracing.start' method. */ export interface StartResult {} /** * Parameters of the 'Tracing.bufferUsage' event. */ export interface BufferUsageEvent { /** * A number in range [0..1] that indicates the used size of event buffer as a fraction of its * total size. */ percentFull?: number; /** * An approximate number of events in the trace log. */ eventCount?: number; /** * A number in range [0..1] that indicates the used size of event buffer as a fraction of its * total size. */ value?: number; } /** * Parameters of the 'Tracing.dataCollected' event. */ export interface DataCollectedEvent { value: any[]; } /** * Parameters of the 'Tracing.tracingComplete' event. */ export interface TracingCompleteEvent { /** * Indicates whether some trace data is known to have been lost, e.g. because the trace ring * buffer wrapped around. */ dataLossOccurred: boolean; /** * A handle of the stream that holds resulting trace data. */ stream?: IO.StreamHandle; /** * Trace data format of returned stream. */ traceFormat?: StreamFormat; /** * Compression format of returned stream. */ streamCompression?: StreamCompression; } /** * Configuration for memory dump. Used only when "memory-infra" category is enabled. */ export interface MemoryDumpConfig { [key: string]: any; } export interface TraceConfig { /** * Controls how the trace buffer stores data. */ recordMode?: | 'recordUntilFull' | 'recordContinuously' | 'recordAsMuchAsPossible' | 'echoToConsole'; /** * Turns on JavaScript stack sampling. */ enableSampling?: boolean; /** * Turns on system tracing. */ enableSystrace?: boolean; /** * Turns on argument filter. */ enableArgumentFilter?: boolean; /** * Included category filters. */ includedCategories?: string[]; /** * Excluded category filters. */ excludedCategories?: string[]; /** * Configuration to synthesize the delays in tracing. */ syntheticDelays?: string[]; /** * Configuration for memory dump triggers. Used only when "memory-infra" category is enabled. */ memoryDumpConfig?: MemoryDumpConfig; } /** * Data format of a trace. Can be either the legacy JSON format or the * protocol buffer format. Note that the JSON format will be deprecated soon. */ export type StreamFormat = 'json' | 'proto'; /** * Compression type to use for traces returned via streams. */ export type StreamCompression = 'none' | 'gzip'; /** * Details exposed when memory request explicitly declared. * Keep consistent with memory_dump_request_args.h and * memory_instrumentation.mojom */ export type MemoryDumpLevelOfDetail = 'background' | 'light' | 'detailed'; /** * Backend type to use for tracing. `chrome` uses the Chrome-integrated * tracing service and is supported on all platforms. `system` is only * supported on Chrome OS and uses the Perfetto system tracing service. * `auto` chooses `system` when the perfettoConfig provided to Tracing.start * specifies at least one non-Chrome data source; otherwise uses `chrome`. */ export type TracingBackend = 'auto' | 'chrome' | 'system'; } /** * Methods and events of the 'WebAudio' domain. */ export interface WebAudioApi { /** * Enables the WebAudio domain and starts sending context lifetime events. */ enable(params: WebAudio.EnableParams): Promise<WebAudio.EnableResult | undefined>; /** * Disables the WebAudio domain. */ disable(params: WebAudio.DisableParams): Promise<WebAudio.DisableResult | undefined>; /** * Fetch the realtime data from the registered contexts. */ getRealtimeData( params: WebAudio.GetRealtimeDataParams, ): Promise<WebAudio.GetRealtimeDataResult | undefined>; /** * Notifies that a new BaseAudioContext has been created. */ on( event: 'contextCreated', listener: (event: WebAudio.ContextCreatedEvent) => void, ): IDisposable; /** * Notifies that an existing BaseAudioContext will be destroyed. */ on( event: 'contextWillBeDestroyed', listener: (event: WebAudio.ContextWillBeDestroyedEvent) => void, ): IDisposable; /** * Notifies that existing BaseAudioContext has changed some properties (id stays the same).. */ on( event: 'contextChanged', listener: (event: WebAudio.ContextChangedEvent) => void, ): IDisposable; /** * Notifies that the construction of an AudioListener has finished. */ on( event: 'audioListenerCreated', listener: (event: WebAudio.AudioListenerCreatedEvent) => void, ): IDisposable; /** * Notifies that a new AudioListener has been created. */ on( event: 'audioListenerWillBeDestroyed', listener: (event: WebAudio.AudioListenerWillBeDestroyedEvent) => void, ): IDisposable; /** * Notifies that a new AudioNode has been created. */ on( event: 'audioNodeCreated', listener: (event: WebAudio.AudioNodeCreatedEvent) => void, ): IDisposable; /** * Notifies that an existing AudioNode has been destroyed. */ on( event: 'audioNodeWillBeDestroyed', listener: (event: WebAudio.AudioNodeWillBeDestroyedEvent) => void, ): IDisposable; /** * Notifies that a new AudioParam has been created. */ on( event: 'audioParamCreated', listener: (event: WebAudio.AudioParamCreatedEvent) => void, ): IDisposable; /** * Notifies that an existing AudioParam has been destroyed. */ on( event: 'audioParamWillBeDestroyed', listener: (event: WebAudio.AudioParamWillBeDestroyedEvent) => void, ): IDisposable; /** * Notifies that two AudioNodes are connected. */ on( event: 'nodesConnected', listener: (event: WebAudio.NodesConnectedEvent) => void, ): IDisposable; /** * Notifies that AudioNodes are disconnected. The destination can be null, and it means all the outgoing connections from the source are disconnected. */ on( event: 'nodesDisconnected', listener: (event: WebAudio.NodesDisconnectedEvent) => void, ): IDisposable; /** * Notifies that an AudioNode is connected to an AudioParam. */ on( event: 'nodeParamConnected', listener: (event: WebAudio.NodeParamConnectedEvent) => void, ): IDisposable; /** * Notifies that an AudioNode is disconnected to an AudioParam. */ on( event: 'nodeParamDisconnected', listener: (event: WebAudio.NodeParamDisconnectedEvent) => void, ): IDisposable; } /** * Types of the 'WebAudio' domain. */ export namespace WebAudio { /** * Parameters of the 'WebAudio.enable' method. */ export interface EnableParams {} /** * Return value of the 'WebAudio.enable' method. */ export interface EnableResult {} /** * Parameters of the 'WebAudio.disable' method. */ export interface DisableParams {} /** * Return value of the 'WebAudio.disable' method. */ export interface DisableResult {} /** * Parameters of the 'WebAudio.getRealtimeData' method. */ export interface GetRealtimeDataParams { contextId: GraphObjectId; } /** * Return value of the 'WebAudio.getRealtimeData' method. */ export interface GetRealtimeDataResult { realtimeData: ContextRealtimeData; } /** * Parameters of the 'WebAudio.contextCreated' event. */ export interface ContextCreatedEvent { context: BaseAudioContext; } /** * Parameters of the 'WebAudio.contextWillBeDestroyed' event. */ export interface ContextWillBeDestroyedEvent { contextId: GraphObjectId; } /** * Parameters of the 'WebAudio.contextChanged' event. */ export interface ContextChangedEvent { context: BaseAudioContext; } /** * Parameters of the 'WebAudio.audioListenerCreated' event. */ export interface AudioListenerCreatedEvent { listener: AudioListener; } /** * Parameters of the 'WebAudio.audioListenerWillBeDestroyed' event. */ export interface AudioListenerWillBeDestroyedEvent { contextId: GraphObjectId; listenerId: GraphObjectId; } /** * Parameters of the 'WebAudio.audioNodeCreated' event. */ export interface AudioNodeCreatedEvent { node: AudioNode; } /** * Parameters of the 'WebAudio.audioNodeWillBeDestroyed' event. */ export interface AudioNodeWillBeDestroyedEvent { contextId: GraphObjectId; nodeId: GraphObjectId; } /** * Parameters of the 'WebAudio.audioParamCreated' event. */ export interface AudioParamCreatedEvent { param: AudioParam; } /** * Parameters of the 'WebAudio.audioParamWillBeDestroyed' event. */ export interface AudioParamWillBeDestroyedEvent { contextId: GraphObjectId; nodeId: GraphObjectId; paramId: GraphObjectId; } /** * Parameters of the 'WebAudio.nodesConnected' event. */ export interface NodesConnectedEvent { contextId: GraphObjectId; sourceId: GraphObjectId; destinationId: GraphObjectId; sourceOutputIndex?: number; destinationInputIndex?: number; } /** * Parameters of the 'WebAudio.nodesDisconnected' event. */ export interface NodesDisconnectedEvent { contextId: GraphObjectId; sourceId: GraphObjectId; destinationId: GraphObjectId; sourceOutputIndex?: number; destinationInputIndex?: number; } /** * Parameters of the 'WebAudio.nodeParamConnected' event. */ export interface NodeParamConnectedEvent { contextId: GraphObjectId; sourceId: GraphObjectId; destinationId: GraphObjectId; sourceOutputIndex?: number; } /** * Parameters of the 'WebAudio.nodeParamDisconnected' event. */ export interface NodeParamDisconnectedEvent { contextId: GraphObjectId; sourceId: GraphObjectId; destinationId: GraphObjectId; sourceOutputIndex?: number; } /** * An unique ID for a graph object (AudioContext, AudioNode, AudioParam) in Web Audio API */ export type GraphObjectId = string; /** * Enum of BaseAudioContext types */ export type ContextType = 'realtime' | 'offline'; /** * Enum of AudioContextState from the spec */ export type ContextState = 'suspended' | 'running' | 'closed'; /** * Enum of AudioNode types */ export type NodeType = string; /** * Enum of AudioNode::ChannelCountMode from the spec */ export type ChannelCountMode = 'clamped-max' | 'explicit' | 'max'; /** * Enum of AudioNode::ChannelInterpretation from the spec */ export type ChannelInterpretation = 'discrete' | 'speakers'; /** * Enum of AudioParam types */ export type ParamType = string; /** * Enum of AudioParam::AutomationRate from the spec */ export type AutomationRate = 'a-rate' | 'k-rate'; /** * Fields in AudioContext that change in real-time. */ export interface ContextRealtimeData { /** * The current context time in second in BaseAudioContext. */ currentTime: number; /** * The time spent on rendering graph divided by render quantum duration, * and multiplied by 100. 100 means the audio renderer reached the full * capacity and glitch may occur. */ renderCapacity: number; /** * A running mean of callback interval. */ callbackIntervalMean: number; /** * A running variance of callback interval. */ callbackIntervalVariance: number; } /** * Protocol object for BaseAudioContext */ export interface BaseAudioContext { contextId: GraphObjectId; contextType: ContextType; contextState: ContextState; realtimeData?: ContextRealtimeData; /** * Platform-dependent callback buffer size. */ callbackBufferSize: number; /** * Number of output channels supported by audio hardware in use. */ maxOutputChannelCount: number; /** * Context sample rate. */ sampleRate: number; } /** * Protocol object for AudioListener */ export interface AudioListener { listenerId: GraphObjectId; contextId: GraphObjectId; } /** * Protocol object for AudioNode */ export interface AudioNode { nodeId: GraphObjectId; contextId: GraphObjectId; nodeType: NodeType; numberOfInputs: number; numberOfOutputs: number; channelCount: number; channelCountMode: ChannelCountMode; channelInterpretation: ChannelInterpretation; } /** * Protocol object for AudioParam */ export interface AudioParam { paramId: GraphObjectId; nodeId: GraphObjectId; contextId: GraphObjectId; paramType: ParamType; rate: AutomationRate; defaultValue: number; minValue: number; maxValue: number; } } /** * Methods and events of the 'WebAuthn' domain. */ export interface WebAuthnApi { /** * Enable the WebAuthn domain and start intercepting credential storage and * retrieval with a virtual authenticator. */ enable(params: WebAuthn.EnableParams): Promise<WebAuthn.EnableResult | undefined>; /** * Disable the WebAuthn domain. */ disable(params: WebAuthn.DisableParams): Promise<WebAuthn.DisableResult | undefined>; /** * Creates and adds a virtual authenticator. */ addVirtualAuthenticator( params: WebAuthn.AddVirtualAuthenticatorParams, ): Promise<WebAuthn.AddVirtualAuthenticatorResult | undefined>; /** * Removes the given authenticator. */ removeVirtualAuthenticator( params: WebAuthn.RemoveVirtualAuthenticatorParams, ): Promise<WebAuthn.RemoveVirtualAuthenticatorResult | undefined>; /** * Adds the credential to the specified authenticator. */ addCredential( params: WebAuthn.AddCredentialParams, ): Promise<WebAuthn.AddCredentialResult | undefined>; /** * Returns a single credential stored in the given virtual authenticator that * matches the credential ID. */ getCredential( params: WebAuthn.GetCredentialParams, ): Promise<WebAuthn.GetCredentialResult | undefined>; /** * Returns all the credentials stored in the given virtual authenticator. */ getCredentials( params: WebAuthn.GetCredentialsParams, ): Promise<WebAuthn.GetCredentialsResult | undefined>; /** * Removes a credential from the authenticator. */ removeCredential( params: WebAuthn.RemoveCredentialParams, ): Promise<WebAuthn.RemoveCredentialResult | undefined>; /** * Clears all the credentials from the specified device. */ clearCredentials( params: WebAuthn.ClearCredentialsParams, ): Promise<WebAuthn.ClearCredentialsResult | undefined>; /** * Sets whether User Verification succeeds or fails for an authenticator. * The default is true. */ setUserVerified( params: WebAuthn.SetUserVerifiedParams, ): Promise<WebAuthn.SetUserVerifiedResult | undefined>; /** * Sets whether tests of user presence will succeed immediately (if true) or fail to resolve (if false) for an authenticator. * The default is true. */ setAutomaticPresenceSimulation( params: WebAuthn.SetAutomaticPresenceSimulationParams, ): Promise<WebAuthn.SetAutomaticPresenceSimulationResult | undefined>; } /** * Types of the 'WebAuthn' domain. */ export namespace WebAuthn { /** * Parameters of the 'WebAuthn.enable' method. */ export interface EnableParams {} /** * Return value of the 'WebAuthn.enable' method. */ export interface EnableResult {} /** * Parameters of the 'WebAuthn.disable' method. */ export interface DisableParams {} /** * Return value of the 'WebAuthn.disable' method. */ export interface DisableResult {} /** * Parameters of the 'WebAuthn.addVirtualAuthenticator' method. */ export interface AddVirtualAuthenticatorParams { options: VirtualAuthenticatorOptions; } /** * Return value of the 'WebAuthn.addVirtualAuthenticator' method. */ export interface AddVirtualAuthenticatorResult { authenticatorId: AuthenticatorId; } /** * Parameters of the 'WebAuthn.removeVirtualAuthenticator' method. */ export interface RemoveVirtualAuthenticatorParams { authenticatorId: AuthenticatorId; } /** * Return value of the 'WebAuthn.removeVirtualAuthenticator' method. */ export interface RemoveVirtualAuthenticatorResult {} /** * Parameters of the 'WebAuthn.addCredential' method. */ export interface AddCredentialParams { authenticatorId: AuthenticatorId; credential: Credential; } /** * Return value of the 'WebAuthn.addCredential' method. */ export interface AddCredentialResult {} /** * Parameters of the 'WebAuthn.getCredential' method. */ export interface GetCredentialParams { authenticatorId: AuthenticatorId; credentialId: string; } /** * Return value of the 'WebAuthn.getCredential' method. */ export interface GetCredentialResult { credential: Credential; } /** * Parameters of the 'WebAuthn.getCredentials' method. */ export interface GetCredentialsParams { authenticatorId: AuthenticatorId; } /** * Return value of the 'WebAuthn.getCredentials' method. */ export interface GetCredentialsResult { credentials: Credential[]; } /** * Parameters of the 'WebAuthn.removeCredential' method. */ export interface RemoveCredentialParams { authenticatorId: AuthenticatorId; credentialId: string; } /** * Return value of the 'WebAuthn.removeCredential' method. */ export interface RemoveCredentialResult {} /** * Parameters of the 'WebAuthn.clearCredentials' method. */ export interface ClearCredentialsParams { authenticatorId: AuthenticatorId; } /** * Return value of the 'WebAuthn.clearCredentials' method. */ export interface ClearCredentialsResult {} /** * Parameters of the 'WebAuthn.setUserVerified' method. */ export interface SetUserVerifiedParams { authenticatorId: AuthenticatorId; isUserVerified: boolean; } /** * Return value of the 'WebAuthn.setUserVerified' method. */ export interface SetUserVerifiedResult {} /** * Parameters of the 'WebAuthn.setAutomaticPresenceSimulation' method. */ export interface SetAutomaticPresenceSimulationParams { authenticatorId: AuthenticatorId; enabled: boolean; } /** * Return value of the 'WebAuthn.setAutomaticPresenceSimulation' method. */ export interface SetAutomaticPresenceSimulationResult {} export type AuthenticatorId = string; export type AuthenticatorProtocol = 'u2f' | 'ctap2'; export type Ctap2Version = 'ctap2_0' | 'ctap2_1'; export type AuthenticatorTransport = 'usb' | 'nfc' | 'ble' | 'cable' | 'internal'; export interface VirtualAuthenticatorOptions { protocol: AuthenticatorProtocol; /** * Defaults to ctap2_0. Ignored if |protocol| == u2f. */ ctap2Version?: Ctap2Version; transport: AuthenticatorTransport; /** * Defaults to false. */ hasResidentKey?: boolean; /** * Defaults to false. */ hasUserVerification?: boolean; /** * If set to true, the authenticator will support the largeBlob extension. * https://w3c.github.io/webauthn#largeBlob * Defaults to false. */ hasLargeBlob?: boolean; /** * If set to true, the authenticator will support the credBlob extension. * https://fidoalliance.org/specs/fido-v2.1-rd-20201208/fido-client-to-authenticator-protocol-v2.1-rd-20201208.html#sctn-credBlob-extension * Defaults to false. */ hasCredBlob?: boolean; /** * If set to true, tests of user presence will succeed immediately. * Otherwise, they will not be resolved. Defaults to true. */ automaticPresenceSimulation?: boolean; /** * Sets whether User Verification succeeds or fails for an authenticator. * Defaults to false. */ isUserVerified?: boolean; } export interface Credential { credentialId: string; isResidentCredential: boolean; /** * Relying Party ID the credential is scoped to. Must be set when adding a * credential. */ rpId?: string; /** * The ECDSA P-256 private key in PKCS#8 format. (Encoded as a base64 string when passed over JSON) */ privateKey: string; /** * An opaque byte sequence with a maximum size of 64 bytes mapping the * credential to a specific user. (Encoded as a base64 string when passed over JSON) */ userHandle?: string; /** * Signature counter. This is incremented by one for each successful * assertion. * See https://w3c.github.io/webauthn/#signature-counter */ signCount: integer; /** * The large blob associated with the credential. * See https://w3c.github.io/webauthn/#sctn-large-blob-extension (Encoded as a base64 string when passed over JSON) */ largeBlob?: string; } } } export default Cdp;
the_stack
import { expect } from 'chai'; import 'mocha'; import { TsoaRoute, FieldErrors, ValidationService, AdditionalProps } from '@tsoa/runtime'; import { TypeAliasDate, TypeAliasDateTime, TypeAliasModel1, TypeAliasModel2 } from 'fixtures/testModel'; describe('ValidationService', () => { describe('Model validate', () => { it('should validate a model with declared properties', () => { const modelDefinition: TsoaRoute.ModelSchema = { dataType: 'refObject', properties: { a: { dataType: 'string', required: true }, }, }; const v = new ValidationService({}); const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'ignore', }; const error = {}; const result = v.validateModel({ fieldErrors: error, minimalSwaggerConfig, name: '', modelDefinition, value: { a: 's' }, }); expect(Object.keys(error)).to.be.empty; expect(result).to.eql({ a: 's' }); }); it('should not allow additionalProperties if noImplicitAdditionalProperties is set to throw-on-extras', () => { // Arrange const modelDefinition: TsoaRoute.ModelSchema = { dataType: 'refObject', additionalProperties: false, properties: { a: { dataType: 'string', required: true }, }, }; const v = new ValidationService({}); const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'throw-on-extras', }; const errorDictionary: FieldErrors = {}; const nameOfAdditionalProperty = 'I am the bad key name'; const dataToValidate = { a: 's', [nameOfAdditionalProperty]: 'something extra', }; // Act v.validateModel({ fieldErrors: errorDictionary, minimalSwaggerConfig, name: '', modelDefinition, value: dataToValidate, }); // Assert const errorKeys = Object.keys(errorDictionary); expect(errorKeys).to.have.lengthOf(1); const firstAndOnlyErrorKey = errorKeys[0]; expect(errorDictionary[firstAndOnlyErrorKey].message).to.eq(`"${nameOfAdditionalProperty}" is an excess property and therefore is not allowed`); if (!dataToValidate[nameOfAdditionalProperty]) { throw new Error( `dataToValidate.${nameOfAdditionalProperty} should have been there because .validateModel should NOT have removed it since it took the more severe option of producing an error instead.`, ); } }); it('should allow (but remove) additionalProperties if noImplicitAdditionalProperties is set to silently-remove-extras', () => { // Arrange const modelDefinition: TsoaRoute.ModelSchema = { dataType: 'refObject', additionalProperties: false, properties: { a: { dataType: 'string', required: true }, }, }; const v = new ValidationService({}); const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'silently-remove-extras', }; const errorDictionary: FieldErrors = {}; const nameOfAdditionalProperty = 'I am the bad key name'; const dataToValidate = { a: 's', [nameOfAdditionalProperty]: 'something extra', }; // Act v.validateModel({ fieldErrors: errorDictionary, minimalSwaggerConfig, name: '', modelDefinition, value: dataToValidate, }); // Assert if (dataToValidate[nameOfAdditionalProperty]) { throw new Error(`dataToValidate.${nameOfAdditionalProperty} should NOT have been present because .validateModel should have removed it due to it being an excess property.`); } expect(dataToValidate).not.to.have.ownProperty(nameOfAdditionalProperty, ''); const errorKeys = Object.keys(errorDictionary); expect(errorKeys).to.have.lengthOf(0); }); it('should allow additionalProperties if noImplicitAdditionalProperties is set to ignore', () => { // Arrange const modelDefinition: TsoaRoute.ModelSchema = { dataType: 'refObject', additionalProperties: false, properties: { a: { dataType: 'string', required: true }, }, }; const v = new ValidationService({}); const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'ignore', }; const errorDictionary: FieldErrors = {}; const nameOfAdditionalProperty = 'I am the bad key name'; const dataToValidate = { a: 's', [nameOfAdditionalProperty]: 'something extra', }; // Act const result = v.validateModel({ fieldErrors: errorDictionary, minimalSwaggerConfig, name: '', modelDefinition, value: dataToValidate, }); expect(Object.keys(errorDictionary)).to.be.empty; expect(result).to.eql({ a: 's', [nameOfAdditionalProperty]: 'something extra', }); }); it('should not require optional properties', () => { const modelDefinition: TsoaRoute.ModelSchema = { dataType: 'refObject', properties: { a: { dataType: 'string' }, }, }; const v = new ValidationService({}); const error = {}; const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'ignore', }; const result = v.validateModel({ name: '', value: {}, modelDefinition, fieldErrors: error, minimalSwaggerConfig }); expect(Object.keys(error)).to.be.empty; expect(result).to.eql({}); }); it('should validate a model with additional properties', () => { const modelDefinition: TsoaRoute.ModelSchema = { dataType: 'refObject', properties: {}, additionalProperties: { dataType: 'any' }, }; const v = new ValidationService({}); const error = {}; const minimalSwaggerConfig: AdditionalProps = { // we're setting this to the "throw" to demonstrate that explicit additionalProperties should always be allowed noImplicitAdditionalProperties: 'throw-on-extras', }; const result = v.validateModel({ name: '', value: { a: 's' }, modelDefinition, fieldErrors: error, minimalSwaggerConfig }); expect(Object.keys(error)).to.be.empty; expect(result).to.eql({ a: 's' }); }); it('should validate a model with optional and additional properties', () => { const modelDefinition: TsoaRoute.ModelSchema = { dataType: 'refObject', additionalProperties: { dataType: 'any' }, properties: { a: { dataType: 'string' }, }, }; const v = new ValidationService({}); const error = {}; const minimalSwaggerConfig: AdditionalProps = { // This test should ignore this, otherwise there's a problem the code // when the model has additionalProperties, that should take precedence since it's explicit noImplicitAdditionalProperties: 'throw-on-extras', }; const result = v.validateModel({ name: '', value: {}, modelDefinition, fieldErrors: error, minimalSwaggerConfig }); expect(Object.keys(error)).to.be.empty; expect(result).to.eql({}); }); it('should validate additional properties only against non-explicitly stated properties', () => { const modelDefinition: TsoaRoute.ModelSchema = { dataType: 'refObject', additionalProperties: { dataType: 'integer', validators: { minimum: { value: 10 } }, }, properties: { a: { dataType: 'integer' }, }, }; const v = new ValidationService({}); const error = {}; const minimalSwaggerConfig: AdditionalProps = { // This test should ignore this, otherwise there's a problem the code // when the model has additionalProperties, that should take precedence since it's explicit noImplicitAdditionalProperties: 'throw-on-extras', }; const result = v.validateModel({ name: '', value: { a: 9 }, modelDefinition, fieldErrors: error, minimalSwaggerConfig }); expect(Object.keys(error)).to.be.empty; expect(result).to.eql({ a: 9 }); }); it('non provided parameters should not result in undefined', () => { const v = new ValidationService({ BEnum: { dataType: 'refEnum', enums: ['X', 'Y'], }, General: { dataType: 'refObject', properties: { a: { dataType: 'string' }, b: { ref: 'BEnum' }, c: { dataType: 'string' }, }, additionalProperties: false, }, }); const error = {}; const result = v.ValidateParam( { required: true, ref: 'General' }, { a: 'value', b: undefined, }, 'body', error, undefined, { noImplicitAdditionalProperties: 'ignore' }, ); expect(result).to.deep.equal({ a: 'value', b: undefined }); expect(Object.keys(error)).to.be.empty; expect('a' in result).to.be.true; // provided expect('b' in result).to.be.true; // provided, but empty expect('c' in result).to.be.false; // not provided }); it('required provided parameters should result in required errors', () => { const v = new ValidationService({ General: { dataType: 'refObject', properties: { a: { dataType: 'string', required: true }, }, additionalProperties: false, }, }); const error: any = {}; v.ValidateParam( { required: true, ref: 'General' }, { c: 'value', }, 'body', error, undefined, { noImplicitAdditionalProperties: 'ignore' }, ); expect(error['body.a'].message).to.equal(`'a' is required`); }); }); describe('Param validate', () => { it('should apply defaults for optional properties', () => { const value = undefined; const propertySchema: TsoaRoute.PropertySchema = { dataType: 'integer', default: '666', required: false, validators: {} }; const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'ignore', }; const result = new ValidationService({}).ValidateParam(propertySchema, value, 'defaultProp', {}, undefined, minimalSwaggerConfig); expect(result).to.equal(666); }); it('should not override values with defaults', () => { const value = 123; const propertySchema: TsoaRoute.PropertySchema = { dataType: 'integer', default: '666', required: false, validators: {} }; const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'ignore', }; const result = new ValidationService({}).ValidateParam(propertySchema, value, 'defaultProp', {}, undefined, minimalSwaggerConfig); expect(result).to.equal(123); }); it('should apply defaults for required properties', () => { const value = undefined; const propertySchema: TsoaRoute.PropertySchema = { dataType: 'integer', default: '666', required: true, validators: {} }; const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'ignore', }; const result = new ValidationService({}).ValidateParam(propertySchema, value, 'defaultProp', {}, undefined, minimalSwaggerConfig); expect(result).to.equal(666); }); }); describe('Integer validate', () => { it('should integer value', () => { const value = '10'; const result = new ValidationService({}).validateInt('name', value, {}); expect(result).to.equal(Number(value)); }); it('should invalid integer format', () => { const name = 'name'; const value = '10.0'; const error = {}; const result = new ValidationService({}).validateInt(name, value, error); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`invalid integer number`); }); it('should integer validate', () => { const name = 'name'; const value = '11'; const error = {}; const validator = { minimum: { value: 10 }, maximum: { value: 12 } }; const result = new ValidationService({}).validateInt(name, value, error, validator); expect(result).to.equal(Number(value)); }); it('should invalid integer min validate', () => { const name = 'name'; const value = '11'; const error = {}; const validator = { minimum: { value: 12 } }; const result = new ValidationService({}).validateInt(name, value, error, validator); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`min 12`); }); it('should invalid integer max validate', () => { const name = 'name'; const value = '11'; const error = {}; const validator = { maximum: { value: 10 } }; const result = new ValidationService({}).validateInt(name, value, error, validator); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`max 10`); }); }); describe('Float validate', () => { it('should float value', () => { const value = '10'; const result = new ValidationService({}).validateFloat('name', value, {}); expect(result).to.equal(Number(value)); }); it('should invalid float format', () => { const name = 'name'; const value = 'Hello'; const error = {}; const result = new ValidationService({}).validateFloat(name, value, error); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`invalid float number`); }); it('should float validate', () => { const name = 'name'; const value = '11.5'; const error = {}; const validator = { minimum: { value: 10 }, maximum: { value: 12 } }; const result = new ValidationService({}).validateFloat(name, value, error, validator); expect(result).to.equal(Number(value)); }); it('should invalid float min validate', () => { const name = 'name'; const value = '12.4'; const error = {}; const validator = { minimum: { value: 12.5 } }; const result = new ValidationService({}).validateFloat(name, value, error, validator); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`min 12.5`); }); it('should invalid float max validate', () => { const name = 'name'; const value = '10.6'; const error = {}; const validator = { maximum: { value: 10.5 } }; const result = new ValidationService({}).validateFloat(name, value, error, validator); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`max 10.5`); }); }); describe('Enum validate', () => { type Enumeration = string[] | number[]; it('should enum number value', () => { const name = 'name'; const value = 1; const error = {}; const enumeration: Enumeration = [0, 1]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(value); }); it('should enum empty string value', () => { const value = ''; const result = new ValidationService({}).validateEnum('name', value, {}, [''] as any); expect(result).to.equal(value); }); it('should enum null is not empty string value', () => { const value = null; const error = {}; const name = 'name'; const result = new ValidationService({}).validateEnum(name, value, error, [''] as any); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; ['']`); }); it('should enum string value', () => { const name = 'name'; const value = 'HELLO'; const error = {}; const enumeration: Enumeration = ['HELLO']; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(value); }); it('should enum no member', () => { const name = 'name'; const value = 'HI'; const error = {}; const enumeration: Enumeration = []; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`no member`); }); it('should enum out of member', () => { const name = 'name'; const value = 'SAY'; const error = {}; const enumeration: Enumeration = ['HELLO', 'HI']; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; ['HELLO','HI']`); }); it('does accept a string value for a numeric enum', () => { const name = 'name'; const value = '1'; const error = {}; const enumeration: Enumeration = [0, 1]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(1); expect(error).to.deep.equal({}); }); it('does not accept a wrong string value for a numeric enum', () => { const name = 'name'; const value = '2'; const error = {}; const enumeration: Enumeration = [0, 1]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [0,1]`); }); it('does accept a numeric value for a string-numeric enum', () => { const name = 'name'; const value = 1; const error = {}; const enumeration: Enumeration = ['0', '1']; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal('1'); expect(error).to.deep.equal({}); }); it('does not accept an improper numeric value for a string-numeric enum', () => { const name = 'name'; const value = 2; const error = {}; const enumeration: Enumeration = ['0', '1']; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; ['0','1']`); }); it('should fail if the value is a non-numeric string for a numeric enum', () => { const name = 'name'; const value = 'foo'; const error = {}; const enumeration: Enumeration = [1, 2]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [1,2]`); }); it('does accept a boolean value for a boolean enum', () => { const name = 'name'; const value = false; const error = {}; const enumeration = [false]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(false); expect(error).to.deep.equal({}); }); it('does accept a stringified boolean value for a boolean enum', () => { const name = 'name'; const value = 'true'; const error = {}; const enumeration = [true]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(true); expect(error).to.deep.equal({}); }); it('does not accept a wrong members of a boolean enum', () => { const name = 'name'; const value = false; const error = {}; const enumeration = [true]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [true]`); }); it('does not accept a wrong members of a boolean enum', () => { const name = 'name'; const value = 'false'; const error = {}; const enumeration = [true]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [true]`); }); it('accepts null in null enum', () => { const name = 'name'; const value = null; const error = {}; const enumeration = [null]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(null); expect(error).to.deep.equal({}); }); it('accepts stringified null in null enum', () => { const name = 'name'; const value = 'null'; const error = {}; const enumeration = [null]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(null); expect(error).to.deep.equal({}); }); it('does not coerce null to 0', () => { const name = 'name'; const value = 'null'; const error = {}; const enumeration = [0]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [0]`); }); it('does not coerce 0 to null', () => { const name = 'name'; const value = 0; const error = {}; const enumeration = [null]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [null]`); }); it('does not coerce null to false', () => { const name = 'name'; const value = null; const error = {}; const enumeration = [false]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [false]`); }); it('does not coerce false to null', () => { const name = 'name'; const value = false; const error = {}; const enumeration = [null]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [null]`); }); it('does not coerce 0 to false', () => { const name = 'name'; const value = 0; const error = {}; const enumeration = [false]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [false]`); }); it('does not coerce false to 0', () => { const name = 'name'; const value = false; const error = {}; const enumeration = [0]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [0]`); }); it("does not coerce null to ''", () => { const name = 'name'; const value = null; const error = {}; const enumeration = ['']; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; ['']`); }); it("does not coerce '' to null", () => { const name = 'name'; const value = ''; const error = {}; const enumeration = [null]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [null]`); }); it('does not coerce 1 to true', () => { const name = 'name'; const value = 1; const error = {}; const enumeration = [true]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [true]`); }); it('does not coerce true to 1', () => { const name = 'name'; const value = true; const error = {}; const enumeration = [1]; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; [1]`); }); it("does not coerce true to '1'", () => { const name = 'name'; const value = true; const error = {}; const enumeration = ['1']; const result = new ValidationService({}).validateEnum(name, value, error, enumeration); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`should be one of the following; ['1']`); }); }); describe('String validate', () => { it('should string value', () => { const value = 'Hello'; const result = new ValidationService({}).validateString('name', value, {}); expect(result).to.equal(value); }); it('should string minLength validate', () => { const name = 'name'; const value = 'AB'; const error = {}; const result = new ValidationService({}).validateString(name, value, error, { minLength: { value: 5 } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`minLength 5`); }); it('should string maxLength validate', () => { const name = 'name'; const value = 'ABCDE'; const error = {}; const result = new ValidationService({}).validateString(name, value, error, { maxLength: { value: 3 } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`maxLength 3`); }); it('should string pattern validate', () => { const name = 'name'; const value = 'ABC'; const error = {}; const result = new ValidationService({}).validateString(name, value, error, { pattern: { value: 'a-z' } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`Not match in 'a-z'`); }); }); describe('Date validate', () => { it('should date value', () => { const value = '2017-01-01'; const result = new ValidationService({}).validateDate('name', value, {}); expect(result).to.deep.equal(new Date(value)); }); it('should invalid date format', () => { const name = 'name'; const value = '2017-33-11'; const error = {}; const result = new ValidationService({}).validateDate(name, value, error); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`invalid ISO 8601 date format, i.e. YYYY-MM-DD`); }); it('should date minDate validate', () => { const name = 'name'; const value = '2017-06-01'; const error = {}; const result = new ValidationService({}).validateDate(name, value, error, { minDate: { value: '2017-07-01' } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`minDate '2017-07-01'`); }); it('should string maxDate validate', () => { const name = 'name'; const value = '2017-06-01'; const error = {}; const result = new ValidationService({}).validateDate(name, value, error, { maxDate: { value: '2017-05-01' } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`maxDate '2017-05-01'`); }); }); describe('DateTime validate', () => { it('should datetime value', () => { const value = '2017-12-30T00:00:00'; const result = new ValidationService({}).validateDateTime('name', value, {}); expect(result).to.deep.equal(new Date(value)); }); it('should invalid datetime format', () => { const name = 'name'; const value = '2017-12-309i'; const error = {}; const result = new ValidationService({}).validateDateTime(name, value, error); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`invalid ISO 8601 datetime format, i.e. YYYY-MM-DDTHH:mm:ss`); }); it('should datetime minDate validate', () => { const name = 'name'; const value = '2017-12-30T00:00:00'; const error = {}; const result = new ValidationService({}).validateDateTime(name, value, error, { minDate: { value: '2017-12-31T00:00:00' } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`minDate '2017-12-31T00:00:00'`); }); it('should datetime maxDate validate', () => { const name = 'name'; const value = '2017-12-30T00:00:00'; const error = {}; const result = new ValidationService({}).validateDateTime(name, value, error, { maxDate: { value: '2017-12-29T00:00:00' } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`maxDate '2017-12-29T00:00:00'`); }); }); describe('Array validate', () => { it('should array value', () => { const value = ['A', 'B', 'C']; const result = new ValidationService({}).validateArray('name', value, {}, { noImplicitAdditionalProperties: 'ignore' }, { dataType: 'string' }); expect(result).to.deep.equal(value); }); it('should invalid array value', () => { const name = 'name'; const value = ['A', 10, true]; const error = {}; const result = new ValidationService({}).validateArray(name, value, error, { noImplicitAdditionalProperties: 'ignore' }, { dataType: 'integer' }); expect(result).to.deep.equal(undefined); expect(error[`${name}.$0`].message).to.equal('invalid integer number'); expect(error[`${name}.$0`].value).to.equal('A'); expect(error[`${name}.$2`].message).to.equal('invalid integer number'); expect(error[`${name}.$2`].value).to.equal(true); }); it('should invalid array nested value', () => { const name = 'name'; const value = [{ a: 123 }, { a: 'bcd' }]; const error = {}; const result = new ValidationService({ ExampleModel: { dataType: 'refObject', properties: { a: { dataType: 'string', required: true }, }, }, }).validateArray(name, value, error, { noImplicitAdditionalProperties: 'ignore' }, { ref: 'ExampleModel' }); expect(result).to.deep.equal(undefined); expect(error).to.deep.equal({ [`${name}.$0.a`]: { message: 'invalid string value', value: 123, }, }); }); it('should array minItems validate', () => { const name = 'name'; const value = [80, 10, 199]; const error = {}; const result = new ValidationService({}).validateArray(name, value, error, { noImplicitAdditionalProperties: 'ignore' }, { dataType: 'integer' }, { minItems: { value: 4 } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`minItems 4`); }); it('should array maxItems validate', () => { const name = 'name'; const value = [80, 10, 199]; const error = {}; const result = new ValidationService({}).validateArray(name, value, error, { noImplicitAdditionalProperties: 'ignore' }, { dataType: 'integer' }, { maxItems: { value: 2 } }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`maxItems 2`); }); it('should array uniqueItems validate', () => { const name = 'name'; const value = [10, 10, 20]; const error = {}; const result = new ValidationService({}).validateArray(name, value, error, { noImplicitAdditionalProperties: 'ignore' }, { dataType: 'integer' }, { uniqueItems: {} }); expect(result).to.equal(undefined); expect(error[name].message).to.equal(`required unique array`); }); it('Should validate refEnum Arrays', () => { const enumModel: TsoaRoute.RefEnumModelSchema = { dataType: 'refEnum', enums: ['foo', 'bar'], }; const v = new ValidationService({ enumModel }); const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'ignore', }; const fieldErrors = {}; const result = v.validateArray('name', ['foo', 'bar', 'foo', 'foobar'], fieldErrors, minimalSwaggerConfig, { dataType: 'refEnum', ref: 'enumModel' }); expect(Object.keys(fieldErrors)).to.not.be.empty; expect(result).to.be.undefined; expect(fieldErrors).to.deep.equal({ 'name.$3': { message: "should be one of the following; ['foo','bar']", value: 'foobar' } }); }); }); describe('Union validate', () => { it('should validate discriminated union with silently-remove-extras on', () => { const v = new ValidationService({ TypeA: { dataType: 'refObject', properties: { type: { dataType: 'enum', enums: ['A'], required: true }, a: { dataType: 'double', required: true }, }, }, TypeB: { dataType: 'refObject', properties: { type: { dataType: 'enum', enums: ['B'], required: true }, b: { dataType: 'double', required: true }, }, }, }); const name = 'name'; const error = {}; const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'silently-remove-extras', }; const subSchemas = [{ ref: 'TypeA' }, { ref: 'TypeB' }]; const resultA = v.validateUnion(name, { type: 'A', a: 100 }, error, minimalSwaggerConfig, subSchemas); const resultB = v.validateUnion(name, { type: 'B', b: 20 }, error, minimalSwaggerConfig, subSchemas); expect(resultA).to.deep.equal({ type: 'A', a: 100 }); expect(resultB).to.deep.equal({ type: 'B', b: 20 }); }); }); describe('Intersection Validate', () => { describe('throw on extras', () => { const minimalSwaggerConfig: AdditionalProps = { noImplicitAdditionalProperties: 'throw-on-extras', }; it('should validate intersection with 3 or more types', () => { const refName = 'ExampleModel'; const subSchemas: TsoaRoute.PropertySchema[] = [{ ref: 'TypeAliasModel1' }, { ref: 'TypeAliasModel2' }, { ref: 'TypeAliasModelDateTime' }]; const models: TsoaRoute.Models = { [refName]: { dataType: 'refObject', properties: { and: { dataType: 'intersection', subSchemas, required: true, }, }, }, TypeAliasModel1: { dataType: 'refObject', properties: { value1: { dataType: 'string', required: true }, }, additionalProperties: false, }, TypeAliasModel2: { dataType: 'refObject', properties: { value2: { dataType: 'string', required: true }, }, additionalProperties: false, }, TypeAliasModelDateTime: { dataType: 'refObject', properties: { dateTimeValue: { dataType: 'datetime', required: true }, }, additionalProperties: false, }, TypeAliasModelDate: { dataType: 'refObject', properties: { dateValue: { dataType: 'date', required: true }, }, additionalProperties: false, }, }; const v = new ValidationService(models); const errorDictionary: FieldErrors = {}; const dataToValidate: TypeAliasModel1 & TypeAliasModel2 & TypeAliasDateTime = { value1: 'this is value 1', value2: 'this is value 2', dateTimeValue: ('2017-01-01T00:00:00' as unknown) as Date, }; // Act const name = 'dataToValidate'; const validatedData = v.validateIntersection('and', dataToValidate, errorDictionary, minimalSwaggerConfig, subSchemas, name + '.'); // Assert const expectedValues = { ...dataToValidate, dateTimeValue: new Date('2017-01-01T00:00:00') }; expect(errorDictionary).to.deep.equal({}); expect(validatedData).to.deep.equal(expectedValues); const errorDictionary2: FieldErrors = {}; const dataToValidate2: TypeAliasModel1 & TypeAliasModel2 & TypeAliasDateTime & TypeAliasDate = { ...dataToValidate, dateValue: ('2017-01-01' as unknown) as Date, }; const subSchemas2 = subSchemas.concat([{ ref: 'TypeAliasModelDate' }]); const validatedData2 = v.validateIntersection('and', dataToValidate2, errorDictionary2, minimalSwaggerConfig, subSchemas2, name + '.'); const expectedValues2 = { ...expectedValues, dateValue: new Date('2017-01-01') }; expect(errorDictionary2).to.deep.equal({}); expect(validatedData2).to.deep.equal(expectedValues2); }); it('should handle cases with unions', () => { const refName = 'ExampleModel'; const subSchemas = [{ ref: 'TypeAliasModel1' }, { ref: 'TypeAliasUnion' }]; const models: TsoaRoute.Models = { [refName]: { dataType: 'refObject', properties: { and: { dataType: 'intersection', subSchemas, required: true, }, }, }, TypeAliasModel1: { dataType: 'refObject', properties: { value1: { dataType: 'string', required: true }, }, additionalProperties: false, }, TypeAliasUnion: { dataType: 'refAlias', type: { dataType: 'union', subSchemas: [{ ref: 'UnionModel1' }, { ref: 'UnionModel2' }, { ref: 'UnionModel3' }], }, }, UnionModel1: { dataType: 'refObject', properties: { value2: { dataType: 'string', required: true }, }, additionalProperties: false, }, UnionModel2: { dataType: 'refObject', properties: { dateTimeValue: { dataType: 'datetime', required: true }, }, additionalProperties: false, }, UnionModel3: { dataType: 'refObject', properties: { dateValue: { dataType: 'date', required: true }, }, additionalProperties: false, }, }; const v = new ValidationService(models); const errorDictionary: FieldErrors = {}; const dataToValidate: TypeAliasModel1 & (TypeAliasModel2 | TypeAliasDateTime | TypeAliasDate) = { value1: 'this is value 1', dateValue: ('2017-01-01' as unknown) as Date, }; // Act const name = 'dataToValidate'; const validatedData = v.validateIntersection('and', dataToValidate, errorDictionary, minimalSwaggerConfig, subSchemas, name + '.'); // Assert const expectedValues = { ...dataToValidate, dateValue: new Date('2017-01-01') }; expect(errorDictionary).to.deep.equal({}); expect(validatedData).to.deep.equal(expectedValues); const errorDictionary2: FieldErrors = {}; const dataToValidate2: TypeAliasModel1 & (TypeAliasModel2 | TypeAliasDateTime | TypeAliasDate) = { value1: 'this is value 1', dateTimeValue: ('2017-01-01T00:00:00' as unknown) as Date, }; // Act const validatedData2 = v.validateIntersection('and', dataToValidate2, errorDictionary2, minimalSwaggerConfig, subSchemas, name + '.'); // Assert const expectedValues2 = { ...dataToValidate2, dateTimeValue: new Date('2017-01-01T00:00:00') }; expect(errorDictionary2).to.deep.equal({}); expect(validatedData2).to.deep.equal(expectedValues2); const errorDictionary3: FieldErrors = {}; const dataToValidate3: TypeAliasModel1 & (TypeAliasModel2 | TypeAliasDateTime | TypeAliasDate) = { value1: 'this is value 1', value2: 'this is value 2', }; // Act const validatedData3 = v.validateIntersection('and', dataToValidate3, errorDictionary3, minimalSwaggerConfig, subSchemas, name + '.'); // Assert expect(errorDictionary3).to.deep.equal({}); expect(validatedData3).to.deep.equal(dataToValidate3); const withUnionsName = 'withUnions'; const withUnionsSubSchemas = [{ ref: 'ServiceObject' }, { ref: 'BigUnion' }]; const WithUnionModels: TsoaRoute.Models = { [withUnionsName]: { dataType: 'refObject', properties: { unions: { dataType: 'intersection', subSchemas: withUnionsSubSchemas, required: true, }, }, }, ServiceObject: { dataType: 'refObject', properties: { service: { dataType: 'enum', enums: ['23'], required: false }, }, }, BigUnion: { dataType: 'refAlias', type: { dataType: 'union', subSchemas: [{ ref: 'Union1' }, { ref: 'Union2' }, { ref: 'Union3' }], }, }, Union1: { dataType: 'refObject', properties: { model: { dataType: 'string', required: true }, barcode_format: { dataType: 'string', required: true }, }, additionalProperties: false, }, Union2: { dataType: 'refObject', properties: { model: { dataType: 'string', required: true }, barcode_format: { dataType: 'string', required: true }, aProperty: { dataType: 'string', required: true }, }, }, Union3: { dataType: 'refObject', properties: { model: { dataType: 'string', required: true }, aAnotherProperty: { dataType: 'string', required: true }, }, additionalProperties: false, }, }; const withUnionValidationService = new ValidationService(WithUnionModels); const withUnionDataToValidate1 = { model: 'model1', service: '23', }; const withUnionErrorDictionary1 = {}; withUnionValidationService.validateIntersection('union', withUnionDataToValidate1, withUnionErrorDictionary1, minimalSwaggerConfig, withUnionsSubSchemas, withUnionsName + '.'); // Assert expect(withUnionErrorDictionary1).to.deep.equal({ 'withUnions.union': { message: `Could not match the intersection against every type. Issues: [{"withUnions.union":{"message":"Could not match the union against any of the items. Issues: [{\\"withUnions.union.barcode_format\\":{\\"message\\":\\"'barcode_format' is required\\"}},{\\"withUnions.union.barcode_format\\":{\\"message\\":\\"'barcode_format' is required\\"},\\"withUnions.union.aProperty\\":{\\"message\\":\\"'aProperty' is required\\"}},{\\"withUnions.union.aAnotherProperty\\":{\\"message\\":\\"'aAnotherProperty' is required\\"}}]","value":{"model":"model1","service":"23"}}}]`, value: withUnionDataToValidate1, }, }); const withUnionDataToValidate2 = { model: 'model2', barcode_format: 'none', aProperty: 'blabla', service: '23', }; const withUnionErrorDictionary2 = {}; const validatedResult2 = withUnionValidationService.validateIntersection( 'union', withUnionDataToValidate2, withUnionErrorDictionary2, minimalSwaggerConfig, withUnionsSubSchemas, withUnionsName + '.', ); // Assert expect(withUnionErrorDictionary2).to.deep.equal({}); expect(validatedResult2).to.deep.equal(withUnionDataToValidate2); const withUnionDataToValidate3 = { model: 'model3', aAnotherProperty: 'blabla', service: '23', }; const withUnionErrorDictionary3 = {}; const validatedResult3 = withUnionValidationService.validateIntersection( 'union', withUnionDataToValidate3, withUnionErrorDictionary3, minimalSwaggerConfig, withUnionsSubSchemas, withUnionsName + '.', ); // Assert expect(withUnionErrorDictionary3).to.deep.equal({}); expect(validatedResult3).to.deep.equal(withUnionDataToValidate3); }); }); }); });
the_stack
import ReactDOM from "react-dom"; import { render, fireEvent, mockBoundingClientRect, restoreOriginalGetBoundingClientRect, assertSelectedElements, } from "./test-utils"; import ExcalidrawApp from "../excalidraw-app"; import * as Renderer from "../renderer/renderScene"; import { KEYS } from "../keys"; import { reseed } from "../random"; import { API } from "./helpers/api"; import { Keyboard, Pointer } from "./helpers/ui"; // Unmount ReactDOM from root ReactDOM.unmountComponentAtNode(document.getElementById("root")!); const renderScene = jest.spyOn(Renderer, "renderScene"); beforeEach(() => { localStorage.clear(); renderScene.mockClear(); reseed(7); }); const { h } = window; const mouse = new Pointer("mouse"); describe("inner box-selection", () => { beforeEach(async () => { await render(<ExcalidrawApp />); }); it("selecting elements visually nested inside another", async () => { const rect1 = API.createElement({ type: "rectangle", x: 0, y: 0, width: 300, height: 300, backgroundColor: "red", fillStyle: "solid", }); const rect2 = API.createElement({ type: "rectangle", x: 50, y: 50, width: 50, height: 50, }); const rect3 = API.createElement({ type: "rectangle", x: 150, y: 150, width: 50, height: 50, }); h.elements = [rect1, rect2, rect3]; Keyboard.withModifierKeys({ ctrl: true }, () => { mouse.downAt(40, 40); mouse.moveTo(290, 290); mouse.up(); assertSelectedElements([rect2.id, rect3.id]); }); }); it("selecting grouped elements visually nested inside another", async () => { const rect1 = API.createElement({ type: "rectangle", x: 0, y: 0, width: 300, height: 300, backgroundColor: "red", fillStyle: "solid", }); const rect2 = API.createElement({ type: "rectangle", x: 50, y: 50, width: 50, height: 50, groupIds: ["A"], }); const rect3 = API.createElement({ type: "rectangle", x: 150, y: 150, width: 50, height: 50, groupIds: ["A"], }); h.elements = [rect1, rect2, rect3]; Keyboard.withModifierKeys({ ctrl: true }, () => { mouse.downAt(40, 40); mouse.moveTo(rect2.x + rect2.width + 10, rect2.y + rect2.height + 10); mouse.up(); assertSelectedElements([rect2.id, rect3.id]); expect(h.state.selectedGroupIds).toEqual({ A: true }); }); }); it("selecting & deselecting grouped elements visually nested inside another", async () => { const rect1 = API.createElement({ type: "rectangle", x: 0, y: 0, width: 300, height: 300, backgroundColor: "red", fillStyle: "solid", }); const rect2 = API.createElement({ type: "rectangle", x: 50, y: 50, width: 50, height: 50, groupIds: ["A"], }); const rect3 = API.createElement({ type: "rectangle", x: 150, y: 150, width: 50, height: 50, groupIds: ["A"], }); h.elements = [rect1, rect2, rect3]; Keyboard.withModifierKeys({ ctrl: true }, () => { mouse.downAt(rect2.x - 20, rect2.x - 20); mouse.moveTo(rect2.x + rect2.width + 10, rect2.y + rect2.height + 10); assertSelectedElements([rect2.id, rect3.id]); expect(h.state.selectedGroupIds).toEqual({ A: true }); mouse.moveTo(rect2.x - 10, rect2.y - 10); assertSelectedElements([rect1.id]); expect(h.state.selectedGroupIds).toEqual({}); mouse.up(); }); }); }); describe("selection element", () => { it("create selection element on pointer down", async () => { const { getByToolName, container } = await render(<ExcalidrawApp />); // select tool const tool = getByToolName("selection"); fireEvent.click(tool); const canvas = container.querySelector("canvas")!; fireEvent.pointerDown(canvas, { clientX: 60, clientY: 100 }); expect(renderScene).toHaveBeenCalledTimes(4); const selectionElement = h.state.selectionElement!; expect(selectionElement).not.toBeNull(); expect(selectionElement.type).toEqual("selection"); expect([selectionElement.x, selectionElement.y]).toEqual([60, 100]); expect([selectionElement.width, selectionElement.height]).toEqual([0, 0]); // TODO: There is a memory leak if pointer up is not triggered fireEvent.pointerUp(canvas); }); it("resize selection element on pointer move", async () => { const { getByToolName, container } = await render(<ExcalidrawApp />); // select tool const tool = getByToolName("selection"); fireEvent.click(tool); const canvas = container.querySelector("canvas")!; fireEvent.pointerDown(canvas, { clientX: 60, clientY: 100 }); fireEvent.pointerMove(canvas, { clientX: 150, clientY: 30 }); expect(renderScene).toHaveBeenCalledTimes(5); const selectionElement = h.state.selectionElement!; expect(selectionElement).not.toBeNull(); expect(selectionElement.type).toEqual("selection"); expect([selectionElement.x, selectionElement.y]).toEqual([60, 30]); expect([selectionElement.width, selectionElement.height]).toEqual([90, 70]); // TODO: There is a memory leak if pointer up is not triggered fireEvent.pointerUp(canvas); }); it("remove selection element on pointer up", async () => { const { getByToolName, container } = await render(<ExcalidrawApp />); // select tool const tool = getByToolName("selection"); fireEvent.click(tool); const canvas = container.querySelector("canvas")!; fireEvent.pointerDown(canvas, { clientX: 60, clientY: 100 }); fireEvent.pointerMove(canvas, { clientX: 150, clientY: 30 }); fireEvent.pointerUp(canvas); expect(renderScene).toHaveBeenCalledTimes(6); expect(h.state.selectionElement).toBeNull(); }); }); describe("select single element on the scene", () => { beforeAll(() => { mockBoundingClientRect(); }); afterAll(() => { restoreOriginalGetBoundingClientRect(); }); it("rectangle", async () => { const { getByToolName, container } = await render(<ExcalidrawApp />); const canvas = container.querySelector("canvas")!; { // create element const tool = getByToolName("rectangle"); fireEvent.click(tool); fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 }); fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 }); fireEvent.pointerUp(canvas); fireEvent.keyDown(document, { key: KEYS.ESCAPE, }); } const tool = getByToolName("selection"); fireEvent.click(tool); // click on a line on the rectangle fireEvent.pointerDown(canvas, { clientX: 45, clientY: 20 }); fireEvent.pointerUp(canvas); expect(renderScene).toHaveBeenCalledTimes(10); expect(h.state.selectionElement).toBeNull(); expect(h.elements.length).toEqual(1); expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy(); h.elements.forEach((element) => expect(element).toMatchSnapshot()); }); it("diamond", async () => { const { getByToolName, container } = await render(<ExcalidrawApp />); const canvas = container.querySelector("canvas")!; { // create element const tool = getByToolName("diamond"); fireEvent.click(tool); fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 }); fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 }); fireEvent.pointerUp(canvas); fireEvent.keyDown(document, { key: KEYS.ESCAPE, }); } const tool = getByToolName("selection"); fireEvent.click(tool); // click on a line on the rectangle fireEvent.pointerDown(canvas, { clientX: 45, clientY: 20 }); fireEvent.pointerUp(canvas); expect(renderScene).toHaveBeenCalledTimes(10); expect(h.state.selectionElement).toBeNull(); expect(h.elements.length).toEqual(1); expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy(); h.elements.forEach((element) => expect(element).toMatchSnapshot()); }); it("ellipse", async () => { const { getByToolName, container } = await render(<ExcalidrawApp />); const canvas = container.querySelector("canvas")!; { // create element const tool = getByToolName("ellipse"); fireEvent.click(tool); fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 }); fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 }); fireEvent.pointerUp(canvas); fireEvent.keyDown(document, { key: KEYS.ESCAPE, }); } const tool = getByToolName("selection"); fireEvent.click(tool); // click on a line on the rectangle fireEvent.pointerDown(canvas, { clientX: 45, clientY: 20 }); fireEvent.pointerUp(canvas); expect(renderScene).toHaveBeenCalledTimes(10); expect(h.state.selectionElement).toBeNull(); expect(h.elements.length).toEqual(1); expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy(); h.elements.forEach((element) => expect(element).toMatchSnapshot()); }); it("arrow", async () => { const { getByToolName, container } = await render(<ExcalidrawApp />); const canvas = container.querySelector("canvas")!; { // create element const tool = getByToolName("arrow"); fireEvent.click(tool); fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 }); fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 }); fireEvent.pointerUp(canvas); fireEvent.keyDown(document, { key: KEYS.ESCAPE, }); } /* 1 2 3 4 5 6 7 8 9 1 2 x 3 4 . 5 6 7 x 8 9 */ const tool = getByToolName("selection"); fireEvent.click(tool); // click on a line on the arrow fireEvent.pointerDown(canvas, { clientX: 40, clientY: 40 }); fireEvent.pointerUp(canvas); expect(renderScene).toHaveBeenCalledTimes(10); expect(h.state.selectionElement).toBeNull(); expect(h.elements.length).toEqual(1); expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy(); h.elements.forEach((element) => expect(element).toMatchSnapshot()); }); it("arrow escape", async () => { const { getByToolName, container } = await render(<ExcalidrawApp />); const canvas = container.querySelector("canvas")!; { // create element const tool = getByToolName("line"); fireEvent.click(tool); fireEvent.pointerDown(canvas, { clientX: 30, clientY: 20 }); fireEvent.pointerMove(canvas, { clientX: 60, clientY: 70 }); fireEvent.pointerUp(canvas); fireEvent.keyDown(document, { key: KEYS.ESCAPE, }); } /* 1 2 3 4 5 6 7 8 9 1 2 x 3 4 . 5 6 7 x 8 9 */ const tool = getByToolName("selection"); fireEvent.click(tool); // click on a line on the arrow fireEvent.pointerDown(canvas, { clientX: 40, clientY: 40 }); fireEvent.pointerUp(canvas); expect(renderScene).toHaveBeenCalledTimes(10); expect(h.state.selectionElement).toBeNull(); expect(h.elements.length).toEqual(1); expect(h.state.selectedElementIds[h.elements[0].id]).toBeTruthy(); h.elements.forEach((element) => expect(element).toMatchSnapshot()); }); });
the_stack
import tinyColor from "tinycolor2"; import * as easing from "d3-ease"; import * as gsap from "gsap"; import { drawElement2Ctx, DrawType } from "./helper"; interface RevealStore { hoverCanvas: HTMLCanvasElement; borderCanvas: HTMLCanvasElement; hoverCtx: CanvasRenderingContext2D; borderCtx: CanvasRenderingContext2D; isMouseDown: boolean; hoverScale: number; } const revealStore: RevealStore = { hoverCanvas: null, borderCanvas: null, hoverCtx: null, borderCtx: null, isMouseDown: false, hoverScale: 1 } as any; const revealItemsMap = new Map<HTMLElement, RevealItem>(); const coverItemsMap = new Map<HTMLElement, boolean>(); const observersMap = new Map<HTMLElement, MutationObserver>(); const pureColor = "#fff"; export interface ColorStore { gradient: CanvasGradient; borderColor: string; } const colorMap = new Map<string, ColorStore>(); /** * Detect rectangle is overlap. * @param rect1 - DOMRect * @param rect2 - DOMRect */ export interface OverlapRect { left: number; right: number; top: number; bottom: number; } export function isRectangleOverlap(rect1: OverlapRect, rect2: OverlapRect) { return Math.max(rect1.left, rect2.left) < Math.min(rect1.right, rect2.right) && Math.max(rect1.top, rect2.top) < Math.min(rect1.bottom, rect2.bottom); } export function isOverflowed(element: HTMLElement) { return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth; } /** * Detect cursor is inside to rect. * @param position The mouse cursor position. * @param rect The DOMRect. */ export function inRectInside(position: { left: number; top: number }, rect: DOMRect) { return (position.left > rect.left && position.left < rect.right && position.top > rect.top && position.top < rect.bottom); } /** Set reveal effect config. */ export interface RevalConfig { /** Set hover borderWidth. */ borderWidth?: number; /** Set hover size. */ hoverSize?: number; /** Set effectEnable type, default is both. */ effectEnable?: "hover" | "border" | "both"; /** Set borderType, default is inside. */ borderType?: "inside" | "outside"; /** Set hoverColor. */ hoverColor?: string; /** Set borderColor. */ borderColor?: string; /** Set canvas zIndex. */ zIndex?: number; hoverGradient?: CanvasGradient; } export interface CircleGradient { x: number; y: number; color1: string; color2: string; r1: number; r2: number; } /** * RevealItem interface. * */ export interface RevealItem { element: HTMLElement; borderWidth?: RevalConfig["borderWidth"]; hoverSize?: RevalConfig["hoverSize"]; effectEnable?: RevalConfig["effectEnable"]; borderType?: RevalConfig["borderType"]; hoverColor?: RevalConfig["hoverColor"]; /** * zIndex is not supported, only for the type. */ zIndex?: RevalConfig["zIndex"]; } const currMousePosition = { x: 0, y: 0 }; const revealConfig: Required<RevalConfig> = { hoverSize: 60, hoverColor: "rgba(255, 255, 255, .2)", borderWidth: 2, effectEnable: "both", borderType: "inside", zIndex: 9999, hoverGradient: null as any, borderColor: "" }; /** Create reveal effect method. */ function createCanvas() { revealStore.hoverCanvas = document.createElement("canvas"); revealStore.borderCanvas = document.createElement("canvas"); document.body.appendChild(revealStore.hoverCanvas); document.body.appendChild(revealStore.borderCanvas); revealStore.hoverCtx = revealStore.hoverCanvas.getContext("2d") as CanvasRenderingContext2D; revealStore.borderCtx = revealStore.borderCanvas.getContext("2d") as CanvasRenderingContext2D; removeListeners(); addListeners(); updateCanvas(); } export function removeCanvas() { document.body.removeChild(revealStore.hoverCanvas); document.body.removeChild(revealStore.borderCanvas); delete revealStore.hoverCanvas; delete revealStore.borderCanvas; delete revealStore.hoverCtx; delete revealStore.borderCtx; } export function updateCanvas() { Object.assign(revealStore.hoverCanvas.style, { width: `${window.innerWidth}px`, height: `${window.innerHeight}px`, position: "fixed", left: "0px", top: "0px", pointerEvents: "none", zIndex: revealConfig.zIndex }); Object.assign(revealStore.borderCanvas.style, { width: `${window.innerWidth}px`, height: `${window.innerHeight}px`, position: "fixed", left: "0px", top: "0px", pointerEvents: "none", zIndex: revealConfig.zIndex }); Object.assign(revealStore.hoverCanvas, { width: window.innerWidth, height: window.innerHeight }); Object.assign(revealStore.borderCanvas, { width: window.innerWidth, height: window.innerHeight }); } export function addListeners() { document.addEventListener("scroll", handleScroll, true); document.addEventListener("click", handleScroll, true); window.addEventListener("resize", updateCanvas); window.addEventListener("mousemove", handleMouseMove); } export function removeListeners() { document.removeEventListener("scroll", handleScroll, true); document.removeEventListener("click", handleScroll, true); window.removeEventListener("resize", updateCanvas); window.removeEventListener("mousemove", handleMouseMove); } export function handleScroll(e: Event) { let hoverEl = document.body as HTMLElement; revealItemsMap.forEach(({ element }) => { if (element) { const rect = element.getBoundingClientRect() as DOMRect; const isInsideEl = inRectInside({ left: currMousePosition.x, top: currMousePosition.y }, rect); if (isInsideEl) { if (hoverEl.contains(element)) { hoverEl = element; } } } }); drawEffect(currMousePosition.x, currMousePosition.y, hoverEl, true); } function handleMouseMove(e: MouseEvent) { const el = e.target as HTMLElement; drawEffect(e.clientX, e.clientY, el, true); } function getHoverParentEl(hoverEl: HTMLElement) { let parentEl: HTMLElement = document.body; revealItemsMap.forEach(({ element }) => { if (element) { if (element.contains(hoverEl) && parentEl.contains(element)) { parentEl = element; } } }); return parentEl; } function clearHoverCtx() { revealStore.hoverCtx.clearRect(0, 0, window.innerWidth, window.innerHeight); } function clearBorderCtx() { revealStore.borderCtx.clearRect(0, 0, window.innerWidth, window.innerHeight); } function drawHoverCircle(ctx: CanvasRenderingContext2D, hoverRevealConfig: Required<RevalConfig>) { let { hoverScale } = revealStore; const { x: mouseX, y: mouseY } = currMousePosition; let { hoverSize, hoverGradient } = hoverRevealConfig; hoverSize = hoverSize * hoverScale; const width = hoverSize * 2; ctx.save(); ctx.translate(mouseX, mouseY); ctx.fillStyle = 0 ? "#fff" : hoverGradient; ctx.scale(width, width); ctx.filter = `blur(${hoverSize / 10}px)`; ctx.fillRect(-.5, -.5, 1, 1); ctx.restore(); } // inside hover effect. function drawHover(hoverEl: HTMLElement) { revealStore.hoverCtx.globalCompositeOperation = "source-over"; const hoverRevealConfig = getRevealConfig(revealItemsMap.get(hoverEl) as RevealItem); drawHoverCircle(revealStore.hoverCtx, hoverRevealConfig); revealStore.hoverCtx.globalCompositeOperation = "destination-in"; revealStore.hoverCtx.fillStyle = pureColor; drawElement2Ctx(revealStore.hoverCtx, hoverEl, DrawType.Fill); } // draw border effect. function drawBorder(hoverRevealConfig: Required<RevalConfig>) { function drawAllRevealBorders() { const { x: mouseX, y: mouseY } = currMousePosition; const effectLeft = mouseX - hoverRevealConfig.hoverSize; const effectTop = mouseY - hoverRevealConfig.hoverSize; const effectSize = 2 * hoverRevealConfig.hoverSize; const effectRect = { left: effectLeft, top: effectTop, right: effectLeft + effectSize, bottom: effectTop + effectSize } as DOMRect; let effectItems: RevealItem[] = []; revealItemsMap.forEach(revealItem => { if (revealItem.element) { const rect = revealItem.element.getBoundingClientRect() as DOMRect; if (isRectangleOverlap(effectRect, rect)) { effectItems.push(revealItem); } } }); // sort effectItems by depth(deeper). effectItems = effectItems.sort((a, b) => a.element.compareDocumentPosition(b.element) & 2 ? -1 : 1); effectItems.forEach(revealItem => { const element = revealItem.element; if (!element) return; const currRevealConfig = getRevealConfig(revealItem); const { borderColor } = currRevealConfig; revealStore.borderCtx.globalCompositeOperation = "source-over"; revealStore.borderCtx.strokeStyle = borderColor; // draw inside border. revealStore.borderCtx.lineWidth = currRevealConfig.borderWidth; revealStore.borderCtx.fillStyle = currRevealConfig.borderColor; revealStore.borderCtx.strokeStyle = currRevealConfig.borderColor; drawElement2Ctx(revealStore.borderCtx, element, DrawType.Stroke); const parentEl = element.parentElement as HTMLElement; if (coverItemsMap.has(parentEl)) { const rect = parentEl.getBoundingClientRect() as DOMRect; revealStore.borderCtx.globalCompositeOperation = "destination-in"; revealStore.hoverCtx.globalCompositeOperation = "destination-in"; revealStore.borderCtx.fillStyle = pureColor; revealStore.hoverCtx.fillStyle = pureColor; revealStore.borderCtx.fillRect(rect.x, rect.y, rect.width, rect.height); revealStore.hoverCtx.fillRect(rect.x, rect.y, rect.width, rect.height); } }); } drawAllRevealBorders(); // make border mask. revealStore.borderCtx.globalCompositeOperation = "destination-in"; drawHoverCircle(revealStore.borderCtx, hoverRevealConfig); } function drawEffect(mouseX: number, mouseY: number, hoverEl: HTMLElement, clearHover: boolean) { currMousePosition.x = mouseX; currMousePosition.y = mouseY; if (clearHover) { clearHoverCtx(); } clearBorderCtx(); let isHoverReveal = revealItemsMap.has(hoverEl); if (!isHoverReveal && !coverItemsMap.has(hoverEl)) { hoverEl = getHoverParentEl(hoverEl); isHoverReveal = revealItemsMap.has(hoverEl); } const hoverRevealConfig = isHoverReveal ? getRevealConfig(revealItemsMap.get(hoverEl) as RevealItem) : revealConfig; switch (hoverRevealConfig.effectEnable) { case "hover": { if (isHoverReveal) { drawHover(hoverEl); } break; } case "border": { drawBorder(hoverRevealConfig); break; } default: { drawBorder(hoverRevealConfig); if (isHoverReveal) { drawHover(hoverEl); } break; } } } function clearCanvas() { if (isCanvasCreated()) { clearHoverCtx(); clearBorderCtx(); } revealItemsMap.clear(); } function isCanvasCreated() { return revealStore.hoverCanvas && revealStore.borderCanvas && revealStore.hoverCtx && revealStore.borderCtx; } function checkAndCreateCanvas() { if (!isCanvasCreated()) { createCanvas(); } } const observerConfig: MutationObserverInit = { attributes: true, characterData: false, childList: true, subtree: true }; const observerParentConfig: MutationObserverInit = { attributes: true, characterData: false, childList: true, subtree: true }; function addObserver(element: HTMLElement) { const { parentElement } = element; const observer = new MutationObserver((mutationsList) => { const elements = revealItemsMap.keys(); let isRemoved = false; for (const el of elements) { if (!document.documentElement.contains(el)) { revealItemsMap.delete(el); observersMap.delete(el); // observer.disconnect(); isRemoved = el === element; } if (isRemoved) break; } if (isRemoved) return; const isInsideEl = inRectInside({ left: currMousePosition.x, top: currMousePosition.y }, element.getBoundingClientRect() as DOMRect); drawEffect(currMousePosition.x, currMousePosition.y, isInsideEl ? element : document.documentElement, isInsideEl); }); // Start observing the target node for configured mutations. // observer.observe(element, observerConfig); if (parentElement) { observer.observe(parentElement, observerParentConfig); } observersMap.set(element, observer); } function clearObserver(element: HTMLElement) { const observer = observersMap.get(element); if (observer) { observer.disconnect(); revealItemsMap.delete(element); } } function clearObservers() { observersMap.forEach(observer => observer.disconnect()); observersMap.clear(); } const hoverMaxScale = .5; const hoverTime = 2; const hoverShortTime = .2; const ease = "Quart.easeInOut"; function addEvent2Elm(element: HTMLElement) { revealStore.hoverScale = hoverMaxScale; let tlMax: gsap.TweenLite = gsap.TweenLite.to(revealStore, hoverTime, { hoverScale: 1, ease, onUpdate() { drawEffect(currMousePosition.x, currMousePosition.y, element, true); } }); element.addEventListener("mousedown", (e) => { revealStore.isMouseDown = true; revealStore.hoverScale = hoverMaxScale; tlMax.restart(); }); element.addEventListener("mouseup", (e) => { revealStore.isMouseDown = false; const tlRestore = gsap.TweenLite.to(revealStore, hoverShortTime, { hoverScale: 1, ease, onUpdate() { drawEffect(currMousePosition.x, currMousePosition.y, element, true); } }); if (tlMax) { tlMax.pause(); } tlRestore.play(); }); } /** * Add reveal effect to revealItem. * @param revealItem - RevealItem */ function addRevealItem(revealItem: RevealItem) { checkAndCreateCanvas(); const { element } = revealItem; if (element) { addObserver(element); revealItemsMap.set(element, revealItem); const { parentElement } = element; if (parentElement && isOverflowed(parentElement)) { coverItemsMap.set(parentElement as HTMLElement, true); } } } /** * Add reveal effect to revealItem list. * @param revealItems - RevealItem[] */ function addRevealItems(revealItems: RevealItem[]) { checkAndCreateCanvas(); revealItems.forEach(revealItem => { addRevealItem(revealItem); }); } /** * Add reveal effect to html element. * @param element - HTMLElement */ function addRevealEl(element: HTMLElement) { checkAndCreateCanvas(); if (element) { addEvent2Elm(element); addObserver(element); const revealItem = { element }; revealItemsMap.set(element, revealItem); const { parentElement } = element; if (parentElement && isOverflowed(parentElement)) { coverItemsMap.set(parentElement as HTMLElement, true); } } } /** * Add reveal effect to html element list. * @param elements - HTMLElement[] | NodeListOf<HTMLElement> */ function addRevealEls(elements: HTMLElement[] | NodeListOf<HTMLElement>) { checkAndCreateCanvas(); elements.forEach((element: HTMLElement) => { addRevealEl(element); }); } function addCoverEl(element: HTMLElement) { if (element) { addObserver(element); coverItemsMap.set(element, true); } } function addCoverEls(elements: HTMLElement[] | NodeListOf<HTMLElement>) { elements.forEach((element: HTMLElement) => { addCoverEl(element); }); } /** * Clear all reveal effect element. */ function clearRevealEl(element: HTMLElement) { if (revealItemsMap.has(element)) { revealItemsMap.delete(element); } clearObserver(element); clearCanvas(); } /** * Clear all reveal effect elements. */ function clearRevealEls() { revealItemsMap.clear(); clearCanvas(); clearObservers(); } /** * Clear all reveal effect item. */ function clearRevealItem(revealItem: RevealItem) { if (revealItemsMap.has(revealItem.element)) { revealItemsMap.delete(revealItem.element); clearObserver(revealItem.element); } clearCanvas(); } /** * Clear all reveal effect items. */ function clearRevealItems() { revealItemsMap.clear(); clearCanvas(); clearObservers(); } function getRevealConfig(config: RevalConfig) { const newConfig = { hoverSize: config.hoverSize === void 0 ? revealConfig.hoverSize : config.hoverSize, borderWidth: config.borderWidth === void 0 ? revealConfig.borderWidth : config.borderWidth, effectEnable: config.effectEnable === void 0 ? revealConfig.effectEnable : config.effectEnable, borderType: config.borderType === void 0 ? revealConfig.borderType : config.borderType, hoverColor: config.hoverColor === void 0 ? revealConfig.hoverColor : config.hoverColor, zIndex: config.zIndex === void 0 ? revealConfig.zIndex : config.zIndex, borderColor: config.borderColor === void 0 ? revealConfig.borderColor : config.borderColor } as Required<RevalConfig>; const newTinyColor = tinyColor(newConfig.hoverColor); const hsla = newTinyColor.toHsl(); const hslaColor = newTinyColor.toHslString(); let storeColor = colorMap.get(hslaColor) as ColorStore; if (!storeColor) { const gradient = revealStore.hoverCtx.createRadialGradient(0, 0, 0, 0, 0, 1); const step = 0.01; for (let x = 1; x > 0; x -= step) { // let alpha = easing.easeCubicIn(x); let alpha = easing.easeCubicInOut(x); gradient.addColorStop(x / 2, `hsla(${hsla.h}, ${hsla.h * 100}%, ${hsla.l * 100}%, ${(1 - alpha) * hsla.a})`); } const borderColor = tinyColor({ h: hsla.h, s: hsla.s, l: hsla.l, a: 1 }).toHslString(); storeColor = { gradient, borderColor }; colorMap.set(hslaColor, storeColor); } newConfig.hoverGradient = storeColor.gradient; if (!newConfig.borderColor) { newConfig.borderColor = storeColor.borderColor; } return newConfig; } function setRevealConfig(config: RevalConfig) { checkAndCreateCanvas(); const newConfig = getRevealConfig(config); Object.assign(revealConfig, newConfig); updateCanvas(); } export { createCanvas, clearCanvas, handleMouseMove, addRevealItem, clearRevealItem, addRevealItems, clearRevealItems, addRevealEl, clearRevealEl, addRevealEls, clearRevealEls, addCoverEl, addCoverEls, setRevealConfig };
the_stack
import { Construct } from 'constructs'; import { CfnGatewayRoute } from './appmesh.generated'; import { HeaderMatch } from './header-match'; import { HttpRouteMethod } from './http-route-method'; import { HttpGatewayRoutePathMatch } from './http-route-path-match'; import { validateGrpcMatchArrayLength, validateGrpcGatewayRouteMatch } from './private/utils'; import { QueryParameterMatch } from './query-parameter-match'; import { Protocol } from './shared-interfaces'; import { IVirtualService } from './virtual-service'; /** * Configuration for gateway route host name match. */ export interface GatewayRouteHostnameMatchConfig { /** * GatewayRoute CFN configuration for host name match. */ readonly hostnameMatch: CfnGatewayRoute.GatewayRouteHostnameMatchProperty; } /** * Used to generate host name matching methods. */ export abstract class GatewayRouteHostnameMatch { /** * The value of the host name must match the specified value exactly. * * @param name The exact host name to match on */ public static exactly(name: string): GatewayRouteHostnameMatch { return new GatewayRouteHostnameMatchImpl({ exact: name }); } /** * The value of the host name with the given name must end with the specified characters. * * @param suffix The specified ending characters of the host name to match on */ public static endsWith(suffix: string): GatewayRouteHostnameMatch { return new GatewayRouteHostnameMatchImpl({ suffix }); } /** * Returns the gateway route host name match configuration. */ public abstract bind(scope: Construct): GatewayRouteHostnameMatchConfig; } class GatewayRouteHostnameMatchImpl extends GatewayRouteHostnameMatch { constructor( private readonly matchProperty: CfnGatewayRoute.GatewayRouteHostnameMatchProperty, ) { super(); } bind(_scope: Construct): GatewayRouteHostnameMatchConfig { return { hostnameMatch: this.matchProperty, }; } } /** * The criterion for determining a request match for this GatewayRoute. */ export interface HttpGatewayRouteMatch { /** * Specify how to match requests based on the 'path' part of their URL. * * @default - matches requests with any path */ readonly path?: HttpGatewayRoutePathMatch; /** * Specifies the client request headers to match on. All specified headers * must match for the gateway route to match. * * @default - do not match on headers */ readonly headers?: HeaderMatch[]; /** * The gateway route host name to be matched on. * * @default - do not match on host name */ readonly hostname?: GatewayRouteHostnameMatch; /** * The method to match on. * * @default - do not match on method */ readonly method?: HttpRouteMethod; /** * The query parameters to match on. * All specified query parameters must match for the route to match. * * @default - do not match on query parameters */ readonly queryParameters?: QueryParameterMatch[]; /** * When `true`, rewrites the original request received at the Virtual Gateway to the destination Virtual Service name. * When `false`, retains the original hostname from the request. * * @default true */ readonly rewriteRequestHostname?: boolean; } /** * The criterion for determining a request match for this GatewayRoute */ export interface GrpcGatewayRouteMatch { /** * Create service name based gRPC gateway route match. * * @default - no matching on service name */ readonly serviceName?: string; /** * Create host name based gRPC gateway route match. * * @default - no matching on host name */ readonly hostname?: GatewayRouteHostnameMatch; /** * Create metadata based gRPC gateway route match. * All specified metadata must match for the route to match. * * @default - no matching on metadata */ readonly metadata?: HeaderMatch[]; /** * When `true`, rewrites the original request received at the Virtual Gateway to the destination Virtual Service name. * When `false`, retains the original hostname from the request. * * @default true */ readonly rewriteRequestHostname?: boolean; } /** * Base options for all gateway route specs. */ export interface CommonGatewayRouteSpecOptions { /** * The priority for the gateway route. When a Virtual Gateway has multiple gateway routes, gateway route match * is performed in the order of specified value, where 0 is the highest priority, * and first matched gateway route is selected. * * @default - no particular priority */ readonly priority?: number; } /** * Properties specific for HTTP Based GatewayRoutes */ export interface HttpGatewayRouteSpecOptions extends CommonGatewayRouteSpecOptions { /** * The criterion for determining a request match for this GatewayRoute. * When path match is defined, this may optionally determine the path rewrite configuration. * * @default - matches any path and automatically rewrites the path to '/' */ readonly match?: HttpGatewayRouteMatch; /** * The VirtualService this GatewayRoute directs traffic to */ readonly routeTarget: IVirtualService; } /** * Properties specific for a gRPC GatewayRoute */ export interface GrpcGatewayRouteSpecOptions extends CommonGatewayRouteSpecOptions { /** * The criterion for determining a request match for this GatewayRoute */ readonly match: GrpcGatewayRouteMatch; /** * The VirtualService this GatewayRoute directs traffic to */ readonly routeTarget: IVirtualService; } /** * All Properties for GatewayRoute Specs */ export interface GatewayRouteSpecConfig { /** * The spec for an http gateway route * * @default - no http spec */ readonly httpSpecConfig?: CfnGatewayRoute.HttpGatewayRouteProperty; /** * The spec for an http2 gateway route * * @default - no http2 spec */ readonly http2SpecConfig?: CfnGatewayRoute.HttpGatewayRouteProperty; /** * The spec for a grpc gateway route * * @default - no grpc spec */ readonly grpcSpecConfig?: CfnGatewayRoute.GrpcGatewayRouteProperty; /** * The priority for the gateway route. When a Virtual Gateway has multiple gateway routes, gateway route match * is performed in the order of specified value, where 0 is the highest priority, * and first matched gateway route is selected. * * @default - no particular priority */ readonly priority?: number; } /** * Used to generate specs with different protocols for a GatewayRoute */ export abstract class GatewayRouteSpec { /** * Creates an HTTP Based GatewayRoute * * @param options - no http gateway route */ public static http(options: HttpGatewayRouteSpecOptions): GatewayRouteSpec { return new HttpGatewayRouteSpec(options, Protocol.HTTP); } /** * Creates an HTTP2 Based GatewayRoute * * @param options - no http2 gateway route */ public static http2(options: HttpGatewayRouteSpecOptions): GatewayRouteSpec { return new HttpGatewayRouteSpec(options, Protocol.HTTP2); } /** * Creates an gRPC Based GatewayRoute * * @param options - no grpc gateway route */ public static grpc(options: GrpcGatewayRouteSpecOptions): GatewayRouteSpec { return new GrpcGatewayRouteSpec(options); } /** * Called when the GatewayRouteSpec type is initialized. Can be used to enforce * mutual exclusivity with future properties */ public abstract bind(scope: Construct): GatewayRouteSpecConfig; } class HttpGatewayRouteSpec extends GatewayRouteSpec { readonly match?: HttpGatewayRouteMatch; /** * The VirtualService this GatewayRoute directs traffic to */ readonly routeTarget: IVirtualService; /** * Type of route you are creating */ readonly routeType: Protocol; readonly priority?: number; constructor(options: HttpGatewayRouteSpecOptions, protocol: Protocol.HTTP | Protocol.HTTP2) { super(); this.routeTarget = options.routeTarget; this.routeType = protocol; this.match = options.match; this.priority = options.priority; } public bind(scope: Construct): GatewayRouteSpecConfig { const pathMatchConfig = (this.match?.path ?? HttpGatewayRoutePathMatch.startsWith('/')).bind(scope); const rewriteRequestHostname = this.match?.rewriteRequestHostname; const prefixPathRewrite = pathMatchConfig.prefixPathRewrite; const wholePathRewrite = pathMatchConfig.wholePathRewrite; const httpConfig: CfnGatewayRoute.HttpGatewayRouteProperty = { match: { prefix: pathMatchConfig.prefixPathMatch, path: pathMatchConfig.wholePathMatch, hostname: this.match?.hostname?.bind(scope).hostnameMatch, method: this.match?.method, headers: this.match?.headers?.map(header => header.bind(scope).headerMatch), queryParameters: this.match?.queryParameters?.map(queryParameter => queryParameter.bind(scope).queryParameterMatch), }, action: { target: { virtualService: { virtualServiceName: this.routeTarget.virtualServiceName, }, }, rewrite: rewriteRequestHostname !== undefined || prefixPathRewrite || wholePathRewrite ? { hostname: rewriteRequestHostname === undefined ? undefined : { defaultTargetHostname: rewriteRequestHostname? 'ENABLED' : 'DISABLED', }, prefix: prefixPathRewrite, path: wholePathRewrite, } : undefined, }, }; return { priority: this.priority, httpSpecConfig: this.routeType === Protocol.HTTP ? httpConfig : undefined, http2SpecConfig: this.routeType === Protocol.HTTP2 ? httpConfig : undefined, }; } } class GrpcGatewayRouteSpec extends GatewayRouteSpec { readonly match: GrpcGatewayRouteMatch; /** * The VirtualService this GatewayRoute directs traffic to */ readonly routeTarget: IVirtualService; readonly priority?: number; constructor(options: GrpcGatewayRouteSpecOptions) { super(); this.match = options.match; this.routeTarget = options.routeTarget; this.priority = options.priority; } public bind(scope: Construct): GatewayRouteSpecConfig { const metadataMatch = this.match.metadata; validateGrpcGatewayRouteMatch(this.match); validateGrpcMatchArrayLength(metadataMatch); return { grpcSpecConfig: { match: { serviceName: this.match.serviceName, hostname: this.match.hostname?.bind(scope).hostnameMatch, metadata: metadataMatch?.map(metadata => metadata.bind(scope).headerMatch), }, action: { target: { virtualService: { virtualServiceName: this.routeTarget.virtualServiceName, }, }, rewrite: this.match.rewriteRequestHostname === undefined ? undefined : { hostname: { defaultTargetHostname: this.match.rewriteRequestHostname ? 'ENABLED' : 'DISABLED', }, }, }, }, priority: this.priority, }; } }
the_stack
import * as DomUtil from '../common/dom_util'; import {Engine} from '../common/engine'; import XpathUtil from '../common/xpath_util'; import {LOCALE} from '../l10n/locale'; import {Grammar} from '../rule_engine/grammar'; import * as StoreUtil from '../rule_engine/store_util'; import {SemanticAnnotations} from '../semantic_tree/semantic_annotations'; import {SemanticAnnotator} from '../semantic_tree/semantic_annotator'; import {SemanticAttr, SemanticRole, SemanticType} from '../semantic_tree/semantic_attr'; import {SemanticNode} from '../semantic_tree/semantic_node'; import {vulgarFractionSmall} from './numbers_util'; /** * Count list of nodes and concatenate this with the context string, adding a * colon at the end. * Returns a closure with a local state. * @param nodes A node array. * @param context A context string. * @return A function returning a string. */ export function nodeCounter(nodes: Node[], context: string|null): () => string { let split = context.split('-'); let func = StoreUtil.nodeCounter(nodes, split[0] || ''); let sep = split[1] || ''; let init = split[2] || ''; let first = true; return function() { let result = func(); if (first) { first = false; return init + result + sep; } else { return result + sep; } }; } /** * Predicate that implements the definition of a simple expression from the * ClearSpeak Rules manual p.10. Quote: * * 1. A number that is an integer, a decimal, or a fraction that is spoken as an * ordinal * * 2. A letter, two juxtaposed letters (e.g., x, y, z, xy, yz, etc.), the * negative of a letter, or the negative of two juxtaposed letters (e.g., -x , * -y , -z , -xy , -yz , etc.) * * 3. An integer, decimal, letter, or the negative of a letter that is followed * by the degree sign (e.g., 45° , -32.5° , x° , - x° ) * * 4. A number that is an integer, a decimal, or a fraction that is spoken as an * ordinal and is followed by a letter or pair of juxtaposed letters (e.g., 2x, * -3y , 4.1z, 2xy, -4 yz ) * * 5. A function (including trigonometric and logarithmic functions) with an * argument that is a simple expression (e.g., sin 2x , log y , f (x)) * * @param node The semantic node. * @return True if the node is a simple expression. */ export function isSimpleExpression(node: SemanticNode): boolean { return isSimpleNumber_(node) || isSimpleLetters_(node) || isSimpleDegree_(node) || isSimpleNegative_(node) || isSimpleFunction_(node); } /** * A function (including trigonometric and logarithmic functions) with an * argument that is a simple expression. * * (5, including nested functions and also embellished function symbols). * @param node The semantic node. * @return True if the node is a simple function. */ export function isSimpleFunction_(node: SemanticNode): boolean { return node.type === SemanticType.APPL && ( // The types are there for distinguishing non-embellished // functions. // TODO: (MS 2.3) Make this more robust, i.e., make sure the // embellished functions are only embellished with simple // expressions. node.childNodes[0].type === // SemanticType.FUNCTION && node.childNodes[0].role === SemanticRole.PREFIXFUNC || // node.childNodes[0].type === SemanticType.IDENTIFIER && node.childNodes[0].role === SemanticRole.SIMPLEFUNC) && (isSimple_(node.childNodes[1]) || node.childNodes[1].type === SemanticType.FENCED && isSimple_(node.childNodes[1].childNodes[0])); } /** * The negation of simple expression defined in item 1, 2, 4. * * (1 + 2 + 4, including negation). * @param node The semantic node. * @return True if the node is negated simple expression. */ export function isSimpleNegative_(node: SemanticNode): boolean { return node.type === SemanticType.PREFIXOP && node.role === SemanticRole.NEGATIVE && isSimple_(node.childNodes[0]) && node.childNodes[0].type !== SemanticType.PREFIXOP && node.childNodes[0].type !== SemanticType.APPL && node.childNodes[0].type !== SemanticType.PUNCTUATED; } /** * An integer, decimal, letter, or the negative of a letter that is followed by * the degree sign. * * (3, including negation). * @param node The semantic node. * @return True if the node is simple degree expression. */ export function isSimpleDegree_(node: SemanticNode): boolean { return node.type === SemanticType.PUNCTUATED && node.role === SemanticRole.ENDPUNCT && (node.childNodes.length === 2 && (node.childNodes[1].role === SemanticRole.DEGREE && (isLetter_(node.childNodes[0]) || isNumber_(node.childNodes[0]) || node.childNodes[0].type === SemanticType.PREFIXOP && node.childNodes[0].role === SemanticRole.NEGATIVE && (isLetter_(node.childNodes[0].childNodes[0]) || isNumber_(node.childNodes[0].childNodes[0]))))); } /** * A letter, two juxtaposed letters (e.g., x, y, z, xy, yz, etc.), or a number * that is an integer, a decimal, or a fraction that is spoken as an ordinal and * is followed by a letter or pair of juxtaposed letters. * * (2 + 4 without negation). * @param node The semantic node. * @return True if the node is simple non-negative letter expression. */ export function isSimpleLetters_(node: SemanticNode): boolean { return isLetter_(node) || node.type === SemanticType.INFIXOP && node.role === SemanticRole.IMPLICIT && (node.childNodes.length === 2 && (isLetter_(node.childNodes[0]) || isSimpleNumber_(node.childNodes[0])) && isLetter_(node.childNodes[1]) || node.childNodes.length === 3 && isSimpleNumber_(node.childNodes[0]) && isLetter_(node.childNodes[1]) && isLetter_(node.childNodes[2])); } /** * Node has a annotation indicating that it is a simple expression. * @param node The semantic node. * @return True if the node is already annotated as simple. */ export function isSimple_(node: SemanticNode): boolean { return node.hasAnnotation('clearspeak', 'simple'); } /** * Test for single letter. * @param node The semantic node. * @return True if the node is a single letter from any alphabet. */ export function isLetter_(node: SemanticNode): boolean { return node.type === SemanticType.IDENTIFIER && (node.role === SemanticRole.LATINLETTER || node.role === SemanticRole.GREEKLETTER || node.role === SemanticRole.OTHERLETTER || node.role === SemanticRole.SIMPLEFUNC); } /** * Tests if a number an integer or a decimal? * * (1 without negation). * @param node The semantic node. * @return True if the number is an integer or a decimal. */ export function isNumber_(node: SemanticNode): boolean { return node.type === SemanticType.NUMBER && (node.role === SemanticRole.INTEGER || node.role === SemanticRole.FLOAT); } /** * A number that is an integer, a decimal, or a fraction that is spoken as an * ordinal, but not negative. * @param node The semantic node. * @return True if node is number or a vulgar fraction. */ export function isSimpleNumber_(node: SemanticNode): boolean { return isNumber_(node) || isSimpleFraction_(node); } /** * A fraction that is spoken as an ordinal. * @param node The semantic node. * @return True if node is a vulgar fraction that would be spoken as * ordinal for the current preference settings. */ export function isSimpleFraction_(node: SemanticNode): boolean { if (hasPreference('Fraction_Over') || hasPreference('Fraction_FracOver')) { return false; } if (node.type !== SemanticType.FRACTION || node.role !== SemanticRole.VULGAR) { return false; } if (hasPreference('Fraction_Ordinal')) { return true; } let enumerator = parseInt(node.childNodes[0].textContent, 10); let denominator = parseInt(node.childNodes[1].textContent, 10); return enumerator > 0 && enumerator < 20 && denominator > 0 && denominator < 11; } /** * Checks for a preference setting. * @param pref The preference. * @return True of the given preference is set. */ export function hasPreference(pref: string): boolean { return Engine.getInstance().style === pref; } SemanticAnnotations.register( new SemanticAnnotator('clearspeak', 'simple', function(node) { return isSimpleExpression(node) ? 'simple' : ''; })); /** * Decides if node has markup of simple node in clearspeak. * @param node The node in question. * @return True if the node has a annotation entry of simple. */ export function simpleNode(node: Element): boolean { if (!node.hasAttribute('annotation')) { return false; } let annotation = node.getAttribute('annotation'); return !!/clearspeak:simple$|clearspeak:simple;/.exec(annotation); } /** * Predicate to decide if a node is a simple cell in a table. * @param node The node in question. * @return True if the node is a simple cell. */ export function simpleCell_(node: Element): boolean { if (simpleNode(node)) { return true; } // TODO: (Simons) This is a special case that has to be removed by rewriting // certain indices from implicit multiplication to punctuation. For clearspeak // this should yield a simple expression then. And have a subscript with index // role. if (node.tagName !== SemanticType.SUBSCRIPT) { return false; } let children = node.childNodes[0].childNodes; let index = children[1] as Element; return (children[0] as Element).tagName === SemanticType.IDENTIFIER && (isInteger_(index) || index.tagName === SemanticType.INFIXOP && index.hasAttribute('role') && index.getAttribute('role') === SemanticRole.IMPLICIT && allIndices_(index)); } /** * Decides if a node is an integer. * @param node The node in question. * @return True if the node is an integer. */ export function isInteger_(node: Element): boolean { return node.tagName === SemanticType.NUMBER && node.hasAttribute('role') && node.getAttribute('role') === SemanticRole.INTEGER; } /** * Decides if a node is an index structure, i.e., identifier or integer. * @param node The node in question. * @return True if the node is an index. */ export function allIndices_(node: Element): boolean { let nodes = XpathUtil.evalXPath('children/*', node); return nodes.every( (x: Element) => isInteger_(x) || x.tagName === SemanticType.IDENTIFIER ); } /** * Query function that decides if a table has only simple cells. * @param node The table node. * @return The node if the table only has simple cells. */ export function allCellsSimple(node: Element): Element[] { let xpath = node.tagName === SemanticType.MATRIX ? 'children/row/children/cell/children/*' : 'children/line/children/*'; let nodes = XpathUtil.evalXPath(xpath, node); let result = nodes.every(simpleCell_); return result ? [node] : []; } /** * Custom query function to check if a vulgar fraction is small enough to be * spoken as numbers in MathSpeak. * @param node Fraction node to be tested. * @return List containing the node if it is eligible. Otherwise * empty. */ export function isSmallVulgarFraction(node: Element): Element[] { return vulgarFractionSmall(node, 20, 11) ? [node] : []; } /** * Checks if a semantic subtree represents a unit expression. * @param node The semantic node in question. * @return True if the node is a unit expression. */ export function isUnitExpression(node: SemanticNode): boolean { return node.type === SemanticType.TEXT || node.type === SemanticType.PUNCTUATED && node.role === SemanticRole.TEXT && isNumber_(node.childNodes[0]) && allTextLastContent_(node.childNodes.slice(1)) || node.type === SemanticType.IDENTIFIER && node.role === SemanticRole.UNIT || node.type === SemanticType.INFIXOP && ( // TODO: Fix: Only integers are considered to be units. node.role === SemanticRole.IMPLICIT || node.role === SemanticRole.UNIT); } /** * Tests if all nodes a text nodes but only the last can be non-empty. * @param nodes A list of semantic nodes. * @return True if condition holds. */ export function allTextLastContent_(nodes: SemanticNode[]): boolean { for (let i = 0; i < nodes.length - 1; i++) { if (!(nodes[i].type === SemanticType.TEXT && nodes[i].textContent === '')) { return false; } } return nodes[nodes.length - 1].type === SemanticType.TEXT; } SemanticAnnotations.register( new SemanticAnnotator('clearspeak', 'unit', function(node) { return isUnitExpression(node) ? 'unit' : ''; })); /** * Translates a node into a word for an ordinal exponent. * @param node The node to translate. * @return The ordinal exponent as a word. */ export function ordinalExponent(node: Element): string { let num = parseInt(node.textContent, 10); if (isNaN(num)) { return node.textContent; } return num > 10 ? LOCALE.NUMBERS.simpleOrdinal(num) : LOCALE.NUMBERS.wordOrdinal(num); } export let NESTING_DEPTH: string|null = null; /** * Computes the nesting depth of a fenced expressions. * @param node The fenced node. * @return The nesting depth as an ordinal number. */ export function nestingDepth(node: Element): string|null { let count = 0; let fence = (node as Element).textContent; let index = node.getAttribute('role') === 'open' ? 0 : 1; let parent = node.parentNode as Element; while (parent) { if (parent.tagName === SemanticType.FENCED && parent.childNodes[0].childNodes[index].textContent === fence) { count++; } parent = parent.parentNode as Element; } NESTING_DEPTH = count > 1 ? LOCALE.NUMBERS.wordOrdinal(count) : ''; return NESTING_DEPTH; } /** * Query function for matching fences. * @param node The node to test. * @return The node if it has matching fences. */ export function matchingFences(node: Element): Element[] { let sibling = node.previousSibling; let left, right; if (sibling) { left = sibling; right = node; } else { left = node; right = node.nextSibling; } if (!right) { // this case should not happen! return []; } return SemanticAttr.isMatchingFence(left.textContent, right.textContent) ? [node] : []; } /** * Correction function for inserting nesting depth (second, third, etc.) between * open and close fence indicator. * @param text The original text, e.g., open paren, close paren. * @param correction The nesting depth as correction text. * @return The corrected text. E.g., open second paren. */ export function insertNesting(text: string, correction: string): string { if (!correction || !text) { return text; } let start = text.match(/^(open|close) /); if (!start) { return correction + ' ' + text; } return start[0] + correction + ' ' + text.substring(start[0].length); } Grammar.getInstance().setCorrection('insertNesting', insertNesting); /** * Query function that decides for an implicit times node, if it has fenced * arguments only. * @param node The implicit times node. * @return The node if it has fenced arguments only. */ export function fencedArguments(node: Element): Element[] { let content = DomUtil.toArray(node.parentNode.childNodes); let children = XpathUtil.evalXPath('../../children/*', node) as Element[]; let index = content.indexOf(node); return fencedFactor_(children[index]) || fencedFactor_(children[index + 1]) ? [node] : []; } /** * Query function that decides for an implicit times node, if it has simple (in * the clearspeak sense) arguments only. * @param node The implicit times node. * @return The node if it has at most three simple arguments. */ export function simpleArguments(node: Element): Element[] { let content = DomUtil.toArray(node.parentNode.childNodes); let children = XpathUtil.evalXPath('../../children/*', node) as Element[]; let index = content.indexOf(node); return simpleFactor_(children[index]) && children[index + 1] && (simpleFactor_(children[index + 1]) || children[index + 1].tagName === SemanticType.ROOT || children[index + 1].tagName === SemanticType.SQRT || children[index + 1].tagName === SemanticType.SUPERSCRIPT && children[index + 1].childNodes[0].childNodes[0] && ((children[index + 1].childNodes[0].childNodes[0] as Element).tagName === SemanticType.NUMBER || (children[index + 1].childNodes[0].childNodes[0] as Element).tagName === SemanticType.IDENTIFIER) && (children[index + 1].childNodes[0].childNodes[1].textContent === '2' || children[index + 1].childNodes[0].childNodes[1].textContent === '3')) ? [node] : []; } /** * Decides if node has a simple factor. * @param node The node in question. * @return True if the node is a number, identifier, function or * applicatio or a fraction. */ export function simpleFactor_(node: Element): boolean { return !!node && (node.tagName === SemanticType.NUMBER || node.tagName === SemanticType.IDENTIFIER || node.tagName === SemanticType.FUNCTION || node.tagName === SemanticType.APPL || // This works as fractions take care of their own // surrounding pauses! node.tagName === SemanticType.FRACTION); } /** * Decides if node has a fenced factor expression. * @param node The node in question. * @return True if the node is a fenced on both sides or a matrix or * vector. */ export function fencedFactor_(node: Element): boolean { return node && (node.tagName === SemanticType.FENCED || node.hasAttribute('role') && node.getAttribute('role') === SemanticRole.LEFTRIGHT || layoutFactor_(node)); } /** * Decides if node has a layout factor, i.e., matrix or vector. * @param node The node in question. * @return True if the node is a matrix or vector. */ export function layoutFactor_(node: Element): boolean { return !!node && (node.tagName === SemanticType.MATRIX || node.tagName === SemanticType.VECTOR); } // TODO: Move this into the number utils. /** * Translates a node into a word for an ordinal number. * @param node The node to translate. * @return The ordinal as a word. */ export function wordOrdinal(node: Element): string { return LOCALE.NUMBERS.wordOrdinal(parseInt(node.textContent, 10)); }
the_stack
namespace gdjs { import PIXI = GlobalPIXIModule.PIXI; const defaultBitmapFontKey = 'GDJS-DEFAULT-BITMAP-FONT'; // When a font is unused, we put it in a cache of unused fonts. It's unloaded // from memory only when the cache is full and the font is at the last position // in the cache. // Set this to 0 to unload from memory ("uninstall") as soon as a font is unused. const uninstallCacheSize = 5; /** * We patch the installed font to use a name that is unique for each font data and texture, * to avoid conflicts between different font files using the same font name (by default, the * font name used by Pixi is the one inside the font data, but this name is not necessarily unique. * For example, 2 resources can use the same font, or we can have multiple objects with the same * font data and different textures). */ const patchInstalledBitmapFont = ( bitmapFont: PIXI.BitmapFont, bitmapFontInstallKey: string ) => { const defaultName = bitmapFont.font; // @ts-ignore - we "hack" into Pixi to change the font name bitmapFont.font = bitmapFontInstallKey; PIXI.BitmapFont.available[bitmapFontInstallKey] = bitmapFont; delete PIXI.BitmapFont.available[defaultName]; return PIXI.BitmapFont.available[bitmapFontInstallKey]; }; /** * PixiBitmapFontManager loads fnt/xml files (using `fetch`), from the "bitmapFont" resources of the game. * * It installs the "BitmapFont" with PixiJS to be used with PIXI.BitmapText. */ export class PixiBitmapFontManager { private _resources: ResourceData[]; private _imageManager: gdjs.PixiImageManager; /** Pixi.BitmapFont used, indexed by their BitmapFont name. */ private _pixiBitmapFontsInUse: Record< string, { objectsUsingTheFont: number } > = {}; /** Pixi.BitmapFont not used anymore, but not yet uninstalled, indexed by their BitmapFont name. */ private _pixiBitmapFontsToUninstall: string[] = []; /** Loaded fonts data, indexed by resource name. */ private _loadedFontsData: Record<string, any> = {}; private _defaultSlugFontName: string | null = null; /** * @param resources The resources data of the game. * @param imageManager The image manager to be used to get textures used by fonts. */ constructor( resources: ResourceData[], imageManager: gdjs.PixiImageManager ) { this._resources = resources; this._imageManager = imageManager; } /** * Get the instance of the default `Pixi.BitmapFont`, always available. */ getDefaultBitmapFont() { if (this._defaultSlugFontName !== null) { return PIXI.BitmapFont.available[this._defaultSlugFontName]; } // Default bitmap font style const fontFamily = 'Arial'; const bitmapFontStyle = new PIXI.TextStyle({ fontFamily: fontFamily, fontSize: 20, padding: 5, align: 'left', fill: '#ffffff', wordWrap: true, lineHeight: 20, }); // Generate default bitmapFont, and replace the name of PIXI.BitmapFont by a unique name const defaultBitmapFont = patchInstalledBitmapFont( PIXI.BitmapFont.from(fontFamily, bitmapFontStyle, { // All the printable ASCII characters chars: [[' ', '~']], }), defaultBitmapFontKey ); // Define the default name used for the default bitmap font. this._defaultSlugFontName = defaultBitmapFont.font; return defaultBitmapFont; } /** * Update the resources data of the game. Useful for hot-reloading, should not be used otherwise. * @param resources The resources data of the game. */ setResources(resources: ResourceData[]): void { this._resources = resources; } /** * Called to specify that the bitmap font with the specified key is used by an object * (i.e: this is reference counting). * `releaseBitmapFont` *must* be called to mark the font as not used anymore when the * object is destroyed or its font changed. * * @param bitmapFontInstallKey Name of the font of the BitmapFont (`bitmapFont.font`) */ private _markBitmapFontAsUsed(bitmapFontInstallKey: string): void { this._pixiBitmapFontsInUse[bitmapFontInstallKey] = this ._pixiBitmapFontsInUse[bitmapFontInstallKey] || { objectsUsingTheFont: 0, }; this._pixiBitmapFontsInUse[bitmapFontInstallKey].objectsUsingTheFont++; for (let i = 0; i < this._pixiBitmapFontsToUninstall.length; ) { if (this._pixiBitmapFontsToUninstall[i] === bitmapFontInstallKey) { // The font is in the cache of fonts to uninstall, because it was previously used and then marked as not used anymore. // Remove it from the cache to avoid the font getting uninstalled. this._pixiBitmapFontsToUninstall.splice(i, 1); } else { i++; } } } /** * When a font is not used by an object anymore (object destroyed or font changed), * call this function to decrease the internal count of objects using the font. * * When a font is not unused anymore, it goes in a temporary cache. The cache holds up to 10 fonts. * If the cache reaches its maximum capacity, the oldest font is uninstalled from memory. * * @param bitmapFontInstallKey Name of the font of the BitmapFont (`bitmapFont.font`) */ releaseBitmapFont(bitmapFontInstallKey: string) { if (bitmapFontInstallKey === defaultBitmapFontKey) { // Never uninstall the default font. return; } if (!this._pixiBitmapFontsInUse[bitmapFontInstallKey]) { console.error( 'BitmapFont with name ' + bitmapFontInstallKey + ' was tried to be released but was never marked as used.' ); return; } this._pixiBitmapFontsInUse[bitmapFontInstallKey].objectsUsingTheFont--; if ( this._pixiBitmapFontsInUse[bitmapFontInstallKey].objectsUsingTheFont === 0 ) { delete this._pixiBitmapFontsInUse[bitmapFontInstallKey]; // Add the font name at the last position of the cache. if (!this._pixiBitmapFontsToUninstall.includes(bitmapFontInstallKey)) { this._pixiBitmapFontsToUninstall.push(bitmapFontInstallKey); } if (this._pixiBitmapFontsToUninstall.length > uninstallCacheSize) { // Remove the first font (i.e: the oldest one) const oldestUnloadedPixiBitmapFontName = this._pixiBitmapFontsToUninstall.shift() as string; PIXI.BitmapFont.uninstall(oldestUnloadedPixiBitmapFontName); console.log( 'Uninstalled BitmapFont "' + oldestUnloadedPixiBitmapFontName + '" from memory.' ); } } } /** * Given a bitmap font resource name and a texture atlas resource name, returns the PIXI.BitmapFont * for it. * The font is register and should be released with `releaseBitmapFont` - so that it can be removed * from memory when unused. */ obtainBitmapFont( bitmapFontResourceName: string, textureAtlasResourceName: string ): PIXI.BitmapFont { const bitmapFontInstallKey = bitmapFontResourceName + '@' + textureAtlasResourceName; if (PIXI.BitmapFont.available[bitmapFontInstallKey]) { // Return the existing BitmapFont that is already in memory and already installed. this._markBitmapFontAsUsed(bitmapFontInstallKey); return PIXI.BitmapFont.available[bitmapFontInstallKey]; } // The Bitmap Font is not loaded, load it in memory. // First get the font data: const fontData = this._loadedFontsData[bitmapFontResourceName]; if (!fontData) { console.warn( 'Could not find Bitmap Font for resource named "' + bitmapFontResourceName + '". The default font will be used.' ); return this.getDefaultBitmapFont(); } // Get the texture to be used in the font: const texture = this._imageManager.getPIXITexture( textureAtlasResourceName ); try { // Create and install the Pixi.BitmapFont in memory: const bitmapFont = patchInstalledBitmapFont( PIXI.BitmapFont.install(fontData, texture), bitmapFontInstallKey ); this._markBitmapFontAsUsed(bitmapFontInstallKey); return bitmapFont; } catch (error) { console.warn( 'Could not load the Bitmap Font for resource named "' + bitmapFontResourceName + '". The default font will be used. Error is: ' + error ); return this.getDefaultBitmapFont(); } } /** * Load the "bitmapFont" resources of the game, so that they are ready * to be used when `obtainBitmapFont` is called. */ loadBitmapFontData( onProgress: (count: integer, total: integer) => void ): Promise<void[]> { const bitmapFontResources = this._resources.filter( (resource) => resource.kind === 'bitmapFont' && !resource.disablePreload ); if (bitmapFontResources.length === 0) { return Promise.resolve([]); } let loadedCount = 0; return Promise.all( bitmapFontResources.map((bitmapFontResource) => { return fetch(bitmapFontResource.file) .then((response) => response.text()) .then((fontData) => { this._loadedFontsData[bitmapFontResource.name] = fontData; }) .catch((error) => { console.error( "Can't fetch the bitmap font file " + bitmapFontResource.file + ', error: ' + error ); }) .then(() => { loadedCount++; onProgress(loadedCount, bitmapFontResources.length); }); }) ); } } // Register the class to let the engine use it. export const BitmapFontManager = gdjs.PixiBitmapFontManager; export type BitmapFontManager = gdjs.PixiBitmapFontManager; }
the_stack
import request from 'supertest'; import { patch, unpatch } from '../../services/patch'; import { gatewayApp } from '../../../src/app'; import { NETWORK_ERROR_CODE, OUT_OF_GAS_ERROR_CODE, UNKNOWN_ERROR_ERROR_CODE, NETWORK_ERROR_MESSAGE, OUT_OF_GAS_ERROR_MESSAGE, UNKNOWN_ERROR_MESSAGE, } from '../../../src/services/error-handler'; import * as transactionSuccesful from '../ethereum/fixtures/transaction-succesful.json'; import * as transactionSuccesfulReceipt from '../ethereum//fixtures/transaction-succesful-receipt.json'; import * as transactionOutOfGas from '../ethereum//fixtures/transaction-out-of-gas.json'; import * as transactionOutOfGasReceipt from '../ethereum/fixtures/transaction-out-of-gas-receipt.json'; import { Avalanche } from '../../../src/chains/avalanche/avalanche'; const avalanche = Avalanche.getInstance('fuji'); afterEach(unpatch); const address: string = '0xFaA12FD102FE8623C9299c72B03E45107F2772B5'; const patchGetWallet = () => { patch(avalanche, 'getWallet', () => { return { address, }; }); }; const patchGetNonce = () => { patch(avalanche.nonceManager, 'getNonce', () => 2); }; const patchGetTokenBySymbol = () => { patch(avalanche, 'getTokenBySymbol', () => { return { chainId: 43114, address: '0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7', decimals: 18, name: 'Wrapped AVAX', symbol: 'WAVAX', logoURI: 'https://raw.githubusercontent.com/ava-labs/bridge-tokens/main/avalanche-tokens/0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7/logo.png', }; }); }; const patchApproveERC20 = () => { patch(avalanche, 'approveERC20', () => { return { type: 2, chainId: 43114, nonce: 115, maxPriorityFeePerGas: { toString: () => '106000000000' }, maxFeePerGas: { toString: () => '106000000000' }, gasPrice: { toString: () => null }, gasLimit: { toString: () => '100000' }, to: '0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa', value: { toString: () => '0' }, data: '0x095ea7b30000000000000000000000007a250d5630b4cf539739df2c5dacb4c659f2488dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', // noqa: mock accessList: [], hash: '0x75f98675a8f64dcf14927ccde9a1d59b67fa09b72cc2642ad055dae4074853d9', // noqa: mock v: 0, r: '0xbeb9aa40028d79b9fdab108fcef5de635457a05f3a254410414c095b02c64643', // noqa: mock s: '0x5a1506fa4b7f8b4f3826d8648f27ebaa9c0ee4bd67f569414b8cd8884c073100', // noqa: mock from: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', confirmations: 0, }; }); }; const patchGetERC20Allowance = () => { patch(avalanche, 'getERC20Allowance', () => ({ value: 1, decimals: 3 })); }; const patchGetNativeBalance = () => { patch(avalanche, 'getNativeBalance', () => ({ value: 1, decimals: 3 })); }; const patchGetERC20Balance = () => { patch(avalanche, 'getERC20Balance', () => ({ value: 1, decimals: 3 })); }; describe('POST /evm/nonce', () => { it('should return 200', async () => { patchGetWallet(); patchGetNonce(); await request(gatewayApp) .post(`/evm/nonce`) .send({ chain: 'avalanche', network: 'fuji', address, }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect((res) => expect(res.body.nonce).toBe(2)); }); it('should return 404 when parameters are invalid', async () => { await request(gatewayApp) .post(`/evm/nonce`) .send({ chain: 'avalanche', network: 'fuji', address: 'da857cbda0ba96757fed842617a4', }) .expect(404); }); }); describe('POST /evm/approve', () => { it('should return 200', async () => { patchGetWallet(); avalanche.getContract = jest.fn().mockReturnValue({ address, }); patch(avalanche.nonceManager, 'getNonce', () => 115); patchGetTokenBySymbol(); patchApproveERC20(); await request(gatewayApp) .post(`/evm/approve`) .send({ chain: 'avalanche', network: 'fuji', address, spender: 'pangolin', token: 'PNG', }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((res: any) => { expect(res.body.nonce).toEqual(115); }); }); it('should return 404 when parameters are invalid', async () => { await request(gatewayApp) .post(`/evm/approve`) .send({ chain: 'avalanche', network: 'fuji', address, spender: 'pangolin', token: 123, nonce: '23', }) .expect(404); }); }); describe('POST /evm/allowances', () => { it('should return 200 asking for allowances', async () => { patchGetWallet(); patchGetTokenBySymbol(); const spender = '0xFaA12FD102FE8623C9299c72B03E45107F2772B5'; avalanche.getSpender = jest.fn().mockReturnValue(spender); avalanche.getContract = jest.fn().mockReturnValue({ address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }); patchGetERC20Allowance(); await request(gatewayApp) .post(`/evm/allowances`) .send({ chain: 'avalanche', network: 'fuji', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', spender: spender, tokenSymbols: ['WETH', 'DAI'], }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect((res) => expect(res.body.spender).toEqual(spender)) .expect((res) => expect(res.body.approvals.WETH).toEqual('0.001')) .expect((res) => expect(res.body.approvals.DAI).toEqual('0.001')); }); }); describe('POST /network/balances', () => { it('should return 200 asking for supported tokens', async () => { patchGetWallet(); patchGetTokenBySymbol(); patchGetNativeBalance(); patchGetERC20Balance(); avalanche.getContract = jest.fn().mockReturnValue({ address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', }); await request(gatewayApp) .post(`/network/balances`) .send({ chain: 'avalanche', network: 'fuji', address: '0xFaA12FD102FE8623C9299c72B03E45107F2772B5', tokenSymbols: ['WETH', 'DAI'], }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .expect((res) => expect(res.body.balances.WETH).toBeDefined()) .expect((res) => expect(res.body.balances.DAI).toBeDefined()); }); }); describe('POST /evm/cancel', () => { it('should return 200', async () => { // override getWallet (network call) avalanche.getWallet = jest.fn().mockReturnValue({ address, }); avalanche.cancelTx = jest.fn().mockReturnValue({ hash: '0xf6b9e7cec507cb3763a1179ff7e2a88c6008372e3a6f297d9027a0b39b0fff77', // noqa: mock }); await request(gatewayApp) .post(`/evm/cancel`) .send({ chain: 'avalanche', network: 'fuji', address, nonce: 23, }) .set('Accept', 'application/json') .expect('Content-Type', /json/) .expect(200) .then((res: any) => { expect(res.body.txHash).toEqual( '0xf6b9e7cec507cb3763a1179ff7e2a88c6008372e3a6f297d9027a0b39b0fff77' // noqa: mock ); }); }); it('should return 404 when parameters are invalid', async () => { await request(gatewayApp) .post(`/evm/cancel`) .send({ chain: 'avalanche', network: 'fuji', address: '', nonce: '23', }) .expect(404); }); }); describe('POST /network/poll', () => { it('should get a NETWORK_ERROR_CODE when the network is unavailable', async () => { patch(avalanche, 'getCurrentBlockNumber', () => { const error: any = new Error('something went wrong'); error.code = 'NETWORK_ERROR'; throw error; }); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'avalanche', network: 'fuji', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(NETWORK_ERROR_CODE); expect(res.body.message).toEqual(NETWORK_ERROR_MESSAGE); }); it('should get a UNKNOWN_ERROR_ERROR_CODE when an unknown error is thrown', async () => { patch(avalanche, 'getCurrentBlockNumber', () => { throw new Error(); }); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'avalanche', network: 'fuji', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(UNKNOWN_ERROR_ERROR_CODE); }); it('should get an OUT of GAS error for failed out of gas transactions', async () => { patch(avalanche, 'getCurrentBlockNumber', () => 1); patch(avalanche, 'getTransaction', () => transactionOutOfGas); patch(avalanche, 'getTransactionReceipt', () => transactionOutOfGasReceipt); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'avalanche', network: 'fuji', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(OUT_OF_GAS_ERROR_CODE); expect(res.body.message).toEqual(OUT_OF_GAS_ERROR_MESSAGE); }); it('should get a null in txReceipt for Tx in the mempool', async () => { patch(avalanche, 'getCurrentBlockNumber', () => 1); patch(avalanche, 'getTransaction', () => transactionOutOfGas); patch(avalanche, 'getTransactionReceipt', () => null); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'avalanche', network: 'fuji', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(200); expect(res.body.txReceipt).toEqual(null); expect(res.body.txData).toBeDefined(); }); it('should get a null in txReceipt and txData for Tx that didnt reach the mempool and TxReceipt is null', async () => { patch(avalanche, 'getCurrentBlockNumber', () => 1); patch(avalanche, 'getTransaction', () => null); patch(avalanche, 'getTransactionReceipt', () => null); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'avalanche', network: 'fuji', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(200); expect(res.body.txReceipt).toEqual(null); expect(res.body.txData).toEqual(null); }); it('should get txStatus = 1 for a succesful query', async () => { patch(avalanche, 'getCurrentBlockNumber', () => 1); patch(avalanche, 'getTransaction', () => transactionSuccesful); patch( avalanche, 'getTransactionReceipt', () => transactionSuccesfulReceipt ); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'avalanche', network: 'fuji', txHash: '0x6d068067a5e5a0f08c6395b31938893d1cdad81f54a54456221ecd8c1941294d', // noqa: mock }); expect(res.statusCode).toEqual(200); expect(res.body.txReceipt).toBeDefined(); expect(res.body.txData).toBeDefined(); }); it('should get unknown error', async () => { patch(avalanche, 'getCurrentBlockNumber', () => { const error: any = new Error('something went wrong'); error.code = -32006; throw error; }); const res = await request(gatewayApp).post('/network/poll').send({ chain: 'avalanche', network: 'fuji', txHash: '0x2faeb1aa55f96c1db55f643a8cf19b0f76bf091d0b7d1b068d2e829414576362', // noqa: mock }); expect(res.statusCode).toEqual(503); expect(res.body.errorCode).toEqual(UNKNOWN_ERROR_ERROR_CODE); expect(res.body.message).toEqual(UNKNOWN_ERROR_MESSAGE); }); });
the_stack
import { ArgumentDefinition, InputObjectType, InputType, isBooleanType, isCustomScalarType, isEnumType, isFloatType, isIDType, isInputObjectType, isIntType, isListType, isNonNullType, isScalarType, isStringType, isVariable, Variable, VariableDefinition, VariableDefinitions, Variables } from './definitions'; import { ArgumentNode, GraphQLError, Kind, print, ValueNode } from 'graphql'; import { didYouMean, suggestionList } from './suggestions'; import { inspect } from 'util'; import { sameType } from './types'; import { assert } from './utils'; // Per-GraphQL spec, max and value for an Int type. const MAX_INT = 2147483647; const MIN_INT = -2147483648; export function valueToString(v: any, expectedType?: InputType): string { if (v === undefined || v === null) { if (expectedType && isNonNullType(expectedType)) { throw buildError(`Invalid undefined/null value for non-null type ${expectedType}`); } return "null"; } if (expectedType && isNonNullType(expectedType)) { expectedType = expectedType.ofType; } if (expectedType && isCustomScalarType(expectedType)) { // If the expected type is a custom scalar, we can't really infer anything from it. expectedType = undefined; } if (isVariable(v)) { return v.toString(); } if (Array.isArray(v)) { let elementsType: InputType | undefined = undefined; if (expectedType) { if (!isListType(expectedType)) { throw buildError(`Invalid list value for non-list type ${expectedType}`); } elementsType = expectedType.ofType; } return '[' + v.map(e => valueToString(e, elementsType)).join(', ') + ']'; } if (typeof v === 'object') { if (expectedType && !isInputObjectType(expectedType)) { throw buildError(`Invalid object value for non-input-object type ${expectedType} (isCustomScalar? ${isCustomScalarType(expectedType)})`); } return '{' + Object.keys(v).map(k => { const valueType = expectedType ? (expectedType as InputObjectType).field(k)?.type : undefined; return `${k}: ${valueToString(v[k], valueType)}`; }).join(', ') + '}'; } if (typeof v === 'string') { if (expectedType) { if (isEnumType(expectedType)) { return v; } if (expectedType === expectedType.schema().idType() && integerStringRegExp.test(v)) { return v; } } return JSON.stringify(v); } return String(v); } // Fundamentally a deep-equal, but the generic 'deep-equal' was showing up on profiling and // as we know our values can only so many things, we can do faster fairly simply. export function valueEquals(a: any, b: any): boolean { if (a === b) { return true; } if (Array.isArray(a)) { return Array.isArray(b) && arrayValueEquals(a, b) ; } if (typeof a === 'object') { return typeof b === 'object' && objectEquals(a, b); } return a === b; } function arrayValueEquals(a: any[], b: any[]): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; ++i) { if (!valueEquals(a[i], b[i])) { return false; } } return true; } function objectEquals(a: {[key: string]: any}, b: {[key: string]: any}): boolean { const keys1 = Object.keys(a); const keys2 = Object.keys(b); if (keys1.length != keys2.length) { return false; } for (const key of keys1) { const v1 = a[key]; const v2 = b[key]; // Beware of false-negative due to getting undefined because the property is not // in args2. if (v2 === undefined) { return v1 === undefined && b.hasOwnProperty(key); } if (!valueEquals(v1, v2)) { return false; } } return true; } export function argumentsEquals(args1: {[key: string]: any}, args2: {[key: string]: any}): boolean { if (args1 === args2) { return true; } return objectEquals(args1, args2); } function buildError(message: string): Error { // Maybe not the right error for this? return new Error(message); } function applyDefaultValues(value: any, type: InputType): any { if (isVariable(value)) { return value; } if (value === null) { if (isNonNullType(type)) { throw new GraphQLError(`Invalid null value for non-null type ${type} while computing default values`); } return null; } if (isNonNullType(type)) { return applyDefaultValues(value, type.ofType); } if (isListType(type)) { if (Array.isArray(value)) { return value.map(v => applyDefaultValues(v, type.ofType)); } else { return applyDefaultValues(value, type.ofType); } } if (isInputObjectType(type)) { if (typeof value !== 'object') { throw new GraphQLError(`Expected value for type ${type} to be an object, but is ${typeof value}.`); } const updated = Object.create(null); for (const field of type.fields()) { if (!field.type) { throw buildError(`Cannot compute default value for field ${field.name} of ${type} as the field type is undefined`); } const fieldValue = value[field.name]; if (fieldValue === undefined) { if (field.defaultValue !== undefined) { updated[field.name] = applyDefaultValues(field.defaultValue, field.type); } else if (isNonNullType(field.type)) { throw new GraphQLError(`Field "${field.name}" of required type ${type} was not provided.`); } } else { updated[field.name] = applyDefaultValues(fieldValue, field.type); } } // Ensure every provided field is defined. for (const fieldName of Object.keys(value)) { if (!type.field(fieldName)) { const suggestions = suggestionList(fieldName, type.fields().map(f => f.name)); throw new GraphQLError(`Field "${fieldName}" is not defined by type "${type}".` + didYouMean(suggestions)); } } return updated; } return value; } export function withDefaultValues(value: any, argument: ArgumentDefinition<any>): any { if (!argument.type) { throw buildError(`Cannot compute default value for argument ${argument} as the type is undefined`); } if (value === undefined) { if (argument.defaultValue) { return applyDefaultValues(argument.defaultValue, argument.type); } } return applyDefaultValues(value, argument.type); } const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; // Adapted from the `astFromValue` function in graphQL-js export function valueToAST(value: any, type: InputType): ValueNode | undefined { if (value === undefined) { return undefined; } if (isNonNullType(type)) { const astValue = valueToAST(value, type.ofType); if (astValue?.kind === Kind.NULL) { throw buildError(`Invalid null value ${valueToString(value)} for non-null type ${type}`); } return astValue; } // only explicit null, not undefined, NaN if (value === null) { return { kind: Kind.NULL }; } if (isVariable(value)) { return { kind: Kind.VARIABLE, name: { kind: Kind.NAME, value: value.name } }; } if (isCustomScalarType(type)) { return valueToASTUntyped(value); } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but // the value is not an array, convert the value using the list's item type. if (isListType(type)) { const itemType: InputType = type.ofType; const items = Array.from(value); if (items != null) { const valuesNodes = []; for (const item of items) { const itemNode = valueToAST(item, itemType); if (itemNode != null) { valuesNodes.push(itemNode); } } return { kind: Kind.LIST, values: valuesNodes }; } return valueToAST(value, itemType); } // Populate the fields of the input object by creating ASTs from each value // in the JavaScript object according to the fields in the input type. if (isInputObjectType(type)) { if (typeof value !== 'object') { throw buildError(`Invalid non-objet value for input type ${type}, cannot be converted to AST: ${inspect(value, true, 10, true)}`); } const fieldNodes = []; for (const field of type.fields()) { if (!field.type) { throw buildError(`Cannot convert value ${valueToString(value)} as field ${field} has no type set`); } const fieldValue = valueToAST(value[field.name], field.type); if (fieldValue) { fieldNodes.push({ kind: Kind.OBJECT_FIELD, name: { kind: Kind.NAME, value: field.name }, value: fieldValue, }); } } return { kind: Kind.OBJECT, fields: fieldNodes }; } // TODO: we may have to handle some coercions (not sure it matters in our use case // though). if (typeof value === 'boolean') { return { kind: Kind.BOOLEAN, value: value }; } if (typeof value === 'number' && isFinite(value)) { const stringNum = String(value); return integerStringRegExp.test(stringNum) ? { kind: Kind.INT, value: stringNum } : { kind: Kind.FLOAT, value: stringNum }; } if (typeof value === 'string') { // Enum types use Enum literals. if (isEnumType(type)) { return { kind: Kind.ENUM, value: value }; } // ID types can use Int literals. if (type === type.schema().idType() && integerStringRegExp.test(value)) { return { kind: Kind.INT, value: value }; } return { kind: Kind.STRING, value: value, }; } throw buildError(`Invalid value for type ${type}, cannot be converted to AST: ${inspect(value)}`); } function valueToASTUntyped(value: any): ValueNode | undefined { if (value === undefined) { return undefined; } if (value === null) { return { kind: Kind.NULL }; } if (isVariable(value)) { return { kind: Kind.VARIABLE, name: { kind: Kind.NAME, value: value.name } }; } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but // the value is not an array, convert the value using the list's item type. if (Array.isArray(value)) { const valuesNodes = []; for (const item of value) { const itemNode = valueToASTUntyped(item); if (itemNode !== undefined) { valuesNodes.push(itemNode); } } return { kind: Kind.LIST, values: valuesNodes }; } if (typeof value === 'object') { const fieldNodes = []; for (const key of Object.keys(value)) { const fieldValue = valueToASTUntyped(value[key]); if (fieldValue) { fieldNodes.push({ kind: Kind.OBJECT_FIELD, name: { kind: Kind.NAME, value: key }, value: fieldValue, }); } } return { kind: Kind.OBJECT, fields: fieldNodes }; } if (typeof value === 'boolean') { return { kind: Kind.BOOLEAN, value: value }; } if (typeof value === 'number' && isFinite(value)) { const stringNum = String(value); return integerStringRegExp.test(stringNum) ? { kind: Kind.INT, value: stringNum } : { kind: Kind.FLOAT, value: stringNum }; } if (typeof value === 'string') { return { kind: Kind.STRING, value: value }; } throw buildError(`Invalid value, cannot be converted to AST: ${inspect(value, true, 10, true)}`); } // see https://spec.graphql.org/draft/#IsVariableUsageAllowed() function isValidVariable(variable: VariableDefinition, locationType: InputType, locationDefault: any): boolean { const variableType = variable.type; if (isNonNullType(locationType) && !isNonNullType(variableType)) { const hasVariableDefault = variable.defaultValue !== undefined && variable.defaultValue !== null; const hasLocationDefault = locationDefault !== undefined; if (!hasVariableDefault && !hasLocationDefault) { return false; } return areTypesCompatible(variableType, locationType.ofType); } return areTypesCompatible(variableType, locationType); } // see https://spec.graphql.org/draft/#AreTypesCompatible() function areTypesCompatible(variableType: InputType, locationType: InputType): boolean { if (isNonNullType(locationType)) { if (!isNonNullType(variableType)) { return false; } return areTypesCompatible(variableType.ofType, locationType.ofType); } if (isNonNullType(variableType)) { return areTypesCompatible(variableType.ofType, locationType); } if (isListType(locationType)) { if (!isListType(variableType)) { return false; } return areTypesCompatible(variableType.ofType, locationType.ofType); } return !isListType(variableType) && sameType(variableType, locationType); } export function isValidValue(value: any, argument: ArgumentDefinition<any>, variableDefinitions: VariableDefinitions): boolean { return isValidValueApplication(value, argument.type!, argument.defaultValue, variableDefinitions); } function isValidValueApplication(value: any, locationType: InputType, locationDefault: any, variableDefinitions: VariableDefinitions): boolean { // Note that this needs to be first, or the recursive call within 'isNonNullType' would break for variables if (isVariable(value)) { const definition = variableDefinitions.definition(value); return !!definition && isValidVariable(definition, locationType, locationDefault); } if (isNonNullType(locationType)) { return value !== null && isValidValueApplication(value, locationType.ofType, undefined, variableDefinitions); } if (value === null || value === undefined) { return true; } if (isCustomScalarType(locationType)) { // There is no imposition on what a custom scalar value can be. return true; } if (isListType(locationType)) { const itemType: InputType = locationType.ofType; if (Array.isArray(value)) { return value.every(item => isValidValueApplication(item, itemType, undefined, variableDefinitions)); } // Equivalent of coercing non-null element as a list of one. return isValidValueApplication(value, itemType, locationDefault, variableDefinitions); } if (isInputObjectType(locationType)) { if (typeof value !== 'object') { return false; } const isValid = locationType.fields().every(field => isValidValueApplication(value[field.name], field.type!, undefined, variableDefinitions)); return isValid; } // TODO: we may have to handle some coercions (not sure it matters in our use case // though). const schema = locationType.schema(); if (typeof value === 'boolean') { return locationType === schema.booleanType(); } if (typeof value === 'number' && isFinite(value)) { const stringNum = String(value); if (locationType === schema.intType() || locationType === schema.idType()) { return integerStringRegExp.test(stringNum); } return locationType === schema.floatType(); } if (typeof value === 'string') { if (isEnumType(locationType)) { return locationType.value(value) !== undefined; } return isScalarType(locationType) && locationType !== schema.booleanType() && locationType !== schema.intType() && locationType !== schema.floatType(); } return false; } export function valueFromAST(node: ValueNode, expectedType: InputType): any { if (node.kind === Kind.NULL) { if (isNonNullType(expectedType)) { throw new GraphQLError(`Invalid null value for non-null type "${expectedType}"`); } return null; } if (node.kind === Kind.VARIABLE) { return new Variable(node.name.value); } if (isNonNullType(expectedType)) { expectedType = expectedType.ofType; } if (isListType(expectedType)) { const baseType = expectedType.ofType; if (node.kind === Kind.LIST) { return node.values.map(v => valueFromAST(v, baseType)); } return [valueFromAST(node, baseType)]; } if (isIntType(expectedType)) { if (node.kind !== Kind.INT) { throw new GraphQLError(`Int cannot represent non-integer value ${print(node)}.`); } const i = parseInt(node.value, 10); if (i > MAX_INT || i < MIN_INT) { throw new GraphQLError(`Int cannot represent non 32-bit signed integer value ${i}.`); } return i; } if (isFloatType(expectedType)) { let parsed: number; if (node.kind === Kind.INT) { parsed = parseInt(node.value, 10); } else if (node.kind === Kind.FLOAT) { parsed = parseFloat(node.value); } else { throw new GraphQLError(`Float can only represent integer or float value, but got a ${node.kind}.`); } if (!isFinite(parsed)) { throw new GraphQLError( `Float cannot represent non numeric value ${parsed}.`); } return parsed; } if (isBooleanType(expectedType)) { if (node.kind !== Kind.BOOLEAN) { throw new GraphQLError(`Boolean cannot represent a non boolean value ${print(node)}.`); } return node.value; } if (isStringType(expectedType)) { if (node.kind !== Kind.STRING) { throw new GraphQLError(`String cannot represent non string value ${print(node)}.`); } return node.value; } if (isIDType(expectedType)) { if (node.kind !== Kind.STRING && node.kind !== Kind.INT) { throw new GraphQLError(`ID cannot represent value ${print(node)}.`); } return node.value; } if (isScalarType(expectedType)) { return valueFromASTUntyped(node); } if (isInputObjectType(expectedType)) { if (node.kind !== Kind.OBJECT) { throw new GraphQLError(`Input Object Type ${expectedType} cannot represent non-object value ${print(node)}.`); } const obj = Object.create(null); for (const f of node.fields) { const name = f.name.value; const field = expectedType.field(name); if (!field) { throw new GraphQLError(`Unknown field "${name}" found in value for Input Object Type "${expectedType}".`); } // TODO: as we recurse in sub-objects, we may get an error on a field value deep in the object // and the error will not be precise to where it happens. We could try to build the path to // the error and include it in the error somehow. obj[name] = valueFromAST(f.value, field.type!); } return obj; } if (isEnumType(expectedType)) { if (node.kind !== Kind.STRING && node.kind !== Kind.ENUM) { throw new GraphQLError(`Enum Type ${expectedType} cannot represent value ${print(node)}.`); } if (!expectedType.value(node.value)) { throw new GraphQLError(`Enum Type ${expectedType} has no value ${node.value}.`); } return node.value; } assert(false, () => `Unexpected input type ${expectedType} of kind ${expectedType.kind}.`); } function valueFromASTUntyped(node: ValueNode): any { switch (node.kind) { case Kind.NULL: return null; case Kind.INT: return parseInt(node.value, 10); case Kind.FLOAT: return parseFloat(node.value); case Kind.STRING: case Kind.ENUM: case Kind.BOOLEAN: return node.value; case Kind.LIST: return node.values.map(valueFromASTUntyped); case Kind.OBJECT: const obj = Object.create(null); node.fields.forEach(f => obj[f.name.value] = valueFromASTUntyped(f.value)); return obj; case Kind.VARIABLE: return new Variable(node.name.value); } } export function argumentsFromAST( context: string, args: readonly ArgumentNode[] | undefined, argsDefiner: { argument(name: string): ArgumentDefinition<any> | undefined } ): {[key: string]: any} { const values = Object.create(null); if (args) { for (const argNode of args) { const name = argNode.name.value; const expectedType = argsDefiner.argument(name)?.type; if (!expectedType) { throw new GraphQLError( `Unknown argument "${name}" found in value: ${context} has no argument named "${name}"` ); } try { values[name] = valueFromAST(argNode.value, expectedType); } catch (e) { if (e instanceof GraphQLError) { throw new GraphQLError(`Invalid value for argument ${name}: ${e.message}`); } throw e; } } } return values; } export function variablesInValue(value: any): Variables { const variables: Variable[] = []; collectVariables(value, variables); return variables; } function collectVariables(value: any, variables: Variable[]) { if (isVariable(value)) { if (!variables.some(v => v.name === value.name)) { variables.push(value); } return; } if (!value) { return; } if (Array.isArray(value)) { value.forEach(v => collectVariables(v, variables)); } if (typeof value === 'object') { Object.keys(value).forEach(k => collectVariables(value[k], variables)); } }
the_stack
import { Component } from "../component"; import { kebabCaseKeys } from "../util"; import { YamlFile } from "../yaml"; import { GitHub } from "./github"; export interface DependabotOptions { /** * How often to check for new versions and raise pull requests. * * @default ScheduleInterval.DAILY */ readonly scheduleInterval?: DependabotScheduleInterval; /** * The strategy to use when edits manifest and lock files. * * @default VersioningStrategy.LOCKFILE_ONLY The default is to only update the * lock file because package.json is controlled by projen and any outside * updates will fail the build. */ readonly versioningStrategy?: VersioningStrategy; /** * You can use the `ignore` option to customize which dependencies are updated. * The ignore option supports the following options. * @default [] */ readonly ignore?: DependabotIgnore[]; /** * Ignores updates to `projen`. * * This is required since projen updates may cause changes in committed files * and anti-tamper checks will fail. * * Projen upgrades are covered through the `ProjenUpgrade` class. * * @default true */ readonly ignoreProjen?: boolean; /** * List of labels to apply to the created PR's. */ readonly labels?: string[]; /** * Map of package registries to use * @default - use public registries */ readonly registries?: { [name: string]: DependabotRegistry }; } /** * Use to add private registry support for dependabot * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#configuration-options-for-private-registries */ export interface DependabotRegistry { /** * Registry type e.g. 'npm-registry' or 'docker-registry' */ readonly type: DependabotRegistryType; /** * Url for the registry e.g. 'https://npm.pkg.github.com' or 'registry.hub.docker.com' */ readonly url: string; /** * The username that Dependabot uses to access the registry * @default - do not authenticate */ readonly username?: string; /** * A reference to a Dependabot secret containing the password for the specified user * @default undefined */ readonly password?: string; /** * A reference to a Dependabot secret containing an access key for this registry * @default undefined */ readonly key?: string; /** * Secret token for dependabot access e.g. '${{ secrets.DEPENDABOT_PACKAGE_TOKEN }}' * @default undefined */ readonly token?: string; /** * For registries with type: python-index, if the boolean value is true, pip * esolves dependencies by using the specified URL rather than the base URL of * the Python Package Index (by default https://pypi.org/simple) * @default undefined */ readonly replacesBase?: boolean; /** * Used with the hex-organization registry type. * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#hex-organization * @default undefined */ readonly organization?: string; } /** * Each configuration type requires you to provide particular settings. * Some types allow more than one way to connect * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#configuration-options-for-private-registries */ export enum DependabotRegistryType { /** * The composer-repository type supports username and password. * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#composer-repository */ COMPOSER_REGISTRY = "composer-registry", /** * The docker-registry type supports username and password. * The docker-registry type can also be used to pull from Amazon ECR using static AWS credentials * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#docker-registry */ DOCKER_REGISTRY = "docker-registry", /** * The git type supports username and password * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#git */ GIT = "git", /** * The hex-organization type supports organization and key * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#hex-organization */ HEX_ORGANIZATION = "hex-organization", /** * The maven-repository type supports username and password, or token * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#maven-repository */ MAVEN_REPOSITORY = "maven-repository", /** * The npm-registry type supports username and password, or token * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#npm-registry */ NPM_REGISTRY = "npm-registry", /** * The nuget-feed type supports username and password, or token * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#nuget-feed */ NUGET_FEED = "nuget-feed", /** * The python-index type supports username and password, or token * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#python-index */ PYTHON_INDEX = "python-index", /** * The rubygems-server type supports username and password, or token * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#rubygems-server */ RUBYGEMS_SERVER = "rubygems-server", /** * The terraform-registry type supports a token * @see https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates#terraform-registry */ TERRAFORM_REGISTRY = "terraform-registry", } /** * You can use the `ignore` option to customize which dependencies are updated. * The ignore option supports the following options. */ export interface DependabotIgnore { /** * Use to ignore updates for dependencies with matching names, optionally * using `*` to match zero or more characters. * * For Java dependencies, the format of the dependency-name attribute is: * `groupId:artifactId`, for example: `org.kohsuke:github-api`. */ readonly dependencyName: string; /** * Use to ignore specific versions or ranges of versions. If you want to * define a range, use the standard pattern for the package manager (for * example: `^1.0.0` for npm, or `~> 2.0` for Bundler). */ readonly versions?: string[]; } /** * How often to check for new versions and raise pull requests for version * updates. */ export enum DependabotScheduleInterval { /** * Runs on every weekday, Monday to Friday. */ DAILY = "daily", /** * Runs once each week. By default, this is on Monday. */ WEEKLY = "weekly", /** * Runs once each month. This is on the first day of the month. */ MONTHLY = "monthly", } /** * The strategy to use when edits manifest and lock files. */ export enum VersioningStrategy { /** * Only create pull requests to update lockfiles updates. Ignore any new * versions that would require package manifest changes. */ LOCKFILE_ONLY = "lockfile-only", /** * - For apps, the version requirements are increased. * - For libraries, the range of versions is widened. */ AUTO = "auto", /** * Relax the version requirement to include both the new and old version, when * possible. */ WIDEN = "widen", /** * Always increase the version requirement to match the new version. */ INCREASE = "increase", /** * Increase the version requirement only when required by the new version. */ INCREASE_IF_NECESSARY = "increase-if-necessary", } /** * Defines dependabot configuration for node projects. * * Since module versions are managed in projen, the versioning strategy will be * configured to "lockfile-only" which means that only updates that can be done * on the lockfile itself will be proposed. */ export class Dependabot extends Component { /** * The raw dependabot configuration. * @see https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates */ public readonly config: any; /** * Whether or not projen is also upgraded in this config, */ public readonly ignoresProjen: boolean; private readonly ignore: any[]; constructor(github: GitHub, options: DependabotOptions = {}) { super(github.project); const project = github.project; this.ignore = []; this.ignoresProjen = options.ignoreProjen ?? true; const registries = options.registries ? kebabCaseKeys(options.registries) : undefined; this.config = { version: 2, registries, updates: [ { "package-ecosystem": "npm", "versioning-strategy": "lockfile-only", directory: "/", schedule: { interval: options.scheduleInterval ?? DependabotScheduleInterval.DAILY, }, ignore: () => (this.ignore.length > 0 ? this.ignore : undefined), labels: options.labels ? options.labels : undefined, registries: registries ? Object.keys(registries) : undefined, }, ], }; new YamlFile(project, ".github/dependabot.yml", { obj: this.config, committed: true, }); for (const i of options.ignore ?? []) { this.addIgnore(i.dependencyName, ...(i.versions ?? [])); } if (this.ignoresProjen) { this.addIgnore("projen"); } } /** * Ignores a dependency from automatic updates. * * @param dependencyName Use to ignore updates for dependencies with matching * names, optionally using `*` to match zero or more characters. * @param versions Use to ignore specific versions or ranges of versions. If * you want to define a range, use the standard pattern for the package * manager (for example: `^1.0.0` for npm, or `~> 2.0` for Bundler). */ public addIgnore(dependencyName: string, ...versions: string[]) { this.ignore.push({ "dependency-name": dependencyName, versions: () => (versions.length > 0 ? versions : undefined), }); } }
the_stack
import { CardStyleInterpolators, createStackNavigator, } from '@react-navigation/stack'; import * as React from 'react'; import {ScrollView, StyleSheet} from 'react-native'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import AstroBirdExample from './apiTest/AstroBirdExample'; import AudioExample from './apiTest/audio/AudioExample'; import AudioSaveLoadExample from './apiTest/audio/AudioSaveLoadExample'; import BlobImageConversion from './apiTest/blob/BlobImageConversion'; import BlobTensorImageConversion from './apiTest/blob/BlobTensorImageConversion'; import CameraFlip from './apiTest/camera/CameraFlip'; import CameraTakePicture from './apiTest/camera/CameraTakePicture'; import CanvasAnimation from './apiTest/CanvasAnimation'; import CanvasArc from './apiTest/CanvasArc'; import CanvasArcMatrix from './apiTest/CanvasArcMatrix'; import CanvasClearRect from './apiTest/CanvasClearRect'; import CanvasClosePath from './apiTest/CanvasClosePath'; import CanvasDrawImage from './apiTest/CanvasDrawImage'; import CanvasFillRect from './apiTest/CanvasFillRect'; import CanvasGetImageData from './apiTest/CanvasGetImageData'; import CanvasImageSprite from './apiTest/CanvasImageSprite'; import CanvasLineCap from './apiTest/CanvasLineCap'; import CanvasLineJoin from './apiTest/CanvasLineJoin'; import CanvasMiterLimit from './apiTest/CanvasMiterLimit'; import CanvasMoveTo from './apiTest/CanvasMoveTo'; import CanvasRect from './apiTest/CanvasRect'; import CanvasRotate from './apiTest/CanvasRotate'; import CanvasSaveRestore from './apiTest/CanvasSaveRestore'; import CanvasScale from './apiTest/CanvasScale'; import CanvasSetTransform from './apiTest/CanvasSetTransform'; import CanvasText from './apiTest/CanvasText'; import CanvasTextAlign from './apiTest/CanvasTextAlign'; import CanvasTranslate from './apiTest/CanvasTranslate'; import ImageScale from './apiTest/ImageScale'; import JSIPlayground from './JSIPlayground'; import AnimeGANv2 from './models/AnimeGANv2'; import DETR from './models/DETR'; import Distilbert from './models/Distilbert'; import FastNeuralStyle from './models/FastNeuralStyle'; import MNIST from './models/MNIST'; import MobileNetV3 from './models/MobileNetV3'; import Wav2Vec2 from './models/Wav2Vec2'; import Playground from './Playground'; import ToolboxContext, {useToolboxContext} from './ToolboxContext'; import ToolboxList from './ToolboxList'; export type Tool = { icon?: React.ReactNode; title: string; subtitle: string; apiTest?: boolean; component?: React.ComponentType<any>; }; export type ToolSection = { title: string; data: Tool[]; }[]; const tools: ToolSection = [ { title: 'Playground', data: [ { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Playground', subtitle: 'A playground to experiment with the PyTorch Core API', apiTest: false, component: Playground, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'JSI Playground', subtitle: 'A JSI playground to experiment with the PyTorch Core API', apiTest: false, component: JSIPlayground, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Astro Bird', subtitle: 'A little game to test performance', apiTest: false, component: AstroBirdExample, }, ], }, { title: 'Models', data: [ { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'MobileNet V3', subtitle: 'Example image classificaion with MobileNet V3', apiTest: false, component: MobileNetV3, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'MNIST', subtitle: 'Handwritten digit classifier', apiTest: false, component: MNIST, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'DETR', subtitle: 'Example to test the DETR model', apiTest: false, component: DETR, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Fast Neural Style', subtitle: 'Example for a neural style transfer model', apiTest: false, component: FastNeuralStyle, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Distilbert', subtitle: 'Example for the Distilbert NLP Q&A model', apiTest: false, component: Distilbert, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Wav2Vec2', subtitle: 'Example to test the Wav2Vec2 model', apiTest: false, component: Wav2Vec2, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'AnimeGANv2', subtitle: 'Example to test the AnimeGANv2 model', apiTest: false, component: AnimeGANv2, }, ], }, { title: 'Camera API Test', data: [ { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Camera#takePicture', subtitle: 'Manually calling takePicture API on camera', apiTest: true, component: CameraTakePicture, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Camera#flip', subtitle: 'Manually calling flip API on camera', apiTest: true, component: CameraFlip, }, ], }, { title: 'Canvas API Test', data: [ { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#rect', subtitle: 'Drawing rect on a canvas', apiTest: true, component: CanvasRect, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#fillRect', subtitle: 'Drawing filled rect on a canvas', apiTest: true, component: CanvasFillRect, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#clearRect', subtitle: 'Clear rect on a canvas', apiTest: true, component: CanvasClearRect, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#arc', subtitle: 'Drawing arc/circles on a canvas', apiTest: true, component: CanvasArc, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Arc Matrix', subtitle: 'Drawing an arcs matrix on a canvas', apiTest: true, component: CanvasArcMatrix, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Animation', subtitle: 'Animate drawings on canvas', apiTest: true, component: CanvasAnimation, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Save and Restore', subtitle: 'Save, draw, and restore context', component: CanvasSaveRestore, apiTest: true, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Set Transform', subtitle: 'Draw with transform', apiTest: true, component: CanvasSetTransform, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Scale', subtitle: 'Drawing with scale on canvas', apiTest: true, component: CanvasScale, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Rotate', subtitle: 'Drawing with rotate on canvas', apiTest: true, component: CanvasRotate, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Translate', subtitle: 'Drawing with translate on canvas', apiTest: true, component: CanvasTranslate, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#moveTo', subtitle: 'Drawing lines on a canvas', apiTest: true, component: CanvasMoveTo, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#lineCap', subtitle: 'Drawing lines with line cap on a canvas', apiTest: true, component: CanvasLineCap, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#lineJoin', subtitle: 'Drawing lines with line join on a canvas', apiTest: true, component: CanvasLineJoin, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#miterLimit', subtitle: 'Drawing lines with miter limit on a canvas', apiTest: true, component: CanvasMiterLimit, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#closePath', subtitle: 'Close path on a canvas', apiTest: true, component: CanvasClosePath, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Image Scale', subtitle: 'Scaling images', apiTest: true, component: ImageScale, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#getImageData', subtitle: 'Retrieve ImageData and draw as image on a canvas', apiTest: true, component: CanvasGetImageData, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#drawImage', subtitle: 'Drawing images on a canvas', apiTest: true, component: CanvasDrawImage, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Text', subtitle: 'Drawing text on canvas', apiTest: true, component: CanvasText, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas#textAlign', subtitle: 'Drawing aligned text on canvas', apiTest: true, component: CanvasTextAlign, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Canvas Image Sprite', subtitle: 'Draw and transform images from an image sprite', apiTest: true, component: CanvasImageSprite, }, ], }, { title: 'Audio API Test', data: [ { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Audio APIs', subtitle: 'Record an audio and test audio APIs on the recorded clip.', apiTest: true, component: AudioExample, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Audio Load & Save Example', subtitle: 'Record an audio and save to a file on device.', apiTest: true, component: AudioSaveLoadExample, }, ], }, { title: 'Blob API Tests', data: [ { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Blob <> Image', subtitle: 'Transform between blob and image', apiTest: true, component: BlobImageConversion, }, { icon: <Icon name="clipboard-text" size={32} color="white" />, title: 'Blob <> Tensor <> Image', subtitle: 'Transform among blob, tensor and image', apiTest: true, component: BlobTensorImageConversion, }, ], }, ]; type ToolboxParamList = { API: undefined; ToolView: { title: string; }; }; const Stack = createStackNavigator<ToolboxParamList>(); function ToolView() { const {activeTool} = useToolboxContext(); const Component = activeTool?.component; return ( <ScrollView contentContainerStyle={styles.container} bounces={false}> {Component && <Component />} </ScrollView> ); } export default function Toolbox() { return ( <ToolboxContext> <Stack.Navigator screenOptions={{ cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS, }}> <Stack.Screen name="API" options={{headerShown: false}}> {props => ( <ToolboxList {...props} tools={tools} onSelect={tool => { props.navigation.navigate('ToolView', { title: tool.title, }); }} /> )} </Stack.Screen> <Stack.Screen name="ToolView" component={ToolView} options={({route}) => { if (route != null) { return {title: route.params.title}; } return {}; }} /> </Stack.Navigator> </ToolboxContext> ); } const styles = StyleSheet.create({ container: { flex: 1, }, });
the_stack
import * as coreHttp from "@azure/core-http"; import * as Parameters from "./models/parameters"; import * as Mappers from "./models/mappers"; import { KeyVaultClientContext } from "./keyVaultClientContext"; import { KeyVaultClientOptionalParams, ApiVersion73Preview, KeyVaultClientSetSecretOptionalParams, KeyVaultClientSetSecretResponse, KeyVaultClientDeleteSecretResponse, KeyVaultClientUpdateSecretOptionalParams, KeyVaultClientUpdateSecretResponse, KeyVaultClientGetSecretResponse, KeyVaultClientGetSecretsOptionalParams, KeyVaultClientGetSecretsResponse, KeyVaultClientGetSecretVersionsOptionalParams, KeyVaultClientGetSecretVersionsResponse, KeyVaultClientGetDeletedSecretsOptionalParams, KeyVaultClientGetDeletedSecretsResponse, KeyVaultClientGetDeletedSecretResponse, KeyVaultClientRecoverDeletedSecretResponse, KeyVaultClientBackupSecretResponse, KeyVaultClientRestoreSecretResponse, KeyVaultClientGetSecretsNextOptionalParams, KeyVaultClientGetSecretsNextResponse, KeyVaultClientGetSecretVersionsNextOptionalParams, KeyVaultClientGetSecretVersionsNextResponse, KeyVaultClientGetDeletedSecretsNextOptionalParams, KeyVaultClientGetDeletedSecretsNextResponse } from "./models"; /** @hidden */ export class KeyVaultClient extends KeyVaultClientContext { /** * Initializes a new instance of the KeyVaultClient class. * @param apiVersion Api Version * @param options The parameter options */ constructor( apiVersion: ApiVersion73Preview, options?: KeyVaultClientOptionalParams ) { super(apiVersion, options); } /** * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure * Key Vault creates a new version of that secret. This operation requires the secrets/set permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param value The value of the secret. * @param options The options parameters. */ setSecret( vaultBaseUrl: string, secretName: string, value: string, options?: KeyVaultClientSetSecretOptionalParams ): Promise<KeyVaultClientSetSecretResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, value, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, setSecretOperationSpec ) as Promise<KeyVaultClientSetSecretResponse>; } /** * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an * individual version of a secret. This operation requires the secrets/delete permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param options The options parameters. */ deleteSecret( vaultBaseUrl: string, secretName: string, options?: coreHttp.OperationOptions ): Promise<KeyVaultClientDeleteSecretResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, deleteSecretOperationSpec ) as Promise<KeyVaultClientDeleteSecretResponse>; } /** * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are * not specified in the request are left unchanged. The value of a secret itself cannot be changed. * This operation requires the secrets/set permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param secretVersion The version of the secret. * @param options The options parameters. */ updateSecret( vaultBaseUrl: string, secretName: string, secretVersion: string, options?: KeyVaultClientUpdateSecretOptionalParams ): Promise<KeyVaultClientUpdateSecretResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, secretVersion, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, updateSecretOperationSpec ) as Promise<KeyVaultClientUpdateSecretResponse>; } /** * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the * secrets/get permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the * latest version of the secret is returned. * @param options The options parameters. */ getSecret( vaultBaseUrl: string, secretName: string, secretVersion: string, options?: coreHttp.OperationOptions ): Promise<KeyVaultClientGetSecretResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, secretVersion, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getSecretOperationSpec ) as Promise<KeyVaultClientGetSecretResponse>; } /** * The Get Secrets operation is applicable to the entire vault. However, only the base secret * identifier and its attributes are provided in the response. Individual secret versions are not * listed in the response. This operation requires the secrets/list permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param options The options parameters. */ getSecrets( vaultBaseUrl: string, options?: KeyVaultClientGetSecretsOptionalParams ): Promise<KeyVaultClientGetSecretsResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getSecretsOperationSpec ) as Promise<KeyVaultClientGetSecretsResponse>; } /** * The full secret identifier and attributes are provided in the response. No values are returned for * the secrets. This operations requires the secrets/list permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param options The options parameters. */ getSecretVersions( vaultBaseUrl: string, secretName: string, options?: KeyVaultClientGetSecretVersionsOptionalParams ): Promise<KeyVaultClientGetSecretVersionsResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getSecretVersionsOperationSpec ) as Promise<KeyVaultClientGetSecretVersionsResponse>; } /** * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for * soft-delete. This operation requires the secrets/list permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param options The options parameters. */ getDeletedSecrets( vaultBaseUrl: string, options?: KeyVaultClientGetDeletedSecretsOptionalParams ): Promise<KeyVaultClientGetDeletedSecretsResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getDeletedSecretsOperationSpec ) as Promise<KeyVaultClientGetDeletedSecretsResponse>; } /** * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. * This operation requires the secrets/get permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param options The options parameters. */ getDeletedSecret( vaultBaseUrl: string, secretName: string, options?: coreHttp.OperationOptions ): Promise<KeyVaultClientGetDeletedSecretResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getDeletedSecretOperationSpec ) as Promise<KeyVaultClientGetDeletedSecretResponse>; } /** * The purge deleted secret operation removes the secret permanently, without the possibility of * recovery. This operation can only be enabled on a soft-delete enabled vault. This operation requires * the secrets/purge permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param options The options parameters. */ purgeDeletedSecret( vaultBaseUrl: string, secretName: string, options?: coreHttp.OperationOptions ): Promise<coreHttp.RestResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, purgeDeletedSecretOperationSpec ) as Promise<coreHttp.RestResponse>; } /** * Recovers the deleted secret in the specified vault. This operation can only be performed on a * soft-delete enabled vault. This operation requires the secrets/recover permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the deleted secret. * @param options The options parameters. */ recoverDeletedSecret( vaultBaseUrl: string, secretName: string, options?: coreHttp.OperationOptions ): Promise<KeyVaultClientRecoverDeletedSecretResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, recoverDeletedSecretOperationSpec ) as Promise<KeyVaultClientRecoverDeletedSecretResponse>; } /** * Requests that a backup of the specified secret be downloaded to the client. All versions of the * secret will be downloaded. This operation requires the secrets/backup permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param options The options parameters. */ backupSecret( vaultBaseUrl: string, secretName: string, options?: coreHttp.OperationOptions ): Promise<KeyVaultClientBackupSecretResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, backupSecretOperationSpec ) as Promise<KeyVaultClientBackupSecretResponse>; } /** * Restores a backed up secret, and all its versions, to a vault. This operation requires the * secrets/restore permission. * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretBundleBackup The backup blob associated with a secret bundle. * @param options The options parameters. */ restoreSecret( vaultBaseUrl: string, secretBundleBackup: Uint8Array, options?: coreHttp.OperationOptions ): Promise<KeyVaultClientRestoreSecretResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretBundleBackup, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, restoreSecretOperationSpec ) as Promise<KeyVaultClientRestoreSecretResponse>; } /** * GetSecretsNext * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param nextLink The nextLink from the previous successful call to the GetSecrets method. * @param options The options parameters. */ getSecretsNext( vaultBaseUrl: string, nextLink: string, options?: KeyVaultClientGetSecretsNextOptionalParams ): Promise<KeyVaultClientGetSecretsNextResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, nextLink, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getSecretsNextOperationSpec ) as Promise<KeyVaultClientGetSecretsNextResponse>; } /** * GetSecretVersionsNext * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param secretName The name of the secret. * @param nextLink The nextLink from the previous successful call to the GetSecretVersions method. * @param options The options parameters. */ getSecretVersionsNext( vaultBaseUrl: string, secretName: string, nextLink: string, options?: KeyVaultClientGetSecretVersionsNextOptionalParams ): Promise<KeyVaultClientGetSecretVersionsNextResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, secretName, nextLink, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getSecretVersionsNextOperationSpec ) as Promise<KeyVaultClientGetSecretVersionsNextResponse>; } /** * GetDeletedSecretsNext * @param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net. * @param nextLink The nextLink from the previous successful call to the GetDeletedSecrets method. * @param options The options parameters. */ getDeletedSecretsNext( vaultBaseUrl: string, nextLink: string, options?: KeyVaultClientGetDeletedSecretsNextOptionalParams ): Promise<KeyVaultClientGetDeletedSecretsNextResponse> { const operationArguments: coreHttp.OperationArguments = { vaultBaseUrl, nextLink, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.sendOperationRequest( operationArguments, getDeletedSecretsNextOperationSpec ) as Promise<KeyVaultClientGetDeletedSecretsNextResponse>; } } // Operation Specifications const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); const setSecretOperationSpec: coreHttp.OperationSpec = { path: "/secrets/{secret-name}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SecretBundle }, default: { bodyMapper: Mappers.KeyVaultError } }, requestBody: { parameterPath: { value: ["value"], tags: ["options", "tags"], contentType: ["options", "contentType"], secretAttributes: ["options", "secretAttributes"] }, mapper: Mappers.SecretSetParameters }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.vaultBaseUrl, Parameters.secretName], headerParameters: [Parameters.contentType, Parameters.accept], mediaType: "json", serializer }; const deleteSecretOperationSpec: coreHttp.OperationSpec = { path: "/secrets/{secret-name}", httpMethod: "DELETE", responses: { 200: { bodyMapper: Mappers.DeletedSecretBundle }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.vaultBaseUrl, Parameters.secretName1], headerParameters: [Parameters.accept], serializer }; const updateSecretOperationSpec: coreHttp.OperationSpec = { path: "/secrets/{secret-name}/{secret-version}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.SecretBundle }, default: { bodyMapper: Mappers.KeyVaultError } }, requestBody: { parameterPath: { contentType: ["options", "contentType"], secretAttributes: ["options", "secretAttributes"], tags: ["options", "tags"] }, mapper: Mappers.SecretUpdateParameters }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.vaultBaseUrl, Parameters.secretName1, Parameters.secretVersion ], headerParameters: [Parameters.contentType, Parameters.accept], mediaType: "json", serializer }; const getSecretOperationSpec: coreHttp.OperationSpec = { path: "/secrets/{secret-name}/{secret-version}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecretBundle }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.vaultBaseUrl, Parameters.secretName1, Parameters.secretVersion ], headerParameters: [Parameters.accept], serializer }; const getSecretsOperationSpec: coreHttp.OperationSpec = { path: "/secrets", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecretListResult }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion, Parameters.maxresults], urlParameters: [Parameters.vaultBaseUrl], headerParameters: [Parameters.accept], serializer }; const getSecretVersionsOperationSpec: coreHttp.OperationSpec = { path: "/secrets/{secret-name}/versions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecretListResult }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion, Parameters.maxresults], urlParameters: [Parameters.vaultBaseUrl, Parameters.secretName1], headerParameters: [Parameters.accept], serializer }; const getDeletedSecretsOperationSpec: coreHttp.OperationSpec = { path: "/deletedsecrets", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeletedSecretListResult }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion, Parameters.maxresults], urlParameters: [Parameters.vaultBaseUrl], headerParameters: [Parameters.accept], serializer }; const getDeletedSecretOperationSpec: coreHttp.OperationSpec = { path: "/deletedsecrets/{secret-name}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeletedSecretBundle }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.vaultBaseUrl, Parameters.secretName1], headerParameters: [Parameters.accept], serializer }; const purgeDeletedSecretOperationSpec: coreHttp.OperationSpec = { path: "/deletedsecrets/{secret-name}", httpMethod: "DELETE", responses: { 204: {}, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.vaultBaseUrl, Parameters.secretName1], headerParameters: [Parameters.accept], serializer }; const recoverDeletedSecretOperationSpec: coreHttp.OperationSpec = { path: "/deletedsecrets/{secret-name}/recover", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.SecretBundle }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.vaultBaseUrl, Parameters.secretName1], headerParameters: [Parameters.accept], serializer }; const backupSecretOperationSpec: coreHttp.OperationSpec = { path: "/secrets/{secret-name}/backup", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.BackupSecretResult }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.vaultBaseUrl, Parameters.secretName1], headerParameters: [Parameters.accept], serializer }; const restoreSecretOperationSpec: coreHttp.OperationSpec = { path: "/secrets/restore", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.SecretBundle }, default: { bodyMapper: Mappers.KeyVaultError } }, requestBody: { parameterPath: { secretBundleBackup: ["secretBundleBackup"] }, mapper: Mappers.SecretRestoreParameters }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.vaultBaseUrl], headerParameters: [Parameters.contentType, Parameters.accept], mediaType: "json", serializer }; const getSecretsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecretListResult }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion, Parameters.maxresults], urlParameters: [Parameters.vaultBaseUrl, Parameters.nextLink], headerParameters: [Parameters.accept], serializer }; const getSecretVersionsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SecretListResult }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion, Parameters.maxresults], urlParameters: [ Parameters.vaultBaseUrl, Parameters.secretName1, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const getDeletedSecretsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.DeletedSecretListResult }, default: { bodyMapper: Mappers.KeyVaultError } }, queryParameters: [Parameters.apiVersion, Parameters.maxresults], urlParameters: [Parameters.vaultBaseUrl, Parameters.nextLink], headerParameters: [Parameters.accept], serializer };
the_stack
// Library module that defines SiteTuner interface and shared DOM hacking logic. // (This is defined separately here, and not in content_script.ts, to avoid // circular dependency issues.) import { CommentVisibilityDecision, AttributeScores, AttributeScore, EnabledAttributes, getCommentVisibility, getHideReasonDescription, getFeedbackQuestion } from '../scores'; import { EnabledWebsites, ThemeType, THEMES } from '../tune_settings'; import { ChromeMessageEnum } from '../messages'; // This is a marker for DOM nodes that we've seen already. This is so we don't // rerun the MutationObserver logic on nodes when we modify the DOM to show/hide // comments. export const TUNE_SEEN_ATTR = 'tune-seen'; // Webcomponent attribute for the comment's visibility state. export const WRAPPER_TUNE_STATE_ATTR = 'tune-state'; export const TUNE_STATE = { filter: 'filter', show: 'show' }; // Webcomponent attributes for a comment's highest attribute score, filter // message, and feedback question displayed. These correspond to the camelcase // input values defined in our web component classes. export const WRAPPER_SITE_NAME_ATTR = 'site-name'; export const WRAPPER_COMMENT_TEXT_ATTR = 'comment-text'; export const WRAPPER_SCORES_ATTR = 'tune-scores'; export const WRAPPER_MAX_ATTRIBUTE_NAME_ATTR = 'max-attribute'; export const WRAPPER_MAX_ATTRIBUTE_SCORE_ATTR = 'max-score'; export const WRAPPER_FILTER_MESSAGE_ATTR = 'filter-message'; export const WRAPPER_FEEDBACK_QUESTION_ATTR = 'feedback-question'; // Container of child nodes of original comment block. export const COMMENT_CHILDREN_CONTAINER_CLASS = 'comment-children-contianer'; export const WRAPPER_CLASS = '--tune-wrapper'; const HANDLE_COMMENT_BATCH_SIZE = 5; const HANDLE_COMMENT_BATCH_DELAY_MS = 100; export function scoreComment(commentText: string): Promise<AttributeScores> { return new Promise((resolve, reject) => { chrome.runtime.sendMessage({action: ChromeMessageEnum.SCORE_TEXT, text: commentText}, (scores) => { resolve(scores); }); }); } // Moves all child nodes from source to dest, including text/comment nodes. function moveAllChildNodes(source: Element, dest: Element): void { while (source.firstChild) { dest.appendChild(source.firstChild); } } // Utility that calls a function on all items in batches, inserting a delay of // 'timeout' in between each batch. We use this to handle scoring comments and // modifying their DOM elements because if many comments are present, the DOM is // not updated until all those comments are scored. Breaking the job into // batches means that the initial comments can be handled more quickly, before // the rest of the comments are scored. function batchActionWithTimeout<T>(items: Array<T>, fn: ((arg: T) => void), batchSize: number, timeout: number) : void { const batch = items.slice(0, batchSize); for (const item of batch) { fn(item); } const rest = items.slice(batchSize); if (rest.length) { setTimeout(() => batchActionWithTimeout(rest, fn, batchSize, timeout), timeout); } } // Wraps JSON.parse to return undefined on parse errors. We don't return null, // since that's a valid JSON value. export function safeParse(json: string): any|undefined { try { return JSON.parse(json); } catch (error) { console.error('JSON parse error:', error); return undefined; } } // Helper function for implementing getTextFromCommentBlock using a selector on // the comment block. export function getTextWithSelector( commentBlock: HTMLElement, textSelector: string) : string|null { const textNode = commentBlock.querySelector(textSelector); if (!(textNode instanceof HTMLElement)) { return null; } // NOTE: This is free-form comment text from the internet! Be mindful of // security issues in how this data is handled. return textNode.innerText; } export const SEEN_SELECTOR = '[' + TUNE_SEEN_ATTR + ']'; export const UNSEEN_SELECTOR = ':not(' + SEEN_SELECTOR + ')'; // SiteTuner handles the DOM hackery for a specific site. It finds comment DOM // elements on a page, extracts and scores the text, and mutates the DOM to hide // elements depending on the user's Tune settings. export abstract class SiteTuner { abstract readonly siteName: string; // This selector identifies the primary comment element operated on by the // rest of this code. The selector should trigger for newly appearing comments // that need to be handled. These elements have name and type `commentBlock: // HTMLElement` is this code. abstract readonly commentBlockSelector: string; // If we should call handleRemovedComment when elements matching // commentBlockSelector are removed. Needed if the site reuses DOM elements in // some tricky way (e.g. YouTube, when navigating to a new video). // // Warning! This can make code complicated if the commentBlockSelector doesn't // exactly identify the object that needs to be wrapped (e.g., if // adjustCommentBlock changes the block to refer to a parent element). This is // because we may move comment blocks when wrapping the comment, which calls // handleRemovedComment. TODO: untangle this stuff. protected shouldHandleRemoveMutations = false; private tuneEnabled = true; private observer: MutationObserver = null; // Function to go from elements returned by commentBlockSelector to the text // comment. abstract getTextFromCommentBlock(commentBlock: HTMLElement): string|null; // Changes the DOM to use as the comment block. This is only needed if the // comment blocks matched by commentBlockSelector is not the same as the DOM // element that should be wrapped. // // One might use this, for example, if the actual comment block (which // includes the username, avatar, metadata, etc.) is not feasible to be // selected with commentBlockSelector (e.g. on Reddit, we select the text // block instead of the comment block). protected adjustCommentBlock(commentBlock: HTMLElement): HTMLElement { return commentBlock; } // Returns our injected comment wrapper component for the comment block. // Override if the wrapper doesn't reside within the commentBlock. // // Note: this is called on the result returned by adjustCommentBlock. // // Public for testing. public getWrapperForAdjustedCommentBlock(commentBlock: HTMLElement): Element|null { return commentBlock.querySelector('.' + WRAPPER_CLASS); } // Should be used for any mutation observer handling specific to subclasses. protected handleCommentChanged(mutation: MutationRecord): void { } // Gets the webcomponent name based on the theme. Can be overridden in // subclasses with more specific webcomponent implementations. protected getCommentWrapperElement(): string { if (this.theme === THEMES.dotted) { return 'tune-dotted-comment-wrapper'; } else { return 'tune-debug-comment-wrapper'; } } constructor(protected threshold: number, protected enabledAttributes: EnabledAttributes, protected theme: ThemeType, protected subtypesEnabled: boolean) { // Note: we create this on initialization but it doesn't start working until // we call 'observe' later on. this.observer = new MutationObserver(mutations => { mutations.forEach(mutation => { this.handleCommentChanged(mutation); // TODO: handling added nodes in batch using batchActionWithTimeout // causes weird issues with YouTube. mutation.addedNodes.forEach(addedNode => { this.handleAddedNode(addedNode); }); if (this.shouldHandleRemoveMutations) { mutation.removedNodes.forEach(removedNode => { this.handleRemovedNode(removedNode); }); } }); }); } // This method kicks off logic for observing the page, detecting // comments, scoring them, and choosing whether to hide them. public launchTuner(): void { this.tuneEnabled = true; this.initializeSelectors(); console.log('launchTuner: handling any comments already present...'); this.handleExistingComments(); console.log('launchTuner: launching mutation observer...'); this.handleNewComments(); } public disableTuner(): void { this.observer.disconnect(); this.tuneEnabled = false; if (this.commentBlockSelector === null) { return; } document.body.querySelectorAll( this.commentBlockSelector + SEEN_SELECTOR) .forEach(commentBlock => this.handleRemovedComment(commentBlock)); } // Performs any initialization that needs to be done for the selectors to use // when querying for comments on the page. Override in subclasses for // website-specific behavior. protected initializeSelectors(): void {} private handleExistingComments(): void { if (this.commentBlockSelector === null) { return; } const items = []; document.body.querySelectorAll(this.commentBlockSelector + UNSEEN_SELECTOR) .forEach(item => items.push(item)); batchActionWithTimeout(items, item => this.handleAddedComment(item), HANDLE_COMMENT_BATCH_SIZE, HANDLE_COMMENT_BATCH_DELAY_MS); } private handleNewComments(): void { this.observer.observe(document.body, {subtree: true, childList: true}); } // Public for tests. public handleAddedNode(addedNode: Node) { // Try to initialize the selectors in case we failed to during initial page // load. // // This is needed because the redesigned Reddit dynamically loads posts w/ // comments without a full page reload. So going to a top-level subreddit // page causes the script to load, but there are no comments to initialize // the selector. If the user then navigates to a page with comments, we need // to try to initialize the selectors again. this.initializeSelectors(); if (!(addedNode instanceof HTMLElement) || this.commentBlockSelector === null) { return; } // New comment blocks may be directly added to the DOM, or they may be // nested within other elements, so we need to call both `matches` and // `querySelectorAll` to handle both cases. (For example, YouTube reply // comment blocks are loaded directly into the DOM as the added node when // the "View replies" button is clicked.) if (addedNode.matches(this.commentBlockSelector + UNSEEN_SELECTOR)) { this.handleAddedComment(addedNode); } addedNode.querySelectorAll(this.commentBlockSelector + UNSEEN_SELECTOR).forEach( commentBlock => this.handleAddedComment(commentBlock)); } // Public for tests. public handleRemovedNode(removedNode: Node) { if (!(removedNode instanceof HTMLElement) || this.commentBlockSelector === null) { return; } if (removedNode.matches(this.commentBlockSelector)) { this.handleRemovedComment(removedNode); } removedNode.querySelectorAll(this.commentBlockSelector).forEach( commentBlock => this.handleRemovedComment(commentBlock)); } // This method is used as an onChange handler for the threshold and // enabledAttributes settings. public onFilterSettingsChange(threshold: number, enabledAttributes: EnabledAttributes, theme: ThemeType, subtypesEnabled: boolean) : void { console.log('onSettingsChange:', threshold, enabledAttributes, theme, subtypesEnabled); this.threshold = threshold; this.enabledAttributes = enabledAttributes; this.subtypesEnabled = subtypesEnabled; if (theme !== this.theme) { this.theme = theme; this.handleThemeChange(); } this.setAllCommentsVisibility(); } public onEnabledSettingsChange(globalEnabled: boolean, enabledWebsites: EnabledWebsites) : void { console.log('onEnabledSitesChange:', globalEnabled, enabledWebsites); const shouldBeEnabled = globalEnabled && enabledWebsites[this.siteName]; if (this.tuneEnabled && !shouldBeEnabled) { console.log('disabling Tune...'); this.disableTuner(); } else if (!this.tuneEnabled && shouldBeEnabled) { console.log('launching Tune...'); this.launchTuner(); } } // Override in subclasses to indicate if certain comment blocks should be // skipped. protected canWrapCommentBlock(commentBlock: HTMLElement): boolean { return true; } // Override in subclasses if DOM manipulation differs from the normal pattern. // Public for test visibility so we can use this with jasmine spyOn. // TODO: This is not great practice, we should restore this to being // protected once tests are better. // Returns a Promise to make testing simpler. public handleAddedComment(commentBlock: Node): Promise<void> { if (!(commentBlock instanceof HTMLElement)) { return Promise.resolve(); } // NOTE: This is free-form comment text from the internet! Be mindful of // security issues in how this data is handled. const text = this.getTextFromCommentBlock(commentBlock); if (text === null) { return Promise.resolve(); } if (!this.canWrapCommentBlock(commentBlock)) { console.log('Skipping comment block', commentBlock); return Promise.resolve(); } console.log('handleAddedComment: ', text.substr(0, 30)); const wrapperComponent = this.wrapCommentBlock(commentBlock, text); if (wrapperComponent === null) { console.error('wrapCommentBlock failed on block:', commentBlock); return Promise.resolve(); } commentBlock.setAttribute(TUNE_SEEN_ATTR, ''); // Note: this is special handling for Reddit. When re-expanding collapsed // comments, the comment block is re-added within the existing wrapper // component. That component still has scores, so no need to rescore in this // case. let scoringPromise; if (wrapperComponent.hasAttribute(WRAPPER_SCORES_ATTR)) { scoringPromise = Promise.resolve(); console.log('wrapper already had scores, skipping scoring:', wrapperComponent); } else { scoringPromise = scoreComment(text).then(scores => { wrapperComponent.setAttribute(WRAPPER_SCORES_ATTR, JSON.stringify(scores)); }); } return scoringPromise.then(() => this.setCommentVisibility(wrapperComponent)); } // When nodes are removed, we want to remove any customization we did to the // DOM because some websites will reuse their DOM elements after they are // removed. // // Public for tests. public handleRemovedComment(commentBlock: Node): void { if (!(commentBlock instanceof HTMLElement)) { return; } if (!commentBlock.hasAttribute(TUNE_SEEN_ATTR)) { return; } if (!this.unwrapCommentBlock(commentBlock)) { console.error('handleRemovedComment: comment not initialized yet?', commentBlock); return; } console.log('handleRemovedComment:', commentBlock); commentBlock.removeAttribute(TUNE_SEEN_ATTR); } // TODO: maybe we should move this logic into the wrapper components? private setCommentVisibility(wrapperComponent: Element) { const scores = safeParse(wrapperComponent.getAttribute(WRAPPER_SCORES_ATTR)); if (scores === undefined) { console.error('BUG: invalid scores? skipping comment:', scores, wrapperComponent); } const commentVisibility: CommentVisibilityDecision = getCommentVisibility( scores, this.threshold, this.enabledAttributes, this.subtypesEnabled); if (commentVisibility.kind === 'showComment') { wrapperComponent.setAttribute(WRAPPER_TUNE_STATE_ATTR, TUNE_STATE.show); } else { wrapperComponent.setAttribute(WRAPPER_TUNE_STATE_ATTR, TUNE_STATE.filter); if (commentVisibility.kind === 'hideCommentDueToScores') { wrapperComponent.setAttribute(WRAPPER_MAX_ATTRIBUTE_NAME_ATTR, commentVisibility.attribute); } } if (this.theme === THEMES.dotted) { wrapperComponent.setAttribute(WRAPPER_FILTER_MESSAGE_ATTR, getHideReasonDescription(commentVisibility)); wrapperComponent.setAttribute(WRAPPER_FEEDBACK_QUESTION_ATTR, getFeedbackQuestion(commentVisibility, this.subtypesEnabled)); if (commentVisibility.kind === 'hideCommentDueToScores') { wrapperComponent.setAttribute(WRAPPER_MAX_ATTRIBUTE_SCORE_ATTR, String(commentVisibility.scaledScore)); } } } // Moves all contents of comment under the webcomponent, and makes the // webcomponent a child of the original comment element. // // Override in subclasses if this manipulation needs to be different. // Note that if you do this, you will also have to override handleThemeChange. // // Public for tests. public wrapCommentBlock(commentBlock: HTMLElement, commentText: string): Element { commentBlock = this.adjustCommentBlock(commentBlock); // Move all comment contents under a new wrapper element. const wrapperComponent = document.createElement(this.getCommentWrapperElement()); wrapperComponent.classList.add(WRAPPER_CLASS); // NOTE: This is free-form comment text from the internet! Be mindful of // security issues in how this data is handled. // // Here, we include the full comment text as an attribute on our wrapper // component. Quotes are automatically escaped by Angular, and <script> and // other tags are innocuous being stored as strings, so this is not a // security issue. But we need to be mindful if we change the way this data // is handled. wrapperComponent.setAttribute(WRAPPER_COMMENT_TEXT_ATTR, commentText); wrapperComponent.setAttribute(WRAPPER_SITE_NAME_ATTR, this.siteName); // We wrap all the original comment's children elements in a new container // so that it's easy to identify and undo our DOM hackery later. const commentChildrenContainer = document.createElement('div'); commentChildrenContainer.classList.add(COMMENT_CHILDREN_CONTAINER_CLASS); moveAllChildNodes(commentBlock, commentChildrenContainer); wrapperComponent.appendChild(commentChildrenContainer); commentBlock.appendChild(wrapperComponent); return wrapperComponent; } // Returns false if the comment hasn't been fully initialized and couldn't be // reset. This should only if the function was called before wrapCommentBlock // completed. // // Public for tests. public unwrapCommentBlock(commentBlock: HTMLElement): boolean { commentBlock = this.adjustCommentBlock(commentBlock); const commentWrapper = this.getWrapperForAdjustedCommentBlock(commentBlock); if (commentWrapper === null) { return false; } const childrenContainer = commentWrapper.querySelector( '.' + COMMENT_CHILDREN_CONTAINER_CLASS); moveAllChildNodes(childrenContainer, commentBlock); commentBlock.removeChild(commentWrapper); return true; } private handleThemeChange(): void { // This is essentially handleRemovedComment and then handleAddedComment, but // without the unnecessary rescoring step. if (this.commentBlockSelector === null) { return; } document.body.querySelectorAll(this.commentBlockSelector + SEEN_SELECTOR) .forEach(commentBlock => { if (!(commentBlock instanceof HTMLElement)) { return; } const text = this.getTextFromCommentBlock(commentBlock); if (text === null) { return; } // Save scores. const scores = this.getWrapperForAdjustedCommentBlock( this.adjustCommentBlock(commentBlock)).getAttribute(WRAPPER_SCORES_ATTR); if (!this.unwrapCommentBlock(commentBlock)) { console.error('comment not initialized yet, not modifying theme:', commentBlock); return; } const wrapperComponent = this.wrapCommentBlock(commentBlock, text); if (wrapperComponent === null) { console.error('wrapCommentBlock unexpectedly failed on block:', commentBlock); return; } wrapperComponent.setAttribute(WRAPPER_SCORES_ATTR, scores); this.setCommentVisibility(wrapperComponent); }); } // Iterates over all comments on the page and decide whether they should be // visible or not based on the current values of threshold and // enabledAttributes. private setAllCommentsVisibility(): void { console.log('setAllCommentsVisibility:', this.threshold, this.enabledAttributes, this.subtypesEnabled); document.body .querySelectorAll('.' + WRAPPER_CLASS + '[' + WRAPPER_SCORES_ATTR + ']') .forEach(wrapper => this.setCommentVisibility(wrapper)); } }
the_stack
import { BoxData, DockMode, DropDirection, LayoutData, maximePlaceHolderId, PanelData, placeHolderStyle, TabBase, TabData, TabGroup } from "./DockData"; let _watchObjectChange: WeakMap<any, any> = new WeakMap(); export function getUpdatedObject(obj: any): any { let result = _watchObjectChange.get(obj); if (result) { return getUpdatedObject(result); } return obj; } function clearObjectCache() { _watchObjectChange = new WeakMap(); } function clone<T>(value: T, extra?: any): T { let newValue: any = {...value, ...extra}; if (Array.isArray(newValue.tabs)) { newValue.tabs = newValue.tabs.concat(); } if (Array.isArray(newValue.children)) { newValue.children = newValue.children.concat(); } _watchObjectChange.set(value, newValue); return newValue; } function maxFlex(currentFlex: number, newFlex: number) { if (currentFlex == null) { return newFlex; } return Math.max(currentFlex, newFlex); } function mergeFlex(currentFlex: number, newFlex: number) { if (currentFlex == null) { return newFlex; } if (currentFlex === newFlex) { return newFlex; } if (currentFlex >= 1) { if (newFlex <= 1) { return 1; } return Math.min(currentFlex, newFlex); } else { if (newFlex >= 1) { return 1; } return Math.max(currentFlex, newFlex); } } let _idCount = 0; export function nextId() { ++_idCount; return `+${_idCount}`; } let _zCount = 0; export function nextZIndex(current?: number): number { if (current === _zCount) { // already the top return current; } return ++_zCount; } function findInPanel(panel: PanelData, id: string, filter: Filter): PanelData | TabData { if (panel.id === id && (filter & Filter.Panel)) { return panel; } if (filter & Filter.Tab) { for (let tab of panel.tabs) { if (tab.id === id) { return tab; } } } return null; } function findInBox(box: BoxData, id: string, filter: Filter): PanelData | TabData | BoxData { let result: PanelData | TabData | BoxData; if ((filter | Filter.Box) && box.id === id) { return box; } for (let child of box.children) { if ('children' in child) { if (result = findInBox(child, id, filter)) { break; } } else if ('tabs' in child) { if (result = findInPanel(child, id, filter)) { break; } } } return result; } export enum Filter { Tab = 1, Panel = 1 << 1, Box = 1 << 2, Docked = 1 << 3, Floated = 1 << 4, Windowed = 1 << 5, Max = 1 << 6, EveryWhere = Docked | Floated | Windowed | Max, AnyTab = Tab | EveryWhere, AnyPanel = Panel | EveryWhere, AnyTabPanel = Tab | Panel | EveryWhere, All = Tab | Panel | Box | EveryWhere, } export function find(layout: LayoutData, id: string, filter: Filter = Filter.AnyTabPanel): PanelData | TabData | BoxData { let result: PanelData | TabData | BoxData; if (filter & Filter.Docked) { result = findInBox(layout.dockbox, id, filter); } if (result) return result; if (filter & Filter.Floated) { result = findInBox(layout.floatbox, id, filter); } if (result) return result; if (filter & Filter.Windowed) { result = findInBox(layout.windowbox, id, filter); } if (result) return result; if (filter & Filter.Max) { result = findInBox(layout.maxbox, id, filter); } return result; } export function addNextToTab(layout: LayoutData, source: TabData | PanelData, target: TabData, direction: DropDirection): LayoutData { let pos = target.parent.tabs.indexOf(target); if (pos >= 0) { if (direction === 'after-tab') { ++pos; } return addTabToPanel(layout, source, target.parent, pos); } return layout; } export function addTabToPanel(layout: LayoutData, source: TabData | PanelData, panel: PanelData, idx = -1): LayoutData { if (idx === -1) { idx = panel.tabs.length; } let tabs: TabData[]; let activeId: string; if ('tabs' in source) { // source is PanelData tabs = source.tabs; activeId = source.activeId; } else { // source is TabData tabs = [source]; } if (tabs.length) { let newPanel = clone(panel); newPanel.tabs.splice(idx, 0, ...tabs); newPanel.activeId = tabs[tabs.length - 1].id; for (let tab of tabs) { tab.parent = newPanel; } if (activeId) { newPanel.activeId = activeId; } layout = replacePanel(layout, panel, newPanel); } return layout; } export function converToPanel(source: TabData | PanelData): PanelData { if ('tabs' in source) { // source is already PanelData return source; } else { let newPanel: PanelData = {tabs: [source], group: source.group, activeId: source.id}; source.parent = newPanel; return newPanel; } } export function dockPanelToPanel(layout: LayoutData, newPanel: PanelData, panel: PanelData, direction: DropDirection): LayoutData { let box = panel.parent; let dockMode: DockMode = (direction === 'left' || direction === 'right') ? 'horizontal' : 'vertical'; let afterPanel = (direction === 'bottom' || direction === 'right'); let pos = box.children.indexOf(panel); if (pos >= 0) { let newBox = clone(box); if (dockMode === box.mode) { if (afterPanel) { ++pos; } panel.size *= 0.5; newPanel.size = panel.size; newBox.children.splice(pos, 0, newPanel); } else { let newChildBox: BoxData = {mode: dockMode, children: []}; newChildBox.size = panel.size; if (afterPanel) { newChildBox.children = [panel, newPanel]; } else { newChildBox.children = [newPanel, panel]; } panel.parent = newChildBox; panel.size = 200; newPanel.parent = newChildBox; newPanel.size = 200; newBox.children[pos] = newChildBox; newChildBox.parent = newBox; } return replaceBox(layout, box, newBox); } return layout; } export function dockPanelToBox(layout: LayoutData, newPanel: PanelData, box: BoxData, direction: DropDirection): LayoutData { let parentBox = box.parent; let dockMode: DockMode = (direction === 'left' || direction === 'right') ? 'horizontal' : 'vertical'; let afterPanel = (direction === 'bottom' || direction === 'right'); if (parentBox) { let pos = parentBox.children.indexOf(box); if (pos >= 0) { let newParentBox = clone(parentBox); if (dockMode === parentBox.mode) { if (afterPanel) { ++pos; } newPanel.size = box.size * 0.3; box.size *= 0.7; newParentBox.children.splice(pos, 0, newPanel); } else { let newChildBox: BoxData = {mode: dockMode, children: []}; newChildBox.size = box.size; if (afterPanel) { newChildBox.children = [box, newPanel]; } else { newChildBox.children = [newPanel, box]; } box.parent = newChildBox; box.size = 280; newPanel.parent = newChildBox; newPanel.size = 120; newParentBox.children[pos] = newChildBox; } return replaceBox(layout, parentBox, newParentBox); } } else if (box === layout.dockbox) { let newBox = clone(box); if (dockMode === box.mode) { let pos = 0; if (afterPanel) { pos = newBox.children.length; } newPanel.size = box.size * 0.3; box.size *= 0.7; newBox.children.splice(pos, 0, newPanel); return replaceBox(layout, box, newBox); } else { // replace root dockbox let newDockBox: BoxData = {mode: dockMode, children: []}; newDockBox.size = box.size; if (afterPanel) { newDockBox.children = [newBox, newPanel]; } else { newDockBox.children = [newPanel, newBox]; } newBox.size = 280; newPanel.size = 120; return replaceBox(layout, box, newDockBox); } } else if (box === layout.maxbox) { let newBox = clone(box); newBox.children.push(newPanel); return replaceBox(layout, box, newBox); } return layout; } export function floatPanel( layout: LayoutData, newPanel: PanelData, rect?: {left: number, top: number, width: number, height: number} ): LayoutData { let newBox = clone(layout.floatbox); if (rect) { newPanel.x = rect.left; newPanel.y = rect.top; newPanel.w = rect.width; newPanel.h = rect.height; } newBox.children.push(newPanel); return replaceBox(layout, layout.floatbox, newBox); } export function panelToWindow( layout: LayoutData, newPanel: PanelData ): LayoutData { let newBox = clone(layout.windowbox); newBox.children.push(newPanel); return replaceBox(layout, layout.windowbox, newBox); } export function removeFromLayout(layout: LayoutData, source: TabData | PanelData): LayoutData { if (source) { let panelData: PanelData; if ('tabs' in source) { panelData = source; layout = removePanel(layout, panelData); } else { panelData = source.parent; layout = removeTab(layout, source); } if (panelData && panelData.parent && panelData.parent.mode === 'maximize') { let newPanel = layout.maxbox.children[0] as PanelData; if (!newPanel || (newPanel.tabs.length === 0 && !newPanel.panelLock)) { // max panel is gone, remove the place holder let placeHolder = find(layout, maximePlaceHolderId) as PanelData; if (placeHolder) { return removePanel(layout, placeHolder); } } } } return layout; } function removePanel(layout: LayoutData, panel: PanelData): LayoutData { let box = panel.parent; if (box) { let pos = box.children.indexOf(panel); if (pos >= 0) { let newBox = clone(box); newBox.children.splice(pos, 1); return replaceBox(layout, box, newBox); } } return layout; } function removeTab(layout: LayoutData, tab: TabData): LayoutData { let panel = tab.parent; if (panel) { let pos = panel.tabs.indexOf(tab); if (pos >= 0) { let newPanel = clone(panel); newPanel.tabs.splice(pos, 1); if (newPanel.activeId === tab.id) { // update selection id if (newPanel.tabs.length > pos) { newPanel.activeId = newPanel.tabs[pos].id; } else if (newPanel.tabs.length) { newPanel.activeId = newPanel.tabs[0].id; } } return replacePanel(layout, panel, newPanel); } } return layout; } export function moveToFront(layout: LayoutData, source: TabData | PanelData): LayoutData { if (source) { let panelData: PanelData; let needUpdate = false; let changes: any = {}; if ('tabs' in source) { panelData = source; } else { panelData = source.parent; if (panelData.activeId !== source.id) { // move tab to front changes.activeId = source.id; needUpdate = true; } } if (panelData && panelData.parent && panelData.parent.mode === 'float') { // move float panel to front let newZ = nextZIndex(panelData.z); if (newZ !== panelData.z) { changes.z = newZ; needUpdate = true; } } if (needUpdate) { layout = replacePanel(layout, panelData, clone(panelData, changes)); } } return layout; } // maximize or restore the panel export function maximize(layout: LayoutData, source: TabData | PanelData): LayoutData { if (source) { if ('tabs' in source) { if (source.parent.mode === 'maximize') { return restorePanel(layout, source); } else { return maximizePanel(layout, source); } } else { return maximizeTab(layout, source); } } return layout; } function maximizePanel(layout: LayoutData, panel: PanelData): LayoutData { let maxbox = layout.maxbox; if (maxbox.children.length) { // invalid maximize return layout; } let placeHodlerPanel: PanelData = { ...panel, id: maximePlaceHolderId, tabs: [], panelLock: {} }; layout = replacePanel(layout, panel, placeHodlerPanel); layout = dockPanelToBox(layout, panel, layout.maxbox, 'middle'); return layout; } function restorePanel(layout: LayoutData, panel: PanelData): LayoutData { layout = removePanel(layout, panel); let placeHolder = find(layout, maximePlaceHolderId) as PanelData; if (placeHolder) { let {x, y, z, w, h} = placeHolder; panel = {...panel, x, y, z, w, h}; return replacePanel(layout, placeHolder, panel); } else { return dockPanelToBox(layout, panel, layout.dockbox, 'right'); } } function maximizeTab(layout: LayoutData, tab: TabData): LayoutData { // TODO to be implemented return layout; } // move float panel into the screen export function fixFloatPanelPos(layout: LayoutData, layoutWidth?: number, layoutHeight?: number): LayoutData { let layoutChanged = false; if (layout && layout.floatbox && layoutWidth > 200 && layoutHeight > 200) { let newFloatChildren = layout.floatbox.children.concat(); for (let i = 0; i < newFloatChildren.length; ++i) { let panel: PanelData = newFloatChildren[i] as PanelData; let panelChange: any = {}; if (panel.w > layoutWidth) { panelChange.w = layoutWidth; } if (panel.h > layoutHeight) { panelChange.h = layoutHeight; } if (panel.y > layoutHeight - 16) { panelChange.y = Math.max(layoutHeight - 16 - (panel.h >> 1), 0); } else if (panel.y < 0) { panelChange.y = 0; } if (panel.x + panel.w < 16) { panelChange.x = 16 - (panel.w >> 1); } else if (panel.x > layoutWidth - 16) { panelChange.x = layoutWidth - 16 - (panel.w >> 1); } if (Object.keys(panelChange).length) { newFloatChildren[i] = clone(panel, panelChange); layoutChanged = true; } } if (layoutChanged) { let newBox = clone(layout.floatbox); newBox.children = newFloatChildren; return replaceBox(layout, layout.floatbox, newBox); } } return layout; } export function fixLayoutData(layout: LayoutData, groups?: {[key: string]: TabGroup}, loadTab?: (tab: TabBase) => TabData): LayoutData { function fixPanelOrBox(d: PanelData | BoxData) { if (d.id == null) { d.id = nextId(); } else if (d.id.startsWith('+')) { let idnum = Number(d.id); if (idnum > _idCount) { // make sure generated id is unique _idCount = idnum; } } if (!(d.size >= 0)) { d.size = 200; } d.minWidth = 0; d.minHeight = 0; d.widthFlex = null; d.heightFlex = null; } function fixPanelData(panel: PanelData): PanelData { fixPanelOrBox(panel); let findActiveId = false; if (loadTab) { for (let i = 0; i < panel.tabs.length; ++i) { panel.tabs[i] = loadTab(panel.tabs[i]); } } if (panel.group == null && panel.tabs.length) { panel.group = panel.tabs[0].group; } let tabGroup = groups?.[panel.group]; if (tabGroup) { if (tabGroup.widthFlex != null) { panel.widthFlex = tabGroup.widthFlex; } if (tabGroup.heightFlex != null) { panel.heightFlex = tabGroup.heightFlex; } } for (let child of panel.tabs) { child.parent = panel; if (child.id === panel.activeId) { findActiveId = true; } if (child.minWidth > panel.minWidth) panel.minWidth = child.minWidth; if (child.minHeight > panel.minHeight) panel.minHeight = child.minHeight; } if (!findActiveId && panel.tabs.length) { panel.activeId = panel.tabs[0].id; } if (panel.minWidth <= 0) { panel.minWidth = 1; } if (panel.minHeight <= 0) { panel.minHeight = 1; } let {panelLock} = panel; if (panelLock) { if (panel.minWidth < panelLock.minWidth) { panel.minWidth = panelLock.minWidth; } if (panel.minHeight < panelLock.minHeight) { panel.minHeight = panelLock.minHeight; } if (panel.panelLock.widthFlex != null) { panel.widthFlex = panelLock.widthFlex; } if (panel.panelLock.heightFlex != null) { panel.heightFlex = panelLock.heightFlex; } } if (panel.z > _zCount) { // make sure next zIndex is on top _zCount = panel.z; } return panel; } function fixBoxData(box: BoxData): BoxData { fixPanelOrBox(box); for (let i = 0; i < box.children.length; ++i) { let child = box.children[i]; child.parent = box; if ('children' in child) { fixBoxData(child); if (child.children.length === 0) { // remove box with no child box.children.splice(i, 1); --i; } else if (child.children.length === 1) { // box with one child should be merged back to parent box let subChild = child.children[0]; if ((subChild as BoxData).mode === box.mode) { // sub child is another box that can be merged into current box let totalSubSize = 0; for (let subsubChild of (subChild as BoxData).children) { totalSubSize += subsubChild.size; } let sizeScale = child.size / totalSubSize; for (let subsubChild of (subChild as BoxData).children) { subsubChild.size *= sizeScale; } // merge children up box.children.splice(i, 1, ...(subChild as BoxData).children); } else { // sub child can be moved up one layer subChild.size = child.size; box.children[i] = subChild; } --i; } } else if ('tabs' in child) { fixPanelData(child); if (child.tabs.length === 0) { // remove panel with no tab if (!child.panelLock) { box.children.splice(i, 1); --i; } else if (child.group === placeHolderStyle && (box.children.length > 1 || box.parent)) { // remove placeHolder Group box.children.splice(i, 1); --i; } } } // merge min size switch (box.mode) { case 'horizontal': if (child.minWidth > 0) box.minWidth += child.minWidth; if (child.minHeight > box.minHeight) box.minHeight = child.minHeight; if (child.widthFlex != null) { box.widthFlex = maxFlex(box.widthFlex, child.widthFlex); } if (child.heightFlex != null) { box.heightFlex = mergeFlex(box.heightFlex, child.heightFlex); } break; case 'vertical': if (child.minWidth > box.minWidth) box.minWidth = child.minWidth; if (child.minHeight > 0) box.minHeight += child.minHeight; if (child.heightFlex != null) { box.heightFlex = maxFlex(box.heightFlex, child.heightFlex); } if (child.widthFlex != null) { box.widthFlex = mergeFlex(box.widthFlex, child.widthFlex); } break; } } // add divider size if (box.children.length > 1) { switch (box.mode) { case 'horizontal': box.minWidth += (box.children.length - 1) * 4; break; case 'vertical': box.minHeight += (box.children.length - 1) * 4; break; } } return box; } if (layout.floatbox) { layout.floatbox.mode = 'float'; } else { layout.floatbox = {mode: 'float', children: [], size: 1}; } if (layout.windowbox) { layout.windowbox.mode = 'window'; } else { layout.windowbox = {mode: 'window', children: [], size: 1}; } if (layout.maxbox) { layout.maxbox.mode = 'maximize'; } else { layout.maxbox = {mode: 'maximize', children: [], size: 1}; } fixBoxData(layout.dockbox); fixBoxData(layout.floatbox); fixBoxData(layout.windowbox); fixBoxData(layout.maxbox); if (layout.dockbox.children.length === 0) { // add place holder panel when root box is empty let newPanel: PanelData = {id: '+0', group: placeHolderStyle, panelLock: {}, size: 200, tabs: []}; newPanel.parent = layout.dockbox; layout.dockbox.children.push(newPanel); } else { // merge and replace root box when box has only one child while (layout.dockbox.children.length === 1 && 'children' in layout.dockbox.children[0]) { let newDockBox = clone(layout.dockbox.children[0] as BoxData); layout.dockbox = newDockBox; for (let child of newDockBox.children) { child.parent = newDockBox; } } } layout.dockbox.parent = null; layout.floatbox.parent = null; layout.windowbox.parent = null; layout.maxbox.parent = null; clearObjectCache(); return layout; } function replacePanel(layout: LayoutData, panel: PanelData, newPanel: PanelData): LayoutData { for (let tab of newPanel.tabs) { tab.parent = newPanel; } let box = panel.parent; if (box) { let pos = box.children.indexOf(panel); if (pos >= 0) { let newBox = clone(box); newBox.children[pos] = newPanel; return replaceBox(layout, box, newBox); } } return layout; } function replaceBox(layout: LayoutData, box: BoxData, newBox: BoxData): LayoutData { for (let child of newBox.children) { child.parent = newBox; } let parentBox = box.parent; if (parentBox) { let pos = parentBox.children.indexOf(box); if (pos >= 0) { let newParentBox = clone(parentBox); newParentBox.children[pos] = newBox; return replaceBox(layout, parentBox, newParentBox); } } else { if (box.id === layout.dockbox.id || box === layout.dockbox) { return {...layout, dockbox: newBox}; } else if (box.id === layout.floatbox.id || box === layout.floatbox) { return {...layout, floatbox: newBox}; } else if (box.id === layout.windowbox.id || box === layout.windowbox) { return {...layout, windowbox: newBox}; } else if (box.id === layout.maxbox.id || box === layout.maxbox) { return {...layout, maxbox: newBox}; } } return layout; } export function getFloatPanelSize(panel: HTMLElement, tabGroup: TabGroup) { if (!panel) { return [300, 300]; } let panelWidth = panel.offsetWidth; let panelHeight = panel.offsetHeight; let [minWidth, maxWidth] = tabGroup.preferredFloatWidth || [100, 600]; let [minHeight, maxHeight] = tabGroup.preferredFloatHeight || [50, 500]; if (!(panelWidth >= minWidth)) { panelWidth = minWidth; } else if (!(panelWidth <= maxWidth)) { panelWidth = maxWidth; } if (!(panelHeight >= minHeight)) { panelHeight = minHeight; } else if (!(panelHeight <= maxHeight)) { panelHeight = maxHeight; } return [panelWidth, panelHeight]; } export function findNearestPanel(rectFrom: DOMRect, rectTo: DOMRect, direction: string): number { let distance = -1; let overlap = -1; let alignment = 0; switch (direction) { case 'ArrowUp': { distance = rectFrom.top - rectTo.bottom + rectFrom.height; overlap = Math.min(rectFrom.right, rectTo.right) - Math.max(rectFrom.left, rectTo.left); break; } case 'ArrowDown': { distance = rectTo.top - rectFrom.bottom + rectFrom.height; overlap = Math.min(rectFrom.right, rectTo.right) - Math.max(rectFrom.left, rectTo.left); break; } case 'ArrowLeft': { distance = rectFrom.left - rectTo.right + rectFrom.width; overlap = Math.min(rectFrom.bottom, rectTo.bottom) - Math.max(rectFrom.top, rectTo.top); alignment = Math.abs(rectFrom.top - rectTo.top); break; } case 'ArrowRight': { distance = rectTo.left - rectFrom.right + rectFrom.width; overlap = Math.min(rectFrom.bottom, rectTo.bottom) - Math.max(rectFrom.top, rectTo.top); alignment = Math.abs(rectFrom.top - rectTo.top); break; } } if (distance < 0 || overlap <= 0) { return -1; } return distance * (alignment + 1) - overlap * 0.001; }
the_stack
import { Category2 } from 'fp-ts/lib/Category' import { Either } from 'fp-ts/lib/Either' import { flow, Predicate, Refinement } from 'fp-ts/lib/function' import { Functor, Functor1, Functor2, Functor3 } from 'fp-ts/lib/Functor' import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from 'fp-ts/lib/HKT' import { Invariant2 } from 'fp-ts/lib/Invariant' import { Option } from 'fp-ts/lib/Option' import { pipe } from 'fp-ts/lib/pipeable' import { ReadonlyNonEmptyArray } from 'fp-ts/lib/ReadonlyNonEmptyArray' import { ReadonlyRecord } from 'fp-ts/lib/ReadonlyRecord' import { Semigroupoid2 } from 'fp-ts/lib/Semigroupoid' import { Traversable1 } from 'fp-ts/lib/Traversable' import * as _ from './internal' import { Iso } from './Iso' import { Optional } from './Optional' import { Prism } from './Prism' import { Traversal } from './Traversal' // ------------------------------------------------------------------------------------- // model // ------------------------------------------------------------------------------------- /** * @category model * @since 2.3.0 */ export interface Lens<S, A> { readonly get: (s: S) => A readonly set: (a: A) => (s: S) => S } // ------------------------------------------------------------------------------------- // constructors // ------------------------------------------------------------------------------------- /** * @category constructors * @since 2.3.8 */ export const lens: <S, A>(get: Lens<S, A>['get'], set: Lens<S, A>['set']) => Lens<S, A> = _.lens /** * @category constructors * @since 2.3.0 */ export const id: <S>() => Lens<S, S> = _.lensId // ------------------------------------------------------------------------------------- // converters // ------------------------------------------------------------------------------------- /** * View a `Lens` as a `Optional`. * * @category converters * @since 2.3.0 */ export const asOptional: <S, A>(sa: Lens<S, A>) => Optional<S, A> = _.lensAsOptional /** * View a `Lens` as a `Traversal`. * * @category converters * @since 2.3.0 */ export const asTraversal: <S, A>(sa: Lens<S, A>) => Traversal<S, A> = _.lensAsTraversal // ------------------------------------------------------------------------------------- // compositions // ------------------------------------------------------------------------------------- /** * Compose a `Lens` with a `Lens`. * * @category compositions * @since 2.3.0 */ export const compose: <A, B>(ab: Lens<A, B>) => <S>(sa: Lens<S, A>) => Lens<S, B> = _.lensComposeLens /** * Alias of `compose`. * * @category compositions * @since 2.3.8 */ export const composeLens = compose /** * Compose a `Lens` with a `Iso`. * * @category compositions * @since 2.3.8 */ export const composeIso: <A, B>(ab: Iso<A, B>) => <S>(sa: Lens<S, A>) => Lens<S, B> = /*#__PURE__*/ flow(_.isoAsLens, compose) /** * Compose a `Lens` with a `Prism`. * * @category compositions * @since 2.3.0 */ export const composePrism: <A, B>(ab: Prism<A, B>) => <S>(sa: Lens<S, A>) => Optional<S, B> = _.lensComposePrism /** * Compose a `Lens` with an `Optional`. * * @category compositions * @since 2.3.0 */ export const composeOptional = <A, B>(ab: Optional<A, B>): (<S>(sa: Lens<S, A>) => Optional<S, B>) => flow(asOptional, _.optionalComposeOptional(ab)) /** * Compose a `Lens` with an `Traversal`. * * @category compositions * @since 2.3.8 */ export const composeTraversal = <A, B>(ab: Traversal<A, B>): (<S>(sa: Lens<S, A>) => Traversal<S, B>) => flow(asTraversal, _.traversalComposeTraversal(ab)) // ------------------------------------------------------------------------------------- // combinators // ------------------------------------------------------------------------------------- /** * @category combinators * @since 2.3.0 */ export const modify = <A>(f: (a: A) => A) => <S>(sa: Lens<S, A>) => (s: S): S => { const o = sa.get(s) const n = f(o) return o === n ? s : sa.set(n)(s) } /** * @category combinators * @since 2.3.5 */ export function modifyF<F extends URIS3>( F: Functor3<F> ): <A, R, E>(f: (a: A) => Kind3<F, R, E, A>) => <S>(sa: Lens<S, A>) => (s: S) => Kind3<F, R, E, S> export function modifyF<F extends URIS2>( F: Functor2<F> ): <A, E>(f: (a: A) => Kind2<F, E, A>) => <S>(sa: Lens<S, A>) => (s: S) => Kind2<F, E, S> export function modifyF<F extends URIS>( F: Functor1<F> ): <A>(f: (a: A) => Kind<F, A>) => <S>(sa: Lens<S, A>) => (s: S) => Kind<F, S> export function modifyF<F>(F: Functor<F>): <A>(f: (a: A) => HKT<F, A>) => <S>(sa: Lens<S, A>) => (s: S) => HKT<F, S> export function modifyF<F>(F: Functor<F>): <A>(f: (a: A) => HKT<F, A>) => <S>(sa: Lens<S, A>) => (s: S) => HKT<F, S> { return (f) => (sa) => (s) => pipe(sa.get(s), f, (fa) => F.map(fa, (a) => sa.set(a)(s))) } /** * Return a `Optional` from a `Lens` focused on a nullable value. * * @category combinators * @since 2.3.0 */ export const fromNullable = <S, A>(sa: Lens<S, A>): Optional<S, NonNullable<A>> => composePrism(_.prismFromNullable<A>())(sa) /** * @category combinators * @since 2.3.0 */ export function filter<A, B extends A>(refinement: Refinement<A, B>): <S>(sa: Lens<S, A>) => Optional<S, B> export function filter<A>(predicate: Predicate<A>): <S>(sa: Lens<S, A>) => Optional<S, A> export function filter<A>(predicate: Predicate<A>): <S>(sa: Lens<S, A>) => Optional<S, A> { return composePrism(_.prismFromPredicate(predicate)) } /** * Return a `Lens` from a `Lens` and a prop. * * @category combinators * @since 2.3.0 */ export const prop: <A, P extends keyof A>(prop: P) => <S>(sa: Lens<S, A>) => Lens<S, A[P]> = _.lensProp /** * Return a `Lens` from a `Lens` and a list of props. * * @category combinators * @since 2.3.0 */ export const props: <A, P extends keyof A>( ...props: readonly [P, P, ...ReadonlyArray<P>] ) => <S>(sa: Lens<S, A>) => Lens<S, { [K in P]: A[K] }> = _.lensProps /** * Return a `Lens` from a `Lens` focused on a component of a tuple. * * @category combinators * @since 2.3.0 */ export const component: <A extends ReadonlyArray<unknown>, P extends keyof A>( prop: P ) => <S>(sa: Lens<S, A>) => Lens<S, A[P]> = _.lensComponent /** * Return a `Optional` from a `Lens` focused on an index of a `ReadonlyArray`. * * @category combinators * @since 2.3.0 */ export const index = (i: number): (<S, A>(sa: Lens<S, ReadonlyArray<A>>) => Optional<S, A>) => flow(asOptional, _.optionalIndex(i)) /** * Return a `Optional` from a `Lens` focused on an index of a `ReadonlyNonEmptyArray`. * * @category combinators * @since 2.3.8 */ export const indexNonEmpty = (i: number): (<S, A>(sa: Lens<S, ReadonlyNonEmptyArray<A>>) => Optional<S, A>) => flow(asOptional, _.optionalIndexNonEmpty(i)) /** * Return a `Optional` from a `Lens` focused on a key of a `ReadonlyRecord`. * * @category combinators * @since 2.3.0 */ export const key = (key: string): (<S, A>(sa: Lens<S, ReadonlyRecord<string, A>>) => Optional<S, A>) => flow(asOptional, _.optionalKey(key)) /** * Return a `Lens` from a `Lens` focused on a required key of a `ReadonlyRecord`. * * @category combinators * @since 2.3.0 */ export const atKey: (key: string) => <S, A>(sa: Lens<S, ReadonlyRecord<string, A>>) => Lens<S, Option<A>> = _.lensAtKey /** * Return a `Optional` from a `Lens` focused on the `Some` of a `Option` type. * * @category combinators * @since 2.3.0 */ export const some: <S, A>(soa: Lens<S, Option<A>>) => Optional<S, A> = /*#__PURE__*/ composePrism(_.prismSome()) /** * Return a `Optional` from a `Lens` focused on the `Right` of a `Either` type. * * @category combinators * @since 2.3.0 */ export const right: <S, E, A>(sea: Lens<S, Either<E, A>>) => Optional<S, A> = /*#__PURE__*/ composePrism(_.prismRight()) /** * Return a `Optional` from a `Lens` focused on the `Left` of a `Either` type. * * @category combinators * @since 2.3.0 */ export const left: <S, E, A>(sea: Lens<S, Either<E, A>>) => Optional<S, E> = /*#__PURE__*/ composePrism(_.prismLeft()) /** * Return a `Traversal` from a `Lens` focused on a `Traversable`. * * @category combinators * @since 2.3.0 */ export function traverse<T extends URIS>(T: Traversable1<T>): <S, A>(sta: Lens<S, Kind<T, A>>) => Traversal<S, A> { return flow(asTraversal, _.traversalTraverse(T)) } /** * @category combinators * @since 2.3.2 */ export function findFirst<A, B extends A>( refinement: Refinement<A, B> ): <S>(sa: Lens<S, ReadonlyArray<A>>) => Optional<S, B> export function findFirst<A>(predicate: Predicate<A>): <S>(sa: Lens<S, ReadonlyArray<A>>) => Optional<S, A> export function findFirst<A>(predicate: Predicate<A>): <S>(sa: Lens<S, ReadonlyArray<A>>) => Optional<S, A> { return composeOptional(_.optionalFindFirst(predicate)) } /** * @category combinators * @since 2.3.8 */ export function findFirstNonEmpty<A, B extends A>( refinement: Refinement<A, B> ): <S>(sa: Lens<S, ReadonlyNonEmptyArray<A>>) => Optional<S, B> export function findFirstNonEmpty<A>( predicate: Predicate<A> ): <S>(sa: Lens<S, ReadonlyNonEmptyArray<A>>) => Optional<S, A> export function findFirstNonEmpty<A>( predicate: Predicate<A> ): <S>(sa: Lens<S, ReadonlyNonEmptyArray<A>>) => Optional<S, A> { return composeOptional(_.optionalFindFirstNonEmpty(predicate)) } // ------------------------------------------------------------------------------------- // pipeables // ------------------------------------------------------------------------------------- /** * @category Invariant * @since 2.3.0 */ export const imap: <A, B>(f: (a: A) => B, g: (b: B) => A) => <E>(sa: Lens<E, A>) => Lens<E, B> = (f, g) => (ea) => imap_(ea, f, g) // ------------------------------------------------------------------------------------- // instances // ------------------------------------------------------------------------------------- const imap_: Invariant2<URI>['imap'] = (ea, ab, ba) => lens(flow(ea.get, ab), flow(ba, ea.set)) /** * @category instances * @since 2.3.0 */ export const URI = 'monocle-ts/Lens' /** * @category instances * @since 2.3.0 */ export type URI = typeof URI declare module 'fp-ts/lib/HKT' { interface URItoKind2<E, A> { readonly [URI]: Lens<E, A> } } /** * @category instances * @since 2.3.0 */ export const Invariant: Invariant2<URI> = { URI, imap: imap_ } /** * @category instances * @since 2.3.8 */ export const Semigroupoid: Semigroupoid2<URI> = { URI, compose: (ab, ea) => compose(ab)(ea) } /** * @category instances * @since 2.3.0 */ export const Category: Category2<URI> = { URI, compose: Semigroupoid.compose, id }
the_stack
import assert from "assert"; import getProvider from "../helpers/getProvider"; import EthereumProvider from "../../src/provider"; describe("forking", () => { describe("auth", () => { describe("Handle invalid url", () => { it("returns the correct error response", async () => { await assert.rejects( getProvider({ fork: { url: "https://mainnet.infura.io/v3/INVALID_URL" // invalid infura URL } }), { message: `Invalid JSON response from fork provider:\n\n invalid project id\n` + `\n\nThe provided fork url, https://mainnet.infura.io/v3/INVALID_URL, may be an invalid or incorrect Infura endpoint.` + `\nVisit https://infura.io/docs/ethereum for Infura documentation.` } ); }); }); describe.skip("Basic Authentication", () => { let provider: EthereumProvider; before(async function () { provider = await getProvider({ fork: { url: "todo", jwt: "todo" } }); }); it("it doesn't crash", async () => { const addresses = [ "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2", "0xbe0eb53f46cd790cd13851d5eff43d12404d33e8", "0x00000000219ab540356cbb839cbe05303d7705fa", "0xc61b9bb3a7a0767e3179713f3a5c7a9aedce193c", "0xdc76cd25977e0a5ae17155770273ad58648900d3", "0x53d284357ec70ce289d6d64134dfac8e511c8a3d", "0x4ddc2d193948926d02f9b1fe9e1daa0718270ed5", "0x73bceb1cd57c711feac4224d062b0f6ff338501e", "0x61edcdf5bb737adffe5043706e7c5bb1f1a56eea", "0x07ee55aa48bb72dcc6e9d78256648910de513eca", "0x229b5c097f9b35009ca1321ad2034d4b3d5070f6", "0x1b3cb81e51011b549d78bf720b0d924ac763a7c2", "0xe853c56864a2ebe4576a807d26fdc4a0ada51919", "0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae", "0xe92d1a43df510f82c66382592a047d288f85226f", "0x2bf792ffe8803585f74e06907900c2dc2c29adcb", "0x267be1c1d684f78cb4f6a176c4911b741e4ffdc0", "0x3f5ce5fbfe3e9af3971dd833d26ba9b5c936f0be", "0xf66852bc122fd40bfecc63cd48217e88bda12109" // "0x558553d54183a8542f7832742e7b4ba9c33aa1e6", // "0xab5801a7d398351b8be11c439e05c5b3259aec9b", // "0x66f820a414680b5bcda5eeca5dea238543f42054", // "0xca8fa8f0b631ecdb18cda619c4fc9d197c8affca", // "0xf977814e90da44bfa03b6295a0616a897441acec", // "0x3bfc20f0b9afcace800d73d2191166ff16540258", // "0x0548f59fee79f8832c299e01dca5c76f034f558e", // "0xc098b2a3aa256d2140208c3de6543aaef5cd3a94", // "0x3dfd23a6c5e8bbcfc9581d2e864a68feb6a076d3", // "0x8103683202aa8da10536036edef04cdd865c225e", // "0x0a4c79ce84202b03e95b7a692e5d728d83c44c76", // "0x2b6ed29a95753c3ad948348e3e7b1a251080ffb9", // "0x1e2fcfd26d36183f1a5d90f0e6296915b02bcb40", // "0x24d48513eac38449ec7c310a79584f87785f856f", // "0x189b9cbd4aff470af2c0102f365fc1823d857965", // "0x00e13ba0cbe2583e23528f4e84ccbf909d39c869", // "0x0e22e8c049f96170ac41e0e3b360a14feb8083a2", // "0x701bd63938518d7db7e0f00945110c80c67df532", // "0xb29380ffc20696729b7ab8d093fa1e2ec14dfe2b", // "0x59448fe20378357f206880c58068f095ae63d5a5", // "0x9bf4001d307dfd62b26a2f1307ee0c0307632d59", // "0xe9fb0895312d39da56c173f1486b1ce934b4004a", // "0xe0f5b79ef9f748562a21d017bb7a6706954b7585", // "0xae93ec389ae6fa1c788ed2e1d222460bb6d0177b", // "0x9845e1909dca337944a0272f1f9f7249833d2d19", // "0x98ec059dc3adfbdd63429454aeb0c990fba4a128", // "0x1ffedd7837bcbc53f91ad4004263deb8e9107540", // "0x657e46adad8be23d569ba3105d7a02124e8def97", // "0x73263803def2ac8b1f8a42fac6539f5841f4e673", // "0x40f0d6fb7c9ddd9cbc1c02a208380c08cf77189b", // "0x78b96178e7ae1ff9adc5d8609e000811657993c8", // "0xd65bd7f995bcc3bdb2ea2f8ff7554a61d1bf6e53", // "0x1a71b118ac6c9086f43bcf2bb6ada3393be82a5c", // "0xfc39f0dc7a1c5d5cd1cdf3b460d5fa99a56abf65", // "0xd44023d2710dd7bef797a074ecec4fc74fdd52b2", // "0x7712bdab7c9559ec64a1f7097f36bc805f51ff1a", // "0x024861e9f89d44d00a7ada4aa89fe03cab9387cd", // "0x7da82c7ab4771ff031b66538d2fb9b0b047f6cf9", // "0x90a9e09501b70570f9b11df2a6d4f047f8630d6d", // "0xbf3aeb96e164ae67e763d9e050ff124e7c3fdd28", // "0xb8808f9e9b88497ec522304055cd537a0913f6a0", // "0x36a85757645e8e8aec062a1dee289c7d615901ca", // "0xf274483d5bb6e2522afea3949728f870ba32bb9c", // "0xa7e4fecddc20d83f36971b67e13f1abc98dfcfa6", // "0x8cf23cd535a240eb0ab8667d24eedbd9eccd5cba", // "0x5b5b69f4e0add2df5d2176d7dbd20b4897bc7ec4", // "0xd69b0089d9ca950640f5dc9931a41a5965f00303", // "0xf774da4418c6dca3051f0e7570829b24214e730b", // "0x3ba25081d3935fcc6788e6220abcace39d58d95d", // "0x12136e543b551ecdfdea9a0ed23ed0eff5505ee0", // "0xfd61352232157815cf7b71045557192bf0ce1884", // "0xfd898a0f677e97a9031654fc79a27cb5e31da34a", // "0x4b4a011c420b91260a272afd91e54accdafdfc1d", // "0xa8dcc0373822b94d7f57326be24ca67bafcaad6b", // "0x844ada2ed8ecd77a1a9c72912df0fcb8b8c495a7", // "0x9c2fc4fc75fa2d7eb5ba9147fa7430756654faa9", // "0xb20411c403687d1036e05c8a7310a0f218429503", // "0x9a1ed80ebc9936cee2d3db944ee6bd8d407e7f9f", // "0xb8cda067fabedd1bb6c11c626862d7255a2414fe", // "0xb9fa6e54025b4f0829d8e1b42e8b846914659632", // "0x701c484bfb40ac628afa487b6082f084b14af0bd", // "0xba18ded5e0d604a86428282964ae0bb249ceb9d0", // "0xfe01a216234f79cfc3bea7513e457c6a9e50250d", // "0x0c05ec4db907cfb91b2a1a29e7b86688b7568a6d", // "0xc4cf565a5d25ee2803c9b8e91fc3d7c62e79fe69", // "0xe04cf52e9fafa3d9bf14c407afff94165ef835f7", // "0x77afe94859163abf0b90725d69e904ea91446c7b", // "0x19d599012788b991ff542f31208bab21ea38403e", // "0xca582d9655a50e6512045740deb0de3a7ee5281f", // "0xd05e6bf1a00b5b4c9df909309f19e29af792422b", // "0x0f00294c6e4c30d9ffc0557fec6c586e6f8c3935", // "0xeb2b00042ce4522ce2d1aacee6f312d26c4eb9d6", // "0x7ae92148e79d60a0749fd6de374c8e81dfddf792", // "0x554f4476825293d4ad20e02b54aca13956acc40a", // "0x9cf36e93a8e2b1eaaa779d9965f46c90b820048c", // "0x4756eeebf378046f8dd3cb6fa908d93bfd45f139", // "0x091933ee1088cdf5daace8baec0997a4e93f0dd6", // "0xa0efb63be0db8fc11681a598bf351a42a6ff50e0", // "0x8b83b9c4683aa4ec897c569010f09c6d04608163", // "0x550cd530bc893fc6d2b4df6bea587f17142ab64e", // "0x828103b231b39fffce028562412b3c04a4640e64", // "0x367989c660881e1ca693730f7126fe0ffc0963fb", // "0xe35b0ef92452c353dbb93775e0df97cedf873c72", // "0x0518f5bb058f6215a0ff5f4df54dae832d734e04", // "0x0e86733eab26cfcc04bb1752a62ec88e910b4cf5", // "0x0ff64c53d295533a37f913bb78be9e2adc78f5fe", // "0xb8b6fe7f357adeab950ac6c270ce340a46989ce1", // "0xeddf8eb4984cc27407a568cae1c78a1ddb0c2c1b", // "0x7145cfedcf479bede20c0a4ba1868c93507d5786", // "0x2fa9f9efc767650aace0422668444c3ff63e1f8d", // "0xd57479b8287666b44978255f1677e412d454d4f0", // "0x4baf012726cb5ec7dda57bc2770798a38100c44d", // "0x6262998ced04146fa42253a5c0af90ca02dfd2a3", // "0x19184ab45c40c2920b0e0e31413b9434abd243ed", // "0xb5ab08d153218c1a6a5318b14eeb92df0fb168d6", // "0x5195427ca88df768c298721da791b93ad11eca65", // "0x0a869d79a7052c7f1b55a8ebabbea3420f0d1e13", // "0x8d95842b0bca501446683be598e12f1c616770c1", // "0xa4a6a282a7fc7f939e01d62d884355d79f5046c1", // "0x35aeed3aa9657abf8b847038bb591b51e1e4c69f", // "0xefb2e870b14d7e555a31b392541acf002dae6ae9", // "0xb93d8596ac840816bd366dc0561e8140afd0d1cb", // "0x11577a8a5baf1e25b9a2d89f39670f447d75c3cd", // "0xdcd0272462140d0a3ced6c4bf970c7641f08cd2c", // "0xaf10cc6c50defff901b535691550d7af208939c5", // "0x67f706db3bbd04a250eed049386c5d09c4ee31f0", // "0x3d4530082c3eb60f58af03f79b1ed3f40e591cd1", // "0x595faf77e533a5cd30ab5859c9a0116de8bad8db", // "0x1bd3fc5ac794e7af8e834a8a4d25b08acd9266ce", // "0xd5268a476aadd1a6729df5b3e5e8f2c1004139af", // "0x7ead3a4361bd26a20deb89c9470be368ee9cb6f1", // "0xf481b7fab9f5d0e74f21ae595a749634fb053619", // "0xdb3c617cdd2fbf0bb4309c325f47678e37f096d9", // "0xd47b4a4c6207b1ee0eb1dd4e5c46a19b50fec00b", // "0xa1a45e91164cdab8fa596809a9b24f8d4fdbe0f3", // "0x16769e533352798deb664ba570230a758346ca1a", // "0x3bc643a841915a267ee067b580bd802a66001c1d", // "0xd65fb7d4cb595833e84c3c094bd4779bab0d4c62", // "0x4ce6b9b77a2e3341c4f94c751cd5c3b2424eb4b2", // "0x376c3e5547c68bc26240d8dcc6729fff665a4448", // "0x2125f3189cd5d650d6142b222f20083efc2d05f2", // "0x1b8766d041567eed306940c587e21c06ab968663", // "0x8fe68ee399bff5f8373b4b0877eaa518ca2026d3", // "0x6a11f3e5a01d129e566d783a7b6e8862bfd66cca", // "0xd9858d573a26bca124282afa21ca4f4a06eff98a", // "0x991a7ff3cb20d5b5d6d9be5efec4e4c51cddad7a", // "0x47029dc4f3922706bf670d335c45550cff4f6a35", // "0x8ae880b5d35305da48b63ce3e52b22d17859f293", // "0x5a710a3cdf2af218740384c52a10852d8870626a", // "0x27321f84704a599ab740281e285cc4463d89a3d5", // "0xbf4ed7b27f1d666546e30d74d50d173d20bca754", // "0xdb89045c811549f7eb925ec16f7d0cd7166556b3", // "0x4eac9ce57af61a6fb1f61f0bf1d8586412be30bc", // "0x5657e633be5912c6bab132315609b51aadd01f95", // "0x7d465b1b48855925ae5fad79b68415468d6a866e", // "0x999e77c988c4c1451d3b1c104a6cca7813a9946e", // "0x7d6149ad9a573a6e2ca6ebf7d4897c1b766841b4", // "0x4fdd5eb2fb260149a3903859043e962ab89d8ed4", // "0x1fe29b608c1cab7b7354fc96c7bbb2a68355ced6", // "0xcdbf58a9a9b54a2c43800c50c7192946de858321", // "0x40f50e8352d64af0ddda6ad6c94b5774884687c3", // "0x2d89034424db22c9c555f14692a181b22b17e42c", // "0x6586ce3d543e0c57b347f0c3b9eeed2f132c104f", // "0x4b5d3010905e0a2f62cce976d52c4f6eb5e545a5", // "0x7f3a1e45f67e92c880e573b43379d71ee089db54", // "0x469f1ea76d13d4b4ea20a233eac8ce6ac74d5087", // "0xb7b678375ee3841846e11765739f04ca9bb75a9a", // "0x3a048255067e077001d970d03da5c9f335f9b77e", // "0x539c92186f7c6cc4cbf443f26ef84c595babbca1", // "0xbfbbfaccd1126a11b8f84c60b09859f80f3bd10f", // "0x868dab0b8e21ec0a48b726a1ccf25826c78c6d7f", // "0x44c2eb90a6d5d74dce8dccbd485cd889f8bc7b6a", // "0x1cc1c81fd28cd948e94da74fa22fc4182d9ecfec", // "0xd47ae555e8d869794adf7d1dbb78a7e47ccf811f", // "0xae3808749e520415fd5184a5ee333b65cc86be8c", // "0xc39cc669a548c661dfa6b5a1eeaa389d1ec53143", // "0x2fd56159f4c8664a1de5c75e430338cfa58cd5b9", // "0xa0e239b0abf4582366adaff486ee268c848c4409", // "0x63b421492ac68600ca218e29f0d432389886d894", // "0x28140cb1ac771d4add91ee23788e50249c10263d", // "0xc5424b857f758e906013f3555dad202e4bdb4567", // "0xa160cdab225685da1d56aa342ad8841c3b53f291", // "0x8b15eb5ea0a405da4d82f26d9197fad62ef7405a", // "0xc56fefd1028b0534bfadcdb580d3519b5586246e", // "0x86a6a0080b1a4c9390416cf73ffb02738d94f8d6", // "0xd793281182a0e3e023116004778f45c29fc14f19", // "0x0dbd8de20eed94a5693d57998827fcf68ed2ecf4", // "0xd24400ae8bfebb18ca49be86258a3c749cf46853", // "0x1b29dd8ff0eb3240238bf97cafd6edea05d5ba82", // "0x76ae5632ae65d95dd704218920f7d8ac4daef9cc", // "0x282edab8a933bc1c02649fe3ea2842ecbe9928a7", // "0x3cceb0d443ca4b1320ae4fa60a053eac163ca512", // "0x30a2ebf10f34c6c4874b0bdd5740690fd2f3b70c", // "0xe4f4866437513e7e023fb3933ba43045312b7459", // "0x1bb762b16438f8b287626fd1042bc6f6848cc286", // "0xdc24316b9ae028f1497c275eb9192a3ea0f67022", // "0xb3764761e297d6f121e79c32a65829cd1ddb4d32", // "0xb46427e2cddecb0bde40bf402361effddd4401e2", // "0x2eb08efb9e10d9f56e46938f28c13ecb33f67b15", // "0xca0a044400c1fa857e4cd0c95d86376b85659303", // "0x18c535cdf2f10a62471676682d00b408306cae0b", // "0x1085b9c6e43895cc441ba1840b940ef786683785", // "0x677f887fae0873bcf7e800f77bc7643063c7dece", // "0x28973c01a23a002e8c40dc123858fd2122e50f87", // "0x583197dccce7e295525acfa016eabe1b25becbc6", // "0x46fde20dfde85c8c169e8823b6f615146674103e", // "0x7d783603bd1caed3cdb8e734a50fb35df1f1da7a", // "0x58c1655ee5c109bf69715411dc32338e40a54c46", // "0x385dc986ac6dfaefe851ac95d3650e0baafef3ac", // "0x67586e3526bbe9f3e19d76bb41f1de0a774b50b4", // "0x79f67f689b9925710d4dda2a39d680e9cea61c81", // "0x6d9d2b30df394f17a5058aceb9a4d3446f1bc042", // "0xd2b0b1daed605718080f861034d3241f1cfd89cb", // "0x368d43c23843ca9b49dc861d80251bda6a090367", // "0x88a7ef2f047f8b07c6c917a6fd1a13438e9d8424", // "0x1d0295df8712965a22e6851059ba205d07542b77", // "0xfdfeb7474b6b104f32599948bb7f8ed81b06def3", // "0xcfee6efec3471874022e205f4894733c42cbbf64", // "0x8033539e873b3f0deaba706dd6d3480e0dd5cb30", // "0x3f7e77b627676763997344a1ad71acb765fc8ac5", // "0x23b8fdb94858cbf1f917256ff7bf20d4ea768110", // "0x80845058350b8c3df5c3015d8a717d64b3bf9267", // "0x7566126f2fd0f2dddae01bb8a6ea49b760383d5a", // "0x802ea31c421ec79e8190cb68b699af3e3bc625fe", // "0xe5e47125d919c4efdff82ab8792e319096492a87", // "0x755cdba6ae4f479f7164792b318b2a06c759833b", // "0x438cb3c3efe8ff20878726da06b7c26db1138f3e", // "0x21346283a31a5ad10fa64377e77a8900ac12d469", // "0x6b378be3c9642ccf25b1a27facb8ace24ac34a12", // "0x1e143b2588705dfea63a17f2032ca123df995ce0", // "0x4920f22b632bfaa40af8d39c31d9607809485952", // "0xe9778e69a961e64d3cdbb34cf6778281d34667c2", // "0xef110ca3c34a5074d455d687ac98f40c03d16173", // "0xf4fa0e6c5ab8d4c9c45c40cf48a8bbbb5cb4f046", // "0xa2f6abe26fe0e1c1f2684ab002ed02a59ffbf85a", // "0xdfb6a4b143f6a1de4725c451c46433801de52bfd", // "0x8759b0b1d9cba80e3836228dfb982abaa2c48b97", // "0x1522900b6dafac587d499a862861c0869be6e428", // "0x97e813b9a81d097e60a5e6311bc9a475199b67ae", // "0xaf306bad224f70d6e1971ba17d97c144cab119e4", // "0x742d35cc6634c0532925a3b844bc454e4438f44e", // "0x8b505e2871f7deb7a63895208e8227dcaa1bff05", // "0x1e22cd8cfa52e950e1f1e78d7e9d59b20df63909", // "0xe5ab43ec248ba3dcf7b57ec498701a7d0576f2e2", // "0x711cd20bf6b436ced327a8c65a14491aa04c2ca1", // "0xff64a8933e05c9d585ab72db95d207ebee9be5a8", // "0x3262f13a39efaca789ae58390441c9ed76bc658a", // "0x9a9d870472bee65080e82bf3591f7c91de31a7cc", // "0x19bf56fca395a600c20f732b05757f30ad24a719", // "0x04b7f4195595d8132dd8249cc8dc7e79a6ae772b", // "0xff2ac8c5834a7585fcc97edb8ba2431c4beab487", // "0x4ed97d6470f5121a8e02498ea37a50987da0eec0", // "0xcac9c634b4464efe71a9a5910edba06686baf457", // "0x2d1566722288be5525b548a642c98b546f116aa0", // "0xf443864ba5d5361bbc54298551067194f980a635", // "0x84bf16e7675cee22d0e0302913ccf58b45333ddf", // "0x891404dd46a473584f5510d5ecbfd8d83794428f", // "0x06fed18718975d9e178e0c0fea35c18eac794c3f", // "0x1342a001544b8b7ae4a5d374e33114c66d78bd5f", // "0xb4f4317b7885de16305d1303570879c21f378255", // "0xd4914762f9bd566bd0882b71af5439c0476d2ff6", // "0x5bcd25b6e044b97dfc941b9ec4b617ec10e1abcd", // "0xa43d2e05ed00c040c8422a88cb8ede921a539f92", // "0x998a7fd73446cd6532bf3058a270581730b27137", // "0x084ef8564b4f75a70b7ad5e8aabf73edac005397", // "0x904cc2b2694ffa78f04708d6f7de205108213126", // "0x693be1ea307e3b3826d34e96336399969898dee8", // "0x8c3389616404fda275cfdba0c7b0b3d1fee9ebdc", // "0xf8a4d3a0b5859a24cd1320ba014ab17f623612e2", // "0xb4db55a20e0624edd82a0cf356e3488b4669bd27", // "0x51cab40a6895d2a5c092f3766b3b9830884b0adf", // "0x2a77d03a2eb21d0d4a3841c62fa4340465b03a3f", // "0x8dc250d5403ba72cbeaf0ac40f7c61c6db3a9a20", // "0x05576087d1ad92873da0a3b76e7105195935b0f5", // "0x7c2a289c0523e748c286a37570d2efc16d2c934e", // "0x062448f804191128d71fc72e10a1d13bd7308e7e", // "0x6a25f40929a1fe4984f914b9d87e2c461cce369b", // "0x36e5c4b77138f0c6386ef969225a005c28bcda63", // "0xbba17b81ab4193455be10741512d0e71520f43cb", // "0xa7efae728d2936e78bda97dc267687568dd593f3", // "0xe20c0178c91050155f461685c24db0c0276c94b6", // "0xa646e29877d52b9e2de457eca09c724ff16d0a2b", // "0x51fd527c62e40bc1ef62f1269f7f13c994777ee2", // "0xe2f34156be01c20aa815530d3a05b8951178bd81", // "0xd0ffc75e8000cba848d259b8d121a7bfcc13dce8", // "0x1f2dfb84fb0afdaf1019b9309181fa0fc86b61c0", // "0x11a05633e78aabf81cbc84d58e0f8d07fd25c992", // "0x876eabf441b2ee5b5b0554fd502a8e0600950cfa", // "0x955a27306f1eb21757ccbd8daa2de82675aabc36", // "0xceffc7330317f72957c662d072a5e7d63b9b578c", // "0x14c728c9aeeafce01f1a7b87d02255dd4326f180", // "0x31e8e8b728bcde2287c275de4bedc4d8c6efa925", // "0x50cb0508434b4c68a2c4fde30b02b269d2d5b6bd", // "0xf79f21c74a1e53c5eb148eb0c6e64196a30d439c", // "0x9d3937226a367bedce0916f9cee4490d22214c7c", // "0x9a9bed3eb03e386d66f8a29dc67dc29bbb1ccb72", // "0xd641651ed7e19a04ce536610d75b3dcaf427ad73", // "0x50bd66bfddf48b8914602bf51c93756731ec51ae", // "0x5a03703125380cfda804446fdaa3b4064cb6cc0a", // "0xc3ecba28af450e2ed469164766751130d93ecc36", // "0x6220d7a458a68d6a554e5904792049fd2ef6bbcc" ]; const aa = await provider.send("eth_getBlockByNumber", [ "0xb3c207", true ]); const aa1 = await provider.send("eth_getBlockByNumber", ["0xb3c207"]); const aa2 = await provider.send("eth_getBlockByNumber", ["0xb3c207"]); const aa3 = await provider.send("eth_getBlockByNumber", ["0xb3c207"]); return; let p = addresses.map(address => { return provider.send("eth_getBalance", [address]).then(balance => { console.log(address, BigInt(balance)); }); }); await Promise.all(p); p = addresses.map(address => { return provider.send("eth_getBalance", [address]).then(balance => { console.log(address, BigInt(balance)); }); }); await Promise.all(p); p = addresses.map(address => { return provider.send("eth_getBalance", [address]).then(balance => { console.log(address, BigInt(balance)); }); }); await Promise.all(p); // const result = await provider.send("eth_getBalance", [ // "0xBE0eB53F46cd790Cd13851d5EFf43D12404d33E8" // ]); // console.log(BigInt(result)); }).timeout(0); }); }); });
the_stack
import { NameKeyMap, SwaggerSailsModel, SwaggerModelAttribute, SwaggerSailsControllers, SwaggerControllerAttribute, SwaggerRouteInfo, BluePrintAction, SwaggerActionAttribute, MiddlewareType } from "./interfaces"; import { forEach, defaults, cloneDeep, groupBy, mapValues, map } from "lodash"; import { Tag } from "swagger-schema-official"; import { OpenApi } from "../types/openapi"; import path from "path"; const transformSailsPathToSwaggerPath = (path: string): string => { return path .split('/') .map(v => v.replace(/^:([^/:?]+)\??$/, '{$1}')) .join('/'); } /** * Maps from a Sails route path of the form `/path/:id` to a * Swagger path of the form `/path/{id}`. * * Also transform standard Sails primary key reference '{id}' to * '_{primaryKeyAttributeName}'. * * Add underscore to path variable names, used to differentiate the PK value * used for paths from query variables. Specifically, differentiate the PK value * used for shortcut blueprint update routes, which allow for PK update * using query parameters. Some validators expect unique names across all * parameter types. */ export const transformSailsPathsToSwaggerPaths = (routes: SwaggerRouteInfo[]): void => { routes.map(route => { route.path = transformSailsPathToSwaggerPath(route.path); if (route.model?.primaryKey) { const pathVariable = '_' + route.model.primaryKey; route.path = route.path.replace('{id}', `{${pathVariable}}`); route.variables = route.variables.map(v => v === 'id' ? pathVariable : v); route.optionalVariables = route.optionalVariables.map(v => v === 'id' ? pathVariable : v); } }); }; /* * Sails returns individual routes for each association: * - /api/v1/quote/:parentid/supplier/:childid * - /api/v1/quote/:parentid/items/:childid * * where the model is 'quote' and the populate aliases are 'supplier' and 'items'. * * We now aggreggate these routes considering: * 1. Blueprint prefix, REST prefix, and model including any pluralization * 2. More complete grouping check including verb, model, and blueprint * * Note that we seek to maintain order of routes. * * RESTful Blueprint Routes * - **add**: PUT /api/v2/activitysummary/:parentid/${alias}/:childid * - **remove**: DELETE /api/v2/activitysummary/:parentid/${alias}/:childid * - **replace**: PUT /api/v2/activitysummary/:parentid/${alias} * - **populate**: GET /api/v2/activitysummary/:parentid/${alias} * * Shortcut Routes * - **add**: GET /api/v2/activitysummary/:parentid/${alias}/add/:childid * - **remove**: GET /api/v2/activitysummary/:parentid/${alias}/remove/:childid * - **replace**: GET /api/v2/activitysummary/:parentid/${alias}/replace * * @see https://sailsjs.com/documentation/concepts/blueprints/blueprint-routes#?restful-blueprint-routes * @see https://sailsjs.com/documentation/concepts/blueprints/blueprint-routes#?shortcut-blueprint-routes * */ export const aggregateAssociationRoutes = (boundRoutes: SwaggerRouteInfo[] /*, models: NameKeyMap<SwaggerSailsModel>*/): SwaggerRouteInfo[] => { type AnnotatedRoute = { route: SwaggerRouteInfo; match: RegExpMatchArray }; /* standard Sails blueprint path pattern, noting that prefix (match[1]) includes * blueprint prefix, REST prefix, and model including any pluralization. */ const re = /^(\/.*)\/{parentid}\/([^/]+)(\/(?:add|remove|replace))?(\/{childid})?$/; // only considering these relevant actions const actions: BluePrintAction[] = [ 'add', 'remove', 'replace', 'populate' ]; // step 1: filter to include path matched blueprint actions with a single association alias defined const routesToBeAggregated = boundRoutes.map(route => { if (route.blueprintAction && actions.indexOf(route.blueprintAction as BluePrintAction) >= 0 && route.associationAliases && route.associationAliases.length === 1) { const match = route.path.match(re); if (match && route.associationAliases[0]===match[2]) { return { route, match } as AnnotatedRoute; } } return undefined; }) .filter(r => !!r) as AnnotatedRoute[]; // step 2: group by verb --> then route prefix --> then model identity --> then blueprint action const groupedByVerb = groupBy(routesToBeAggregated, r => r.route.verb); const thenByPathPrefix = mapValues(groupedByVerb, verbGroup => groupBy(verbGroup, r => r.match[1])); const thenByModelIdentity = mapValues(thenByPathPrefix, verbGroup => mapValues(verbGroup, prefixGroup => groupBy(prefixGroup, r => r.route.model!.identity))); const thenByAction = mapValues(thenByModelIdentity, verbGroup => mapValues(verbGroup, prefixGroup => mapValues(prefixGroup, modelGroup => groupBy(modelGroup, r => r.route.blueprintAction)))); // const example = { // get: { // <-- verb groups // '/api/v9/rest/pets': { // <-- url prefix groups // pet: { // <-- model identity groups // populate: [ // <-- blueprint association action groups (add, remove, replace, populate) // { // route: { path: '/api/v9/rest/pets/{parentid}/owner', ... }, // match: ['/api/v9/rest/pets/{parentid}/owner', '/api/v9/rest/pets', ... ], // }, { // route: { path: '/api/v9/rest/pets/{parentid}/caredForBy', ... }, // match: ['/api/v9/rest/pets/{parentid}/caredForBy', '/api/v9/rest/pets', ... ], // } // ] // } // } // } // }; // step 3: perform aggregation of leaf groups const transformedRoutes: NameKeyMap<SwaggerRouteInfo | 'REMOVE'> = {}; map(thenByAction, verbGroup => { map(verbGroup, prefixGroup => { map(prefixGroup, modelGroup => { map(modelGroup, actionGroup => { // first route becomes 'aggregated' version const g = actionGroup[0]; const prefix = g.match[1]; const pk = '_' + g.route.model!.primaryKey; // note '_' as per transformSailsPathsToSwaggerPaths() const shortcutRoutePart = g.match[3] || ''; const childPart = g.match[4] || ''; const aggregatedRoute = { ...g.route, path: `${prefix}/{${pk}}/{association}${shortcutRoutePart}${childPart}`, variables: [ ...g.route.variables.map(v => v==='parentid' ? pk : v), 'association' ], optionalVariables: g.route.optionalVariables.map(v => v==='parentid' ? pk : v), associationAliases: actionGroup.map(r => r.route.associationAliases![0]), } const routeKey = g.route.verb + '|' + g.route.path; transformedRoutes[routeKey] = aggregatedRoute; // mark others for removal actionGroup.slice(1).map(g => { const routeKey = g.route.verb + '|' + g.route.path; transformedRoutes[routeKey] = 'REMOVE'; }); }) }) }) }); // step 4: filter return boundRoutes.map(route => { const routeKey = route.verb + '|' + route.path; if(transformedRoutes[routeKey] === undefined) { return route; // not being aggregrated --> retain } else if(transformedRoutes[routeKey] === 'REMOVE') { return undefined; // mark for removal } else { return transformedRoutes[routeKey]; // new aggregated route } }) .filter(r => !!r) as SwaggerRouteInfo[]; } /** * Merges JSDoc `actions` and `model` elements **but not** `components` and `tags` * (which are merged in `mergeComponents()` and `mergeTags()`). * * @param models * @param modelsJsDoc */ export const mergeModelJsDoc = (models: NameKeyMap<SwaggerSailsModel>, modelsJsDoc: NameKeyMap<SwaggerModelAttribute>): void => { forEach(models, model => { const modelJsDoc = modelsJsDoc[model.identity]; if(modelJsDoc) { if(modelJsDoc.actions) { forEach(modelJsDoc.actions, (action, actionName) => { if(!model.swagger.actions) { model.swagger.actions = {}; } if(!model.swagger.actions[actionName]) { model.swagger.actions[actionName] = { ...action }; } else { defaults(model.swagger.actions[actionName], action); } }); } if(modelJsDoc.modelSchema) { if(!model.swagger.modelSchema) { model.swagger.modelSchema = { ...modelJsDoc.modelSchema }; } else { defaults(model.swagger.modelSchema, modelJsDoc.modelSchema); } } } }); } /** * Merges JSDoc into `controllerFiles` (not `actions`). * * The merge includes JSDoc `actions` and `controller` elements **but not** `components` and `tags` * (which are merged in `mergeComponents()` and `mergeTags()`). * * @param controllers * @param controllersJsDoc */ export const mergeControllerJsDoc = (controllers: SwaggerSailsControllers, controllersJsDoc: NameKeyMap<SwaggerControllerAttribute>): void => { forEach(controllers.controllerFiles, (controllerFile, identity) => { const controllerJsDoc = controllersJsDoc[identity]; if(controllerJsDoc) { if(controllerJsDoc.actions) { forEach(controllerJsDoc.actions, (action, actionName) => { if(!controllerFile.swagger.actions) { controllerFile.swagger.actions = {}; } if(!controllerFile.swagger.actions[actionName]) { controllerFile.swagger.actions[actionName] = { ...action }; } else { defaults(controllerFile.swagger.actions[actionName], action); } }); } } }); } /** * Merges controller file Swagger/JSDoc into `routes` from controller files and controller file JSDoc. * * The merge includes JSDoc `actions` and `exclude` elements **but not** `components` and `tags` * (which are merged in `mergeComponents()` and `mergeTags()`). * * Specifically, in order of precedence: * 1. Route itself; in `SwaggerRouteInfo` and taken from `route.options` (from `config/routes.js` or route bound by hook) * 2. Controller file action function `swagger` element (`controllers.actions[].swagger` below) * 3. Controller file `swagger` element export (`controllers.controllerFiles[].swagger.actions[]` below) incl `allActions`. * 4. Controller file JSDoc `@swagger` comments under the `/{action}` path (`controllersJsDoc[].actions[]` below) incl `allActions`. * * This function also merges the Actions2Machine details (inputs, exits etc) into `routes`. * * @param sails * @param routes * @param controllers * @param controllersJsDoc */ export const mergeControllerSwaggerIntoRouteInfo = (sails: Sails.Sails, routes: SwaggerRouteInfo[], controllers: SwaggerSailsControllers, controllersJsDoc: NameKeyMap<SwaggerControllerAttribute>): void => { routes.map(route => { const mergeIntoDest = (source: SwaggerActionAttribute | undefined) => { if(!source) { return; } if(!route.swagger) { route.swagger = { ...source }; } else { defaults(route.swagger, source); } } const actionNameLookup = path.basename(route.action); const controllerAction = controllers.actions[route.action]; if (controllerAction) { // for actions, route will have action type 'function' --> update from controller info route.actionType = controllerAction.actionType; route.defaultTagName = controllerAction.defaultTagName; // for actions2, store machine metadata (inputs, exits etc) into route if(route.actionType === 'actions2') { route.actions2Machine = controllerAction; } /* * Step 2: Controller file action function `swagger` element */ mergeIntoDest(controllerAction.swagger); /* * Step 3: Controller file `swagger` element export */ const controllerFileIdentity = controllerAction.actionType === 'controller' ? path.dirname(route.action) : route.action; const controllerFile = controllers.controllerFiles[controllerFileIdentity]; if(controllerFile) { if (controllerFile.swagger) { if (controllerFile.swagger.actions) { mergeIntoDest(controllerFile.swagger.actions[actionNameLookup]); } mergeIntoDest(controllerFile.swagger.actions?.allactions); } } else { sails.log.error(`ERROR: sails-hook-swagger-generator: Error resolving/loading controller file '${controllerFileIdentity}'`); } /* * Step 4: Controller file JSDoc `@swagger` comments under the `/{action}` path */ const controllerJsDoc = controllersJsDoc[controllerFileIdentity]; if(controllerJsDoc && controllerJsDoc.actions) { mergeIntoDest(controllerJsDoc.actions[actionNameLookup]); mergeIntoDest(controllerJsDoc.actions.allactions); } } else { if(route.middlewareType === MiddlewareType.ACTION) { sails.log.error(`ERROR: sails-hook-swagger-generator: Error resolving/loading controller action '${route.action}' source file`); } } }); } /** * Merge elements of components from `config/routes.js`, model definition files and * controller definition files. * * Elements of components are added to the top-level Swagger/OpenAPI definitions as follows: * 1. Elements of the component definition reference (schemas, parameters, etc) are added where * they **do not exist**. * 2. Existing elements are **not** overwritten or merged. * * For example, the element `components.schemas.pet` will be added as part of a merge process, * but the contents of multiple definitions of `pet` **will not** be merged. * * @param dest * @param routesJsDoc * @param models * @param controllers */ export const mergeComponents = (dest: OpenApi.Components, // routesJsDoc: OpenApi.OpenApi, models: NameKeyMap<SwaggerSailsModel>, modelsJsDoc: NameKeyMap<SwaggerModelAttribute>, controllers: SwaggerSailsControllers, controllersJsDoc: NameKeyMap<SwaggerControllerAttribute>): void => { const mergeIntoDest = (source: OpenApi.Components | undefined) => { if (!source) { return; } for (const key in source) { const componentName = key as keyof OpenApi.Components; if (!dest[componentName]) { (dest[componentName] as unknown) = {}; } defaults(dest[componentName], source[componentName]); } } // WIP TBC mergeIntoDest(routesJsDoc.components); forEach(models, model => mergeIntoDest(model.swagger?.components)); forEach(modelsJsDoc, jsDoc => mergeIntoDest(jsDoc.components)); forEach(controllers.controllerFiles, controllerFile => mergeIntoDest(controllerFile.swagger?.components)); forEach(controllersJsDoc, jsDoc => mergeIntoDest(jsDoc.components)); } /** * Merge tag definitions from `config/routes.js`, model definition files and * controller definition files. * * Tags are added to the top-level Swagger/OpenAPI definitions as follows: * 1. If a tags with the specified name **does not** exist, it is added. * 1. Where a tag with the specified name **does** exist, elements _of that tag_ that do not exist are added * e.g. `description` and `externalDocs` elements. * * @param dest * @param routesJsDoc * @param models * @param controllers */ export const mergeTags = (dest: Tag[], // routesJsDoc: OpenApi.OpenApi, models: NameKeyMap<SwaggerSailsModel>, modelsJsDoc: NameKeyMap<SwaggerModelAttribute>, controllers: SwaggerSailsControllers, controllersJsDoc: NameKeyMap<SwaggerControllerAttribute>, defaultModelTags: Tag[]): void => { const mergeIntoDest = (source: Tag[] | undefined) => { if(!source) { return; } source.map(sourceTag => { const destTag = dest.find(t => t.name === sourceTag.name); if(destTag) { defaults(destTag, sourceTag); // merge into existing } else { dest.push(cloneDeep(sourceTag)); // add new tag } }); } // WIP TBC mergeIntoDest(routesJsDoc.tags); forEach(models, model => mergeIntoDest(model.swagger?.tags)); forEach(modelsJsDoc, jsDoc => mergeIntoDest(jsDoc.tags)); forEach(controllers.controllerFiles, controllerFile => mergeIntoDest(controllerFile.swagger?.tags)); forEach(controllersJsDoc, jsDoc => mergeIntoDest(jsDoc.tags)); mergeIntoDest(defaultModelTags); }
the_stack
import * as canvas from "canvas"; import * as fs from "fs"; import * as minimist from "minimist"; import * as path from "path"; import * as process from "process"; import { ColorReducer } from "../src/colorreductionmanagement"; import { RGB } from "../src/common"; import { FacetBorderSegmenter } from "../src/facetBorderSegmenter"; import { FacetBorderTracer } from "../src/facetBorderTracer"; import { FacetCreator } from "../src/facetCreator"; import { FacetLabelPlacer } from "../src/facetLabelPlacer"; import { FacetResult } from "../src/facetmanagement"; import { FacetReducer } from "../src/facetReducer"; import { Settings } from "../src/settings"; import { Point } from "../src/structs/point"; const svg2img = require("svg2img"); class CLISettingsOutputProfile { public name: string = ""; public svgShowLabels: boolean = true; public svgFillFacets: boolean = true; public svgShowBorders: boolean = true; public svgSizeMultiplier: number = 3; public svgFontSize: number = 60; public svgFontColor: string = "black"; public filetype: "svg" | "png" | "jpg" = "svg"; public filetypeQuality: number = 95; } class CLISettings extends Settings { public outputProfiles: CLISettingsOutputProfile[] = []; } async function main() { const args = minimist(process.argv.slice(2)); const imagePath = args.i; const svgPath = args.o; if (typeof imagePath === "undefined" || typeof svgPath === "undefined") { console.log("Usage: exe -i <input_image> -o <output_svg> [-c <settings_json>]"); process.exit(1); } let configPath = args.c; if (typeof configPath === "undefined") { configPath = path.join(process.cwd(), "settings.json"); } else { if (!path.isAbsolute(configPath)) { configPath = path.join(process.cwd(), configPath); } } const settings: CLISettings = require(configPath); const img = await canvas.loadImage(imagePath); const c = canvas.createCanvas(img.width, img.height); const ctx = c.getContext("2d"); ctx.drawImage(img, 0, 0, c.width, c.height); let imgData = ctx.getImageData(0, 0, c.width, c.height); // resize if required if (settings.resizeImageIfTooLarge && (c.width > settings.resizeImageWidth || c.height > settings.resizeImageHeight)) { let width = c.width; let height = c.height; if (width > settings.resizeImageWidth) { const newWidth = settings.resizeImageWidth; const newHeight = c.height / c.width * settings.resizeImageWidth; width = newWidth; height = newHeight; } if (height > settings.resizeImageHeight) { const newHeight = settings.resizeImageHeight; const newWidth = width / height * newHeight; width = newWidth; height = newHeight; } const tempCanvas = canvas.createCanvas(width, height); tempCanvas.width = width; tempCanvas.height = height; tempCanvas.getContext("2d")!.drawImage(c, 0, 0, width, height); c.width = width; c.height = height; ctx.drawImage(tempCanvas, 0, 0, width, height); imgData = ctx.getImageData(0, 0, c.width, c.height); console.log(`Resized image to ${width}x${height}`); } console.log("Running k-means clustering"); const cKmeans = canvas.createCanvas(imgData.width, imgData.height); const ctxKmeans = cKmeans.getContext("2d")!; ctxKmeans.fillStyle = "white"; ctxKmeans.fillRect(0, 0, cKmeans.width, cKmeans.height); const kmeansImgData = ctxKmeans.getImageData(0, 0, cKmeans.width, cKmeans.height); await ColorReducer.applyKMeansClustering(imgData, kmeansImgData, ctx, settings, (kmeans) => { const progress = (100 - (kmeans.currentDeltaDistanceDifference > 100 ? 100 : kmeans.currentDeltaDistanceDifference)) / 100; ctxKmeans.putImageData(kmeansImgData, 0, 0); }); const colormapResult = ColorReducer.createColorMap(kmeansImgData); let facetResult = new FacetResult(); if (typeof settings.narrowPixelStripCleanupRuns === "undefined" || settings.narrowPixelStripCleanupRuns === 0) { console.log("Creating facets"); facetResult = await FacetCreator.getFacets(imgData.width, imgData.height, colormapResult.imgColorIndices, (progress) => { // progress }); console.log("Reducing facets"); await FacetReducer.reduceFacets(settings.removeFacetsSmallerThanNrOfPoints, settings.removeFacetsFromLargeToSmall, settings.maximumNumberOfFacets, colormapResult.colorsByIndex, facetResult, colormapResult.imgColorIndices, (progress) => { // progress }); } else { for (let run = 0; run < settings.narrowPixelStripCleanupRuns; run++) { console.log("Removing narrow pixels run #" + (run + 1)); // clean up narrow pixel strips await ColorReducer.processNarrowPixelStripCleanup(colormapResult); console.log("Creating facets"); facetResult = await FacetCreator.getFacets(imgData.width, imgData.height, colormapResult.imgColorIndices, (progress) => { // progress }); console.log("Reducing facets"); await FacetReducer.reduceFacets(settings.removeFacetsSmallerThanNrOfPoints, settings.removeFacetsFromLargeToSmall, settings.maximumNumberOfFacets, colormapResult.colorsByIndex, facetResult, colormapResult.imgColorIndices, (progress) => { // progress }); // the colormapResult.imgColorIndices get updated as the facets are reduced, so just do a few runs of pixel cleanup } } console.log("Build border paths"); await FacetBorderTracer.buildFacetBorderPaths(facetResult, (progress) => { // progress }); console.log("Build border path segments"); await FacetBorderSegmenter.buildFacetBorderSegments(facetResult, settings.nrOfTimesToHalveBorderSegments, (progress) => { // progress }); console.log("Determine label placement"); await FacetLabelPlacer.buildFacetLabelBounds(facetResult, (progress) => { // progress }); for (const profile of settings.outputProfiles) { console.log("Generating output for " + profile.name); if (typeof profile.filetype === "undefined") { profile.filetype = "svg"; } const svgProfilePath = path.join(path.dirname(svgPath), path.basename(svgPath).substr(0, path.basename(svgPath).length - path.extname(svgPath).length) + "-" + profile.name) + "." + profile.filetype; const svgString = await createSVG(facetResult, colormapResult.colorsByIndex, profile.svgSizeMultiplier, profile.svgFillFacets, profile.svgShowBorders, profile.svgShowLabels, profile.svgFontSize, profile.svgFontColor); if (profile.filetype === "svg") { fs.writeFileSync(svgProfilePath, svgString); } else if (profile.filetype === "png") { const imageBuffer = await new Promise<Buffer>((then, reject) => { svg2img(svgString, function (error: Error, buffer: Buffer) { if (error) { reject(error); } else { then(buffer); } }); }); fs.writeFileSync(svgProfilePath, imageBuffer); } else if (profile.filetype === "jpg") { const imageBuffer = await new Promise<Buffer>((then, reject) => { svg2img(svgString, { format: "jpg", quality: profile.filetypeQuality }, function (error: Error, buffer: Buffer) { if (error) { reject(error); } else { then(buffer); } }); }); fs.writeFileSync(svgProfilePath, imageBuffer); } } console.log("Generating palette info"); const palettePath = path.join(path.dirname(svgPath), path.basename(svgPath).substr(0, path.basename(svgPath).length - path.extname(svgPath).length) + ".json"); const colorFrequency: number[] = []; for (const color of colormapResult.colorsByIndex) { colorFrequency.push(0); } for (const facet of facetResult.facets) { if (facet !== null) { colorFrequency[facet.color] += facet.pointCount; } } const colorAliasesByColor: { [key: string]: string } = {}; for (const alias of Object.keys(settings.colorAliases)) { colorAliasesByColor[settings.colorAliases[alias].join(",")] = alias; } const totalFrequency = colorFrequency.reduce((sum, val) => sum + val); const paletteInfo = JSON.stringify(colormapResult.colorsByIndex.map((color, index) => { return { areaPercentage: colorFrequency[index] / totalFrequency, color, colorAlias: colorAliasesByColor[color.join(",")], frequency: colorFrequency[index], index, }; }), null, 2); fs.writeFileSync(palettePath, paletteInfo); } async function createSVG(facetResult: FacetResult, colorsByIndex: RGB[], sizeMultiplier: number, fill: boolean, stroke: boolean, addColorLabels: boolean, fontSize: number = 60, fontColor: string = "black", onUpdate: ((progress: number) => void) | null = null) { let svgString = ""; const xmlns = "http://www.w3.org/2000/svg"; const svgWidth = sizeMultiplier * facetResult.width; const svgHeight = sizeMultiplier * facetResult.height; svgString += `<?xml version="1.0" standalone="no"?> <svg width="${svgWidth}" height="${svgHeight}" xmlns="${xmlns}">`; for (const f of facetResult.facets) { if (f != null && f.borderSegments.length > 0) { let newpath: Point[] = []; const useSegments = true; if (useSegments) { newpath = f.getFullPathFromBorderSegments(false); } else { for (let i: number = 0; i < f.borderPath.length; i++) { newpath.push(new Point(f.borderPath[i].getWallX() + 0.5, f.borderPath[i].getWallY() + 0.5)); } } if (newpath[0].x !== newpath[newpath.length - 1].x || newpath[0].y !== newpath[newpath.length - 1].y) { newpath.push(newpath[0]); } // close loop if necessary // Create a path in SVG's namespace // using quadratic curve absolute positions let svgPathString = ""; let data = "M "; data += newpath[0].x * sizeMultiplier + " " + newpath[0].y * sizeMultiplier + " "; for (let i: number = 1; i < newpath.length; i++) { const midpointX = (newpath[i].x + newpath[i - 1].x) / 2; const midpointY = (newpath[i].y + newpath[i - 1].y) / 2; data += "Q " + (midpointX * sizeMultiplier) + " " + (midpointY * sizeMultiplier) + " " + (newpath[i].x * sizeMultiplier) + " " + (newpath[i].y * sizeMultiplier) + " "; } let svgStroke = ""; if (stroke) { svgStroke = "#000"; } else { // make the border the same color as the fill color if there is no border stroke // to not have gaps in between facets if (fill) { svgStroke = `rgb(${colorsByIndex[f.color][0]},${colorsByIndex[f.color][1]},${colorsByIndex[f.color][2]})`; } } let svgFill = ""; if (fill) { svgFill = `rgb(${colorsByIndex[f.color][0]},${colorsByIndex[f.color][1]},${colorsByIndex[f.color][2]})`; } else { svgFill = "none"; } svgPathString = `<path data-facetId="${f.id}" d="${data}" `; svgPathString += `style="`; svgPathString += `fill: ${svgFill};`; if (svgStroke !== "") { svgPathString += `stroke: ${svgStroke}; stroke-width:1px`; } svgPathString += `"`; svgPathString += `>`; svgPathString += `</path>`; svgString += svgPathString; // add the color labels if necessary. I mean, this is the whole idea behind the paint by numbers part // so I don't know why you would hide them if (addColorLabels) { const labelOffsetX = f.labelBounds.minX * sizeMultiplier; const labelOffsetY = f.labelBounds.minY * sizeMultiplier; const labelWidth = f.labelBounds.width * sizeMultiplier; const labelHeight = f.labelBounds.height * sizeMultiplier; // const svgLabelString = `<g class="label" transform="translate(${labelOffsetX},${labelOffsetY})"> // <svg width="${labelWidth}" height="${labelHeight}" overflow="visible" viewBox="-50 -50 100 100" preserveAspectRatio="xMidYMid meet"> // <rect xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" fill="rgb(255,255,255,0.5)" x="-50" y="-50"/> // <text font-family="Tahoma" font-size="60" dominant-baseline="middle" text-anchor="middle">${f.color}</text> // </svg> // </g>`; const nrOfDigits = (f.color + "").length; const svgLabelString = `<g class="label" transform="translate(${labelOffsetX},${labelOffsetY})"> <svg width="${labelWidth}" height="${labelHeight}" overflow="visible" viewBox="-50 -50 100 100" preserveAspectRatio="xMidYMid meet"> <text font-family="Tahoma" font-size="${(fontSize / nrOfDigits)}" dominant-baseline="middle" text-anchor="middle" fill="${fontColor}">${f.color}</text> </svg> </g>`; svgString += svgLabelString; } } } svgString += `</svg>`; return svgString; } main().then(() => { console.log("Finished"); }).catch((err) => { console.error("Error: " + err.name + " " + err.message + " " + err.stack); });
the_stack
import type { IFrontendDomChangeEvent } from '@secret-agent/core/models/DomChangesTable'; declare global { interface Window { replayDomChanges(...args: any[]); replayInteractions(...args: any[]); getIsMainFrame?: () => boolean; debugLogs: any[]; debugToConsole: boolean; selfFrameIdPath: string; getNodeById(id: number): Node; } } // copied since we can't import data types enum DomActionType { newDocument = 0, location = 1, added = 2, removed = 3, text = 4, attribute = 5, property = 6, } const SHADOW_NODE_TYPE = 40; const domChangeList = []; if (!window.debugLogs) window.debugLogs = []; function isMainFrame() { if ('isMainFrame' in window) return (window as any).isMainFrame; if ('getIsMainFrame' in window) return window.getIsMainFrame(); return true; } function debugLog(message: string, ...args: any[]) { if (window.debugToConsole) { // eslint-disable-next-line prefer-rest-params,no-console console.log(...arguments); } window.debugLogs.push({ message, args }); } window.replayDomChanges = function replayDomChanges(changeEvents: IFrontendDomChangeEvent[]) { if (changeEvents) applyDomChanges(changeEvents); }; window.addEventListener('message', ev => { if (ev.data.action !== 'replayDomChanges') return; if (ev.data.recipientFrameIdPath && !window.selfFrameIdPath) { window.selfFrameIdPath = ev.data.recipientFrameIdPath; } domChangeList.push(ev.data.event); if (document.readyState !== 'loading') applyDomChanges([]); }); function applyDomChanges(changeEvents: IFrontendDomChangeEvent[]) { const toProcess = domChangeList.concat(changeEvents); domChangeList.length = 0; for (const changeEvent of toProcess) { try { replayDomEvent(changeEvent); } catch (err) { debugLog('ERROR applying change', changeEvent, err); } } } /////// DOM REPLAYER /////////////////////////////////////////////////////////////////////////////////////////////////// function replayDomEvent(event: IFrontendDomChangeEvent) { if (!window.selfFrameIdPath && isMainFrame()) { window.selfFrameIdPath = 'main'; } const { action, textContent, frameIdPath } = event; if (frameIdPath && frameIdPath !== window.selfFrameIdPath) { delegateToSubframe(event); return; } if (action === DomActionType.newDocument) { onNewDocument(event); return; } if (action === DomActionType.location) { debugLog('Location: href=%s', event.textContent); window.history.replaceState({}, 'Replay', textContent); return; } if (isPreservedElement(event)) return; const { parentNodeId } = event; let node: Node; let parentNode: Node; try { parentNode = getNode(parentNodeId); node = deserializeNode(event, parentNode as Element); if (!parentNode && (action === DomActionType.added || action === DomActionType.removed)) { debugLog('WARN: parent node id not found', event); return; } switch (action) { case DomActionType.added: if (!event.previousSiblingId) { (parentNode as Element).prepend(node); } else if (getNode(event.previousSiblingId)) { const next = getNode(event.previousSiblingId).nextSibling; if (next) parentNode.insertBefore(node, next); else parentNode.appendChild(node); } break; case DomActionType.removed: if (parentNode.contains(node)) parentNode.removeChild(node); break; case DomActionType.attribute: setNodeAttributes(node as Element, event); break; case DomActionType.property: setNodeProperties(node as Element, event); break; case DomActionType.text: node.textContent = textContent; break; } } catch (error) { // eslint-disable-next-line no-console console.error('ERROR: applying action', error.stack, parentNode, node, event); } } /////// PRESERVE HTML, BODY, HEAD ELEMS //////////////////////////////////////////////////////////////////////////////// const preserveElements = new Set<string>(['HTML', 'HEAD', 'BODY']); function isPreservedElement(event: IFrontendDomChangeEvent) { const { action, nodeId, nodeType } = event; if (nodeType === document.DOCUMENT_NODE) { NodeTracker.restore(nodeId, document); return true; } if (nodeType === document.DOCUMENT_TYPE_NODE) { NodeTracker.restore(nodeId, document.doctype); return true; } let tagName = event.tagName; if (!tagName) { const existing = getNode(nodeId); if (existing) tagName = (existing as Element).tagName; } if (!preserveElements.has(tagName)) return false; const elem = document.querySelector(tagName); if (!elem) { debugLog('Preserved element doesnt exist!', tagName); return true; } NodeTracker.restore(nodeId, elem); if (action === DomActionType.removed) { elem.innerHTML = ''; for (const attr of elem.attributes) { elem.removeAttributeNS(attr.name, attr.namespaceURI); elem.removeAttribute(attr.name); } debugLog('WARN: script trying to remove preserved node', event, elem); return true; } if (action === DomActionType.added) { elem.innerHTML = ''; } if (event.attributes) { setNodeAttributes(elem, event); } if (event.properties) { setNodeProperties(elem, event); } return true; } /////// DELEGATION BETWEEN FRAMES //////////////////////////////////////////////////////////////////////////////////// const pendingFrameCreationEvents = new Map< string, { recipientFrameIdPath: string; event: IFrontendDomChangeEvent; action: string }[] >(); (window as any).pendingFrameCreationEvents = pendingFrameCreationEvents; function delegateToSubframe(event: IFrontendDomChangeEvent) { const childPath = event.frameIdPath .replace(window.selfFrameIdPath, '') .split('_') .filter(Boolean) .map(Number); const childId = childPath.shift(); const recipientFrameIdPath = `${window.selfFrameIdPath}_${childId}`; const node = getNode(childId); if (!node) { if (!pendingFrameCreationEvents.has(recipientFrameIdPath)) { pendingFrameCreationEvents.set(recipientFrameIdPath, []); } // queue for pending events pendingFrameCreationEvents .get(recipientFrameIdPath) .push({ recipientFrameIdPath, event, action: 'replayDomChanges' }); debugLog('Frame: not loaded yet, queuing pending', recipientFrameIdPath); return; } if ( (event.action === DomActionType.location || event.action === DomActionType.newDocument) && node instanceof HTMLObjectElement ) { return; } const frame = node as HTMLIFrameElement; if (!frame.contentWindow) { debugLog('Frame: without window', frame); return; } const events = [{ recipientFrameIdPath, event, action: 'replayDomChanges' }]; if (pendingFrameCreationEvents.has(recipientFrameIdPath)) { events.unshift(...pendingFrameCreationEvents.get(recipientFrameIdPath)); pendingFrameCreationEvents.delete(recipientFrameIdPath); } for (const message of events) { frame.contentWindow.postMessage(message, '*'); } } function onNewDocument(event: IFrontendDomChangeEvent) { const { textContent } = event; const href = textContent; const newUrl = new URL(href); debugLog( 'Location: (new document) %s, frame: %s, idx: %s', href, event.frameIdPath, event.eventIndex, ); if (!isMainFrame()) { if (window.location.href !== href) { window.location.href = href; } return; } window.scrollTo({ top: 0 }); if (document.documentElement) { document.documentElement.innerHTML = ''; while (document.documentElement.previousSibling) { const prev = document.documentElement.previousSibling; if (prev === document.doctype) break; prev.remove(); } } if (window.location.origin === newUrl.origin) { window.history.replaceState({}, 'Replay', href); } } function getNode(id: number) { if (id === null || id === undefined) return null; return NodeTracker.getWatchedNodeWithId(id, false); } window.getNodeById = getNode; function setNodeAttributes(node: Element, data: IFrontendDomChangeEvent) { const attributes = data.attributes; if (!attributes) return; const namespaces = data.attributeNamespaces; for (const [name, value] of Object.entries(attributes)) { const ns = namespaces ? namespaces[name] : null; try { if (name === 'xmlns' || name.startsWith('xmlns') || node.tagName === 'HTML' || !ns) { if (value === null) node.removeAttribute(name); else node.setAttribute(name, value as any); } else if (value === null) { node.removeAttributeNS(ns || null, name); } else { node.setAttributeNS(ns || null, name, value as any); } } catch (err) { if ( !err.toString().includes('not a valid attribute name') && !err.toString().includes('qualified name') ) throw err; } } } function setNodeProperties(node: Element, data: IFrontendDomChangeEvent) { const properties = data.properties; if (!properties) return; for (const [name, value] of Object.entries(properties)) { if (name === 'sheet.cssRules') { const sheet = (node as HTMLStyleElement).sheet as CSSStyleSheet; const newRules = value as string[]; let i = 0; for (i = 0; i < sheet.cssRules.length; i += 1) { const newRule = newRules[i]; if (newRule !== sheet.cssRules[i].cssText) { sheet.deleteRule(i); if (newRule) sheet.insertRule(newRule, i); } } for (; i < newRules.length; i += 1) { sheet.insertRule(newRules[i], i); } } else { node[name] = value; } } } function deserializeNode(data: IFrontendDomChangeEvent, parent: Element): Node { if (data === null) return null; let node = getNode(data.nodeId); if (node) { setNodeProperties(node as Element, data); setNodeAttributes(node as Element, data); if (data.textContent) node.textContent = data.textContent; return node; } if (parent && typeof parent.attachShadow === 'function' && data.nodeType === SHADOW_NODE_TYPE) { // NOTE: we just make all shadows open in replay node = parent.attachShadow({ mode: 'open' }); NodeTracker.restore(data.nodeId, node); return node; } switch (data.nodeType) { case Node.COMMENT_NODE: node = document.createComment(data.textContent); break; case Node.TEXT_NODE: node = document.createTextNode(data.textContent); break; case Node.ELEMENT_NODE: if (!node) { if (data.namespaceUri) { node = document.createElementNS(data.namespaceUri, data.tagName); } else { node = document.createElement(data.tagName); } } if (node instanceof HTMLIFrameElement) { debugLog('Added Child Frame: frameIdPath=%s', `${window.selfFrameIdPath}_${data.nodeId}`); } if (data.tagName === 'NOSCRIPT') { const sheet = new CSSStyleSheet(); // @ts-ignore sheet.replaceSync( `noscript { display:none !important; } noscript * { display:none !important; }`, ); // @ts-ignore document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]; } (node as any).nodeId = data.nodeId; setNodeAttributes(node as Element, data); setNodeProperties(node as Element, data); if (data.textContent) { node.textContent = data.textContent; } break; } if (!node) throw new Error(`Unable to translate node! nodeType = ${data.nodeType}`); NodeTracker.restore(data.nodeId, node); return node; }
the_stack
import { CallReceiverMock, HookCallerMock } from '@0xsequence/wallet-contracts' import { Transaction } from '@0xsequence/transactions' import { LocalRelayer } from '@0xsequence/relayer' import { WalletContext, Networks } from '@0xsequence/network' import { JsonRpcProvider } from '@ethersproject/providers' import { ethers, Signer as AbstractSigner } from 'ethers' import { configureLogger } from '@0xsequence/utils' import chaiAsPromised from 'chai-as-promised' import * as chai from 'chai' const CallReceiverMockArtifact = require('@0xsequence/wallet-contracts/artifacts/contracts/mocks/CallReceiverMock.sol/CallReceiverMock.json') const HookCallerMockArtifact = require('@0xsequence/wallet-contracts/artifacts/contracts/mocks/HookCallerMock.sol/HookCallerMock.json') const { expect } = chai.use(chaiAsPromised) configureLogger({ logLevel: 'DEBUG' }) import { Wallet } from '@0xsequence/wallet' import { deployWalletContext } from '@0xsequence/wallet/tests/utils/deploy-wallet-context' import { OverwriterSequenceEstimator } from '../src' import { OverwriterEstimator } from '../dist/0xsequence-estimator.cjs' import { encodeData } from '@0xsequence/wallet/tests/utils' type EthereumInstance = { chainId: number provider: JsonRpcProvider signer: AbstractSigner } describe('Wallet integration', function () { let ethnode: EthereumInstance let relayer: LocalRelayer let callReceiver: CallReceiverMock let hookCaller: HookCallerMock let context: WalletContext let networks: Networks let estimator: OverwriterSequenceEstimator before(async () => { // Provider from hardhat without a server instance const url = "http://127.0.0.1:10045/" const provider = new ethers.providers.JsonRpcProvider(url) ethnode = { chainId: (await provider.getNetwork()).chainId, provider: provider, signer: provider.getSigner() } networks = [{ name: 'local', chainId: ethnode.chainId, provider: ethnode.provider, isDefaultChain: true, isAuthChain: true }] // Deploy Sequence env const [ factory, mainModule, mainModuleUpgradable, guestModule, sequenceUtils, requireFreshSigner ] = await deployWalletContext(ethnode.signer) // Create fixed context obj context = { factory: factory.address, mainModule: mainModule.address, mainModuleUpgradable: mainModuleUpgradable.address, guestModule: guestModule.address, sequenceUtils: sequenceUtils.address, libs: { requireFreshSigner: requireFreshSigner.address } } // Deploy call receiver mock callReceiver = (await new ethers.ContractFactory( CallReceiverMockArtifact.abi, CallReceiverMockArtifact.bytecode, ethnode.signer ).deploy()) as CallReceiverMock // Deploy hook caller mock hookCaller = (await new ethers.ContractFactory( HookCallerMockArtifact.abi, HookCallerMockArtifact.bytecode, ethnode.signer ).deploy()) as HookCallerMock // Deploy local relayer relayer = new LocalRelayer({signer: ethnode.signer }) // Create gas estimator estimator = new OverwriterSequenceEstimator(new OverwriterEstimator({ rpc: ethnode.provider })) }) function sleep(ms: number) {   return new Promise(resolve => setTimeout(resolve, ms)); } beforeEach(async () => { await callReceiver.setRevertFlag(false) await callReceiver.testCall(0, []) }) describe('estimate gas of transactions', () => { const options = [{ name: "single signer wallet", getWallet: async () => { const pk = ethers.utils.randomBytes(32) const wallet = await Wallet.singleOwner(pk, context) return wallet.connect(ethnode.provider, relayer) } }, { name: "multiple signers wallet", getWallet: async () => { const signers = new Array(4).fill(0).map(() => ethers.Wallet.createRandom()) const config = { threshold: 3, signers: signers.map((s) => ({ weight: 1, address: s.address})) } const wallet = new Wallet({ context, config }, ...signers.slice(0, 3)) return wallet.connect(ethnode.provider, relayer) } }, { name: "many multiple signers wallet", getWallet: async () => { const signers = new Array(111).fill(0).map(() => ethers.Wallet.createRandom()) const config = { threshold: 11, signers: signers.map((s) => ({ weight: 1, address: s.address})) } const wallet = new Wallet({ context, config }, ...signers.slice(0, 12)) return wallet.connect(ethnode.provider, relayer) } }, { name: "nested wallet", getWallet: async () => { const EOAsigners = new Array(2).fill(0).map(() => ethers.Wallet.createRandom()) const NestedSigners = await Promise.all(new Array(2).fill(0).map(async () => { const signers = new Array(3).fill(0).map(() => ethers.Wallet.createRandom()) const config = { threshold: 2, signers: signers.map((s) => ({ weight: 1, address: s.address })) } const wallet = new Wallet({ context: context, config: config }, ...signers.slice(0, 2)).connect(ethnode.provider, relayer) await relayer.deployWallet(wallet.config, wallet.context) return wallet.connect(ethnode.provider, relayer) })) const signers = [...NestedSigners, ...EOAsigners] const config = { threshold: 3, signers: signers.map((s) => ({ weight: 1, address: s.address})) } const wallet = new Wallet({ context, config }, ...signers) return wallet.connect(ethnode.provider, relayer) } }, { name: "asymetrical signers wallet", getWallet: async () => { const signersA = new Array(5).fill(0).map(() => ethers.Wallet.createRandom()) const signersB = new Array(6).fill(0).map(() => ethers.Wallet.createRandom()) const signers = [...signersA, ...signersB] const config = { threshold: 5, signers: signers.map((s, i) => ({ weight: (i <= signersA.length ? 1 : 10), address: s.address})) } const wallet = new Wallet({ context, config }, ...signersA) return wallet.connect(ethnode.provider, relayer) } } ] options.map((o) => { describe(`with ${o.name}`, () => { let wallet: Wallet beforeEach(async () => { wallet = await o.getWallet() }) describe("with deployed wallet", () => { let txs: Transaction[] beforeEach(async () => { await callReceiver.testCall(0, []) await relayer.deployWallet(wallet.config, wallet.context) }) describe("a single transaction", () => { beforeEach(async () => { txs = [{ delegateCall: false, revertOnError: false, gasLimit: 0, to: callReceiver.address, value: ethers.constants.Zero, data: await encodeData(callReceiver, "testCall", 14442, "0x112233"), nonce: 0 }] }) it("should use estimated gas for a single transaction", async () => { const estimation = await estimator.estimateGasLimits(wallet.config, wallet.context, ...txs) const realTx = await (await wallet.sendTransaction(estimation.transactions)).wait(1) expect(realTx.gasUsed.toNumber()).to.be.approximately(estimation.total.toNumber(), 10000) expect(realTx.gasUsed.toNumber()).to.be.below(estimation.total.toNumber()) expect((await callReceiver.lastValA()).toNumber()).to.equal(14442) }) it("should predict gas usage for a single transaction", async () => { const estimation = await estimator.estimateGasLimits(wallet.config, wallet.context, ...txs) const realTx = await (await wallet.sendTransaction(txs)).wait(1) expect(realTx.gasUsed.toNumber()).to.be.approximately(estimation.total.toNumber(), 10000) expect(realTx.gasUsed.toNumber()).to.be.below(estimation.total.toNumber()) expect((await callReceiver.lastValA()).toNumber()).to.equal(14442) }) it("should use estimated gas for a single failing transaction", async () => { await callReceiver.setRevertFlag(true) const estimation = await estimator.estimateGasLimits(wallet.config, wallet.context, ...txs) const realTx = await (await wallet.sendTransaction(estimation.transactions)).wait(1) expect(realTx.gasUsed.toNumber()).to.be.approximately(estimation.total.toNumber(), 10000) expect(realTx.gasUsed.toNumber()).to.be.below(estimation.total.toNumber()) expect((await callReceiver.lastValA()).toNumber()).to.equal(0) }) }) describe("a batch of transactions", () => { let valB: Uint8Array beforeEach(async () => { await callReceiver.setRevertFlag(true) valB = ethers.utils.randomBytes(99) txs = [{ delegateCall: false, revertOnError: false, gasLimit: 0, to: callReceiver.address, value: ethers.constants.Zero, data: await encodeData(callReceiver, "setRevertFlag", false), nonce: 0 }, { delegateCall: false, revertOnError: true, gasLimit: 0, to: callReceiver.address, value: ethers.constants.Zero, data: await encodeData(callReceiver, "testCall", 2, valB), nonce: 0 }] }) it("should use estimated gas for a batch of transactions", async () => { const estimation = await estimator.estimateGasLimits(wallet.config, wallet.context, ...txs) const realTx = await (await wallet.sendTransaction(estimation.transactions)).wait(1) expect(realTx.gasUsed.toNumber()).to.be.approximately(estimation.total.toNumber(), 30000) expect(realTx.gasUsed.toNumber()).to.be.below(estimation.total.toNumber()) expect(ethers.utils.hexlify(await callReceiver.lastValB())).to.equal(ethers.utils.hexlify(valB)) }) }) }) }) }) }) })
the_stack
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { NzMessageService } from 'ng-zorro-antd/message'; import { AccountService } from 'src/app/services/account.service'; import { AnalyticsService } from 'src/app/services/analytics.service'; import { uuidv4 } from 'src/app/utils'; import { NewReportComponent } from './components/new-report/new-report.component'; import { CalculationType, DataCard, dataSource, Dimension, DimensionModalOptions, IDataCard, IDataItem, updataReportParam } from './types/analytics'; import { DataSourcesComponent } from './components/data-sources/data-sources.component'; import { dataGrouping, sameTimeGroup } from './types/data-grouping'; import { hasSameKeyName } from './types/same-keyname'; import { NzSelectOptionInterface } from "ng-zorro-antd/select"; @Component({ selector: 'app-analytics', templateUrl: './analytics.component.html', styleUrls: ['./analytics.component.less'] }) export class AnalyticsComponent implements OnInit { listData: DataCard[] = []; isLoading = false; dataSourceModalVisible = false; public dataSourcesManageModalVisible = false; private analyticBoardId: string = ""; private envID: number = null; public dataSourceList: dataSource[] = []; // 数据源列表 public dataSourceBoardType: 'table' | 'form' = 'table'; // 添加数据源弹窗界面类型 public dataSourceOperatorType: 'new' | 'edit' = 'new'; // 如何操作数据源 public currentDataSource: dataSource; // 当前数据源 public currentDataItem: IDataItem = null; public currentDataCard: DataCard = null; public reportsForCurrDataSource: any[] = []; // 当前将要被删除的数据源,被使用的报表列表 public willSaveCard: IDataCard; // 将要保存的报表 // analytic dimension modal options public dimensionModalOptions = new DimensionModalOptions(); @ViewChild("addDataSourceTem", {static: false}) addDataSoureTem: TemplateRef<any>; @ViewChild("dataSources", {static: false}) dataSourceCom: DataSourcesComponent; @ViewChild("newReport", {static: false}) newReportCom: NewReportComponent; constructor( private message: NzMessageService, private accountServe: AccountService, private analyticServe: AnalyticsService ) { } ngOnInit(): void { this.initBoardData(); } // 初始化看板数据 private initBoardData() { const { projectEnv: {envId} } = this.accountServe.getCurrentAccountProjectEnv(); this.analyticServe.getAnalyticBoardData(envId) .subscribe((result: { id: string; envId: number; dataSourceDefs: dataSource[], dimensions: Dimension[], dataGroups: DataCard[] }) => { this.listData = []; this.analyticBoardId = result.id; this.envID = result.envId; this.dataSourceList = result.dataSourceDefs; this.dimensionModalOptions.dimensions = result.dimensions; let groups = result.dataGroups; groups.forEach((group: DataCard) => { group.items.length && group.items.map((item: IDataItem) => { item.isLoading = true; item.isSetupDataSource = true; }); const dimensionOptions = this.createDimensionOptions(result.dimensions); this.listData[this.listData.length] = new DataCard({ ...group, itemsCount: group.items.length, isLoading: false, isEditing: false, dimensionOptions: dimensionOptions } ); }) this.requestValueForItems(); }) } // 设置每个 item 的 value 值 private requestValueForItems() { dataGrouping(this.listData, this.envID).forEach((item: sameTimeGroup) => { this.analyticServe.computeResult(item).subscribe(result => this.setItemValue(result.items, this.listData)); }) } // 设置 item 的 value 值 private setItemValue(result: {id: string, value: number}[], list: IDataCard[]) { result.forEach((item: {id: string, value: number}) => { next: for(let i = 0; i < list.length; i++) { const items = list[i].items; if(items.length) { for(let j = 0; j < items.length; j++) { if(items[j].id === item.id) { items[j].isLoading = false; items[j].value = item.value; break next; } } } } }) } // 切换看板状态 public toggleEditingCard(card: IDataCard) { if(card.isEditing) { if(!card.name) { this.message.error("必须填写报表名字!"); return; } // 表报必须填写开始日期 const isStartTime = card.startTime; if(!isStartTime) { this.message.error("必须填写开始日期!"); return; } // 筛选是否有没有 name 值和 DataSource 的 选项 const result = card.items.filter(item => !item.name || !item.dataSource); if(result.length) { this.willSaveCard = card; card.isTooltip = true; } else { this.setSaveReportParam(card); } } else { card.isEditing = true; } } // 确认保存 public onSureToSave() { this.willSaveCard.items = this.willSaveCard.items.filter(i => i.name !== null && i.name !== '' && i.dataSource !== null); this.setSaveReportParam(this.willSaveCard); } // 设置保存报表参数 private setSaveReportParam(card: IDataCard) { let param: updataReportParam = { analyticBoardId: this.analyticBoardId, envId: this.envID, id: card.id, name: card.name || null, items: card.items, startTime: card.startTime, endTime: card.endTime, dimensions: card.dimensions } this.onSaveReportData(param, card); } // 保存报表 private onSaveReportData(param: updataReportParam, card: IDataCard) { card.isLoading = true; this.analyticServe.saveReport(param) .subscribe(() => { this.message.success("报表更新成功!"); card.isEditing = false; card.itemsCount = card.items.length; card.isTooltip = false; card.isLoading = false; const dimensions = card.dimensionOptions .filter(option => card.dimensions.includes(option.value)) .map(item => ({ id: item.value as string, key: item.groupLabel as string, value: item.label as string }) ); const param: sameTimeGroup = { envId: this.envID, startTime: card.startTime, endTime: card.endTime, items: card.items, dimensions: dimensions } this.analyticServe.computeResult(param) .subscribe(result => this.setItemValue(result.items, [card])) }) } // 创建报表 public onCreateCard() { const card = new DataCard(); card.dimensionOptions = this.createDimensionOptions(this.dimensionModalOptions.dimensions); card.dimensions = []; this.currentDataCard = card; this.onAddItem(card); this.listData = [card, ...this.listData]; } // 添加 item public onAddItem(data: DataCard) { data.items = [...data.items, { id: uuidv4(), name: null, value: null, dataSource: null, unit: null, color: null, calculationType: CalculationType.Count, isSetupDataSource: false }] data.itemsCount = data.itemsCount + 1; } // 删除报表 public removeCard(card: IDataCard) { this.analyticServe.deleteReport(this.envID, this.analyticBoardId, card.id) .subscribe(() => { const idx = this.listData.findIndex(d => d.id === card.id); idx > -1 && this.listData.splice(idx, 1); this.message.success("表报移除成功!"); }) } // 删除 item public removeDataItem(card: DataCard, item: IDataItem) { const idx = card.items.findIndex(i => i.id === item.id); if (idx > -1) { card.items.splice(idx, 1); card.itemsCount = card.itemsCount - 1; } } // 点击设置数据源(打开设置数据源弹窗) public onSetDataSource(card: DataCard, item: IDataItem) { this.currentDataItem = {...item}; this.currentDataCard = card; this.dataSourceModalVisible = true; } // 切换数据源界面 public onOperatorDataSource() { if(this.dataSourceBoardType === 'table') { this.currentDataSource = { id: uuidv4(), name: "", dataType: "数值", keyName: "" } this.dataSourceOperatorType = 'new'; this.dataSourceBoardType = 'form'; } else { // 检查是否有重复的 keyName const dataSource: dataSource = this.dataSourceCom.setParam(); const isHas = hasSameKeyName(this.dataSourceList, dataSource); if(!isHas) { this.onAddDataSource(dataSource); } else { this.message.error("当前数据源的 keyName 重复,请设置不同的 keyName") } } } // 操作取消按钮 public onOperatorCancel() { if(this.dataSourceBoardType === 'table') { this.dataSourcesManageModalVisible = false; } else { this.dataSourceBoardType = "table"; } } // 设置数据源 public onApplyDataSource () { this.currentDataItem = {...this.currentDataItem, ...this.newReportCom.setParam(), isSetupDataSource: true}; this.currentDataCard.updateItem(this.currentDataItem); this.dataSourceModalVisible = false; } // 刷新页面 public onRefreshPage() { this.initBoardData(); } // 打开添加数据源弹窗 public onOpenDataSoureModal() { this.dataSourcesManageModalVisible = true; } // 关闭添加数据源弹窗 public onCloseAddDataSoureModal() { this.dataSourcesManageModalVisible = false; } // 关闭/返回 分析维度弹窗 public onCloseDimensionModal() { this.dimensionModalOptions.handleCancel(); } // 新建/更新 分析维度弹窗 public onSaveDimensionModal() { if (this.dimensionModalOptions.mode === 'show-list') { // set current dimension const initialDimension = { id: uuidv4(), key: "", value: "" }; this.dimensionModalOptions.handleOk(initialDimension); } else { let currentDimension = this.dimensionModalOptions.currentDimension; const param = { analyticBoardId: this.analyticBoardId, envID: this.envID, id: currentDimension.id, key: currentDimension.key, value: currentDimension.value }; this.analyticServe.upsertDimension(param) .subscribe(() => { this.dimensionModalOptions.upsertDimension(); this.syncCardDimensions(); this.message.success("新增分析维度成功!"); }); } } // 删除分析维度 public onDeleteDimension(dimension: Dimension) { const cardsUseThisDimension = this.findCardsUseThisDimension(dimension); if (cardsUseThisDimension.length) { cardsUseThisDimension.forEach(card => { this.message.error(`当前分析维度正在被报表 ${card.name} 使用,不能删除!`); }); return; } this.analyticServe.deleteDimension(this.envID, this.analyticBoardId, dimension.id) .subscribe(() => { this.dimensionModalOptions.deleteDimension(dimension); this.syncCardDimensions(); this.message.success("删除分析维度成功!"); }) } private findCardsUseThisDimension(dimension: Dimension): DataCard[] { const cardsUseThisDimension : DataCard[] = []; this.listData.forEach(card => { if (card.dimensions.includes(dimension.id)) { cardsUseThisDimension.push(card); } }); return cardsUseThisDimension; } // 确认添加数据源 private onAddDataSource = (dataSource: dataSource) => { const newDataSource = { analyticBoardId: this.analyticBoardId, envID: this.envID, id: dataSource.id, name: dataSource.name, keyName: dataSource.keyName, dataType: dataSource.dataType } this.analyticServe.addDataSourece(newDataSource) .subscribe(() => { this.dataSourceOperatorType === 'new' && (this.dataSourceList[this.dataSourceList.length] = dataSource); this.dataSourceBoardType = "table"; }) } // 删除数据源 public onDeleteDataSource(dataSource: dataSource) { // 检测是否有使用过该数据源的报表 const isHas = this.findReportsForCurrentDataSource(dataSource); if(isHas) { this.onApplyDelete(dataSource); } else { // 显示使用当前数据源的报表 this.reportsForCurrDataSource.forEach(report => { this.message.warning(`当前数据源正在被报表 “${report.name}” 的 “${report.itemName}” 项目使用!`); }) } } // 查找正在使用当前数据源的报表 private findReportsForCurrentDataSource(dataSource: dataSource): boolean { this.reportsForCurrDataSource = []; this.listData.forEach((data: DataCard) => { if(data.items.length) { data.items.forEach((item: IDataItem) => { if(item.dataSource.id === dataSource.id) { this.reportsForCurrDataSource[this.reportsForCurrDataSource.length] = { name: data.name, itemName: item.name }; } }) } }) return this.reportsForCurrDataSource.length === 0; } // 执行删除 private onApplyDelete(dataSource: dataSource) { this.analyticServe.deleteDateSource(this.envID, this.analyticBoardId, dataSource.id) .subscribe(() => { const index = this.dataSourceList.findIndex(data => data.id === dataSource.id); if(index !== -1) { this.dataSourceList.splice(index, 1); this.dataSourceList = [...this.dataSourceList]; } }) } private createDimensionOptions(dimensions: Dimension[]): NzSelectOptionInterface[] { const initialOptions = dimensions.map(dimension => { return { groupLabel: dimension.key, label: dimension.value, value: dimension.id, disabled: false } }); function compareOption(itemOne: NzSelectOptionInterface, itemTwo: NzSelectOptionInterface) { if (itemOne.groupLabel < itemTwo.groupLabel) { return -1; } if (itemOne.groupLabel > itemTwo.groupLabel) { return 1; } return 0; } // 必须要排序 否则下拉组件会出现顺序错乱 :< return initialOptions.sort(compareOption); } private syncCardDimensions() { this.listData.forEach(card => { card.dimensionOptions = this.createDimensionOptions(this.dimensionModalOptions.dimensions); card.onSelectDimension(); }) } }
the_stack
import { TAbstractFile, TFile, TFolder, Keymap, Notice, App, Menu, HoverParent, debounce, MenuItem } from "obsidian"; import { hoverSource, startDrag } from "./Explorer"; import { PopupMenu, MenuParent } from "./menus"; import { ContextMenu } from "./ContextMenu"; declare module "obsidian" { interface HoverPopover { hide(): void hoverEl: HTMLDivElement } interface App { viewRegistry: { isExtensionRegistered(ext: string): boolean getTypeByExtension(ext: string): string } } interface Vault { getConfig(option: string): any getConfig(option:"showUnsupportedFiles"): boolean } } const alphaSort = new Intl.Collator(undefined, {usage: "sort", sensitivity: "base", numeric: true}).compare; const previewIcons: Record<string, string> = { markdown: "document", image: "image-file", audio: "audio-file", pdf: "pdf-file", } const viewtypeIcons: Record<string, string> = { ...previewIcons, // add third-party plugins excalidraw: "excalidraw-icon", }; // Global auto preview mode let autoPreview = false export class FolderMenu extends PopupMenu { parentFolder: TFolder = this.parent instanceof FolderMenu ? this.parent.folder : null; constructor(public parent: MenuParent, public folder: TFolder, public selectedFile?: TAbstractFile, public opener?: HTMLElement) { super(parent); this.loadFiles(folder, selectedFile); this.scope.register([], "Tab", this.togglePreviewMode.bind(this)); this.scope.register(["Mod"], "Enter", this.onEnter.bind(this)); this.scope.register(["Alt"], "Enter", this.onKeyboardContextMenu.bind(this)); this.scope.register([], "\\", this.onKeyboardContextMenu.bind(this)); this.scope.register([], "F2", this.doRename.bind(this)); this.scope.register(["Shift"], "F2", this.doMove.bind(this)); // Scroll preview window up and down this.scope.register([], "PageUp", this.doScroll.bind(this, -1, false)); this.scope.register([], "PageDown", this.doScroll.bind(this, 1, false)); this.scope.register(["Mod"], "Home", this.doScroll.bind(this, 0, true)); this.scope.register(["Mod"], "End", this.doScroll.bind(this, 1, true)); const { dom } = this; dom.style.setProperty( // Allow popovers (hover preview) to overlay this menu "--layer-menu", "" + (parseInt(getComputedStyle(document.body).getPropertyValue("--layer-popover")) - 1) ); const menuItem = ".menu-item[data-file-path]"; dom.on("click", menuItem, this.onItemClick, true); dom.on("contextmenu", menuItem, this.onItemMenu ); dom.on('mouseover' , menuItem, this.onItemHover); dom.on("mousedown", menuItem, e => {e.stopPropagation()}, true); // Fix drag cancelling dom.on('dragstart', menuItem, (event, target) => { startDrag(this.app, target.dataset.filePath, event); }); // When we unload, reactivate parent menu's hover, if needed this.register(() => { autoPreview && this.parent instanceof FolderMenu && this.parent.showPopover(); }) } onArrowLeft(): boolean | undefined { return super.onArrowLeft() ?? this.openBreadcrumb(this.opener?.previousElementSibling); } onKeyboardContextMenu() { const target = this.items[this.selected]?.dom, file = target && this.fileForDom(target); if (file) new ContextMenu(this, file).cascade(target); } doScroll(direction: number, toEnd: boolean, event: KeyboardEvent) { const preview = this.hoverPopover?.hoverEl.find(".markdown-preview-view"); if (preview) { preview.style.scrollBehavior = toEnd ? "auto": "smooth"; const oldTop = preview.scrollTop; const newTop = (toEnd ? 0 : preview.scrollTop) + direction * (toEnd ? preview.scrollHeight : preview.clientHeight); preview.scrollTop = newTop; if (!toEnd) { // Paging past the beginning or end if (newTop >= preview.scrollHeight) { this.onArrowDown(event); } else if (newTop < 0) { if (oldTop > 0) preview.scrollTop = 0; else this.onArrowUp(event); } } } else { if (!autoPreview) { autoPreview = true; this.showPopover(); } // No preview, just go to next or previous item else if (direction > 0) this.onArrowDown(event); else this.onArrowUp(event); } } doRename() { const file = this.currentFile() if (file) this.app.fileManager.promptForFileRename(file); } doMove() { const explorerPlugin = this.app.internalPlugins.plugins["file-explorer"]; if (!explorerPlugin.enabled) { new Notice("File explorer core plugin must be enabled to move files or folders"); return; } const modal = explorerPlugin.instance.moveFileModal; modal.setCurrentFile(this.currentFile()); modal.open() } currentItem() { return this.items[this.selected]; } currentFile() { return this.fileForDom(this.currentItem()?.dom) } fileForDom(targetEl: HTMLDivElement) { const { filePath } = targetEl?.dataset; if (filePath) return this.app.vault.getAbstractFileByPath(filePath); } itemForPath(filePath: string) { return this.items.findIndex(i => i.dom.dataset.filePath === filePath); } openBreadcrumb(element: Element) { if (element && this.rootMenu() === this) { const prevExplorable = this.opener.previousElementSibling; this.hide(); (element as HTMLDivElement).click() return false; } } onArrowRight(): boolean | undefined { const file = this.currentFile(); if (file instanceof TFolder && file !== this.selectedFile) { this.onClickFile(file, this.currentItem().dom); return false; } return this.openBreadcrumb(this.opener?.nextElementSibling); } loadFiles(folder: TFolder, selectedFile?: TAbstractFile) { this.dom.empty(); this.items = []; const allFiles = this.app.vault.getConfig("showUnsupportedFiles"); const {children, parent} = folder; const items = children.slice().sort((a: TAbstractFile, b: TAbstractFile) => alphaSort(a.name, b.name)) const folders = items.filter(f => f instanceof TFolder) as TFolder[]; const files = items.filter(f => f instanceof TFile && (allFiles || this.fileIcon(f))) as TFile[]; folders.sort((a, b) => alphaSort(a.name, b.name)); files.sort((a, b) => alphaSort(a.basename, b.basename)); if (parent) folders.unshift(parent); folders.map(this.addFile, this); if (folders.length && files.length) this.addSeparator(); files.map( this.addFile, this); if (selectedFile) this.select(this.itemForPath(selectedFile.path)); else this.selected = -1; } fileIcon(file: TAbstractFile) { if (file instanceof TFolder) return "folder"; if (file instanceof TFile) { const viewType = this.app.viewRegistry.getTypeByExtension(file.extension); if (viewType) return viewtypeIcons[viewType] ?? "document"; } } fileCount: (file: TAbstractFile) => number = (file: TAbstractFile) => ( file instanceof TFolder ? file.children.map(this.fileCount).reduce((a,b) => a+b, 0) : (this.fileIcon(file) ? 1 : 0) ) addFile(file: TAbstractFile) { const icon = this.fileIcon(file); this.addItem(i => { i.setTitle((file === this.folder.parent) ? ".." : file.name); i.dom.dataset.filePath = file.path; i.dom.setAttr("draggable", "true"); i.dom.addClass (file instanceof TFolder ? "is-qe-folder" : "is-qe-file"); if (icon) i.setIcon(icon); if (file instanceof TFile) { i.setTitle(file.basename); if (file.extension !== "md") i.dom.createDiv({text: file.extension, cls: ["nav-file-tag","qe-extension"]}); } else if (file !== this.folder.parent) { const count = this.fileCount(file); if (count) i.dom.createDiv({text: ""+count, cls: "nav-file-tag qe-file-count"}); } i.onClick(e => this.onClickFile(file, i.dom, e)) }); } togglePreviewMode() { if (autoPreview = !autoPreview) this.showPopover(); else this.hidePopover(); } onload() { super.onload(); this.registerEvent(this.app.vault.on("rename", (file, oldPath) => { if (this.folder === file.parent) { // Destination was here; refresh the list const selectedFile = this.itemForPath(oldPath) >= 0 ? file : this.currentFile(); this.loadFiles(this.folder, selectedFile); } else { // Remove it if it was moved out of here this.removeItemForPath(oldPath); } })); this.registerEvent(this.app.vault.on("delete", file => this.removeItemForPath(file.path))); // Activate preview immediately if applicable if (autoPreview && this.selected != -1) this.showPopover(); } removeItemForPath(path: string) { const posn = this.itemForPath(path); if (posn < 0) return; const item = this.items[posn]; if (this.selected > posn) this.selected -= 1; item.dom.detach() this.items.remove(item); } onEscape() { super.onEscape(); if (this.parent instanceof PopupMenu) this.parent.onEscape(); } hide() { this.hidePopover(); return super.hide(); } setChildMenu(menu: PopupMenu) { super.setChildMenu(menu); if (autoPreview && this.canShowPopover()) this.showPopover(); } select(idx: number, scroll = true) { const old = this.selected; super.select(idx, scroll); if (old !== this.selected) { // selected item changed; trigger new popover or hide the old one if (autoPreview) this.showPopover(); else this.hidePopover(); } } hidePopover() { this.hoverPopover?.hide(); } canShowPopover() { return !this.child && this.visible; } showPopover = debounce(() => { this.hidePopover(); if (!autoPreview) return; this.maybeHover(this.currentItem()?.dom, file => this.app.workspace.trigger('link-hover', this, null, file.path, "")); }, 50, true) onItemHover = (event: MouseEvent, targetEl: HTMLDivElement) => { if (!autoPreview) this.maybeHover(targetEl, file => this.app.workspace.trigger('hover-link', { event, source: hoverSource, hoverParent: this, targetEl, linktext: file.path })); } maybeHover(targetEl: HTMLDivElement, cb: (file: TFile) => void) { if (!this.canShowPopover()) return; let file = this.fileForDom(targetEl) if (file instanceof TFolder) file = this.folderNote(file); if (file instanceof TFile && previewIcons[this.app.viewRegistry.getTypeByExtension(file.extension)]) { cb(file) }; } folderNote(folder: TFolder) { return this.app.vault.getAbstractFileByPath(this.folderNotePath(folder)); } folderNotePath(folder: TFolder) { return `${folder.path}/${folder.name}.md`; } _popover: HoverParent["hoverPopover"]; get hoverPopover() { return this._popover; } set hoverPopover(popover) { if (popover && !this.canShowPopover()) { popover.hide(); return; } this._popover = popover; if (autoPreview && popover && this.currentItem()) { // Position the popover so it doesn't overlap the menu horizontally (as long as it fits) // and so that its vertical position overlaps the selected menu item (placing the top a // bit above the current item, unless it would go off the bottom of the screen) const hoverEl = popover.hoverEl; hoverEl.show(); const menu = this.dom.getBoundingClientRect(), selected = this.currentItem().dom.getBoundingClientRect(), container = hoverEl.offsetParent || document.documentElement, popupHeight = hoverEl.offsetHeight, left = Math.min(menu.right + 2, container.clientWidth - hoverEl.offsetWidth), top = Math.min(Math.max(0, selected.top - popupHeight/8), container.clientHeight - popupHeight) ; hoverEl.style.top = top + "px"; hoverEl.style.left = left + "px"; } } onItemClick = (event: MouseEvent, target: HTMLDivElement) => { const file = this.fileForDom(target); if (!file) return; if (!this.onClickFile(file, target, event)) { // Keep current menu tree open event.stopPropagation(); event.preventDefault(); return false; } } onClickFile(file: TAbstractFile, target: HTMLDivElement, event?: MouseEvent|KeyboardEvent) { this.hidePopover(); const idx = this.itemForPath(file.path); if (idx >= 0 && this.selected != idx) this.select(idx); if (file instanceof TFile) { if (this.app.viewRegistry.isExtensionRegistered(file.extension)) { this.app.workspace.openLinkText(file.path, "", event && Keymap.isModifier(event, "Mod")); // Close the entire menu tree this.rootMenu().hide(); event?.stopPropagation(); return true; } else { new Notice(`.${file.extension} files cannot be opened in Obsidian; Use "Open in Default App" to open them externally`); // fall through } } else if (file === this.parentFolder) { // We're a child menu and selected "..": just return to previous menu this.hide(); } else if (file === this.folder.parent) { // Not a child menu, but selected "..": go to previous breadcrumb this.onArrowLeft(); } else if (file === this.selectedFile) { // Targeting the initially-selected subfolder: go to next breadcrumb this.openBreadcrumb(this.opener?.nextElementSibling); } else { // Otherwise, pop a new menu for the subfolder const folderMenu = new FolderMenu(this, file as TFolder, this.folderNote(file as TFolder) || this.folder); folderMenu.cascade(target, event instanceof MouseEvent ? event : undefined); } } onItemMenu = (event: MouseEvent, target: HTMLDivElement) => { const file = this.fileForDom(target); if (file) { const idx = this.itemForPath(file.path); if (idx >= 0 && this.selected != idx) this.select(idx); new ContextMenu(this, file).cascade(target, event); // Keep current menu tree open event.stopPropagation(); } } }
the_stack
import { expect } from "chai"; import { mount, shallow } from "enzyme"; import * as React from "react"; import * as sinon from "sinon"; import { RelativePosition } from "@itwin/appui-abstract"; import { fireEvent, render, RenderResult } from "@testing-library/react"; import { Popup, PopupProps } from "../../core-react"; function NestedPopup() { const [showPopup, setShowPopup] = React.useState(false); const buttonRef = React.useRef<HTMLButtonElement>(null); const togglePopup = React.useCallback(() => { setShowPopup(!showPopup); }, [showPopup]); const handleClose = React.useCallback(() => { setShowPopup(false); }, []); return ( <div> <button data-testid="NestedPopup" onClick={togglePopup} ref={buttonRef}>{showPopup ? "Close" : "Open"}</button> <Popup isOpen={showPopup} position={RelativePosition.Bottom} target={buttonRef.current} onClose={handleClose} showArrow={true} showShadow={true} > <div> <button data-testid="NestedPopup-Button">Test</button> </div> </Popup> </div> ); } function PrimaryPopup({ closeOnNestedPopupOutsideClick }: { closeOnNestedPopupOutsideClick?: boolean }) { const [showPopup, setShowPopup] = React.useState(false); const buttonRef = React.useRef<HTMLButtonElement>(null); const togglePopup = React.useCallback(() => { setShowPopup(!showPopup); }, [showPopup]); const handleClose = React.useCallback(() => { setShowPopup(false); }, []); return ( <div> <button data-testid="PrimaryPopup" onClick={togglePopup} ref={buttonRef}>{showPopup ? "Close" : "Open"}</button> <Popup isOpen={showPopup} position={RelativePosition.Bottom} target={buttonRef.current} onClose={handleClose} showArrow={true} showShadow={true} closeOnNestedPopupOutsideClick={closeOnNestedPopupOutsideClick}> <NestedPopup /> </Popup> </div> ); } describe("<Popup />", () => { const sandbox = sinon.createSandbox(); afterEach(() => { sandbox.restore(); }); it("renders correctly", () => { const component = render(<Popup isOpen top={30} left={70} />); expect(component.getByTestId("core-popup")).to.exist; }); it("mounts and unmounts correctly", () => { const wrapper = render(<Popup isOpen top={30} left={70} />); wrapper.unmount(); }); it("mounts with role correctly", () => { const wrapper = render(<Popup isOpen top={30} left={70} role="alert" />); wrapper.unmount(); }); it("renders correctly closed and open", () => { const component = render(<Popup top={30} left={70} />); expect(component.queryByTestId("core-popup")).not.to.exist; component.rerender(<Popup isOpen top={30} left={70} />); expect(component.getByTestId("core-popup")).to.exist; }); it("button opens popup and moves focus correctly (HTMLElementRef)", async () => { const focusTarget = React.createRef<HTMLButtonElement>(); // button that should receive focus after popup is open let button: HTMLElement | null = null; let isOpen = false; const component = render(<div> <button ref={(el) => { button = el; }} onClick={() => isOpen = !isOpen} /> <Popup isOpen={isOpen} top={30} left={70} focusTarget={focusTarget} moveFocus> <div> <button data-testid="button-not-to-have-focus" /> <button data-testid="button-to-have-focus" ref={focusTarget} /> </div> </Popup> </div>); expect(component).not.to.be.null; expect(button).not.to.be.null; expect(isOpen).to.be.false; fireEvent.click(button!); expect(isOpen).to.be.true; component.rerender(<div> <button ref={(el) => { button = el; }} onClick={() => isOpen = !isOpen} /> <Popup isOpen={isOpen} top={30} left={70} focusTarget={focusTarget} moveFocus> <div> <button data-testid="button-not-to-have-focus" /> <button data-testid="button-to-have-focus" ref={focusTarget} /> </div> </Popup> </div>); // component.debug(); const popup = component.getByTestId("core-popup"); expect(popup).to.exist; // wait for button to receive focus await new Promise((r) => { setTimeout(r, 80); }); const buttonWithFocus = component.getByTestId("button-to-have-focus") as HTMLButtonElement; const focusedElement = document.activeElement; expect(focusedElement).to.eq(buttonWithFocus); }); it("button opens popup and moves focus correctly (CSS Selector)", async () => { let button: HTMLElement | null = null; let isOpen = false; const component = render(<div> <button ref={(el) => { button = el; }} onClick={() => isOpen = !isOpen} /> <Popup isOpen={isOpen} top={30} left={70} focusTarget=".button-to-have-focus" moveFocus> <div> <button className="button-not-to-have-focus" data-testid="button-not-to-have-focus" /> <button className="button-to-have-focus" data-testid="button-to-have-focus" /> </div> </Popup> </div>); expect(component).not.to.be.null; expect(button).not.to.be.null; expect(isOpen).to.be.false; fireEvent.click(button!); expect(isOpen).to.be.true; component.rerender(<div> <button ref={(el) => { button = el; }} onClick={() => isOpen = !isOpen} /> <Popup isOpen={isOpen} top={30} left={70} focusTarget=".button-to-have-focus" moveFocus> <div> <button className="button-not-to-have-focus" data-testid="button-not-to-have-focus" /> <button className="button-to-have-focus" data-testid="button-to-have-focus" /> </div> </Popup> </div>); // component.debug(); const popup = component.getByTestId("core-popup"); expect(popup).to.exist; // wait for button to receive focus await new Promise((r) => { setTimeout(r, 80); }); const buttonWithFocus = component.getByTestId("button-to-have-focus") as HTMLButtonElement; const focusedElement = document.activeElement; expect(focusedElement).to.eq(buttonWithFocus); }); it("button opens popup and moves focus to first available", async () => { let button: HTMLElement | null = null; let isOpen = false; const component = render(<div> <button ref={(el) => { button = el; }} onClick={() => isOpen = !isOpen} /> <Popup isOpen={isOpen} top={30} left={70} moveFocus> <div> <span /> <input data-testid="input-one" /> <input data-testid="input-two" /> </div> </Popup> </div>); expect(component).not.to.be.null; expect(button).not.to.be.null; expect(isOpen).to.be.false; fireEvent.click(button!); expect(isOpen).to.be.true; component.rerender(<div> <button ref={(el) => { button = el; }} onClick={() => isOpen = !isOpen} /> <Popup isOpen={isOpen} top={30} left={70} moveFocus> <div> <span /> <input data-testid="input-one" /> <input data-testid="input-two" /> </div> </Popup> </div>); // component.debug(); const popup = component.getByTestId("core-popup"); expect(popup).to.exist; // wait for button to receive focus await new Promise((r) => { setTimeout(r, 80); }); const topDiv = component.getByTestId("focus-trap-div") as HTMLDivElement; const bottomDiv = component.getByTestId("focus-trap-limit-div") as HTMLDivElement; const inputOne = component.getByTestId("input-one") as HTMLInputElement; expect(document.activeElement).to.eq(inputOne); const inputTwo = component.getByTestId("input-two") as HTMLInputElement; inputTwo.focus(); expect(document.activeElement).to.eq(inputTwo as HTMLElement); // if we hit top - reset focus to bottom topDiv.focus(); expect(document.activeElement).to.eq(inputTwo as HTMLElement); // if we hit bottom - reset focus to top bottomDiv.focus(); expect(document.activeElement).to.eq(inputOne as HTMLElement); }); it("popup and moves focus to first available (button)", async () => { const component = render(<div> <Popup isOpen top={30} left={70} moveFocus> <div> <span /> <button data-testid="item-one" /> <button data-testid="item-two" /> </div> </Popup> </div>); expect(component.getByTestId("core-popup")).to.exist; // wait for button to receive focus await new Promise((r) => { setTimeout(r, 80); }); const activeFocusElement = document.activeElement; expect(activeFocusElement).to.eq(component.getByTestId("item-one")); }); it("popup and moves focus to first available (a)", async () => { const component = render(<div> <Popup isOpen top={30} left={70} moveFocus> <div> <span /> <div> <div> <a href="test" data-testid="item-one">test1</a> </div> </div> <a href="test" data-testid="item-two">test2</a> </div> </Popup> </div>); expect(component.getByTestId("core-popup")).to.exist; // component.debug(); // wait for button to receive focus await new Promise((r) => { setTimeout(r, 80); }); const activeFocusElement = document.activeElement; expect(activeFocusElement).to.eq(component.getByTestId("item-one")); }); it("popup and moves focus to first available (textarea)", async () => { const component = render(<div> <Popup isOpen top={30} left={70} moveFocus> <div> <span /> <textarea data-testid="item-one" /> <textarea data-testid="item-two" /> </div> </Popup> </div>); expect(component.getByTestId("core-popup")).to.exist; // wait for button to receive focus await new Promise((r) => { setTimeout(r, 80); }); const activeFocusElement = document.activeElement; expect(activeFocusElement).to.eq(component.getByTestId("item-one")); }); it("popup should NOT close when click in nested popup", async () => { const component = render(<PrimaryPopup />); const primaryButton = component.getByTestId("PrimaryPopup"); expect(primaryButton).to.exist; fireEvent.click(primaryButton); const secondaryButton = component.getByTestId("NestedPopup"); expect(secondaryButton).to.exist; fireEvent.click(secondaryButton); let nestedButton = component.getByTestId("NestedPopup-Button"); expect(nestedButton).to.exist; fireEvent.click(nestedButton); const mouseDown = new PointerEvent("pointerdown"); sinon.stub(mouseDown, "target").get(() => nestedButton); window.dispatchEvent(mouseDown); // component.debug(); nestedButton = component.getByTestId("NestedPopup-Button"); expect(nestedButton).to.exist; }); it("popup should close when click in nested popup", async () => { const component = render(<PrimaryPopup closeOnNestedPopupOutsideClick={true} />); const primaryButton = component.getByTestId("PrimaryPopup"); expect(primaryButton).to.exist; fireEvent.click(primaryButton); const secondaryButton = component.getByTestId("NestedPopup"); expect(secondaryButton).to.exist; fireEvent.click(secondaryButton); const nestedButton = component.getByTestId("NestedPopup-Button"); expect(nestedButton).to.exist; fireEvent.click(nestedButton); const mouseDown = new PointerEvent("pointerdown"); sinon.stub(mouseDown, "target").get(() => nestedButton); window.dispatchEvent(mouseDown); // component.debug(); expect(component.queryByTestId("NestedPopup-Button")).to.be.null; }); describe("renders", () => { it("should render with few props", () => { const wrapper = mount( <div> <Popup isOpen /> </div>); wrapper.unmount(); }); it("should render with many props", () => { const wrapper = mount( <div> <Popup isOpen onOpen={() => { }} onClose={() => { }} showShadow showArrow position={RelativePosition.BottomRight} /> </div>); wrapper.unmount(); }); it("renders correctly with few props", () => { shallow( <div> <Popup isOpen /> </div>).should.matchSnapshot(); }); it("renders correctly with many props", () => { shallow( <div> <Popup isOpen onOpen={() => { }} onClose={() => { }} showShadow showArrow position={RelativePosition.BottomRight} /> </div>).should.matchSnapshot(); }); it("renders correctly with no animation", () => { shallow( <div> <Popup isOpen animate={false} /> </div>).should.matchSnapshot(); }); }); describe("componentDidUpdate", () => { it("should call onOpen", () => { const spyOnOpen = sinon.spy(); const wrapper = mount(<Popup onOpen={spyOnOpen} />); wrapper.setProps({ isOpen: true }); expect(spyOnOpen.calledOnce).to.be.true; wrapper.unmount(); }); it("should call onClose", () => { const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} />); wrapper.setProps({ isOpen: false }); expect(spyOnClose.calledOnce).to.be.true; wrapper.unmount(); }); }); describe("positioning", () => { let divWrapper: RenderResult; let targetElement: HTMLElement | null; beforeEach(() => { divWrapper = render(<div data-testid="test-target" />); targetElement = divWrapper.getByTestId("test-target"); }); afterEach(() => { divWrapper.unmount(); }); it("should render TopLeft", () => { const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 100, height: 50 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.TopLeft} target={target} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-top-left"); expect(popup.length).be.eq(1); wrapper.state("top").should.eq(96); wrapper.state("position").should.eq(RelativePosition.TopLeft); wrapper.unmount(); }); it("should render TopRight", () => { const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 100, height: 50 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.TopRight} target={target} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-top-right"); wrapper.state("top").should.eq(96); expect(popup.length).be.eq(1); wrapper.state("position").should.eq(RelativePosition.TopRight); wrapper.unmount(); }); it("should render BottomLeft", () => { const wrapper = mount<PopupProps>(<Popup position={RelativePosition.BottomLeft} target={targetElement} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-bottom-left"); expect(popup.length).be.eq(1); wrapper.state("position").should.eq(RelativePosition.BottomLeft); wrapper.unmount(); }); it("should render BottomRight", () => { const wrapper = mount<PopupProps>(<Popup position={RelativePosition.BottomRight} target={targetElement} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-bottom-right"); expect(popup.length).be.eq(1); wrapper.state("position").should.eq(RelativePosition.BottomRight); wrapper.unmount(); }); it("should render Top", () => { const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 100, height: 50 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Top} target={target} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-top"); expect(popup.length).be.eq(1); wrapper.state("top").should.eq(96); wrapper.state("position").should.eq(RelativePosition.Top); wrapper.unmount(); }); it("should render Left", () => { const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ x: 100, width: 50 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Left} target={target} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-left"); expect(popup.length).be.eq(1); wrapper.state("left").should.eq(96); wrapper.state("position").should.eq(RelativePosition.Left); wrapper.unmount(); }); it("should render Right", () => { const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Right} target={targetElement} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-right"); expect(popup.length).be.eq(1); wrapper.state("position").should.eq(RelativePosition.Right); wrapper.unmount(); }); it("should render Bottom", () => { const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Bottom} target={targetElement} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-bottom"); expect(popup.length).be.eq(1); wrapper.state("position").should.eq(RelativePosition.Bottom); wrapper.unmount(); }); it("should render LeftTop", () => { const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ x: 100, width: 50 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.LeftTop} target={target} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-left-top"); expect(popup.length).be.eq(1); wrapper.state("position").should.eq(RelativePosition.LeftTop); wrapper.unmount(); }); it("should render RightTop", () => { const wrapper = mount<PopupProps>(<Popup position={RelativePosition.RightTop} target={targetElement} />); wrapper.setProps({ isOpen: true }); const popup = wrapper.find("div.core-popup-right-top"); expect(popup.length).be.eq(1); wrapper.state("position").should.eq(RelativePosition.RightTop); wrapper.unmount(); }); it("should render Bottom then Right", () => { const wrapper = mount(<Popup position={RelativePosition.Bottom} target={targetElement} />); wrapper.setProps({ isOpen: true }); let popup = wrapper.find("div.core-popup-bottom"); expect(popup.length).be.eq(1); wrapper.setProps({ position: RelativePosition.Right }); wrapper.update(); popup = wrapper.find("div.core-popup-right"); expect(popup.length).be.eq(1); wrapper.unmount(); }); }); describe("re-positioning", () => { it("should reposition Bottom to Top", () => { sandbox.stub(window, "innerHeight").get(() => 1000); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 100, height: 900 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Bottom} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.Top); wrapper.unmount(); }); it("should reposition BottomLeft to TopLeft", () => { sandbox.stub(window, "innerHeight").get(() => 1000); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 100, height: 900 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.BottomLeft} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.TopLeft); wrapper.unmount(); }); it("should reposition BottomRight to TopRight", () => { sandbox.stub(window, "innerHeight").get(() => 1000); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 100, height: 900 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.BottomRight} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.TopRight); wrapper.unmount(); }); it("should reposition Top to Bottom", () => { sandbox.stub(window, "scrollY").get(() => 100); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 80 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Top} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.Bottom); wrapper.unmount(); }); it("should reposition TopLeft to BottomLeft", () => { sandbox.stub(window, "scrollY").get(() => 100); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 80 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.TopLeft} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.BottomLeft); wrapper.unmount(); }); it("should reposition TopLeft to BottomLeft", () => { sandbox.stub(window, "scrollY").get(() => 100); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 80 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.TopLeft} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.BottomLeft); wrapper.unmount(); }); it("should reposition TopRight to BottomRight", () => { sandbox.stub(window, "scrollY").get(() => 100); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 80 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.TopRight} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.BottomRight); wrapper.unmount(); }); it("should reposition Left to Right", () => { sandbox.stub(window, "scrollX").get(() => 100); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ x: 80 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Left} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.Right); wrapper.unmount(); }); it("should reposition LeftTop to RightTop", () => { sandbox.stub(window, "scrollX").get(() => 100); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ x: 80 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.LeftTop} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.RightTop); wrapper.unmount(); }); it("should reposition Right to Left", () => { sandbox.stub(window, "innerWidth").get(() => 1000); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ width: 1010 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Right} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.Left); wrapper.unmount(); }); it("should reposition RightTop to LeftTop", () => { sandbox.stub(window, "innerWidth").get(() => 1000); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ width: 1010 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.RightTop} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.LeftTop); wrapper.unmount(); }); it("should not reposition on bottom overflow", () => { sandbox.stub(window, "innerHeight").get(() => 900); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ y: 100, height: 900 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Top} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.Top); wrapper.unmount(); }); it("should not reposition on right overflow", () => { sandbox.stub(window, "innerWidth").get(() => 1000); const target = document.createElement("div"); sinon.stub(target, "getBoundingClientRect").returns(DOMRect.fromRect({ x: 100, width: 1000 })); const wrapper = mount<PopupProps>(<Popup position={RelativePosition.Left} target={target} />); wrapper.setProps({ isOpen: true }); wrapper.state("position").should.eq(RelativePosition.Left); wrapper.unmount(); }); }); describe("outside click", () => { it("should call onOutsideClick", () => { const spy = sinon.spy(); const wrapper = mount(<Popup isOpen onOutsideClick={spy} />); const popup = wrapper.find(".core-popup").getDOMNode(); sinon.stub(popup, "contains").returns(false); const mouseDown = new PointerEvent("pointerdown"); sinon.stub(mouseDown, "target").get(() => document.createElement("div")); window.dispatchEvent(mouseDown); expect(spy.calledOnceWithExactly(mouseDown)).be.true; wrapper.unmount(); }); it("should close on click outside without onOutsideClick", () => { const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} />); const popup = wrapper.find(".core-popup").getDOMNode(); sinon.stub(popup, "contains").returns(false); const mouseDown = new PointerEvent("pointerdown"); sinon.stub(mouseDown, "target").get(() => document.createElement("div")); window.dispatchEvent(mouseDown); spyOnClose.calledOnce.should.true; expect(wrapper.state("isOpen")).to.be.false; wrapper.unmount(); }); it("should not close on click outside if pinned", () => { const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} isPinned />); const popup = wrapper.find(".core-popup").getDOMNode(); sinon.stub(popup, "contains").returns(false); const mouseDown = new PointerEvent("pointerdown"); sinon.stub(mouseDown, "target").get(() => document.createElement("div")); window.dispatchEvent(mouseDown); spyOnClose.calledOnce.should.false; expect(wrapper.state("isOpen")).to.be.true; wrapper.unmount(); }); it("should not close on popup content click", () => { const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} />); const popup = wrapper.find(".core-popup").getDOMNode(); sinon.stub(popup, "contains").returns(true); const mouseDown = new PointerEvent("pointerdown"); sinon.stub(mouseDown, "target").get(() => document.createElement("div")); window.dispatchEvent(mouseDown); spyOnClose.calledOnce.should.false; expect(wrapper.state("isOpen")).to.be.true; wrapper.unmount(); }); it("should not close on target content click", () => { const target = document.createElement("div"); sinon.stub(target, "contains").returns(true); const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} target={target} />); const mouseDown = new PointerEvent("pointerdown"); sinon.stub(mouseDown, "target").get(() => document.createElement("div")); window.dispatchEvent(mouseDown); spyOnClose.calledOnce.should.false; expect(wrapper.state("isOpen")).to.be.true; wrapper.unmount(); }); }); describe("scrolling", () => { it("should hide when scrolling", () => { const wrapper = mount<Popup>(<Popup isOpen />); const scroll = new WheelEvent("wheel"); sinon.stub(scroll, "target").get(() => document.createElement("div")); window.dispatchEvent(scroll); expect(wrapper.state().isOpen).false; wrapper.unmount(); }); it("should not hide when scrolling popup content", () => { const wrapper = mount<Popup>(<Popup isOpen />); const popup = wrapper.find(".core-popup").getDOMNode(); const scroll = new WheelEvent("wheel"); sinon.stub(scroll, "target").get(() => popup); window.dispatchEvent(scroll); expect(wrapper.state().isOpen).true; wrapper.unmount(); }); it("should not hide when scrolling if pinned", () => { const wrapper = mount<Popup>(<Popup isOpen isPinned />); const scroll = new WheelEvent("wheel"); sinon.stub(scroll, "target").get(() => document.createElement("div")); window.dispatchEvent(scroll); expect(wrapper.state().isOpen).true; wrapper.unmount(); }); it("should not hide when scrolling if closeOnWheel=false", () => { const wrapper = mount<Popup>(<Popup isOpen closeOnWheel={false} />); const scroll = new WheelEvent("wheel"); sinon.stub(scroll, "target").get(() => document.createElement("div")); window.dispatchEvent(scroll); expect(wrapper.state().isOpen).true; wrapper.unmount(); }); it("should not hide when scrolling if onWheel prop is passed", () => { const spyWheel = sinon.spy(); const wrapper = mount<Popup>(<Popup isOpen onWheel={spyWheel} />); const scroll = new WheelEvent("wheel"); sinon.stub(scroll, "target").get(() => document.createElement("div")); window.dispatchEvent(scroll); expect(wrapper.state().isOpen).true; sinon.assert.called(spyWheel); wrapper.unmount(); }); }); describe("context menu", () => { it("should hide when context menu used", () => { const wrapper = mount<Popup>(<Popup isOpen />); const contextMenu = new MouseEvent("contextmenu"); sinon.stub(contextMenu, "target").get(() => document.createElement("div")); window.dispatchEvent(contextMenu); expect(wrapper.state().isOpen).false; wrapper.unmount(); }); it("should not hide when context menu used popup content", () => { const wrapper = mount<Popup>(<Popup isOpen />); const popup = wrapper.find(".core-popup").getDOMNode(); const contextMenu = new MouseEvent("contextmenu"); sinon.stub(contextMenu, "target").get(() => popup); window.dispatchEvent(contextMenu); expect(wrapper.state().isOpen).true; wrapper.unmount(); }); it("should not hide when context menu used if pinned", () => { const wrapper = mount<Popup>(<Popup isOpen isPinned />); const contextMenu = new MouseEvent("contextmenu"); sinon.stub(contextMenu, "target").get(() => document.createElement("div")); window.dispatchEvent(contextMenu); expect(wrapper.state().isOpen).true; wrapper.unmount(); }); it("should not hide when context menu used if closeOnContextMenu=false", () => { const wrapper = mount<Popup>(<Popup isOpen closeOnContextMenu={false} />); const contextMenu = new MouseEvent("contextmenu"); sinon.stub(contextMenu, "target").get(() => document.createElement("div")); window.dispatchEvent(contextMenu); expect(wrapper.state().isOpen).true; wrapper.unmount(); }); it("should not hide when context menu used if onContextMenu prop is passed", () => { const spyContextMenu = sinon.spy(); const wrapper = mount<Popup>(<Popup isOpen onContextMenu={spyContextMenu} />); const contextMenu = new MouseEvent("contextmenu"); sinon.stub(contextMenu, "target").get(() => document.createElement("div")); window.dispatchEvent(contextMenu); expect(wrapper.state().isOpen).true; sinon.assert.called(spyContextMenu); wrapper.unmount(); }); }); describe("keyboard handling", () => { it("should close on Escape", () => { const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} />); expect(wrapper.state("isOpen")).to.be.true; window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, view: window, key: "Escape" })); spyOnClose.calledOnce.should.true; expect(wrapper.state("isOpen")).to.be.false; wrapper.unmount(); }); it("should close on Enter", () => { const spyOnClose = sinon.spy(); const spyOnEnter = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} onEnter={spyOnEnter} />); expect(wrapper.state("isOpen")).to.be.true; window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, view: window, key: "Enter" })); spyOnClose.calledOnce.should.true; spyOnEnter.calledOnce.should.true; expect(wrapper.state("isOpen")).to.be.false; wrapper.unmount(); }); it("should not close on Enter if closeOnEnter=false", () => { const spyOnClose = sinon.spy(); const spyOnEnter = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} onEnter={spyOnEnter} closeOnEnter={false} />); expect(wrapper.state("isOpen")).to.be.true; window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, view: window, key: "Enter" })); spyOnClose.calledOnce.should.false; spyOnEnter.calledOnce.should.true; expect(wrapper.state("isOpen")).to.be.true; wrapper.unmount(); }); it("should do nothing on 'a'", () => { const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose}><div>fake content</div></Popup>); expect(wrapper.state("isOpen")).to.be.true; window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, view: window, key: "a" })); spyOnClose.calledOnce.should.false; expect(wrapper.state("isOpen")).to.be.true; wrapper.unmount(); }); it("should not close if Pinned", () => { const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} isPinned />); expect(wrapper.state("isOpen")).to.be.true; window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, view: window, key: "Escape" })); spyOnClose.calledOnce.should.false; expect(wrapper.state("isOpen")).to.be.true; wrapper.unmount(); }); it("should not close if not open", () => { const spyOnClose = sinon.spy(); const wrapper = mount(<Popup isOpen onClose={spyOnClose} />); wrapper.setState({ isOpen: false }); window.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, view: window, key: "Escape" })); spyOnClose.notCalled.should.true; wrapper.unmount(); }); }); });
the_stack
import * as parse5 from 'parse5'; import SaxStream from 'parse5-sax-parser'; import { Position } from 'vscode-languageserver-textdocument'; import { AccessScopeExpression, CallScopeExpression, ExpressionKind, ExpressionType, Interpolation, parseExpression, } from '../../common/@aurelia-runtime-patch/src'; import { SourceCodeLocation as ASTSourceCodeLocation } from '../../common/@aurelia-runtime-patch/src/binding/ast'; import { AureliaView } from '../../common/constants'; import { DiagnosticMessages } from '../../common/diagnosticMessages/DiagnosticMessages'; import { findAllExpressionRecursive, ParseExpressionUtil, } from '../../common/parseExpression/ParseExpressionUtil'; import { getBindableNameFromAttritute } from '../../common/template/aurelia-attributes'; import { AbstractRegionLanguageService } from './languageServer/AbstractRegionLanguageService'; import { AttributeInterpolationLanguageService } from './languageServer/AttributeInterpolationLanguageService'; import { AttributeLanguageService } from './languageServer/AttributeLanguageService'; import { AureliaHtmlLanguageService } from './languageServer/AureliaHtmlLanguageService'; import { BindableAttributeLanguageService } from './languageServer/BindableAttributeLanguageService'; import { CustomElementLanguageService } from './languageServer/CustomElementLanguageService'; import { ImportLanguageService } from './languageServer/ImportLanguageService'; import { RepeatForLanguageService } from './languageServer/RepeatForLanguageService'; import { TextInterpolationLanguageService } from './languageServer/TextInterpolationLanguageService'; import { ValueConverterLanguageService } from './languageServer/ValueConverterLanguageService'; import { IViewRegionsVisitor } from './ViewRegionsVisitor'; export type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>; export type RequiredBy<T, K extends keyof T> = Partial<T> & Pick<T, K>; export interface ViewRegionInfoV2<RegionDataType = unknown> { // type: ViewRegionType; subType?: ViewRegionSubType; // sourceCodeLocation: SourceCodeLocation; startTagLocation?: SourceCodeLocation; // tagName: string; attributeName?: string; attributeValue?: string; textValue?: string; regionValue?: string; // accessScopes?: (AccessScopeExpression | CallScopeExpression)[]; data?: RegionDataType; } export enum ViewRegionType { Attribute = 'Attribute', AttributeInterpolation = 'AttributeInterpolation', BindableAttribute = 'BindableAttribute', CustomElement = 'CustomElement', Html = 'html', Import = 'Import', RepeatFor = 'RepeatFor', TextInterpolation = 'TextInterpolation', ValueConverter = 'ValueConverter', } export enum ViewRegionSubType { StartTag = 'StartTag', EndTag = 'EndTag', } type CustomElementRegionData = AbstractRegion[]; export interface RepeatForRegionData { /** repeat.for="num of >numbers<" */ iterableName: string; iterableStartOffset: number; iterableEndOffset: number; /** repeat.for=">num< of numbers" */ iterator: string; } /** * TODO: how to deal with the second valCon? ___v___ * * repo of repos | sort:column.value:direction.value | take:10 * _____________ _________________________________ * ^initiatorText ^valueConverterText */ export interface ValueConverterRegionData { /** * ``` * >repo of repos< | sort:column.value:direction.value | take:10 * ``` * * TODO: Should initiatro text be only first part or all for `| take:10`? */ initiatorText: string; /** ```repo of repos | >sort<:column.value:direction.value | take:10``` */ valueConverterName: string; /** ``` repo of repos | sort:>column.value:direction.value< | take:10 ``` */ valueConverterText: string; } interface SourceCodeLocation { startOffset: number; startCol: number; startLine: number; endOffset: number; endCol: number; endLine: number; } export abstract class AbstractRegion implements ViewRegionInfoV2 { public languageService: AbstractRegionLanguageService; // public type: ViewRegionType; public subType?: ViewRegionSubType; // public sourceCodeLocation: SourceCodeLocation; public startTagLocation?: SourceCodeLocation; // public tagName: string; public attributeName?: string; public attributeValue?: string; public textValue?: string; public regionValue?: string; // public accessScopes?: ViewRegionInfoV2['accessScopes']; public data?: unknown; constructor(info: ViewRegionInfoV2) { // this.type = info.type; if (info.subType !== undefined) this.subType = info.subType; // this.sourceCodeLocation = { startCol: info.sourceCodeLocation.startCol, startLine: info.sourceCodeLocation.startLine, startOffset: info.sourceCodeLocation.startOffset, endLine: info.sourceCodeLocation.endLine, endCol: info.sourceCodeLocation.endCol, endOffset: info.sourceCodeLocation.endOffset, }; if (info.startTagLocation !== undefined) this.startTagLocation = info.startTagLocation; // this.tagName = info.tagName; this.attributeName = info.attributeName; this.attributeValue = info.attributeValue; if (info.textValue !== undefined) this.textValue = info.textValue; if (info.regionValue !== undefined) this.regionValue = info.regionValue; // if (info.accessScopes !== undefined) this.accessScopes = info.accessScopes; if (info.data !== undefined) this.data = info.data; } // region static public static create(info: ViewRegionInfoV2) { return info; } public static is(region: AbstractRegion): unknown { return region; } public static isInterpolationRegion(region: AbstractRegion): boolean { const isInterpolationRegion = AttributeInterpolationRegion.is(region) === true || TextInterpolationRegion.is(region) === true; return isInterpolationRegion; } // public static parse5Start( // startTag: SaxStream.StartTagToken, // attr: parse5.Attribute // ) {} // public static parse5Interpolation( // startTag: SaxStream.StartTagToken, // attr: parse5.Attribute, // interpolationMatch: RegExpExecArray | null // ) {} // public static parse5End(endTag: SaxStream.EndTagToken, attr: parse5.Attribute) {} // public static parse5Text( // text: SaxStream.TextToken, // interpolationMatch: RegExpExecArray | null // ) {} // endregion public // region public public accept<T>(visitor: IViewRegionsVisitor<T>): T | void { // eslint-disable-next-line @typescript-eslint/no-unused-expressions visitor; } public getStartPosition(): Position { return { line: this.sourceCodeLocation.startLine, character: this.sourceCodeLocation.startCol, }; } public getEndPosition(): Position { return { line: this.sourceCodeLocation.endLine, character: this.sourceCodeLocation.endCol, }; } // endregion public } export class AttributeRegion extends AbstractRegion { public languageService: AttributeLanguageService; public readonly type: ViewRegionType.Attribute; public readonly accessScopes?: AccessScopeExpression[]; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new AttributeLanguageService(); } public static create(info: Optional<ViewRegionInfoV2, 'type'>) { const finalInfo = convertToRegionInfo({ ...info, type: ViewRegionType.Attribute, }); return new AttributeRegion(finalInfo); } public static is(region: AbstractRegion): region is CustomElementRegion { return region.type === ViewRegionType.Attribute; } public static parse5( startTag: SaxStream.StartTagToken, attr: parse5.Attribute ) { const attrLocation = startTag.sourceCodeLocation?.attrs[attr.name]; if (!attrLocation) return; /** Eg. >click.delegate="<increaseCounter()" */ const attrNameLength = attr.name.length + // click.delegate 2; // =" /** Eg. click.delegate="increaseCounter()><" */ const lastCharIndex = attrLocation.endOffset - 1; // - 1 the quote const startOffset = attrLocation.startOffset + attrNameLength; const updatedLocation: parse5.Location = { ...attrLocation, startOffset, endOffset: lastCharIndex, }; const { expressions: accessScopes } = ParseExpressionUtil.getAllExpressionsOfKindV2( attr.value, [ExpressionKind.AccessScope, ExpressionKind.CallScope], { startOffset } ); const viewRegion = AttributeRegion.create({ attributeName: attr.name, attributeValue: attr.value, sourceCodeLocation: updatedLocation, tagName: startTag.tagName, accessScopes, regionValue: attr.value, }); return viewRegion; } public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitAttribute(this); } } export class AttributeInterpolationRegion extends AbstractRegion { public languageService: AttributeInterpolationLanguageService; public readonly type: ViewRegionType.AttributeInterpolation; public readonly accessScopes: AccessScopeExpression[]; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new AttributeInterpolationLanguageService(); } public static create(info: Optional<ViewRegionInfoV2, 'type'>) { const finalInfo = convertToRegionInfo({ ...info, type: ViewRegionType.AttributeInterpolation, }); return new AttributeInterpolationRegion(finalInfo); } public static is(region: AbstractRegion): region is CustomElementRegion { return region.type === ViewRegionType.AttributeInterpolation; } public static parse5Interpolation( startTag: SaxStream.StartTagToken, attr: parse5.Attribute, interpolationMatch: RegExpExecArray | null, documentHasCrlf: boolean ) { const attrLocation = startTag.sourceCodeLocation?.attrs[attr.name]; if (!attrLocation) return; /** Eg. >click.delegate="<increaseCounter()" */ const attrNameLength = attr.name.length + // click.delegate 2; // =" // attrNameLength /* ? */ /** Eg. click.delegate="increaseCounter()><" */ // const lastCharIndex = attrLocation.endOffset - 1; // - 1 the quote const startOffset = attrLocation.startOffset + attrNameLength; // const updatedLocation: parse5.Location = { // ...attrLocation, // startOffset, // endOffset: lastCharIndex, // }; try { // attr.value /* ? */ const parsed = ParseExpressionUtil.parseInterpolation( attr.value, startOffset ); // parsed; /* ? */ // parsed.parts; /* ? */ // Used to find interpolation(s) inside string let stringTracker = attr.value; // For each expression "group", create a region const finalRegions = parsed?.expressions.map( (expression, expressionIndex) => { const accessScopes: ViewRegionInfoV2['accessScopes'] = []; findAllExpressionRecursive( expression, [ExpressionKind.AccessScope, ExpressionKind.CallScope], accessScopes ); if (documentHasCrlf) { accessScopes.forEach((scope) => { const { start } = scope.nameLocation; const textUntilMatch = attr.value.substring(0, start); // crlf = carriage return, line feed (windows specific) let numberOfCrlfs = 0; const crlfRegex = /\n/g; numberOfCrlfs = textUntilMatch.match(crlfRegex)?.length ?? 0; scope.nameLocation.start += numberOfCrlfs; scope.nameLocation.end += numberOfCrlfs; }); } const isLastIndex = expressionIndex === parsed.expressions.length - 1; const startInterpol = parsed.interpolationStarts[expressionIndex] - startOffset; let endInterpol; if (isLastIndex) { const lastPartLength = parsed.parts[expressionIndex + 1].length; endInterpol = attrLocation.endOffset - 1 - // " (closing quote) startOffset - // lastPartLength; // - lastPartLength: last part can be a normal string, we don't want to include that } else { endInterpol = parsed.interpolationEnds[expressionIndex] - startOffset; } const potentialRegionValue = stringTracker.substring( startInterpol, endInterpol ); const updatedStartOffset = startInterpol + startOffset; const updatedLocation: SourceCodeLocation = { ...attrLocation, startOffset: updatedStartOffset, endOffset: updatedStartOffset + potentialRegionValue.length, }; // Create default Access scope if (accessScopes.length === 0) { const nameLocation: ASTSourceCodeLocation = { start: updatedLocation.startOffset + 2, // + 2: ${ end: updatedLocation.endOffset - 1, // - 1: } }; const emptyAccessScope = new AccessScopeExpression( '', 0, nameLocation ); accessScopes.push(emptyAccessScope); } const viewRegion = AttributeInterpolationRegion.create({ attributeName: attr.name, attributeValue: attr.value, sourceCodeLocation: updatedLocation, tagName: startTag.tagName, accessScopes, regionValue: potentialRegionValue, }); return viewRegion; } ); // finalRegions; /* ?*/ return finalRegions; } catch (error) { // const _error = error as Error // logger.log(_error.message,{logLevel:'DEBUG'}) // logger.log(_error.stack,{logLevel:'DEBUG'}) return []; } } public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitAttributeInterpolation(this); } } export class AureliaHtmlRegion extends AbstractRegion { public languageService: AureliaHtmlLanguageService; public readonly type: ViewRegionType.Html; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new AureliaHtmlLanguageService(); } public static create() { const finalInfo = convertToRegionInfo({ sourceCodeLocation: { startLine: 0, startCol: 0, startOffset: 0, endLine: 0, endCol: 0, endOffset: 0, }, type: ViewRegionType.AttributeInterpolation, }); return new AureliaHtmlRegion(finalInfo); } public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitAureliaHtmlInterpolation(this); } } export class BindableAttributeRegion extends AbstractRegion { public languageService: BindableAttributeLanguageService; public readonly type: ViewRegionType.BindableAttribute; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new BindableAttributeLanguageService(); } public static create(info: Optional<ViewRegionInfoV2, 'type'>) { const finalInfo = convertToRegionInfo({ ...info, type: ViewRegionType.BindableAttribute, }); return new BindableAttributeRegion(finalInfo); } public static is(region: AbstractRegion): region is CustomElementRegion { return region.type === ViewRegionType.BindableAttribute; } public static parse5Start( startTag: SaxStream.StartTagToken, attr: parse5.Attribute ) { const attrLocation = startTag.sourceCodeLocation?.attrs[attr.name]; if (!attrLocation) return; const startOffset = attrLocation.startOffset; /** Eg. >click.delegate="<increaseCounter()" */ const onlyBindableName = getBindableNameFromAttritute(attr.name); const endOffset = startOffset + onlyBindableName.length; const updatedLocation = { ...attrLocation, startOffset, endOffset, endCol: attrLocation.startCol + onlyBindableName.length, }; const viewRegion = BindableAttributeRegion.create({ attributeName: attr.name, attributeValue: attr.value, sourceCodeLocation: updatedLocation, regionValue: onlyBindableName, tagName: startTag.tagName, }); return viewRegion; } public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitBindableAttribute(this); } } export class CustomElementRegion extends AbstractRegion { public languageService: CustomElementLanguageService; public readonly type: ViewRegionType.CustomElement; public startTagLocation: SourceCodeLocation; public data: CustomElementRegionData = []; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new CustomElementLanguageService(); } // region public static public static create(info: Optional<ViewRegionInfoV2, 'type'>) { const finalInfo = convertToRegionInfo({ ...info, type: ViewRegionType.CustomElement, }); return new CustomElementRegion(finalInfo); } public static createStart( info: RequiredBy< ViewRegionInfoV2, 'sourceCodeLocation' | 'startTagLocation' | 'tagName' > ) { info.subType = ViewRegionSubType.StartTag; return CustomElementRegion.create(info); } public static createEnd(info: Optional<ViewRegionInfoV2, 'type'>) { info.subType = ViewRegionSubType.EndTag; return CustomElementRegion.create(info); } public static is(region: AbstractRegion): region is CustomElementRegion { return region.type === ViewRegionType.CustomElement; } public static parse5Start(startTag: SaxStream.StartTagToken) { // startTag/*?*/ const tagName = startTag.tagName; const { sourceCodeLocation } = startTag; if (!sourceCodeLocation) return; const { startLine, startCol, startOffset } = sourceCodeLocation; const finalStartCol = startCol + 1; // + 1 for "<" of closing tag const finalStartOffset = startOffset + 1; // + 1 for < of closing tag const finalEndCol = finalStartCol + tagName.length; const finalEndOffset = finalStartOffset + tagName.length; const onlyOpeningTagLocation = { startCol: finalStartCol, startOffset: finalStartOffset, startLine, endLine: startLine, endCol: finalEndCol, endOffset: finalEndOffset, }; const viewRegion = CustomElementRegion.createStart({ tagName, sourceCodeLocation: onlyOpeningTagLocation, startTagLocation: { startCol: sourceCodeLocation.startCol, startLine: sourceCodeLocation.startLine, startOffset: sourceCodeLocation.startOffset, endCol: sourceCodeLocation.endCol, endLine: sourceCodeLocation.endLine, endOffset: sourceCodeLocation.endOffset, }, }); return viewRegion; } public static parse5End(endTag: SaxStream.EndTagToken) { const { sourceCodeLocation } = endTag; if (!sourceCodeLocation) return; const { startCol, startOffset, endOffset } = sourceCodeLocation; const finalStartCol = startCol + 2; // + 2 for "</" of closing tag const finalStartOffset = startOffset + 2; // + 2 for </ of closing tag const finalEndCol = finalStartCol + endTag.tagName.length; const finalEndOffset = endOffset - 1; // - 1 > of closing tag const updatedEndLocation = { ...sourceCodeLocation, startCol: finalStartCol, startOffset: finalStartOffset, endCol: finalEndCol, endOffset: finalEndOffset, }; const customElementViewRegion = CustomElementRegion.createEnd({ tagName: endTag.tagName, sourceCodeLocation: updatedEndLocation, }); return customElementViewRegion; } // endregion public static // region public public getBindableAttributes(): ViewRegionInfoV2[] { const bindableAttributeRegions = this.data?.filter( (subRegion) => subRegion.type === ViewRegionType.BindableAttribute ); if (bindableAttributeRegions === undefined) return []; return bindableAttributeRegions; } public addBindable( info: Optional<ViewRegionInfoV2, 'type' | 'tagName'> ): void { const finalInfo: ViewRegionInfoV2 = { ...info, type: ViewRegionType.BindableAttribute, tagName: this.tagName, }; const bindableAttribute = BindableAttributeRegion.create(finalInfo); this.data.push(bindableAttribute); } public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitCustomElement(this); } // endregion public } export class ImportRegion extends AbstractRegion { public languageService: ImportLanguageService; public readonly type: ViewRegionType.Import; public startTagLocation: SourceCodeLocation; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new ImportLanguageService(); } // region public static public static create(info: Optional<ViewRegionInfoV2, 'type'>) { const finalInfo = convertToRegionInfo({ ...info, type: ViewRegionType.Import, }); return new ImportRegion(finalInfo); } public static is(region: AbstractRegion): region is CustomElementRegion { return region.type === ViewRegionType.CustomElement; } public static parse5(startTag: SaxStream.StartTagToken) { if (!startTag.sourceCodeLocation) return; let importSource: string | undefined; startTag.attrs.forEach((attr) => { const isFrom = attr.name === AureliaView.IMPORT_FROM_ATTRIBUTE; if (isFrom) { importSource = attr.value; } }); const importRegion = this.create({ attributeName: AureliaView.IMPORT_FROM_ATTRIBUTE, attributeValue: importSource, tagName: startTag.tagName, sourceCodeLocation: startTag.sourceCodeLocation, type: ViewRegionType.Import, regionValue: importSource, // data: getRepeatForData(), }); return importRegion; } // endregion public static // region public public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitImport(this); } // endregion public } export class RepeatForRegion extends AbstractRegion { public languageService: RepeatForLanguageService; public readonly type: ViewRegionType.RepeatFor; public readonly data: RepeatForRegionData; public readonly accessScopes: AccessScopeExpression[]; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new RepeatForLanguageService(); } public static create(info: Optional<ViewRegionInfoV2, 'type' | 'tagName'>) { const finalInfo = convertToRegionInfo({ ...info, type: ViewRegionType.RepeatFor, }); return new RepeatForRegion(finalInfo); } public static parse5Start( startTag: SaxStream.StartTagToken, attr: parse5.Attribute ) { const attrLocation = startTag.sourceCodeLocation?.attrs[attr.name]; if (!attrLocation) return; /** Eg. >repeat.for="<rule of grammarRules" */ const startInterpolationLength = attr.name.length + // click.delegate 2; // =" /** Eg. click.delegate="increaseCounter()><" */ const endInterpolationLength = attrLocation.endOffset - 1; // - 1 the quote // __<label repeat.for="rule of grammarRules"> const startColAdjust = attrLocation.startCol + // __<label_ attr.name.length + // repeat.for 2 - // =" 1; // index starts from 0 const startOffset = attrLocation.startOffset + startInterpolationLength; const updatedLocation: parse5.Location = { ...attrLocation, startOffset: startOffset, startCol: startColAdjust, endOffset: endInterpolationLength, }; function getRepeatForData() { const [iterator, ofKeyword, iterable] = attr.value.split(' '); const iterableStartOffset = startOffset + iterator.length + // iterator 1 + // space ofKeyword.length + // of 1; // space const repeatForData: RepeatForRegionData = { iterator, iterableName: iterable, iterableStartOffset, iterableEndOffset: iterableStartOffset + iterable.length, }; return repeatForData; } const { expressions: accessScopes } = ParseExpressionUtil.getAllExpressionsOfKindV2( attr.value, [ExpressionKind.AccessScope, ExpressionKind.CallScope], { startOffset, expressionType: ExpressionType.IsIterator } ); const repeatForViewRegion = RepeatForRegion.create({ accessScopes, attributeName: attr.name, attributeValue: attr.value, sourceCodeLocation: updatedLocation, type: ViewRegionType.RepeatFor, data: getRepeatForData(), regionValue: attr.value, }); return repeatForViewRegion; } public static is(region: AbstractRegion): region is RepeatForRegion { return region.type === ViewRegionType.RepeatFor; } public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitRepeatFor(this); } } export class TextInterpolationRegion extends AbstractRegion { public languageService: TextInterpolationLanguageService; public readonly type: ViewRegionType.TextInterpolation; public readonly accessScopes: AccessScopeExpression[]; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new TextInterpolationLanguageService(); } public static create(info: Optional<ViewRegionInfoV2, 'type' | 'tagName'>) { const finalInfo = convertToRegionInfo({ ...info, type: ViewRegionType.TextInterpolation, }); return new TextInterpolationRegion(finalInfo); } public static is(region: AbstractRegion): region is CustomElementRegion { return region.type === ViewRegionType.TextInterpolation; } /** * Text nodes often begin with `\n`, which makes finding by line/col harder. * We thus, only modify offset. */ public static parse5Text( text: SaxStream.TextToken, /** Make up for difference between parse5 (not counting \n) and vscode (counting \n) */ documentHasCrlf: boolean ) { const textLocation = text.sourceCodeLocation; if (!textLocation) return; const startOffset = textLocation.startOffset; let { expressions: accessScopes, parts } = ParseExpressionUtil.getAllExpressionsOfKindV2( text.text, [ExpressionKind.AccessScope, ExpressionKind.CallScope], { expressionType: ExpressionType.Interpolation, startOffset } ); // crlf fix if (documentHasCrlf) { accessScopes.forEach((scope) => { const { start } = scope.nameLocation; const textUntilMatch = text.text.substring(0, start); // crlf = carriage return, line feed (windows specific) let numberOfCrlfs = 0; const crlfRegex = /\n/g; numberOfCrlfs = textUntilMatch.match(crlfRegex)?.length ?? 0; scope.nameLocation.start += numberOfCrlfs; scope.nameLocation.end += numberOfCrlfs; }); } if (text.sourceCodeLocation == null) return; const textRegion = TextInterpolationRegion.create({ regionValue: text.text, sourceCodeLocation: text.sourceCodeLocation, textValue: text.text, accessScopes, }); return textRegion; } public static createRegionsFromExpressionParser( text: SaxStream.TextToken, documentHasCrlf: boolean ): TextInterpolationRegion[] | undefined { const textLocation = text.sourceCodeLocation; if (!textLocation) return; const startOffset = textLocation.startOffset; // startOffset; /*?*/ try { // text.text; /* ? */ const parsed = ParseExpressionUtil.parseInterpolation( text.text, startOffset ); // parsed; /* ? */ // parsed.parts; /* ? */ // Used to find interpolation(s) inside string let stringTracker = text.text; // For each expression "group", create a region const finalRegions = parsed?.expressions.map( (expression, expressionIndex) => { const accessScopes: ViewRegionInfoV2['accessScopes'] = []; findAllExpressionRecursive( expression, [ExpressionKind.AccessScope, ExpressionKind.CallScope], accessScopes ); if (documentHasCrlf) { accessScopes.forEach((scope) => { const { start } = scope.nameLocation; const textUntilMatch = text.text.substring(0, start); // crlf = carriage return, line feed (windows specific) let numberOfCrlfs = 0; const crlfRegex = /\n/g; numberOfCrlfs = textUntilMatch.match(crlfRegex)?.length ?? 0; scope.nameLocation.start += numberOfCrlfs; scope.nameLocation.end += numberOfCrlfs; }); } const isLastIndex = expressionIndex === parsed.expressions.length - 1; const startInterpol = parsed.interpolationStarts[expressionIndex] - startOffset; let endInterpol; if (isLastIndex) { const lastPartLength = parsed.parts[expressionIndex + 1].length; endInterpol = textLocation.endOffset - startOffset - // lastPartLength; // - lastPartLength: last part can be a normal string, we don't want to include that } else { endInterpol = parsed.interpolationEnds[expressionIndex] - startOffset; } const potentialRegionValue = stringTracker.substring( startInterpol, endInterpol ); const updatedStartOffset = startInterpol + startOffset; const updatedLocation: SourceCodeLocation = { ...textLocation, startOffset: updatedStartOffset, endOffset: updatedStartOffset + potentialRegionValue.length, }; // Create default Access scope if (accessScopes.length === 0) { const nameLocation: ASTSourceCodeLocation = { start: updatedLocation.startOffset + 2, // + 2: ${ end: updatedLocation.endOffset - 1, // - 1: } }; const emptyAccessScope = new AccessScopeExpression( '', 0, nameLocation ); accessScopes.push(emptyAccessScope); } const textRegion = TextInterpolationRegion.create({ regionValue: potentialRegionValue, sourceCodeLocation: updatedLocation, textValue: text.text, accessScopes, }); return textRegion; } ); // finalRegions; /* ?*/ return finalRegions; } catch (error) { // const _error = error as Error // logger.log(_error.message,{logLevel:'DEBUG'}) // logger.log(_error.stack,{logLevel:'DEBUG'}) return []; } } public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitTextInterpolation(this); } } export class ValueConverterRegion extends AbstractRegion { public languageService: ValueConverterLanguageService; public data: ValueConverterRegionData; public readonly type: ViewRegionType.ValueConverter; constructor(info: ViewRegionInfoV2) { super(info); this.languageService = new ValueConverterLanguageService(); } public static create(info: Optional<ViewRegionInfoV2, 'type' | 'tagName'>) { const finalInfo = convertToRegionInfo({ ...info, type: ViewRegionType.ValueConverter, }); return new ValueConverterRegion(finalInfo); } public static is( region: AbstractRegion | undefined ): region is ValueConverterRegion { return region?.type === ViewRegionType.ValueConverter; } public static parse5Start( startTag: SaxStream.StartTagToken, attr: parse5.Attribute ) { const attrLocation = startTag.sourceCodeLocation?.attrs[attr.name]; if (!attrLocation) return []; // 6.1. Split up repeat.for='repo of repos | sort:column.value:direction.value | take:10' // Don't split || ("or") const [initiatorText, ...valueConverterRegionsSplit] = attr.value.split(/(?<!\|)\|(?!\|)/g); // 6.2. For each value converter const valueConverterRegions: ValueConverterRegion[] = []; valueConverterRegionsSplit.forEach((valueConverterViewText, index) => { // 6.3. Split into name and arguments const [valueConverterName, ...valueConverterArguments] = valueConverterViewText.split(':'); if (valueConverterRegionsSplit.length >= 2 && index >= 1) { const dm = new DiagnosticMessages( 'Chained value converters not supported yet.' ); dm.log(); dm.additionalLog('No infos for', valueConverterViewText); return; } const startValueConverterLength = attr.name.length /** repeat.for */ + 2 /** =' */ + initiatorText.length /** repo of repos_ */ + 1; /** | */ const startColAdjust = attrLocation.startCol /** indentation and to length attribute */ + startValueConverterLength; const endValueConverterLength = startValueConverterLength + valueConverterViewText.length; const endColAdjust = startColAdjust + valueConverterViewText.length; // 6.4. Save the location const updatedLocation: parse5.Location = { ...attrLocation, startOffset: attrLocation.startOffset + startValueConverterLength - 1, // [!] Don't include '|', because when we type |, we already want to get completions startCol: startColAdjust, endOffset: attrLocation.startOffset + endValueConverterLength, endCol: endColAdjust, }; // 6.5. Create region with useful info const valueConverterRegion = ValueConverterRegion.create({ attributeName: attr.name, sourceCodeLocation: updatedLocation, type: ViewRegionType.ValueConverter, regionValue: attr.value, data: { initiatorText, valueConverterName: valueConverterName.trim(), valueConverterText: valueConverterArguments.join(':'), }, }); valueConverterRegions.push(valueConverterRegion); }); return valueConverterRegions; } public accept<T>(visitor: IViewRegionsVisitor<T>): T { return visitor.visitValueConverter(this); } } function convertToRegionInfo(info: Partial<ViewRegionInfoV2>) { // Convert to zero-based (col and line from parse5 is one-based) if (info.sourceCodeLocation) { const copySourceLocation = { ...info.sourceCodeLocation }; copySourceLocation.startCol -= 1; copySourceLocation.startLine -= 1; copySourceLocation.endCol -= 1; copySourceLocation.endLine -= 1; info.sourceCodeLocation = copySourceLocation; } if (info.startTagLocation) { const copyStartTagLocation = { ...info.startTagLocation }; copyStartTagLocation.startCol -= 1; copyStartTagLocation.startLine -= 1; copyStartTagLocation.endCol -= 1; copyStartTagLocation.endLine -= 1; info.startTagLocation = copyStartTagLocation; } return info as ViewRegionInfoV2; }
the_stack
import FDBDatabase from "./FDBDatabase"; import FDBOpenDBRequest from "./FDBOpenDBRequest"; import FDBVersionChangeEvent from "./FDBVersionChangeEvent"; import cmp from "./lib/cmp"; import Database from "./lib/Database"; import enforceRange from "./lib/enforceRange"; import { AbortError, VersionError } from "./lib/errors"; import FakeEvent from "./lib/FakeEvent"; import { queueTask } from "./lib/scheduling"; const waitForOthersClosedDelete = ( databases: Map<string, Database>, name: string, openDatabases: FDBDatabase[], cb: (err: Error | null) => void, ) => { const anyOpen = openDatabases.some(openDatabase2 => { return !openDatabase2._closed && !openDatabase2._closePending; }); if (anyOpen) { queueTask(() => waitForOthersClosedDelete(databases, name, openDatabases, cb), ); return; } databases.delete(name); cb(null); }; // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-deleting-a-database const deleteDatabase = ( databases: Map<string, Database>, name: string, request: FDBOpenDBRequest, cb: (err: Error | null) => void, ) => { try { const db = databases.get(name); if (db === undefined) { cb(null); return; } db.deletePending = true; const openDatabases = db.connections.filter(connection => { return !connection._closed && !connection._closePending; }); for (const openDatabase2 of openDatabases) { if (!openDatabase2._closePending) { const event = new FDBVersionChangeEvent("versionchange", { newVersion: null, oldVersion: db.version, }); openDatabase2.dispatchEvent(event); } } const anyOpen = openDatabases.some(openDatabase3 => { return !openDatabase3._closed && !openDatabase3._closePending; }); if (request && anyOpen) { const event = new FDBVersionChangeEvent("blocked", { newVersion: null, oldVersion: db.version, }); request.dispatchEvent(event); } waitForOthersClosedDelete(databases, name, openDatabases, cb); } catch (err) { cb(err); } }; // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-running-a-versionchange-transaction const runVersionchangeTransaction = ( connection: FDBDatabase, version: number, request: FDBOpenDBRequest, cb: (err: Error | null) => void, ) => { connection._runningVersionchangeTransaction = true; const oldVersion = connection.version; const openDatabases = connection._rawDatabase.connections.filter( otherDatabase => { return connection !== otherDatabase; }, ); for (const openDatabase2 of openDatabases) { if (!openDatabase2._closed && !openDatabase2._closePending) { const event = new FDBVersionChangeEvent("versionchange", { newVersion: version, oldVersion, }); openDatabase2.dispatchEvent(event); } } const anyOpen = openDatabases.some(openDatabase3 => { return !openDatabase3._closed && !openDatabase3._closePending; }); if (anyOpen) { const event = new FDBVersionChangeEvent("blocked", { newVersion: version, oldVersion, }); request.dispatchEvent(event); } const waitForOthersClosed = () => { const anyOpen2 = openDatabases.some(openDatabase2 => { return !openDatabase2._closed && !openDatabase2._closePending; }); if (anyOpen2) { queueTask(waitForOthersClosed); return; } // Set the version of database to version. This change is considered part of the transaction, and so if the // transaction is aborted, this change is reverted. connection._rawDatabase.version = version; connection.version = version; // Get rid of this setImmediate? const transaction = connection.transaction( connection.objectStoreNames, "versionchange", ); request.result = connection; request.readyState = "done"; request.transaction = transaction; transaction._rollbackLog.push(() => { connection._rawDatabase.version = oldVersion; connection.version = oldVersion; }); const event = new FDBVersionChangeEvent("upgradeneeded", { newVersion: version, oldVersion, }); request.dispatchEvent(event); transaction.addEventListener("error", () => { connection._runningVersionchangeTransaction = false; // throw arguments[0].target.error; // console.log("error in versionchange transaction - not sure if anything needs to be done here", e.target.error.name); }); transaction.addEventListener("abort", () => { connection._runningVersionchangeTransaction = false; request.transaction = null; queueTask(() => { cb(new AbortError()); }); }); transaction.addEventListener("complete", () => { connection._runningVersionchangeTransaction = false; request.transaction = null; // Let other complete event handlers run before continuing queueTask(() => { if (connection._closePending) { cb(new AbortError()); } else { cb(null); } }); }); }; waitForOthersClosed(); }; // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#dfn-steps-for-opening-a-database const openDatabase = ( databases: Map<string, Database>, name: string, version: number | undefined, request: FDBOpenDBRequest, cb: (err: Error | null, connection?: FDBDatabase) => void, ) => { let db = databases.get(name); if (db === undefined) { db = new Database(name, 0); databases.set(name, db); } if (version === undefined) { version = db.version !== 0 ? db.version : 1; } if (db.version > version) { return cb(new VersionError()); } const connection = new FDBDatabase(db); if (db.version < version) { runVersionchangeTransaction(connection, version, request, err => { if (err) { // DO THIS HERE: ensure that connection is closed by running the steps for closing a database connection before these // steps are aborted. return cb(err); } cb(null, connection); }); } else { cb(null, connection); } }; class FDBFactory { public cmp = cmp; private _databases: Map<string, Database> = new Map(); // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-deleteDatabase-IDBOpenDBRequest-DOMString-name public deleteDatabase(name: string) { const request = new FDBOpenDBRequest(); request.source = null; queueTask(() => { const db = this._databases.get(name); const oldVersion = db !== undefined ? db.version : 0; deleteDatabase(this._databases, name, request, err => { if (err) { request.error = new Error(); request.error.name = err.name; request.readyState = "done"; const event = new FakeEvent("error", { bubbles: true, cancelable: true, }); event.eventPath = []; request.dispatchEvent(event); return; } request.result = undefined; request.readyState = "done"; const event2 = new FDBVersionChangeEvent("success", { newVersion: null, oldVersion, }); request.dispatchEvent(event2); }); }); return request; } // tslint:disable-next-line max-line-length // http://www.w3.org/TR/2015/REC-IndexedDB-20150108/#widl-IDBFactory-open-IDBOpenDBRequest-DOMString-name-unsigned-long-long-version public open(name: string, version?: number) { if (arguments.length > 1 && version !== undefined) { // Based on spec, not sure why "MAX_SAFE_INTEGER" instead of "unsigned long long", but it's needed to pass // tests version = enforceRange(version, "MAX_SAFE_INTEGER"); } if (version === 0) { throw new TypeError(); } const request = new FDBOpenDBRequest(); request.source = null; queueTask(() => { openDatabase( this._databases, name, version, request, (err, connection) => { if (err) { request.result = undefined; request.readyState = "done"; request.error = new Error(); request.error.name = err.name; const event = new FakeEvent("error", { bubbles: true, cancelable: true, }); event.eventPath = []; request.dispatchEvent(event); return; } request.result = connection; request.readyState = "done"; const event2 = new FakeEvent("success"); event2.eventPath = []; request.dispatchEvent(event2); }, ); }); return request; } // https://w3c.github.io/IndexedDB/#dom-idbfactory-databases public databases() { return new Promise(resolve => { const result = []; for (const [name, database] of this._databases) { result.push({ name, version: database.version, }); } resolve(result); }); } public toString() { return "[object IDBFactory]"; } } export default FDBFactory;
the_stack
import fs from 'fs'; import log from 'loglevel'; import micromatch from 'micromatch'; import path from 'path'; import {ROOT_FILE_ENTRY} from '@constants/constants'; import {AppConfig} from '@models/appconfig'; import {AppState, FileMapType, HelmChartMapType, HelmValuesMapType, ResourceMapType} from '@models/appstate'; import {FileEntry} from '@models/fileentry'; import {HelmChart, HelmValuesFile} from '@models/helm'; import {K8sResource} from '@models/k8sresource'; import {isHelmChartFolder, processHelmChartFolder} from '@redux/services/helm'; import {updateReferringRefsOnDelete} from '@redux/services/resourceRefs'; import { clearResourceSelections, highlightChildrenResources, updateSelectionAndHighlights, } from '@redux/services/selection'; import {getFileStats, getFileTimestamp} from '@utils/files'; import {deleteResource, extractK8sResources, reprocessResources} from './resource'; type PathRemovalSideEffect = { removedResources: K8sResource[]; }; /** * Creates a FileEntry for the specified relative path */ export function createFileEntry(fileEntryPath: string) { const fileEntry: FileEntry = { name: fileEntryPath.substr(fileEntryPath.lastIndexOf(path.sep) + 1), filePath: fileEntryPath, isExcluded: false, isSupported: false, }; return fileEntry; } /** * Checks if the specified filename should be excluded per the global exclusion config */ export function fileIsExcluded(appConfig: AppConfig, fileEntry: FileEntry) { const scanExcludes = appConfig.projectConfig?.scanExcludes || appConfig.scanExcludes; return scanExcludes.some(e => micromatch.isMatch(fileEntry.filePath, e)); } /** * Returns the root folder for the specified fileMap */ export function getRootFolder(fileMap: FileMapType) { return fileMap && fileMap[ROOT_FILE_ENTRY] ? fileMap[ROOT_FILE_ENTRY].filePath : undefined; } /** * Recursively reads the provided folder in line with the provided appConfig and populates the * provided maps with found files and resources. * * Returns the list of filenames (not paths) found in the specified folder */ export function readFiles( folder: string, appConfig: AppConfig, resourceMap: ResourceMapType, fileMap: FileMapType, helmChartMap: HelmChartMapType, helmValuesMap: HelmValuesMapType, depth: number = 1, isSupportedResource: (resource: K8sResource) => boolean = () => true ) { const files = fs.readdirSync(folder); const result: string[] = []; // if there is no root entry assume this is the root folder (questionable..) if (!fileMap[ROOT_FILE_ENTRY]) { fileMap[ROOT_FILE_ENTRY] = createFileEntry(folder); } const rootFolder = fileMap[ROOT_FILE_ENTRY].filePath; // is this a helm chart folder? if (isHelmChartFolder(files)) { processHelmChartFolder( folder, rootFolder, files, appConfig, resourceMap, fileMap, helmChartMap, helmValuesMap, result, depth ); } else { files.forEach(file => { const filePath = path.join(folder, file); const fileEntryPath = filePath.substr(rootFolder.length); const fileEntry = createFileEntry(fileEntryPath); fileEntry.timestamp = getFileTimestamp(filePath); if (fileIsExcluded(appConfig, fileEntry)) { fileEntry.isExcluded = true; } else if (getFileStats(filePath)?.isDirectory()) { const folderReadsMaxDepth = appConfig.projectConfig?.folderReadsMaxDepth || appConfig.folderReadsMaxDepth; if (depth === folderReadsMaxDepth) { log.warn(`[readFiles]: Ignored ${filePath} because max depth was reached.`); } else { fileEntry.children = readFiles( filePath, appConfig, resourceMap, fileMap, helmChartMap, helmValuesMap, depth + 1 ); } } else if (appConfig.fileIncludes.some(e => micromatch.isMatch(fileEntry.name, e))) { try { extractK8sResourcesFromFile(filePath, fileMap).forEach(resource => { if (!isSupportedResource(resource)) { fileEntry.isSupported = false; return; } resourceMap[resource.id] = resource; }); } catch (e) { log.warn(`Failed to parse yaml in file ${fileEntry.name}; ${e}`); } fileEntry.isSupported = true; } fileMap[fileEntry.filePath] = fileEntry; result.push(fileEntry.name); }); } return result; } /** * Returns all resources associated with the specified path */ export function getResourcesForPath(filePath: string, resourceMap: ResourceMapType) { return Object.values(resourceMap).filter(r => r.filePath === filePath); } /** * Returns the absolute path to the folder containing the file containing the * specified resource */ export function getAbsoluteResourceFolder(resource: K8sResource, fileMap: FileMapType) { return path.join( fileMap[ROOT_FILE_ENTRY].filePath, resource.filePath.substr(0, resource.filePath.lastIndexOf(path.sep)) ); } /** * Returns the relative path to the folder containing the file containing the * specified resource */ export function getResourceFolder(resource: K8sResource) { return resource.filePath.substr(0, resource.filePath.lastIndexOf('/')); } /** * Returns the absolute path to the file that containing specified resource */ export function getAbsoluteResourcePath(resource: K8sResource, fileMap: FileMapType) { return path.join(fileMap[ROOT_FILE_ENTRY].filePath, resource.filePath); } /** * Returns the absolute path to the specified FileEntry */ export function getAbsoluteFileEntryPath(fileEntry: FileEntry, fileMap: FileMapType) { return path.join(fileMap[ROOT_FILE_ENTRY].filePath, fileEntry.filePath); } /** * Returns the absolute path to the specified HelmChart */ export function getAbsoluteHelmChartPath(helmChart: HelmChart, fileMap: FileMapType) { return path.join(fileMap[ROOT_FILE_ENTRY].filePath, helmChart.filePath); } /** * Returns the absolute path to the specified Helm Values File */ export function getAbsoluteValuesFilePath(helmValuesFile: HelmValuesFile, fileMap: FileMapType) { return path.join(fileMap[ROOT_FILE_ENTRY].filePath, helmValuesFile.filePath); } /** * Extracts all resources from the file at the specified path */ export function extractK8sResourcesFromFile(filePath: string, fileMap: FileMapType): K8sResource[] { const fileContent = fs.readFileSync(filePath, 'utf8'); const rootEntry = fileMap[ROOT_FILE_ENTRY]; return extractK8sResources(fileContent, rootEntry ? filePath.substr(rootEntry.filePath.length) : filePath); } /** * Returns a list of all FileEntries "leading up" to (and including) the specified path */ export function getAllFileEntriesForPath(filePath: string, fileMap: FileMapType) { let parent = fileMap[ROOT_FILE_ENTRY]; const result: FileEntry[] = []; filePath.split(path.sep).forEach(pathSegment => { if (parent.children?.includes(pathSegment)) { const child = fileMap[getChildFilePath(pathSegment, parent, fileMap)]; if (child) { result.push(child); parent = child; } } }); return result; } /** * Gets the relative path of a child to a specified parent */ export function getChildFilePath(child: string, parentEntry: FileEntry, fileMap: FileMapType) { return parentEntry === fileMap[ROOT_FILE_ENTRY] ? path.sep + child : path.join(parentEntry.filePath, child); } /** * Returns the fileEntry for the specified absolute path */ export function getFileEntryForAbsolutePath(filePath: string, fileMap: FileMapType) { if (!fileMap[ROOT_FILE_ENTRY]) { return undefined; } const rootFolder = fileMap[ROOT_FILE_ENTRY].filePath; if (filePath === rootFolder) { return fileMap[ROOT_FILE_ENTRY]; } return filePath.startsWith(rootFolder) ? fileMap[filePath.substr(rootFolder.length)] : undefined; } /** * Updates the fileEntry from the specified path - and its associated resources */ export function reloadFile(absolutePath: string, fileEntry: FileEntry, state: AppState) { let absolutePathTimestamp = getFileTimestamp(absolutePath); if (!fileEntry.timestamp || (absolutePathTimestamp && absolutePathTimestamp > fileEntry.timestamp)) { fileEntry.timestamp = absolutePathTimestamp; let wasFileSelected = state.selectedPath === fileEntry.filePath; const resourcesInFile = getResourcesForPath(fileEntry.filePath, state.resourceMap); let wasAnyResourceSelected = false; resourcesInFile.forEach(resource => { if (state.selectedResourceId === resource.id) { updateSelectionAndHighlights(state, resource); wasAnyResourceSelected = true; } deleteResource(resource, state.resourceMap); }); if (state.selectedPath === fileEntry.filePath) { state.selectedPath = undefined; state.selectedResourceId = undefined; clearResourceSelections(state.resourceMap); } const resourcesFromFile = extractK8sResourcesFromFile(absolutePath, state.fileMap); resourcesFromFile.forEach(resource => { state.resourceMap[resource.id] = resource; }); reprocessResources( resourcesFromFile.map(r => r.id), state.resourceMap, state.fileMap, state.resourceRefsProcessingOptions ); if (wasAnyResourceSelected) { if (resourcesInFile.length === 1 && resourcesFromFile.length === 1) { updateSelectionAndHighlights(state, resourcesFromFile[0]); } else { state.selectedPath = undefined; state.selectedResourceId = undefined; clearResourceSelections(state.resourceMap); } } if (wasFileSelected) { selectFilePath(fileEntry.filePath, state); state.shouldEditorReloadSelectedPath = true; } } else { log.info(`ignoring changed file ${absolutePath} because of timestamp`); } } /** * Adds the file at the specified path with the specified parent */ function addFile(absolutePath: string, state: AppState, appConfig: AppConfig) { log.info(`adding file ${absolutePath}`); let rootFolder = state.fileMap[ROOT_FILE_ENTRY].filePath; const fileEntry = createFileEntry(absolutePath.substr(rootFolder.length)); if (!appConfig.fileIncludes.some(e => micromatch.isMatch(fileEntry.name, e))) { return fileEntry; } fileEntry.isSupported = true; const resourcesFromFile = extractK8sResourcesFromFile(absolutePath, state.fileMap); resourcesFromFile.forEach(resource => { state.resourceMap[resource.id] = resource; }); reprocessResources( resourcesFromFile.map(r => r.id), state.resourceMap, state.fileMap, state.resourceRefsProcessingOptions ); return fileEntry; } /** * Adds the folder at the specified path with the specified parent */ function addFolder(absolutePath: string, state: AppState, appConfig: AppConfig) { log.info(`adding folder ${absolutePath}`); const rootFolder = state.fileMap[ROOT_FILE_ENTRY].filePath; if (absolutePath.startsWith(rootFolder)) { const folderEntry = createFileEntry(absolutePath.substr(rootFolder.length)); folderEntry.children = readFiles( absolutePath, appConfig, state.resourceMap, state.fileMap, state.helmChartMap, state.helmValuesMap ); return folderEntry; } log.error(`added folder ${absolutePath} is not under root ${rootFolder} - ignoring...`); } /** * Adds the file/folder at specified path - and its contained resources */ export function addPath(absolutePath: string, state: AppState, appConfig: AppConfig) { const parentPath = absolutePath.substr(0, absolutePath.lastIndexOf(path.sep)); const parentEntry = getFileEntryForAbsolutePath(parentPath, state.fileMap); if (parentEntry) { let isDirectory: boolean; try { isDirectory = fs.statSync(absolutePath).isDirectory(); } catch (err) { if (err instanceof Error) { log.warn(`[addPath]: ${err.message}`); } return undefined; } const fileEntry = isDirectory ? addFolder(absolutePath, state, appConfig) : addFile(absolutePath, state, appConfig); if (fileEntry) { state.fileMap[fileEntry.filePath] = fileEntry; parentEntry.children = parentEntry.children || []; parentEntry.children.push(fileEntry.name); parentEntry.children.sort(); } return fileEntry; } log.warn(`Failed to find folder entry for ${absolutePath}, ignoring..`); return undefined; } /** * Removes the specified fileEntry and its resources from the provided state */ export function removeFile(fileEntry: FileEntry, state: AppState, removalSideEffect?: PathRemovalSideEffect) { log.info(`removing file ${fileEntry.filePath}`); getResourcesForPath(fileEntry.filePath, state.resourceMap).forEach(resource => { if (removalSideEffect) { removalSideEffect.removedResources.push(resource); } deleteResource(resource, state.resourceMap); }); } /** * Removes the specified fileEntry and its resources from the provided state */ function removeFolder(fileEntry: FileEntry, state: AppState, removalSideEffect?: PathRemovalSideEffect) { log.info(`removing folder ${fileEntry.filePath}`); fileEntry.children?.forEach(child => { const childEntry = state.fileMap[path.join(fileEntry.filePath, child)]; if (childEntry) { if (childEntry.children) { removeFolder(childEntry, state, removalSideEffect); } else { removeFile(childEntry, state, removalSideEffect); } } }); } /** * Removes the FileEntry at the specified path - and its associated resources */ export function removePath(absolutePath: string, state: AppState, fileEntry: FileEntry) { delete state.fileMap[fileEntry.filePath]; const removalSideEffect: PathRemovalSideEffect = { removedResources: [], }; if (fileEntry.children) { removeFolder(fileEntry, state, removalSideEffect); } else { removeFile(fileEntry, state, removalSideEffect); } if (state.selectedPath && !state.fileMap[state.selectedPath]) { state.selectedPath = undefined; clearResourceSelections(state.resourceMap); } else if (state.selectedResourceId && !state.resourceMap[state.selectedResourceId]) { state.selectedResourceId = undefined; clearResourceSelections(state.resourceMap); } // remove from parent const parentPath = absolutePath.substr(0, absolutePath.lastIndexOf(path.sep)); const parentEntry = getFileEntryForAbsolutePath(parentPath, state.fileMap); if (parentEntry && parentEntry.children) { const ix = parentEntry.children.indexOf(fileEntry.name); if (ix >= 0) { parentEntry.children.splice(ix, 1); } } // clear refs removalSideEffect.removedResources.forEach(r => updateReferringRefsOnDelete(r, state.resourceMap)); } /** * Selects the specified filePath - used by several reducers */ export function selectFilePath(filePath: string, state: AppState) { const entries = getAllFileEntriesForPath(filePath, state.fileMap); clearResourceSelections(state.resourceMap); if (entries.length > 0) { const parent = entries[entries.length - 1]; getResourcesForPath(parent.filePath, state.resourceMap).forEach(r => { r.isHighlighted = true; }); if (parent.children) { highlightChildrenResources(parent, state.resourceMap, state.fileMap); } Object.values(state.helmValuesMap).forEach(valuesFile => { valuesFile.isSelected = valuesFile.filePath === filePath; }); } state.selectedResourceId = undefined; state.selectedPath = filePath; }
the_stack
import { Transform } from 'stream'; declare module 'cloudinary' { /****************************** Constants *************************************/ /****************************** Transformations *******************************/ type CropMode = string | "scale" | "fit" | "limit" | "mfit" | "fill" | "lfill" | "pad" | "lpad" | "mpad" | "crop" | "thumb" | "imagga_crop" | "imagga_scale"; type Gravity = string | "north_west" | "north" | "north_east" | "west" | "center" | "east" | "south_west" | "south" | "south_east" | "xy_center" | "face" | "face:center" | "face:auto" | "faces" | "faces:center" | "faces:auto" | "body" | "body:face" | "adv_face" | "adv_faces" | "adv_eyes" | "custom" | "custom:face" | "custom:faces" | "custom:adv_face" | "custom:adv_faces" | "auto" | "auto:adv_face" | "auto:adv_faces" | "auto:adv_eyes" | "auto:body" | "auto:face" | "auto:faces" | "auto:custom_no_override" | "auto:none" | "liquid" | "ocr_text"; type Angle = number | string | Array<number | string> | "auto_right" | "auto_left" | "ignore" | "vflip" | "hflip"; type ImageEffect = string | "hue" | "red" | "green" | "blue" | "negate" | "brightness" | "auto_brightness" | "brightness_hsb" | "sepia" | "grayscale" | "blackwhite" | "saturation" | "colorize" | "replace_color" | "simulate_colorblind" | "assist_colorblind" | "recolor" | "tint" | "contrast" | "auto_contrast" | "auto_color" | "vibrance" | "noise" | "ordered_dither" | "pixelate_faces" | "pixelate_region" | "pixelate" | "unsharp_mask" | "sharpen" | "blur_faces" | "blur_region" | "blur" | "tilt_shift" | "gradient_fade" | "vignette" | "anti_removal" | "overlay" | "mask" | "multiply" | "displace" | "shear" | "distort" | "trim" | "make_transparent" | "shadow" | "viesus_correct" | "fill_light" | "gamma" | "improve"; type VideoEffect = string | "accelerate" | "reverse" | "boomerang" | "loop" | "make_transparent" | "transition"; type AudioCodec = string | "none" | "aac" | "vorbis" | "mp3"; type AudioFrequency = string | number | 8000 | 11025 | 16000 | 22050 | 32000 | 37800 | 44056 | 44100 | 47250 | 48000 | 88200 | 96000 | 176400 | 192000; /****************************** Flags *************************************/ type ImageFlags = string | Array<string> | "any_format" | "attachment" | "apng" | "awebp" | "clip" | "clip_evenodd" | "cutter" | "force_strip" | "getinfo" | "ignore_aspect_ratio" | "immutable_cache" | "keep_attribution" | "keep_iptc" | "layer_apply" | "lossy" | "preserve_transparency" | "png8" | "png32" | "progressive" | "rasterize" | "region_relative" | "relative" | "replace_image" | "sanitize" | "strip_profile" | "text_no_trim" | "no_overflow" | "text_disallow_overflow" | "tiff8_lzw" | "tiled"; type VideoFlags = string | Array<string> | "animated" | "awebp" | "attachment" | "streaming_attachment" | "hlsv3" | "keep_dar" | "splice" | "layer_apply" | "no_stream" | "mono" | "relative" | "truncate_ts" | "waveform"; type ColorSpace = string | "srgb" | "no_cmyk" | "keep_cmyk"; type DeliveryType = string | "upload" | "private" | "authenticated" | "fetch" | "multi" | "text" | "asset" | "list" | "facebook" | "twitter" | "twitter_name" | "instagram" | "gravatar" | "youtube" | "hulu" | "vimeo" | "animoto" | "worldstarhiphop" | "dailymotion"; /****************************** URL *************************************/ type ResourceType = string | "image" | "raw" | "video"; type ImageFormat = string | "gif" | "png" | "jpg" | "bmp" | "ico" | "pdf" | "tiff" | "eps" | "jpc" | "jp2" | "psd" | "webp" | "zip" | "svg" | "webm" | "wdp" | "hpx" | "djvu" | "ai" | "flif" | "bpg" | "miff" | "tga" | "heic" type VideoFormat = string | "auto" | "flv" | "m3u8" | "ts" | "mov" | "mkv" | "mp4" | "mpd" | "ogv" | "webm" export interface CommonTransformationOptions { transformation?: TransformationOptions; raw_transformation?: string; crop?: CropMode; width?: number | string; height?: number | string; size?: string; aspect_ratio?: number | string; gravity?: Gravity; x?: number | string; y?: number | string; zoom?: number | string; effect?: string | Array<number | string>; background?: string; angle?: Angle; radius?: number | string; overlay?: string | object; custom_function?: string | { function_type: string | "wasm" | "remote", source: string } variables?: Array<string | object>; if?: string; else?: string; end_if?: string; dpr?: number | string; quality?: number | string; delay?: number | string; [futureKey: string]: any; } export interface ImageTransformationOptions extends CommonTransformationOptions { underlay?: string | Object; color?: string; color_space?: ColorSpace; opacity?: number | string; border?: string; default_image?: string; density?: number | string; format?: ImageFormat; fetch_format?: ImageFormat; effect?: string | Array<number | string> | ImageEffect; page?: number | string; flags?: ImageFlags | string; [futureKey: string]: any; } interface VideoTransformationOptions extends CommonTransformationOptions { audio_codec?: AudioCodec; audio_frequency?: AudioFrequency; video_codec?: string | Object; bit_rate?: number | string; fps?: string | Array<number | string>; keyframe_interval?: string; offset?: string, start_offset?: number | string; end_offset?: number | string; duration?: number | string; streaming_profile?: StreamingProfiles video_sampling?: number | string; format?: VideoFormat; fetch_format?: VideoFormat; effect?: string | Array<number | string> | VideoEffect; flags?: VideoFlags; [futureKey: string]: any; } interface TextStyleOptions { text_style?: string; font_family?: string; font_size?: number; font_color?: string; font_weight?: string; font_style?: string; background?: string; opacity?: number; text_decoration?: string } interface ConfigOptions { cloud_name?: string; api_key?: string; api_secret?: string; private_cdn?: boolean; secure_distribution?: string; force_version?: boolean; ssl_detected?: boolean; secure?: boolean; cdn_subdomain?: boolean; secure_cdn_subdomain?: boolean; cname?: string; shorten?: boolean; sign_url?: boolean; long_url_signature?: boolean; use_root_path?: boolean; auth_token?: object; account_id?: string; provisioning_api_key?: string; provisioning_api_secret?: string; oauth_token?: string; [futureKey: string]: any; } export interface ResourceOptions { type?: string; resource_type?: string; } export interface UrlOptions extends ResourceOptions { version?: string; format?: string; url_suffix?: string; [futureKey: string]: any; } export interface ImageTagOptions { html_height?: string; html_width?: string; srcset?: object; attributes?: object; client_hints?: boolean; responsive?: boolean; hidpi?: boolean; responsive_placeholder?: boolean; [futureKey: string]: any; } export interface VideoTagOptions { source_types?: string | string[]; source_transformation?: TransformationOptions; fallback_content?: string; poster?: string | object; controls?: boolean; preload?: string; [futureKey: string]: any; } /****************************** Admin API Options *************************************/ export interface AdminApiOptions { agent?: object; content_type?: string; oauth_token?: string; [futureKey: string]: any; } export interface ArchiveApiOptions { allow_missing?: boolean; async?: boolean; expires_at?: number; flatten_folders?: boolean; flatten_transformations?: boolean; keep_derived?: boolean; mode?: string; notification_url?: string; prefixes?: string; public_ids?: string[] | string; fully_qualified_public_ids?: string[] | string; skip_transformation_name?: boolean; tags?: string | string[]; target_format?: TargetArchiveFormat; target_public_id?: string; target_tags?: string[]; timestamp?: number; transformations?: TransformationOptions; type?: DeliveryType use_original_filename?: boolean; [futureKey: string]: any; } export interface UpdateApiOptions extends ResourceOptions { access_control?: string[]; auto_tagging?: number; background_removal?: string; categorization?: string; context?: boolean | string; custom_coordinates?: string; detection?: string; face_coordinates?: string; headers?: string; notification_url?: string; ocr?: string; raw_convert?: string; similarity_search?: string; tags?: string | string[]; moderation_status?: string; unsafe_update?: object; allowed_for_strict?: boolean; [futureKey: string]: any; } export interface PublishApiOptions extends ResourceOptions { invalidate?: boolean; overwrite?: boolean; [futureKey: string]: any; } export interface ResourceApiOptions extends ResourceOptions { transformation?: TransformationOptions; transformations?: TransformationOptions; keep_original?: boolean; next_cursor?: boolean | string; public_ids?: string[]; prefix?: string; all?: boolean; max_results?: number; tags?: boolean; tag?: string; context?: boolean; direction?: number | string; moderations?: boolean; start_at?: string; exif?: boolean; colors?: boolean; derived_next_cursor?: string; faces?: boolean; image_metadata?: boolean; pages?: boolean; coordinates?: boolean; phash?: boolean; cinemagraph_analysis?: boolean; accessibility_analysis?: boolean; [futureKey: string]: any; } export interface UploadApiOptions { access_mode?: AccessMode; allowed_formats?: Array<VideoFormat> | Array<ImageFormat>; async?: boolean; backup?: boolean; callback?: string; colors?: boolean; discard_original_filename?: boolean; eager?: TransformationOptions; eager_async?: boolean; eager_notification_url?: string; eval?: string; exif?: boolean; faces?: boolean; folder?: string; format?: VideoFormat | ImageFormat; image_metadata?: boolean; invalidate?: boolean; moderation?: ModerationKind; notification_url?: string; overwrite?: boolean; phash?: boolean; proxy?: string; public_id?: string; quality_analysis?: boolean; responsive_breakpoints?: object; return_delete_token?: boolean timestamp?: number; transformation?: TransformationOptions; type?: DeliveryType; unique_filename?: boolean; upload_preset?: string; use_filename?: boolean; chunk_size?: number; disable_promises?: boolean; oauth_token?: string; [futureKey: string]: any; } export interface ProvisioningApiOptions { account_id?: string; provisioning_api_key?: string; provisioning_api_secret?: string; agent?: object; content_type?: string; [futureKey: string]: any; } export interface AuthTokenApiOptions { key: string; acl: string; ip?: string; start_time?: number; duration?: number; expiration?: number; url?: string; } type TransformationOptions = string | string[] | VideoTransformationOptions | ImageTransformationOptions | Object | Array<ImageTransformationOptions> | Array<VideoTransformationOptions>; type ImageTransformationAndTagsOptions = ImageTransformationOptions | ImageTagOptions; type VideoTransformationAndTagsOptions = VideoTransformationOptions | VideoTagOptions; type ImageAndVideoFormatOptions = ImageFormat | VideoFormat; type ConfigAndUrlOptions = ConfigOptions | UrlOptions; type AdminAndPublishOptions = AdminApiOptions | PublishApiOptions; type AdminAndResourceOptions = AdminApiOptions | ResourceApiOptions; type AdminAndUpdateApiOptions = AdminApiOptions | UpdateApiOptions; /****************************** API *************************************/ type Status = string | "pending" | "approved" | "rejected"; type StreamingProfiles = string | "4k" | "full_hd" | "hd" | "sd" | "full_hd_wifi" | "full_hd_lean" | "hd_lean"; type ModerationKind = string | "manual" | "webpurify" | "aws_rek" | "metascan"; type AccessMode = string | "public" | "authenticated"; type TargetArchiveFormat = string | "zip" | "tgz"; // err is kept for backwards compatibility, it currently will always be undefined type ResponseCallback = (err?: any, callResult?: any) => any; type UploadResponseCallback = (err?: UploadApiErrorResponse, callResult?: UploadApiResponse) => void; export interface UploadApiResponse { public_id: string; version: number; signature: string; width: number; height: number; format: string; resource_type: string; created_at: string; tags: Array<string>; pages: number; bytes: number; type: string; etag: string; placeholder: boolean; url: string; secure_url: string; access_mode: string; original_filename: string; moderation: Array<string>; access_control: Array<string>; context: object; metadata: object; [futureKey: string]: any; } export interface UploadApiErrorResponse { message: string; name: string; http_code: number; [futureKey: string]: any; } class UploadStream extends Transform { } export interface DeleteApiResponse { message: string; http_code: number; } export interface MetadataFieldApiOptions { external_id?: string; type?: string; label?: string; mandatory?: boolean; default_value?: number; validation?: object; datasource?: object; [futureKey: string]: any; } export interface MetadataFieldApiResponse { external_id: string; type: string; label: string; mandatory: boolean; default_value: number; validation: object; datasource: object; [futureKey: string]: any; } export interface MetadataFieldsApiResponse { metadata_fields: MetadataFieldApiResponse[] } export interface DatasourceChange { values: Array<object> } export interface ResourceApiResponse { resources: [ { public_id: string; format: string; version: number; resource_type: string; type: string; placeholder: boolean; created_at: string; bytes: number; width: number; height: number; backup: boolean; access_mode: string; url: string; secure_url: string; tags: Array<string>; context: object; next_cursor: string; derived_next_cursor: string; exif: object; image_metadata: object; faces: number[][]; quality_analysis: number; colors: string[][]; derived: Array<string>; moderation: object; phash: string; predominant: object; coordinates: object; access_control: Array<string>; pages: number; [futureKey: string]: any; } ] } export namespace v2 { /****************************** Global Utils *************************************/ function cloudinary_js_config(): string; function config(new_config?: boolean | ConfigOptions): ConfigOptions; function config<K extends keyof ConfigOptions, V extends ConfigOptions[K]>(key: K, value?: undefined): V; function config<K extends keyof ConfigOptions, V extends ConfigOptions[K]>(key: K, value: V): ConfigOptions & { [Property in K]: V } function url(public_id: string, options?: TransformationOptions | ConfigAndUrlOptions): string; /****************************** Tags *************************************/ function image(source: string, options?: ImageTransformationAndTagsOptions | ConfigAndUrlOptions): string; function picture(public_id: string, options?: ImageTransformationAndTagsOptions | ConfigAndUrlOptions): string; function source(public_id: string, options?: TransformationOptions | ConfigAndUrlOptions): string; function video(public_id: string, options?: VideoTransformationAndTagsOptions | ConfigAndUrlOptions): string; /****************************** Utils *************************************/ namespace utils { function sign_request(params_to_sign: object, options?: ConfigAndUrlOptions): { signature: string; api_key: string; [key:string]:any}; function api_sign_request(params_to_sign: object, api_secret: string): string; function api_url(action?: string, options?: ConfigAndUrlOptions): string; function url(public_id?: string, options?: TransformationOptions | ConfigAndUrlOptions): string; function video_thumbnail_url(public_id?: string, options?: VideoTransformationOptions | ConfigAndUrlOptions): string; function video_url(public_id?: string, options?: VideoTransformationOptions | ConfigAndUrlOptions): string; function archive_params(options?: ArchiveApiOptions): Promise<any>; function download_archive_url(options?: ArchiveApiOptions | ConfigAndUrlOptions): string function download_zip_url(options?: ArchiveApiOptions | ConfigAndUrlOptions): string; function generate_auth_token(options?: AuthTokenApiOptions): string; function webhook_signature(data?: string, timestamp?: number, options?: ConfigOptions): string; function private_download_url(publicID: string, format:string, options: Partial<{ resource_type: ResourceType; type: DeliveryType; expires_at: number; attachment: boolean; }>): string; } /****************************** Admin API V2 Methods *************************************/ namespace api { function create_streaming_profile(name: string, options: AdminApiOptions | { display_name?: string, representations: TransformationOptions }, callback?: ResponseCallback): Promise<any>; function create_transformation(name: string, transformation: TransformationOptions, callback?: ResponseCallback): Promise<any>; function create_transformation(name: string, transformation: TransformationOptions, options?: AdminApiOptions | { allowed_for_strict?: boolean }, callback?: ResponseCallback): Promise<any>; function create_upload_mapping(folder: string, options: AdminApiOptions | { template: string }, callback?: ResponseCallback): Promise<any>; function create_upload_preset(options?: AdminApiOptions | { name?: string, unsigned?: boolean, disallow_public_id?: boolean }, callback?: ResponseCallback): Promise<any>; function delete_all_resources(value?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<any>; function delete_derived_by_transformation(public_ids: string[], transformations: TransformationOptions, callback?: ResponseCallback): Promise<any>; function delete_derived_by_transformation(public_ids: string[], transformations: TransformationOptions, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function delete_derived_resources(public_ids: string[], callback?: ResponseCallback): Promise<any>; function delete_derived_resources(public_ids: string[], options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<any>; function delete_resources(value: string[], callback?: ResponseCallback): Promise<any>; function delete_resources(value: string[], options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<any>; function delete_resources_by_prefix(prefix: string, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<any>; function delete_resources_by_prefix(prefix: string, callback?: ResponseCallback): Promise<any>; function delete_resources_by_tag(tag: string, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<any>; function delete_resources_by_tag(tag: string, callback?: ResponseCallback): Promise<any>; function delete_streaming_profile(name: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function delete_streaming_profile(name: string, callback?: ResponseCallback): Promise<any>; function delete_transformation(transformationName: TransformationOptions, callback?: ResponseCallback): Promise<any>; function delete_transformation(transformationName: TransformationOptions, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function delete_upload_mapping(folder: string, callback?: ResponseCallback): Promise<any>; function delete_upload_mapping(folder: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function delete_upload_preset(name: string, callback?: ResponseCallback): Promise<any>; function delete_upload_preset(name: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function get_streaming_profile(name: string | ResponseCallback, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function get_streaming_profile(name: string | ResponseCallback, callback?: ResponseCallback): Promise<any>; function list_streaming_profiles(callback?: ResponseCallback): Promise<any>; function list_streaming_profiles(options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function ping(options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function ping(callback?: ResponseCallback): Promise<any>; function publish_by_ids(public_ids: string[], options?: AdminAndPublishOptions, callback?: ResponseCallback): Promise<any>; function publish_by_ids(public_ids: string[], callback?: ResponseCallback): Promise<any>; function publish_by_prefix(prefix: string[] | string, options?: AdminAndPublishOptions, callback?: ResponseCallback): Promise<any>; function publish_by_prefix(prefix: string[] | string, callback?: ResponseCallback): Promise<any>; function publish_by_tag(tag: string, options?: AdminAndPublishOptions, callback?: ResponseCallback): Promise<any>; function publish_by_tag(tag: string, callback?: ResponseCallback): Promise<any>; function resource(public_id: string, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<any>; function resource(public_id: string, callback?: ResponseCallback): Promise<any>; function resource_types(options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function resources(options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<any>; function resources_by_context(key: string, value?: string, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<ResourceApiResponse>; function resources_by_context(key: string, value?: string, options?: AdminAndResourceOptions): Promise<ResourceApiResponse>; function resources_by_context(key: string, options?: AdminAndResourceOptions): Promise<ResourceApiResponse>; function resources_by_context(key: string, callback?: ResponseCallback): Promise<ResourceApiResponse>; function resources_by_ids(public_ids: string[] | string, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<ResourceApiResponse>; function resources_by_ids(public_ids: string[] | string, callback?: ResponseCallback): Promise<ResourceApiResponse>; function resources_by_moderation(moderation: ModerationKind, status: Status, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<ResourceApiResponse>; function resources_by_moderation(moderation: ModerationKind, status: Status, callback?: ResponseCallback): Promise<ResourceApiResponse>; function resources_by_tag(tag: string, options?: AdminAndResourceOptions, callback?: ResponseCallback): Promise<ResourceApiResponse>; function resources_by_tag(tag: string, callback?: ResponseCallback): Promise<ResourceApiResponse>; function restore(public_ids: string[], options?: AdminApiOptions | { resource_type: ResourceType, type: DeliveryType }, callback?: ResponseCallback): Promise<any>; function restore(public_ids: string[], callback?: ResponseCallback): Promise<any>; function root_folders(callback?: ResponseCallback, options?: AdminApiOptions): Promise<any>; function search(params: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function search(params: string, callback?: ResponseCallback): Promise<any>; function sub_folders(root_folder: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function sub_folders(root_folder: string, callback?: ResponseCallback): Promise<any>; function tags(callback?: ResponseCallback, options?: AdminApiOptions | { max_results?: number, next_cursor?: string, prefix?: string }): Promise<any>; function transformation(transformation: TransformationOptions, options?: AdminApiOptions | { max_results?: number, next_cursor?: string, named?: boolean }, callback?: ResponseCallback): Promise<any>; function transformation(transformation: TransformationOptions, callback?: ResponseCallback): Promise<any>; function transformations(options?: AdminApiOptions | { max_results?: number, next_cursor?: string, named?: boolean }, callback?: ResponseCallback): Promise<any>; function transformations(callback?: ResponseCallback): Promise<any>; function update(public_id: string, options?: AdminAndUpdateApiOptions, callback?: ResponseCallback): Promise<any>; function update(public_id: string, callback?: ResponseCallback): Promise<any>; function update_resources_access_mode_by_ids(access_mode: AccessMode, ids: string[], options?: AdminAndUpdateApiOptions, callback?: ResponseCallback): Promise<any>; function update_resources_access_mode_by_ids(access_mode: AccessMode, ids: string[], callback?: ResponseCallback): Promise<any>; function update_resources_access_mode_by_prefix(access_mode: AccessMode, prefix: string, options?: AdminAndUpdateApiOptions, callback?: ResponseCallback): Promise<any>; function update_resources_access_mode_by_prefix(access_mode: AccessMode, prefix: string, callback?: ResponseCallback): Promise<any>; function update_resources_access_mode_by_tag(access_mode: AccessMode, tag: string, options?: AdminAndUpdateApiOptions, callback?: ResponseCallback): Promise<any>; function update_resources_access_mode_by_tag(access_mode: AccessMode, tag: string, callback?: ResponseCallback): Promise<any>; function update_streaming_profile(name: string, options: { display_name?: string, representations: Array<{ transformation?: VideoTransformationOptions }> }, callback?: ResponseCallback): Promise<any>; function update_transformation(transformation_name: TransformationOptions, updates?: TransformationOptions, callback?: ResponseCallback): Promise<any>; function update_transformation(transformation_name: TransformationOptions, callback?: ResponseCallback): Promise<any>; function update_upload_mapping(name: string, options: AdminApiOptions | { template: string }, callback?: ResponseCallback): Promise<any>; function update_upload_preset(name?: string, options?: AdminApiOptions | { unsigned?: boolean, disallow_public_id?: boolean }, callback?: ResponseCallback): Promise<any>; function update_upload_preset(name?: string, callback?: ResponseCallback): Promise<any>; function upload_mapping(name?: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function upload_mapping(name?: string, callback?: ResponseCallback): Promise<any>; function upload_mappings(options?: AdminApiOptions | { max_results?: number, next_cursor?: string }, callback?: ResponseCallback): Promise<any>; function upload_mappings(callback?: ResponseCallback): Promise<any>; function upload_preset(name?: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function upload_preset(name?: string, callback?: ResponseCallback): Promise<any>; function upload_presets(options?: AdminApiOptions | { max_results?: number, next_cursor?: string }, callback?: ResponseCallback): Promise<any>; function usage(callback?: ResponseCallback, options?: AdminApiOptions): Promise<any>; function usage(options?: AdminApiOptions): Promise<any>; function create_folder(path:string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; function delete_folder(path:string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<any>; /****************************** Structured Metadata API V2 Methods *************************************/ function add_metadata_field(field: MetadataFieldApiOptions, options?: AdminApiOptions, callback?: ResponseCallback): Promise<MetadataFieldApiResponse>; function add_metadata_field(field: MetadataFieldApiOptions, callback?: ResponseCallback): Promise<MetadataFieldApiResponse>; function list_metadata_fields(callback?: ResponseCallback, options?: AdminApiOptions): Promise<MetadataFieldsApiResponse>; function list_metadata_fields(options?: AdminApiOptions): Promise<MetadataFieldsApiResponse>; function delete_metadata_field(field_external_id: string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<DeleteApiResponse>; function delete_metadata_field(field_external_id: string, callback?: ResponseCallback): Promise<DeleteApiResponse>; function metadata_field_by_field_id(external_id:string, options?: AdminApiOptions, callback?: ResponseCallback): Promise<MetadataFieldApiResponse>; function metadata_field_by_field_id(external_id:string, callback?: ResponseCallback): Promise<MetadataFieldApiResponse>; function update_metadata_field(external_id: string, field: MetadataFieldApiOptions, options?: AdminApiOptions, callback?: ResponseCallback): Promise<MetadataFieldApiResponse>; function update_metadata_field(external_id: string, field: MetadataFieldApiOptions, callback?: ResponseCallback): Promise<MetadataFieldApiResponse>; function update_metadata_field_datasource(field_external_id: string, entries_external_id: object, options?: AdminApiOptions, callback?: ResponseCallback): Promise<DatasourceChange>; function update_metadata_field_datasource(field_external_id: string, entries_external_id: object, callback?: ResponseCallback): Promise<DatasourceChange>; function delete_datasource_entries(field_external_id: string, entries_external_id: string[], options?: AdminApiOptions, callback?: ResponseCallback): Promise<DatasourceChange>; function delete_datasource_entries(field_external_id: string, entries_external_id: string[], callback?: ResponseCallback): Promise<DatasourceChange>; function restore_metadata_field_datasource(field_external_id: string, entries_external_id: string[], options?: AdminApiOptions, callback?: ResponseCallback): Promise<DatasourceChange>; function restore_metadata_field_datasource(field_external_id: string, entries_external_id: string[], callback?: ResponseCallback): Promise<DatasourceChange>; } /****************************** Upload API V2 Methods *************************************/ namespace uploader { function add_context(context: string, public_ids: string[], options?: { type?: DeliveryType, resource_type?: ResourceType }, callback?: ResponseCallback): Promise<any>; function add_context(context: string, public_ids: string[], callback?: ResponseCallback): Promise<any>; function add_tag(tag: string, public_ids: string[], options?: { type?: DeliveryType, resource_type?: ResourceType }, callback?: ResponseCallback): Promise<any>; function add_tag(tag: string, public_ids: string[], callback?: ResponseCallback): Promise<any>; function create_archive(options?: ArchiveApiOptions, target_format?: TargetArchiveFormat, callback?: ResponseCallback,): Promise<any>; function create_zip(options?: ArchiveApiOptions, callback?: ResponseCallback): Promise<any>; function destroy(public_id: string, options?: { resource_type?: ResourceType, type?: DeliveryType, invalidate?: boolean }, callback?: ResponseCallback,): Promise<any>; function destroy(public_id: string, callback?: ResponseCallback,): Promise<any>; function explicit(public_id: string, options?: UploadApiOptions, callback?: ResponseCallback): Promise<any>; function explicit(public_id: string, callback?: ResponseCallback): Promise<any>; function explode(public_id: string, options?: { page?: 'all', type?: DeliveryType, format?: ImageAndVideoFormatOptions, notification_url?: string, transformations?: TransformationOptions }, callback?: ResponseCallback): Promise<any> function explode(public_id: string, callback?: ResponseCallback): Promise<any> function generate_sprite(tag: string, options?: { transformation?: TransformationOptions, format?: ImageAndVideoFormatOptions, notification_url?: string, async?: boolean }, callback?: ResponseCallback): Promise<any>; function generate_sprite(tag: string, callback?: ResponseCallback): Promise<any>; function image_upload_tag(field?: string, options?: UploadApiOptions): Promise<any>; function multi(tag: string, options?: { transformation?: TransformationOptions, async?: boolean, format?: ImageAndVideoFormatOptions, notification_url?: string }, callback?: ResponseCallback): Promise<any>; function multi(tag: string, callback?: ResponseCallback): Promise<any>; function remove_all_context(public_ids: string[], options?: { context?: string, resource_type?: ResourceType, type?: DeliveryType }, callback?: ResponseCallback): Promise<any>; function remove_all_context(public_ids: string[], callback?: ResponseCallback): Promise<any>; function remove_all_tags(public_ids: string[], options?: { tag?: string, resource_type?: ResourceType, type?: DeliveryType }, callback?: ResponseCallback): Promise<any>; function remove_all_tags(public_ids: string[], callback?: ResponseCallback): Promise<any>; function remove_tag(tag: string, public_ids: string[], options?: { tag?: string, resource_type?: ResourceType, type?: DeliveryType }, callback?: ResponseCallback): Promise<any>; function remove_tag(tag: string, public_ids: string[], callback?: ResponseCallback): Promise<any>; function rename(from_public_id: string, to_public_id: string, options?: { resource_type?: ResourceType, type?: DeliveryType, to_type?: DeliveryType, overwrite?: boolean, invalidate?: boolean }, callback?: ResponseCallback): Promise<any>; function rename(from_public_id: string, to_public_id: string, callback?: ResponseCallback): Promise<any>; function replace_tag(tag: string, public_ids: string[], options?: { resource_type?: ResourceType, type?: DeliveryType }, callback?: ResponseCallback): Promise<any>; function replace_tag(tag: string, public_ids: string[], callback?: ResponseCallback): Promise<any>; function text(text: string, options?: TextStyleOptions | { public_id?: string }, callback?: ResponseCallback): Promise<any>; function text(text: string, callback?: ResponseCallback): Promise<any>; function unsigned_image_upload_tag(field: string, upload_preset: string, options?: UploadApiOptions): Promise<any>; function unsigned_upload(file: string, upload_preset: string, options?: UploadApiOptions, callback?: ResponseCallback): Promise<any>; function unsigned_upload(file: string, upload_preset: string, callback?: ResponseCallback): Promise<any>; function unsigned_upload_stream(upload_preset: string, options?: UploadApiOptions, callback?: ResponseCallback): UploadStream; function unsigned_upload_stream(upload_preset: string, callback?: ResponseCallback): UploadStream; function upload(file: string, options?: UploadApiOptions, callback?: UploadResponseCallback): Promise<UploadApiResponse>; function upload(file: string, callback?: UploadResponseCallback): Promise<UploadApiResponse>; function upload_chunked(path: string, options?: UploadApiOptions, callback?: UploadResponseCallback): Promise<UploadApiResponse>; function upload_chunked(path: string, callback?: UploadResponseCallback): Promise<UploadApiResponse>; function upload_chunked_stream(options?: UploadApiOptions, callback?: UploadResponseCallback): UploadStream; function upload_large(path: string, options?: UploadApiOptions, callback?: UploadResponseCallback): Promise<UploadApiResponse>; function upload_large(path: string, callback?: UploadResponseCallback): Promise<UploadApiResponse>; function upload_stream(options?: UploadApiOptions, callback?: UploadResponseCallback): UploadStream; function upload_stream(callback?: UploadResponseCallback): UploadStream; function upload_tag_params(options?: UploadApiOptions, callback?: UploadResponseCallback): Promise<any>; function upload_url(options?: ConfigOptions): Promise<any>; function create_slideshow(options?: ConfigOptions & { manifest_transformation?: TransformationOptions, manifest_json?: Record<string, any>}, callback?: UploadResponseCallback): Promise<any>; /****************************** Structured Metadata API V2 Methods *************************************/ function update_metadata(metadata: string | object, public_ids: string[], options?:UploadApiOptions, callback?: ResponseCallback): Promise<MetadataFieldApiResponse>; function update_metadata(metadata: string| object, public_ids: string[], callback?: ResponseCallback): Promise<MetadataFieldApiResponse>; } /****************************** Search API *************************************/ class search { aggregate(value?: string): search; execute(): Promise<any>; expression(value?: string): search; max_results(value?: number): search; next_cursor(value?: string): search; sort_by(key: string, value: 'asc' | 'desc'): search; to_query(value?: string): search; with_field(value?: string): search; static aggregate(args?: string): search; static expression(args?: string): search; static instance(args?: string): search; static max_results(args?: number): search; static next_cursor(args?: string): search; static sort_by(key: string, value: 'asc' | 'desc'): search; static with_field(args?: string): search; } /****************************** Provisioning API *************************************/ namespace provisioning { namespace account { function sub_accounts(enabled: boolean, ids?: string[], prefix?: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function sub_account(subAccountId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function create_sub_account(name: string, cloudName: string, customAttributes?: object, enabled?: boolean, baseAccount?: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function delete_sub_account(subAccountId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function update_sub_account(subAccountId: string, name?: string, cloudName?: string, customAttributes?: object, enabled?: boolean, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function user(userId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function users(pending: boolean, userIds?: string[], prefix?: string, subAccountId?: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function create_user(name: string, email: string, role: string, subAccountIds?: string[], options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function update_user(userId: string, name?: string, email?: string, role?: string, subAccountIds?: string[], options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function delete_user(userId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function create_user_group(name: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function update_user_group(groupId: string, name: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function delete_user_group(groupId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function add_user_to_group(groupId: string, userId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function remove_user_from_group(groupId: string, userId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function user_group(groupId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function user_groups(options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; function user_group_users(groupId: string, options?: ProvisioningApiOptions, callback?: ResponseCallback): Promise<any>; } } } }
the_stack
* This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import { HTMLStencilElement, JSXBase } from "@stencil/core/internal"; export namespace Components { interface FwButton { /** * Identifier of the theme based on which the button is styled. */ "color": "primary" | "secondary" | "danger" | "link" | "text"; /** * Disables the button on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled": boolean; /** * Sets the button to a full-width block. If the attribute’s value is undefined, the value is set to false. */ "expand": boolean; /** * Accepts the id of the fw-modal component to open it on click */ "modalTriggerId": string; /** * Size of the button. */ "size": "normal" | "mini" | "small"; /** * Button type based on which actions are performed when the button is clicked. */ "type": "button" | "reset" | "submit"; } interface FwCheckbox { /** * Sets the state of the check box to selected. If the attribute’s value is undefined, the value is set to false. */ "checked": boolean; /** * Disables the check box on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled": boolean; /** * Label displayed on the interface, for the check box. */ "label": string; /** * Name of the component, saved as part of form data. */ "name": string; /** * Identifier corresponding to the component, that is saved when the form data is saved. */ "value": string; } interface FwDatepicker { /** * Format in which the date values selected in the calendar are populated in the input box and saved when the form data is saved. */ "dateFormat": string; /** * Starting date of the date range that is preselected in the calendar, if mode is range. Must be a date later than the min-date value. */ "fromDate": string; /** * Latest date a user can select in the calendar, if mode is range. */ "maxDate": string; /** * Earliest date a user can select in the calendar, if mode is range. */ "minDate": string; /** * Type of date selection enabled for the calendar. If the value is range, a user can select a date range in the calendar. */ "mode": "single date" | "range"; /** * Name of the component, saved as part of form data. */ "name": string; /** * Text displayed in the input box before a user selects a date or date range. */ "placeholder": string; /** * Ending date of the date range that is preselected in the calendar, if mode is range. Must be a date earlier than the max-date value. */ "toDate": string; /** * Date that is preselected in the calendar, if mode is single date or undefined. */ "value": string; } interface FwDropdownButton { /** * Dropdown Button color */ "color": "primary" | "secondary" | "danger" | "link" | "text"; /** * Disables the dropdown button if its true */ "disabled": boolean; /** * Label for the dropdown button */ "label": string; /** * Options to show in the dropdown button */ "options": any[]; /** * Placeholder text for search input. Validated only if dropdown and searchable is true */ "placeholder": string; /** * Displays a searchable dropdown button */ "searchable": boolean; /** * Displays a split dropdown button */ "split": boolean; /** * Value of the dropdown button */ "value": any; } interface FwIcon { /** * Color in which the icon is displayed, specified as a standard CSS color or as a HEX code. */ "color": string; /** * Identifier of the icon. The attribute’s value must be a valid svg file in the repo of icons (assets/icons). */ "name": string; /** * Size of the icon, specified in number of pixels. */ "size": number; } interface FwInput { /** * Specifies whether the browser can display suggestions to autocomplete the text value. */ "autocomplete": "on" | "off"; /** * Specifies whether the browser can auto focus the input field */ "autofocus": boolean; /** * Displays a right-justified clear icon in the text box. Clicking the icon clears the input text. If the attribute’s value is undefined, the value is set to false. For a read-only input box, the clear icon is not displayed unless a default value is specified for the input box. */ "clearInput": boolean; /** * Disables the component on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled": boolean; /** * Identifier of the icon that is displayed in the left side of the text box. The attribute’s value must be a valid svg file in the repo of icons (assets/icons). */ "iconLeft": string; /** * Identifier of the icon that is displayed in the right side of the text box. The attribute’s value must be a valid svg file in the repo of icons (assets/icons). */ "iconRight": string; /** * Label displayed on the interface, for the component. */ "label": string; /** * Maximum number of characters a user can enter in the text box. */ "maxlength"?: number; /** * Minimum number of characters a user must enter in the text box for the value to be valid. */ "minlength"?: number; /** * Name of the component, saved as part of form data. */ "name": string; /** * Text displayed in the text box before a user enters a value. */ "placeholder"?: string | null; /** * If true, the user cannot enter a value in the input box. If the attribute’s value is undefined, the value is set to false. */ "readonly": boolean; /** * Specifies the input box as a mandatory field and displays an asterisk next to the label. If the attribute’s value is undefined, the value is set to false. */ "required": boolean; /** * Sets focus on a specific `fw-input`. Use this method instead of the global `input.focus()`. */ "setFocus": () => Promise<void>; /** * Theme based on which the text box is styled. */ "state": "normal" | "warning" | "error"; /** * Descriptive or instructional text displayed below the text box. */ "stateText": string; /** * Type of value accepted as the input value. If a user enters a value other than the specified type, the input box is not populated. */ "type": "text" | "number"; /** * Default value displayed in the input box. */ "value"?: string | null; } interface FwLabel { /** * Theme based on which the label is styled. */ "color": "blue" | "red" | "green" | "yellow" | "grey" | "normal"; /** * Display text in the label. */ "value": string; } interface FwModal { /** * The text for the cancel button */ "cancelText": string; /** * Enable custom footer */ "customFooter": boolean; /** * The title text to be displayed on the modal */ "description": string; /** * Hides the footer */ "hideFooter": boolean; /** * The icon to be displayed with the title */ "icon": string; /** * Size of the modal */ "size": "standard" | "small" | "large"; /** * The text for the success button */ "successText": string; /** * The title text to be displayed on the modal */ "titleText": string; /** * Toggle the visibility of the modal */ "visible": boolean; } interface FwRadio { /** * Sets the state to selected. If the attribute’s value is undefined, the value is set to false. */ "checked": boolean; /** * Disables the component on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled": boolean; /** * Label displayed on the interface, for the component. */ "label": string; /** * Name of the component, saved as part of form data. */ "name": string; /** * Identifier corresponding to the component, that is saved when the form data is saved. */ "value": string; } interface FwRadioGroup { /** * If true, a radio group can be saved without selecting any option. If an option is selected, the selection can be cleared. If the attribute’s value is undefined, the value is set to false. */ "allowEmpty": boolean; /** * Name of the component, saved as part of form data. */ "name": string; /** * Default option that is selected when the radio group is displayed on the interface. Must be a valid value corresponding to the fw-radio components used in the Radio Group. */ "value"?: any | null; } interface FwSelect { /** * If true, the select component is auto focused on the page */ "autofocus": boolean; /** * Disables the component on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled": boolean; /** * If true, the user must select a value. The default value is not displayed. */ "forceSelect": boolean; "getSelectedItem": () => Promise<any>; /** * Label displayed on the interface, for the component. */ "label": string; /** * Works with `multiple` enabled. Configures the maximum number of options that can be selected with a multi-select component. */ "max": number; /** * Enables selection of multiple options. If the attribute’s value is undefined, the value is set to false. */ "multiple": boolean; /** * Name of the component, saved as part of form data. */ "name": string; /** * Text displayed in the list box before an option is selected. */ "placeholder"?: string | null; /** * If true, the user cannot modify the default value selected. If the attribute's value is undefined, the value is set to true. */ "readonly": boolean; /** * Specifies the select field as a mandatory field and displays an asterisk next to the label. If the attribute’s value is undefined, the value is set to false. */ "required": boolean; "setSelectedValues": (values: string[]) => Promise<any>; /** * Theme based on which the list box is styled. */ "state": "normal" | "warning" | "error"; /** * Descriptive or instructional text displayed below the list box. */ "stateText": string; /** * Type of option accepted as the input value. If a user tries to enter an option other than the specified type, the list is not populated. */ "type": "text" | "number"; /** * Value of the option that is displayed as the default selection, in the list box. Must be a valid value corresponding to the fw-select-option components used in Select. */ "value": any; } interface FwSelectOption { /** * Sets the state of the option to disabled. The selected option is disabled and greyed out. If the attribute’s value is undefined, the value is set to false. */ "disabled": boolean; /** * States that the option is an HTML value. If the attribute's value is undefined, the value is set to true. */ "html": boolean; /** * HTML content that is displayed as the option. */ "htmlContent"?: string; /** * Alternate text displayed on the interface, in place of the actual HTML content. */ "optionText": string; /** * Sets the state of the option to selected. The selected option is highlighted and a check mark is displayed next to it. If the attribute’s value is undefined, the value is set to false. */ "selected": boolean; /** * Value corresponding to the option, that is saved when the form data is saved. */ "value": string; } interface FwSpinner { /** * Color in which the loader is displayed, specified as a standard CSS color. */ "color": string; /** * Size of the loader. */ "size": "small" | "medium" | "large" | "default"; } interface FwTab { /** * Disables this tab */ "disabled": boolean; /** * Name of the tab displayed on the UI. */ "tabHeader": string; /** * HTML that can be rendered in tab header. */ "tabHeaderHtml": string; } interface FwTabs { /** * The index of the activated Tab(Starts from 0) */ "activeTabIndex": number; } interface FwTag { /** * Sets the state of the tag to disabled. The close button is disabled. If the attribute’s value is undefined, the value is set to false. */ "disabled": false; /** * Display text in the tag component. */ "text": string; /** * Value associated with the tag component, that is saved when the form data is saved. */ "value": string; } interface FwTextarea { /** * If true, the textarea is autofocused */ "autofocus": boolean; /** * Width of the input box, specified as number of columns. */ "cols"?: number; /** * Disables the text area on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled": boolean; /** * Label displayed on the interface, for the component. */ "label": string; /** * Maximum number of characters a user can enter in the input box. */ "maxlength"?: number; /** * Minimum number of characters a user must enter in the input box for the value to be valid. */ "minlength"?: number; /** * Name of the component, saved as part of form data. */ "name": string; /** * Text displayed in the input box before a user enters a value. */ "placeholder"?: string | null; /** * If true, the user cannot enter a value in the input box. If the attribute’s value is undefined, the value is set to false. */ "readonly": boolean; /** * Specifies the input box as a mandatory field and displays an asterisk next to the label. If the attribute’s value is undefined, the value is set to false. */ "required": boolean; /** * Height of the input box, specified as number of rows. */ "rows"?: number; /** * Sets focus on a specific `fw-textarea`. Use this method instead of the global `input.focus()`. */ "setFocus": () => Promise<void>; /** * Theme based on which the input box is styled. */ "state": "normal" | "warning" | "error"; /** * Descriptive or instructional text displayed below the input box. */ "stateText": string; /** * Default value displayed in the input box. */ "value"?: string | null; /** * Type of text wrapping used by the input box. If the value is hard, the text in the textarea is wrapped (contains line breaks) when the form data is saved. If the value is soft, the text in the textarea is saved as a single line, when the form data is saved. */ "wrap": "soft" | "hard"; } interface FwTimepicker { /** * Set true to disable the element */ "disabled": boolean; /** * Format in which time values are populated in the list box. If the value is hh:mm p, the time values are in the 12-hour format. If the value is hh:mm, the time values are in the 24-hr format. */ "format": "hh:mm A" | "HH:mm"; /** * Time interval between the values displayed in the list, specified in minutes. */ "interval": number; /** * Upper time-limit for the values displayed in the list. If this attribute’s value is in the hh:mm format, it is assumed to be hh:mm AM. */ "maxTime"?: string; /** * Lower time-limit for the values displayed in the list. If this attribute’s value is in the hh:mm format, it is assumed to be hh:mm AM. */ "minTime"?: string; /** * Name of the component, saved as part of form data. */ "name": string; /** * Time output value */ "value"?: string; } interface FwToast { /** * The Content of the action link */ "actionLinkText": string; /** * The content to be diaplyed in toast */ "content": string; /** * Pause the toast from hiding on mouse hover */ "pauseOnHover": boolean; /** * position of the toast notification in screen */ "position": "top-center" | "top-left" | "top-right"; /** * won't close automatically */ "sticky": boolean; /** * Time duration of the toast visibility */ "timeout": number; "trigger": (configs: object) => Promise<void>; /** * Type of the toast - success,failure, warning, inprogress */ "type": "success" | "error" | "warning" | "inprogress"; } interface FwToggle { /** * Sets the selected state as the default state. If the attribute’s value is undefined, the value is set to false. */ "checked": boolean; /** * Specifies whether to disable the control on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled": boolean; /** * Name of the component, saved as part of the form data. */ "name": string; /** * Size of the input control. */ "size": "small" | "medium" | "large"; } } declare global { interface HTMLFwButtonElement extends Components.FwButton, HTMLStencilElement { } var HTMLFwButtonElement: { prototype: HTMLFwButtonElement; new (): HTMLFwButtonElement; }; interface HTMLFwCheckboxElement extends Components.FwCheckbox, HTMLStencilElement { } var HTMLFwCheckboxElement: { prototype: HTMLFwCheckboxElement; new (): HTMLFwCheckboxElement; }; interface HTMLFwDatepickerElement extends Components.FwDatepicker, HTMLStencilElement { } var HTMLFwDatepickerElement: { prototype: HTMLFwDatepickerElement; new (): HTMLFwDatepickerElement; }; interface HTMLFwDropdownButtonElement extends Components.FwDropdownButton, HTMLStencilElement { } var HTMLFwDropdownButtonElement: { prototype: HTMLFwDropdownButtonElement; new (): HTMLFwDropdownButtonElement; }; interface HTMLFwIconElement extends Components.FwIcon, HTMLStencilElement { } var HTMLFwIconElement: { prototype: HTMLFwIconElement; new (): HTMLFwIconElement; }; interface HTMLFwInputElement extends Components.FwInput, HTMLStencilElement { } var HTMLFwInputElement: { prototype: HTMLFwInputElement; new (): HTMLFwInputElement; }; interface HTMLFwLabelElement extends Components.FwLabel, HTMLStencilElement { } var HTMLFwLabelElement: { prototype: HTMLFwLabelElement; new (): HTMLFwLabelElement; }; interface HTMLFwModalElement extends Components.FwModal, HTMLStencilElement { } var HTMLFwModalElement: { prototype: HTMLFwModalElement; new (): HTMLFwModalElement; }; interface HTMLFwRadioElement extends Components.FwRadio, HTMLStencilElement { } var HTMLFwRadioElement: { prototype: HTMLFwRadioElement; new (): HTMLFwRadioElement; }; interface HTMLFwRadioGroupElement extends Components.FwRadioGroup, HTMLStencilElement { } var HTMLFwRadioGroupElement: { prototype: HTMLFwRadioGroupElement; new (): HTMLFwRadioGroupElement; }; interface HTMLFwSelectElement extends Components.FwSelect, HTMLStencilElement { } var HTMLFwSelectElement: { prototype: HTMLFwSelectElement; new (): HTMLFwSelectElement; }; interface HTMLFwSelectOptionElement extends Components.FwSelectOption, HTMLStencilElement { } var HTMLFwSelectOptionElement: { prototype: HTMLFwSelectOptionElement; new (): HTMLFwSelectOptionElement; }; interface HTMLFwSpinnerElement extends Components.FwSpinner, HTMLStencilElement { } var HTMLFwSpinnerElement: { prototype: HTMLFwSpinnerElement; new (): HTMLFwSpinnerElement; }; interface HTMLFwTabElement extends Components.FwTab, HTMLStencilElement { } var HTMLFwTabElement: { prototype: HTMLFwTabElement; new (): HTMLFwTabElement; }; interface HTMLFwTabsElement extends Components.FwTabs, HTMLStencilElement { } var HTMLFwTabsElement: { prototype: HTMLFwTabsElement; new (): HTMLFwTabsElement; }; interface HTMLFwTagElement extends Components.FwTag, HTMLStencilElement { } var HTMLFwTagElement: { prototype: HTMLFwTagElement; new (): HTMLFwTagElement; }; interface HTMLFwTextareaElement extends Components.FwTextarea, HTMLStencilElement { } var HTMLFwTextareaElement: { prototype: HTMLFwTextareaElement; new (): HTMLFwTextareaElement; }; interface HTMLFwTimepickerElement extends Components.FwTimepicker, HTMLStencilElement { } var HTMLFwTimepickerElement: { prototype: HTMLFwTimepickerElement; new (): HTMLFwTimepickerElement; }; interface HTMLFwToastElement extends Components.FwToast, HTMLStencilElement { } var HTMLFwToastElement: { prototype: HTMLFwToastElement; new (): HTMLFwToastElement; }; interface HTMLFwToggleElement extends Components.FwToggle, HTMLStencilElement { } var HTMLFwToggleElement: { prototype: HTMLFwToggleElement; new (): HTMLFwToggleElement; }; interface HTMLElementTagNameMap { "fw-button": HTMLFwButtonElement; "fw-checkbox": HTMLFwCheckboxElement; "fw-datepicker": HTMLFwDatepickerElement; "fw-dropdown-button": HTMLFwDropdownButtonElement; "fw-icon": HTMLFwIconElement; "fw-input": HTMLFwInputElement; "fw-label": HTMLFwLabelElement; "fw-modal": HTMLFwModalElement; "fw-radio": HTMLFwRadioElement; "fw-radio-group": HTMLFwRadioGroupElement; "fw-select": HTMLFwSelectElement; "fw-select-option": HTMLFwSelectOptionElement; "fw-spinner": HTMLFwSpinnerElement; "fw-tab": HTMLFwTabElement; "fw-tabs": HTMLFwTabsElement; "fw-tag": HTMLFwTagElement; "fw-textarea": HTMLFwTextareaElement; "fw-timepicker": HTMLFwTimepickerElement; "fw-toast": HTMLFwToastElement; "fw-toggle": HTMLFwToggleElement; } } declare namespace LocalJSX { interface FwButton { /** * Identifier of the theme based on which the button is styled. */ "color"?: "primary" | "secondary" | "danger" | "link" | "text"; /** * Disables the button on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: boolean; /** * Sets the button to a full-width block. If the attribute’s value is undefined, the value is set to false. */ "expand"?: boolean; /** * Accepts the id of the fw-modal component to open it on click */ "modalTriggerId"?: string; /** * Triggered when the button loses focus. */ "onFwBlur"?: (event: CustomEvent<void>) => void; /** * Triggered when the button is clicked. */ "onFwClick"?: (event: CustomEvent<void>) => void; /** * Triggered when the button comes into focus. */ "onFwFocus"?: (event: CustomEvent<void>) => void; /** * Size of the button. */ "size"?: "normal" | "mini" | "small"; /** * Button type based on which actions are performed when the button is clicked. */ "type"?: "button" | "reset" | "submit"; } interface FwCheckbox { /** * Sets the state of the check box to selected. If the attribute’s value is undefined, the value is set to false. */ "checked"?: boolean; /** * Disables the check box on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: boolean; /** * Label displayed on the interface, for the check box. */ "label"?: string; /** * Name of the component, saved as part of form data. */ "name"?: string; /** * Triggered when the check box loses focus. */ "onFwBlur"?: (event: CustomEvent<void>) => void; /** * Triggered when the check box’s value is modified. */ "onFwChange"?: (event: CustomEvent<any>) => void; /** * Triggered when the check box comes into focus. */ "onFwFocus"?: (event: CustomEvent<void>) => void; /** * Identifier corresponding to the component, that is saved when the form data is saved. */ "value"?: string; } interface FwDatepicker { /** * Format in which the date values selected in the calendar are populated in the input box and saved when the form data is saved. */ "dateFormat"?: string; /** * Starting date of the date range that is preselected in the calendar, if mode is range. Must be a date later than the min-date value. */ "fromDate"?: string; /** * Latest date a user can select in the calendar, if mode is range. */ "maxDate"?: string; /** * Earliest date a user can select in the calendar, if mode is range. */ "minDate"?: string; /** * Type of date selection enabled for the calendar. If the value is range, a user can select a date range in the calendar. */ "mode"?: "single date" | "range"; /** * Name of the component, saved as part of form data. */ "name"?: string; /** * Triggered when the update button clicked */ "onFwChange"?: (event: CustomEvent<any>) => void; /** * Text displayed in the input box before a user selects a date or date range. */ "placeholder"?: string; /** * Ending date of the date range that is preselected in the calendar, if mode is range. Must be a date earlier than the max-date value. */ "toDate"?: string; /** * Date that is preselected in the calendar, if mode is single date or undefined. */ "value"?: string; } interface FwDropdownButton { /** * Dropdown Button color */ "color"?: "primary" | "secondary" | "danger" | "link" | "text"; /** * Disables the dropdown button if its true */ "disabled"?: boolean; /** * Label for the dropdown button */ "label"?: string; /** * Triggered when an option is clicked */ "onFwOptionClick"?: (event: CustomEvent<any>) => void; /** * Triggered when Add button for searchable dropdown is clicked */ "onFwOptionsAdd"?: (event: CustomEvent<any>) => void; /** * Options to show in the dropdown button */ "options"?: any[]; /** * Placeholder text for search input. Validated only if dropdown and searchable is true */ "placeholder"?: string; /** * Displays a searchable dropdown button */ "searchable"?: boolean; /** * Displays a split dropdown button */ "split"?: boolean; /** * Value of the dropdown button */ "value"?: any; } interface FwIcon { /** * Color in which the icon is displayed, specified as a standard CSS color or as a HEX code. */ "color"?: string; /** * Identifier of the icon. The attribute’s value must be a valid svg file in the repo of icons (assets/icons). */ "name"?: string; /** * Size of the icon, specified in number of pixels. */ "size"?: number; } interface FwInput { /** * Specifies whether the browser can display suggestions to autocomplete the text value. */ "autocomplete"?: "on" | "off"; /** * Specifies whether the browser can auto focus the input field */ "autofocus"?: boolean; /** * Displays a right-justified clear icon in the text box. Clicking the icon clears the input text. If the attribute’s value is undefined, the value is set to false. For a read-only input box, the clear icon is not displayed unless a default value is specified for the input box. */ "clearInput"?: boolean; /** * Disables the component on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: boolean; /** * Identifier of the icon that is displayed in the left side of the text box. The attribute’s value must be a valid svg file in the repo of icons (assets/icons). */ "iconLeft"?: string; /** * Identifier of the icon that is displayed in the right side of the text box. The attribute’s value must be a valid svg file in the repo of icons (assets/icons). */ "iconRight"?: string; /** * Label displayed on the interface, for the component. */ "label"?: string; /** * Maximum number of characters a user can enter in the text box. */ "maxlength"?: number; /** * Minimum number of characters a user must enter in the text box for the value to be valid. */ "minlength"?: number; /** * Name of the component, saved as part of form data. */ "name"?: string; /** * Triggered when the input box loses focus. */ "onFwBlur"?: (event: CustomEvent<void>) => void; /** * Triggered when the value in the input box is modified. */ "onFwChange"?: (event: CustomEvent<any>) => void; /** * Triggered when the input box comes into focus. */ "onFwFocus"?: (event: CustomEvent<void>) => void; /** * Triggered when a value is entered in the input box. */ "onFwInput"?: (event: CustomEvent<KeyboardEvent>) => void; /** * Triggered when clear icon is clicked. */ "onFwInputClear"?: (event: CustomEvent<any>) => void; /** * Text displayed in the text box before a user enters a value. */ "placeholder"?: string | null; /** * If true, the user cannot enter a value in the input box. If the attribute’s value is undefined, the value is set to false. */ "readonly"?: boolean; /** * Specifies the input box as a mandatory field and displays an asterisk next to the label. If the attribute’s value is undefined, the value is set to false. */ "required"?: boolean; /** * Theme based on which the text box is styled. */ "state"?: "normal" | "warning" | "error"; /** * Descriptive or instructional text displayed below the text box. */ "stateText"?: string; /** * Type of value accepted as the input value. If a user enters a value other than the specified type, the input box is not populated. */ "type"?: "text" | "number"; /** * Default value displayed in the input box. */ "value"?: string | null; } interface FwLabel { /** * Theme based on which the label is styled. */ "color"?: "blue" | "red" | "green" | "yellow" | "grey" | "normal"; /** * Display text in the label. */ "value"?: string; } interface FwModal { /** * The text for the cancel button */ "cancelText"?: string; /** * Enable custom footer */ "customFooter"?: boolean; /** * The title text to be displayed on the modal */ "description"?: string; /** * Hides the footer */ "hideFooter"?: boolean; /** * The icon to be displayed with the title */ "icon"?: string; /** * Triggered when the default action button is clicked. */ "onFwAction"?: (event: CustomEvent<void>) => void; /** * Triggered when modal is closed. */ "onFwClosed"?: (event: CustomEvent<void>) => void; /** * Size of the modal */ "size"?: "standard" | "small" | "large"; /** * The text for the success button */ "successText"?: string; /** * The title text to be displayed on the modal */ "titleText"?: string; /** * Toggle the visibility of the modal */ "visible"?: boolean; } interface FwRadio { /** * Sets the state to selected. If the attribute’s value is undefined, the value is set to false. */ "checked"?: boolean; /** * Disables the component on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: boolean; /** * Label displayed on the interface, for the component. */ "label"?: string; /** * Name of the component, saved as part of form data. */ "name"?: string; /** * Triggered when the radio button loses focus. */ "onFwBlur"?: (event: CustomEvent<void>) => void; /** * Triggered when the radio button in focus is cleared. */ "onFwDeselect"?: (event: CustomEvent<any>) => void; /** * Triggered when the radio button comes into focus. */ "onFwFocus"?: (event: CustomEvent<void>) => void; /** * Triggered when the radio button in focus is selected. */ "onFwSelect"?: (event: CustomEvent<any>) => void; /** * Identifier corresponding to the component, that is saved when the form data is saved. */ "value"?: string; } interface FwRadioGroup { /** * If true, a radio group can be saved without selecting any option. If an option is selected, the selection can be cleared. If the attribute’s value is undefined, the value is set to false. */ "allowEmpty"?: boolean; /** * Name of the component, saved as part of form data. */ "name"?: string; /** * Triggered when an option in the Radio Group is selected or deselected. */ "onFwChange"?: (event: CustomEvent<any>) => void; /** * Default option that is selected when the radio group is displayed on the interface. Must be a valid value corresponding to the fw-radio components used in the Radio Group. */ "value"?: any | null; } interface FwSelect { /** * If true, the select component is auto focused on the page */ "autofocus"?: boolean; /** * Disables the component on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: boolean; /** * If true, the user must select a value. The default value is not displayed. */ "forceSelect"?: boolean; /** * Label displayed on the interface, for the component. */ "label"?: string; /** * Works with `multiple` enabled. Configures the maximum number of options that can be selected with a multi-select component. */ "max"?: number; /** * Enables selection of multiple options. If the attribute’s value is undefined, the value is set to false. */ "multiple"?: boolean; /** * Name of the component, saved as part of form data. */ "name"?: string; /** * Triggered when the list box loses focus. */ "onFwBlur"?: (event: CustomEvent<any>) => void; /** * Triggered when a value is selected or deselected from the list box options. */ "onFwChange"?: (event: CustomEvent<any>) => void; /** * Triggered when the list box comes into focus. */ "onFwFocus"?: (event: CustomEvent<any>) => void; /** * Text displayed in the list box before an option is selected. */ "placeholder"?: string | null; /** * If true, the user cannot modify the default value selected. If the attribute's value is undefined, the value is set to true. */ "readonly"?: boolean; /** * Specifies the select field as a mandatory field and displays an asterisk next to the label. If the attribute’s value is undefined, the value is set to false. */ "required"?: boolean; /** * Theme based on which the list box is styled. */ "state"?: "normal" | "warning" | "error"; /** * Descriptive or instructional text displayed below the list box. */ "stateText"?: string; /** * Type of option accepted as the input value. If a user tries to enter an option other than the specified type, the list is not populated. */ "type"?: "text" | "number"; /** * Value of the option that is displayed as the default selection, in the list box. Must be a valid value corresponding to the fw-select-option components used in Select. */ "value"?: any; } interface FwSelectOption { /** * Sets the state of the option to disabled. The selected option is disabled and greyed out. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: boolean; /** * States that the option is an HTML value. If the attribute's value is undefined, the value is set to true. */ "html"?: boolean; /** * HTML content that is displayed as the option. */ "htmlContent"?: string; /** * Triggered when an option is selected. */ "onFwSelected"?: (event: CustomEvent<any>) => void; /** * Alternate text displayed on the interface, in place of the actual HTML content. */ "optionText"?: string; /** * Sets the state of the option to selected. The selected option is highlighted and a check mark is displayed next to it. If the attribute’s value is undefined, the value is set to false. */ "selected"?: boolean; /** * Value corresponding to the option, that is saved when the form data is saved. */ "value"?: string; } interface FwSpinner { /** * Color in which the loader is displayed, specified as a standard CSS color. */ "color"?: string; /** * Size of the loader. */ "size"?: "small" | "medium" | "large" | "default"; } interface FwTab { /** * Disables this tab */ "disabled"?: boolean; /** * Triggered when either tabHeader or tabHeaderHtml changes. */ "onPropChanged"?: (event: CustomEvent<any>) => void; /** * Name of the tab displayed on the UI. */ "tabHeader"?: string; /** * HTML that can be rendered in tab header. */ "tabHeaderHtml"?: string; } interface FwTabs { /** * The index of the activated Tab(Starts from 0) */ "activeTabIndex"?: number; /** * Triggered when a the view switches to a new tab. */ "onFwChange"?: (event: CustomEvent<any>) => void; } interface FwTag { /** * Sets the state of the tag to disabled. The close button is disabled. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: false; /** * Triggered when the tag is deselected. */ "onFwClosed"?: (event: CustomEvent<any>) => void; /** * Display text in the tag component. */ "text"?: string; /** * Value associated with the tag component, that is saved when the form data is saved. */ "value"?: string; } interface FwTextarea { /** * If true, the textarea is autofocused */ "autofocus"?: boolean; /** * Width of the input box, specified as number of columns. */ "cols"?: number; /** * Disables the text area on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: boolean; /** * Label displayed on the interface, for the component. */ "label"?: string; /** * Maximum number of characters a user can enter in the input box. */ "maxlength"?: number; /** * Minimum number of characters a user must enter in the input box for the value to be valid. */ "minlength"?: number; /** * Name of the component, saved as part of form data. */ "name"?: string; /** * Triggered when the input box loses focus. */ "onFwBlur"?: (event: CustomEvent<void>) => void; /** * Triggered when the value in the input box is modified. */ "onFwChange"?: (event: CustomEvent<any>) => void; /** * Triggered when the input box comes into focus. */ "onFwFocus"?: (event: CustomEvent<void>) => void; /** * Triggered when a value is entered in the input box. */ "onFwInput"?: (event: CustomEvent<KeyboardEvent>) => void; /** * Text displayed in the input box before a user enters a value. */ "placeholder"?: string | null; /** * If true, the user cannot enter a value in the input box. If the attribute’s value is undefined, the value is set to false. */ "readonly"?: boolean; /** * Specifies the input box as a mandatory field and displays an asterisk next to the label. If the attribute’s value is undefined, the value is set to false. */ "required"?: boolean; /** * Height of the input box, specified as number of rows. */ "rows"?: number; /** * Theme based on which the input box is styled. */ "state"?: "normal" | "warning" | "error"; /** * Descriptive or instructional text displayed below the input box. */ "stateText"?: string; /** * Default value displayed in the input box. */ "value"?: string | null; /** * Type of text wrapping used by the input box. If the value is hard, the text in the textarea is wrapped (contains line breaks) when the form data is saved. If the value is soft, the text in the textarea is saved as a single line, when the form data is saved. */ "wrap"?: "soft" | "hard"; } interface FwTimepicker { /** * Set true to disable the element */ "disabled"?: boolean; /** * Format in which time values are populated in the list box. If the value is hh:mm p, the time values are in the 12-hour format. If the value is hh:mm, the time values are in the 24-hr format. */ "format"?: "hh:mm A" | "HH:mm"; /** * Time interval between the values displayed in the list, specified in minutes. */ "interval"?: number; /** * Upper time-limit for the values displayed in the list. If this attribute’s value is in the hh:mm format, it is assumed to be hh:mm AM. */ "maxTime"?: string; /** * Lower time-limit for the values displayed in the list. If this attribute’s value is in the hh:mm format, it is assumed to be hh:mm AM. */ "minTime"?: string; /** * Name of the component, saved as part of form data. */ "name"?: string; /** * Time output value */ "value"?: string; } interface FwToast { /** * The Content of the action link */ "actionLinkText"?: string; /** * The content to be diaplyed in toast */ "content"?: string; /** * Triggered when the action link clicked. */ "onFwLinkClick"?: (event: CustomEvent<any>) => void; /** * Pause the toast from hiding on mouse hover */ "pauseOnHover"?: boolean; /** * position of the toast notification in screen */ "position"?: "top-center" | "top-left" | "top-right"; /** * won't close automatically */ "sticky"?: boolean; /** * Time duration of the toast visibility */ "timeout"?: number; /** * Type of the toast - success,failure, warning, inprogress */ "type"?: "success" | "error" | "warning" | "inprogress"; } interface FwToggle { /** * Sets the selected state as the default state. If the attribute’s value is undefined, the value is set to false. */ "checked"?: boolean; /** * Specifies whether to disable the control on the interface. If the attribute’s value is undefined, the value is set to false. */ "disabled"?: boolean; /** * Name of the component, saved as part of the form data. */ "name"?: string; /** * Triggered when the input control is selected or deselected. */ "onFwChange"?: (event: CustomEvent<any>) => void; /** * Size of the input control. */ "size"?: "small" | "medium" | "large"; } interface IntrinsicElements { "fw-button": FwButton; "fw-checkbox": FwCheckbox; "fw-datepicker": FwDatepicker; "fw-dropdown-button": FwDropdownButton; "fw-icon": FwIcon; "fw-input": FwInput; "fw-label": FwLabel; "fw-modal": FwModal; "fw-radio": FwRadio; "fw-radio-group": FwRadioGroup; "fw-select": FwSelect; "fw-select-option": FwSelectOption; "fw-spinner": FwSpinner; "fw-tab": FwTab; "fw-tabs": FwTabs; "fw-tag": FwTag; "fw-textarea": FwTextarea; "fw-timepicker": FwTimepicker; "fw-toast": FwToast; "fw-toggle": FwToggle; } } export { LocalJSX as JSX }; declare module "@stencil/core" { export namespace JSX { interface IntrinsicElements { "fw-button": LocalJSX.FwButton & JSXBase.HTMLAttributes<HTMLFwButtonElement>; "fw-checkbox": LocalJSX.FwCheckbox & JSXBase.HTMLAttributes<HTMLFwCheckboxElement>; "fw-datepicker": LocalJSX.FwDatepicker & JSXBase.HTMLAttributes<HTMLFwDatepickerElement>; "fw-dropdown-button": LocalJSX.FwDropdownButton & JSXBase.HTMLAttributes<HTMLFwDropdownButtonElement>; "fw-icon": LocalJSX.FwIcon & JSXBase.HTMLAttributes<HTMLFwIconElement>; "fw-input": LocalJSX.FwInput & JSXBase.HTMLAttributes<HTMLFwInputElement>; "fw-label": LocalJSX.FwLabel & JSXBase.HTMLAttributes<HTMLFwLabelElement>; "fw-modal": LocalJSX.FwModal & JSXBase.HTMLAttributes<HTMLFwModalElement>; "fw-radio": LocalJSX.FwRadio & JSXBase.HTMLAttributes<HTMLFwRadioElement>; "fw-radio-group": LocalJSX.FwRadioGroup & JSXBase.HTMLAttributes<HTMLFwRadioGroupElement>; "fw-select": LocalJSX.FwSelect & JSXBase.HTMLAttributes<HTMLFwSelectElement>; "fw-select-option": LocalJSX.FwSelectOption & JSXBase.HTMLAttributes<HTMLFwSelectOptionElement>; "fw-spinner": LocalJSX.FwSpinner & JSXBase.HTMLAttributes<HTMLFwSpinnerElement>; "fw-tab": LocalJSX.FwTab & JSXBase.HTMLAttributes<HTMLFwTabElement>; "fw-tabs": LocalJSX.FwTabs & JSXBase.HTMLAttributes<HTMLFwTabsElement>; "fw-tag": LocalJSX.FwTag & JSXBase.HTMLAttributes<HTMLFwTagElement>; "fw-textarea": LocalJSX.FwTextarea & JSXBase.HTMLAttributes<HTMLFwTextareaElement>; "fw-timepicker": LocalJSX.FwTimepicker & JSXBase.HTMLAttributes<HTMLFwTimepickerElement>; "fw-toast": LocalJSX.FwToast & JSXBase.HTMLAttributes<HTMLFwToastElement>; "fw-toggle": LocalJSX.FwToggle & JSXBase.HTMLAttributes<HTMLFwToggleElement>; } } }
the_stack
import {shallowEqual} from 'react-redux'; import asyncLib from 'async'; import log from 'loglevel'; import {Middleware} from 'redux'; import {ItemInstance, NavigatorInstanceState, SectionBlueprint, SectionInstance} from '@models/navigator'; import {collapseSectionIds, expandSectionIds, updateNavigatorInstanceState} from '@redux/reducers/navigator'; import {AppDispatch, RootState} from '@redux/store'; import sectionBlueprintMap from './sectionBlueprintMap'; const heightByContainerElementId: Record<string, number> = {}; const resizeObserver = new window.ResizeObserver(entries => { entries.forEach(entry => { const elementId = entry.target.id; const {height} = entry.contentRect; heightByContainerElementId[elementId] = height; }); }); sectionBlueprintMap.getAll().forEach(sectionBlueprint => { const element = document.getElementById(sectionBlueprint.containerElementId); if (!element) { throw new Error( `[SectionBlueprint]: Couldn't find container element with id ${sectionBlueprint.containerElementId}` ); } resizeObserver.observe(element); }); const getContainerElementHeight = (containerElementId: string) => { if (heightByContainerElementId[containerElementId]) { return heightByContainerElementId[containerElementId]; } const element = document.getElementById(containerElementId); if (!element) { return window.innerHeight; } resizeObserver.observe(element); return element.getBoundingClientRect().height; }; const fullScopeCache: Record<string, any> = {}; const pickPartialRecord = (record: Record<string, any>, keys: string[]) => { return Object.entries(record) .filter(([key]) => keys.includes(key)) .reduce<Record<string, any>>((acc, [k, v]) => { acc[k] = v; return acc; }, {}); }; const hasNavigatorInstanceStateChanged = ( navigatorState: NavigatorInstanceState, newNavigatorInstanceState: NavigatorInstanceState ) => { const {itemInstanceMap, sectionInstanceMap} = newNavigatorInstanceState; return ( !shallowEqual(pickPartialRecord(navigatorState.itemInstanceMap, Object.keys(itemInstanceMap)), itemInstanceMap) || !shallowEqual( pickPartialRecord(navigatorState.sectionInstanceMap, Object.keys(sectionInstanceMap)), sectionInstanceMap ) ); }; function isScrolledIntoView(elementId: string, containerElementHeight: number) { const element = document.getElementById(elementId); const boundingClientRect = element?.getBoundingClientRect(); if (!boundingClientRect) { return false; } const elementTop = boundingClientRect.top; const elementBottom = boundingClientRect.bottom; return elementTop < containerElementHeight && elementBottom >= 0; } function computeItemScrollIntoView(sectionInstance: SectionInstance, itemInstanceMap: Record<string, ItemInstance>) { const sectionBlueprint = sectionBlueprintMap.getById(sectionInstance.id); const containerElementHeight = getContainerElementHeight(sectionBlueprint.containerElementId); const allDescendantVisibleItems: ItemInstance[] = (sectionInstance.visibleDescendantItemIds || []).map( itemId => itemInstanceMap[itemId] ); const selectedItem = allDescendantVisibleItems.find(i => i.isSelected); if (selectedItem) { if (!isScrolledIntoView(selectedItem.id, containerElementHeight)) { selectedItem.shouldScrollIntoView = true; } return; } const highlightedItems = allDescendantVisibleItems.filter(i => i.isHighlighted); const isAnyHighlightedItemInView = highlightedItems.some(i => isScrolledIntoView(i.id, containerElementHeight)); if (highlightedItems.length > 0 && !isAnyHighlightedItemInView) { highlightedItems[0].shouldScrollIntoView = true; } } function computeSectionCheckable( sectionBlueprint: SectionBlueprint<any>, sectionInstance: SectionInstance, sectionScope: Record<string, any> ) { if (!sectionBlueprint.builder?.makeCheckable || !sectionInstance.visibleDescendantItemIds) { sectionInstance.checkable = undefined; return; } const {checkedItemIds, checkItemsActionCreator, uncheckItemsActionCreator} = sectionBlueprint.builder.makeCheckable(sectionScope); let nrOfCheckedItems = 0; sectionInstance.visibleDescendantItemIds.forEach(itemId => { if (checkedItemIds.includes(itemId)) { nrOfCheckedItems += 1; } }); const isChecked = nrOfCheckedItems === 0 ? 'unchecked' : nrOfCheckedItems < sectionInstance.visibleDescendantItemIds.length ? 'partial' : 'checked'; sectionInstance.checkable = { value: isChecked, checkItemsAction: checkItemsActionCreator(sectionInstance.visibleDescendantItemIds), uncheckItemsAction: uncheckItemsActionCreator(sectionInstance.visibleDescendantItemIds), }; } /** * Compute the visibility of each section based on the visibility of it's children * Compute the array of all visible descendant sections for each section */ function computeSectionVisibility( sectionInstance: SectionInstance, sectionInstanceMap: Record<string, SectionInstance> ): [boolean, string[] | undefined, string[] | undefined] { const sectionBlueprint = sectionBlueprintMap.getById(sectionInstance.id); let visibleDescendantItemIds: string[] = []; if (sectionBlueprint.childSectionIds && sectionBlueprint.childSectionIds.length > 0) { const childSectionVisibilityMap: Record<string, boolean> = {}; sectionBlueprint.childSectionIds.forEach(childSectionId => { const childSectionInstance = sectionInstanceMap[childSectionId]; const [isChildSectionVisible, visibleDescendantSectionIdsOfChildSection, visibleDescendantItemIdsOfChildSection] = computeSectionVisibility(childSectionInstance, sectionInstanceMap); if (visibleDescendantSectionIdsOfChildSection) { if (sectionInstance.visibleDescendantSectionIds) { sectionInstance.visibleDescendantSectionIds.push(...visibleDescendantSectionIdsOfChildSection); } else { sectionInstance.visibleDescendantSectionIds = [...visibleDescendantSectionIdsOfChildSection]; } } if (visibleDescendantItemIdsOfChildSection) { visibleDescendantItemIds.push(...visibleDescendantItemIdsOfChildSection); } childSectionVisibilityMap[childSectionId] = isChildSectionVisible; if (isChildSectionVisible) { if (sectionInstance.visibleChildSectionIds) { sectionInstance.visibleChildSectionIds.push(childSectionId); } else { sectionInstance.visibleChildSectionIds = [childSectionId]; } } }); if (sectionInstance.visibleChildSectionIds) { if (sectionInstance.visibleDescendantSectionIds) { sectionInstance.visibleDescendantSectionIds.push(...sectionInstance.visibleChildSectionIds); sectionInstance.visibleDescendantSectionIds = [...new Set(sectionInstance.visibleDescendantSectionIds)]; } else { sectionInstance.visibleDescendantSectionIds = [...sectionInstance.visibleChildSectionIds]; } } sectionInstance.isVisible = sectionInstance.isVisible || Object.values(childSectionVisibilityMap).some(isVisible => isVisible === true); } if (sectionInstance.visibleItemIds) { visibleDescendantItemIds.push(...sectionInstance.visibleItemIds); } sectionInstance.visibleDescendantItemIds = visibleDescendantItemIds; return [ sectionInstance.isVisible, sectionInstance.visibleDescendantSectionIds, sectionInstance.visibleDescendantItemIds, ]; } /** * Build the section and item instances based on the registered section blueprints */ const processSectionBlueprints = (state: RootState, dispatch: AppDispatch) => { const sectionInstanceMap: Record<string, SectionInstance> = {}; const itemInstanceMap: Record<string, ItemInstance> = {}; const fullScope: Record<string, any> = {}; const scopeKeysBySectionId: Record<string, string[]> = {}; const isChangedByScopeKey: Record<string, boolean> = {}; // check if anything from the full scope has changed and store the keys of changed values asyncLib.each(sectionBlueprintMap.getAll(), async sectionBlueprint => { const sectionScope = sectionBlueprint.getScope(state); const sectionScopeKeys: string[] = []; Object.entries(sectionScope).forEach(([key, value]) => { sectionScopeKeys.push(key); if (fullScope[key]) { return; } fullScope[key] = value; if (!shallowEqual(fullScopeCache[key], value)) { isChangedByScopeKey[key] = true; } else { isChangedByScopeKey[key] = false; } }); scopeKeysBySectionId[sectionBlueprint.id] = sectionScopeKeys; }); if (Object.values(isChangedByScopeKey).every(isChanged => isChanged === false)) { log.debug('fullScope did not change.'); return; } asyncLib.each(sectionBlueprintMap.getAll(), async sectionBlueprint => { const sectionScopeKeys = scopeKeysBySectionId[sectionBlueprint.id]; const hasSectionScopeChanged = Object.entries(isChangedByScopeKey).some( ([key, value]) => sectionScopeKeys.includes(key) && value === true ); if (!hasSectionScopeChanged) { log.debug(`Section ${sectionBlueprint.id} scope did not change`); return; } const sectionScope = pickPartialRecord(fullScope, scopeKeysBySectionId[sectionBlueprint.id]); const sectionBuilder = sectionBlueprint.builder; const itemBlueprint = sectionBlueprint.itemBlueprint; let itemInstances: ItemInstance[] | undefined; let rawItems: any[] = []; // build the item instances if the section has the itemBlueprint defined if (itemBlueprint) { rawItems = (sectionBlueprint.builder?.getRawItems && sectionBlueprint.builder.getRawItems(sectionScope)) || []; const itemBuilder = itemBlueprint.builder; itemInstances = rawItems?.map(rawItem => { return { name: itemBlueprint.getName(rawItem, sectionScope), id: itemBlueprint.getInstanceId(rawItem, sectionScope), sectionId: sectionBlueprint.id, rootSectionId: sectionBlueprint.rootSectionId, isSelected: Boolean(itemBuilder?.isSelected ? itemBuilder.isSelected(rawItem, sectionScope) : false), isHighlighted: Boolean(itemBuilder?.isHighlighted ? itemBuilder.isHighlighted(rawItem, sectionScope) : false), isVisible: Boolean(itemBuilder?.isVisible ? itemBuilder.isVisible(rawItem, sectionScope) : true), isDirty: Boolean(itemBuilder?.isDirty ? itemBuilder.isDirty(rawItem, sectionScope) : false), isDisabled: Boolean(itemBuilder?.isDisabled ? itemBuilder.isDisabled(rawItem, sectionScope) : false), isCheckable: Boolean(itemBuilder?.isCheckable ? itemBuilder.isCheckable(rawItem, sectionScope) : false), isChecked: Boolean(itemBuilder?.isChecked ? itemBuilder.isChecked(rawItem, sectionScope) : false), meta: itemBuilder?.getMeta ? itemBuilder.getMeta(rawItem, sectionScope) : undefined, }; }); itemInstances?.forEach(itemInstance => { itemInstanceMap[itemInstance.id] = itemInstance; }); } const isSectionSelected = Boolean(itemInstances?.some(i => i.isSelected === true)); const isSectionHighlighted = Boolean(itemInstances?.some(i => i.isHighlighted === true)); const isSectionInitialized = Boolean( sectionBuilder?.isInitialized ? sectionBuilder.isInitialized(sectionScope, rawItems) : true ); const isSectionEmpty = Boolean( sectionBuilder?.isEmpty ? sectionBuilder.isEmpty(sectionScope, rawItems, itemInstances) : false ); const sectionGroups = sectionBuilder?.getGroups ? sectionBuilder.getGroups(sectionScope) : []; const sectionInstanceGroups = sectionGroups.map(g => ({ ...g, visibleItemIds: g.itemIds.filter(itemId => itemInstanceMap[itemId].isVisible === true), })); const visibleItemIds = itemInstances?.filter(i => i.isVisible === true).map(i => i.id) || []; const visibleGroupIds = sectionInstanceGroups.filter(g => g.visibleItemIds.length > 0).map(g => g.id); const sectionInstance: SectionInstance = { id: sectionBlueprint.id, rootSectionId: sectionBlueprint.rootSectionId, itemIds: itemInstances?.map(i => i.id) || [], groups: sectionInstanceGroups, isLoading: Boolean(sectionBuilder?.isLoading ? sectionBuilder.isLoading(sectionScope, rawItems) : false), isVisible: Boolean(sectionBuilder?.shouldBeVisibleBeforeInitialized === true && !isSectionInitialized) || (sectionBlueprint && sectionBlueprint.customization?.emptyDisplay && isSectionEmpty) || (isSectionInitialized && Boolean(sectionBuilder?.isVisible ? sectionBuilder.isVisible(sectionScope, rawItems) : true) && (visibleItemIds.length > 0 || visibleGroupIds.length > 0)), isInitialized: isSectionInitialized, isSelected: isSectionSelected, isHighlighted: isSectionHighlighted, isEmpty: isSectionEmpty, meta: sectionBuilder?.getMeta ? sectionBuilder.getMeta(sectionScope, rawItems) : undefined, shouldExpand: Boolean( itemInstances?.some(itemInstance => itemInstance.isVisible && itemInstance.shouldScrollIntoView) ), visibleItemIds, visibleGroupIds, }; sectionInstanceMap[sectionBlueprint.id] = sectionInstance; }); const sectionInstanceRoots = Object.values(sectionInstanceMap).filter(sectionInstance => { const sectionBlueprint = sectionBlueprintMap.getById(sectionInstance.id); return sectionBlueprint.rootSectionId === sectionBlueprint.id; }); asyncLib.each(sectionInstanceRoots, async sectionInstanceRoot => computeSectionVisibility(sectionInstanceRoot, sectionInstanceMap) ); // this has to run after the `computeSectionVisibility` because it depends on the `section.visibleDescendantItemIds` asyncLib.each(sectionInstanceRoots, async sectionInstanceRoot => computeItemScrollIntoView(sectionInstanceRoot, itemInstanceMap) ); // this has to run after the `computeSectionVisibility` because it depends on the `section.visibleDescendantItemIds` asyncLib.each(Object.values(sectionInstanceMap), async sectionInstance => { const sectionBlueprint = sectionBlueprintMap.getById(sectionInstance.id); const sectionScope = pickPartialRecord(fullScope, scopeKeysBySectionId[sectionBlueprint.id]); computeSectionCheckable(sectionBlueprint, sectionInstance, sectionScope); }); if (Object.keys(itemInstanceMap).length === 0 && Object.keys(sectionInstanceMap).length === 0) { return; } const newNavigatorInstanceState: NavigatorInstanceState = { sectionInstanceMap, itemInstanceMap, }; if (hasNavigatorInstanceStateChanged(state.navigator, newNavigatorInstanceState)) { dispatch(updateNavigatorInstanceState(newNavigatorInstanceState)); } }; export const sectionBlueprintMiddleware: Middleware = store => next => action => { next(action); // ignore actions that will not affect any section scope if ( action?.type === updateNavigatorInstanceState.type || action?.type === expandSectionIds.type || action?.type === collapseSectionIds.type ) { return; } const state: RootState = store.getState(); processSectionBlueprints(state, store.dispatch); };
the_stack
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ATN } from "antlr4ts/atn/ATN"; import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer"; import { CharStream } from "antlr4ts/CharStream"; import { Lexer } from "antlr4ts/Lexer"; import { LexerATNSimulator } from "antlr4ts/atn/LexerATNSimulator"; import { NotNull } from "antlr4ts/Decorators"; import { Override } from "antlr4ts/Decorators"; import { RuleContext } from "antlr4ts/RuleContext"; import { Vocabulary } from "antlr4ts/Vocabulary"; import { VocabularyImpl } from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; export class LGFileLexer extends Lexer { public static readonly NEWLINE = 1; public static readonly OPTION = 2; public static readonly COMMENT = 3; public static readonly IMPORT = 4; public static readonly TEMPLATE_NAME_LINE = 5; public static readonly INLINE_MULTILINE = 6; public static readonly MULTILINE_PREFIX = 7; public static readonly TEMPLATE_BODY = 8; public static readonly INVALID_LINE = 9; public static readonly MULTILINE_SUFFIX = 10; public static readonly ESCAPE_CHARACTER = 11; public static readonly MULTILINE_TEXT = 12; public static readonly MULTILINE_MODE = 1; // tslint:disable:no-trailing-whitespace public static readonly channelNames: string[] = [ "DEFAULT_TOKEN_CHANNEL", "HIDDEN", ]; // tslint:disable:no-trailing-whitespace public static readonly modeNames: string[] = [ "DEFAULT_MODE", "MULTILINE_MODE", ]; public static readonly ruleNames: string[] = [ "WHITESPACE", "NEWLINE", "OPTION", "COMMENT", "IMPORT", "TEMPLATE_NAME_LINE", "INLINE_MULTILINE", "MULTILINE_PREFIX", "TEMPLATE_BODY", "INVALID_LINE", "MULTILINE_SUFFIX", "ESCAPE_CHARACTER", "MULTILINE_TEXT", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "'```'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, "NEWLINE", "OPTION", "COMMENT", "IMPORT", "TEMPLATE_NAME_LINE", "INLINE_MULTILINE", "MULTILINE_PREFIX", "TEMPLATE_BODY", "INVALID_LINE", "MULTILINE_SUFFIX", "ESCAPE_CHARACTER", "MULTILINE_TEXT", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(LGFileLexer._LITERAL_NAMES, LGFileLexer._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return LGFileLexer.VOCABULARY; } // tslint:enable:no-trailing-whitespace startTemplate = false; constructor(input: CharStream) { super(input); this._interp = new LexerATNSimulator(LGFileLexer._ATN, this); } // @Override public get grammarFileName(): string { return "LGFileLexer.g4"; } // @Override public get ruleNames(): string[] { return LGFileLexer.ruleNames; } // @Override public get serializedATN(): string { return LGFileLexer._serializedATN; } // @Override public get channelNames(): string[] { return LGFileLexer.channelNames; } // @Override public get modeNames(): string[] { return LGFileLexer.modeNames; } // @Override public action(_localctx: RuleContext, ruleIndex: number, actionIndex: number): void { switch (ruleIndex) { case 5: this.TEMPLATE_NAME_LINE_action(_localctx, actionIndex); break; } } private TEMPLATE_NAME_LINE_action(_localctx: RuleContext, actionIndex: number): void { switch (actionIndex) { case 0: this.startTemplate = true; break; } } // @Override public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean { switch (ruleIndex) { case 2: return this.OPTION_sempred(_localctx, predIndex); case 3: return this.COMMENT_sempred(_localctx, predIndex); case 4: return this.IMPORT_sempred(_localctx, predIndex); case 5: return this.TEMPLATE_NAME_LINE_sempred(_localctx, predIndex); case 6: return this.INLINE_MULTILINE_sempred(_localctx, predIndex); case 7: return this.MULTILINE_PREFIX_sempred(_localctx, predIndex); case 8: return this.TEMPLATE_BODY_sempred(_localctx, predIndex); case 9: return this.INVALID_LINE_sempred(_localctx, predIndex); } return true; } private OPTION_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 0: return !this.startTemplate ; } return true; } private COMMENT_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 1: return !this.startTemplate ; } return true; } private IMPORT_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 2: return !this.startTemplate ; } return true; } private TEMPLATE_NAME_LINE_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 3: return this._tokenStartCharPositionInLine == 0 ; } return true; } private INLINE_MULTILINE_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 4: return this.startTemplate && this._tokenStartCharPositionInLine == 0 ; } return true; } private MULTILINE_PREFIX_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 5: return this.startTemplate && this._tokenStartCharPositionInLine == 0 ; } return true; } private TEMPLATE_BODY_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 6: return this.startTemplate ; } return true; } private INVALID_LINE_sempred(_localctx: RuleContext, predIndex: number): boolean { switch (predIndex) { case 7: return !this.startTemplate ; } return true; } public static readonly _serializedATN: string = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x02\x0E\xD6\b\x01" + "\b\x01\x04\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06" + "\t\x06\x04\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f" + "\x04\r\t\r\x04\x0E\t\x0E\x03\x02\x03\x02\x03\x03\x05\x03\"\n\x03\x03\x03" + "\x03\x03\x03\x04\x07\x04\'\n\x04\f\x04\x0E\x04*\v\x04\x03\x04\x03\x04" + "\x07\x04.\n\x04\f\x04\x0E\x041\v\x04\x03\x04\x03\x04\x03\x04\x03\x04\x06" + "\x047\n\x04\r\x04\x0E\x048\x03\x04\x03\x04\x03\x05\x07\x05>\n\x05\f\x05" + "\x0E\x05A\v\x05\x03\x05\x03\x05\x07\x05E\n\x05\f\x05\x0E\x05H\v\x05\x03" + "\x05\x03\x05\x03\x06\x07\x06M\n\x06\f\x06\x0E\x06P\v\x06\x03\x06\x03\x06" + "\x07\x06T\n\x06\f\x06\x0E\x06W\v\x06\x03\x06\x03\x06\x03\x06\x07\x06\\" + "\n\x06\f\x06\x0E\x06_\v\x06\x03\x06\x03\x06\x07\x06c\n\x06\f\x06\x0E\x06" + "f\v\x06\x03\x06\x03\x06\x03\x07\x07\x07k\n\x07\f\x07\x0E\x07n\v\x07\x03" + "\x07\x03\x07\x07\x07r\n\x07\f\x07\x0E\x07u\v\x07\x03\x07\x03\x07\x03\x07" + "\x03\b\x07\b{\n\b\f\b\x0E\b~\v\b\x03\b\x03\b\x07\b\x82\n\b\f\b\x0E\b\x85" + "\v\b\x03\b\x03\b\x03\b\x03\b\x03\b\x07\b\x8C\n\b\f\b\x0E\b\x8F\v\b\x03" + "\b\x03\b\x03\b\x03\b\x03\b\x07\b\x96\n\b\f\b\x0E\b\x99\v\b\x03\b\x03\b" + "\x03\t\x07\t\x9E\n\t\f\t\x0E\t\xA1\v\t\x03\t\x03\t\x07\t\xA5\n\t\f\t\x0E" + "\t\xA8\v\t\x03\t\x03\t\x03\t\x03\t\x03\t\x07\t\xAF\n\t\f\t\x0E\t\xB2\v" + "\t\x03\t\x03\t\x03\t\x03\t\x03\n\x03\n\x03\n\x07\n\xBB\n\n\f\n\x0E\n\xBE" + "\v\n\x03\v\x03\v\x03\v\x07\v\xC3\n\v\f\v\x0E\v\xC6\v\v\x03\f\x03\f\x03" + "\f\x03\f\x03\f\x03\f\x03\r\x03\r\x05\r\xD0\n\r\x03\x0E\x06\x0E\xD3\n\x0E" + "\r\x0E\x0E\x0E\xD4\x05U]\xD4\x02\x02\x0F\x04\x02\x02\x06\x02\x03\b\x02" + "\x04\n\x02\x05\f\x02\x06\x0E\x02\x07\x10\x02\b\x12\x02\t\x14\x02\n\x16" + "\x02\v\x18\x02\f\x1A\x02\r\x1C\x02\x0E\x04\x02\x03\x06\x06\x02\v\v\"\"" + "\xA2\xA2\uFF01\uFF01\x04\x02\f\f\x0F\x0F\x06\x02\f\f\x0F\x0F]]__\x05\x02" + "\f\f\x0F\x0F*+\x02\xEA\x02\x06\x03\x02\x02\x02\x02\b\x03\x02\x02\x02\x02" + "\n\x03\x02\x02\x02\x02\f\x03\x02\x02\x02\x02\x0E\x03\x02\x02\x02\x02\x10" + "\x03\x02\x02\x02\x02\x12\x03\x02\x02\x02\x02\x14\x03\x02\x02\x02\x02\x16" + "\x03\x02\x02\x02\x03\x18\x03\x02\x02\x02\x03\x1A\x03\x02\x02\x02\x03\x1C" + "\x03\x02\x02\x02\x04\x1E\x03\x02\x02\x02\x06!\x03\x02\x02\x02\b(\x03\x02" + "\x02\x02\n?\x03\x02\x02\x02\fN\x03\x02\x02\x02\x0El\x03\x02\x02\x02\x10" + "|\x03\x02\x02\x02\x12\x9F\x03\x02\x02\x02\x14\xB7\x03\x02\x02\x02\x16" + "\xBF\x03\x02\x02\x02\x18\xC7\x03\x02\x02\x02\x1A\xCD\x03\x02\x02\x02\x1C" + "\xD2\x03\x02\x02\x02\x1E\x1F\t\x02\x02\x02\x1F\x05\x03\x02\x02\x02 \"" + "\x07\x0F\x02\x02! \x03\x02\x02\x02!\"\x03\x02\x02\x02\"#\x03\x02\x02\x02" + "#$\x07\f\x02\x02$\x07\x03\x02\x02\x02%\'\x05\x04\x02\x02&%\x03\x02\x02" + "\x02\'*\x03\x02\x02\x02(&\x03\x02\x02\x02()\x03\x02\x02\x02)+\x03\x02" + "\x02\x02*(\x03\x02\x02\x02+/\x07@\x02\x02,.\x05\x04\x02\x02-,\x03\x02" + "\x02\x02.1\x03\x02\x02\x02/-\x03\x02\x02\x02/0\x03\x02\x02\x0202\x03\x02" + "\x02\x021/\x03\x02\x02\x0223\x07#\x02\x0234\x07%\x02\x0246\x03\x02\x02" + "\x0257\n\x03\x02\x0265\x03\x02\x02\x0278\x03\x02\x02\x0286\x03\x02\x02" + "\x0289\x03\x02\x02\x029:\x03\x02\x02\x02:;\x06\x04\x02\x02;\t\x03\x02" + "\x02\x02<>\x05\x04\x02\x02=<\x03\x02\x02\x02>A\x03\x02\x02\x02?=\x03\x02" + "\x02\x02?@\x03\x02\x02\x02@B\x03\x02\x02\x02A?\x03\x02\x02\x02BF\x07@" + "\x02\x02CE\n\x03\x02\x02DC\x03\x02\x02\x02EH\x03\x02\x02\x02FD\x03\x02" + "\x02\x02FG\x03\x02\x02\x02GI\x03\x02\x02\x02HF\x03\x02\x02\x02IJ\x06\x05" + "\x03\x02J\v\x03\x02\x02\x02KM\x05\x04\x02\x02LK\x03\x02\x02\x02MP\x03" + "\x02\x02\x02NL\x03\x02\x02\x02NO\x03\x02\x02\x02OQ\x03\x02\x02\x02PN\x03" + "\x02\x02\x02QU\x07]\x02\x02RT\n\x04\x02\x02SR\x03\x02\x02\x02TW\x03\x02" + "\x02\x02UV\x03\x02\x02\x02US\x03\x02\x02\x02VX\x03\x02\x02\x02WU\x03\x02" + "\x02\x02XY\x07_\x02\x02Y]\x07*\x02\x02Z\\\n\x05\x02\x02[Z\x03\x02\x02" + "\x02\\_\x03\x02\x02\x02]^\x03\x02\x02\x02][\x03\x02\x02\x02^`\x03\x02" + "\x02\x02_]\x03\x02\x02\x02`d\x07+\x02\x02ac\n\x03\x02\x02ba\x03\x02\x02" + "\x02cf\x03\x02\x02\x02db\x03\x02\x02\x02de\x03\x02\x02\x02eg\x03\x02\x02" + "\x02fd\x03\x02\x02\x02gh\x06\x06\x04\x02h\r\x03\x02\x02\x02ik\x05\x04" + "\x02\x02ji\x03\x02\x02\x02kn\x03\x02\x02\x02lj\x03\x02\x02\x02lm\x03\x02" + "\x02\x02mo\x03\x02\x02\x02nl\x03\x02\x02\x02os\x07%\x02\x02pr\n\x03\x02" + "\x02qp\x03\x02\x02\x02ru\x03\x02\x02\x02sq\x03\x02\x02\x02st\x03\x02\x02" + "\x02tv\x03\x02\x02\x02us\x03\x02\x02\x02vw\x06\x07\x05\x02wx\b\x07\x02" + "\x02x\x0F\x03\x02\x02\x02y{\x05\x04\x02\x02zy\x03\x02\x02\x02{~\x03\x02" + "\x02\x02|z\x03\x02\x02\x02|}\x03\x02\x02\x02}\x7F\x03\x02\x02\x02~|\x03" + "\x02\x02\x02\x7F\x83\x07/\x02\x02\x80\x82\x05\x04\x02\x02\x81\x80\x03" + "\x02\x02\x02\x82\x85\x03\x02\x02\x02\x83\x81\x03\x02\x02\x02\x83\x84\x03" + "\x02\x02\x02\x84\x86\x03\x02\x02\x02\x85\x83\x03\x02\x02\x02\x86\x87\x07" + "b\x02\x02\x87\x88\x07b\x02\x02\x88\x89\x07b\x02\x02\x89\x8D\x03\x02\x02" + "\x02\x8A\x8C\n\x03\x02\x02\x8B\x8A\x03\x02\x02\x02\x8C\x8F\x03\x02\x02" + "\x02\x8D\x8B\x03\x02\x02\x02\x8D\x8E\x03\x02\x02\x02\x8E\x90\x03\x02\x02" + "\x02\x8F\x8D\x03\x02\x02\x02\x90\x91\x07b\x02\x02\x91\x92\x07b\x02\x02" + "\x92\x93\x07b\x02\x02\x93\x97\x03\x02\x02\x02\x94\x96\x05\x04\x02\x02" + "\x95\x94\x03\x02\x02\x02\x96\x99\x03\x02\x02\x02\x97\x95\x03\x02\x02\x02" + "\x97\x98\x03\x02\x02\x02\x98\x9A\x03\x02\x02\x02\x99\x97\x03\x02\x02\x02" + "\x9A\x9B\x06\b\x06\x02\x9B\x11\x03\x02\x02\x02\x9C\x9E\x05\x04\x02\x02" + "\x9D\x9C\x03\x02\x02\x02\x9E\xA1\x03\x02\x02\x02\x9F\x9D\x03\x02\x02\x02" + "\x9F\xA0\x03\x02\x02\x02\xA0\xA2\x03\x02\x02\x02\xA1\x9F\x03\x02\x02\x02" + "\xA2\xA6\x07/\x02\x02\xA3\xA5\x05\x04\x02\x02\xA4\xA3\x03\x02\x02\x02" + "\xA5\xA8\x03\x02\x02\x02\xA6\xA4\x03\x02\x02\x02\xA6\xA7\x03\x02\x02\x02" + "\xA7\xA9\x03\x02\x02\x02\xA8\xA6\x03\x02\x02\x02\xA9\xAA\x07b\x02\x02" + "\xAA\xAB\x07b\x02\x02\xAB\xAC\x07b\x02\x02\xAC\xB0\x03\x02\x02\x02\xAD" + "\xAF\n\x03\x02\x02\xAE\xAD\x03\x02\x02\x02\xAF\xB2\x03\x02\x02\x02\xB0" + "\xAE\x03\x02\x02\x02\xB0\xB1\x03\x02\x02\x02\xB1\xB3\x03\x02\x02\x02\xB2" + "\xB0\x03\x02\x02\x02\xB3\xB4\x06\t\x07\x02\xB4\xB5\x03\x02\x02\x02\xB5" + "\xB6\b\t\x03\x02\xB6\x13\x03\x02\x02\x02\xB7\xB8\n\x03\x02\x02\xB8\xBC" + "\x06\n\b\x02\xB9\xBB\n\x03\x02\x02\xBA\xB9\x03\x02\x02\x02\xBB\xBE\x03" + "\x02\x02\x02\xBC\xBA\x03\x02\x02\x02\xBC\xBD\x03\x02\x02\x02\xBD\x15\x03" + "\x02\x02\x02\xBE\xBC\x03\x02\x02\x02\xBF\xC0\n\x03\x02\x02\xC0\xC4\x06" + "\v\t\x02\xC1\xC3\n\x03\x02\x02\xC2\xC1\x03\x02\x02\x02\xC3\xC6\x03\x02" + "\x02\x02\xC4\xC2\x03\x02\x02\x02\xC4\xC5\x03\x02\x02\x02\xC5\x17\x03\x02" + "\x02\x02\xC6\xC4\x03\x02\x02\x02\xC7\xC8\x07b\x02\x02\xC8\xC9\x07b\x02" + "\x02\xC9\xCA\x07b\x02\x02\xCA\xCB\x03\x02\x02\x02\xCB\xCC\b\f\x04\x02" + "\xCC\x19\x03\x02\x02\x02\xCD\xCF\x07^\x02\x02\xCE\xD0\n\x03\x02\x02\xCF" + "\xCE\x03\x02\x02\x02\xCF\xD0\x03\x02\x02\x02\xD0\x1B\x03\x02\x02\x02\xD1" + "\xD3\v\x02\x02\x02\xD2\xD1\x03\x02\x02\x02\xD3\xD4\x03\x02\x02\x02\xD4" + "\xD5\x03\x02\x02\x02\xD4\xD2\x03\x02\x02\x02\xD5\x1D\x03\x02\x02\x02\x1B" + "\x02\x03!(/8?FNU]dls|\x83\x8D\x97\x9F\xA6\xB0\xBC\xC4\xCF\xD4\x05\x03" + "\x07\x02\x07\x03\x02\x06\x02\x02"; public static __ATN: ATN; public static get _ATN(): ATN { if (!LGFileLexer.__ATN) { LGFileLexer.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(LGFileLexer._serializedATN)); } return LGFileLexer.__ATN; } }
the_stack
* @title: Load model * @description: * This sample shows how to load geometry models and how to add instances of them to the scene. * The sample will first request and load a dinning room model into a Scene object and when finished * you will then be able to load and remove two additional models to the same scene. */ /*{{ javascript("jslib/camera.js") }}*/ /*{{ javascript("jslib/aabbtree.js") }}*/ /*{{ javascript("jslib/effectmanager.js") }}*/ /*{{ javascript("jslib/shadermanager.js") }}*/ /*{{ javascript("jslib/texturemanager.js") }}*/ /*{{ javascript("jslib/geometry.js") }}*/ /*{{ javascript("jslib/material.js") }}*/ /*{{ javascript("jslib/light.js") }}*/ /*{{ javascript("jslib/scenenode.js") }}*/ /*{{ javascript("jslib/scene.js") }}*/ /*{{ javascript("jslib/scenedebugging.js") }}*/ /*{{ javascript("jslib/renderingcommon.js") }}*/ /*{{ javascript("jslib/forwardrendering.js") }}*/ /*{{ javascript("jslib/resourceloader.js") }}*/ /*{{ javascript("jslib/utilities.js") }}*/ /*{{ javascript("jslib/requesthandler.js") }}*/ /*{{ javascript("jslib/observer.js") }}*/ /*{{ javascript("jslib/vertexbuffermanager.js") }}*/ /*{{ javascript("jslib/indexbuffermanager.js") }}*/ /*{{ javascript("jslib/vmath.js") }}*/ /*{{ javascript("jslib/services/turbulenzservices.js") }}*/ /*{{ javascript("jslib/services/turbulenzbridge.js") }}*/ /*{{ javascript("jslib/services/gamesession.js") }}*/ /*{{ javascript("jslib/services/mappingtable.js") }}*/ /*{{ javascript("scripts/sceneloader.js") }}*/ /*{{ javascript("scripts/htmlcontrols.js") }}*/ /*global TurbulenzEngine: true */ /*global TurbulenzServices: false */ /*global RequestHandler: false */ /*global TextureManager: false */ /*global ShaderManager: false */ /*global EffectManager: false */ /*global Scene: false */ /*global SceneNode: false */ /*global SceneLoader: false */ /*global Camera: false */ /*global CameraController: false */ /*global Light: false */ /*global LightInstance: false */ /*global HTMLControls: false */ /*global ForwardRendering: false */ TurbulenzEngine.onload = function onloadFn() { var errorCallback = function errorCallback(msg) { window.alert(msg); }; // Create the engine devices objects var graphicsDeviceParameters = { }; var graphicsDevice = TurbulenzEngine.createGraphicsDevice(graphicsDeviceParameters); if (!graphicsDevice.shadingLanguageVersion) { errorCallback("No shading language support detected.\nPlease check your graphics drivers are up to date."); graphicsDevice = null; return; } // Clear the background color of the engine window if (graphicsDevice.beginFrame()) { graphicsDevice.clear([0.5, 0.5, 0.5, 1.0]); graphicsDevice.endFrame(); } var clearColor = [0.0, 0.0, 0.0, 1.0]; var mathDeviceParameters = {}; var mathDevice = TurbulenzEngine.createMathDevice(mathDeviceParameters); var inputDeviceParameters = { }; var inputDevice = TurbulenzEngine.createInputDevice(inputDeviceParameters); // Create a camera with a 60 degree FOV var camera = Camera.create(mathDevice); var halfFov = Math.tan(30 * Math.PI / 180); camera.recipViewWindowX = 1.0 / halfFov; camera.recipViewWindowY = 1.0 / halfFov; camera.updateProjectionMatrix(); var worldUp = mathDevice.v3BuildYAxis(); camera.lookAt(worldUp, worldUp, mathDevice.v3Build(0.0, 50.0, 200.0)); camera.updateViewMatrix(); var cameraController = CameraController.create(graphicsDevice, inputDevice, camera); var requestHandlerParameters = {}; var requestHandler = RequestHandler.create(requestHandlerParameters); var textureManager = TextureManager.create(graphicsDevice, requestHandler, null, errorCallback); var shaderManager = ShaderManager.create(graphicsDevice, requestHandler, null, errorCallback); var effectManager = EffectManager.create(); var scene = Scene.create(mathDevice); var sceneLoader = SceneLoader.create(); var renderer; var maxSpeed = cameraController.maxSpeed; var intervalID; var cube; var duck; var sphere; var loadingDuck = false; var loadingCube = false; var loadingSphere = false; var duckTransform = mathDevice.m43BuildIdentity(); var relPos = mathDevice.v3Build(-4.5, 4.8, -3); mathDevice.m43Translate(duckTransform, relPos); var cubeTransform = mathDevice.m43BuildIdentity(); relPos = mathDevice.v3Build(-2, 5.4, 4); mathDevice.m43Translate(cubeTransform, relPos); var sphereTransform = mathDevice.m43BuildIdentity(); relPos = mathDevice.v3Build(-6, 5.8, 2); mathDevice.m43Translate(sphereTransform, relPos); var buttonLoadDuck; var buttonRemoveDuck; var buttonLoadCube; var buttonRemoveCube; var buttonLoadSphere; var buttonRemoveSphere; var buttonsAvailable; var loadModelDuck = function loadModelDuckFn() { // load in the duck sceneLoader.load({scene : scene, append : true, assetPath : "models/duck.dae", keepLights : false, keepCameras : false, graphicsDevice : graphicsDevice, mathDevice : mathDevice, textureManager : textureManager, shaderManager : shaderManager, effectManager : effectManager, requestHandler : requestHandler, baseMatrix : duckTransform, disabled : true }); // we check this flag in the update loop to know when to call sceneLoader.complete() loadingDuck = true; if (buttonsAvailable) { buttonLoadDuck.disabled = true; } }; var removeModelDuck = function removeModelDuckFn() { // Remove the duck from the scene scene.removeRootNode(duck); // Destroy the duck // Set references to null duck.destroy(); duck = null; if (buttonsAvailable) { buttonRemoveDuck.disabled = true; buttonLoadDuck.disabled = false; } }; var loadModelCube = function loadModelCubeFn() { // Load in the cube sceneLoader.load({ scene : scene, append : true, assetPath : "models/cube.dae", keepLights : false, graphicsDevice : graphicsDevice, mathDevice : mathDevice, textureManager : textureManager, shaderManager : shaderManager, effectManager : effectManager, requestHandler : requestHandler, baseMatrix : cubeTransform, disabled : true }); // we check this flag in the update loop to know when to call sceneLoader.complete() loadingCube = true; if (buttonsAvailable) { buttonLoadCube.disabled = true; } }; var removeModelCube = function removeModelCubeFn() { // Remove the cube from the scene scene.removeRootNode(cube); // Set references to null cube.destroy(); cube = null; if (buttonsAvailable) { buttonRemoveCube.disabled = true; buttonLoadCube.disabled = false; } }; var loadModelSphere = function loadModelSphereFn() { // Load in the sphere sceneLoader.load({ scene : scene, append : true, assetPath : "models/sphere.dae", keepLights : false, graphicsDevice : graphicsDevice, mathDevice : mathDevice, textureManager : textureManager, shaderManager : shaderManager, effectManager : effectManager, requestHandler : requestHandler, baseMatrix : sphereTransform, disabled : true }); // we check this flag in the update loop to know when to call sceneLoader.complete() loadingSphere = true; if (buttonsAvailable) { buttonLoadSphere.disabled = true; } }; var removeModelSphere = function removeModelSphereFn() { // Remove the sphere from the scene scene.removeRootNode(sphere); // Set references to null sphere.destroy(); sphere = null; if (buttonsAvailable) { buttonRemoveSphere.disabled = true; buttonLoadSphere.disabled = false; } }; // Link up with the HTML controls on the page var htmlControls = HTMLControls.create(); htmlControls.addButtonControl({ id: "buttonLoadDuck", value: "Load", fn: loadModelDuck }); htmlControls.addButtonControl({ id: "buttonRemoveDuck", value: "Remove", fn: removeModelDuck }); htmlControls.addButtonControl({ id: "buttonLoadCube", value: "Load", fn: loadModelCube }); htmlControls.addButtonControl({ id: "buttonRemoveCube", value: "Remove", fn: removeModelCube }); htmlControls.addButtonControl({ id: "buttonLoadSphere", value: "Load", fn: loadModelSphere }); htmlControls.addButtonControl({ id: "buttonRemoveSphere", value: "Remove", fn: removeModelSphere }); buttonLoadDuck = document.getElementById("buttonLoadDuck"); buttonRemoveDuck = document.getElementById("buttonRemoveDuck"); buttonLoadCube = document.getElementById("buttonLoadCube"); buttonRemoveCube = document.getElementById("buttonRemoveCube"); buttonLoadSphere = document.getElementById("buttonLoadSphere"); buttonRemoveSphere = document.getElementById("buttonRemoveSphere"); // check that we can access the buttons buttonsAvailable = buttonLoadDuck && buttonRemoveDuck && buttonLoadCube && buttonRemoveCube && buttonLoadSphere && buttonRemoveSphere; if (buttonsAvailable) { buttonLoadDuck.disabled = true; buttonLoadCube.disabled = true; buttonLoadSphere.disabled = true; buttonRemoveDuck.disabled = true; buttonRemoveCube.disabled = true; buttonRemoveSphere.disabled = true; } htmlControls.register(); // Create a callback for post scene load to update the camera position var loadCubeFinished = function loadCubeFinishedFn(scene) { loadingCube = false; cube = scene.findNode("cube"); cube.enableHierarchy(true); buttonRemoveCube.disabled = false; }; var loadDuckFinished = function loadDuckFinishedFn(scene) { loadingDuck = false; duck = scene.findNode("LOD3sp"); duck.enableHierarchy(true); buttonRemoveDuck.disabled = false; }; var loadSphereFinished = function loadSphereFinishedFn(scene) { loadingSphere = false; sphere = scene.findNode("sphere"); sphere.enableHierarchy(true); buttonRemoveSphere.disabled = false; }; var v3Build = mathDevice.v3Build; // Callback for when the scene is loaded to add some lights function loadSceneFinished(scene) { var addPointLight = function addLightFn(lightName, lightMaterial, position, color) { var light = Light.create( { name : lightName, color : mathDevice.v3Build(color[0], color[1], color[2]), point : true, shadows : true, halfExtents: v3Build.call(mathDevice, 40, 40, 40), origin: v3Build.call(mathDevice, 0, 10, 0), material : lightMaterial }); scene.addLight(light); var lightMatrix = mathDevice.m43BuildTranslation(v3Build.apply(mathDevice, position)); var lightNode = SceneNode.create( { name: lightName + "-node", local: lightMatrix }); lightNode.addLightInstance(LightInstance.create(light)); scene.addRootNode(lightNode); }; var lightMaterialData = { effect: "lambert", parameters : { lightfalloff: "textures/default_light.png", lightprojection: "textures/default_light.png" } }; scene.loadMaterial(graphicsDevice, textureManager, effectManager, "defaultLightMaterial", lightMaterialData); var lightMaterial = scene.getMaterial("defaultLightMaterial"); // Add some lights into the scene addPointLight("globalLight", lightMaterial, [-3.5, 15, -0.5], [1, 1, 1]); scene.addLight(Light.create({name : "ambient", ambient : true, color : [0.1, 0.1, 0.1]})); if (buttonsAvailable) { buttonLoadDuck.disabled = false; buttonLoadCube.disabled = false; buttonLoadSphere.disabled = false; } } var previousFrameTime; // Create some rendering callbacks to pass to the renderer function drawExtraDecalsFn() { } function drawExtraTransparentFn() { } function drawDebugFn() { } var update = function updateFn() { var currentTime = TurbulenzEngine.time; var deltaTime = (currentTime - previousFrameTime); if (deltaTime > 0.1) { deltaTime = 0.1; } cameraController.maxSpeed = (deltaTime * maxSpeed); // Update the input device inputDevice.update(); cameraController.update(); // Update the aspect ratio of the camera in case of window resizes var deviceWidth = graphicsDevice.width; var deviceHeight = graphicsDevice.height; var aspectRatio = (deviceWidth / deviceHeight); if (aspectRatio !== camera.aspectRatio) { camera.aspectRatio = aspectRatio; camera.updateProjectionMatrix(); } camera.updateViewProjectionMatrix(); // If the duck is loading then check if it is complete if (loadingDuck && sceneLoader.complete()) { loadDuckFinished(scene); } else if (loadingCube && sceneLoader.complete()) { loadCubeFinished(scene); } else if (loadingSphere && sceneLoader.complete()) { loadSphereFinished(scene); } scene.update(); renderer.update(graphicsDevice, camera, scene, currentTime); if (graphicsDevice.beginFrame()) { renderer.draw(graphicsDevice, clearColor, drawExtraDecalsFn, drawExtraTransparentFn, drawDebugFn); graphicsDevice.endFrame(); } previousFrameTime = currentTime; }; var loadingLoop = function loadingLoopFn() { if (sceneLoader.complete()) { // Register the mainLoop callback as the new interval TurbulenzEngine.clearInterval(intervalID); // Move the camera to look at the scene camera.lookAt(mathDevice.v3Build(-3.5, 5, -0.5), worldUp, mathDevice.v3Build(-13, 10, 8)); camera.updateViewMatrix(); camera.updateProjectionMatrix(); maxSpeed = 30; renderer.updateShader(shaderManager); intervalID = TurbulenzEngine.setInterval(update, 1000 / 60); } }; // Start calling the loading loop at 10Hz intervalID = TurbulenzEngine.setInterval(loadingLoop, 1000 / 10); previousFrameTime = TurbulenzEngine.time; var loadAssets = function loadAssetsFn() { // Renderer for the scene (requires shader assets). renderer = ForwardRendering.create(graphicsDevice, mathDevice, shaderManager, effectManager, {}); // Load the diningroom sceneLoader.load({ scene : scene, append : true, assetPath : "models/diningroom.dae", keepLights : true, graphicsDevice : graphicsDevice, mathDevice : mathDevice, textureManager : textureManager, shaderManager : shaderManager, effectManager : effectManager, requestHandler: requestHandler, postSceneLoadFn : loadSceneFinished }); }; var mappingTableReceived = function mappingTableReceivedFn(mappingTable) { textureManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); shaderManager.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); sceneLoader.setPathRemapping(mappingTable.urlMapping, mappingTable.assetPrefix); loadAssets(); }; var gameSessionCreated = function gameSessionCreatedFn(gameSession) { TurbulenzServices.createMappingTable(requestHandler, gameSession, mappingTableReceived); }; var gameSession = TurbulenzServices.createGameSession(requestHandler, gameSessionCreated); // Create a scene destroy callback to run when the window is closed TurbulenzEngine.onunload = function destroyScene() { TurbulenzEngine.clearInterval(intervalID); if (gameSession) { gameSession.destroy(); gameSession = null; } requestHandler = null; sceneLoader = null; if (scene) { scene.destroy(); scene = null; } htmlControls = null; effectManager = null; if (textureManager) { textureManager.destroy(); textureManager = null; } if (shaderManager) { shaderManager.destroy(); shaderManager = null; } if (renderer) { renderer.destroy(); renderer = null; } cameraController = null; camera = null; TurbulenzEngine.flush(); inputDevice = null; graphicsDevice = null; mathDevice = null; }; };
the_stack
import { html } from 'lit'; import '@cds/core/alert/register.js'; import '@cds/core/icon/register.js'; import { CdsAlert, getIconStatusTuple, iconShapeIsAlertStatusType } from '@cds/core/alert'; import { CdsIcon } from '@cds/core/icon/icon.element.js'; import { infoStandardIcon } from '@cds/core/icon/shapes/info-standard.js'; import { componentIsStable, createTestElement, getComponentSlotContent, onceEvent, removeTestElement, } from '@cds/core/test'; import { CdsInternalCloseButton } from '@cds/core/internal-components/close-button'; import { I18nService } from '@cds/core/internal'; describe('Alert element – ', () => { let testElement: HTMLElement; let component: CdsAlert; const placeholderText = 'I am a default alert with no attributes.'; const alertStatusIconSelector = '.alert-status-icon'; describe('Lightweight alerts: ', () => { beforeEach(async () => { testElement = await createTestElement(html`<cds-alert>${placeholderText}</cds-alert>`); component = testElement.querySelector<CdsAlert>('cds-alert'); }); afterEach(() => { removeTestElement(testElement); }); it('should slot the component', async () => { await componentIsStable(component); const slots = getComponentSlotContent(component); expect(slots.default).toBe(`${placeholderText}`); }); it('should not show alert-actions', async () => { await componentIsStable(component); expect(component.querySelectorAll('.alert-actions-wrapper').length).toBe(0); }); it('should not be closable', async () => { await componentIsStable(component); expect(component.hasAttribute('closable')).toBe(false); component.closable = true; await componentIsStable(component); expect(component.querySelectorAll('cds-internal-close-button').length).toBe(0); }); }); describe('custom icons: ', () => { let customComponent: CdsAlert; beforeEach(async () => { testElement = await createTestElement(html` <cds-alert id="defaultAlert">${placeholderText}</cds-alert> <cds-alert id="customAlert"><cds-icon shape="ohai"></cds-icon>${placeholderText}</cds-alert> `); component = testElement.querySelector<CdsAlert>('#defaultAlert'); customComponent = testElement.querySelector<CdsAlert>('#customAlert'); }); afterEach(() => { removeTestElement(testElement); }); it('should default to an show "info" icon if not defined', async () => { const iconName = infoStandardIcon[0]; await componentIsStable(component); const alertSlotContent = getComponentSlotContent(component); const alertStatusIcon = component.shadowRoot.querySelector(alertStatusIconSelector); expect(alertSlotContent['alert-icon']).toBe(''); expect(alertStatusIcon.getAttribute('shape')).toBe(iconName); }); it('should be show "info" icon if given a weird status and no custom icon shape', async () => { const iconName = infoStandardIcon[0]; await componentIsStable(component); component.setAttribute('status', 'jabberwocky'); await componentIsStable(component); const alertSlotContent = getComponentSlotContent(component); const alertStatusIcon = component.shadowRoot.querySelector(alertStatusIconSelector); expect(alertSlotContent['alert-icon']).toBe(''); expect(alertStatusIcon.getAttribute('shape')).toBe(iconName); }); it('should default to the status icon shape if status is set and custom shape is not defined', async () => { await componentIsStable(component); const alertSlotContent = getComponentSlotContent(component); const alertStatusIcon = component.shadowRoot.querySelector(alertStatusIconSelector); expect(alertSlotContent['alert-icon']).toBe(''); expect(alertStatusIcon).not.toBeNull(); expect(alertStatusIcon.hasAttribute('shape')).toBe(true); expect(alertStatusIcon.getAttribute('shape')).toEqual('info-standard'); component.setAttribute('status', 'warning'); await componentIsStable(component); expect(component.status).toBe('warning'); expect(alertStatusIcon.getAttribute('shape')).toEqual('warning-standard'); await componentIsStable(customComponent); customComponent.setAttribute('status', 'danger'); await componentIsStable(customComponent); const customAlertSlotContent = getComponentSlotContent(customComponent); expect(customComponent.status).toBe('danger'); expect(customAlertSlotContent['alert-icon'].includes('cds-icon')).toBe(true); expect(customAlertSlotContent['alert-icon'].includes('shape="error-standard"')).toBe(false); expect(customAlertSlotContent['alert-icon'].includes('shape="ohai"')).toBe(true); }); it('should support a custom icon shape', async () => { await componentIsStable(customComponent); const customAlertSlotContent = getComponentSlotContent(customComponent); expect(customAlertSlotContent['alert-icon'].includes('cds-icon')).toBe(true); expect(customAlertSlotContent['alert-icon'].includes('shape="ohai"')).toBe(true); }); }); describe('status: ', () => { let customComponent: CdsAlert; beforeEach(async () => { testElement = await createTestElement(html` <cds-alert id="defaultAlert">${placeholderText}</cds-alert> <cds-alert id="customAlert"><cds-icon shape="ohai"></cds-icon>${placeholderText}</cds-alert> `); component = testElement.querySelector<CdsAlert>('#defaultAlert'); customComponent = testElement.querySelector<CdsAlert>('#customAlert'); }); afterEach(() => { removeTestElement(testElement); }); it('should default to an "info" icon if status is not defined', async () => { await componentIsStable(component); const iconName = infoStandardIcon[0]; const alertStatusIcon = component.shadowRoot.querySelector(alertStatusIconSelector); expect(component.status).toBe('neutral'); expect(alertStatusIcon.getAttribute('shape')).toBe(iconName); expect(alertStatusIcon.getAttribute('shape')).toBe(iconName); }); it('should allow users to change statuses', async () => { await componentIsStable(component); expect(component.status).toBe('neutral'); expect(component.shadowRoot.querySelector(alertStatusIconSelector).getAttribute('shape')).toBe( infoStandardIcon[0] ); component.setAttribute('status', 'warning'); await componentIsStable(component); expect(component.status).toBe('warning'); expect(component.shadowRoot.querySelector(alertStatusIconSelector).getAttribute('shape')).toBe( 'warning-standard' ); }); it('should show the spinner if set to loading status', async () => { await componentIsStable(customComponent); customComponent.setAttribute('status', 'loading'); await componentIsStable(customComponent); expect(customComponent.status).toBe('loading'); expect(customComponent.shadowRoot.querySelector(alertStatusIconSelector)).toBeNull(); expect(customComponent.shadowRoot.querySelector('cds-icon')).toBeNull(); expect(customComponent.shadowRoot.querySelector('.alert-spinner')).not.toBeNull(); const customAlertSlotContent = getComponentSlotContent(customComponent); expect(customAlertSlotContent['alert-icon']).toBeUndefined(); }); }); describe('Boxed (default type pastel) alerts: ', () => { let testElement: HTMLElement; let component: CdsAlert; const placeholderText = 'I am a default alert with no attributes.'; const placeholderActionsText = 'This is where action elements go.'; beforeEach(async () => { testElement = await createTestElement(html` <cds-alert alert-group-type="default"> ${placeholderText} <cds-alert-actions>${placeholderActionsText}</cds-alert-actions> </cds-alert> `); component = testElement.querySelector<CdsAlert>('cds-alert'); }); afterEach(() => { removeTestElement(testElement); }); it('should slot the component', async () => { await componentIsStable(component); const slots = getComponentSlotContent(component); expect(slots.default.trim()).toBe(`${placeholderText}`); }); it('should show alert actions', async () => { component.type = 'default'; await componentIsStable(component); const slots = getComponentSlotContent(component); expect(slots.actions.includes('<cds-alert-actions slot="actions" _type="default">')).toBe(true); expect(slots.actions.includes(placeholderActionsText)).toBe(true); }); }); describe('Banner alerts: ', () => { let testElement: HTMLElement; let component: CdsAlert; const placeholderText = 'I am a default alert with no attributes.'; beforeEach(async () => { testElement = await createTestElement( html`<cds-alert-group type="banner"><cds-alert closable>${placeholderText}</cds-alert></cds-alert-group>` ); component = testElement.querySelector<CdsAlert>('cds-alert'); }); afterEach(() => { removeTestElement(testElement); }); it('should slot the component', async () => { await componentIsStable(component); const slots = getComponentSlotContent(component); expect(slots.default.trim()).toBe(`${placeholderText}`); }); it('close-button should be size "20"', async () => { await componentIsStable(component); const closeBtn = component.shadowRoot.querySelector<CdsInternalCloseButton>('cds-internal-close-button'); expect(!!closeBtn).not.toBe(false, 'close-button should exist'); expect(closeBtn.iconSize).toBe('20', 'close-button icon size should be 20'); }); it('should show neutral spinner if set to loading status', async () => { await componentIsStable(component); component.setAttribute('status', 'loading'); await componentIsStable(component); expect(component.status).toBe('loading'); expect(component.shadowRoot.querySelector(alertStatusIconSelector)).toBeNull(); expect(component.shadowRoot.querySelector('cds-icon')).toBeNull(); const spinner = component.shadowRoot.querySelector('.alert-spinner'); expect(spinner).not.toBeNull('loading status should show spinner'); const customAlertSlotContent = getComponentSlotContent(component); expect(customAlertSlotContent['alert-icon']).toBeUndefined(); }); }); describe('Alert – close button: ', () => { let testElement: HTMLElement; let component: CdsAlert; const placeholderText = 'I am a default alert with no attributes.'; const placeholderActionsText = 'This is where action elements go.'; const getCloseButton = () => component.shadowRoot.querySelector<CdsInternalCloseButton>('cds-internal-close-button'); beforeEach(async () => { testElement = await createTestElement(html` <cds-alert alert-group-type="default"> ${placeholderText} <cds-alert-actions>${placeholderActionsText}</cds-alert-actions> </cds-alert> `); component = testElement.querySelector<CdsAlert>('cds-alert'); }); afterEach(() => { removeTestElement(testElement); }); it('should show the close button', async () => { await componentIsStable(component); expect(getCloseButton()).toBe(null); component.closable = true; component.type = 'banner'; await componentIsStable(component); expect(getCloseButton()).not.toBe(null); }); it('should set the close button aria-label', async () => { const expectedLabel = 'ohai'; await componentIsStable(component); component.type = 'default'; component.setAttribute('closable', 'true'); component.setAttribute('cds-i18n', `{ "closeButtonAriaLabel": "${expectedLabel}" }`); await componentIsStable(component); expect(getCloseButton()).not.toBe(null); expect(getCloseButton().getAttribute('aria-label')).toBe(expectedLabel); }); it('should emit a closeChanged event when close button is clicked', async () => { component.type = 'default'; component.closable = true; await componentIsStable(component); const event = onceEvent(component, 'closeChange'); getCloseButton().click(); expect((await event).detail).toBe(true); }); it('sets 16 as the default icon size', async () => { await componentIsStable(component); component.closable = true; component.type = 'default'; await componentIsStable(component); const icon = getCloseButton().shadowRoot.querySelector<CdsIcon>('cds-icon'); expect(icon).not.toBeNull(); expect(icon.hasAttribute('size')).toBe(true); expect(icon.getAttribute('size')).toBe('16'); }); }); describe('Aria: ', () => { let testElement: HTMLElement; beforeEach(async () => { testElement = await createTestElement(html`<cds-alert>${placeholderText}</cds-alert>`); component = testElement.querySelector<CdsAlert>('cds-alert'); }); afterEach(() => { removeTestElement(testElement); }); it('should set up "aria-describedby" as expected', async () => { const ariaAttr = 'aria-describedby'; await componentIsStable(component); expect(component.hasAttribute(ariaAttr)).toBe(true, 'alert element has ' + ariaAttr); const describedById = component.getAttribute(ariaAttr); const contentWrapper = component.shadowRoot.querySelector('.alert-content'); expect(component.shadowRoot.querySelector('#' + describedById)).not.toBeNull( ariaAttr + ' id element should exist' ); expect(contentWrapper.getAttribute('id')).toBe(describedById, ariaAttr + ' id should be on the content wrapper'); }); it('should set role to "region" as/when expected', async () => { await componentIsStable(component); expect(component.hasAttribute('role')).toBe(true, 'role exists on alert element'); expect(component.getAttribute('role')).toBe('region', 'role is set to "region" on alert element'); }); it('should use "aria-label" on the alert icon', async () => { await componentIsStable(component); let alertIcon = component.shadowRoot.querySelector('cds-icon.alert-status-icon'); expect(alertIcon.getAttribute('aria-label')).toBe('Info', 'default alert has aria-label "Info"'); component.setAttribute('status', 'danger'); await componentIsStable(component); expect(alertIcon.getAttribute('shape')).toBe('error-standard', 'verify status has changed'); expect(alertIcon.getAttribute('aria-label')).toBe( 'Error', 'icon shapes have aria-label "Error" after status change' ); component.setAttribute('status', 'loading'); await componentIsStable(component); alertIcon = component.shadowRoot.querySelector('.alert-spinner'); expect(component.shadowRoot.querySelector('cds-icon.alert-icon')).toBeNull('verify loading status pt. 1'); expect(alertIcon).not.toBeNull('verify loading status pt. 2'); expect(alertIcon.getAttribute('aria-label')).toBe( 'Loading', 'loading spinner has aria-label "Loading" after status changed to loading' ); }); }); }); describe('getIconStatusTuple: ', () => { it('should return "info" as the default', async () => { const [shapeName, title] = getIconStatusTuple('hippogriff'); expect(shapeName).toBe(infoStandardIcon[0]); expect(title).toBe(I18nService.keys.alert.info); }); it('should return statuses as expected', async () => { let [shapeName, title] = getIconStatusTuple('info'); expect(shapeName).toBe(infoStandardIcon[0]); expect(title).toBe(I18nService.keys.alert.info); [shapeName, title] = getIconStatusTuple('success'); expect(shapeName).toBe('success-standard'); expect(title).toBe(I18nService.keys.alert.success); [shapeName, title] = getIconStatusTuple('warning'); expect(shapeName).toBe('warning-standard'); expect(title).toBe(I18nService.keys.alert.warning); [shapeName, title] = getIconStatusTuple('danger'); expect(shapeName).toBe('error-standard'); expect(title).toBe(I18nService.keys.alert.danger); [shapeName, title] = getIconStatusTuple('unknown'); expect(shapeName).toBe('help'); expect(title).toBe(I18nService.keys.alert.info); [shapeName, title] = getIconStatusTuple('loading'); expect(shapeName).toBe('loading'); expect(title).toBe(I18nService.keys.alert.loading); }); }); describe('iconShapeIsAlertStatusType: ', () => { it('should return false as expected', async () => { expect(iconShapeIsAlertStatusType('')).toBe(false); expect(iconShapeIsAlertStatusType('jabberwocky')).toBe(false); expect(iconShapeIsAlertStatusType(null)).toBe(false); }); it('should return true as expected', async () => { expect(iconShapeIsAlertStatusType('error-standard')).toBe(true); expect(iconShapeIsAlertStatusType('warning-standard')).toBe(true); expect(iconShapeIsAlertStatusType('info-standard')).toBe(true); expect(iconShapeIsAlertStatusType('success-standard')).toBe(true); expect(iconShapeIsAlertStatusType('help')).toBe(true); }); });
the_stack
import { ShapeAD } from "types/shape"; import { evalShapes } from "engine/Evaluator"; import * as ShapeDef from "renderer/ShapeDef"; import { unsafelyUnwrap } from "utils/Error"; import { compileDomain, compileSubstance, initializeMat } from "index"; import { compileStyle } from "compiler/Style"; import { numOf } from "engine/Autodiff"; const makeSty = (shapeSty: string): string => `canvas { width = 800 height = 700 } global { global.shape = ${shapeSty} } `; const getShape = async (shapeSty: string): Promise<ShapeAD> => { // adapted from loadProgs function in compiler/Style.test.ts const env0 = unsafelyUnwrap(compileDomain("")); const [subEnv, varEnv] = unsafelyUnwrap(compileSubstance("", env0)); const state = unsafelyUnwrap(compileStyle(makeSty(shapeSty), subEnv, varEnv)); // adapted from prepareState function in index.ts await initializeMat(); const shapes = evalShapes({ ...state, originalTranslation: state.originalTranslation, }); expect(shapes.length).toBe(1); return shapes[0]; }; const circleSty = `Circle { r: 100 center: (42, 121) } `; const ellipseSty = `Ellipse { rx: 200 ry: 100 center: (42, 121) } `; const rectSty = `Rectangle { center: (0, 0) w: 150 h: 200 } `; const calloutStyNoPadding = `Callout { center: (-50, -100) w: 100 h: 100 anchor: (100, -200) } `; const calloutStyPadding = `Callout { center: (-50, -100) w: 100 h: 100 anchor: (100, -200) padding: 20 } `; // https://en.wikipedia.org/wiki/Polygon#/media/File:Assorted_polygons.svg const polygonSty = (t: string) => `${t} { points: [(564, 24), (733, 54), (755, 154), (693, 257), (548, 216), (571, 145), (630, 146), (617, 180), (664, 196), (701, 120), (591, 90), (528, 129)] scale: .5 } `; const pathStringSty = `PathString { center: (-50, 100) w: 100 h: 200 rotation: 30 } `; const imageSty = `Image { center: (0, 0) w: 150 h: 200 } `; const squareSty = `Square { side: 50 center: (30, 70) rotation: 30 } `; const lineSty = (t: string) => `${t} { start: (-300, 200) end: (100, -150) thickness: 50 } `; const pathStyL = `Path { pathData: pathFromPoints("open", [(-100, -100), (100, -50), (-50, 100)]) } `; const pathStyQ = `Path { pathData: makePath((-100, 0), (100, 0), 50, 10) } `; const pathStyC = `Path { pathData: cubicCurveFromPoints("open", [(0, 0), (50, 50), (200, 0), (75, -25)]) } `; const pathStyT = `Path { pathData: quadraticCurveFromPoints("open", [(0, 0), (50, 50), (75, -25), (200, 0)]) } `; const pathStyS = `Path { pathData: cubicCurveFromPoints("open", [(0, 0), (50, 50), (200, 0), (75, -25), (0, -100), (100, -75)]) } `; const pathStyAUnscaled = `Path { pathData: arc("open", (-50, 50), (100, -25), (200, 100), 30, 1, 0) } `; const pathStyASmall = `Path { pathData: arc("open", (-50, 50), (100, -25), (200, 100), 30, 0, 0) } `; const pathStyAScaled = `Path { pathData: arc("open", (-75, -50), (200, 25), (25, 50), 60, 0, 0) } `; describe("ShapeDef", () => { test("circleDef.bbox", async () => { const shape = await getShape(circleSty); const { w, h, center: [x, y], } = ShapeDef.circleDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(200); expect(numOf(h)).toBeCloseTo(200); expect(numOf(x)).toBeCloseTo(42); expect(numOf(y)).toBeCloseTo(121); }); test("ellipseDef.bbox", async () => { const shape = await getShape(ellipseSty); const { w, h, center: [x, y], } = ShapeDef.ellipseDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(400); expect(numOf(h)).toBeCloseTo(200); expect(numOf(x)).toBeCloseTo(42); expect(numOf(y)).toBeCloseTo(121); }); test("rectDef.bbox", async () => { const shape = await getShape(rectSty); const { w, h, center: [x, y], } = ShapeDef.rectDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(150); expect(numOf(h)).toBeCloseTo(200); expect(numOf(x)).toBeCloseTo(0); expect(numOf(y)).toBeCloseTo(0); }); test("calloutDef.bbox no padding", async () => { const shape = await getShape(calloutStyNoPadding); const { w, h, center: [x, y], } = ShapeDef.calloutDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(215); expect(numOf(h)).toBeCloseTo(165); expect(numOf(x)).toBeCloseTo(-7.5); expect(numOf(y)).toBeCloseTo(-117.5); }); test("calloutDef.bbox padding", async () => { const shape = await getShape(calloutStyPadding); const { w, h, center: [x, y], } = ShapeDef.calloutDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(210); expect(numOf(h)).toBeCloseTo(160); expect(numOf(x)).toBeCloseTo(-5); expect(numOf(y)).toBeCloseTo(-120); }); test("polygonDef.bbox", async () => { const shape = await getShape(polygonSty("Polygon")); const { w, h, center: [x, y], } = ShapeDef.polygonDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(113.5); expect(numOf(h)).toBeCloseTo(116.5); expect(numOf(x)).toBeCloseTo(320.75); expect(numOf(y)).toBeCloseTo(70.25); }); test("freeformPolygonDef.bbox", async () => { const shape = await getShape(polygonSty("FreeformPolygon")); const { w, h, center: [x, y], } = ShapeDef.freeformPolygonDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(113.5); expect(numOf(h)).toBeCloseTo(116.5); expect(numOf(x)).toBeCloseTo(320.75); expect(numOf(y)).toBeCloseTo(70.25); }); test("pathStringDef.bbox", async () => { const shape = await getShape(pathStringSty); const { w, h, center: [x, y], } = ShapeDef.pathStringDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(186.603); expect(numOf(h)).toBeCloseTo(223.205); expect(numOf(x)).toBeCloseTo(-106.699); expect(numOf(y)).toBeCloseTo(88.397); }); test("polylineDef.bbox", async () => { const shape = await getShape(polygonSty("Polyline")); const { w, h, center: [x, y], } = ShapeDef.polylineDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(113.5); expect(numOf(h)).toBeCloseTo(116.5); expect(numOf(x)).toBeCloseTo(320.75); expect(numOf(y)).toBeCloseTo(70.25); }); test("imageDef.bbox", async () => { const shape = await getShape(imageSty); const { w, h, center: [x, y], } = ShapeDef.imageDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(150); expect(numOf(h)).toBeCloseTo(200); expect(numOf(x)).toBeCloseTo(0); expect(numOf(y)).toBeCloseTo(0); }); test("squareDef.bbox", async () => { const shape = await getShape(squareSty); const { w, h, center: [x, y], } = ShapeDef.squareDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(68.301); expect(numOf(h)).toBeCloseTo(68.301); expect(numOf(x)).toBeCloseTo(14.151); expect(numOf(y)).toBeCloseTo(60.849); }); // no Text test because w and h seem to just be set to 0 when using getShape test("lineDef.bbox", async () => { const shape = await getShape(lineSty("Line")); const { w, h, center: [x, y], } = ShapeDef.lineDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(432.925); expect(numOf(h)).toBeCloseTo(387.629); expect(numOf(x)).toBeCloseTo(-100); expect(numOf(y)).toBeCloseTo(25); }); test("arrowDef.bbox", async () => { const shape = await getShape(lineSty("Arrow")); const { w, h, center: [x, y], } = ShapeDef.arrowDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(432.925); expect(numOf(h)).toBeCloseTo(387.629); expect(numOf(x)).toBeCloseTo(-100); expect(numOf(y)).toBeCloseTo(25); }); test("curveDef.bbox lines", async () => { const shape = await getShape(pathStyL); const { w, h, center: [x, y], } = ShapeDef.curveDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(200); expect(numOf(h)).toBeCloseTo(200); expect(numOf(x)).toBeCloseTo(0); expect(numOf(y)).toBeCloseTo(0); }); test("curveDef.bbox quadratic", async () => { const shape = await getShape(pathStyQ); const { w, h, center: [x, y], } = ShapeDef.curveDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(180); expect(numOf(h)).toBeCloseTo(50); expect(numOf(x)).toBeCloseTo(0); expect(numOf(y)).toBeCloseTo(-25); }); test("curveDef.bbox cubic", async () => { const shape = await getShape(pathStyC); const { w, h, center: [x, y], } = ShapeDef.curveDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(200); expect(numOf(h)).toBeCloseTo(75); expect(numOf(x)).toBeCloseTo(100); expect(numOf(y)).toBeCloseTo(12.5); }); test("curveDef.bbox quadratic join", async () => { const shape = await getShape(pathStyT); const { w, h, center: [x, y], } = ShapeDef.curveDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(200); expect(numOf(h)).toBeCloseTo(150); expect(numOf(x)).toBeCloseTo(100); expect(numOf(y)).toBeCloseTo(-25); }); test("curveDef.bbox cubic join", async () => { const shape = await getShape(pathStyS); const { w, h, center: [x, y], } = ShapeDef.curveDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(250); expect(numOf(h)).toBeCloseTo(150); expect(numOf(x)).toBeCloseTo(75); expect(numOf(y)).toBeCloseTo(-25); }); test("curveDef.bbox arc unscaled", async () => { const shape = await getShape(pathStyAUnscaled); const { w, h, center: [x, y], } = ShapeDef.curveDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(400); expect(numOf(h)).toBeCloseTo(400); expect(numOf(x)).toBeCloseTo(-1.297); expect(numOf(y)).toBeCloseTo(-76.281); }); test("curveDef.bbox arc small", async () => { const shape = await getShape(pathStyASmall); const { w, h, center: [x, y], } = ShapeDef.curveDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(400); expect(numOf(h)).toBeCloseTo(400); expect(numOf(x)).toBeCloseTo(51.297); expect(numOf(y)).toBeCloseTo(101.282); }); test("curveDef.bbox arc scaled", async () => { const shape = await getShape(pathStyAScaled); const { w, h, center: [x, y], } = ShapeDef.curveDef.bbox(shape.properties); expect(numOf(w)).toBeCloseTo(311.512); expect(numOf(h)).toBeCloseTo(311.512); expect(numOf(x)).toBeCloseTo(62.5); expect(numOf(y)).toBeCloseTo(-12.5); }); });
the_stack
import { Server as HttpServer } from 'http'; import HttpStatusCodes from 'http-status-codes'; import { Container, Service } from 'typedi'; import { Get } from '../../src/decorator/Get'; import { JsonController } from '../../src/decorator/JsonController'; import { createExpressServer, getMetadataArgsStorage } from '../../src/index'; import { useContainer } from '../../src/util/container'; import { axios } from '../utilities/axios'; import DoneCallback = jest.DoneCallback; describe(``, () => { let expressServer: HttpServer; describe('using typedi container should be possible', () => { beforeEach((done: DoneCallback) => { // reset metadata args storage useContainer(Container); getMetadataArgsStorage().reset(); @Service() class QuestionRepository { findQuestions(): any[] { return [ { id: 1, title: 'question #1', }, { id: 2, title: 'question #2', }, ]; } } @Service() class PostRepository { findPosts(): any[] { return [ { id: 1, title: 'post #1', }, { id: 2, title: 'post #2', }, ]; } } @Service() @JsonController() class TestContainerController { private questionRepository: QuestionRepository = new QuestionRepository(); private postRepository: PostRepository = new PostRepository(); @Get('/questions') questions(): any[] { return this.questionRepository.findQuestions(); } @Get('/posts') posts(): any[] { return this.postRepository.findPosts(); } } expressServer = createExpressServer().listen(3001, done); }); afterEach((done: DoneCallback) => { useContainer(undefined); expressServer.close(done); }); it('typedi container', async () => { expect.assertions(4); let response; try { response = await axios.get('/questions'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'question #1', }, { id: 2, title: 'question #2', }, ]); response = await axios.get('/posts'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'post #1', }, { id: 2, title: 'post #2', }, ]); } catch (err) { console.log(err); } }); }); describe('using custom container should be possible', () => { beforeEach((done: DoneCallback) => { const fakeContainer = { services: [] as any, get(service: any): any { if (!this.services[service.name]) { this.services[service.name] = new service(); } return this.services[service.name]; }, }; class QuestionRepository { findQuestions(): any[] { return [ { id: 1, title: 'question #1', }, { id: 2, title: 'question #2', }, ]; } } class PostRepository { findPosts(): any[] { return [ { id: 1, title: 'post #1', }, { id: 2, title: 'post #2', }, ]; } } // reset metadata args storage useContainer(fakeContainer); getMetadataArgsStorage().reset(); @JsonController() class TestContainerController { private questionRepository: QuestionRepository = new QuestionRepository(); private postRepository: PostRepository = new PostRepository(); @Get('/questions') questions(): any[] { return this.questionRepository.findQuestions(); } @Get('/posts') posts(): any[] { return this.postRepository.findPosts(); } } expressServer = createExpressServer().listen(3001, done); }); afterEach((done: DoneCallback) => { useContainer(undefined); expressServer.close(done); }); it('custom container', async () => { expect.assertions(4); let response; try { response = await axios.get('/questions'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'question #1', }, { id: 2, title: 'question #2', }, ]); response = await axios.get('/posts'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'post #1', }, { id: 2, title: 'post #2', }, ]); } catch (err) { console.log(err); } }); }); describe('using custom container with fallback should be possible', () => { beforeEach((done: DoneCallback) => { const fakeContainer = { services: [] as any, get(service: any): any { return this.services[service.name]; }, }; class QuestionRepository { findQuestions(): any[] { return [ { id: 1, title: 'question #1', }, { id: 2, title: 'question #2', }, ]; } } class PostRepository { findPosts(): any[] { return [ { id: 1, title: 'post #1', }, { id: 2, title: 'post #2', }, ]; } } // reset metadata args storage useContainer(fakeContainer, { fallback: true }); getMetadataArgsStorage().reset(); @JsonController() class TestContainerController { private questionRepository: QuestionRepository = new QuestionRepository(); private postRepository: PostRepository = new PostRepository(); @Get('/questions') questions(): any[] { return this.questionRepository.findQuestions(); } @Get('/posts') posts(): any[] { return this.postRepository.findPosts(); } } @JsonController() class SecondTestContainerController { @Get('/photos') photos(): any[] { return [ { id: 1, title: 'photo #1', }, { id: 2, title: 'photo #2', }, ]; } } expressServer = createExpressServer().listen(3001, done); }); afterEach((done: DoneCallback) => { useContainer(undefined); expressServer.close(done); }); it('custom container with fallback', async () => { expect.assertions(6); let response; try { response = await axios.get('/questions'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'question #1', }, { id: 2, title: 'question #2', }, ]); response = await axios.get('/posts'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'post #1', }, { id: 2, title: 'post #2', }, ]); response = await axios.get('/photos'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'photo #1', }, { id: 2, title: 'photo #2', }, ]); } catch (err) { console.log(err); } }); }); describe('using custom container with fallback and fallback on throw error should be possible', () => { beforeEach((done: DoneCallback) => { const fakeContainer = { services: [] as any, get(service: any): any { if (!this.services[service.name]) throw new Error(`Provider was not found for ${service.name}`); return this.services[service.name]; }, }; class QuestionRepository { findQuestions(): any[] { return [ { id: 1, title: 'question #1', }, { id: 2, title: 'question #2', }, ]; } } class PostRepository { findPosts(): any[] { return [ { id: 1, title: 'post #1', }, { id: 2, title: 'post #2', }, ]; } } // reset metadata args storage useContainer(fakeContainer, { fallback: true, fallbackOnErrors: true }); getMetadataArgsStorage().reset(); @JsonController() class TestContainerController { private questionRepository: QuestionRepository = new QuestionRepository(); private postRepository: PostRepository = new PostRepository(); @Get('/questions') questions(): any[] { return this.questionRepository.findQuestions(); } @Get('/posts') posts(): any[] { return this.postRepository.findPosts(); } } @JsonController() class SecondTestContainerController { @Get('/photos') photos(): any[] { return [ { id: 1, title: 'photo #1', }, { id: 2, title: 'photo #2', }, ]; } } // fakeContainer.services['TestContainerController'] = new TestContainerController(questionRepository, postRepository); expressServer = createExpressServer().listen(3001, done); }); afterEach((done: DoneCallback) => { useContainer(undefined); expressServer.close(done); }); it('custom container with fallback and fallback on throw error', async () => { expect.assertions(6); let response; try { response = await axios.get('/questions'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'question #1', }, { id: 2, title: 'question #2', }, ]); response = await axios.get('/posts'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'post #1', }, { id: 2, title: 'post #2', }, ]); response = await axios.get('/photos'); expect(response.status).toEqual(HttpStatusCodes.OK); expect(response.data).toEqual([ { id: 1, title: 'photo #1', }, { id: 2, title: 'photo #2', }, ]); } catch (err) { // Handle Error Here console.error(err); } }); }); });
the_stack
import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { combineLatest, Observable, of as observableOf } from 'rxjs'; import { combineLatest as combineLatestOperators, distinctUntilChanged, filter, first, map, publishReplay, refCount, startWith, switchMap, } from 'rxjs/operators'; import { CurrentUserPermissionsService } from '../../../../../../core/src/core/permissions/current-user-permissions.service'; import { endpointEntityType } from '../../../../../../store/src/helpers/stratos-entity-factory'; import { APIResource, EntityInfo } from '../../../../../../store/src/types/api.types'; import { UsersRolesSetChanges } from '../../../../actions/users-roles.actions'; import { IOrganization, ISpace } from '../../../../cf-api.types'; import { CFAppState } from '../../../../cf-app-state'; import { cfEntityCatalog } from '../../../../cf-entity-catalog'; import { organizationEntityType, spaceEntityType } from '../../../../cf-entity-types'; import { createEntityRelationKey, createEntityRelationPaginationKey, } from '../../../../entity-relations/entity-relations.types'; import { CfUserService } from '../../../../shared/data-services/cf-user.service'; import { createDefaultOrgRoles, createDefaultSpaceRoles } from '../../../../store/reducers/cf-users-roles.reducer'; import { selectCfUsersRolesCf, selectCfUsersRolesPicked, selectCfUsersRolesRoles, } from '../../../../store/selectors/cf-users-roles.selector'; import { CfUser, IUserPermissionInOrg, UserRoleInOrg, UserRoleInSpace } from '../../../../store/types/cf-user.types'; import { CfRoleChange, CfUserRolesSelected } from '../../../../store/types/users-roles.types'; import { CfUserPermissionsChecker } from '../../../../user-permissions/cf-user-permissions-checkers'; import { canUpdateOrgSpaceRoles } from '../../cf.helpers'; @Injectable() export class CfRolesService { existingRoles$: Observable<CfUserRolesSelected>; newRoles$: Observable<IUserPermissionInOrg>; loading$: Observable<boolean>; cfOrgs: { [cfGuid: string]: Observable<APIResource<IOrganization>[]>, } = {}; /** * Given a list of orgs or spaces remove those that the connected user cannot edit roles in. */ static filterEditableOrgOrSpace<T extends IOrganization | ISpace>( userPerms: CurrentUserPermissionsService, isOrg: boolean, orgOrSpaces$: Observable<APIResource<T>[]> ): Observable<APIResource<T>[]> { return orgOrSpaces$.pipe( // Create an observable containing the original list of organisations and a corresponding list of whether an org can be edited switchMap(orgsOrSpaces => { return combineLatest( observableOf(orgsOrSpaces), combineLatest(orgsOrSpaces.map(orgOrSpace => CfRolesService.canEditOrgOrSpace( userPerms, orgOrSpace.metadata.guid, orgOrSpace.entity.cfGuid, isOrg ? orgOrSpace.metadata.guid : (orgOrSpace as APIResource<ISpace>).entity.organization_guid, isOrg ? CfUserPermissionsChecker.ALL_SPACES : orgOrSpace.metadata.guid, )))); }), // Filter out orgs than the current user cannot edit map(([orgs, canEdit]) => orgs.filter(org => canEdit.find(canEditOrgOrSpace => canEditOrgOrSpace.guid === org.metadata.guid).canEdit)), ); } /** * Create an observable with an org/space guids and whether it can be edited by the connected user */ static canEditOrgOrSpace<T>( userPerms: CurrentUserPermissionsService, guid: string, cfGuid: string, orgGuid: string, spaceGuid): Observable<{ guid: string, canEdit: boolean, }> { return canUpdateOrgSpaceRoles(userPerms, cfGuid, orgGuid, spaceGuid).pipe( first(), map(canEdit => ({ guid, canEdit })) ); } constructor( private store: Store<CFAppState>, private cfUserService: CfUserService, private userPerms: CurrentUserPermissionsService, ) { this.existingRoles$ = this.store.select(selectCfUsersRolesPicked).pipe( combineLatestOperators(this.store.select(selectCfUsersRolesCf)), filter(([users, cfGuid]) => !!cfGuid), switchMap(([users, cfGuid]) => this.populateRoles(cfGuid, users)), distinctUntilChanged(), publishReplay(1), refCount() ); this.newRoles$ = this.store.select(selectCfUsersRolesRoles).pipe( distinctUntilChanged(), publishReplay(1), refCount() ); this.loading$ = this.existingRoles$.pipe( combineLatestOperators(this.newRoles$), map(([existingRoles, newRoles]) => !existingRoles || !newRoles), startWith(true), ); } /** * Take the structure that cf stores user roles in (per user and flat) and convert into a format that's easier to use and compare with * (easier to access at specific levels, easier to parse pieces around) */ populateRoles(cfGuid: string, selectedUsers: CfUser[]): Observable<CfUserRolesSelected> { if (!cfGuid || !selectedUsers || selectedUsers.length === 0) { return observableOf({}); } const userGuids = selectedUsers.map(user => user.guid); return this.cfUserService.getUsers(cfGuid).pipe( map(users => { const roles = {}; // For each user (excluding those that are not selected).... users.forEach(user => { if (userGuids.indexOf(user.metadata.guid) >= 0) { this.populateUserRoles(user, roles); } }); return roles; }), ); } private populateUserRoles(user: APIResource<CfUser>, roles: CfUserRolesSelected) { const mappedUser: { [orgGuid: string]: IUserPermissionInOrg, } = {}; const orgRoles = this.cfUserService.getOrgRolesFromUser(user.entity); const spaceRoles = this.cfUserService.getSpaceRolesFromUser(user.entity); // ... populate org roles ... orgRoles.forEach(org => { mappedUser[org.orgGuid] = { ...org, spaces: {} }; }); // ... and for each space, populate space roles spaceRoles.forEach(space => { if (!mappedUser[space.orgGuid]) { mappedUser[space.orgGuid] = createDefaultOrgRoles(space.orgGuid, space.orgName); } if (!space.orgName && mappedUser[space.orgGuid]) { space.orgName = mappedUser[space.orgGuid].name; } mappedUser[space.orgGuid].spaces[space.spaceGuid] = { ...space }; }); roles[user.metadata.guid] = mappedUser; } /** * Create a collection of role `change` items representing the diff between existing roles and newly selected roles. */ createRolesDiff(orgGuid: string): Observable<CfRoleChange[]> { return this.existingRoles$.pipe( combineLatestOperators( this.newRoles$, this.store.select(selectCfUsersRolesPicked), ), first(), map(([existingRoles, newRoles, pickedUsers]) => { const changes = []; // For each user, loop through the new roles and compare with any existing. If there's a diff, add it to a changes collection to be // returned pickedUsers.forEach(user => { changes.push(...this.createRolesUserDiff(existingRoles, newRoles, changes, user, orgGuid)); }); this.store.dispatch(new UsersRolesSetChanges(changes)); return changes; }) ); } private createRolesUserDiff( existingRoles: CfUserRolesSelected, newRoles: IUserPermissionInOrg, changes: CfRoleChange[], user: CfUser, orgGuid: string ): CfRoleChange[] { const existingUserRoles = existingRoles[user.guid] || {}; const newChanges: CfRoleChange[] = []; // Compare org roles const existingOrgRoles = existingUserRoles[orgGuid] || createDefaultOrgRoles(orgGuid, newRoles.name); newChanges.push(...this.comparePermissions({ userGuid: user.guid, orgGuid, orgName: newRoles.name, add: false, role: null }, existingOrgRoles.permissions, newRoles.permissions)); // Compare space roles Object.keys(newRoles.spaces).forEach(spaceGuid => { const newSpace = newRoles.spaces[spaceGuid]; const oldSpace = existingOrgRoles.spaces[spaceGuid] || createDefaultSpaceRoles(orgGuid, newRoles.name, spaceGuid, newSpace.name); newChanges.push(...this.comparePermissions({ userGuid: user.guid, orgGuid, orgName: newRoles.name, spaceGuid, spaceName: newSpace.name, add: false, role: null }, oldSpace.permissions, newSpace.permissions)); }); return newChanges; } fetchOrg(cfGuid: string, orgGuid: string): Observable<EntityInfo<APIResource<IOrganization>>> { return cfEntityCatalog.org.store.getEntityService(orgGuid, cfGuid, { includeRelations: [], populateMissing: false }) .waitForEntity$; } fetchOrgEntity(cfGuid: string, orgGuid: string): Observable<APIResource<IOrganization>> { return this.fetchOrg(cfGuid, orgGuid).pipe( filter(entityInfo => !!entityInfo.entity), map(entityInfo => entityInfo.entity), ); } fetchOrgs(cfGuid: string): Observable<APIResource<IOrganization>[]> { if (!this.cfOrgs[cfGuid]) { const paginationKey = createEntityRelationPaginationKey(endpointEntityType, cfGuid); const orgs$ = cfEntityCatalog.org.store.getPaginationService( cfGuid, paginationKey, { includeRelations: [ createEntityRelationKey(organizationEntityType, spaceEntityType) ], populateMissing: true } ).entities$; this.cfOrgs[cfGuid] = CfRolesService.filterEditableOrgOrSpace<IOrganization>(this.userPerms, true, orgs$).pipe( map(orgs => orgs.sort((a, b) => a.entity.name.localeCompare(b.entity.name))), publishReplay(1), refCount() ); } return this.cfOrgs[cfGuid]; } /** * Compare a set of org or space permissions and return the differences */ private comparePermissions( template: CfRoleChange, oldPerms: UserRoleInOrg | UserRoleInSpace, newPerms: UserRoleInOrg | UserRoleInSpace) : CfRoleChange[] { const changes = []; Object.keys(oldPerms).forEach(permKey => { if (newPerms[permKey] === undefined) { // Skip this, the user hasn't set it return; } if (!!oldPerms[permKey] !== !!newPerms[permKey]) { changes.push({ ...template, add: !!newPerms[permKey], role: permKey }); } }); return changes; } }
the_stack
import { observable, computed, reaction, autorun, action, IReactionDisposer } from 'mobx'; import { TreeModel } from './tree.model'; import { TreeOptions } from './tree-options.model'; import { ITreeNode } from '../defs/api'; import { TREE_EVENTS } from '../constants/events'; export class TreeNode implements ITreeNode { private handler: IReactionDisposer; @computed get isHidden() { return this.treeModel.isHidden(this); }; @computed get isExpanded() { return this.treeModel.isExpanded(this); }; @computed get isActive() { return this.treeModel.isActive(this); }; @computed get isFocused() { return this.treeModel.isNodeFocused(this); }; @computed get isSelected() { if (this.isSelectable()) { return this.treeModel.isSelected(this); } else { return this.children.some((node: TreeNode) => node.isSelected); } }; @computed get isAllSelected() { if (this.isSelectable()) { return this.treeModel.isSelected(this); } else { return this.children.every((node: TreeNode) => node.isAllSelected); } }; @computed get isPartiallySelected() { return this.isSelected && !this.isAllSelected; } @observable children: TreeNode[]; @observable index: number; @observable position = 0; @observable height: number; @computed get level(): number { return this.parent ? this.parent.level + 1 : 0; } @computed get path(): string[] { return this.parent ? [...this.parent.path, this.id] : []; } get elementRef(): any { throw `Element Ref is no longer supported since introducing virtual scroll\n You may use a template to obtain a reference to the element`; } private _originalNode: any; get originalNode() { return this._originalNode; }; constructor(public data: any, public parent: TreeNode, public treeModel: TreeModel, index: number) { if (this.id === undefined || this.id === null) { this.id = uuid(); } // Make sure there's a unique id without overriding existing ids to work with immutable data structures this.index = index; if (this.getField('children')) { this._initChildren(); } this.autoLoadChildren(); } // helper get functions: get hasChildren(): boolean { return !!(this.getField('hasChildren') || (this.children && this.children.length > 0)); } get isCollapsed(): boolean { return !this.isExpanded; } get isLeaf(): boolean { return !this.hasChildren; } get isRoot(): boolean { return this.parent.data.virtual; } get realParent(): TreeNode { return this.isRoot ? null : this.parent; } // proxy functions: get options(): TreeOptions { return this.treeModel.options; } fireEvent(event) { this.treeModel.fireEvent(event); } // field accessors: get displayField() { return this.getField('display'); } get id() { return this.getField('id'); } set id(value) { this.setField('id', value); } getField(key) { return this.data[this.options[`${key}Field`]]; } setField(key, value) { this.data[this.options[`${key}Field`]] = value; } // traversing: _findAdjacentSibling(steps, skipHidden = false) { const siblings = this._getParentsChildren(skipHidden); const index = siblings.indexOf(this); return siblings.length > index + steps ? siblings[index + steps] : null; } findNextSibling(skipHidden = false) { return this._findAdjacentSibling(+1, skipHidden); } findPreviousSibling(skipHidden = false) { return this._findAdjacentSibling(-1, skipHidden); } getVisibleChildren() { return this.visibleChildren; } @computed get visibleChildren() { return (this.children || []).filter((node) => !node.isHidden); } getFirstChild(skipHidden = false) { let children = skipHidden ? this.visibleChildren : this.children; return children != null && children.length ? children[0] : null; } getLastChild(skipHidden = false) { let children = skipHidden ? this.visibleChildren : this.children; return children != null && children.length ? children[children.length - 1] : null; } findNextNode(goInside = true, skipHidden = false) { return goInside && this.isExpanded && this.getFirstChild(skipHidden) || this.findNextSibling(skipHidden) || this.parent && this.parent.findNextNode(false, skipHidden); } findPreviousNode(skipHidden = false) { let previousSibling = this.findPreviousSibling(skipHidden); if (!previousSibling) { return this.realParent; } return previousSibling._getLastOpenDescendant(skipHidden); } _getLastOpenDescendant(skipHidden = false) { const lastChild = this.getLastChild(skipHidden); return (this.isCollapsed || !lastChild) ? this : lastChild._getLastOpenDescendant(skipHidden); } private _getParentsChildren(skipHidden = false): any[] { const children = this.parent && (skipHidden ? this.parent.getVisibleChildren() : this.parent.children); return children || []; } private getIndexInParent(skipHidden = false) { return this._getParentsChildren(skipHidden).indexOf(this); } isDescendantOf(node: TreeNode) { if (this === node) return true; else return this.parent && this.parent.isDescendantOf(node); } getNodePadding(): string { return this.options.levelPadding * (this.level - 1) + 'px'; } getClass(): string { return [this.options.nodeClass(this), `tree-node-level-${ this.level }`].join(' '); } onDrop($event) { this.mouseAction('drop', $event.event, { from: $event.element, to: { parent: this, index: 0, dropOnNode: true } }); } allowDrop = (element, $event?) => { return this.options.allowDrop(element, { parent: this, index: 0 }, $event); } allowDragoverStyling = () => { return this.options.allowDragoverStyling; } allowDrag() { return this.options.allowDrag(this); } // helper methods: loadNodeChildren() { if (!this.options.getChildren) { return Promise.resolve(); // Not getChildren method - for using redux } return Promise.resolve(this.options.getChildren(this)) .then((children) => { if (children) { this.setField('children', children); this._initChildren(); if (this.options.useTriState && this.treeModel.isSelected(this)) { this.setIsSelected(true); } this.children.forEach((child) => { if (child.getField('isExpanded') && child.hasChildren) { child.expand(); } }); }}).then(() => { this.fireEvent({ eventName: TREE_EVENTS.loadNodeChildren, node: this }); }); } expand() { if (!this.isExpanded) { this.toggleExpanded(); } return this; } collapse() { if (this.isExpanded) { this.toggleExpanded(); } return this; } doForAll(fn: (node: ITreeNode) => any) { Promise.resolve(fn(this)).then(() => { if (this.children) { this.children.forEach((child) => child.doForAll(fn)); } }); } expandAll() { this.doForAll((node) => node.expand()); } collapseAll() { this.doForAll((node) => node.collapse()); } ensureVisible() { if (this.realParent) { this.realParent.expand(); this.realParent.ensureVisible(); } return this; } toggleExpanded() { this.setIsExpanded(!this.isExpanded); return this; } setIsExpanded(value) { if (this.hasChildren) { this.treeModel.setExpandedNode(this, value); } return this; }; autoLoadChildren() { this.handler = reaction( () => this.isExpanded, (isExpanded) => { if (!this.children && this.hasChildren && isExpanded) { this.loadNodeChildren(); } }, { fireImmediately: true } ); } dispose() { if (this.children) { this.children.forEach((child) => child.dispose()); } if (this.handler) { this.handler(); } this.parent = null; this.children = null; } setIsActive(value, multi = false) { this.treeModel.setActiveNode(this, value, multi); if (value) { this.focus(this.options.scrollOnActivate); } return this; } isSelectable() { return this.isLeaf || !this.children || !this.options.useTriState; } @action setIsSelected(value) { if (this.isSelectable()) { this.treeModel.setSelectedNode(this, value); } else { this.visibleChildren.forEach((child) => child.setIsSelected(value)); } return this; } toggleSelected() { this.setIsSelected(!this.isSelected); return this; } toggleActivated(multi = false) { this.setIsActive(!this.isActive, multi); return this; } setActiveAndVisible(multi = false) { this.setIsActive(true, multi) .ensureVisible(); setTimeout(this.scrollIntoView.bind(this)); return this; } scrollIntoView(force = false) { this.treeModel.virtualScroll.scrollIntoView(this, force); } focus(scroll = true) { let previousNode = this.treeModel.getFocusedNode(); this.treeModel.setFocusedNode(this); if (scroll) { this.scrollIntoView(); } if (previousNode) { this.fireEvent({ eventName: TREE_EVENTS.blur, node: previousNode }); } this.fireEvent({ eventName: TREE_EVENTS.focus, node: this }); return this; } blur() { let previousNode = this.treeModel.getFocusedNode(); this.treeModel.setFocusedNode(null); if (previousNode) { this.fireEvent({ eventName: TREE_EVENTS.blur, node: this }); } return this; } setIsHidden(value) { this.treeModel.setIsHidden(this, value); } hide() { this.setIsHidden(true); } show() { this.setIsHidden(false); } mouseAction(actionName: string, $event, data: any = null) { this.treeModel.setFocus(true); const actionMapping = this.options.actionMapping.mouse; const mouseAction = actionMapping[actionName]; if (mouseAction) { mouseAction(this.treeModel, this, $event, data); } } getSelfHeight() { return this.options.nodeHeight(this); } @action _initChildren() { this.children = this.getField('children') .map((c, index) => new TreeNode(c, this, this.treeModel, index)); } } function uuid() { return Math.floor(Math.random() * 10000000000000); }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/annotationsMappers"; import * as Parameters from "../models/parameters"; import { ApplicationInsightsManagementClientContext } from "../applicationInsightsManagementClientContext"; /** Class representing a Annotations. */ export class Annotations { private readonly client: ApplicationInsightsManagementClientContext; /** * Create a Annotations. * @param {ApplicationInsightsManagementClientContext} client Reference to the service client. */ constructor(client: ApplicationInsightsManagementClientContext) { this.client = client; } /** * Gets the list of annotations for a component for given time range * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param start The start time to query from for annotations, cannot be older than 90 days from * current date. * @param end The end time to query for annotations. * @param [options] The optional parameters * @returns Promise<Models.AnnotationsListResponse> */ list(resourceGroupName: string, resourceName: string, start: string, end: string, options?: msRest.RequestOptionsBase): Promise<Models.AnnotationsListResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param start The start time to query from for annotations, cannot be older than 90 days from * current date. * @param end The end time to query for annotations. * @param callback The callback */ list(resourceGroupName: string, resourceName: string, start: string, end: string, callback: msRest.ServiceCallback<Models.AnnotationsListResult>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param start The start time to query from for annotations, cannot be older than 90 days from * current date. * @param end The end time to query for annotations. * @param options The optional parameters * @param callback The callback */ list(resourceGroupName: string, resourceName: string, start: string, end: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.AnnotationsListResult>): void; list(resourceGroupName: string, resourceName: string, start: string, end: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AnnotationsListResult>, callback?: msRest.ServiceCallback<Models.AnnotationsListResult>): Promise<Models.AnnotationsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, start, end, options }, listOperationSpec, callback) as Promise<Models.AnnotationsListResponse>; } /** * Create an Annotation of an Application Insights component. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationProperties Properties that need to be specified to create an annotation of a * Application Insights component. * @param [options] The optional parameters * @returns Promise<Models.AnnotationsCreateResponse> */ create(resourceGroupName: string, resourceName: string, annotationProperties: Models.Annotation, options?: msRest.RequestOptionsBase): Promise<Models.AnnotationsCreateResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationProperties Properties that need to be specified to create an annotation of a * Application Insights component. * @param callback The callback */ create(resourceGroupName: string, resourceName: string, annotationProperties: Models.Annotation, callback: msRest.ServiceCallback<Models.Annotation[]>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationProperties Properties that need to be specified to create an annotation of a * Application Insights component. * @param options The optional parameters * @param callback The callback */ create(resourceGroupName: string, resourceName: string, annotationProperties: Models.Annotation, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Annotation[]>): void; create(resourceGroupName: string, resourceName: string, annotationProperties: Models.Annotation, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Annotation[]>, callback?: msRest.ServiceCallback<Models.Annotation[]>): Promise<Models.AnnotationsCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, annotationProperties, options }, createOperationSpec, callback) as Promise<Models.AnnotationsCreateResponse>; } /** * Delete an Annotation of an Application Insights component. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationId The unique annotation ID. This is unique within a Application Insights * component. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, resourceName: string, annotationId: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationId The unique annotation ID. This is unique within a Application Insights * component. * @param callback The callback */ deleteMethod(resourceGroupName: string, resourceName: string, annotationId: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationId The unique annotation ID. This is unique within a Application Insights * component. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, resourceName: string, annotationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, resourceName: string, annotationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, annotationId, options }, deleteMethodOperationSpec, callback); } /** * Get the annotation for given id. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationId The unique annotation ID. This is unique within a Application Insights * component. * @param [options] The optional parameters * @returns Promise<Models.AnnotationsGetResponse> */ get(resourceGroupName: string, resourceName: string, annotationId: string, options?: msRest.RequestOptionsBase): Promise<Models.AnnotationsGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationId The unique annotation ID. This is unique within a Application Insights * component. * @param callback The callback */ get(resourceGroupName: string, resourceName: string, annotationId: string, callback: msRest.ServiceCallback<Models.Annotation[]>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param resourceName The name of the Application Insights component resource. * @param annotationId The unique annotation ID. This is unique within a Application Insights * component. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, resourceName: string, annotationId: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.Annotation[]>): void; get(resourceGroupName: string, resourceName: string, annotationId: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.Annotation[]>, callback?: msRest.ServiceCallback<Models.Annotation[]>): Promise<Models.AnnotationsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, annotationId, options }, getOperationSpec, callback) as Promise<Models.AnnotationsGetResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/Annotations", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion0, Parameters.start, Parameters.end ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.AnnotationsListResult }, default: { bodyMapper: Mappers.AnnotationError } }, serializer }; const createOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/Annotations", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.resourceName ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "annotationProperties", mapper: { ...Mappers.Annotation, required: true } }, responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "Annotation" } } } } }, default: { bodyMapper: Mappers.AnnotationError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/Annotations/{annotationId}", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.resourceName, Parameters.annotationId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{resourceName}/Annotations/{annotationId}", urlParameters: [ Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.resourceName, Parameters.annotationId ], queryParameters: [ Parameters.apiVersion0 ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Sequence", element: { type: { name: "Composite", className: "Annotation" } } } } }, default: { bodyMapper: Mappers.AnnotationError } }, serializer };
the_stack
import hermite from "cubic-hermite"; import { useEffect, useState } from "react"; import { Replicache, ReadTransaction } from "replicache"; import { getClientState } from "../frontend/client-state"; import { getShape } from "../frontend/shape"; /** * Gets the current position of the cursor for `clientID`, but smoothing out * the motion by interpolating extra frames. */ export function useCursor( rep: Replicache, clientID: string ): { x: number; y: number } | null { const [values, setValues] = useState<Array<number> | null>(null); const smoothie = Smoothie.get( rep, `cursor/${clientID}`, async (tx: ReadTransaction) => { const clientState = await getClientState(tx, clientID); return [clientState.cursor.x, clientState.cursor.y]; } ); useListener(smoothie, setValues, clientID); if (!values) { return null; } const [x, y] = values; return { x, y }; } /** * Gets the current position of the shape for `shapeID`, but smoothing out * the motion by interpolating extra frames. */ export function useShape(rep: Replicache, shapeID: string) { const [values, setValues] = useState<Array<number> | null>(null); const smoother = Smoothie.get( rep, `shape/${shapeID}`, async (tx: ReadTransaction) => { const shape = await getShape(tx, shapeID); return ( shape && [shape.x, shape.y, shape.width, shape.height, shape.rotate] ); } ); useListener(smoother, setValues, shapeID); if (!values) { return null; } const [x, y, w, h, r] = values; return { x, y, w, h, r }; } /** * Tracks progress of an animation smoothing jumps between one or more * numeric properties. */ type Animation = { startValues: Array<number>; targetValues: Array<number>; startVelocities: Array<number>; targetVelocities: Array<number>; startTime: number; duration: number; currentValues: Array<number>; timerID: number; }; type Listener = (current: Array<number> | null) => void; type SubscriptionFunction = ( tx: ReadTransaction ) => Promise<Array<number> | null>; const minAnimationDuration = 50; const maxAnimationDuration = 5000; /** * Smoothie interpolates frames between Repicache subscription notifications. * * We cannot simply animate at the UI layer, because we need multiple UI * elements that appear to be together (e.g., the selection highlight for * a shape and the shape itself) to animate in lockstep. The UI lacks * sufficient information to synchronize this way. * * We use hermite splines to smooth out the frames that we get because they * are easy to use and create a more appealing curve than simply chaining * tweens between frames. */ class Smoothie { private static instances = new Map<string, Smoothie>(); /** * Gets the specified named instance * @param rep Replicache instance to query * @param key Unique name for the data to extract / smooth * @param sub A subscription function, of the type that would be passed to * Replicache.subscribe(). The return value must be an Array of numbers. * These are the values we will smooth over time. * @returns */ static get( rep: Replicache, key: string, sub: SubscriptionFunction ): Smoothie { let s = this.instances.get(key); if (!s) { s = new Smoothie(rep, sub); this.instances.set(key, s); } return s; } private rep: Replicache; // The target values we're currently animating to. private latestTargets: Array<number> | null = null; // The latest time the latestTargets changed. private latestTimestamp = 0; // The current animation we're running. Only non-null when one is // actually running. private currentAnimation: Animation | null = null; // Current listeners. private listeners = new Set<Listener>(); private constructor(rep: Replicache, sub: SubscriptionFunction) { this.rep = rep; this.rep.subscribe(sub, { onData: (targets) => { const now = performance.now(); // We can flip back to null, for example if the object we are watching // gets deleted. So we must handle that and count it as achange. if (targets == null) { this.jumpTo(null, now); return; } if (this.latestTargets == null) { this.jumpTo(targets, now); return; } if (!shallowEqual(targets, this.latestTargets)) { if (targets.length != this.latestTargets.length) { console.info("Number of targets changed - ignoring"); return; } let duration = now - this.latestTimestamp; if (duration < minAnimationDuration) { // If the time since last frame is very short, it looks better to // skip the animation. This mainly happens with frames generated // locally. this.jumpTo(targets, now); } else if (!this.currentAnimation) { // Otherwise if there's no current animation running, start one. this.currentAnimation = { startValues: this.latestTargets, targetValues: targets, startVelocities: targets.map((_) => 0), targetVelocities: targets.map((_) => 0), startTime: now, duration: this.frameDuration(now), currentValues: this.latestTargets, timerID: this.scheduleAnimate(), }; } else { // Otherwise, cancel the existing animation and start a new one. cancelAnimationFrame(this.currentAnimation.timerID); const t = (now - this.currentAnimation.startTime) / this.currentAnimation.duration; // Get the current velocities. These will be the initial // velocities for the new animation. const startVelocities = hermite.derivative( this.currentAnimation.startValues, this.currentAnimation.startVelocities, this.currentAnimation.targetValues, this.currentAnimation.targetVelocities, Math.max(0, Math.min(t, 1)) ); this.currentAnimation = { startValues: this.currentAnimation.currentValues, targetValues: targets, startVelocities, targetVelocities: targets.map((_) => 0), startTime: now, duration: this.frameDuration(now), currentValues: this.currentAnimation.currentValues, timerID: this.scheduleAnimate(), }; } this.latestTargets = targets; this.latestTimestamp = now; } }, }); } jumpTo(targets: Array<number> | null, now: number) { this.currentAnimation && cancelAnimationFrame(this.currentAnimation.timerID); this.currentAnimation = null; this.latestTargets = targets; this.latestTimestamp = now; this.fire(); } scheduleAnimate() { return requestAnimationFrame((time) => { if (!this.currentAnimation) { return; } // Update the current animated values. const t = (performance.now() - this.currentAnimation.startTime) / this.currentAnimation.duration; this.currentAnimation = { ...this.currentAnimation, currentValues: hermite( this.currentAnimation.startValues, this.currentAnimation.startVelocities, this.currentAnimation.targetValues, this.currentAnimation.targetVelocities, Math.min(1, Math.max(0, t)) ), }; this.fire(); if (t >= 1) { // If we're done, clear the animation. this.currentAnimation = null; return; } // Otherwise, schedule the next frame. this.currentAnimation.timerID == this.scheduleAnimate(); }); } private getCurrentValues(): Array<number> | null { if (this.currentAnimation) { return this.currentAnimation.currentValues; } else if (this.latestTargets) { return this.latestTargets; } else { return null; } } addListener(l: Listener) { this.listeners.add(l); const c = this.getCurrentValues(); if (c) { l(c); } } removeListener(l: Listener) { this.listeners.delete(l); } fire() { const c = this.getCurrentValues(); this.listeners.forEach((l) => { try { l(c); } catch (e) { console.error(e); } }); } frameDuration(now: number) { return Math.min( maxAnimationDuration, // We can't simply use the delay since the last frame as the // duration for the animation because we want the animation to smoothly // slow down and stop once we stop receving events. But if we're receiving // frames approximately every Fms, and we set the duration of each frame's // animation to be Fms, then we will see a choppy movement when these // animations are connected one to the next. // // Also we sometimes get frames in which no movement occurs. // This is because push can take longer than pull, so we // might have pushes happening at a rate of 150ms/frame, and pulls // happening at a rate of 100ms/frame. So every third frame or so // we'd get no new position information. In that case, if the frame duration // is close to the rate pulls are happening, we'll see the // animation slow down then speed up again. // // Instead, we arbitrarily assume that there are n additional frames // coming after this one. This has the effect of smoothing out the // animation at the cost of extending the animation n frames longer than it // actually took on the source machine. (now - this.latestTimestamp) * 3 ); } } function useListener( smoother: Smoothie, listener: (values: Array<number> | null) => void, dep: string ) { useEffect(() => { smoother.addListener(listener); return () => smoother.removeListener(listener); }, [dep]); } function shallowEqual(a1: any[], a2: any[]) { if (a1.length != a2.length) { return false; } if (a1.some((v1, idx) => v1 != a2[idx])) { return false; } return true; }
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import type * as vscode from 'vscode'; import { Uri as URI } from './uri'; import { FileEditType } from './baseTypes'; export class Disposable { static from(...inDisposables: { dispose(): any }[]): Disposable { let disposables: ReadonlyArray<{ dispose(): any }> | undefined = inDisposables; return new Disposable(function () { if (disposables) { for (const disposable of disposables) { if (disposable && typeof disposable.dispose === 'function') { disposable.dispose(); } } disposables = undefined; } }); } #callOnDispose?: () => any; constructor(callOnDispose: () => any) { this.#callOnDispose = callOnDispose; } dispose(): any { if (typeof this.#callOnDispose === 'function') { this.#callOnDispose(); this.#callOnDispose = undefined; } } } export class Position implements vscode.Position { static Min(...positions: vscode.Position[]): vscode.Position { if (positions.length === 0) { throw new TypeError(); } let result = positions[0]; for (let i = 1; i < positions.length; i++) { const p = positions[i]; if (p.isBefore(result!)) { result = p; } } return result; } static Max(...positions: vscode.Position[]): vscode.Position { if (positions.length === 0) { throw new TypeError(); } let result = positions[0]; for (let i = 1; i < positions.length; i++) { const p = positions[i]; if (p.isAfter(result!)) { result = p; } } return result; } static isPosition(other: any): other is Position { if (!other) { return false; } if (other instanceof Position) { return true; } const { line, character } = <Position>other; if (typeof line === 'number' && typeof character === 'number') { return true; } return false; } private _line: number; private _character: number; get line(): number { return this._line; } get character(): number { return this._character; } constructor(line: number, character: number) { if (line < 0) { throw illegalArgument('line must be non-negative'); } if (character < 0) { throw illegalArgument('character must be non-negative'); } this._line = line; this._character = character; } isBefore(other: vscode.Position): boolean { if (this._line < other.line) { return true; } if (other.line < this._line) { return false; } return this._character < other.character; } isBeforeOrEqual(other: vscode.Position): boolean { if (this._line < other.line) { return true; } if (other.line < this._line) { return false; } return this._character <= other.character; } isAfter(other: vscode.Position): boolean { return !this.isBeforeOrEqual(other); } isAfterOrEqual(other: vscode.Position): boolean { return !this.isBefore(other); } isEqual(other: vscode.Position): boolean { return this._line === other.line && this._character === other.character; } compareTo(other: vscode.Position): number { if (this._line < other.line) { return -1; } else if (this._line > other.line) { return 1; } else { // equal line if (this._character < other.character) { return -1; } else if (this._character > other.character) { return 1; } else { // equal line and character return 0; } } } translate(change: { lineDelta?: number; characterDelta?: number }): Position; translate(lineDelta?: number, characterDelta?: number): Position; translate( lineDeltaOrChange: number | undefined | { lineDelta?: number; characterDelta?: number }, characterDelta: number = 0 ): Position { if (lineDeltaOrChange === null || characterDelta === null) { throw illegalArgument(); } let lineDelta: number; if (typeof lineDeltaOrChange === 'undefined') { lineDelta = 0; } else if (typeof lineDeltaOrChange === 'number') { lineDelta = lineDeltaOrChange; } else { lineDelta = typeof lineDeltaOrChange.lineDelta === 'number' ? lineDeltaOrChange.lineDelta : 0; characterDelta = typeof lineDeltaOrChange.characterDelta === 'number' ? lineDeltaOrChange.characterDelta : 0; } if (lineDelta === 0 && characterDelta === 0) { return this; } return new Position(this.line + lineDelta, this.character + characterDelta); } with(change: { line?: number; character?: number }): Position; with(line?: number, character?: number): Position; with(lineOrChange: number | undefined | { line?: number; character?: number }, character: number = this.character): Position { if (lineOrChange === null || character === null) { throw illegalArgument(); } let line: number; if (typeof lineOrChange === 'undefined') { line = this.line; } else if (typeof lineOrChange === 'number') { line = lineOrChange; } else { line = typeof lineOrChange.line === 'number' ? lineOrChange.line : this.line; character = typeof lineOrChange.character === 'number' ? lineOrChange.character : this.character; } if (line === this.line && character === this.character) { return this; } return new Position(line, character); } toJSON(): unknown { return { line: this.line, character: this.character }; } } export class Range implements vscode.Range { static isRange(thing: any): thing is vscode.Range { if (thing instanceof Range) { return true; } if (!thing) { return false; } return Position.isPosition((<Range>thing).start) && Position.isPosition(<Range>thing.end); } protected _start: Position; protected _end: Position; get start(): Position { return this._start; } get end(): Position { return this._end; } constructor(start: vscode.Position, end: vscode.Position); constructor(startLine: number, startColumn: number, endLine: number, endColumn: number); constructor( startLineOrStart: number | vscode.Position, startColumnOrEnd: number | vscode.Position, endLine?: number, endColumn?: number ) { let start: Position | undefined; let end: Position | undefined; if ( typeof startLineOrStart === 'number' && typeof startColumnOrEnd === 'number' && typeof endLine === 'number' && typeof endColumn === 'number' ) { start = new Position(startLineOrStart, startColumnOrEnd); end = new Position(endLine, endColumn); } else if (startLineOrStart instanceof Position && startColumnOrEnd instanceof Position) { start = startLineOrStart; end = startColumnOrEnd; } if (!start || !end) { throw new Error('Invalid arguments'); } if (start.isBefore(end)) { this._start = start; this._end = end; } else { this._start = end; this._end = start; } } contains(positionOrRange: vscode.Position | vscode.Range): boolean { if (positionOrRange instanceof Range) { return this.contains(positionOrRange._start) && this.contains(positionOrRange._end); } else if (positionOrRange instanceof Position) { if (positionOrRange.isBefore(this._start)) { return false; } if (this._end.isBefore(positionOrRange)) { return false; } return true; } return false; } isEqual(other: vscode.Range): boolean { return this._start.isEqual(other.start) && this._end.isEqual(other.end); } intersection(other: vscode.Range): vscode.Range | undefined { const start = Position.Max(other.start, this._start); const end = Position.Min(other.end, this._end); if (start.isAfter(end)) { // this happens when there is no overlap: // |-----| // |----| return undefined; } return new Range(start, end); } union(other: Range): Range { if (this.contains(other)) { return this; } else if (other.contains(this)) { return other; } const start = Position.Min(other.start, this._start); const end = Position.Max(other.end, this.end); return new Range(start, end); } get isEmpty(): boolean { return this._start.isEqual(this._end); } get isSingleLine(): boolean { return this._start.line === this._end.line; } with(change: { start?: Position; end?: Position }): Range; with(start?: Position, end?: Position): Range; with(startOrChange: Position | undefined | { start?: Position; end?: Position }, end: Position = this.end): Range { if (startOrChange === null || end === null) { throw illegalArgument(); } let start: Position; if (!startOrChange) { start = this.start; } else if (Position.isPosition(startOrChange)) { start = startOrChange; } else { start = startOrChange.start || this.start; end = startOrChange.end || this.end; } if (start.isEqual(this._start) && end.isEqual(this.end)) { return this; } return new Range(start, end); } toJSON(): any { return [this.start, this.end]; } } export class Selection extends Range implements vscode.Selection { static isSelection(thing: any): thing is Selection { if (thing instanceof Selection) { return true; } if (!thing) { return false; } return ( Range.isRange(thing) && Position.isPosition((<Selection>thing).anchor) && Position.isPosition((<Selection>thing).active) && typeof (<Selection>thing).isReversed === 'boolean' ); } private _anchor: Position; public get anchor(): Position { return this._anchor; } private _active: Position; public get active(): Position { return this._active; } constructor(anchor: vscode.Position, active: vscode.Position); constructor(anchorLine: number, anchorColumn: number, activeLine: number, activeColumn: number); constructor( anchorLineOrAnchor: number | vscode.Position, anchorColumnOrActive: number | vscode.Position, activeLine?: number, activeColumn?: number ) { let anchor: Position | undefined; let active: Position | undefined; if ( typeof anchorLineOrAnchor === 'number' && typeof anchorColumnOrActive === 'number' && typeof activeLine === 'number' && typeof activeColumn === 'number' ) { anchor = new Position(anchorLineOrAnchor, anchorColumnOrActive); active = new Position(activeLine, activeColumn); } else if (anchorLineOrAnchor instanceof Position && anchorColumnOrActive instanceof Position) { anchor = anchorLineOrAnchor; active = anchorColumnOrActive; } if (!anchor || !active) { throw new Error('Invalid arguments'); } super(anchor, active); this._anchor = anchor; this._active = active; } get isReversed(): boolean { return this._anchor === this._end; } toJSON() { return { start: this.start, end: this.end, active: this.active, anchor: this.anchor, }; } } export class TextEdit { static isTextEdit(thing: any): thing is TextEdit { if (thing instanceof TextEdit) { return true; } if (!thing) { return false; } return Range.isRange(<TextEdit>thing) && typeof (<TextEdit>thing).newText === 'string'; } static replace(range: Range, newText: string): TextEdit { return new TextEdit(range, newText); } static insert(position: Position, newText: string): TextEdit { return TextEdit.replace(new Range(position, position), newText); } static delete(range: Range): TextEdit { return TextEdit.replace(range, ''); } static setEndOfLine(eol: vscode.EndOfLine): TextEdit { const ret = new TextEdit(new Range(new Position(0, 0), new Position(0, 0)), ''); ret.newEol = eol; return ret; } protected _range: vscode.Range; protected _newText: string | null; protected _newEol?: vscode.EndOfLine; get range(): vscode.Range { return this._range; } set range(value: vscode.Range) { if (value && !Range.isRange(value)) { throw illegalArgument('range'); } this._range = value; } get newText(): string { return this._newText || ''; } set newText(value: string) { if (value && typeof value !== 'string') { throw illegalArgument('newText'); } this._newText = value; } get newEol(): vscode.EndOfLine | undefined { return this._newEol; } set newEol(value: vscode.EndOfLine | undefined) { if (value && typeof value !== 'number') { throw illegalArgument('newEol'); } this._newEol = value; } constructor(range: vscode.Range, newText: string | null) { this._range = range; this._newText = newText; } toJSON(): any { return { range: this.range, newText: this.newText, newEol: this._newEol, }; } } export interface IFileOperationOptions { overwrite?: boolean; ignoreIfExists?: boolean; ignoreIfNotExists?: boolean; recursive?: boolean; } export interface IFileOperation { _type: FileEditType.File; from?: URI; to?: URI; options?: IFileOperationOptions; metadata?: vscode.WorkspaceEditEntryMetadata; } export interface IFileTextEdit { _type: FileEditType.Text; uri: URI; edit: vscode.TextEdit; metadata?: vscode.WorkspaceEditEntryMetadata; } export class SnippetString { static isSnippetString(thing: any): thing is SnippetString { if (thing instanceof SnippetString) { return true; } if (!thing) { return false; } return typeof (<SnippetString>thing).value === 'string'; } private static _escape(value: string): string { return value.replace(/\$|}|\\/g, '\\$&'); } private _tabstop: number = 1; value: string; constructor(value?: string) { this.value = value || ''; } appendText(string: string): SnippetString { this.value += SnippetString._escape(string); return this; } appendTabstop(number: number = this._tabstop++): SnippetString { this.value += '$'; this.value += number; return this; } appendPlaceholder(value: string | ((snippet: SnippetString) => any), number: number = this._tabstop++): SnippetString { if (typeof value === 'function') { const nested = new SnippetString(); nested._tabstop = this._tabstop; value(nested); this._tabstop = nested._tabstop; value = nested.value; } else { value = SnippetString._escape(value); } this.value += '${'; this.value += number; this.value += ':'; this.value += value; this.value += '}'; return this; } appendChoice(values: string[], number: number = this._tabstop++): SnippetString { const value = SnippetString._escape(values.toString()); this.value += '${'; this.value += number; this.value += '|'; this.value += value; this.value += '|}'; return this; } appendVariable(name: string, defaultValue?: string | ((snippet: SnippetString) => any)): SnippetString { if (typeof defaultValue === 'function') { const nested = new SnippetString(); nested._tabstop = this._tabstop; defaultValue(nested); this._tabstop = nested._tabstop; defaultValue = nested.value; } else if (typeof defaultValue === 'string') { defaultValue = defaultValue.replace(/\$|}/g, '\\$&'); } this.value += '${'; this.value += name; if (defaultValue) { this.value += ':'; this.value += defaultValue; } this.value += '}'; return this; } } export enum DiagnosticTag { Unnecessary = 1, Deprecated = 2, } export enum DiagnosticSeverity { Hint = 3, Information = 2, Warning = 1, Error = 0, } export class Location { static isLocation(thing: any): thing is Location { if (thing instanceof Location) { return true; } if (!thing) { return false; } return Range.isRange((<Location>thing).range) && URI.isUri((<Location>thing).uri); } uri: URI; range!: Range; constructor(uri: URI, rangeOrPosition: Range | Position) { this.uri = uri; if (!rangeOrPosition) { //that's OK } else if (rangeOrPosition instanceof Range) { this.range = rangeOrPosition; } else if (rangeOrPosition instanceof Position) { this.range = new Range(rangeOrPosition, rangeOrPosition); } else { throw new Error('Illegal argument'); } } toJSON(): any { return { uri: this.uri, range: this.range, }; } } export class DiagnosticRelatedInformation { static is(thing: any): thing is DiagnosticRelatedInformation { if (!thing) { return false; } return ( typeof (<DiagnosticRelatedInformation>thing).message === 'string' && (<DiagnosticRelatedInformation>thing).location && Range.isRange((<DiagnosticRelatedInformation>thing).location.range) && URI.isUri((<DiagnosticRelatedInformation>thing).location.uri) ); } location: Location; message: string; constructor(location: Location, message: string) { this.location = location; this.message = message; } static isEqual(a: DiagnosticRelatedInformation, b: DiagnosticRelatedInformation): boolean { if (a === b) { return true; } if (!a || !b) { return false; } return ( a.message === b.message && a.location.range.isEqual(b.location.range) && a.location.uri.toString() === b.location.uri.toString() ); } } export class Diagnostic { range: Range; message: string; severity: DiagnosticSeverity; source?: string; code?: string | number; relatedInformation?: DiagnosticRelatedInformation[]; tags?: DiagnosticTag[]; constructor(range: Range, message: string, severity: DiagnosticSeverity = DiagnosticSeverity.Error) { if (!Range.isRange(range)) { throw new TypeError('range must be set'); } if (!message) { throw new TypeError('message must be set'); } this.range = range; this.message = message; this.severity = severity; } toJSON(): any { return { severity: DiagnosticSeverity[this.severity], message: this.message, range: this.range, source: this.source, code: this.code, }; } static isEqual(a: Diagnostic | undefined, b: Diagnostic | undefined): boolean { if (a === b) { return true; } if (!a || !b) { return false; } return ( a.message === b.message && a.severity === b.severity && a.code === b.code && a.severity === b.severity && a.source === b.source && a.range.isEqual(b.range) && equals(a.tags, b.tags) && equals(a.relatedInformation, b.relatedInformation, DiagnosticRelatedInformation.isEqual) ); } } export enum DocumentHighlightKind { Text = 0, Read = 1, Write = 2, } export class DocumentHighlight { range: Range; kind: DocumentHighlightKind; constructor(range: Range, kind: DocumentHighlightKind = DocumentHighlightKind.Text) { this.range = range; this.kind = kind; } toJSON(): any { return { range: this.range, kind: DocumentHighlightKind[this.kind], }; } } export enum SymbolKind { File = 0, Module = 1, Namespace = 2, Package = 3, Class = 4, Method = 5, Property = 6, Field = 7, Constructor = 8, Enum = 9, Interface = 10, Function = 11, Variable = 12, Constant = 13, String = 14, Number = 15, Boolean = 16, Array = 17, Object = 18, Key = 19, Null = 20, EnumMember = 21, Struct = 22, Event = 23, Operator = 24, TypeParameter = 25, } export enum SymbolTag { Deprecated = 1, } export class SymbolInformation { static validate(candidate: SymbolInformation): void { if (!candidate.name) { throw new Error('name must not be falsy'); } } name: string; location!: Location; kind: SymbolKind; tags?: SymbolTag[]; containerName: string | undefined; constructor(name: string, kind: SymbolKind, containerName: string | undefined, location: Location); constructor(name: string, kind: SymbolKind, range: Range, uri?: URI, containerName?: string); constructor( name: string, kind: SymbolKind, rangeOrContainer: string | undefined | Range, locationOrUri?: Location | URI, containerName?: string ) { this.name = name; this.kind = kind; this.containerName = containerName; if (typeof rangeOrContainer === 'string') { this.containerName = rangeOrContainer; } if (locationOrUri instanceof Location) { this.location = locationOrUri; } else if (rangeOrContainer instanceof Range) { this.location = new Location(locationOrUri!, rangeOrContainer); } SymbolInformation.validate(this); } toJSON(): any { return { name: this.name, kind: SymbolKind[this.kind], location: this.location, containerName: this.containerName, }; } } export class DocumentSymbol { static validate(candidate: DocumentSymbol): void { if (!candidate.name) { throw new Error('name must not be falsy'); } if (!candidate.range.contains(candidate.selectionRange)) { throw new Error('selectionRange must be contained in fullRange'); } if (candidate.children) { candidate.children.forEach(DocumentSymbol.validate); } } name: string; detail: string; kind: SymbolKind; tags?: SymbolTag[]; range: Range; selectionRange: Range; children: DocumentSymbol[]; constructor(name: string, detail: string, kind: SymbolKind, range: Range, selectionRange: Range) { this.name = name; this.detail = detail; this.kind = kind; this.range = range; this.selectionRange = selectionRange; this.children = []; DocumentSymbol.validate(this); } } export enum CodeActionTrigger { Automatic = 1, Manual = 2, } export class CodeActionKind { private static readonly sep = '.'; public static Empty: CodeActionKind; public static QuickFix: CodeActionKind; public static Refactor: CodeActionKind; public static RefactorExtract: CodeActionKind; public static RefactorInline: CodeActionKind; public static RefactorRewrite: CodeActionKind; public static Source: CodeActionKind; public static SourceOrganizeImports: CodeActionKind; public static SourceFixAll: CodeActionKind; constructor(public readonly value: string) {} public append(parts: string): CodeActionKind { return new CodeActionKind(this.value ? this.value + CodeActionKind.sep + parts : parts); } public intersects(other: CodeActionKind): boolean { return this.contains(other) || other.contains(this); } public contains(other: CodeActionKind): boolean { return this.value === other.value || other.value.startsWith(this.value + CodeActionKind.sep); } } CodeActionKind.Empty = new CodeActionKind(''); CodeActionKind.QuickFix = CodeActionKind.Empty.append('quickfix'); CodeActionKind.Refactor = CodeActionKind.Empty.append('refactor'); CodeActionKind.RefactorExtract = CodeActionKind.Refactor.append('extract'); CodeActionKind.RefactorInline = CodeActionKind.Refactor.append('inline'); CodeActionKind.RefactorRewrite = CodeActionKind.Refactor.append('rewrite'); CodeActionKind.Source = CodeActionKind.Empty.append('source'); CodeActionKind.SourceOrganizeImports = CodeActionKind.Source.append('organizeImports'); CodeActionKind.SourceFixAll = CodeActionKind.Source.append('fixAll'); export class SelectionRange { range: Range; parent?: SelectionRange; constructor(range: Range, parent?: SelectionRange) { this.range = range; this.parent = parent; if (parent && !parent.range.contains(this.range)) { throw new Error('Invalid argument: parent must contain this range'); } } } export class CallHierarchyItem { _sessionId?: string; _itemId?: string; kind: SymbolKind; name: string; detail?: string; uri: URI; range: Range; selectionRange: Range; constructor(kind: SymbolKind, name: string, detail: string, uri: URI, range: Range, selectionRange: Range) { this.kind = kind; this.name = name; this.detail = detail; this.uri = uri; this.range = range; this.selectionRange = selectionRange; } } export class CallHierarchyIncomingCall { from: vscode.CallHierarchyItem; fromRanges: vscode.Range[]; constructor(item: vscode.CallHierarchyItem, fromRanges: vscode.Range[]) { this.fromRanges = fromRanges; this.from = item; } } export class CallHierarchyOutgoingCall { to: vscode.CallHierarchyItem; fromRanges: vscode.Range[]; constructor(item: vscode.CallHierarchyItem, fromRanges: vscode.Range[]) { this.fromRanges = fromRanges; this.to = item; } } export class CodeLens { range: Range; command: vscode.Command | undefined; constructor(range: Range, command?: vscode.Command) { this.range = range; this.command = command; } get isResolved(): boolean { return !!this.command; } } export class CodeInset { range: Range; height?: number; constructor(range: Range, height?: number) { this.range = range; this.height = height; } } export enum SignatureHelpTriggerKind { Invoke = 1, TriggerCharacter = 2, ContentChange = 3, } export enum CompletionTriggerKind { Invoke = 0, TriggerCharacter = 1, TriggerForIncompleteCompletions = 2, } export interface CompletionContext { readonly triggerKind: CompletionTriggerKind; readonly triggerCharacter?: string; } export enum CompletionItemKind { Text = 0, Method = 1, Function = 2, Constructor = 3, Field = 4, Variable = 5, Class = 6, Interface = 7, Module = 8, Property = 9, Unit = 10, Value = 11, Enum = 12, Keyword = 13, Snippet = 14, Color = 15, File = 16, Reference = 17, Folder = 18, EnumMember = 19, Constant = 20, Struct = 21, Event = 22, Operator = 23, TypeParameter = 24, User = 25, Issue = 26, } export enum CompletionItemTag { Deprecated = 1, } export interface CompletionItemLabel { name: string; parameters?: string; qualifier?: string; type?: string; } export class CompletionItem /* implements vscode.CompletionItem */ { label: string | CompletionItemLabel; kind?: CompletionItemKind; tags?: CompletionItemTag[]; detail?: string; documentation?: string | vscode.MarkdownString; sortText?: string; filterText?: string; preselect?: boolean; insertText?: string | SnippetString; keepWhitespace?: boolean; range?: Range | { inserting: Range; replacing: Range }; commitCharacters?: string[]; textEdit?: TextEdit; additionalTextEdits?: TextEdit[]; command?: vscode.Command; constructor(label: string | CompletionItemLabel, kind?: CompletionItemKind) { this.label = label; this.kind = kind; } toJSON(): any { return { label: this.label, kind: this.kind && CompletionItemKind[this.kind], detail: this.detail, documentation: this.documentation, sortText: this.sortText, filterText: this.filterText, preselect: this.preselect, insertText: this.insertText, textEdit: this.textEdit, }; } } export class CompletionList { isIncomplete?: boolean; items: vscode.CompletionItem[]; constructor(items: vscode.CompletionItem[] = [], isIncomplete: boolean = false) { this.items = items; this.isIncomplete = isIncomplete; } } export enum ViewColumn { Active = -1, Beside = -2, One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, } export enum StatusBarAlignment { Left = 1, Right = 2, } export enum TextEditorLineNumbersStyle { Off = 0, On = 1, Relative = 2, } export enum TextDocumentSaveReason { Manual = 1, AfterDelay = 2, FocusOut = 3, } export enum TextEditorRevealType { Default = 0, InCenter = 1, InCenterIfOutsideViewport = 2, AtTop = 3, } export enum TextEditorSelectionChangeKind { Keyboard = 1, Mouse = 2, Command = 3, } /** * These values match very carefully the values of `TrackedRangeStickiness` */ export enum DecorationRangeBehavior { /** * TrackedRangeStickiness.AlwaysGrowsWhenTypingAtEdges */ OpenOpen = 0, /** * TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges */ ClosedClosed = 1, /** * TrackedRangeStickiness.GrowsOnlyWhenTypingBefore */ OpenClosed = 2, /** * TrackedRangeStickiness.GrowsOnlyWhenTypingAfter */ ClosedOpen = 3, } // eslint-disable-next-line @typescript-eslint/no-namespace export namespace TextEditorSelectionChangeKind { export function fromValue(s: string | undefined) { switch (s) { case 'keyboard': return TextEditorSelectionChangeKind.Keyboard; case 'mouse': return TextEditorSelectionChangeKind.Mouse; case 'api': return TextEditorSelectionChangeKind.Command; } return undefined; } } export class DocumentLink { range: Range; target?: URI; tooltip?: string; constructor(range: Range, target: URI | undefined) { if (target && !URI.isUri(target)) { throw illegalArgument('target'); } if (!Range.isRange(range) || range.isEmpty) { throw illegalArgument('range'); } this.range = range; this.target = target; } } export class Color { readonly red: number; readonly green: number; readonly blue: number; readonly alpha: number; constructor(red: number, green: number, blue: number, alpha: number) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; } } export type IColorFormat = string | { opaque: string; transparent: string }; export class ColorInformation { range: Range; color: Color; constructor(range: Range, color: Color) { if (color && !(color instanceof Color)) { throw illegalArgument('color'); } if (!Range.isRange(range) || range.isEmpty) { throw illegalArgument('range'); } this.range = range; this.color = color; } } export class ColorPresentation { label: string; textEdit?: TextEdit; additionalTextEdits?: TextEdit[]; constructor(label: string) { if (!label || typeof label !== 'string') { throw illegalArgument('label'); } this.label = label; } } export enum ColorFormat { RGB = 0, HEX = 1, HSL = 2, } export enum SourceControlInputBoxValidationType { Error = 0, Warning = 1, Information = 2, } export enum TaskRevealKind { Always = 1, Silent = 2, Never = 3, } export enum TaskPanelKind { Shared = 1, Dedicated = 2, New = 3, } export class TaskGroup implements vscode.TaskGroup { private _id: string; readonly isDefault: boolean = false; public static Clean: TaskGroup = new TaskGroup('clean', 'Clean'); public static Build: TaskGroup = new TaskGroup('build', 'Build'); public static Rebuild: TaskGroup = new TaskGroup('rebuild', 'Rebuild'); public static Test: TaskGroup = new TaskGroup('test', 'Test'); public static from(value: string) { switch (value) { case 'clean': return TaskGroup.Clean; case 'build': return TaskGroup.Build; case 'rebuild': return TaskGroup.Rebuild; case 'test': return TaskGroup.Test; default: return undefined; } } constructor(id: string, _label: string) { if (typeof id !== 'string') { throw illegalArgument('name'); } if (typeof _label !== 'string') { throw illegalArgument('name'); } this._id = id; } get id(): string { return this._id; } } export enum ShellQuoting { Escape = 1, Strong = 2, Weak = 3, } export enum TaskScope { Global = 1, Workspace = 2, } export enum ProgressLocation { SourceControl = 1, Window = 10, Notification = 15, } export class TreeItem { label?: string | vscode.TreeItemLabel; resourceUri?: URI; iconPath?: string | URI | { light: string | URI; dark: string | URI }; command?: vscode.Command; contextValue?: string; tooltip?: string | vscode.MarkdownString; constructor(label: string | vscode.TreeItemLabel, collapsibleState?: vscode.TreeItemCollapsibleState); constructor(resourceUri: URI, collapsibleState?: vscode.TreeItemCollapsibleState); constructor( arg1: string | vscode.TreeItemLabel | URI, public collapsibleState: vscode.TreeItemCollapsibleState = TreeItemCollapsibleState.None ) { if (URI.isUri(arg1)) { this.resourceUri = arg1; } else { this.label = arg1; } } } export enum TreeItemCollapsibleState { None = 0, Collapsed = 1, Expanded = 2, } export class ThemeIcon { static File: ThemeIcon; static Folder: ThemeIcon; readonly id: string; readonly themeColor?: ThemeColor; constructor(id: string, color?: ThemeColor) { this.id = id; this.themeColor = color; } with(color: ThemeColor): ThemeIcon { return new ThemeIcon(this.id, color); } } ThemeIcon.File = new ThemeIcon('file'); ThemeIcon.Folder = new ThemeIcon('folder'); export class ThemeColor { id: string; constructor(id: string) { this.id = id; } } export enum ConfigurationTarget { Global = 1, Workspace = 2, WorkspaceFolder = 3, } export class DebugAdapterInlineImplementation implements vscode.DebugAdapterInlineImplementation { readonly implementation: vscode.DebugAdapter; constructor(impl: vscode.DebugAdapter) { this.implementation = impl; } } export class EvaluatableExpression implements vscode.EvaluatableExpression { readonly range: vscode.Range; readonly expression?: string; constructor(range: vscode.Range, expression?: string) { this.range = range; this.expression = expression; } } export enum LogLevel { Trace = 1, Debug = 2, Info = 3, Warning = 4, Error = 5, Critical = 6, Off = 7, } //#region file api export enum FileChangeType { Changed = 1, Created = 2, Deleted = 3, } //#endregion //#region folding api export class FoldingRange { start: number; end: number; kind?: FoldingRangeKind; constructor(start: number, end: number, kind?: FoldingRangeKind) { this.start = start; this.end = end; this.kind = kind; } } export enum FoldingRangeKind { Comment = 1, Imports = 2, Region = 3, } //#endregion //#region Comment export enum CommentThreadCollapsibleState { /** * Determines an item is collapsed */ Collapsed = 0, /** * Determines an item is expanded */ Expanded = 1, } export enum CommentMode { Editing = 0, Preview = 1, } //#endregion //#region Semantic Coloring export class SemanticTokensLegend { public readonly tokenTypes: string[]; public readonly tokenModifiers: string[]; constructor(tokenTypes: string[], tokenModifiers: string[] = []) { this.tokenTypes = tokenTypes; this.tokenModifiers = tokenModifiers; } } export class SemanticTokens { readonly resultId?: string; readonly data: Uint32Array; constructor(data: Uint32Array, resultId?: string) { this.resultId = resultId; this.data = data; } } export class SemanticTokensEdit { readonly start: number; readonly deleteCount: number; readonly data?: Uint32Array; constructor(start: number, deleteCount: number, data?: Uint32Array) { this.start = start; this.deleteCount = deleteCount; this.data = data; } } export class SemanticTokensEdits { readonly resultId?: string; readonly edits: SemanticTokensEdit[]; constructor(edits: SemanticTokensEdit[], resultId?: string) { this.resultId = resultId; this.edits = edits; } } //#endregion //#region debug export enum DebugConsoleMode { /** * Debug session should have a separate debug console. */ Separate = 0, /** * Debug session should share debug console with its parent session. * This value has no effect for sessions which do not have a parent session. */ MergeWithParent = 1, } export enum DebugConfigurationProviderTriggerKind { /** * `DebugConfigurationProvider.provideDebugConfigurations` is called to provide the initial debug configurations for a newly created launch.json. */ Initial = 1, /** * `DebugConfigurationProvider.provideDebugConfigurations` is called to provide dynamically generated debug configurations when the user asks for them through the UI (e.g. via the "Select and Start Debugging" command). */ Dynamic = 2, } //#endregion export enum ExtensionKind { UI = 1, Workspace = 2, } export class Decoration { static validate(d: Decoration): void { if (d.letter && d.letter.length !== 1) { throw new Error("The 'letter'-property must be undefined or a single character"); } if (!d.bubble && !d.color && !d.letter && !d.priority && !d.title) { throw new Error('The decoration is empty'); } } letter?: string; title?: string; color?: vscode.ThemeColor; priority?: number; bubble?: boolean; } //#region Theming export class ColorTheme implements vscode.ColorTheme { constructor(public readonly kind: ColorThemeKind) {} } export enum ColorThemeKind { Light = 1, Dark = 2, HighContrast = 3, } //#endregion Theming //#region Notebook export enum CellKind { Markdown = 1, Code = 2, } export enum CellOutputKind { Text = 1, Error = 2, Rich = 3, } export enum NotebookCellRunState { Running = 1, Idle = 2, Success = 3, Error = 4, } export enum NotebookRunState { Running = 1, Idle = 2, } export enum NotebookCellStatusBarAlignment { Left = 1, Right = 2, } export enum NotebookEditorRevealType { Default = 0, InCenter = 1, InCenterIfOutsideViewport = 2, } //#endregion //#region Timeline //#endregion Timeline //#region ExtensionContext export enum ExtensionMode { /** * The extension is installed normally (for example, from the marketplace * or VSIX) in VS Code. */ Production = 1, /** * The extension is running from an `--extensionDevelopmentPath` provided * when launching VS Code. */ Development = 2, /** * The extension is running from an `--extensionDevelopmentPath` and * the extension host is running unit tests. */ Test = 3, } export enum ExtensionRuntime { /** * The extension is running in a NodeJS extension host. Runtime access to NodeJS APIs is available. */ Node = 1, /** * The extension is running in a Webworker extension host. Runtime access is limited to Webworker APIs. */ Webworker = 2, } //#endregion ExtensionContext export enum StandardTokenType { Other = 0, Comment = 1, String = 2, RegEx = 4, } function illegalArgument(msg?: string) { return new Error(msg); } function equals<T>( one: ReadonlyArray<T> | undefined, other: ReadonlyArray<T> | undefined, itemEquals: (a: T, b: T) => boolean = (a, b) => a === b ): boolean { if (one === other) { return true; } if (!one || !other) { return false; } if (one.length !== other.length) { return false; } for (let i = 0, len = one.length; i < len; i++) { if (!itemEquals(one[i], other[i])) { return false; } } return true; }
the_stack
import { findPrice, PricePeriod } from '@joplin/lib/utils/joplinCloud'; import { UserFlagType } from '../../services/database/types'; import { AccountType } from '../../models/UserModel'; import { betaUserTrialPeriodDays, isBetaUser, stripeConfig } from '../../utils/stripe'; import { beforeAllDb, afterAllTests, beforeEachDb, models, koaAppContext, expectNotThrow } from '../../utils/testing/testUtils'; import { AppContext } from '../../utils/types'; import uuidgen from '../../utils/uuidgen'; import { postHandlers } from './stripe'; function mockStripe(overrides: any = null) { return { customers: { retrieve: jest.fn(), }, subscriptions: { del: jest.fn(), }, ...overrides, }; } interface WebhookOptions { stripe?: any; eventId?: string; subscriptionId?: string; customerId?: string; sessionId?: string; } async function simulateWebhook(ctx: AppContext, type: string, object: any, options: WebhookOptions = {}) { options = { stripe: mockStripe(), eventId: uuidgen(), ...options, }; await postHandlers.webhook(options.stripe, {}, ctx, { id: options.eventId, type, data: { object, }, }, false); } async function createUserViaSubscription(ctx: AppContext, userEmail: string, options: WebhookOptions = {}) { options = { subscriptionId: `sub_${uuidgen()}`, customerId: `cus_${uuidgen()}`, ...options, }; const stripeSessionId = 'sess_123'; const stripePrice = findPrice(stripeConfig().prices, { accountType: 2, period: PricePeriod.Monthly }); await models().keyValue().setValue(`stripeSessionToPriceId::${stripeSessionId}`, stripePrice.id); await simulateWebhook(ctx, 'checkout.session.completed', { id: stripeSessionId, customer: options.customerId, subscription: options.subscriptionId, customer_details: { email: userEmail, }, }, options); } describe('index/stripe', function() { beforeAll(async () => { await beforeAllDb('index/stripe'); stripeConfig().enabled = true; }); afterAll(async () => { await afterAllTests(); }); beforeEach(async () => { await beforeEachDb(); }); test('should handle the checkout.session.completed event', async function() { const startTime = Date.now(); const ctx = await koaAppContext(); await createUserViaSubscription(ctx, 'toto@example.com', { subscriptionId: 'sub_123' }); const user = await models().user().loadByEmail('toto@example.com'); expect(user.account_type).toBe(AccountType.Pro); expect(user.email_confirmed).toBe(0); const sub = await models().subscription().byUserId(user.id); expect(sub.stripe_subscription_id).toBe('sub_123'); expect(sub.is_deleted).toBe(0); expect(sub.last_payment_time).toBeGreaterThanOrEqual(startTime); expect(sub.last_payment_failed_time).toBe(0); }); test('should not process the same event twice', async function() { const ctx = await koaAppContext(); await createUserViaSubscription(ctx, 'toto@example.com', { eventId: 'evt_1' }); const v = await models().keyValue().value('stripeEventDone::evt_1'); expect(v).toBe(1); // This event should simply be skipped await expectNotThrow(async () => createUserViaSubscription(ctx, 'toto@example.com', { eventId: 'evt_1' })); }); test('should check if it is a beta user', async function() { const user1 = await models().user().save({ email: 'toto@example.com', password: uuidgen() }); const user2 = await models().user().save({ email: 'tutu@example.com', password: uuidgen() }); await models().user().save({ id: user2.id, created_time: 1624441295775 }); expect(await isBetaUser(models(), user1.id)).toBe(false); expect(await isBetaUser(models(), user2.id)).toBe(true); await models().subscription().save({ user_id: user2.id, stripe_user_id: 'usr_111', stripe_subscription_id: 'sub_111', last_payment_time: Date.now(), }); expect(await isBetaUser(models(), user2.id)).toBe(false); }); test('should find out beta user trial end date', async function() { const fromDateTime = 1627901594842; // Mon Aug 02 2021 10:53:14 GMT+0000 expect(betaUserTrialPeriodDays(1624441295775, fromDateTime)).toBe(50); // Wed Jun 23 2021 09:41:35 GMT+0000 expect(betaUserTrialPeriodDays(1614682158000, fromDateTime)).toBe(7); // Tue Mar 02 2021 10:49:18 GMT+0000 }); test('should setup subscription for an existing user', async function() { // This is for example if a user has been manually added to the system, // and then later they setup their subscription. Applies to beta users // for instance. const ctx = await koaAppContext(); const user = await models().user().save({ email: 'toto@example.com', password: uuidgen() }); expect(await models().subscription().byUserId(user.id)).toBeFalsy(); await createUserViaSubscription(ctx, 'toto@example.com', { subscriptionId: 'sub_123' }); const sub = await models().subscription().byUserId(user.id); expect(sub).toBeTruthy(); expect(sub.stripe_subscription_id).toBe('sub_123'); }); test('should cancel duplicate subscriptions', async function() { const stripe = mockStripe(); const ctx = await koaAppContext(); await createUserViaSubscription(ctx, 'toto@example.com', { stripe }); expect((await models().user().all()).length).toBe(1); const user = (await models().user().all())[0]; const subBefore = await models().subscription().byUserId(user.id); expect(stripe.subscriptions.del).toHaveBeenCalledTimes(0); await createUserViaSubscription(ctx, 'toto@example.com', { stripe }); expect((await models().user().all()).length).toBe(1); const subAfter = await models().subscription().byUserId(user.id); expect(stripe.subscriptions.del).toHaveBeenCalledTimes(1); expect(subBefore.stripe_subscription_id).toBe(subAfter.stripe_subscription_id); }); test('should disable an account if the sub is cancelled', async function() { const stripe = mockStripe(); const ctx = await koaAppContext(); await createUserViaSubscription(ctx, 'toto@example.com', { stripe, subscriptionId: 'sub_init' }); await simulateWebhook(ctx, 'customer.subscription.deleted', { id: 'sub_init' }); const user = (await models().user().all())[0]; const sub = (await models().subscription().all())[0]; expect(user.enabled).toBe(0); expect(sub.is_deleted).toBe(1); }); test('should re-enable account if sub was cancelled and new sub created', async function() { const stripe = mockStripe(); const ctx = await koaAppContext(); await createUserViaSubscription(ctx, 'toto@example.com', { stripe, subscriptionId: 'sub_init' }); const user = (await models().user().all())[0]; const sub = await models().subscription().byUserId(user.id); expect(sub.stripe_subscription_id).toBe('sub_init'); await simulateWebhook(ctx, 'customer.subscription.deleted', { id: 'sub_init' }); await createUserViaSubscription(ctx, 'toto@example.com', { stripe, subscriptionId: 'cus_recreate' }); { const user = (await models().user().all())[0]; const sub = await models().subscription().byUserId(user.id); expect(user.enabled).toBe(1); expect(sub.is_deleted).toBe(0); expect(sub.stripe_subscription_id).toBe('cus_recreate'); } }); test('should re-enable account if successful payment is made', async function() { const stripe = mockStripe(); const ctx = await koaAppContext(); await createUserViaSubscription(ctx, 'toto@example.com', { stripe, subscriptionId: 'sub_init' }); let user = (await models().user().all())[0]; await models().user().save({ id: user.id, enabled: 0, can_upload: 0, }); await models().userFlag().add(user.id, UserFlagType.FailedPaymentFinal); await simulateWebhook(ctx, 'invoice.paid', { subscription: 'sub_init' }); user = await models().user().load(user.id); expect(user.enabled).toBe(1); expect(user.can_upload).toBe(1); }); test('should attach new sub to existing user', async function() { // Simulates: // - User subscribes // - Later the subscription is cancelled, either automatically by Stripe or manually // - Then a new subscription is attached to the user on Stripe // => In that case, the sub should be attached to the user on Joplin Server const stripe = mockStripe({ customers: { retrieve: async () => { return { name: 'Toto', email: 'toto@example.com', }; }, }, }); const ctx = await koaAppContext(); await createUserViaSubscription(ctx, 'toto@example.com', { stripe, subscriptionId: 'sub_1', customerId: 'cus_toto', }); await simulateWebhook(ctx, 'customer.subscription.deleted', { id: 'sub_1' }); const stripePrice = findPrice(stripeConfig().prices, { accountType: 1, period: PricePeriod.Monthly }); await simulateWebhook(ctx, 'customer.subscription.created', { id: 'sub_new', customer: 'cus_toto', items: { data: [{ price: { id: stripePrice.id } }] }, }, { stripe }); const user = (await models().user().all())[0]; const sub = await models().subscription().byUserId(user.id); expect(sub.stripe_user_id).toBe('cus_toto'); expect(sub.stripe_subscription_id).toBe('sub_new'); }); test('should not cancel a subscription as duplicate if it is already associated with a user', async function() { // When user goes through a Stripe checkout, we get the following // events: // // - checkout.session.completed // - customer.subscription.created // // However we create the subscription as soon as we get // "checkout.session.completed", because by then we already have all the // necessary information. The problem is that Stripe is then going to // send "customer.subscription.created", even though the sub is already // created. Also we have some code to cancel duplicate subscriptions // (when a user accidentally subscribe multiple times), and we don't // want that newly, valid, subscription to be cancelled as a duplicate. const stripe = mockStripe({ customers: { retrieve: async () => { return { name: 'Toto', email: 'toto@example.com', }; }, }, }); const ctx = await koaAppContext(); await createUserViaSubscription(ctx, 'toto@example.com', { stripe, subscriptionId: 'sub_1', customerId: 'cus_toto', }); const stripePrice = findPrice(stripeConfig().prices, { accountType: 1, period: PricePeriod.Monthly }); await simulateWebhook(ctx, 'customer.subscription.created', { id: 'sub_1', customer: 'cus_toto', items: { data: [{ price: { id: stripePrice.id } }] }, }, { stripe }); // Verify that we didn't try to delete that new subscription expect(stripe.subscriptions.del).toHaveBeenCalledTimes(0); }); });
the_stack
import { Component, EventEmitter, Input, Output, OnChanges, SimpleChanges, ViewChild, ElementRef, Renderer2 } from '@angular/core'; import { Subject, Observable, of as observableOf } from 'rxjs'; import { List } from 'immutable'; import { clamp, compact, isEmpty } from 'lodash'; import { SearchBarCategoryItem, Chicklet, SuggestionItem } from 'app/types/types'; import { debounceTime, switchMap, distinctUntilChanged } from 'rxjs/operators'; @Component({ selector: 'app-search-bar', templateUrl: './search-bar.component.html', styleUrls: ['./search-bar.component.scss'] }) export class SearchBarComponent implements OnChanges { suggestionsVisible = false; isLoadingSuggestions = false; highlightedIndex = -1; inputText = ''; selectedCategoryType: SearchBarCategoryItem = undefined; visibleCategories = List<SearchBarCategoryItem>(); suggestions: List<SuggestionItem> = List<SuggestionItem>(); private suggestionsVisibleStream = new Subject<boolean>(); private suggestionSearchTermDebounce = new Subject<Chicklet>(); @Input() numberOfFilters: number; @Input() categories: SearchBarCategoryItem[] = []; @Input() dynamicSuggestions: string[]; @Output() suggestValues: EventEmitter<any> = new EventEmitter<any>(); @Output() itemSelected: EventEmitter<any> = new EventEmitter<any>(); @Output() filtersButtonClick: EventEmitter<any> = new EventEmitter<any>(); @ViewChild('search_box', { static: true }) inputField: ElementRef; constructor(private renderer: Renderer2) { // This is needed because focus is lost when clicking items. this.suggestionsVisibleStream.pipe( // wait 0.2 seconds after each lost and gain focus debounceTime(200), // switch to the latest focus change switchMap((active: boolean): Observable<boolean> => { return observableOf(active); }) ).subscribe((active: boolean) => { this.suggestionsVisible = active; }); this.suggestionSearchTermDebounce.pipe( // wait 1/3 second after each keystroke before considering the term debounceTime(300), // ignore new term if same as previous term distinctUntilChanged() ).subscribe((c: Chicklet) => { if (c.text && c.text.length > 0) { this.isLoadingSuggestions = true; this.suggestValues.emit({ detail: c }); } }); } ngOnChanges(changes: SimpleChanges) { if (changes.dynamicSuggestions) { this.suggestions = List<SuggestionItem>( compact(changes.dynamicSuggestions.currentValue.filter((suggestion) => !isEmpty(suggestion)).map((suggestion) => { return {name: suggestion, title: suggestion}; }))); this.isLoadingSuggestions = false; } if (changes.categories) { this.visibleCategories = List<SearchBarCategoryItem>(changes.categories.currentValue); } } handleFiltersClick() { this.filtersButtonClick.emit(); } handleFocusOut() { this.suggestionsVisibleStream.next(false); } handleCategoryClick(): void { this.clearAll(); this.suggestionsVisibleStream.next(true); this.renderer.selectRootElement('#search_box').focus(); } // Handlers // We bind to both the focus and click events here. We do that because the dropdown // is closed via the app_click action that is triggered from the app component. We // need to stopPropagation here to prevent the app_click action from triggering and // immediately closing the dropdown. handleFocus(event: Event): void { event.stopPropagation(); this.suggestionsVisibleStream.next(true); } handleSuggestionClick(suggestion: SuggestionItem, event: Event): void { event.stopPropagation(); const type = this.selectedCategoryType.type; this.clearAll(); this.itemSelected.emit({ detail: { text: suggestion.name, type: type}}); } // This is triggered when a user clicks on an item in the dropdown. handleCategoryItemClick(type: SearchBarCategoryItem, event: Event): void { event.stopPropagation(); if (!this.selectedCategoryType) { this.categorySelected(type); } } handleSuggestionItemOnMouseOver(index: number): void { this.highlightedIndex = index; } handleCategoryItemOnMouseOver(index: number): void { this.highlightedIndex = index; } pressArrowDown(): void { const downList = (this.selectedCategoryType) ? this.suggestions : this.visibleCategories; this.highlightedIndex = clamp( this.highlightedIndex + 1, -1, downList.size - 1 ); this.suggestionsVisible = true; } pressArrowUp(): void { const upList = (this.selectedCategoryType) ? this.suggestions : this.visibleCategories; this.highlightedIndex = clamp( this.highlightedIndex + -1, -1, upList.size - 1 ); this.suggestionsVisible = true; } pressEnterCategorySelected(currentText: string): void { if (this.highlightedIndex >= 0) { const sug: SuggestionItem = this.suggestions.get(this.highlightedIndex); const type: string = this.selectedCategoryType.type; this.clearAll(); this.itemSelected.emit({ detail: { text: sug.name, type: type }}); } else { if (this.hasStaticSuggestions()) { if (!this.suggestions.isEmpty()) { if ( this.suggestions.size === 1) { const sug = this.suggestions.first(); const type = this.selectedCategoryType.type; this.clearAll(); this.itemSelected.emit({ detail: { text: sug.name, type: type}}); } } } else { if (this.selectedCategoryType.allowWildcards && (currentText.indexOf('?') >= 0 || currentText.indexOf('*') >= 0) ) { const type = this.selectedCategoryType.type; this.clearAll(); this.itemSelected.emit({ detail: { text: currentText, type: type}}); } else if (!this.suggestions.isEmpty()) { const foundSuggestion = this.suggestions.find((suggestion: SuggestionItem, _key: number, _iter: any) => suggestion.title === currentText); if (foundSuggestion) { const type = this.selectedCategoryType.type; this.clearAll(); this.itemSelected.emit({ detail: { text: foundSuggestion.name, type: type}}); } } } } } pressEnter(currentText: string): void { if (this.selectedCategoryType) { this.pressEnterCategorySelected(currentText); } else { if (!this.visibleCategories.isEmpty()) { if (this.highlightedIndex >= 0) { const type = this.visibleCategories.get(this.highlightedIndex); this.categorySelected(type); } else if ( this.visibleCategories.size === 1) { const type = this.visibleCategories.first(); this.categorySelected(type); } } } this.suggestionsVisible = true; } pressBackspace(currentText: string): void { if (this.selectedCategoryType) { if (this.inputText === '') { this.clearCategorySelected(); } else { if (!this.hasStaticSuggestions()) { const type = this.selectedCategoryType.type; this.clearSuggestions(); this.requestForSuggestions({ text: currentText, type: type }); } else { this.updateVisibleProvidedSuggestions(currentText); } } } else { if (this.inputText === '') { this.clearCategorySelected(); } else { this.updateVisibleCategories(currentText); } } this.inputText = currentText; this.suggestionsVisible = true; } pressDefaultText(currentText: string): void { if (this.selectedCategoryType) { if (!this.hasStaticSuggestions()) { const type = this.selectedCategoryType.type; this.clearSuggestions(); this.requestForSuggestions({ text: currentText, type: type }); } else { this.updateVisibleProvidedSuggestions(currentText); } } else { this.updateVisibleCategories(currentText); } this.inputText = currentText; this.suggestionsVisible = true; } handleInput(key, currentText): void { switch (key.toLowerCase()) { case 'arrowdown': this.pressArrowDown(); break; case 'arrowup': this.pressArrowUp(); break; case 'arrowleft': this.suggestionsVisible = true; break; case 'arrowright': this.suggestionsVisible = true; break; case 'enter': this.pressEnter(currentText); break; case 'backspace': this.pressBackspace(currentText); break; case 'escape': this.suggestionsVisible = false; break; default: this.pressDefaultText(currentText); break; } } getFilterText(): string { if (this.selectedCategoryType) { switch (this.selectedCategoryType.type) { case 'platform': return 'Enter a platform type'; case 'policy_revision': return 'Enter a revision ID number'; case '': return 'Filter nodes by …'; default: const normal_type = this.selectedCategoryType.text.replace( '_name', '').split('_').join(' '); return `Enter ${normal_type} name`; } } else { return 'Filter by...'; } } categorySelected(type: SearchBarCategoryItem): void { this.selectedCategoryType = type; this.inputText = ''; this.highlightedIndex = -1; this.inputField.nativeElement.value = ''; this.inputField.nativeElement.focus(); if (this.hasStaticSuggestions()) { this.suggestions = List<SuggestionItem>(type.providedValues); this.suggestionsVisible = true; this.isLoadingSuggestions = false; } else { this.suggestValues.emit({ detail: { text: '', type: type.type } }); } } clearCategorySelected(): void { this.selectedCategoryType = undefined; this.visibleCategories = List(this.categories); this.highlightedIndex = -1; } clearAll(): void { this.clearCategorySelected(); this.clearSuggestions(); this.highlightedIndex = -1; this.inputField.nativeElement.value = ''; } clearSuggestions(): void { this.suggestions = List<SuggestionItem>(); this.dynamicSuggestions = []; this.highlightedIndex = -1; } updateVisibleCategories(currentText: string): void { this.highlightedIndex = -1; this.visibleCategories = List(this.categories.filter(cat => { return cat.text.toLowerCase().indexOf(currentText.toLowerCase()) !== -1; })); } updateVisibleProvidedSuggestions(currentText: string): void { this.highlightedIndex = -1; this.suggestions = List(this.selectedCategoryType.providedValues.filter( (item: SuggestionItem) => { return item.title.toLowerCase().indexOf(currentText.toLowerCase()) !== -1; })); } requestForSuggestions(c: Chicklet): void { this.isLoadingSuggestions = true; this.suggestionSearchTermDebounce.next(c); this.suggestValues.emit({ detail: { text: c.text, type: c.type } }); } hasStaticSuggestions(): boolean { return this.selectedCategoryType.providedValues !== undefined; } }
the_stack
import { encode as encodeWithPackBitsForICNS } from "./lib/icns-encoder"; import { Image } from "./lib/Image"; import * as Resize from "./lib/resize3"; import * as Resize4 from "./lib/resize4"; import * as UPNG from "./lib/UPNG"; /** * Support of Apple ICNS format is based on https://en.wikipedia.org/wiki/Apple_Icon_Image_format * * Support of Microsoft ICO format is based on http://fileformats.wikia.com/wiki/Icon * and https://en.wikipedia.org/wiki/ICO_(file_format). * * Uses additional code taken and modified from the resources below. * * Read/write PNG images: * https://github.com/photopea/UPNG.js * https://github.com/photopea/UPNG.js/blob/e984235ee69b97e99380153c9fc32ec5a44e5614/UPNG.js * Copyright (c) 2017 Photopea, Ivan Kutskir, https://www.photopea.com * The MIT License (MIT) * * Resize images (original code): * https://github.com/guyonroche/imagejs * https://github.com/guyonroche/imagejs/blob/33e6806afd3fc69fe39c1a610b7ffeac063b3f3e/lib/resize.js * Copyright (c) 2015 guyonroche, Guyon Roche * The MIT License (MIT) * * Resize images and image blitting (blit, getPixelIndex, scan): * https://github.com/oliver-moran/jimp * https://github.com/oliver-moran/jimp/blob/7fd08253b02f0865029ba00f17dbe7a9f38f4d83/resize2.js * https://github.com/oliver-moran/jimp/blob/05db5dfb9101585530ec508123ea4feab23df897/index.js * Copyright (c) 2014 Oliver Moran * The MIT License (MIT) * * Packbits compression for certain Apple ICNS icon types: * https://github.com/fiahfy/packbits * Hints from * https://github.com/fiahfy/packbits/issues/1 * Hints for bitmap masks (method createBitmap) from * https://github.com/fiahfy/ico/blob/master/src/index.js * Copyright (c) 2018 fiahfy, https://fiahfy.github.io/ * The MIT License (MIT) */ //////////////////////////////////////// // Logging //////////////////////////////////////// /** * Logger function type (compatible with console.log). */ export type Logger = (message: any, ...optionalParams: any[]) => void; /** * External log function. */ let logFnc: Logger | undefined; /** * Set an external logger for log messages from png2icons and UPNG. * Note: If no logger is set, *nothing* will ever be logged, not even errors. * @param logger Called with info/error messages during processing. */ export function setLogger(logger: Logger): void { logFnc = logger; } /** * Internal log function. Only calls the external logger if it exists. * @param message Primary log message. * @param optionalParams Any number of additional log messages. */ function LogMessage(message: any, ...optionalParams: any[]): void { if (logFnc) { logFnc("png2icons", message, ...optionalParams); } } //////////////////////////////////////// // Common code //////////////////////////////////////// /** * Maximum number of colors for color reduction. */ const MAX_COLORS: number = 256; /** * `Nearest neighbor` resizing interploation algorithm. * @see resize3.js */ export const NEAREST_NEIGHBOR = 0; /** * `Bilinear` resizing interploation algorithm. * @see resize3.js */ export const BILINEAR = 1; /** * `Bicubic` resizing interploation algorithm. * @see resize3.js */ export const BICUBIC = 2; /** * `Bezier` resizing interploation algorithm. * @see resize3.js */ export const BEZIER = 3; /** * `Hermite` resizing interploation algorithm. * @see resize3.js */ export const HERMITE = 4; /** * `Bicubic` resizing interploation algorithm. * @see resize4.js */ export const BICUBIC2 = 5; /** * `Bilinear` resizing interploation algorithm. * @see resize4.js */ // export const BILINEAR2 = 6; /** * Simple rectangle. */ interface IRect { // tslint:disable-next-line: completed-docs Left: number; // tslint:disable-next-line: completed-docs Top: number; // tslint:disable-next-line: completed-docs Width: number; // tslint:disable-next-line: completed-docs Height: number; } /** * Create and return a rectangle. * @param left Left position (upper left corner) * @param top Top position (upper left corner). * @param width Width of rectangle. * @param height Height of rectangle. * @returns A new rectangle created from the input parameters. */ function getRect(left: number, top: number, width: number, height: number): IRect { return { Left: left, Top: top, Width: width, Height: height }; } /** * Fit one rectangle into another one. * @param src Source rectangle. * @param dst Destination rectangle. * @returns A new rectangle where "src" has been upsized/downsized proportionally to fit exactly in to "dst". */ function getStretchedRect(src: IRect, dst: IRect): IRect { let f: number; let tmp: number; const result: IRect = getRect(0, 0, 0, 0); if ((src.Width / src.Height) >= (dst.Width / dst.Height)) { f = (dst.Width / src.Width); result.Left = 0; result.Width = dst.Width; tmp = Math.floor(src.Height * f); result.Top = Math.floor((dst.Height - tmp) / 2); result.Height = tmp; } else { f = (dst.Height / src.Height); result.Top = 0; result.Height = dst.Height; tmp = Math.floor(src.Width * f); result.Left = Math.floor((dst.Width - tmp) / 2); result.Width = tmp; } return result; } /** * Holds already scaled images (raw pixels). */ const scaledImageCache: Image[] = []; /** * Scale a source image to fit into a new given size. The result of the scaling * is put to a cache. If the cache already contains a scaled image of the same * size this is returned immediately instead. Scaling also isn't done if the * source and destination rectangles are the same. * @see resize.js * @param srcImage Source image. * @param destRect Destination rectangle to fit the rescaled image into. * @param scalingAlgorithm Scaling method (one of the constants NEAREST_NEIGHBOR, BILINEAR, ...). * @returns Uint8Array The rescaled image. */ function getScaledImageData(srcImage: Image, destRect: IRect, scalingAlgorithm: number): Uint8Array { // Nothing to do if ((srcImage.width === destRect.Width) && (srcImage.height === destRect.Height)) { return srcImage.data; } // Already rescaled for (const image of scaledImageCache) { if ((destRect.Width === image.width) && (destRect.Height === image.height)) { return image.data; } } const scaleResult: Image = { data: new Uint8Array(destRect.Width * destRect.Height * 4), height: destRect.Height, width: destRect.Width, }; if (scalingAlgorithm === NEAREST_NEIGHBOR) { Resize.nearestNeighbor(srcImage, scaleResult); } else if (scalingAlgorithm === BILINEAR) { Resize.bilinearInterpolation(srcImage, scaleResult); } else if (scalingAlgorithm === BICUBIC) { Resize.bicubicInterpolation(srcImage, scaleResult); } else if (scalingAlgorithm === BEZIER) { Resize.bezierInterpolation(srcImage, scaleResult); } else if (scalingAlgorithm === HERMITE) { Resize.hermiteInterpolation(srcImage, scaleResult); } else if (scalingAlgorithm === BICUBIC2) { Resize4.bicubic(srcImage, scaleResult, destRect.Width / srcImage.width); // } else if (scalingAlgorithm === BILINEAR2) { // Resize4.bilinear(srcImage, scaleResult, destRect.Width / srcImage.width); } else { Resize.bicubicInterpolation(srcImage, scaleResult); } scaledImageCache.push(scaleResult); return scaleResult.data; } /** * Create an image form a PNG. * @param input A buffer containing the raw PNG data/file. * @returns Image An image containing the raw bitmap and the image dimensions. * @see Declaration image.d.ts. */ function getImageFromPNG(input: Buffer): Image | null { try { // Decoded PNG image const PNG: UPNG.UPNGImage = UPNG.decode(input); return { data: new Uint8Array(UPNG.toRGBA8(PNG)[0]), height: PNG.height, width: PNG.width, }; } catch (e) { LogMessage("Couldn't decode PNG:", e); return null; } } /** * An already PNG encoded image. */ interface IPNGImage { // tslint:disable-next-line: completed-docs Data: ArrayBuffer; // tslint:disable-next-line: completed-docs Width: number; // tslint:disable-next-line: completed-docs Height: number; } /** * Holds already scaled images (PNG encoded). */ const scaledPNGImageCache: IPNGImage[] = []; /** * Encode a raw RGBA image to PNG. The result of the encoding is put to a cache. * If the cache already contains a PNG image of the same size this is returned * immediately instead. * @param rgba An ArrayBuffer holding the raw RGBA image data. * @param width Width of the image to be encoded. * @param height Height of the image to be encoded. * @param numOfColors Number of colors to reduce to. * @returns A PNG image. */ function getCachedPNG(rgba: ArrayBuffer, width: number, height: number, numOfColors: number) { // Already encoded for (const image of scaledPNGImageCache) { if ((image.Width === width) && (image.Height === height)) { return image.Data; } } const result = UPNG.encode([rgba], width, height, numOfColors, [], true); scaledPNGImageCache.push({ Data: result, Width: width, Height: height, }); return result; } /** * The image which is currently processed. * @see function `checkCache()`. */ let currentImage: Buffer | null = null; /** * Checks if the given image has been cached/processed already. If the * given image differs from the current one both caches are cleared. * @param image The (new) input image. */ function checkCache(image: Buffer): void { if (!image) { return; } if (!currentImage) { currentImage = image; return; } if (image.compare(currentImage) !== 0) { clearCache(); currentImage = image; } } /** * Clears both image caches (input PNG and scaled images). */ export function clearCache(): void { scaledPNGImageCache.length = 0; scaledImageCache.length = 0; currentImage = null; } /** * Scans through a region of the bitmap, calling a function for each pixel. * @param x The x coordinate to begin the scan at. * @param y The y coordiante to begin the scan at. * @param w The width of the scan region. * @param h The height of the scan region. * @param f A function to call on every pixel; the (x, y) position of the pixel * and the index of the pixel in the bitmap buffer are passed to the function. */ function scanImage(image: Image, x: number, y: number, w: number, h: number, f: (sx: number, sy: number, idx: number) => void): void { for (let _y = y; _y < (y + h); _y++) { for (let _x = x; _x < (x + w); _x++) { // tslint:disable-next-line:no-bitwise const idx = (image.width * _y + _x) << 2; f.call(image, _x, _y, idx); } } } /** * Blits a source image onto a target image. * @param source The source image. * @param target The target image. * @param x The x position in target to blit the source image. * @param y The y position target to blit the source image. */ function blit(source: Image, target: Image, x: number, y: number) { x = Math.round(x); y = Math.round(y); scanImage(source, 0, 0, source.width, source.height, (sx: number, sy: number, idx: number) => { if ((x + sx >= 0) && (y + sy >= 0) && (target.width - x - sx > 0) && (target.height - y - sy > 0)) { // tslint:disable-next-line:no-bitwise const destIdx = (target.width * (y + sy) + (x + sx)) << 2; // const destIdx = getPixelIndex(target, x + sx, y + sy); target.data[destIdx] = source.data[idx]; target.data[destIdx + 1] = source.data[idx + 1]; target.data[destIdx + 2] = source.data[idx + 2]; target.data[destIdx + 3] = source.data[idx + 3]; } }); } /** * Create a quadratic image form a non quadratic image. The source image * will be centered horizontally and vertically onto the result image. * The "non-used" pixels in the target image are used as an alpha channel. * @param image A non-quadratic image. * @returns A quadratic image. */ function getQuadraticImage(image: Image): Image { if (image.height === image.width) { return image; } let edgeLength: number; let blitX: number; let blitY: number; if (image.height > image.width) { edgeLength = image.height; blitX = (image.height - image.width) / 2; blitY = 0; } else { edgeLength = image.width; blitX = 0; blitY = (image.width - image.height) / 2; } const result: Image | null = { data: new Uint8Array(edgeLength * edgeLength * 4), height: edgeLength, width: edgeLength, }; blit(image, result, blitX, blitY); return result; } /** * Extract a single channel of an image with n bytes per pixel, e. g. in RGBA format. * @param image Input image. * @param bpp Number of bytes per pixel. * @param channelIndex Position of the channel byte in the <bpp>-value for each pixel. * @returns The extracted channel. */ function getImageChannel(image: Uint8Array, bpp: number, channelIndex: number): Buffer { const channel: Buffer = Buffer.alloc(image.length / bpp); const length: number = image.length; let outPos: number = 0; for (let i = channelIndex; i < length; i = i + 4) { channel.writeUInt8(image[i], outPos++); } return channel; } //////////////////////////////////////// // Apple ICNS //////////////////////////////////////// /** * Icon format */ enum IconFormat { /** * Compression type PNG for icon. */ PNG, /** * Compression type ARGB PackBits (for icon types ic05 and ic04). */ PackBitsARGB, /** * Compression type RGB PackBits (for icon types il32 and is32). */ PackBitsRGB, /** * (Uncompressed) alpha channel only (for icon masks l8mk and s8mk). */ Alpha, } /** * Data for one icon chunk. */ interface IICNSChunkParams { /** * Magic number for icon type. */ OSType: string; /** * (Compression) Type for icon. */ Format: IconFormat; /** * Icon output size. */ Size: number; /** * Info for logging. */ Info: string; } /** * Convert an RGBA image into a PackBits compressed (A)RBG image, (with header). * @param image Input image in RGBA format. * @param withAlphaChannel Write out an alpha channel and the appropriate header. * @returns Output image in (A)RGB format, compressed with PackBits and preceeded by * an "ARGB" header, if applicable. */ function encodeIconWithPackBits(image: Buffer, withAlphaChannel: boolean): Uint8Array { const R: Buffer = encodeWithPackBitsForICNS(getImageChannel(image, 4, 0)); const G: Buffer = encodeWithPackBitsForICNS(getImageChannel(image, 4, 1)); const B: Buffer = encodeWithPackBitsForICNS(getImageChannel(image, 4, 2)); if (withAlphaChannel) { const header: Buffer = Buffer.alloc(4); header.write("ARGB", 0, 4, "ascii"); const A: Buffer = encodeWithPackBitsForICNS(getImageChannel(image, 4, 3)); return Buffer.concat([header, A, R, G, B], header.length + A.length + R.length + G.length + B.length); } else { return Buffer.concat([R, G, B], R.length + G.length + B.length); } } /** * Create and append an ICNS icon chunk to the final result buffer. * @see resize.js, UPNG.js * @param chunkParams Object which configures the icon chunk generation. * @param srcImage The source image. * @param scalingAlgorithm Scaling method (one of the constants NEAREST_NEIGHBOR, BILINEAR, ...). * @param numOfColors Maximum colors in output ICO chunks (0 = all colors/lossless, other values (> 0) means lossy). * @param outBuffer The buffer where the generated chunk *shall be* appended to. * @returns The buffer where the generated chunk *has been* appended to (outbuffer+icon chunk) * or null if an error occured. */ function appendIcnsChunk(chunkParams: IICNSChunkParams, srcImage: Image, scalingAlgorithm: number, numOfColors: number, outBuffer: Buffer): Buffer | null { try { // Fit source rect to target rect const icnsChunkRect: IRect = getStretchedRect( getRect(0, 0, srcImage.width, srcImage.height), getRect(0, 0, chunkParams.Size, chunkParams.Size), ); // Scale image const scaledRawData: Uint8Array = getScaledImageData(srcImage, icnsChunkRect, scalingAlgorithm); // Icon buffer let encodedIcon: ArrayBuffer; // Header bytes or every icon const iconHeader: Buffer = Buffer.alloc(8); // Write icon header, eg 'ic10' + (length of icon + icon header length) iconHeader.write(chunkParams.OSType, 0); // Write icon switch (chunkParams.Format) { case IconFormat.PNG: encodedIcon = getCachedPNG( scaledRawData.buffer, icnsChunkRect.Width, icnsChunkRect.Height, numOfColors, ); break; case IconFormat.PackBitsARGB: encodedIcon = encodeIconWithPackBits(Buffer.from(scaledRawData.buffer), true); break; case IconFormat.PackBitsRGB: encodedIcon = encodeIconWithPackBits(Buffer.from(scaledRawData.buffer), false); break; case IconFormat.Alpha: // Aplpha channel is provided as is. encodedIcon = getImageChannel(Buffer.from(scaledRawData.buffer), 4, 3); break; default: throw new Error("Unknown format for icon (must be PNG, PackBitsARGB, PackBitsRGB or Alpha)"); } // Size of chunk = encoded icon size + icon header length iconHeader.writeUInt32BE(encodedIcon.byteLength + 8, 4); return Buffer.concat( [outBuffer, iconHeader, Buffer.from(encodedIcon)], outBuffer.length + iconHeader.length + encodedIcon.byteLength, ); } catch (e) { LogMessage("Could't append ICNS chunk", e); return null; } } /** * Create the Apple ICNS format. * @see resize.js, UPNG.js * @param input A raw buffer containing the complete source PNG file. * @param scalingAlgorithm One of the supported scaling algorithms for resizing. * @param numOfColors Maximum colors in output ICO chunks (0 = all colors/lossless, other values (<= 256) means lossy). * @returns A buffer which contains the binary data of the ICNS file or null in case of an error. */ export function createICNS(input: Buffer, scalingAlgorithm: number, numOfColors: number): Buffer | null { // Handle caching of input. checkCache(input); // Source for all resizing actions let inputImage: Image | null = getImageFromPNG(input); if (!inputImage) { return null; } // Make source image quadratic. const srcImage = getQuadraticImage(inputImage); inputImage = null; // All available chunk types const icnsChunks: IICNSChunkParams[] = [ // Note: Strange enough, but the order of the different chunks in the output file // seems to be relevant if ic04 and ic05 packbits icons are used. For example, if // they are placed at the end of the file the Finder and the Preview app are unable // to display them correctly. The position doesn't seem to have an impact for PNG // encoded icons, only for those two icons. ic04 and ic05 are supported on versions // 10.14 and newer but they don't seem to have a negative impact on older versions, // they are simply ignored. Nevertheless png2icons uses is32 and il32 for better // support on older versions. // The following order is the same of that created by iconutil on 10.14. { OSType: "ic12", Format: IconFormat.PNG, Size: 64, Info: "32x32@2 " }, { OSType: "ic07", Format: IconFormat.PNG, Size: 128, Info: "128x128 " }, { OSType: "ic13", Format: IconFormat.PNG, Size: 256, Info: "128x128@2" }, { OSType: "ic08", Format: IconFormat.PNG, Size: 256, Info: "256x256 " }, // { OSType: "ic04", Format: IconFormat.PackBitsARGB, Size: 16, Info: "16x16 " }, { OSType: "ic14", Format: IconFormat.PNG, Size: 512, Info: "256x256@2" }, { OSType: "ic09", Format: IconFormat.PNG, Size: 512, Info: "512x512 " }, // { OSType: "ic05", Format: IconFormat.PackBitsARGB, Size: 32, Info: "32x32 " }, { OSType: "ic10", Format: IconFormat.PNG, Size: 1024, Info: "512x512@2" }, { OSType: "ic11", Format: IconFormat.PNG, Size: 32, Info: "16x16@2 " }, // Important note: // The types il32 and is32 have to be Packbits encoded in RGB and they *need* // a *corresponding separate mask icon entry*. This mask contains an *uncompressed* // alpha channel with the same image dimensions. // Finding information on this was nearly impossible, the only source which finally // led to the solution was this documentation from the stone ages: // https://books.google.de/books?id=MTNUf464tHwC&pg=PA434&lpg=PA434&dq=mac+is32+icns&source=bl&ots=0fZ2g1qiia&sig=ACfU3U0uEMDeLkjeRL6CgD9_G_bPHasmEw&hl=de&sa=X&ved=2ahUKEwi_pYH0-5PjAhUGZ1AKHRx7CWMQ6AEwBnoECAkQAQ#v=onepage&q=mac%20is32%20icns&f=false { OSType: "il32", Format: IconFormat.PackBitsRGB, Size: 32, Info: "32x32 " }, { OSType: "l8mk", Format: IconFormat.Alpha, Size: 32, Info: "32x32 " }, { OSType: "is32", Format: IconFormat.PackBitsRGB, Size: 16, Info: "16x16 " }, { OSType: "s8mk", Format: IconFormat.Alpha, Size: 16, Info: "16x16 " }, // icp5 and icp4 would be an alternative and the Preview app displays them correctly // but they don't work in Finder. They also seem to be unsupported in older // versions (e. g. 10.12). // { OSType: "icp5", Format: IconFormat.PNG, Size: 32, Info: "32x32 " }, // { OSType: "icp4", Format: IconFormat.PNG, Size: 16, Info: "16x16 " }, ]; // ICNS header, "icns" + length of file (written later) let outBuffer: Buffer | null = Buffer.alloc(8, 0); outBuffer.write("icns", 0); // Append all icon chunks const nOfColors: number = (numOfColors < 0) ? 0 : ((numOfColors > MAX_COLORS) ? MAX_COLORS : numOfColors); for (const chunkParams of icnsChunks) { outBuffer = appendIcnsChunk(chunkParams, srcImage, scalingAlgorithm, nOfColors, outBuffer); if (!outBuffer) { return null; } LogMessage(`wrote type ${chunkParams.OSType} for size ${chunkParams.Info} with ${chunkParams.Size} pixels`); } // Write total file size at offset 4 of output and return final result outBuffer.writeUInt32BE(outBuffer.length, 4); LogMessage("done"); return outBuffer; } //////////////////////////////////////// // Microsoft ICO //////////////////////////////////////// /** * Length of Windows BMP header. */ const BITMAPINFOHEADERLENGTH: number = 40; /** * Get the directory header of an ICO file. * @see https://en.wikipedia.org/wiki/ICO_(file_format) * @param numOfImages Number of images the file will contain. * @returns Buffer The ICO header (file level). */ function getICONDIR(numOfImages: number): Buffer { const iconDir: Buffer = Buffer.alloc(6); iconDir.writeUInt16LE(0, 0); // Reserved. Must always be 0. iconDir.writeUInt16LE(1, 2); // Specifies image type: 1 for icon (.ICO) image, 2 for cursor (.CUR) image. Other values are invalid. iconDir.writeUInt16LE(numOfImages, 4); // Specifies number of images in the file. return iconDir; } /** * Get one entry for the directory header of an ICO file. * @see https://en.wikipedia.org/wiki/ICO_(file_format) * @param imageSize Total length in bytes of the image for the icon chunk. * @param width Width of the image for the icon chunk. * @param height Height of the image for the icon chunk. * @param offset Offset of the image (file level). * @returns Buffer The header for this icon. */ function getICONDIRENTRY(imageSize: number, width: number, height: number, offset: number): Buffer { const iconDirEntry: Buffer = Buffer.alloc(16); width = width >= 256 ? 0 : width; height = height >= 256 ? 0 : height; iconDirEntry.writeUInt8(width, 0); // Specifies image width in pixels. Can be any number between 0 and 255. Value 0 means image width is 256 pixels. iconDirEntry.writeUInt8(height, 1); // Specifies image height in pixels. Can be any number between 0 and 255. Value 0 means image height is 256 pixels. iconDirEntry.writeUInt8(0, 2); // Specifies number of colors in the color palette. Should be 0 if the image does not use a color palette. iconDirEntry.writeUInt8(0, 3); // Reserved. Should be 0. iconDirEntry.writeUInt16LE(1, 4); // In ICO format: Specifies color planes. Should be 0 or 1. iconDirEntry.writeUInt16LE(32, 6); // In ICO format: Specifies bits per pixel (UPNG.toRGBA8 always gives 4 bytes per pixel (RGBA)). iconDirEntry.writeUInt32LE(imageSize, 8); // Specifies the size of the image's data in bytes iconDirEntry.writeUInt32LE(offset, 12); // Specifies the offset of BMP or PNG data from the beginning of the ICO/CUR file. return iconDirEntry; } /** * Calculate the size of the mask for the alpha channel. * @param bitmapWidth Width of the bitmap. * @param bitmapHeight Height of the bitmap. * @see https://github.com/fiahfy/ico. * @returns The size of the mask in bytes. */ function getMaskSize(bitmapWidth: number, bitmapHeight: number): number { return (bitmapWidth + (bitmapWidth % 32 ? 32 - bitmapWidth % 32 : 0)) * bitmapHeight / 8; } /** * Get the Bitmap Info Header for an entry in the directory. * @see https://en.wikipedia.org/wiki/BMP_file_format * @param image Image The source image for the entry. * @returns Buffer The Bitmap Info Header for the entry. */ function getBITMAPINFOHEADER(image: Image): Buffer { const buffer: Buffer = Buffer.alloc(BITMAPINFOHEADERLENGTH); const imageSize = image.data.length + getMaskSize(image.width, image.height); buffer.writeUInt32LE(40, 0); // Size of this header (40 bytes). buffer.writeInt32LE(image.width, 4); // Bitmap width in pixels. buffer.writeInt32LE(image.height * 2, 8); // Bitmap height in pixels (must be doubled because of alpha channel). buffer.writeUInt16LE(1, 12); // Number of color planes (must be 1). buffer.writeUInt16LE(32, 14); // Bits per pixel (UPNG.toRGBA8 always gives 4 bytes per pixel (RGBA)). buffer.writeUInt32LE(0, 16); // Compression method (here always 0). buffer.writeUInt32LE(imageSize, 20); // Image size (image buffer + padding). buffer.writeInt32LE(3780, 24); // Horizontal resolution of the image (pixels per meter, 3780 = 96 DPI). buffer.writeInt32LE(3780, 28); // Horizontal resolution of the image (pixels per meter, 3780 = 96 DPI). buffer.writeUInt32LE(0, 32); // Number of colors in the color palette, or 0 to default to 2^n. buffer.writeUInt32LE(0, 36); // Number of important colors used, or 0 when every color is important; generally ignored. return buffer; } /** * Get a DIB representation of the raw image data in a DIB with a mask. * Bitmap data starts with the lower left hand corner of the image. * Pixel order is blue, green, red, alpha. * @see https://en.wikipedia.org/wiki/BMP_file_format * @param image Source image. * @returns Buffer The DIB for the given image. */ function getDIB(image: Image): Buffer { // Source bitmap const bitmap: Buffer = Buffer.from(image.data); // Target bitmap const DIB: Buffer = Buffer.alloc(image.data.length); // Mask data const maskSize: number = getMaskSize(image.width, image.height); let maskBits: number[] = []; // Change order from lower to top const bytesPerPixel: number = 4; const columns: number = image.width * bytesPerPixel; const rows: number = image.height * columns; const end: number = rows - columns; for (let row = 0; row < rows; row += columns) { for (let col = 0; col < columns; col += bytesPerPixel) { // Swap pixels from RGBA to BGRA let pos = row + col; const r = bitmap.readUInt8(pos); const g = bitmap.readUInt8(pos + 1); const b = bitmap.readUInt8(pos + 2); const a = bitmap.readUInt8(pos + 3); pos = (end - row) + col; DIB.writeUInt8(b, pos); DIB.writeUInt8(g, pos + 1); DIB.writeUInt8(r, pos + 2); DIB.writeUInt8(a, pos + 3); // Store mask bit maskBits.push(bitmap[pos + 3] === 0 ? 1 : 0); } const padding = maskBits.length % 32 ? 32 - maskBits.length % 32 : 0; maskBits = maskBits.concat(Array(padding).fill(0)); } // Create mask from mask bits const mask: Buffer[] = []; for (let i = 0; i < maskBits.length; i += 8) { const n: number = parseInt(maskBits.slice(i, i + 8).join(""), 2); const buf: Buffer = Buffer.alloc(1); buf.writeUInt8(n, 0); mask.push(buf); } return Buffer.concat([DIB, Buffer.concat(mask, maskSize)]); } /** * Create the Microsoft ICO format using PNG and/or Windows bitmaps for every icon. * @see https://en.wikipedia.org/wiki/ICO_(file_format) * @see resize.js, UPNG.js * @param input A raw buffer containing the complete source PNG file. * @param scalingAlgorithm One of the supported scaling algorithms for resizing. * @param numOfColors Maximum colors in output ICO chunks (0 = all colors/lossless, other values * (<= 256) means lossy). Only used if "PNG" is true. * @param PNG Store each chunk in the generated output in either PNG or Windows BMP format. PNG * as opposed to DIB is valid but older Windows versions may not be able to display it. * @param forWinExe Optional. If true all icons will be stored as PNGs, only the sizes smaller * than 64 will be stored as BMPs. This avoids display problems with the icon in the file * properties dialog of Windows versions older than Windows 10. Should be set to true if * the ICO file is intended to be used for embeddingin a Windows executable. If used, the * parameter PNG is ignored. * @returns A buffer which contains the binary data of the ICO file or null in case of an error. */ export function createICO(input: Buffer, scalingAlgorithm: number, numOfColors: number, PNG: boolean, forWinExe?: boolean): Buffer | null { // Handle caching of input. checkCache(input); // Source for all resizing actions let inputImage: Image | null = getImageFromPNG(input); if (!inputImage) { return null; } // Make source image quadratic. const srcImage = getQuadraticImage(inputImage); inputImage = null; // All chunk sizes const icoChunkSizes: number[] = [256, 128, 96, 72, 64, 48, 32, 24, 16]; // An array which receives the directory header and all entry headers const icoDirectory: Buffer[] = []; // Create and append directory header icoDirectory.push(getICONDIR(icoChunkSizes.length)); // Final total length of all buffers. let totalLength: number = icoDirectory[0].length; // ICONDIR header // Temporary storage for all scaled images const icoChunkImages: Buffer[] = []; // Initial offset for the first image let chunkOffset: number = icoDirectory[0].length + (icoChunkSizes.length * 16); // fixed length of ICONDIRENTRY is 16 // Process each chunk for (const icoChunkSize of icoChunkSizes) { // Target rect for scaled image const icoChunkRect = getStretchedRect( getRect(0, 0, srcImage.width, srcImage.height), getRect(0, 0, icoChunkSize, icoChunkSize), ); // Get scaled raw image const scaledRawImage: Image = { data: getScaledImageData(srcImage, icoChunkRect, scalingAlgorithm), height: icoChunkRect.Height, width: icoChunkRect.Width, }; // Make icon let formatInfo: string; // In Windows executable mode use PNG only for sizes >= 64. if (PNG || (forWinExe && ([256, 128, 96, 72, 64].indexOf(icoChunkRect.Height) !== -1))) { formatInfo = "png"; const encodedIcon = getCachedPNG( scaledRawImage.data.buffer, scaledRawImage.width, scaledRawImage.height, (numOfColors < 0) ? 0 : ((numOfColors > MAX_COLORS) ? MAX_COLORS : numOfColors), ); const iconDirEntry: Buffer = getICONDIRENTRY( encodedIcon.byteLength, scaledRawImage.width, scaledRawImage.height, chunkOffset, ); icoDirectory.push(iconDirEntry); icoChunkImages.push(Buffer.from(encodedIcon)); totalLength += iconDirEntry.length + encodedIcon.byteLength; chunkOffset += encodedIcon.byteLength; } else { formatInfo = "bmp"; const iconDirEntry: Buffer = getICONDIRENTRY( scaledRawImage.data.length + getMaskSize(scaledRawImage.width, scaledRawImage.height) + BITMAPINFOHEADERLENGTH, scaledRawImage.width, scaledRawImage.height, chunkOffset, ); icoDirectory.push(iconDirEntry); const bmpInfoHeader = getBITMAPINFOHEADER(scaledRawImage); const DIB = getDIB(scaledRawImage); icoChunkImages.push(bmpInfoHeader, DIB); totalLength += iconDirEntry.length + bmpInfoHeader.length + DIB.length; chunkOffset += bmpInfoHeader.length + DIB.length; } LogMessage(`wrote ${formatInfo} icon for size ${icoChunkSize}`); } LogMessage(`done`); return Buffer.concat(icoDirectory.concat(icoChunkImages), totalLength); }
the_stack