text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { toWorkspaceFolders, IWorkspaceIdentifier, hasWorkspaceFileExtension, UNTITLED_WORKSPACE_NAME, IResolvedWorkspace, IStoredWorkspaceFolder, isStoredWorkspaceFolder, IWorkspaceFolderCreationData, IUntitledWorkspaceInfo, getStoredWorkspaceFolder, IEnterWorkspaceResult, isUntitledWorkspace, isWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces'; import { IEnvironmentMainService } from 'vs/platform/environment/electron-main/environmentMainService'; import { join, dirname } from 'vs/base/common/path'; import { writeFile, rimrafSync, readdirSync, writeFileSync, Promises } from 'vs/base/node/pfs'; import { readFileSync, existsSync, mkdirSync, statSync, Stats } from 'fs'; import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform'; import { Event, Emitter } from 'vs/base/common/event'; import { ILogService } from 'vs/platform/log/common/log'; import { createHash } from 'crypto'; import { parse } from 'vs/base/common/json'; import { URI } from 'vs/base/common/uri'; import { Schemas } from 'vs/base/common/network'; import { Disposable } from 'vs/base/common/lifecycle'; import { originalFSPath, joinPath, basename, extUriBiasedIgnorePathCase } from 'vs/base/common/resources'; import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; import { ICodeWindow } from 'vs/platform/windows/electron-main/windows'; import { localize } from 'vs/nls'; import { IProductService } from 'vs/platform/product/common/productService'; import { MessageBoxOptions, BrowserWindow } from 'electron'; import { withNullAsUndefined } from 'vs/base/common/types'; import { IBackupMainService } from 'vs/platform/backup/electron-main/backup'; import { IDialogMainService } from 'vs/platform/dialogs/electron-main/dialogMainService'; import { findWindowOnWorkspaceOrFolder } from 'vs/platform/windows/electron-main/windowsFinder'; export const IWorkspacesManagementMainService = createDecorator<IWorkspacesManagementMainService>('workspacesManagementMainService'); export interface IWorkspaceEnteredEvent { window: ICodeWindow; workspace: IWorkspaceIdentifier; } export interface IWorkspacesManagementMainService { readonly _serviceBrand: undefined; readonly onDidDeleteUntitledWorkspace: Event<IWorkspaceIdentifier>; readonly onDidEnterWorkspace: Event<IWorkspaceEnteredEvent>; enterWorkspace(intoWindow: ICodeWindow, openedWindows: ICodeWindow[], path: URI): Promise<IEnterWorkspaceResult | undefined>; createUntitledWorkspace(folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): Promise<IWorkspaceIdentifier>; createUntitledWorkspaceSync(folders?: IWorkspaceFolderCreationData[]): IWorkspaceIdentifier; deleteUntitledWorkspace(workspace: IWorkspaceIdentifier): Promise<void>; deleteUntitledWorkspaceSync(workspace: IWorkspaceIdentifier): void; getUntitledWorkspacesSync(): IUntitledWorkspaceInfo[]; isUntitledWorkspace(workspace: IWorkspaceIdentifier): boolean; resolveLocalWorkspaceSync(path: URI): IResolvedWorkspace | undefined; getWorkspaceIdentifier(workspacePath: URI): Promise<IWorkspaceIdentifier>; } export interface IStoredWorkspace { folders: IStoredWorkspaceFolder[]; remoteAuthority?: string; } export class WorkspacesManagementMainService extends Disposable implements IWorkspacesManagementMainService { declare readonly _serviceBrand: undefined; private readonly untitledWorkspacesHome = this.environmentMainService.untitledWorkspacesHome; // local URI that contains all untitled workspaces private readonly _onDidDeleteUntitledWorkspace = this._register(new Emitter<IWorkspaceIdentifier>()); readonly onDidDeleteUntitledWorkspace: Event<IWorkspaceIdentifier> = this._onDidDeleteUntitledWorkspace.event; private readonly _onDidEnterWorkspace = this._register(new Emitter<IWorkspaceEnteredEvent>()); readonly onDidEnterWorkspace: Event<IWorkspaceEnteredEvent> = this._onDidEnterWorkspace.event; constructor( @IEnvironmentMainService private readonly environmentMainService: IEnvironmentMainService, @ILogService private readonly logService: ILogService, @IBackupMainService private readonly backupMainService: IBackupMainService, @IDialogMainService private readonly dialogMainService: IDialogMainService, @IProductService private readonly productService: IProductService ) { super(); } resolveLocalWorkspaceSync(uri: URI): IResolvedWorkspace | undefined { if (!this.isWorkspacePath(uri)) { return undefined; // does not look like a valid workspace config file } if (uri.scheme !== Schemas.file) { return undefined; } let contents: string; try { contents = readFileSync(uri.fsPath, 'utf8'); } catch (error) { return undefined; // invalid workspace } return this.doResolveWorkspace(uri, contents); } private isWorkspacePath(uri: URI): boolean { return isUntitledWorkspace(uri, this.environmentMainService) || hasWorkspaceFileExtension(uri); } private doResolveWorkspace(path: URI, contents: string): IResolvedWorkspace | undefined { try { const workspace = this.doParseStoredWorkspace(path, contents); const workspaceIdentifier = getWorkspaceIdentifier(path); return { id: workspaceIdentifier.id, configPath: workspaceIdentifier.configPath, folders: toWorkspaceFolders(workspace.folders, workspaceIdentifier.configPath, extUriBiasedIgnorePathCase), remoteAuthority: workspace.remoteAuthority }; } catch (error) { this.logService.warn(error.toString()); } return undefined; } private doParseStoredWorkspace(path: URI, contents: string): IStoredWorkspace { // Parse workspace file const storedWorkspace: IStoredWorkspace = parse(contents); // use fault tolerant parser // Filter out folders which do not have a path or uri set if (storedWorkspace && Array.isArray(storedWorkspace.folders)) { storedWorkspace.folders = storedWorkspace.folders.filter(folder => isStoredWorkspaceFolder(folder)); } else { throw new Error(`${path.toString(true)} looks like an invalid workspace file.`); } return storedWorkspace; } async createUntitledWorkspace(folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): Promise<IWorkspaceIdentifier> { const { workspace, storedWorkspace } = this.newUntitledWorkspace(folders, remoteAuthority); const configPath = workspace.configPath.fsPath; await Promises.mkdir(dirname(configPath), { recursive: true }); await writeFile(configPath, JSON.stringify(storedWorkspace, null, '\t')); return workspace; } createUntitledWorkspaceSync(folders?: IWorkspaceFolderCreationData[], remoteAuthority?: string): IWorkspaceIdentifier { const { workspace, storedWorkspace } = this.newUntitledWorkspace(folders, remoteAuthority); const configPath = workspace.configPath.fsPath; mkdirSync(dirname(configPath), { recursive: true }); writeFileSync(configPath, JSON.stringify(storedWorkspace, null, '\t')); return workspace; } private newUntitledWorkspace(folders: IWorkspaceFolderCreationData[] = [], remoteAuthority?: string): { workspace: IWorkspaceIdentifier, storedWorkspace: IStoredWorkspace } { const randomId = (Date.now() + Math.round(Math.random() * 1000)).toString(); const untitledWorkspaceConfigFolder = joinPath(this.untitledWorkspacesHome, randomId); const untitledWorkspaceConfigPath = joinPath(untitledWorkspaceConfigFolder, UNTITLED_WORKSPACE_NAME); const storedWorkspaceFolder: IStoredWorkspaceFolder[] = []; for (const folder of folders) { storedWorkspaceFolder.push(getStoredWorkspaceFolder(folder.uri, true, folder.name, untitledWorkspaceConfigFolder, !isWindows, extUriBiasedIgnorePathCase)); } return { workspace: getWorkspaceIdentifier(untitledWorkspaceConfigPath), storedWorkspace: { folders: storedWorkspaceFolder, remoteAuthority } }; } async getWorkspaceIdentifier(configPath: URI): Promise<IWorkspaceIdentifier> { return getWorkspaceIdentifier(configPath); } isUntitledWorkspace(workspace: IWorkspaceIdentifier): boolean { return isUntitledWorkspace(workspace.configPath, this.environmentMainService); } deleteUntitledWorkspaceSync(workspace: IWorkspaceIdentifier): void { if (!this.isUntitledWorkspace(workspace)) { return; // only supported for untitled workspaces } // Delete from disk this.doDeleteUntitledWorkspaceSync(workspace); // Event this._onDidDeleteUntitledWorkspace.fire(workspace); } async deleteUntitledWorkspace(workspace: IWorkspaceIdentifier): Promise<void> { this.deleteUntitledWorkspaceSync(workspace); } private doDeleteUntitledWorkspaceSync(workspace: IWorkspaceIdentifier): void { const configPath = originalFSPath(workspace.configPath); try { // Delete Workspace rimrafSync(dirname(configPath)); // Mark Workspace Storage to be deleted const workspaceStoragePath = join(this.environmentMainService.workspaceStorageHome.fsPath, workspace.id); if (existsSync(workspaceStoragePath)) { writeFileSync(join(workspaceStoragePath, 'obsolete'), ''); } } catch (error) { this.logService.warn(`Unable to delete untitled workspace ${configPath} (${error}).`); } } getUntitledWorkspacesSync(): IUntitledWorkspaceInfo[] { const untitledWorkspaces: IUntitledWorkspaceInfo[] = []; try { const untitledWorkspacePaths = readdirSync(this.untitledWorkspacesHome.fsPath).map(folder => joinPath(this.untitledWorkspacesHome, folder, UNTITLED_WORKSPACE_NAME)); for (const untitledWorkspacePath of untitledWorkspacePaths) { const workspace = getWorkspaceIdentifier(untitledWorkspacePath); const resolvedWorkspace = this.resolveLocalWorkspaceSync(untitledWorkspacePath); if (!resolvedWorkspace) { this.doDeleteUntitledWorkspaceSync(workspace); } else { untitledWorkspaces.push({ workspace, remoteAuthority: resolvedWorkspace.remoteAuthority }); } } } catch (error) { if (error.code !== 'ENOENT') { this.logService.warn(`Unable to read folders in ${this.untitledWorkspacesHome} (${error}).`); } } return untitledWorkspaces; } async enterWorkspace(window: ICodeWindow, windows: ICodeWindow[], path: URI): Promise<IEnterWorkspaceResult | undefined> { if (!window || !window.win || !window.isReady) { return undefined; // return early if the window is not ready or disposed } const isValid = await this.isValidTargetWorkspacePath(window, windows, path); if (!isValid) { return undefined; // return early if the workspace is not valid } const result = this.doEnterWorkspace(window, getWorkspaceIdentifier(path)); if (!result) { return undefined; } // Emit as event this._onDidEnterWorkspace.fire({ window, workspace: result.workspace }); return result; } private async isValidTargetWorkspacePath(window: ICodeWindow, windows: ICodeWindow[], workspacePath?: URI): Promise<boolean> { if (!workspacePath) { return true; } if (isWorkspaceIdentifier(window.openedWorkspace) && extUriBiasedIgnorePathCase.isEqual(window.openedWorkspace.configPath, workspacePath)) { return false; // window is already opened on a workspace with that path } // Prevent overwriting a workspace that is currently opened in another window if (findWindowOnWorkspaceOrFolder(windows, workspacePath)) { const options: MessageBoxOptions = { title: this.productService.nameLong, type: 'info', buttons: [localize('ok', "OK")], message: localize('workspaceOpenedMessage', "Unable to save workspace '{0}'", basename(workspacePath)), detail: localize('workspaceOpenedDetail', "The workspace is already opened in another window. Please close that window first and then try again."), noLink: true }; await this.dialogMainService.showMessageBox(options, withNullAsUndefined(BrowserWindow.getFocusedWindow())); return false; } return true; // OK } private doEnterWorkspace(window: ICodeWindow, workspace: IWorkspaceIdentifier): IEnterWorkspaceResult | undefined { if (!window.config) { return undefined; } window.focus(); // Register window for backups and migrate current backups over let backupPath: string | undefined; if (!window.config.extensionDevelopmentPath) { backupPath = this.backupMainService.registerWorkspaceBackupSync({ workspace, remoteAuthority: window.remoteAuthority }, window.config.backupPath); } // if the window was opened on an untitled workspace, delete it. if (isWorkspaceIdentifier(window.openedWorkspace) && this.isUntitledWorkspace(window.openedWorkspace)) { this.deleteUntitledWorkspaceSync(window.openedWorkspace); } // Update window configuration properly based on transition to workspace window.config.workspace = workspace; window.config.backupPath = backupPath; return { workspace, backupPath }; } } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE: DO NOT CHANGE. IDENTIFIERS HAVE TO REMAIN STABLE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! export function getWorkspaceIdentifier(configPath: URI): IWorkspaceIdentifier { function getWorkspaceId(): string { let configPathStr = configPath.scheme === Schemas.file ? originalFSPath(configPath) : configPath.toString(); if (!isLinux) { configPathStr = configPathStr.toLowerCase(); // sanitize for platform file system } return createHash('md5').update(configPathStr).digest('hex'); } return { id: getWorkspaceId(), configPath }; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE: DO NOT CHANGE. IDENTIFIERS HAVE TO REMAIN STABLE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! export function getSingleFolderWorkspaceIdentifier(folderUri: URI): ISingleFolderWorkspaceIdentifier | undefined; export function getSingleFolderWorkspaceIdentifier(folderUri: URI, folderStat: Stats): ISingleFolderWorkspaceIdentifier; export function getSingleFolderWorkspaceIdentifier(folderUri: URI, folderStat?: Stats): ISingleFolderWorkspaceIdentifier | undefined { function getFolderId(): string | undefined { // Remote: produce a hash from the entire URI if (folderUri.scheme !== Schemas.file) { return createHash('md5').update(folderUri.toString()).digest('hex'); } // Local: produce a hash from the path and include creation time as salt if (!folderStat) { try { folderStat = statSync(folderUri.fsPath); } catch (error) { return undefined; // folder does not exist } } let ctime: number | undefined; if (isLinux) { ctime = folderStat.ino; // Linux: birthtime is ctime, so we cannot use it! We use the ino instead! } else if (isMacintosh) { ctime = folderStat.birthtime.getTime(); // macOS: birthtime is fine to use as is } else if (isWindows) { if (typeof folderStat.birthtimeMs === 'number') { ctime = Math.floor(folderStat.birthtimeMs); // Windows: fix precision issue in node.js 8.x to get 7.x results (see https://github.com/nodejs/node/issues/19897) } else { ctime = folderStat.birthtime.getTime(); } } // we use the ctime as extra salt to the ID so that we catch the case of a folder getting // deleted and recreated. in that case we do not want to carry over previous state return createHash('md5').update(folderUri.fsPath).update(ctime ? String(ctime) : '').digest('hex'); } const folderId = getFolderId(); if (typeof folderId === 'string') { return { id: folderId, uri: folderUri }; } return undefined; // invalid folder }
the_stack
import { NodeTransform, TransformContext } from '../transform' import { NodeTypes, ElementTypes, CallExpression, ObjectExpression, ElementNode, DirectiveNode, ExpressionNode, ArrayExpression, createCallExpression, createArrayExpression, createObjectProperty, createSimpleExpression, createObjectExpression, Property, ComponentNode, VNodeCall, TemplateTextChildNode, DirectiveArguments, createVNodeCall, ConstantTypes } from '../ast' import { PatchFlags, PatchFlagNames, isSymbol, isOn, isObject, isReservedProp, capitalize, camelize } from '@vue/shared' import { createCompilerError, ErrorCodes } from '../errors' import { RESOLVE_DIRECTIVE, RESOLVE_COMPONENT, RESOLVE_DYNAMIC_COMPONENT, MERGE_PROPS, NORMALIZE_CLASS, NORMALIZE_STYLE, NORMALIZE_PROPS, TO_HANDLERS, TELEPORT, KEEP_ALIVE, SUSPENSE, UNREF, GUARD_REACTIVE_PROPS } from '../runtimeHelpers' import { getInnerRange, toValidAssetId, findProp, isCoreComponent, isStaticArgOf, findDir, isStaticExp } from '../utils' import { buildSlots } from './vSlot' import { getConstantType } from './hoistStatic' import { BindingTypes } from '../options' import { checkCompatEnabled, CompilerDeprecationTypes, isCompatEnabled } from '../compat/compatConfig' // some directive transforms (e.g. v-model) may return a symbol for runtime // import, which should be used instead of a resolveDirective call. const directiveImportMap = new WeakMap<DirectiveNode, symbol>() // generate a JavaScript AST for this element's codegen export const transformElement: NodeTransform = (node, context) => { // perform the work on exit, after all child expressions have been // processed and merged. return function postTransformElement() { node = context.currentNode! if ( !( node.type === NodeTypes.ELEMENT && (node.tagType === ElementTypes.ELEMENT || node.tagType === ElementTypes.COMPONENT) ) ) { return } const { tag, props } = node const isComponent = node.tagType === ElementTypes.COMPONENT // The goal of the transform is to create a codegenNode implementing the // VNodeCall interface. let vnodeTag = isComponent ? resolveComponentType(node as ComponentNode, context) : `"${tag}"` const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT let vnodeProps: VNodeCall['props'] let vnodeChildren: VNodeCall['children'] let vnodePatchFlag: VNodeCall['patchFlag'] let patchFlag: number = 0 let vnodeDynamicProps: VNodeCall['dynamicProps'] let dynamicPropNames: string[] | undefined let vnodeDirectives: VNodeCall['directives'] let shouldUseBlock = // dynamic component may resolve to plain elements isDynamicComponent || vnodeTag === TELEPORT || vnodeTag === SUSPENSE || (!isComponent && // <svg> and <foreignObject> must be forced into blocks so that block // updates inside get proper isSVG flag at runtime. (#639, #643) // This is technically web-specific, but splitting the logic out of core // leads to too much unnecessary complexity. (tag === 'svg' || tag === 'foreignObject')) // props if (props.length > 0) { const propsBuildResult = buildProps(node, context) vnodeProps = propsBuildResult.props patchFlag = propsBuildResult.patchFlag dynamicPropNames = propsBuildResult.dynamicPropNames const directives = propsBuildResult.directives vnodeDirectives = directives && directives.length ? (createArrayExpression( directives.map(dir => buildDirectiveArgs(dir, context)) ) as DirectiveArguments) : undefined if (propsBuildResult.shouldUseBlock) { shouldUseBlock = true } } // children if (node.children.length > 0) { if (vnodeTag === KEEP_ALIVE) { // Although a built-in component, we compile KeepAlive with raw children // instead of slot functions so that it can be used inside Transition // or other Transition-wrapping HOCs. // To ensure correct updates with block optimizations, we need to: // 1. Force keep-alive into a block. This avoids its children being // collected by a parent block. shouldUseBlock = true // 2. Force keep-alive to always be updated, since it uses raw children. patchFlag |= PatchFlags.DYNAMIC_SLOTS if (__DEV__ && node.children.length > 1) { context.onError( createCompilerError(ErrorCodes.X_KEEP_ALIVE_INVALID_CHILDREN, { start: node.children[0].loc.start, end: node.children[node.children.length - 1].loc.end, source: '' }) ) } } const shouldBuildAsSlots = isComponent && // Teleport is not a real component and has dedicated runtime handling vnodeTag !== TELEPORT && // explained above. vnodeTag !== KEEP_ALIVE if (shouldBuildAsSlots) { const { slots, hasDynamicSlots } = buildSlots(node, context) vnodeChildren = slots if (hasDynamicSlots) { patchFlag |= PatchFlags.DYNAMIC_SLOTS } } else if (node.children.length === 1 && vnodeTag !== TELEPORT) { const child = node.children[0] const type = child.type // check for dynamic text children const hasDynamicTextChild = type === NodeTypes.INTERPOLATION || type === NodeTypes.COMPOUND_EXPRESSION if ( hasDynamicTextChild && getConstantType(child, context) === ConstantTypes.NOT_CONSTANT ) { patchFlag |= PatchFlags.TEXT } // pass directly if the only child is a text node // (plain / interpolation / expression) if (hasDynamicTextChild || type === NodeTypes.TEXT) { vnodeChildren = child as TemplateTextChildNode } else { vnodeChildren = node.children } } else { vnodeChildren = node.children } } // patchFlag & dynamicPropNames if (patchFlag !== 0) { if (__DEV__) { if (patchFlag < 0) { // special flags (negative and mutually exclusive) vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */` } else { // bitwise flags const flagNames = Object.keys(PatchFlagNames) .map(Number) .filter(n => n > 0 && patchFlag & n) .map(n => PatchFlagNames[n]) .join(`, `) vnodePatchFlag = patchFlag + ` /* ${flagNames} */` } } else { vnodePatchFlag = String(patchFlag) } if (dynamicPropNames && dynamicPropNames.length) { vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames) } } node.codegenNode = createVNodeCall( context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, isComponent, node.loc ) } } export function resolveComponentType( node: ComponentNode, context: TransformContext, ssr = false ) { let { tag } = node // 1. dynamic component const isExplicitDynamic = isComponentTag(tag) const isProp = findProp(node, 'is') if (isProp) { if ( isExplicitDynamic || (__COMPAT__ && isCompatEnabled( CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT, context )) ) { const exp = isProp.type === NodeTypes.ATTRIBUTE ? isProp.value && createSimpleExpression(isProp.value.content, true) : isProp.exp if (exp) { return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [ exp ]) } } else if ( isProp.type === NodeTypes.ATTRIBUTE && isProp.value!.content.startsWith('vue:') ) { // <button is="vue:xxx"> // if not <component>, only is value that starts with "vue:" will be // treated as component by the parse phase and reach here, unless it's // compat mode where all is values are considered components tag = isProp.value!.content.slice(4) } } // 1.5 v-is (TODO: Deprecate) const isDir = !isExplicitDynamic && findDir(node, 'is') if (isDir && isDir.exp) { return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [ isDir.exp ]) } // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...) const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag) if (builtIn) { // built-ins are simply fallthroughs / have special handling during ssr // so we don't need to import their runtime equivalents if (!ssr) context.helper(builtIn) return builtIn } // 3. user component (from setup bindings) // this is skipped in browser build since browser builds do not perform // binding analysis. if (!__BROWSER__) { const fromSetup = resolveSetupReference(tag, context) if (fromSetup) { return fromSetup } const dotIndex = tag.indexOf('.') if (dotIndex > 0) { const ns = resolveSetupReference(tag.slice(0, dotIndex), context) if (ns) { return ns + tag.slice(dotIndex) } } } // 4. Self referencing component (inferred from filename) if ( !__BROWSER__ && context.selfName && capitalize(camelize(tag)) === context.selfName ) { context.helper(RESOLVE_COMPONENT) // codegen.ts has special check for __self postfix when generating // component imports, which will pass additional `maybeSelfReference` flag // to `resolveComponent`. context.components.add(tag + `__self`) return toValidAssetId(tag, `component`) } // 5. user component (resolve) context.helper(RESOLVE_COMPONENT) context.components.add(tag) return toValidAssetId(tag, `component`) } function resolveSetupReference(name: string, context: TransformContext) { const bindings = context.bindingMetadata if (!bindings || bindings.__isScriptSetup === false) { return } const camelName = camelize(name) const PascalName = capitalize(camelName) const checkType = (type: BindingTypes) => { if (bindings[name] === type) { return name } if (bindings[camelName] === type) { return camelName } if (bindings[PascalName] === type) { return PascalName } } const fromConst = checkType(BindingTypes.SETUP_CONST) if (fromConst) { return context.inline ? // in inline mode, const setup bindings (e.g. imports) can be used as-is fromConst : `$setup[${JSON.stringify(fromConst)}]` } const fromMaybeRef = checkType(BindingTypes.SETUP_LET) || checkType(BindingTypes.SETUP_REF) || checkType(BindingTypes.SETUP_MAYBE_REF) if (fromMaybeRef) { return context.inline ? // setup scope bindings that may be refs need to be unrefed `${context.helperString(UNREF)}(${fromMaybeRef})` : `$setup[${JSON.stringify(fromMaybeRef)}]` } } export type PropsExpression = ObjectExpression | CallExpression | ExpressionNode export function buildProps( node: ElementNode, context: TransformContext, props: ElementNode['props'] = node.props, ssr = false ): { props: PropsExpression | undefined directives: DirectiveNode[] patchFlag: number dynamicPropNames: string[] shouldUseBlock: boolean } { const { tag, loc: elementLoc, children } = node const isComponent = node.tagType === ElementTypes.COMPONENT let properties: ObjectExpression['properties'] = [] const mergeArgs: PropsExpression[] = [] const runtimeDirectives: DirectiveNode[] = [] const hasChildren = children.length > 0 let shouldUseBlock = false // patchFlag analysis let patchFlag = 0 let hasRef = false let hasClassBinding = false let hasStyleBinding = false let hasHydrationEventBinding = false let hasDynamicKeys = false let hasVnodeHook = false const dynamicPropNames: string[] = [] const analyzePatchFlag = ({ key, value }: Property) => { if (isStaticExp(key)) { const name = key.content const isEventHandler = isOn(name) if ( !isComponent && isEventHandler && // omit the flag for click handlers because hydration gives click // dedicated fast path. name.toLowerCase() !== 'onclick' && // omit v-model handlers name !== 'onUpdate:modelValue' && // omit onVnodeXXX hooks !isReservedProp(name) ) { hasHydrationEventBinding = true } if (isEventHandler && isReservedProp(name)) { hasVnodeHook = true } if ( value.type === NodeTypes.JS_CACHE_EXPRESSION || ((value.type === NodeTypes.SIMPLE_EXPRESSION || value.type === NodeTypes.COMPOUND_EXPRESSION) && getConstantType(value, context) > 0) ) { // skip if the prop is a cached handler or has constant value return } if (name === 'ref') { hasRef = true } else if (name === 'class') { hasClassBinding = true } else if (name === 'style') { hasStyleBinding = true } else if (name !== 'key' && !dynamicPropNames.includes(name)) { dynamicPropNames.push(name) } // treat the dynamic class and style binding of the component as dynamic props if ( isComponent && (name === 'class' || name === 'style') && !dynamicPropNames.includes(name) ) { dynamicPropNames.push(name) } } else { hasDynamicKeys = true } } for (let i = 0; i < props.length; i++) { // static attribute const prop = props[i] if (prop.type === NodeTypes.ATTRIBUTE) { const { loc, name, value } = prop let isStatic = true if (name === 'ref') { hasRef = true if (context.scopes.vFor > 0) { properties.push( createObjectProperty( createSimpleExpression('ref_for', true), createSimpleExpression('true') ) ) } // in inline mode there is no setupState object, so we can't use string // keys to set the ref. Instead, we need to transform it to pass the // actual ref instead. if ( !__BROWSER__ && value && context.inline && context.bindingMetadata[value.content] ) { isStatic = false properties.push( createObjectProperty( createSimpleExpression('ref_key', true), createSimpleExpression(value.content, true, value.loc) ) ) } } // skip is on <component>, or is="vue:xxx" if ( name === 'is' && (isComponentTag(tag) || (value && value.content.startsWith('vue:')) || (__COMPAT__ && isCompatEnabled( CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT, context ))) ) { continue } properties.push( createObjectProperty( createSimpleExpression( name, true, getInnerRange(loc, 0, name.length) ), createSimpleExpression( value ? value.content : '', isStatic, value ? value.loc : loc ) ) ) } else { // directives const { name, arg, exp, loc } = prop const isVBind = name === 'bind' const isVOn = name === 'on' // skip v-slot - it is handled by its dedicated transform. if (name === 'slot') { if (!isComponent) { context.onError( createCompilerError(ErrorCodes.X_V_SLOT_MISPLACED, loc) ) } continue } // skip v-once/v-memo - they are handled by dedicated transforms. if (name === 'once' || name === 'memo') { continue } // skip v-is and :is on <component> if ( name === 'is' || (isVBind && isStaticArgOf(arg, 'is') && (isComponentTag(tag) || (__COMPAT__ && isCompatEnabled( CompilerDeprecationTypes.COMPILER_IS_ON_ELEMENT, context )))) ) { continue } // skip v-on in SSR compilation if (isVOn && ssr) { continue } if ( // #938: elements with dynamic keys should be forced into blocks (isVBind && isStaticArgOf(arg, 'key')) || // inline before-update hooks need to force block so that it is invoked // before children (isVOn && hasChildren && isStaticArgOf(arg, 'vue:before-update')) ) { shouldUseBlock = true } if (isVBind && isStaticArgOf(arg, 'ref') && context.scopes.vFor > 0) { properties.push( createObjectProperty( createSimpleExpression('ref_for', true), createSimpleExpression('true') ) ) } // special case for v-bind and v-on with no argument if (!arg && (isVBind || isVOn)) { hasDynamicKeys = true if (exp) { if (properties.length) { mergeArgs.push( createObjectExpression(dedupeProperties(properties), elementLoc) ) properties = [] } if (isVBind) { if (__COMPAT__) { // 2.x v-bind object order compat if (__DEV__) { const hasOverridableKeys = mergeArgs.some(arg => { if (arg.type === NodeTypes.JS_OBJECT_EXPRESSION) { return arg.properties.some(({ key }) => { if ( key.type !== NodeTypes.SIMPLE_EXPRESSION || !key.isStatic ) { return true } return ( key.content !== 'class' && key.content !== 'style' && !isOn(key.content) ) }) } else { // dynamic expression return true } }) if (hasOverridableKeys) { checkCompatEnabled( CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER, context, loc ) } } if ( isCompatEnabled( CompilerDeprecationTypes.COMPILER_V_BIND_OBJECT_ORDER, context ) ) { mergeArgs.unshift(exp) continue } } mergeArgs.push(exp) } else { // v-on="obj" -> toHandlers(obj) mergeArgs.push({ type: NodeTypes.JS_CALL_EXPRESSION, loc, callee: context.helper(TO_HANDLERS), arguments: [exp] }) } } else { context.onError( createCompilerError( isVBind ? ErrorCodes.X_V_BIND_NO_EXPRESSION : ErrorCodes.X_V_ON_NO_EXPRESSION, loc ) ) } continue } const directiveTransform = context.directiveTransforms[name] if (directiveTransform) { // has built-in directive transform. const { props, needRuntime } = directiveTransform(prop, node, context) !ssr && props.forEach(analyzePatchFlag) properties.push(...props) if (needRuntime) { runtimeDirectives.push(prop) if (isSymbol(needRuntime)) { directiveImportMap.set(prop, needRuntime) } } } else { // no built-in transform, this is a user custom directive. runtimeDirectives.push(prop) // custom dirs may use beforeUpdate so they need to force blocks // to ensure before-update gets called before children update if (hasChildren) { shouldUseBlock = true } } } } let propsExpression: PropsExpression | undefined = undefined // has v-bind="object" or v-on="object", wrap with mergeProps if (mergeArgs.length) { if (properties.length) { mergeArgs.push( createObjectExpression(dedupeProperties(properties), elementLoc) ) } if (mergeArgs.length > 1) { propsExpression = createCallExpression( context.helper(MERGE_PROPS), mergeArgs, elementLoc ) } else { // single v-bind with nothing else - no need for a mergeProps call propsExpression = mergeArgs[0] } } else if (properties.length) { propsExpression = createObjectExpression( dedupeProperties(properties), elementLoc ) } // patchFlag analysis if (hasDynamicKeys) { patchFlag |= PatchFlags.FULL_PROPS } else { if (hasClassBinding && !isComponent) { patchFlag |= PatchFlags.CLASS } if (hasStyleBinding && !isComponent) { patchFlag |= PatchFlags.STYLE } if (dynamicPropNames.length) { patchFlag |= PatchFlags.PROPS } if (hasHydrationEventBinding) { patchFlag |= PatchFlags.HYDRATE_EVENTS } } if ( !shouldUseBlock && (patchFlag === 0 || patchFlag === PatchFlags.HYDRATE_EVENTS) && (hasRef || hasVnodeHook || runtimeDirectives.length > 0) ) { patchFlag |= PatchFlags.NEED_PATCH } // pre-normalize props, SSR is skipped for now if (!context.inSSR && propsExpression) { switch (propsExpression.type) { case NodeTypes.JS_OBJECT_EXPRESSION: // means that there is no v-bind, // but still need to deal with dynamic key binding let classKeyIndex = -1 let styleKeyIndex = -1 let hasDynamicKey = false for (let i = 0; i < propsExpression.properties.length; i++) { const key = propsExpression.properties[i].key if (isStaticExp(key)) { if (key.content === 'class') { classKeyIndex = i } else if (key.content === 'style') { styleKeyIndex = i } } else if (!key.isHandlerKey) { hasDynamicKey = true } } const classProp = propsExpression.properties[classKeyIndex] const styleProp = propsExpression.properties[styleKeyIndex] // no dynamic key if (!hasDynamicKey) { if (classProp && !isStaticExp(classProp.value)) { classProp.value = createCallExpression( context.helper(NORMALIZE_CLASS), [classProp.value] ) } if ( styleProp && !isStaticExp(styleProp.value) && // the static style is compiled into an object, // so use `hasStyleBinding` to ensure that it is a dynamic style binding (hasStyleBinding || // v-bind:style and style both exist, // v-bind:style with static literal object styleProp.value.type === NodeTypes.JS_ARRAY_EXPRESSION) ) { styleProp.value = createCallExpression( context.helper(NORMALIZE_STYLE), [styleProp.value] ) } } else { // dynamic key binding, wrap with `normalizeProps` propsExpression = createCallExpression( context.helper(NORMALIZE_PROPS), [propsExpression] ) } break case NodeTypes.JS_CALL_EXPRESSION: // mergeProps call, do nothing break default: // single v-bind propsExpression = createCallExpression( context.helper(NORMALIZE_PROPS), [ createCallExpression(context.helper(GUARD_REACTIVE_PROPS), [ propsExpression ]) ] ) break } } return { props: propsExpression, directives: runtimeDirectives, patchFlag, dynamicPropNames, shouldUseBlock } } // Dedupe props in an object literal. // Literal duplicated attributes would have been warned during the parse phase, // however, it's possible to encounter duplicated `onXXX` handlers with different // modifiers. We also need to merge static and dynamic class / style attributes. // - onXXX handlers / style: merge into array // - class: merge into single expression with concatenation function dedupeProperties(properties: Property[]): Property[] { const knownProps: Map<string, Property> = new Map() const deduped: Property[] = [] for (let i = 0; i < properties.length; i++) { const prop = properties[i] // dynamic keys are always allowed if (prop.key.type === NodeTypes.COMPOUND_EXPRESSION || !prop.key.isStatic) { deduped.push(prop) continue } const name = prop.key.content const existing = knownProps.get(name) if (existing) { if (name === 'style' || name === 'class' || isOn(name)) { mergeAsArray(existing, prop) } // unexpected duplicate, should have emitted error during parse } else { knownProps.set(name, prop) deduped.push(prop) } } return deduped } function mergeAsArray(existing: Property, incoming: Property) { if (existing.value.type === NodeTypes.JS_ARRAY_EXPRESSION) { existing.value.elements.push(incoming.value) } else { existing.value = createArrayExpression( [existing.value, incoming.value], existing.loc ) } } function buildDirectiveArgs( dir: DirectiveNode, context: TransformContext ): ArrayExpression { const dirArgs: ArrayExpression['elements'] = [] const runtime = directiveImportMap.get(dir) if (runtime) { // built-in directive with runtime dirArgs.push(context.helperString(runtime)) } else { // user directive. // see if we have directives exposed via <script setup> const fromSetup = !__BROWSER__ && resolveSetupReference('v-' + dir.name, context) if (fromSetup) { dirArgs.push(fromSetup) } else { // inject statement for resolving directive context.helper(RESOLVE_DIRECTIVE) context.directives.add(dir.name) dirArgs.push(toValidAssetId(dir.name, `directive`)) } } const { loc } = dir if (dir.exp) dirArgs.push(dir.exp) if (dir.arg) { if (!dir.exp) { dirArgs.push(`void 0`) } dirArgs.push(dir.arg) } if (Object.keys(dir.modifiers).length) { if (!dir.arg) { if (!dir.exp) { dirArgs.push(`void 0`) } dirArgs.push(`void 0`) } const trueExpression = createSimpleExpression(`true`, false, loc) dirArgs.push( createObjectExpression( dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression) ), loc ) ) } return createArrayExpression(dirArgs, dir.loc) } function stringifyDynamicPropNames(props: string[]): string { let propsNamesString = `[` for (let i = 0, l = props.length; i < l; i++) { propsNamesString += JSON.stringify(props[i]) if (i < l - 1) propsNamesString += ', ' } return propsNamesString + `]` } function isComponentTag(tag: string) { return tag === 'component' || tag === 'Component' }
the_stack
* @module Utils */ import { assert, compareBooleans, compareBooleansOrUndefined, compareNumbers, compareStringsOrUndefined, CompressedId64Set, Id64String, } from "@itwin/core-bentley"; import { Cartographic, DefaultSupportedTypes, GeoCoordStatus, PlanarClipMaskPriority, PlanarClipMaskSettings, RealityDataProvider, RealityDataSourceKey, SpatialClassifiers, ViewFlagOverrides, } from "@itwin/core-common"; import { Angle, Constant, Ellipsoid, Matrix3d, Point3d, Range3d, Ray3d, Transform, TransformProps, Vector3d, XYZ } from "@itwin/core-geometry"; import { calculateEcefToDbTransformAtLocation } from "../BackgroundMapGeometry"; import { DisplayStyleState } from "../DisplayStyleState"; import { HitDetail } from "../HitDetail"; import { IModelApp } from "../IModelApp"; import { IModelConnection } from "../IModelConnection"; import { PlanarClipMaskState } from "../PlanarClipMaskState"; import { RealityDataSource } from "../RealityDataSource"; import { RenderMemory } from "../render/RenderMemory"; import { SceneContext } from "../ViewContext"; import { ViewState } from "../ViewState"; import { BatchedTileIdMap, CesiumIonAssetProvider, createClassifierTileTreeReference, createDefaultViewFlagOverrides, DisclosedTileTreeSet, GeometryTileTreeReference, getGcsConverterAvailable, RealityTile, RealityTileLoader, RealityTileParams, RealityTileTree, RealityTileTreeParams, SpatialClassifierTileTreeReference, Tile, TileDrawArgs, TileLoadPriority, TileRequest, TileTree, TileTreeOwner, TileTreeReference, TileTreeSupplier, } from "./internal"; function getUrl(content: any) { return content ? (content.url ? content.url : content.uri) : undefined; } interface RealityTreeId { rdSourceKey: RealityDataSourceKey; transform?: Transform; modelId: Id64String; maskModelIds?: string; deduplicateVertices: boolean; produceGeometry?: boolean; toEcefTransform?: Transform; } function compareOrigins(lhs: XYZ, rhs: XYZ): number { let cmp = compareNumbers(lhs.x, rhs.x); if (0 === cmp) { cmp = compareNumbers(lhs.y, rhs.y); if (0 === cmp) cmp = compareNumbers(lhs.z, rhs.z); } return cmp; } function compareMatrices(lhs: Matrix3d, rhs: Matrix3d): number { for (let i = 0; i < 9; i++) { const cmp = compareNumbers(lhs.coffs[i], rhs.coffs[i]); if (0 !== cmp) return cmp; } return 0; } function compareTransforms(lhs?: Transform, rhs?: Transform) { if (undefined === lhs) return undefined !== rhs ? -1 : 0; else if (undefined === rhs) return 1; const cmp = compareOrigins(lhs.origin, rhs.origin); return 0 !== cmp ? cmp : compareMatrices(lhs.matrix, rhs.matrix); } class RealityTreeSupplier implements TileTreeSupplier { public readonly isEcefDependent = true; public getOwner(treeId: RealityTreeId, iModel: IModelConnection): TileTreeOwner { return iModel.tiles.getTileTreeOwner(treeId, this); } public async createTileTree(treeId: RealityTreeId, iModel: IModelConnection): Promise<TileTree | undefined> { if (treeId.maskModelIds) await iModel.models.load(CompressedId64Set.decompressSet(treeId.maskModelIds)); const opts = { deduplicateVertices: treeId.deduplicateVertices, produceGeometry: treeId.produceGeometry }; return RealityModelTileTree.createRealityModelTileTree(treeId.rdSourceKey, iModel, treeId.modelId, treeId.transform, opts); } public compareTileTreeIds(lhs: RealityTreeId, rhs: RealityTreeId): number { let cmp = compareStringsOrUndefined(lhs.rdSourceKey.id, rhs.rdSourceKey.id); if (0 === cmp) { cmp = compareStringsOrUndefined(lhs.rdSourceKey.format, rhs.rdSourceKey.format); if (0 === cmp) { cmp = compareStringsOrUndefined(lhs.rdSourceKey.iTwinId, rhs.rdSourceKey.iTwinId); if (0 === cmp) { cmp = compareStringsOrUndefined(lhs.modelId, rhs.modelId); if (0 === cmp) cmp = compareBooleans(lhs.deduplicateVertices, rhs.deduplicateVertices); } } } if (0 !== cmp) return cmp; cmp = compareStringsOrUndefined(lhs.maskModelIds, rhs.maskModelIds); if (0 !== cmp) return cmp; cmp = compareBooleansOrUndefined(lhs.produceGeometry, rhs.produceGeometry); if (0 !== cmp) return cmp; cmp = compareTransforms(lhs.transform, rhs.transform); if (0 !== cmp) return cmp; return compareTransforms(lhs.toEcefTransform, rhs.toEcefTransform); } } const realityTreeSupplier = new RealityTreeSupplier(); /** @internal */ export function createRealityTileTreeReference(props: RealityModelTileTree.ReferenceProps): RealityModelTileTree.Reference { return new RealityTreeReference(props); } const zeroPoint = Point3d.createZero(); const earthEllipsoid = Ellipsoid.createCenterMatrixRadii(zeroPoint, undefined, Constant.earthRadiusWGS84.equator, Constant.earthRadiusWGS84.equator, Constant.earthRadiusWGS84.polar); const scratchRay = Ray3d.createXAxis(); /** @internal */ export class RealityTileRegion { constructor(values: { minLongitude: number, minLatitude: number, minHeight: number, maxLongitude: number, maxLatitude: number, maxHeight: number }) { this.minLongitude = values.minLongitude; this.minLatitude = values.minLatitude; this.minHeight = values.minHeight; this.maxLongitude = values.maxLongitude; this.maxLatitude = values.maxLatitude; this.maxHeight = values.maxHeight; } public minLongitude: number; public minLatitude: number; public minHeight: number; public maxLongitude: number; public maxLatitude: number; public maxHeight: number; public static create(region: number[]): RealityTileRegion { const minHeight = region[4]; const maxHeight = region[5]; const minLongitude = region[0]; const maxLongitude = region[2]; const minLatitude = Cartographic.parametricLatitudeFromGeodeticLatitude(region[1]); const maxLatitude = Cartographic.parametricLatitudeFromGeodeticLatitude(region[3]); return new RealityTileRegion({ minLongitude, minLatitude, minHeight, maxLongitude, maxLatitude, maxHeight }); } public static isGlobal(boundingVolume: any) { return Array.isArray(boundingVolume?.region) && (boundingVolume.region[2] - boundingVolume.region[0]) > Angle.piRadians && (boundingVolume.region[3] - boundingVolume.region[1]) > Angle.piOver2Radians; } public getRange(): { range: Range3d, corners?: Point3d[] } { const maxAngle = Math.max(Math.abs(this.maxLatitude - this.minLatitude), Math.abs(this.maxLongitude - this.minLongitude)); let corners; let range: Range3d; if (maxAngle < Math.PI / 8) { corners = new Array<Point3d>(8); const chordTolerance = (1 - Math.cos(maxAngle / 2)) * Constant.earthRadiusWGS84.polar; const addEllipsoidCorner = ((long: number, lat: number, index: number) => { const ray = earthEllipsoid.radiansToUnitNormalRay(long, lat, scratchRay)!; corners[index] = ray.fractionToPoint(this.minHeight - chordTolerance); corners[index + 4] = ray.fractionToPoint(this.maxHeight + chordTolerance); }); addEllipsoidCorner(this.minLongitude, this.minLatitude, 0); addEllipsoidCorner(this.minLongitude, this.maxLatitude, 1); addEllipsoidCorner(this.maxLongitude, this.minLatitude, 2); addEllipsoidCorner(this.maxLongitude, this.maxLatitude, 3); range = Range3d.createArray(corners); } else { const minEq = Constant.earthRadiusWGS84.equator + this.minHeight, maxEq = Constant.earthRadiusWGS84.equator + this.maxHeight; const minEllipsoid = Ellipsoid.createCenterMatrixRadii(zeroPoint, undefined, minEq, minEq, Constant.earthRadiusWGS84.polar + this.minHeight); const maxEllipsoid = Ellipsoid.createCenterMatrixRadii(zeroPoint, undefined, maxEq, maxEq, Constant.earthRadiusWGS84.polar + this.maxHeight); range = minEllipsoid.patchRangeStartEndRadians(this.minLongitude, this.maxLongitude, this.minLatitude, this.maxLatitude); range.extendRange(maxEllipsoid.patchRangeStartEndRadians(this.minLongitude, this.maxLongitude, this.minLatitude, this.maxLatitude)); } return { range, corners }; } } /** @internal */ export class RealityModelTileUtils { public static rangeFromBoundingVolume(boundingVolume: any): { range: Range3d, corners?: Point3d[], region?: RealityTileRegion } | undefined { if (undefined === boundingVolume) return undefined; let corners: Point3d[] | undefined; let range: Range3d | undefined; if (undefined !== boundingVolume.box) { const box: number[] = boundingVolume.box; const center = Point3d.create(box[0], box[1], box[2]); const ux = Vector3d.create(box[3], box[4], box[5]); const uy = Vector3d.create(box[6], box[7], box[8]); const uz = Vector3d.create(box[9], box[10], box[11]); corners = new Array<Point3d>(); for (let j = 0; j < 2; j++) { for (let k = 0; k < 2; k++) { for (let l = 0; l < 2; l++) { corners.push(center.plus3Scaled(ux, (j ? -1.0 : 1.0), uy, (k ? -1.0 : 1.0), uz, (l ? -1.0 : 1.0))); } } } range = Range3d.createArray(corners); } else if (Array.isArray(boundingVolume.sphere)) { const sphere: number[] = boundingVolume.sphere; const center = Point3d.create(sphere[0], sphere[1], sphere[2]); const radius = sphere[3]; range = Range3d.createXYZXYZ(center.x - radius, center.y - radius, center.z - radius, center.x + radius, center.y + radius, center.z + radius); } else if (Array.isArray(boundingVolume.region)) { const region = RealityTileRegion.create(boundingVolume.region); const regionRange = region.getRange(); return { range: regionRange.range, corners: regionRange.corners, region }; } return range ? { range, corners } : undefined; } public static maximumSizeFromGeometricTolerance(range: Range3d, geometricError: number): number { const minToleranceRatio = true === IModelApp.renderSystem.isMobile ? IModelApp.tileAdmin.mobileRealityTileMinToleranceRatio : 1.0; // Nominally the error on screen size of a tile. Increasing generally increases performance (fewer draw calls) at expense of higher load times. // NB: We increase the above minToleranceRatio on mobile devices in order to help avoid pruning too often based on the memory threshold for // pruning currently used by reality tile trees on mobile. return minToleranceRatio * range.diagonal().magnitude() / geometricError; } public static transformFromJson(jTrans: number[] | undefined): Transform { return (jTrans === undefined) ? Transform.createIdentity() : Transform.createOriginAndMatrix(Point3d.create(jTrans[12], jTrans[13], jTrans[14]), Matrix3d.createRowValues(jTrans[0], jTrans[4], jTrans[8], jTrans[1], jTrans[5], jTrans[9], jTrans[2], jTrans[6], jTrans[10])); } } /** @internal */ enum SMTextureType { None = 0, // no textures Embedded = 1, // textures are available and stored in the nodes Streaming = 2, // textures need to be downloaded, Bing Maps, etc… } /** @internal */ class RealityModelTileTreeProps { public location: Transform; public tilesetJson: any; public doDrapeBackgroundMap: boolean = false; public rdSource: RealityDataSource; public yAxisUp = false; public root: any; constructor(json: any, root: any, rdSource: RealityDataSource, tilesetToDbTransform: Transform, public readonly tilesetToEcef?: Transform) { this.tilesetJson = root; this.rdSource = rdSource; this.location = tilesetToDbTransform; this.doDrapeBackgroundMap = (json.root && json.root.SMMasterHeader && SMTextureType.Streaming === json.root.SMMasterHeader.IsTextured); if (json.asset.gltfUpAxis === undefined || json.asset.gltfUpAxis === "y" || json.asset.gltfUpAxis === "Y") this.yAxisUp = true; } } class RealityModelTileTreeParams implements RealityTileTreeParams { public id: string; public modelId: string; public iModel: IModelConnection; public is3d = true; public loader: RealityModelTileLoader; public rootTile: RealityTileParams; public get location() { return this.loader.tree.location; } public get yAxisUp() { return this.loader.tree.yAxisUp; } public get priority() { return this.loader.priority; } public constructor(tileTreeId: string, iModel: IModelConnection, modelId: Id64String, loader: RealityModelTileLoader, public readonly gcsConverterAvailable: boolean, public readonly rootToEcef: Transform | undefined) { this.loader = loader; this.id = tileTreeId; this.modelId = modelId; this.iModel = iModel; this.rootTile = new RealityModelTileProps(loader.tree.tilesetJson, undefined, "", undefined, undefined === loader.tree.tilesetJson.refine ? undefined : loader.tree.tilesetJson.refine === "ADD"); } } /** @internal */ class RealityModelTileProps implements RealityTileParams { public readonly contentId: string; public readonly range: Range3d; public readonly contentRange?: Range3d; public readonly maximumSize: number; public readonly isLeaf: boolean; public readonly transformToRoot?: Transform; public readonly additiveRefinement?: boolean; public readonly parent?: RealityTile; public readonly noContentButTerminateOnSelection?: boolean; public readonly rangeCorners?: Point3d[]; public readonly region?: RealityTileRegion; constructor(json: any, parent: RealityTile | undefined, thisId: string, transformToRoot?: Transform, additiveRefinement?: boolean) { this.contentId = thisId; this.parent = parent; const boundingVolume = RealityModelTileUtils.rangeFromBoundingVolume(json.boundingVolume); if (boundingVolume) { this.range = boundingVolume.range; this.rangeCorners = boundingVolume.corners; this.region = boundingVolume?.region; } else { this.range = Range3d.createNull(); assert(false, "Unbounded tile"); } this.isLeaf = !Array.isArray(json.children) || 0 === json.children.length; this.transformToRoot = transformToRoot; this.additiveRefinement = additiveRefinement; const hasContents = undefined !== getUrl(json.content); if (hasContents) this.contentRange = RealityModelTileUtils.rangeFromBoundingVolume(json.content.boundingVolume)?.range; else { // A node without content should probably be selectable even if not additive refinement - But restrict it to that case here // to avoid potential problems with existing reality models, but still avoid overselection in the OSM world building set. if (this.additiveRefinement || parent?.additiveRefinement) this.noContentButTerminateOnSelection = true; } this.maximumSize = (this.noContentButTerminateOnSelection || hasContents) ? RealityModelTileUtils.maximumSizeFromGeometricTolerance(Range3d.fromJSON(this.range), json.geometricError) : 0; } } /** @internal */ class FindChildResult { constructor(public id: string, public json: any, public transformToRoot?: Transform) { } } /** @internal */ function assembleUrl(prefix: string, url: string): string { if (url.startsWith("./")) { url = url.substring(2); } else { const prefixParts = prefix.split("/"); prefixParts.pop(); while (url.startsWith("../")) { prefixParts.pop(); url = url.substring(3); } prefixParts.push(""); prefix = prefixParts.join("/"); } return prefix + url; } /** @internal */ function addUrlPrefix(subTree: any, prefix: string) { if (undefined === subTree) return; if (undefined !== subTree.content) { if (undefined !== subTree.content.url) subTree.content.url = assembleUrl(prefix, subTree.content.url); else if (undefined !== subTree.content.uri) subTree.content.uri = assembleUrl(prefix, subTree.content.uri); } if (undefined !== subTree.children) for (const child of subTree.children) addUrlPrefix(child, prefix); } /** @internal */ async function expandSubTree(root: any, rdsource: RealityDataSource): Promise<any> { const childUrl = getUrl(root.content); if (undefined !== childUrl && childUrl.endsWith("json")) { // A child may contain a subTree... const subTree = await rdsource.getTileJson(childUrl); const prefixIndex = childUrl.lastIndexOf("/"); if (prefixIndex > 0) addUrlPrefix(subTree.root, childUrl.substring(0, prefixIndex + 1)); return subTree.root; } else { return root; } } /** @internal */ class RealityModelTileLoader extends RealityTileLoader { public readonly tree: RealityModelTileTreeProps; private readonly _batchedIdMap?: BatchedTileIdMap; private _viewFlagOverrides: ViewFlagOverrides; private readonly _deduplicateVertices: boolean; public constructor(tree: RealityModelTileTreeProps, batchedIdMap?: BatchedTileIdMap, opts?: { deduplicateVertices?: boolean, produceGeometry?: boolean }) { super(opts?.produceGeometry ?? false); this.tree = tree; this._batchedIdMap = batchedIdMap; this._deduplicateVertices = opts?.deduplicateVertices ?? false; let clipVolume; if (RealityTileRegion.isGlobal(tree.tilesetJson.boundingVolume)) clipVolume = false; this._viewFlagOverrides = createDefaultViewFlagOverrides({ lighting: true, clipVolume }); // Display edges if they are present (Cesium outline extension) and enabled for view. this._viewFlagOverrides.visibleEdges = undefined; this._viewFlagOverrides.hiddenEdges = undefined; // Allow wiremesh display. this._viewFlagOverrides.wiremesh = undefined; } public get doDrapeBackgroundMap(): boolean { return this.tree.doDrapeBackgroundMap; } public override get wantDeduplicatedVertices() { return this._deduplicateVertices; } public get maxDepth(): number { return 32; } // Can be removed when element tile selector is working. public get minDepth(): number { return 0; } public get priority(): TileLoadPriority { return TileLoadPriority.Context; } public override getBatchIdMap(): BatchedTileIdMap | undefined { return this._batchedIdMap; } public get clipLowResolutionTiles(): boolean { return true; } public override get viewFlagOverrides(): ViewFlagOverrides { return this._viewFlagOverrides; } public async loadChildren(tile: RealityTile): Promise<Tile[] | undefined> { const props = await this.getChildrenProps(tile); if (undefined === props) return undefined; const children = []; for (const prop of props) children.push(tile.realityRoot.createTile(prop)); return children; } public async getChildrenProps(parent: RealityTile): Promise<RealityTileParams[]> { const props: RealityModelTileProps[] = []; const thisId = parent.contentId; const prefix = thisId.length ? `${thisId}_` : ""; const findResult = await this.findTileInJson(this.tree.tilesetJson, thisId, "", undefined); if (undefined !== findResult && Array.isArray(findResult.json.children)) { for (let i = 0; i < findResult.json.children.length; i++) { const childId = prefix + i; const foundChild = await this.findTileInJson(this.tree.tilesetJson, childId, "", undefined); if (undefined !== foundChild) props.push(new RealityModelTileProps(foundChild.json, parent, foundChild.id, foundChild.transformToRoot, foundChild.json.refine === undefined ? undefined : foundChild.json.refine === "ADD")); } } return props; } public getRequestChannel(_tile: Tile) { // ###TODO: May want to extract the hostname from the URL. return IModelApp.tileAdmin.channels.getForHttp("itwinjs-reality-model"); } public async requestTileContent(tile: Tile, isCanceled: () => boolean): Promise<TileRequest.Response> { const foundChild = await this.findTileInJson(this.tree.tilesetJson, tile.contentId, ""); if (undefined === foundChild || undefined === foundChild.json.content || isCanceled()) return undefined; return this.tree.rdSource.getTileContent(getUrl(foundChild.json.content)); } private async findTileInJson(tilesetJson: any, id: string, parentId: string, transformToRoot?: Transform): Promise<FindChildResult | undefined> { if (id.length === 0) return new FindChildResult(id, tilesetJson, transformToRoot); // Root. const separatorIndex = id.indexOf("_"); const childId = (separatorIndex < 0) ? id : id.substring(0, separatorIndex); const childIndex = parseInt(childId, 10); if (isNaN(childIndex) || tilesetJson === undefined || tilesetJson.children === undefined || childIndex >= tilesetJson.children.length) { assert(false, "scalable mesh child not found."); return undefined; } const foundChild = tilesetJson.children[childIndex]; const thisParentId = parentId.length ? (`${parentId}_${childId}`) : childId; if (foundChild.transform) { const thisTransform = RealityModelTileUtils.transformFromJson(foundChild.transform); transformToRoot = transformToRoot ? transformToRoot.multiplyTransformTransform(thisTransform) : thisTransform; } if (separatorIndex >= 0) { return this.findTileInJson(foundChild, id.substring(separatorIndex + 1), thisParentId, transformToRoot); } tilesetJson.children[childIndex] = await expandSubTree(foundChild, this.tree.rdSource); return new FindChildResult(thisParentId, tilesetJson.children[childIndex], transformToRoot); } } /** @internal */ export type RealityModelSource = ViewState | DisplayStyleState; /** @internal */ export class RealityModelTileTree extends RealityTileTree { private readonly _isContentUnbounded: boolean; public constructor(params: RealityTileTreeParams) { super(params); this._isContentUnbounded = this.rootTile.contentRange.diagonal().magnitude() > 2 * Constant.earthRadiusWGS84.equator; if (!this.isContentUnbounded && !this.rootTile.contentRange.isNull) { const worldContentRange = this.iModelTransform.multiplyRange(this.rootTile.contentRange); this.iModel.expandDisplayedExtents(worldContentRange); } } public override get isContentUnbounded() { return this._isContentUnbounded; } } /** @internal */ // eslint-disable-next-line no-redeclare export namespace RealityModelTileTree { export interface ReferenceBaseProps { iModel: IModelConnection; source: RealityModelSource; rdSourceKey: RealityDataSourceKey; modelId?: Id64String; tilesetToDbTransform?: TransformProps; tilesetToEcefTransform?: TransformProps; name?: string; classifiers?: SpatialClassifiers; planarClipMask?: PlanarClipMaskSettings; } export interface ReferenceProps extends ReferenceBaseProps { url?: string; requestAuthorization?: string; produceGeometry?: boolean; } export abstract class Reference extends TileTreeReference { protected readonly _name: string; protected _transform?: Transform; protected _iModel: IModelConnection; private _modelId: Id64String; private _isGlobal?: boolean; protected readonly _source: RealityModelSource; protected _planarClipMask?: PlanarClipMaskState; protected _classifier?: SpatialClassifierTileTreeReference; protected _mapDrapeTree?: TileTreeReference; public get modelId() { return this._modelId; } // public get classifiers(): SpatialClassifiers | undefined { return undefined !== this._classifier ? this._classifier.classifiers : undefined; } public get planarClipMask(): PlanarClipMaskState | undefined { return this._planarClipMask; } public set planarClipMask(planarClipMask: PlanarClipMaskState | undefined) { this._planarClipMask = planarClipMask; } public get planarClipMaskPriority(): number { if (this._planarClipMask?.settings.priority !== undefined) return this._planarClipMask.settings.priority; return this.isGlobal ? PlanarClipMaskPriority.GlobalRealityModel : PlanarClipMaskPriority.RealityModel; } protected get maskModelIds(): string | undefined { return this._planarClipMask?.settings.compressedModelIds; } public constructor(props: RealityModelTileTree.ReferenceBaseProps) { super(); this._name = undefined !== props.name ? props.name : ""; this._modelId = props.modelId ? props.modelId : props.iModel.transientIds.next; let transform; if (undefined !== props.tilesetToDbTransform) { const tf = Transform.fromJSON(props.tilesetToDbTransform); if (!tf.isIdentity) transform = tf; this._transform = transform; } this._iModel = props.iModel; this._source = props.source; if (props.planarClipMask) this._planarClipMask = PlanarClipMaskState.create(props.planarClipMask); if (undefined !== props.classifiers) this._classifier = createClassifierTileTreeReference(props.classifiers, this, props.iModel, props.source); } public get planarClassifierTreeRef() { return this._classifier && this._classifier.activeClassifier && this._classifier.isPlanar ? this._classifier : undefined; } public override unionFitRange(union: Range3d): void { const contentRange = this.computeWorldContentRange(); if (!contentRange.isNull && contentRange.diagonal().magnitude() < Constant.earthRadiusWGS84.equator) union.extendRange(contentRange); } public override get isGlobal() { if (undefined === this._isGlobal) { const range = this.computeWorldContentRange(); if (!range.isNull) this._isGlobal = range.diagonal().magnitude() > 2 * Constant.earthRadiusWGS84.equator; } return this._isGlobal === undefined ? false : this._isGlobal; } public override addToScene(context: SceneContext): void { // NB: The classifier must be added first, so we can find it when adding our own tiles. if (this._classifier && this._classifier.activeClassifier) this._classifier.addToScene(context); this.addPlanarClassifierOrMaskToScene(context); super.addToScene(context); } protected addPlanarClassifierOrMaskToScene(context: SceneContext) { // A planarClassifier is required if there is a classification tree OR planar masking is required. const classifierTree = this.planarClassifierTreeRef; const planarClipMask = this._planarClipMask ?? context.viewport.displayStyle.getPlanarClipMaskState(this.modelId); if (!classifierTree && !planarClipMask) return; if (classifierTree && !classifierTree.treeOwner.load()) return; context.addPlanarClassifier(this.modelId, classifierTree, planarClipMask); } public override discloseTileTrees(trees: DisclosedTileTreeSet): void { super.discloseTileTrees(trees); if (undefined !== this._classifier) this._classifier.discloseTileTrees(trees); if (undefined !== this._mapDrapeTree) this._mapDrapeTree.discloseTileTrees(trees); if (undefined !== this._planarClipMask) this._planarClipMask.discloseTileTrees(trees); } public override collectStatistics(stats: RenderMemory.Statistics): void { super.collectStatistics(stats); const tree = undefined !== this._classifier ? this._classifier.treeOwner.tileTree : undefined; if (undefined !== tree) tree.collectStatistics(stats); } } export async function createRealityModelTileTree(rdSourceKey: RealityDataSourceKey, iModel: IModelConnection, modelId: Id64String, tilesetToDb: Transform | undefined, opts?: { deduplicateVertices?: boolean, produceGeometry?: boolean }): Promise<TileTree | undefined> { const rdSource = await RealityDataSource.fromKey(rdSourceKey, iModel.iTwinId); // If we can get a valid connection from sourceKey, returns the tile tree if (rdSource) { // Serialize the reality data source key into a string to uniquely identify this tile tree const tileTreeId = rdSource.key.toString(); if (tileTreeId === undefined) return undefined; const props = await getTileTreeProps(rdSource, tilesetToDb, iModel); const loader = new RealityModelTileLoader(props, new BatchedTileIdMap(iModel), opts); const gcsConverterAvailable = await getGcsConverterAvailable(iModel); const params = new RealityModelTileTreeParams(tileTreeId, iModel, modelId, loader, gcsConverterAvailable, props.tilesetToEcef); return new RealityModelTileTree(params); } return undefined; } async function getTileTreeProps(rdSource: RealityDataSource, tilesetToDbJson: any, iModel: IModelConnection): Promise<RealityModelTileTreeProps> { const json = await rdSource.getRootDocument(iModel.iTwinId); let rootTransform = iModel.ecefLocation ? iModel.getMapEcefToDb(0) : Transform.createIdentity(); const geoConverter = iModel.noGcsDefined ? undefined : iModel.geoServices.getConverter("WGS84"); if (geoConverter !== undefined) { let realityTileRange = RealityModelTileUtils.rangeFromBoundingVolume(json.root.boundingVolume)!.range; if (json.root.transform) { const realityToEcef = RealityModelTileUtils.transformFromJson(json.root.transform); realityTileRange = realityToEcef.multiplyRange(realityTileRange); } if (iModel.ecefLocation) { // In initial publishing version the iModel ecef Transform was used to locate the reality model. // This would work well only for tilesets published from that iModel but for iModels the ecef transform is calculated // at the center of the project extents and the reality model location may differ greatly, and the curvature of the earth // could introduce significant errors. // The publishing was modified to calculate the ecef transform at the reality model range center and at the same time the "iModelPublishVersion" // member was added to the root object. In order to continue to locate reality models published from older versions at the // project extents center we look for Tileset version 0.0 and no root.iModelVersion. const ecefOrigin = realityTileRange.localXYZToWorld(.5, .5, .5)!; const dbOrigin = rootTransform.multiplyPoint3d(ecefOrigin); const realityOriginToProjectDistance = iModel.projectExtents.distanceToPoint(dbOrigin); const maxProjectDistance = 1E5; // Only use the project GCS projection if within 100KM of the project. Don't attempt to use GCS if global reality model or in another locale - Results will be unreliable. if (realityOriginToProjectDistance < maxProjectDistance && json.asset?.version !== "0.0" || undefined !== json.root?.iModelPublishVersion) { const cartographicOrigin = Cartographic.fromEcef(ecefOrigin); if (cartographicOrigin !== undefined) { const geoOrigin = Point3d.create(cartographicOrigin.longitudeDegrees, cartographicOrigin.latitudeDegrees, cartographicOrigin.height); const response = await geoConverter.getIModelCoordinatesFromGeoCoordinates([geoOrigin]); if (response.iModelCoords[0].s === GeoCoordStatus.Success) { const ecefToDb = await calculateEcefToDbTransformAtLocation(Point3d.fromJSON(response.iModelCoords[0].p), iModel); if (ecefToDb) rootTransform = ecefToDb; } } } } } let tilesetToEcef = Transform.createIdentity(); if (json.root.transform) { tilesetToEcef = RealityModelTileUtils.transformFromJson(json.root.transform); rootTransform = rootTransform.multiplyTransformTransform(tilesetToEcef); } if (undefined !== tilesetToDbJson) rootTransform = Transform.fromJSON(tilesetToDbJson).multiplyTransformTransform(rootTransform); const root = await expandSubTree(json.root, rdSource); return new RealityModelTileTreeProps(json, root, rdSource, rootTransform, tilesetToEcef); } } /** Supplies a reality data [[TileTree]] from a URL. May be associated with a persistent [[GeometricModelState]], or attached at run-time via a [[ContextRealityModelState]]. * @internal */ export class RealityTreeReference extends RealityModelTileTree.Reference { protected _rdSourceKey: RealityDataSourceKey; private readonly _produceGeometry?: boolean; public constructor(props: RealityModelTileTree.ReferenceProps) { super(props); this._produceGeometry = props.produceGeometry; // Maybe we should throw if both props.rdSourceKey && props.url are undefined if (props.rdSourceKey) this._rdSourceKey = props.rdSourceKey; else this._rdSourceKey = RealityDataSource.createKeyFromUrl(props.url ?? "", RealityDataProvider.ContextShare); if (this._produceGeometry) this.collectTileGeometry = (collector) => this._collectTileGeometry(collector); } public get treeOwner(): TileTreeOwner { const treeId: RealityTreeId = { rdSourceKey: this._rdSourceKey, transform: this._transform, modelId: this.modelId, maskModelIds: this.maskModelIds, deduplicateVertices: this._wantWiremesh, produceGeometry: this._produceGeometry, }; return realityTreeSupplier.getOwner(treeId, this._iModel); } protected override _createGeometryTreeReference(): GeometryTileTreeReference { const ref = new RealityTreeReference({ iModel: this._iModel, modelId: this.modelId, source: this._source, rdSourceKey: this._rdSourceKey, name: this._name, produceGeometry: true, }); assert(undefined !== ref.collectTileGeometry); return ref as GeometryTileTreeReference; } private get _wantWiremesh(): boolean { return this._source.viewFlags.wiremesh; } public override get castsShadows() { return true; } protected override get _isLoadingComplete(): boolean { return !this._mapDrapeTree || this._mapDrapeTree.isLoadingComplete; } public override createDrawArgs(context: SceneContext): TileDrawArgs | undefined { // For global reality models (OSM Building layer only) - offset the reality model by the BIM elevation bias. This would not be necessary // if iModels had their elevation set correctly but unfortunately many GCS erroneously report Sea (Geoid) elevation rather than // Geodetic. const tree = this.treeOwner.load(); if (undefined === tree) return undefined; const drawArgs = super.createDrawArgs(context); if (drawArgs !== undefined && this._iModel.isGeoLocated && tree.isContentUnbounded) { const elevationBias = context.viewport.view.displayStyle.backgroundMapElevationBias; if (undefined !== elevationBias) drawArgs.location.origin.z -= elevationBias; } return drawArgs; } public override addToScene(context: SceneContext): void { const tree = this.treeOwner.tileTree as RealityTileTree; if (undefined !== tree && context.viewport.iModel.isGeoLocated && (tree.loader as RealityModelTileLoader).doDrapeBackgroundMap) { // NB: We save this off strictly so that discloseTileTrees() can find it...better option? this._mapDrapeTree = context.viewport.backgroundDrapeMap; context.addBackgroundDrapedModel(this, undefined); } super.addToScene(context); } public override async getToolTip(hit: HitDetail): Promise<HTMLElement | string | undefined> { const tree = this.treeOwner.tileTree; if (undefined === tree || hit.iModel !== tree.iModel) return undefined; const map = (tree as RealityTileTree).loader.getBatchIdMap(); const batch = undefined !== map ? map.getBatchProperties(hit.sourceId) : undefined; if (undefined === batch && tree.modelId !== hit.sourceId) return undefined; const strings = []; const loader = (tree as RealityModelTileTree).loader; const type = (loader as RealityModelTileLoader).tree.rdSource.realityDataType; // If a type is specified, display it if (type !== undefined) { // Case insensitive switch (type.toUpperCase()) { case DefaultSupportedTypes.RealityMesh3dTiles.toUpperCase(): strings.push(IModelApp.localization.getLocalizedString("iModelJs:RealityModelTypes.RealityMesh3DTiles")); break; case DefaultSupportedTypes.Terrain3dTiles.toUpperCase(): strings.push(IModelApp.localization.getLocalizedString("iModelJs:RealityModelTypes.Terrain3DTiles")); break; case DefaultSupportedTypes.Cesium3dTiles.toUpperCase(): strings.push(IModelApp.localization.getLocalizedString("iModelJs:RealityModelTypes.Cesium3DTiles")); break; } } if (this._name) { strings.push(`${IModelApp.localization.getLocalizedString("iModelJs:TooltipInfo.Name")} ${this._name}`); } else { const cesiumAsset = this._rdSourceKey.provider === RealityDataProvider.CesiumIonAsset ? CesiumIonAssetProvider.parseCesiumUrl(this._rdSourceKey.id) : undefined; strings.push(cesiumAsset ? `Cesium Asset: ${cesiumAsset.id}` : this._rdSourceKey.id); } if (batch !== undefined) for (const key of Object.keys(batch)) if (-1 === key.indexOf("#")) // Avoid internal cesium strings.push(`${key}: ${batch[key]}`); const div = document.createElement("div"); div.innerHTML = strings.join("<br>"); return div; } public override addLogoCards(cards: HTMLTableElement): void { if (this._rdSourceKey.provider === RealityDataProvider.CesiumIonAsset && !cards.dataset.openStreetMapLogoCard) { cards.dataset.openStreetMapLogoCard = "true"; cards.appendChild(IModelApp.makeLogoCard({ heading: "OpenStreetMap", notice: `&copy;<a href=\"https://www.openstreetmap.org/copyright\">OpenStreetMap</a> ${IModelApp.localization.getLocalizedString("iModelJs:BackgroundMap:OpenStreetMapContributors")}` })); } } }
the_stack
import { AnyAction, createSelector, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { QueryStatus, QuerySubState, SubscriptionOptions, QueryKeys, RootState } from '../core/apiState'; import { EndpointDefinitions, MutationDefinition, QueryDefinition, QueryArgFrom, ResultTypeFrom, } from '../endpointDefinitions'; import { QueryResultSelectorResult, MutationResultSelectorResult, skipSelector } from '../core/buildSelectors'; import { QueryActionCreatorResult, MutationActionCreatorResult } from '../core/buildInitiate'; import { shallowEqual } from '../utils'; import { Api } from '../apiTypes'; import { Id, NoInfer, Override } from '../tsHelpers'; import { ApiEndpointMutation, ApiEndpointQuery, CoreModule, PrefetchOptions } from '../core/module'; import { ReactHooksModuleOptions } from './module'; import { useShallowStableValue } from './useShallowStableValue'; import { UninitializedValue, UNINITIALIZED_VALUE } from '../constants'; export interface QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> { useQuery: UseQuery<Definition>; useLazyQuery: UseLazyQuery<Definition>; useQuerySubscription: UseQuerySubscription<Definition>; useLazyQuerySubscription: UseLazyQuerySubscription<Definition>; useQueryState: UseQueryState<Definition>; } export interface MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> { useMutation: UseMutation<Definition>; } /** * test description here */ export type UseQuery<D extends QueryDefinition<any, any, any, any>> = < R extends Record<string, any> = UseQueryStateDefaultResult<D> >( arg: QueryArgFrom<D>, options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R> ) => UseQueryStateResult<D, R> & ReturnType<UseQuerySubscription<D>>; interface UseQuerySubscriptionOptions extends SubscriptionOptions { /** * Prevents a query from automatically running. * * @remarks * When skip is true: * * - **If the query has cached data:** * * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed * * The query will have a status of `uninitialized` * * If `skip: false` is set after skipping the initial load, the cached result will be used * - **If the query does not have cached data:** * * The query will have a status of `uninitialized` * * The query will not exist in the state when viewed with the dev tools * * The query will not automatically fetch on mount * * The query will not automatically run when additional components with the same query are added that do run * * @example * ```ts * // codeblock-meta title="Skip example" * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => { * const { data, error, status } = useGetPokemonByNameQuery(name, { * skip, * }); * * return ( * <div> * {name} - {status} * </div> * ); * }; * ``` */ skip?: boolean; /** * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result. * - `false` - Will not cause a query to be performed _unless_ it does not exist yet. * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator. * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed. * * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false. */ refetchOnMountOrArgChange?: boolean | number; } export type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = ( arg: QueryArgFrom<D>, options?: UseQuerySubscriptionOptions ) => Pick<QueryActionCreatorResult<D>, 'refetch'>; export type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = { lastArg: QueryArgFrom<D>; }; export type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R = UseQueryStateDefaultResult<D>>( options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'> ) => [(arg: QueryArgFrom<D>) => void, UseQueryStateResult<D, R>, UseLazyQueryLastPromiseInfo<D>]; export type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = ( options?: SubscriptionOptions ) => [(arg: QueryArgFrom<D>) => void, QueryArgFrom<D> | UninitializedValue]; export type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = ( state: QueryResultSelectorResult<D>, lastResult: R | undefined, defaultQueryStateSelector: DefaultQueryStateSelector<D> ) => R; export type DefaultQueryStateSelector<D extends QueryDefinition<any, any, any, any>> = ( state: QueryResultSelectorResult<D>, lastResult: Pick<UseQueryStateDefaultResult<D>, 'data'> ) => UseQueryStateDefaultResult<D>; export type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <R = UseQueryStateDefaultResult<D>>( arg: QueryArgFrom<D>, options?: UseQueryStateOptions<D, R> ) => UseQueryStateResult<D, R>; export type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = { /** * Prevents a query from automatically running. * * @remarks * When skip is true: * * - **If the query has cached data:** * * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed * * The query will have a status of `uninitialized` * * If `skip: false` is set after skipping the initial load, the cached result will be used * - **If the query does not have cached data:** * * The query will have a status of `uninitialized` * * The query will not exist in the state when viewed with the dev tools * * The query will not automatically fetch on mount * * The query will not automatically run when additional components with the same query are added that do run * * @example * ```ts * // codeblock-meta title="Skip example" * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => { * const { data, error, status } = useGetPokemonByNameQuery(name, { * skip, * }); * * return ( * <div> * {name} - {status} * </div> * ); * }; * ``` */ skip?: boolean; /** * `selectFromResult` allows you to get a specific segment from a query result in a performant manner. * When using this feature, the component will not rerender unless the underlying data of the selected item has changed. * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection. * * @example * ```ts * // codeblock-meta title="Using selectFromResult to extract a single result" * function PostsList() { * const { data: posts } = api.useGetPostsQuery(); * * return ( * <ul> * {posts?.data?.map((post) => ( * <PostById key={post.id} id={post.id} /> * ))} * </ul> * ); * } * * function PostById({ id }: { id: number }) { * // Will select the post with the given id, and will only rerender if the given posts data changes * const { post } = api.useGetPostsQuery(undefined, { * selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }), * }); * * return <li>{post?.name}</li>; * } * ``` */ selectFromResult?: QueryStateSelector<R, D>; }; export type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = NoInfer<R>; type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & { /** * Query has not started yet. */ isUninitialized: false; /** * Query is currently loading for the first time. No data yet. */ isLoading: false; /** * Query is currently fetching, but might have data from an earlier request. */ isFetching: false; /** * Query has data from a successful load. */ isSuccess: false; /** * Query is currently in "error" state. */ isError: false; }; type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = Id< | Override<Extract<UseQueryStateBaseResult<D>, { status: QueryStatus.uninitialized }>, { isUninitialized: true }> | Override< UseQueryStateBaseResult<D>, | { isLoading: true; isFetching: boolean; data: undefined } | ({ isSuccess: true; isFetching: boolean; error: undefined } & Required< Pick<UseQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'> >) | ({ isError: true } & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>) > > & { /** * @deprecated will be removed in the next version * please use the `isLoading`, `isFetching`, `isSuccess`, `isError` * and `isUninitialized` flags instead */ status: QueryStatus; }; export type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = ( state: MutationResultSelectorResult<D>, defaultMutationStateSelector: DefaultMutationStateSelector<D> ) => R; export type DefaultMutationStateSelector<D extends MutationDefinition<any, any, any, any>> = ( state: MutationResultSelectorResult<D> ) => MutationResultSelectorResult<D>; export type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = { selectFromResult?: MutationStateSelector<R, D>; }; export type UseMutationStateResult<_ extends MutationDefinition<any, any, any, any>, R> = NoInfer<R>; export type UseMutation<D extends MutationDefinition<any, any, any, any>> = < R extends Record<string, any> = MutationResultSelectorResult<D> >( options?: UseMutationStateOptions<D, R> ) => [ ( arg: QueryArgFrom<D> ) => { /** * Unwraps a mutation call to provide the raw response/error. * * @remarks * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap(). * * @example * ```ts * // codeblock-meta title="Using .unwrap" * addPost({ id: 1, name: 'Example' }) * .unwrap() * .then((payload) => console.log('fulfilled', payload)) * .catch((error) => console.error('rejected', error)); * ``` * * @example * ```ts * // codeblock-meta title="Using .unwrap with async await" * try { * const payload = await addPost({ id: 1, name: 'Example' }).unwrap(); * console.log('fulfilled', payload) * } catch (error) { * console.error('rejected', error); * } * ``` */ unwrap: () => Promise<ResultTypeFrom<D>>; }, UseMutationStateResult<D, R> ]; const defaultMutationStateSelector: DefaultMutationStateSelector<any> = (currentState) => currentState; const defaultQueryStateSelector: DefaultQueryStateSelector<any> = (currentState, lastResult) => { // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args const data = (currentState.isSuccess ? currentState.data : lastResult?.data) ?? currentState.data; // isFetching = true any time a request is in flight const isFetching = currentState.isLoading; // isLoading = true only when loading while no data is present yet (initial load with no data in the cache) const isLoading = !data && isFetching; // isSuccess = true when data is present const isSuccess = currentState.isSuccess || (isFetching && !!data); return { ...currentState, data, isFetching, isLoading, isSuccess } as UseQueryStateDefaultResult<any>; }; /** * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`. * We want the initial render to already come back with * `{ isUninitialized: false, isFetching: true, isLoading: true }` * to prevent that the library user has to do an additional check for `isUninitialized`/ */ const noPendingQueryStateSelector: DefaultQueryStateSelector<any> = (currentState, lastResult) => { const selected = defaultQueryStateSelector(currentState, lastResult); if (selected.isUninitialized) { return { ...selected, isUninitialized: false, isFetching: true, isLoading: true, status: QueryStatus.pending, }; } return selected; }; type GenericPrefetchThunk = ( endpointName: any, arg: any, options: PrefetchOptions ) => ThunkAction<void, any, any, AnyAction>; /** * * @param opts.api - An API with defined endpoints to create hooks for * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used * @returns An object containing functions to generate hooks based on an endpoint */ export function buildHooks<Definitions extends EndpointDefinitions>({ api, moduleOptions: { batch, useDispatch, useSelector }, }: { api: Api<any, Definitions, any, any, CoreModule>; moduleOptions: Required<ReactHooksModuleOptions>; }) { return { buildQueryHooks, buildMutationHook, usePrefetch }; function usePrefetch<EndpointName extends QueryKeys<Definitions>>( endpointName: EndpointName, defaultOptions?: PrefetchOptions ) { const dispatch = useDispatch<ThunkDispatch<any, any, AnyAction>>(); const stableDefaultOptions = useShallowStableValue(defaultOptions); return useCallback( (arg: any, options?: PrefetchOptions) => dispatch( (api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, { ...stableDefaultOptions, ...options }) ), [endpointName, dispatch, stableDefaultOptions] ); } function buildQueryHooks(name: string): QueryHooks<any> { const useQuerySubscription: UseQuerySubscription<any> = ( arg: any, { refetchOnReconnect, refetchOnFocus, refetchOnMountOrArgChange, skip = false, pollingInterval = 0 } = {} ) => { const { initiate } = api.endpoints[name] as ApiEndpointQuery< QueryDefinition<any, any, any, any, any>, Definitions >; const dispatch = useDispatch<ThunkDispatch<any, any, AnyAction>>(); const stableArg = useShallowStableValue(arg); const stableSubscriptionOptions = useShallowStableValue({ refetchOnReconnect, refetchOnFocus, pollingInterval, }); const promiseRef = useRef<QueryActionCreatorResult<any>>(); useEffect(() => { if (skip) { return; } const lastPromise = promiseRef.current; const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions; if (!lastPromise || lastPromise.arg !== stableArg) { lastPromise?.unsubscribe(); const promise = dispatch( initiate(stableArg, { subscriptionOptions: stableSubscriptionOptions, forceRefetch: refetchOnMountOrArgChange, }) ); promiseRef.current = promise; } else if (stableSubscriptionOptions !== lastSubscriptionOptions) { lastPromise.updateSubscriptionOptions(stableSubscriptionOptions); } }, [dispatch, initiate, refetchOnMountOrArgChange, skip, stableArg, stableSubscriptionOptions]); useEffect(() => { return () => { promiseRef.current?.unsubscribe(); promiseRef.current = undefined; }; }, []); return useMemo( () => ({ /** * A method to manually refetch data for the query */ refetch: () => void promiseRef.current?.refetch(), }), [] ); }; const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({ refetchOnReconnect, refetchOnFocus, pollingInterval = 0, } = {}) => { const { initiate } = api.endpoints[name] as ApiEndpointQuery< QueryDefinition<any, any, any, any, any>, Definitions >; const dispatch = useDispatch<ThunkDispatch<any, any, AnyAction>>(); const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE); const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(); const stableSubscriptionOptions = useShallowStableValue({ refetchOnReconnect, refetchOnFocus, pollingInterval, }); useEffect(() => { const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions; if (stableSubscriptionOptions !== lastSubscriptionOptions) { promiseRef.current?.updateSubscriptionOptions(stableSubscriptionOptions); } }, [stableSubscriptionOptions]); const subscriptionOptionsRef = useRef(stableSubscriptionOptions); useEffect(() => { subscriptionOptionsRef.current = stableSubscriptionOptions; }, [stableSubscriptionOptions]); const trigger = useCallback( function (arg: any, preferCacheValue = false) { batch(() => { promiseRef.current?.unsubscribe(); promiseRef.current = dispatch( initiate(arg, { subscriptionOptions: subscriptionOptionsRef.current, forceRefetch: !preferCacheValue, }) ); setArg(arg); }); }, [dispatch, initiate] ); /* cleanup on unmount */ useEffect(() => { return () => { promiseRef?.current?.unsubscribe(); }; }, []); /* if "cleanup on unmount" was triggered from a fast refresh, we want to reinstate the query */ useEffect(() => { if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) { trigger(arg, true); } }, [arg, trigger]); return useMemo(() => [trigger, arg], [trigger, arg]); }; const useQueryState: UseQueryState<any> = ( arg: any, { skip = false, selectFromResult = defaultQueryStateSelector as QueryStateSelector<any, any> } = {} ) => { const { select } = api.endpoints[name] as ApiEndpointQuery<QueryDefinition<any, any, any, any, any>, Definitions>; const stableArg = useShallowStableValue(arg); const lastValue = useRef<any>(); const querySelector = useMemo( () => createSelector( [select(skip ? skipSelector : stableArg), (_: any, lastResult: any) => lastResult], (subState, lastResult) => selectFromResult(subState, lastResult, defaultQueryStateSelector) ), [select, skip, stableArg, selectFromResult] ); const currentState = useSelector( (state: RootState<Definitions, any, any>) => querySelector(state, lastValue.current), shallowEqual ); useEffect(() => { lastValue.current = currentState; }, [currentState]); return currentState; }; return { useQueryState, useQuerySubscription, useLazyQuerySubscription, useLazyQuery(options) { const [trigger, arg] = useLazyQuerySubscription(options); const queryStateResults = useQueryState(arg, { ...options, skip: arg === UNINITIALIZED_VALUE, }); const info = useMemo(() => ({ lastArg: arg }), [arg]); return useMemo(() => [trigger, queryStateResults, info], [trigger, queryStateResults, info]); }, useQuery(arg, options) { const querySubscriptionResults = useQuerySubscription(arg, options); const queryStateResults = useQueryState(arg, { selectFromResult: options?.skip ? undefined : (noPendingQueryStateSelector as QueryStateSelector<any, any>), ...options, }); return useMemo(() => ({ ...queryStateResults, ...querySubscriptionResults }), [ queryStateResults, querySubscriptionResults, ]); }, }; } function buildMutationHook(name: string): UseMutation<any> { return ({ selectFromResult = defaultMutationStateSelector as MutationStateSelector<any, any> } = {}) => { const { select, initiate } = api.endpoints[name] as ApiEndpointMutation< MutationDefinition<any, any, any, any, any>, Definitions >; const dispatch = useDispatch<ThunkDispatch<any, any, AnyAction>>(); const [requestId, setRequestId] = useState<string>(); const promiseRef = useRef<MutationActionCreatorResult<any>>(); useEffect(() => { return () => { promiseRef.current?.unsubscribe(); promiseRef.current = undefined; }; }, []); const triggerMutation = useCallback( function (arg) { let promise: MutationActionCreatorResult<any>; batch(() => { promiseRef?.current?.unsubscribe(); promise = dispatch(initiate(arg)); promiseRef.current = promise; setRequestId(promise.requestId); }); return promise!; }, [dispatch, initiate] ); const mutationSelector = useMemo( () => createSelector([select(requestId || skipSelector)], (subState) => selectFromResult(subState, defaultMutationStateSelector) ), [select, requestId, selectFromResult] ); const currentState = useSelector(mutationSelector, shallowEqual); return useMemo(() => [triggerMutation, currentState], [triggerMutation, currentState]); }; } }
the_stack
import test from "ava"; import { CellProvider } from "./cell_provider"; import { TransactionSkeleton, TransactionSkeletonType, } from "@ckb-lumos/helpers"; import { dao, common } from "../src"; import { predefined, Config } from "@ckb-lumos/config-manager"; const { LINA, AGGRON4 } = predefined; import { bob } from "./account_info"; import { inputs } from "./secp256k1_blake160_inputs"; import { Script, Cell, HexString } from "@ckb-lumos/base"; import { bobMultisigDaoInputs, bobMultisigInputs, bobSecpDaoDepositInput, bobSecpDaoWithdrawInput, } from "./inputs"; const cellProvider = new CellProvider(inputs); let txSkeleton: TransactionSkeletonType = TransactionSkeleton({ cellProvider }); const generateDaoTypeScript = (config: Config): Script => { return { code_hash: config.SCRIPTS.DAO!.CODE_HASH, hash_type: config.SCRIPTS.DAO!.HASH_TYPE, args: "0x", }; }; test("deposit secp256k1_blake160", async (t) => { txSkeleton = await dao.deposit( txSkeleton, bob.mainnetAddress, bob.mainnetAddress, BigInt(1000 * 10 ** 8) ); const inputCapacity = txSkeleton .get("inputs") .map((i) => BigInt(i.cell_output.capacity)) .reduce((result, c) => result + c, BigInt(0)); const outputCapacity = txSkeleton .get("outputs") .map((o) => BigInt(o.cell_output.capacity)) .reduce((result, c) => result + c, BigInt(0)); t.is(outputCapacity, inputCapacity); t.is(txSkeleton.get("cellDeps").size, 2); t.deepEqual(txSkeleton.get("cellDeps").get(0)!.out_point, { tx_hash: LINA.SCRIPTS.DAO!.TX_HASH, index: LINA.SCRIPTS.DAO!.INDEX, }); t.is(txSkeleton.get("cellDeps").get(0)!.dep_type, LINA.SCRIPTS.DAO!.DEP_TYPE); t.is(txSkeleton.get("inputs").size, 1); t.is(txSkeleton.get("witnesses").size, 1); t.is(txSkeleton.get("outputs").size, 2); t.deepEqual( txSkeleton.get("outputs").get(0)!.cell_output!.type, generateDaoTypeScript(LINA) ); }); test("withdraw secp256k1_blake160", async (t) => { txSkeleton = await dao.deposit( txSkeleton, bob.mainnetAddress, bob.mainnetAddress, BigInt(1000 * 10 ** 8) ); const fromInput = txSkeleton.get("outputs").get(0)!; (fromInput.block_hash = "0x" + "1".repeat(64)), (fromInput.block_number = "0x100"); fromInput.out_point = { tx_hash: "0x" + "1".repeat(64), index: "0x0", }; txSkeleton = TransactionSkeleton({ cellProvider }); txSkeleton = await dao.withdraw(txSkeleton, fromInput, bob.mainnetAddress); t.is(txSkeleton.get("cellDeps").size, 2); t.deepEqual(txSkeleton.get("cellDeps").get(0)!.out_point, { tx_hash: LINA.SCRIPTS.DAO!.TX_HASH, index: LINA.SCRIPTS.DAO!.INDEX, }); t.is(txSkeleton.get("cellDeps").get(0)!.dep_type, LINA.SCRIPTS.DAO!.DEP_TYPE); t.is(txSkeleton.get("inputs").size, 1); t.is(txSkeleton.get("witnesses").size, 1); t.not(txSkeleton.get("witnesses").get(0)!, "0x"); t.is(txSkeleton.get("outputs").size, 1); t.is( txSkeleton.get("inputs").get(0)!.cell_output.capacity, txSkeleton.get("outputs").get(0)!.cell_output.capacity ); t.is(txSkeleton.get("headerDeps").size, 1); t.is(txSkeleton.get("headerDeps").get(0)!, fromInput.block_hash); t.deepEqual( txSkeleton.get("outputs").get(0)!.cell_output.type, generateDaoTypeScript(LINA) ); const inputCapacity = txSkeleton .get("inputs") .map((i) => BigInt(i.cell_output.capacity)) .reduce((result, c) => result + c, BigInt(0)); const outputCapacity = txSkeleton .get("outputs") .map((o) => BigInt(o.cell_output.capacity)) .reduce((result, c) => result + c, BigInt(0)); t.is(outputCapacity, inputCapacity); }); const calculateMaximumWithdrawInfo = { depositInput: { cell_output: { capacity: "0x174876e800", lock: { code_hash: "0x9bd7e06f3ecf4be0f2fcd2188b23f1b9fcc88e5d4b65a8637b17723bbda3cce8", hash_type: "type", args: "0xe2193df51d78411601796b35b17b4f8f2cd85bd0", }, type: { code_hash: "0x82d76d1b75fe2fd9a27dfbaa65a039221a380d76c926f378d3f81cf3e7e13f2e", hash_type: "type", args: "0x", }, }, out_point: { tx_hash: "0x9fbcf16a96897c1b0b80d4070752b9f30577d91275f5b460b048b955b58e08eb", index: "0x0", }, block_hash: "0x41d081cd95d705c4e80a6b473f71050efc4a0a0057ee8cab98c4933ad11f0719", block_number: "0x19249", data: "0x0000000000000000", }, depositHeader: { compact_target: "0x20010000", dao: "0x8eedf002d7c88852433518952edc28002dd416364532c50800d096d05aac0200", epoch: "0xa000500283a", hash: "0x41d081cd95d705c4e80a6b473f71050efc4a0a0057ee8cab98c4933ad11f0719", nonce: "0x98e10e0a992f7274c7dc0c62e9d42f02", number: "0x19249", parent_hash: "0xd4f3e8725de77aedadcf15755c0f6cdd00bc8d4a971e251385b59ce8215a5d70", proposals_hash: "0x0000000000000000000000000000000000000000000000000000000000000000", timestamp: "0x17293289266", transactions_root: "0x9294a800ec389d1b0d9e7c570c249da260a44cc2790bd4aa250f3d5c83eb8cde", uncles_hash: "0x0000000000000000000000000000000000000000000000000000000000000000", version: "0x0", }, withdrawHeader: { compact_target: "0x20010000", dao: "0x39d32247d33f90523d37dae613dd280037e9cc1d7b01c708003d8849d8ac0200", epoch: "0xa0008002842", hash: "0x156ecda80550b6664e5d745b6277c0ae56009681389dcc8f1565d815633ae906", nonce: "0x7ffb49f45f12f2b30ac45586ecf13de2", number: "0x1929c", parent_hash: "0xfe601308a34f1faf68906d2338e60246674ed1f1fbbad3d8471daca21a11cdf7", proposals_hash: "0x0000000000000000000000000000000000000000000000000000000000000000", timestamp: "0x1729cdd69c9", transactions_root: "0x467d72af12af6cb122985f9838bfc47073bba30cc37a4075aef54b0f0768f384", uncles_hash: "0x0000000000000000000000000000000000000000000000000000000000000000", version: "0x0", }, expectedWithdrawCapacity: BigInt("0x1748ec3fdc"), }; test("calculateMaximumWithdraw", (t) => { const { depositInput, depositHeader, withdrawHeader, expectedWithdrawCapacity, } = calculateMaximumWithdrawInfo; const result = dao.calculateMaximumWithdraw( depositInput as Cell, depositHeader.dao, withdrawHeader.dao ); t.is(result, expectedWithdrawCapacity); }); test("deposit multisig", async (t) => { const cellProvider = new CellProvider(bobMultisigInputs); let txSkeleton: TransactionSkeletonType = TransactionSkeleton({ cellProvider, }); txSkeleton = await dao.deposit( txSkeleton, bob.fromInfo, bob.multisigTestnetAddress, BigInt(500 * 10 ** 8), { config: AGGRON4 } ); txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 }); const inputCapacity = txSkeleton .get("inputs") .map((i) => BigInt(i.cell_output.capacity)) .reduce((result, c) => result + c, BigInt(0)); const outputCapacity = txSkeleton .get("outputs") .map((o) => BigInt(o.cell_output.capacity)) .reduce((result, c) => result + c, BigInt(0)); t.is(outputCapacity, inputCapacity); t.is(txSkeleton.get("cellDeps").size, 2); t.deepEqual(txSkeleton.get("cellDeps").get(0)!.out_point, { tx_hash: AGGRON4.SCRIPTS.DAO!.TX_HASH, index: AGGRON4.SCRIPTS.DAO!.INDEX, }); t.is( txSkeleton.get("cellDeps").get(0)!.dep_type, AGGRON4.SCRIPTS.DAO!.DEP_TYPE ); t.is(txSkeleton.get("inputs").size, 1); t.is(txSkeleton.get("witnesses").size, 1); t.is(txSkeleton.get("outputs").size, 2); t.deepEqual( txSkeleton.get("outputs").get(0)!.cell_output!.type, generateDaoTypeScript(AGGRON4) ); t.is(txSkeleton.get("signingEntries").size, 1); const expectedMessage = "0xa41875ea85b7abda153b7aa3c24e2874e30c88d69203a2f8b9bceb6e52e8b73c"; const message = txSkeleton.get("signingEntries").get(0)!.message; t.is(message, expectedMessage); t.is(txSkeleton.get("witnesses").size, 1); const expectedWitness = "0x6d000000100000006d0000006d000000590000000000010136c329ed630d6ce750712a477543672adab57f4c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; const witness = txSkeleton.get("witnesses").get(0)!; t.is(witness, expectedWitness); }); test("withdraw multisig", async (t) => { const cellProvider = new CellProvider(bobMultisigDaoInputs); let txSkeleton: TransactionSkeletonType = TransactionSkeleton({ cellProvider, }); txSkeleton = await dao.withdraw( txSkeleton, bobMultisigDaoInputs[0], bob.fromInfo, { config: AGGRON4, } ); txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4 }); t.is(txSkeleton.get("cellDeps").size, 2); t.deepEqual(txSkeleton.get("cellDeps").get(0)!.out_point, { tx_hash: AGGRON4.SCRIPTS.DAO!.TX_HASH, index: AGGRON4.SCRIPTS.DAO!.INDEX, }); t.is( txSkeleton.get("cellDeps").get(0)!.dep_type, AGGRON4.SCRIPTS.DAO!.DEP_TYPE ); t.is(txSkeleton.get("inputs").size, 1); t.is(txSkeleton.get("witnesses").size, 1); t.not(txSkeleton.get("witnesses").get(0)!, "0x"); t.is(txSkeleton.get("outputs").size, 1); t.is( txSkeleton.get("inputs").get(0)!.cell_output.capacity, txSkeleton.get("outputs").get(0)!.cell_output.capacity ); t.is(txSkeleton.get("headerDeps").size, 1); t.is( txSkeleton.get("headerDeps").get(0)!, bobMultisigDaoInputs[0].block_hash ); t.deepEqual( txSkeleton.get("outputs").get(0)!.cell_output.type, generateDaoTypeScript(AGGRON4) ); const inputCapacity = txSkeleton .get("inputs") .map((i) => BigInt(i.cell_output.capacity)) .reduce((result, c) => result + c, BigInt(0)); const outputCapacity = txSkeleton .get("outputs") .map((o) => BigInt(o.cell_output.capacity)) .reduce((result, c) => result + c, BigInt(0)); t.is(outputCapacity, inputCapacity); const expectedMessage = "0x0d54fdf2cb8ec8cfbb41376e8fbd2851866a07724e5f5075d83d8b519279e801"; const expectedWitness = "0x6d000000100000006d0000006d000000590000000000010136c329ed630d6ce750712a477543672adab57f4c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; t.is(txSkeleton.get("signingEntries").size, 1); t.is(txSkeleton.get("witnesses").size, 1); const message = txSkeleton.get("signingEntries").get(0)!.message; t.is(message, expectedMessage); const witness = txSkeleton.get("witnesses").get(0); t.is(witness, expectedWitness); }); test("deposit, dao script not exists", async (t) => { await t.throwsAsync( async () => { await dao.deposit( txSkeleton, bob.mainnetAddress, bob.mainnetAddress, BigInt(1000 * 10 ** 8), { config: { PREFIX: "ckt", SCRIPTS: {}, }, } ); }, undefined, "Provided config does not have DAO script setup!" ); }); test("deposit, toAddress not exists", async (t) => { await t.throwsAsync( async () => { await dao.deposit( txSkeleton, bob.mainnetAddress, undefined as any, BigInt(1000 * 10 ** 8), { config: { PREFIX: "ckt", SCRIPTS: {}, }, } ); }, undefined, "You must provide a to address!" ); }); test("CellCollector, all", async (t) => { const cellProvider = new CellProvider(bobMultisigDaoInputs); const iter = new dao.CellCollector( bob.multisigTestnetAddress, cellProvider, "all", { config: AGGRON4, } ).collect(); let count = 0; while (!(await iter.next()).done) { count += 1; } t.is(count, 1); }); test("CellCollector, deposit", async (t) => { const cellProvider = new CellProvider(bobMultisigDaoInputs); const iter = new dao.CellCollector( bob.multisigTestnetAddress, cellProvider, "deposit", { config: AGGRON4, } ).collect(); let count = 0; while (!(await iter.next()).done) { count += 1; } t.is(count, 1); }); test("CellCollector, withdraw", async (t) => { const cellProvider = new CellProvider(bobMultisigDaoInputs); const iter = new dao.CellCollector( bob.multisigTestnetAddress, cellProvider, "withdraw", { config: AGGRON4, } ).collect(); let count = 0; while (!(await iter.next()).done) { count += 1; } t.is(count, 0); }); test("listDaoCells, deposit", async (t) => { const cellProvider = new CellProvider(bobMultisigDaoInputs); const iter = dao.listDaoCells( cellProvider, bob.multisigTestnetAddress, "deposit", { config: AGGRON4, } ); let count = 0; while (!(await iter.next()).done) { count += 1; } t.is(count, 1); }); test("calculateDaoEarliestSince", (t) => { const { depositHeader, withdrawHeader } = calculateMaximumWithdrawInfo; const result = dao.calculateDaoEarliestSince( depositHeader.epoch, withdrawHeader.epoch ); // since: relative = false, type = epochNumber value = { length: 10, index: 5, number: 10478 } // if decrease index to 4, will false to validation by dao script t.is(result, BigInt("0x20000a00050028ee")); }); class RpcMocker { async get_header(hash: HexString) { if (hash === calculateMaximumWithdrawInfo.depositHeader.hash) { return calculateMaximumWithdrawInfo.depositHeader; } if (hash === calculateMaximumWithdrawInfo.withdrawHeader.hash) { return calculateMaximumWithdrawInfo.withdrawHeader; } throw new Error("RpcMocker get_header error!"); } } test("unlock", async (t) => { const cellProvider = new CellProvider([bobSecpDaoWithdrawInput]); let txSkeleton = TransactionSkeleton({ cellProvider }); txSkeleton = await dao.unlock( txSkeleton, bobSecpDaoDepositInput, bobSecpDaoWithdrawInput, bob.testnetAddress, bob.testnetAddress, { config: AGGRON4, RpcClient: RpcMocker as any, } ); txSkeleton = common.prepareSigningEntries(txSkeleton, { config: AGGRON4, }); t.is(txSkeleton.get("inputs").size, 1); t.is(txSkeleton.get("outputs").size, 1); t.deepEqual(txSkeleton.get("headerDeps").toJS(), [ calculateMaximumWithdrawInfo.depositHeader.hash, calculateMaximumWithdrawInfo.withdrawHeader.hash, ]); const expectedMessage = "0xf276a45b7dbc018c2e10c4cd0a61915dd28db768894efc1b2c557c9566fc43fd"; const expectedWitness = "0x61000000100000005500000061000000410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000"; t.is(txSkeleton.get("signingEntries").size, 1); t.is(txSkeleton.get("witnesses").size, 1); const message = txSkeleton.get("signingEntries").get(0)!.message; const witness = txSkeleton.get("witnesses").get(0)!; t.is(message, expectedMessage); t.is(witness, expectedWitness); });
the_stack
import { Entity, RELATION_API_CONSUMED_BY, RELATION_API_PROVIDED_BY, RELATION_CONSUMES_API, RELATION_DEPENDENCY_OF, RELATION_DEPENDS_ON, RELATION_HAS_PART, RELATION_PART_OF, RELATION_PROVIDES_API, } from '@backstage/catalog-model'; import { EmptyState } from '@backstage/core-components'; import { EntityApiDefinitionCard, EntityConsumedApisCard, EntityConsumingComponentsCard, EntityHasApisCard, EntityProvidedApisCard, EntityProvidingComponentsCard, } from '@backstage/plugin-api-docs'; import { EntityAzurePipelinesContent, EntityAzureGitTagsContent, EntityAzurePullRequestsContent, isAzureDevOpsAvailable, isAzurePipelinesAvailable, } from '@backstage/plugin-azure-devops'; import { EntityBadgesDialog } from '@backstage/plugin-badges'; import { EntityAboutCard, EntityDependsOnComponentsCard, EntityDependsOnResourcesCard, EntityHasComponentsCard, EntityHasResourcesCard, EntityHasSubcomponentsCard, EntityHasSystemsCard, EntityLayout, EntityLinksCard, EntityOrphanWarning, EntityProcessingErrorsPanel, EntitySwitch, hasCatalogProcessingErrors, isComponentType, isKind, isOrphan, } from '@backstage/plugin-catalog'; import { Direction, EntityCatalogGraphCard, } from '@backstage/plugin-catalog-graph'; import { EntityCircleCIContent, isCircleCIAvailable, } from '@backstage/plugin-circleci'; import { EntityCloudbuildContent, isCloudbuildAvailable, } from '@backstage/plugin-cloudbuild'; import { EntityCodeCoverageContent } from '@backstage/plugin-code-coverage'; import { EntityGithubActionsContent, EntityRecentGithubActionsRunsCard, isGithubActionsAvailable, } from '@backstage/plugin-github-actions'; import { EntityJenkinsContent, EntityLatestJenkinsRunCard, isJenkinsAvailable, } from '@backstage/plugin-jenkins'; import { EntityKafkaContent } from '@backstage/plugin-kafka'; import { EntityKubernetesContent } from '@backstage/plugin-kubernetes'; import { EntityLastLighthouseAuditCard, EntityLighthouseContent, isLighthouseAvailable, } from '@backstage/plugin-lighthouse'; import { EntityGroupProfileCard, EntityMembersListCard, EntityOwnershipCard, EntityUserProfileCard, } from '@backstage/plugin-org'; import { EntityPagerDutyCard, isPagerDutyAvailable, } from '@backstage/plugin-pagerduty'; import { EntityRollbarContent, isRollbarAvailable, } from '@backstage/plugin-rollbar'; import { EntitySentryContent } from '@backstage/plugin-sentry'; import { EntityTechdocsContent } from '@backstage/plugin-techdocs'; import { EntityTodoContent } from '@backstage/plugin-todo'; import { Button, Grid } from '@material-ui/core'; import BadgeIcon from '@material-ui/icons/CallToAction'; import { EntityGithubInsightsContent, EntityGithubInsightsLanguagesCard, EntityGithubInsightsReadmeCard, EntityGithubInsightsReleasesCard, isGithubInsightsAvailable, } from '@roadiehq/backstage-plugin-github-insights'; import { EntityGithubPullRequestsContent, EntityGithubPullRequestsOverviewCard, isGithubPullRequestsAvailable, } from '@roadiehq/backstage-plugin-github-pull-requests'; import { EntityTravisCIContent, EntityTravisCIOverviewCard, isTravisciAvailable, } from '@roadiehq/backstage-plugin-travis-ci'; import { EntityBuildkiteContent, isBuildkiteAvailable, } from '@roadiehq/backstage-plugin-buildkite'; import { isNewRelicDashboardAvailable, EntityNewRelicDashboardContent, EntityNewRelicDashboardCard, } from '@backstage/plugin-newrelic-dashboard'; import { EntityGoCdContent, isGoCdAvailable } from '@backstage/plugin-gocd'; import React, { ReactNode, useMemo, useState } from 'react'; import { TechDocsAddons } from '@backstage/plugin-techdocs-react'; import { TextSize, ReportIssue, } from '@backstage/plugin-techdocs-module-addons-contrib'; const customEntityFilterKind = ['Component', 'API', 'System']; const EntityLayoutWrapper = (props: { children?: ReactNode }) => { const [badgesDialogOpen, setBadgesDialogOpen] = useState(false); const extraMenuItems = useMemo(() => { return [ { title: 'Badges', Icon: BadgeIcon, onClick: () => setBadgesDialogOpen(true), }, ]; }, []); return ( <> <EntityLayout UNSTABLE_extraContextMenuItems={extraMenuItems}> {props.children} </EntityLayout> <EntityBadgesDialog open={badgesDialogOpen} onClose={() => setBadgesDialogOpen(false)} /> </> ); }; const techdocsContent = ( <EntityTechdocsContent> <TechDocsAddons> <TextSize /> <ReportIssue /> </TechDocsAddons> </EntityTechdocsContent> ); /** * NOTE: This page is designed to work on small screens such as mobile devices. * This is based on Material UI Grid. If breakpoints are used, each grid item must set the `xs` prop to a column size or to `true`, * since this does not default. If no breakpoints are used, the items will equitably share the asvailable space. * https://material-ui.com/components/grid/#basic-grid. */ export const cicdContent = ( <EntitySwitch> <EntitySwitch.Case if={isJenkinsAvailable}> <EntityJenkinsContent /> </EntitySwitch.Case> <EntitySwitch.Case if={isBuildkiteAvailable}> <EntityBuildkiteContent /> </EntitySwitch.Case> <EntitySwitch.Case if={isCircleCIAvailable}> <EntityCircleCIContent /> </EntitySwitch.Case> <EntitySwitch.Case if={isCloudbuildAvailable}> <EntityCloudbuildContent /> </EntitySwitch.Case> <EntitySwitch.Case if={isTravisciAvailable}> <EntityTravisCIContent /> </EntitySwitch.Case> <EntitySwitch.Case if={isGoCdAvailable}> <EntityGoCdContent /> </EntitySwitch.Case> <EntitySwitch.Case if={isGithubActionsAvailable}> <EntityGithubActionsContent /> </EntitySwitch.Case> <EntitySwitch.Case if={isAzurePipelinesAvailable}> <EntityAzurePipelinesContent defaultLimit={25} /> </EntitySwitch.Case> <EntitySwitch.Case> <EmptyState title="No CI/CD available for this entity" missing="info" description="You need to add an annotation to your component if you want to enable CI/CD for it. You can read more about annotations in Backstage by clicking the button below." action={ <Button variant="contained" color="primary" href="https://backstage.io/docs/features/software-catalog/well-known-annotations" > Read more </Button> } /> </EntitySwitch.Case> </EntitySwitch> ); const cicdCard = ( <EntitySwitch> <EntitySwitch.Case if={isJenkinsAvailable}> <Grid item sm={6}> <EntityLatestJenkinsRunCard branch="master" variant="gridItem" /> </Grid> </EntitySwitch.Case> <EntitySwitch.Case if={isTravisciAvailable as (e: Entity) => boolean}> <Grid item sm={6}> <EntityTravisCIOverviewCard /> </Grid> </EntitySwitch.Case> <EntitySwitch.Case if={isGithubActionsAvailable}> <Grid item sm={6}> <EntityRecentGithubActionsRunsCard limit={4} variant="gridItem" /> </Grid> </EntitySwitch.Case> </EntitySwitch> ); const entityWarningContent = ( <> <EntitySwitch> <EntitySwitch.Case if={isOrphan}> <Grid item xs={12}> <EntityOrphanWarning /> </Grid> </EntitySwitch.Case> </EntitySwitch> <EntitySwitch> <EntitySwitch.Case if={hasCatalogProcessingErrors}> <Grid item xs={12}> <EntityProcessingErrorsPanel /> </Grid> </EntitySwitch.Case> </EntitySwitch> </> ); const errorsContent = ( <EntitySwitch> <EntitySwitch.Case if={isRollbarAvailable}> <EntityRollbarContent /> </EntitySwitch.Case> <EntitySwitch.Case> <EntitySentryContent /> </EntitySwitch.Case> </EntitySwitch> ); const pullRequestsContent = ( <EntitySwitch> <EntitySwitch.Case if={isAzureDevOpsAvailable}> <EntityAzurePullRequestsContent defaultLimit={25} /> </EntitySwitch.Case> <EntitySwitch.Case> <EntityGithubPullRequestsContent /> </EntitySwitch.Case> </EntitySwitch> ); const overviewContent = ( <Grid container spacing={3} alignItems="stretch"> {entityWarningContent} <Grid item md={6} xs={12}> <EntityAboutCard variant="gridItem" /> </Grid> <Grid item md={6} xs={12}> <EntityCatalogGraphCard variant="gridItem" height={400} /> </Grid> <EntitySwitch> <EntitySwitch.Case if={isPagerDutyAvailable}> <Grid item md={6}> <EntityPagerDutyCard /> </Grid> </EntitySwitch.Case> </EntitySwitch> <EntitySwitch> <EntitySwitch.Case if={isNewRelicDashboardAvailable}> <Grid item md={6} xs={12}> <EntityNewRelicDashboardCard /> </Grid> </EntitySwitch.Case> </EntitySwitch> <Grid item md={4} xs={12}> <EntityLinksCard /> </Grid> {cicdCard} <EntitySwitch> <EntitySwitch.Case if={isGithubInsightsAvailable}> <Grid item md={6}> <EntityGithubInsightsLanguagesCard /> <EntityGithubInsightsReleasesCard /> </Grid> <Grid item md={6}> <EntityGithubInsightsReadmeCard maxHeight={350} /> </Grid> </EntitySwitch.Case> </EntitySwitch> <EntitySwitch> <EntitySwitch.Case if={isLighthouseAvailable}> <Grid item sm={4}> <EntityLastLighthouseAuditCard variant="gridItem" /> </Grid> </EntitySwitch.Case> </EntitySwitch> <EntitySwitch> <EntitySwitch.Case if={isGithubPullRequestsAvailable}> <Grid item sm={4}> <EntityGithubPullRequestsOverviewCard /> </Grid> </EntitySwitch.Case> </EntitySwitch> <Grid item md={8} xs={12}> <EntityHasSubcomponentsCard variant="gridItem" /> </Grid> </Grid> ); const serviceEntityPage = ( <EntityLayoutWrapper> <EntityLayout.Route path="/" title="Overview"> {overviewContent} </EntityLayout.Route> <EntityLayout.Route path="/ci-cd" title="CI/CD"> {cicdContent} </EntityLayout.Route> <EntityLayout.Route path="/errors" title="Errors"> {errorsContent} </EntityLayout.Route> <EntityLayout.Route path="/api" title="API"> <Grid container spacing={3} alignItems="stretch"> <Grid item xs={12} md={6}> <EntityProvidedApisCard /> </Grid> <Grid item xs={12} md={6}> <EntityConsumedApisCard /> </Grid> </Grid> </EntityLayout.Route> <EntityLayout.Route path="/dependencies" title="Dependencies"> <Grid container spacing={3} alignItems="stretch"> <Grid item xs={12} md={6}> <EntityDependsOnComponentsCard variant="gridItem" /> </Grid> <Grid item xs={12} md={6}> <EntityDependsOnResourcesCard variant="gridItem" /> </Grid> </Grid> </EntityLayout.Route> <EntityLayout.Route path="/docs" title="Docs"> {techdocsContent} </EntityLayout.Route> <EntityLayout.Route if={isNewRelicDashboardAvailable} path="/newrelic-dashboard" title="New Relic Dashboard" > <EntityNewRelicDashboardContent /> </EntityLayout.Route> <EntityLayout.Route path="/kubernetes" title="Kubernetes"> <EntityKubernetesContent /> </EntityLayout.Route> <EntityLayout.Route path="/pull-requests" title="Pull Requests"> {pullRequestsContent} </EntityLayout.Route> <EntityLayout.Route path="/code-insights" title="Code Insights"> <EntityGithubInsightsContent /> </EntityLayout.Route> <EntityLayout.Route path="/code-coverage" title="Code Coverage"> <EntityCodeCoverageContent /> </EntityLayout.Route> <EntityLayout.Route path="/kafka" title="Kafka"> <EntityKafkaContent /> </EntityLayout.Route> <EntityLayout.Route path="/todos" title="TODOs"> <EntityTodoContent /> </EntityLayout.Route> </EntityLayoutWrapper> ); const websiteEntityPage = ( <EntityLayoutWrapper> <EntityLayout.Route path="/" title="Overview"> {overviewContent} </EntityLayout.Route> <EntityLayout.Route path="/ci-cd" title="CI/CD"> {cicdContent} </EntityLayout.Route> <EntityLayout.Route path="/lighthouse" title="Lighthouse"> <EntityLighthouseContent /> </EntityLayout.Route> <EntityLayout.Route path="/errors" title="Errors"> {errorsContent} </EntityLayout.Route> <EntityLayout.Route path="/dependencies" title="Dependencies"> <Grid container spacing={3} alignItems="stretch"> <Grid item md={6}> <EntityDependsOnComponentsCard variant="gridItem" /> </Grid> <Grid item md={6}> <EntityDependsOnResourcesCard variant="gridItem" /> </Grid> </Grid> </EntityLayout.Route> <EntityLayout.Route path="/docs" title="Docs"> {techdocsContent} </EntityLayout.Route> <EntityLayout.Route if={isNewRelicDashboardAvailable} path="/newrelic-dashboard" title="New Relic Dashboard" > <EntityNewRelicDashboardContent /> </EntityLayout.Route> <EntityLayout.Route path="/kubernetes" title="Kubernetes"> <EntityKubernetesContent /> </EntityLayout.Route> <EntityLayout.Route if={isAzureDevOpsAvailable} path="/git-tags" title="Git Tags" > <EntityAzureGitTagsContent /> </EntityLayout.Route> <EntityLayout.Route path="/pull-requests" title="Pull Requests"> {pullRequestsContent} </EntityLayout.Route> <EntityLayout.Route path="/code-insights" title="Code Insights"> <EntityGithubInsightsContent /> </EntityLayout.Route> <EntityLayout.Route path="/code-coverage" title="Code Coverage"> <EntityCodeCoverageContent /> </EntityLayout.Route> <EntityLayout.Route path="/todos" title="TODOs"> <EntityTodoContent /> </EntityLayout.Route> </EntityLayoutWrapper> ); const defaultEntityPage = ( <EntityLayoutWrapper> <EntityLayout.Route path="/" title="Overview"> {overviewContent} </EntityLayout.Route> <EntityLayout.Route path="/docs" title="Docs"> {techdocsContent} </EntityLayout.Route> <EntityLayout.Route path="/todos" title="TODOs"> <EntityTodoContent /> </EntityLayout.Route> </EntityLayoutWrapper> ); const componentPage = ( <EntitySwitch> <EntitySwitch.Case if={isComponentType('service')}> {serviceEntityPage} </EntitySwitch.Case> <EntitySwitch.Case if={isComponentType('website')}> {websiteEntityPage} </EntitySwitch.Case> <EntitySwitch.Case>{defaultEntityPage}</EntitySwitch.Case> </EntitySwitch> ); const apiPage = ( <EntityLayoutWrapper> <EntityLayout.Route path="/" title="Overview"> <Grid container spacing={3}> {entityWarningContent} <Grid item md={6} xs={12}> <EntityAboutCard /> </Grid> <Grid item md={6} xs={12}> <EntityCatalogGraphCard variant="gridItem" height={400} /> </Grid> <Grid item xs={12}> <Grid container> <Grid item xs={12} md={6}> <EntityProvidingComponentsCard /> </Grid> <Grid item xs={12} md={6}> <EntityConsumingComponentsCard /> </Grid> </Grid> </Grid> </Grid> </EntityLayout.Route> <EntityLayout.Route path="/definition" title="Definition"> <Grid container spacing={3}> <Grid item xs={12}> <EntityApiDefinitionCard /> </Grid> </Grid> </EntityLayout.Route> </EntityLayoutWrapper> ); const userPage = ( <EntityLayoutWrapper> <EntityLayout.Route path="/" title="Overview"> <Grid container spacing={3}> {entityWarningContent} <Grid item xs={12} md={6}> <EntityUserProfileCard variant="gridItem" /> </Grid> <Grid item xs={12} md={6}> <EntityOwnershipCard variant="gridItem" entityFilterKind={customEntityFilterKind} /> </Grid> </Grid> </EntityLayout.Route> </EntityLayoutWrapper> ); const groupPage = ( <EntityLayoutWrapper> <EntityLayout.Route path="/" title="Overview"> <Grid container spacing={3}> {entityWarningContent} <Grid item xs={12} md={6}> <EntityGroupProfileCard variant="gridItem" /> </Grid> <Grid item xs={12} md={6}> <EntityOwnershipCard variant="gridItem" entityFilterKind={customEntityFilterKind} /> </Grid> <Grid item xs={12}> <EntityMembersListCard /> </Grid> </Grid> </EntityLayout.Route> </EntityLayoutWrapper> ); const systemPage = ( <EntityLayoutWrapper> <EntityLayout.Route path="/" title="Overview"> <Grid container spacing={3} alignItems="stretch"> {entityWarningContent} <Grid item md={6}> <EntityAboutCard variant="gridItem" /> </Grid> <Grid item md={6} xs={12}> <EntityCatalogGraphCard variant="gridItem" height={400} /> </Grid> <Grid item md={6}> <EntityHasComponentsCard variant="gridItem" /> </Grid> <Grid item md={6}> <EntityHasApisCard variant="gridItem" /> </Grid> <Grid item md={6}> <EntityHasResourcesCard variant="gridItem" /> </Grid> </Grid> </EntityLayout.Route> <EntityLayout.Route path="/diagram" title="Diagram"> <EntityCatalogGraphCard variant="gridItem" direction={Direction.TOP_BOTTOM} title="System Diagram" height={700} relations={[ RELATION_PART_OF, RELATION_HAS_PART, RELATION_API_CONSUMED_BY, RELATION_API_PROVIDED_BY, RELATION_CONSUMES_API, RELATION_PROVIDES_API, RELATION_DEPENDENCY_OF, RELATION_DEPENDS_ON, ]} unidirectional={false} /> </EntityLayout.Route> </EntityLayoutWrapper> ); const domainPage = ( <EntityLayoutWrapper> <EntityLayout.Route path="/" title="Overview"> <Grid container spacing={3} alignItems="stretch"> {entityWarningContent} <Grid item md={6}> <EntityAboutCard variant="gridItem" /> </Grid> <Grid item md={6} xs={12}> <EntityCatalogGraphCard variant="gridItem" height={400} /> </Grid> <Grid item md={6}> <EntityHasSystemsCard variant="gridItem" /> </Grid> </Grid> </EntityLayout.Route> </EntityLayoutWrapper> ); export const entityPage = ( <EntitySwitch> <EntitySwitch.Case if={isKind('component')} children={componentPage} /> <EntitySwitch.Case if={isKind('api')} children={apiPage} /> <EntitySwitch.Case if={isKind('group')} children={groupPage} /> <EntitySwitch.Case if={isKind('user')} children={userPage} /> <EntitySwitch.Case if={isKind('system')} children={systemPage} /> <EntitySwitch.Case if={isKind('domain')} children={domainPage} /> <EntitySwitch.Case>{defaultEntityPage}</EntitySwitch.Case> </EntitySwitch> );
the_stack
declare module "attachCustomCommands" { import * as admin from 'firebase-admin'; /** * Params for attachCustomCommand function for * attaching custom commands. */ export interface AttachCustomCommandParams { Cypress: any; cy: any; firebase: any; } /** * Action for Firestore */ export type FirestoreAction = 'get' | 'add' | 'set' | 'update' | 'delete'; /** * Data from loaded fixture */ export interface FixtureData { [k: string]: any; } type WhereOptions = [string, FirebaseFirestore.WhereFilterOp, any]; /** * Options for callFirestore custom Cypress command. */ export interface CallFirestoreOptions { /** * Whether or not to include createdAt and createdBy */ withMeta?: boolean; /** * Merge during set */ merge?: boolean; /** * Size of batch to use while deleting */ batchSize?: number; /** * Filter documents by the specified field and the value should satisfy * the relation constraint provided */ where?: WhereOptions | WhereOptions[]; /** * Order documents */ orderBy?: string | [string, FirebaseFirestore.OrderByDirection]; /** * Limit to n number of documents */ limit?: number; /** * Limit to last n number of documents */ limitToLast?: number; /** * Firestore statics (i.e. admin.firestore). This should only be needed during * testing due to @firebase/testing not containing statics */ statics?: typeof admin.firestore; } /** * Action for Real Time Database */ export type RTDBAction = 'push' | 'remove' | 'set' | 'update' | 'delete' | 'get'; /** * Options for callRtdb commands */ export interface CallRtdbOptions { /** * Whether or not to include meta data */ withMeta?: boolean; /** * Limit to the last <num> results. * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#limittolast */ limitToLast?: number; /** * Limit to the first <num> results. * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#limittofirst */ limitToFirst?: number; /** * Select a child key by which to order results * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#orderbychild */ orderByChild?: string; /** * Order by key name * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#orderbykey */ orderByKey?: boolean; /** * Order by primitive value * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#orderbyvalue */ orderByValue?: boolean; /** * Creates a Query with the specified starting point. * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#startat */ startAt?: number | string | boolean | null | [number | string | boolean | null, string]; /** * Creates a Query with the specified starting point. * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#startafter */ startAfter?: number | string | boolean | null | [number | string | boolean | null, string]; /** * End results after <val, key> (based on specified ordering) * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#endbefore */ endBefore?: number | string | boolean | null | [number | string | boolean | null, string]; /** * End results at <val> (based on specified ordering) * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#endat */ endAt?: number | string | boolean | null | [number | string | boolean | null, string]; /** * Restrict results to <val> (based on specified ordering) * @see https://firebase.google.com/docs/reference/js/firebase.database.Query#equalto */ equalTo?: number | string | boolean | null | [number | string | boolean | null, string]; } global { namespace Cypress { interface Chainable { /** * Login to Firebase auth as a user with either a passed uid or the TEST_UID * environment variable. A custom auth token is generated using firebase-admin * authenticated with serviceAccount.json or SERVICE_ACCOUNT env var. * @see https://github.com/prescottprue/cypress-firebase#cylogin * @param uid - UID of user to login as * @param customClaims - Custom claims to attach to the custom token * @example <caption>Env Based Login (TEST_UID)</caption> * cy.login() * @example <caption>Passed UID</caption> * cy.login('123SOMEUID') */ login: (uid?: string, customClaims?: any) => Chainable; /** * Log current user out of Firebase Auth * @see https://github.com/prescottprue/cypress-firebase#cylogout * @example * cy.logout() */ logout: () => Chainable; /** * Call Real Time Database path with some specified action. Authentication is through * `FIREBASE_TOKEN` (CI token) since firebase-tools is used under the hood, allowing * for admin privileges. * @param action - The action type to call with (set, push, update, remove) * @param actionPath - Path within RTDB that action should be applied * @param dataOrOptions - Data to be used in write action or options to be used for query * @param options - Options object * @see https://github.com/prescottprue/cypress-firebase#cycallrtdb * @example <caption>Set Data</caption> * const fakeProject = { some: 'data' } * cy.callRtdb('set', 'projects/ABC123', fakeProject) * @example <caption>Set Data With Meta Data</caption> * const fakeProject = { some: 'data' } * // Adds createdAt and createdBy (current user's uid) on data * cy.callRtdb('set', 'projects/ABC123', fakeProject, { withMeta: true }) */ callRtdb: (action: RTDBAction, actionPath: string, dataOrOptions?: FixtureData | string | boolean | CallRtdbOptions, options?: CallRtdbOptions) => Chainable; /** * Call Firestore instance with some specified action. Supports get, set, update, * add, and delete. Authentication is through serviceAccount.json or SERVICE_ACCOUNT * environment variable. * @param action - The action type to call with (set, push, update, remove) * @param actionPath - Path within RTDB that action should be applied * @param dataOrOptions - Data to be used in write action or options to be used for query * @param options - Options object * @see https://github.com/prescottprue/cypress-firebase#cycallfirestore * @example <caption>Set Data</caption> * const project = { some: 'data' } * cy.callFirestore('set', 'project/test-project', project) * @example <caption>Add New Document</caption> * const project = { some: 'data' } * cy.callFirestore('add', 'projects', project) * @example <caption>Basic Get</caption> * cy.callFirestore('get', 'projects/test-project').then((project) => { * cy.log('Project:', project) * }) * @example <caption>Passing A Fixture</caption> * cy.fixture('fakeProject.json').then((project) => { * cy.callFirestore('add', 'projects', project) * }) */ callFirestore: (action: FirestoreAction, actionPath: string, dataOrOptions?: FixtureData | string | boolean | CallFirestoreOptions, options?: CallFirestoreOptions) => Chainable; } } } interface CommandNamespacesConfig { login?: string; logout?: string; callRtdb?: string; callFirestore?: string; getAuthUser?: string; } interface CustomCommandOptions { commandNames?: CommandNamespacesConfig; } /** * Attach custom commands including cy.login, cy.logout, cy.callRtdb, * @param context - Context values passed from Cypress environment * custom command attachment * @param options - Custom command options */ export default function attachCustomCommands(context: AttachCustomCommandParams, options?: CustomCommandOptions): void; } declare module "extendWithFirebaseConfig" { export interface CypressEnvironmentOptions { envName?: string; firebaseProjectId?: string; [k: string]: any; } export interface CypressConfig { env?: CypressEnvironmentOptions; baseUrl?: string; [k: string]: any; } export interface ExtendedCypressConfigEnv { [k: string]: any; FIREBASE_AUTH_EMULATOR_HOST?: string; FIRESTORE_EMULATOR_HOST?: string; FIREBASE_DATABASE_EMULATOR_HOST?: string; GCLOUD_PROJECT?: string; } export interface ExtendedCypressConfig { [k: string]: any; env: ExtendedCypressConfigEnv; } export interface ExtendWithFirebaseConfigSettings { localBaseUrl?: string; localHostPort?: string | number; } /** * Load config for Cypress from environment variables. Loads * FIREBASE_AUTH_EMULATOR_HOST, FIRESTORE_EMULATOR_HOST, * FIREBASE_DATABASE_EMULATOR_HOST, and GCLOUD_PROJECT variable * values from environment to pass to Cypress environment * @param cypressConfig - Existing Cypress config * @returns Cypress config extended with environment variables */ export default function extendWithFirebaseConfig(cypressConfig: CypressConfig): ExtendedCypressConfig; } declare module "node-utils" { interface ServiceAccount { type: string; project_id: string; private_key_id: string; private_key: string; client_email: string; client_id: string; auth_uri: string; token_uri: string; auth_provider_x509_cert_url: string; client_x509_cert_url: string; } /** * Get service account from either environment variables or local file. * SERVICE_ACCOUNT environment variables takes precedence * NOTE: Loading from default local file path "process.cwd()}/serviceAccount.json" * is now deprecated * @param envSlug - Environment option * @returns Service account object */ export function getServiceAccount(envSlug?: string): ServiceAccount | null; } declare module "firebase-utils" { import * as admin from 'firebase-admin'; import { CallFirestoreOptions } from "attachCustomCommands"; /** * Check whether a value is a string or not * @param valToCheck - Value to check * @returns Whether or not value is a string */ export function isString(valToCheck: any): boolean; /** * Initialize Firebase instance from service account (from either local * serviceAccount.json or environment variables) * @returns Initialized Firebase instance * @param adminInstance - firebase-admin instance to initialize * @param overrideConfig - firebase-admin instance to initialize */ export function initializeFirebase(adminInstance: any, overrideConfig?: admin.AppOptions): admin.app.App; /** * Check with or not a slash path is the path of a document * @param slashPath - Path to check for whether or not it is a doc * @returns Whether or not slash path is a document path */ export function isDocPath(slashPath: string): boolean; /** * Convert slash path to Firestore reference * @param firestoreInstance - Instance on which to * create ref * @param slashPath - Path to convert into firestore refernce * @param options - Options object * @returns Ref at slash path */ export function slashPathToFirestoreRef(firestoreInstance: any, slashPath: string, options?: CallFirestoreOptions): admin.firestore.CollectionReference | admin.firestore.DocumentReference | admin.firestore.Query; /** * @param db - Firestore instance * @param collectionPath - Path of collection * @param batchSize - Size of delete batch * @returns Promise which resolves with results of deleting batch */ export function deleteCollection(db: any, collectionPath: string, batchSize?: number): Promise<any>; } declare module "tasks" { import * as admin from 'firebase-admin'; import { FixtureData, FirestoreAction, RTDBAction, CallRtdbOptions, CallFirestoreOptions } from "attachCustomCommands"; /** * @param adminInstance - firebase-admin instance * @param action - Action to run * @param actionPath - Path in RTDB * @param options - Query options * @param data - Data to pass to action * @returns Promise which resolves with results of calling RTDB */ export function callRtdb(adminInstance: any, action: RTDBAction, actionPath: string, options?: CallRtdbOptions, data?: FixtureData | string | boolean): Promise<any>; /** * @param adminInstance - firebase-admin instance * @param action - Action to run * @param actionPath - Path to collection or document within Firestore * @param options - Query options * @param data - Data to pass to action * @returns Promise which resolves with results of calling Firestore */ export function callFirestore(adminInstance: admin.app.App, action: FirestoreAction, actionPath: string, options?: CallFirestoreOptions, data?: FixtureData): Promise<any>; /** * Create a custom token * @param adminInstance - Admin SDK instance * @param uid - UID of user for which the custom token will be generated * @param settings - Settings object * @returns Promise which resolves with a custom Firebase Auth token */ export function createCustomToken(adminInstance: any, uid: string, settings?: any): Promise<string>; /** * Get Firebase Auth user based on UID * @param adminInstance - Admin SDK instance * @param uid - UID of user for which the custom token will be generated * @returns Promise which resolves with a custom Firebase Auth token */ export function getAuthUser(adminInstance: any, uid: string): Promise<admin.auth.UserRecord>; } declare module "plugin" { import { AppOptions } from 'firebase-admin'; import { ExtendedCypressConfig } from "extendWithFirebaseConfig"; /** * @param cypressOnFunc - on function from cypress plugins file * @param cypressConfig - Cypress config * @param adminInstance - firebase-admin instance * @param overrideConfig - Override config for firebase instance * @returns Extended Cypress config */ export default function pluginWithTasks(cypressOnFunc: any, cypressConfig: any, adminInstance: any, overrideConfig?: AppOptions): ExtendedCypressConfig; } declare module "index" { import attachCustomCommands from "attachCustomCommands"; import plugin from "plugin"; export { attachCustomCommands, plugin }; }
the_stack
import { equal } from 'assert'; import html from '../src/markup/format/html'; import haml from '../src/markup/format/haml'; import pug from '../src/markup/format/pug'; import slim from '../src/markup/format/slim'; import parse from '../src/markup'; import createConfig, { Options } from '../src/config'; describe('Format', () => { const defaultConfig = createConfig(); const field = createConfig({ options: { 'output.field': (index, placeholder) => placeholder ? `\${${index}:${placeholder}}` : `\${${index}}` } }); function createProfile(options: Partial<Options>) { const config = createConfig({ options }); return config; } describe('HTML', () => { const format = (abbr: string, config = defaultConfig) => html(parse(abbr, config), config); it('basic', () => { equal(format('div>p'), '<div>\n\t<p></p>\n</div>'); equal(format('div>p*3'), '<div>\n\t<p></p>\n\t<p></p>\n\t<p></p>\n</div>'); equal(format('div#a>p.b*2>span'), '<div id="a">\n\t<p class="b"><span></span></p>\n\t<p class="b"><span></span></p>\n</div>'); equal(format('div>div>div'), '<div>\n\t<div>\n\t\t<div></div>\n\t</div>\n</div>'); equal(format('table>tr*2>td{item}*2'), '<table>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n\t<tr>\n\t\t<td>item</td>\n\t\t<td>item</td>\n\t</tr>\n</table>'); }); it('inline elements', () => { const profile = createProfile({ 'output.inlineBreak': 3 }); const breakInline = createProfile({ 'output.inlineBreak': 1 }); const keepInline = createProfile({ 'output.inlineBreak': 0 }); const xhtml = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('div>a>b*3', xhtml), '<div>\n\t<a href="">\n\t\t<b></b>\n\t\t<b></b>\n\t\t<b></b>\n\t</a>\n</div>'); equal(format('p>i', profile), '<p><i></i></p>'); equal(format('p>i*2', profile), '<p><i></i><i></i></p>'); equal(format('p>i*2', breakInline), '<p>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', profile), '<p>\n\t<i></i>\n\t<i></i>\n\t<i></i>\n</p>'); equal(format('p>i*3', keepInline), '<p><i></i><i></i><i></i></p>'); equal(format('i*2', profile), '<i></i><i></i>'); equal(format('i*3', profile), '<i></i>\n<i></i>\n<i></i>'); equal(format('i{a}+i{b}', profile), '<i>a</i><i>b</i>'); equal(format('img[src]/+p', xhtml), '<img src="" alt="" />\n<p></p>'); equal(format('div>img[src]/+p', xhtml), '<div>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n</div>'); equal(format('div>p+img[src]/+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*2+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" /><img src="" alt="" />\n\t<p></p>\n</div>'); equal(format('div>p+img[src]/*3+p', xhtml), '<div>\n\t<p></p>\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<img src="" alt="" />\n\t<p></p>\n</div>'); }); it('generate fields', () => { equal(format('a[href]', field), '<a href="${1}">${2}</a>'); equal(format('a[href]*2', field), '<a href="${1}">${2}</a><a href="${3}">${4}</a>'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}\n${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar\n foo bar'); equal(format('ul>li*2', field), '<ul>\n\t<li>${1}</li>\n\t<li>${2}</li>\n</ul>'); equal(format('div>img[src]/', field), '<div><img src="${1}" alt="${2}"></div>'); }); // it.only('debug', () => { // equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoobar\n\t<p></p>\n</div>'); // }); it('mixed content', () => { equal(format('div{foo}'), '<div>foo</div>'); equal(format('div>{foo}'), '<div>foo</div>'); equal(format('div>{foo}+{bar}'), '<div>\n\tfoo\n\tbar\n</div>'); equal(format('div>{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+{bar}+p+{foo}+{bar}+p'), '<div>\n\tfoo\n\tbar\n\t<p></p>\n\tfoo\n\tbar\n\t<p></p>\n</div>'); equal(format('div>{foo}+p+{bar}'), '<div>\n\tfoo\n\t<p></p>\n\tbar\n</div>'); equal(format('div>{foo}>p'), '<div>\n\tfoo\n\t<p></p>\n</div>'); equal(format('div>{<!-- ${0} -->}'), '<div><!-- --></div>'); equal(format('div>{<!-- ${0} -->}+p'), '<div>\n\t<!-- -->\n\t<p></p>\n</div>'); equal(format('div>p+{<!-- ${0} -->}'), '<div>\n\t<p></p>\n\t<!-- -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p'), '<div>\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p'), '<div>\n\t<!-- <p></p> -->\n\t<!-- <p></p> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}*2>p*2'), '<div>\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n\t<!-- \n\t<p></p>\n\t<p></p>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}>b'), '<div>\n\t<!-- <b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*2'), '<div>\n\t<!-- <b></b><b></b> -->\n</div>'); equal(format('div>{<!-- ${0} -->}>b*3'), '<div>\n\t<!-- \n\t<b></b>\n\t<b></b>\n\t<b></b>\n\t-->\n</div>'); equal(format('div>{<!-- ${0} -->}', field), '<div><!-- ${1} --></div>'); equal(format('div>{<!-- ${0} -->}>b', field), '<div>\n\t<!-- <b>${1}</b> -->\n</div>'); }); it('self-closing', () => { const xmlStyle = createProfile({ 'output.selfClosingStyle': 'xml' }); const htmlStyle = createProfile({ 'output.selfClosingStyle': 'html' }); const xhtmlStyle = createProfile({ 'output.selfClosingStyle': 'xhtml' }); equal(format('img[src]/', htmlStyle), '<img src="" alt="">'); equal(format('img[src]/', xhtmlStyle), '<img src="" alt="" />'); equal(format('img[src]/', xmlStyle), '<img src="" alt=""/>'); equal(format('div>img[src]/', xhtmlStyle), '<div><img src="" alt="" /></div>'); }); it('boolean attributes', () => { const compact = createProfile({ 'output.compactBoolean': true }); const noCompact = createProfile({ 'output.compactBoolean': false }); equal(format('p[b.]', noCompact), '<p b="b"></p>'); equal(format('p[b.]', compact), '<p b></p>'); equal(format('p[contenteditable]', compact), '<p contenteditable></p>'); equal(format('p[contenteditable]', noCompact), '<p contenteditable="contenteditable"></p>'); equal(format('p[contenteditable=foo]', compact), '<p contenteditable="foo"></p>'); }); it('no formatting', () => { const profile = createProfile({ 'output.format': false }); equal(format('div>p', profile), '<div><p></p></div>'); equal(format('div>{foo}+p+{bar}', profile), '<div>foo<p></p>bar</div>'); equal(format('div>{foo}>p', profile), '<div>foo<p></p></div>'); equal(format('div>{<!-- ${0} -->}>p', profile), '<div><!-- <p></p> --></div>'); }); it('format specific nodes', () => { equal(format('{<!DOCTYPE html>}+html>(head>meta[charset=${charset}]/+title{${1:Document}})+body', field), '<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset="UTF-8">\n\t<title>${2:Document}</title>\n</head>\n<body>\n\t${3}\n</body>\n</html>'); }); it('comment', () => { const opt = createConfig({ options: { 'comment.enabled': true } }); equal(format('ul>li.item', opt), '<ul>\n\t<li class="item"></li>\n\t<!-- /.item -->\n</ul>'); equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li>\n\t\t<!-- /#foo.item -->\n\t</ul>\n</div>'); opt.options['comment.after'] = ' { [%ID] }'; equal(format('div>ul>li.item#foo', opt), '<div>\n\t<ul>\n\t\t<li class="item" id="foo"></li> { %foo }\n\t</ul>\n</div>'); }); }); describe('HAML', () => { const format = (abbr: string, config = defaultConfig) => haml(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\t%ul.nav\n\t\t%li.nav-item(title="test") \n\t\t%li.nav-item(title="test") '); // https://github.com/emmetio/emmet/issues/446 equal(format('li>a'), '%li\n\t%a(href="") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1" title="test" data-n2="v2") '); let profile = createProfile({ 'output.compactBoolean': true }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled foo="" title="test")/'); profile = createProfile({ 'output.compactBoolean': false }); equal(format('input[disabled. foo title=test]/', profile), '%input(type="text" disabled=true foo="" title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), '%span Text 1'); equal(format('span{Text 1}>b{Text 2}'), '%span Text 1\n\t%b Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), '%span\n\tText 1 |\n\tText 2 |\n\t%b Text 3'); equal(format('div>span{Text 1\nText 2\nText 123}>b{Text 3}'), '%div\n\t%span\n\t\tText 1 |\n\t\tText 2 |\n\t\tText 123 |\n\t\t%b Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), '%a(href="${1}") ${2}'); equal(format('a[href]*2', field), '%a(href="${1}") ${2}\n%a(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), '%ul\n\t%li ${1}\n\t%li ${2}'); equal(format('div>img[src]/', field), '%div\n\t%img(src="${1}" alt="${2}")/'); }); }); describe('Pug', () => { const format = (abbr: string, config = defaultConfig) => pug(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item(title="test") \n\t\tli.nav-item(title="test") '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar(data-n1="v1", title="test", data-n2="v2") '); equal(format('input[disabled. foo title=test]'), 'input(type="text", disabled, foo="", title="test")'); // Use closing slash for XML output format equal(format('input[disabled. foo title=test]', createProfile({ 'output.selfClosingStyle': 'xml' })), 'input(type="text", disabled, foo="", title="test")/'); }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a(href="${1}") ${2}'); equal(format('a[href]*2', field), 'a(href="${1}") ${2}\na(href="${3}") ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg(src="${1}", alt="${2}")'); }); }); describe('Slim', () => { const format = (abbr: string, config = defaultConfig) => slim(parse(abbr, config), config); it('basic', () => { equal(format('div#header>ul.nav>li[title=test].nav-item*2'), '#header\n\tul.nav\n\t\tli.nav-item title="test" \n\t\tli.nav-item title="test" '); equal(format('div#foo[data-n1=v1 title=test data-n2=v2].bar'), '#foo.bar data-n1="v1" title="test" data-n2="v2" '); // const profile = createProfile({ inlineBreak: 0 }); // equal(format('ul>li>span{Text}', profile), 'ul\n\tli: span Text'); // equal(format('ul>li>span{Text}'), 'ul\n\tli\n\t\tspan Text'); // equal(format('ul>li>span{Text}*2', profile), 'ul\n\tli\n\t\tspan Text\n\t\tspan Text'); }); // it.skip('attribute wrappers', () => { // equal(format('input[disabled. foo title=test]'), 'input disabled=true foo="" title="test"'); // equal(format('input[disabled. foo title=test]', null, { attributeWrap: 'round' }), // 'input(disabled foo="" title="test")'); // }); it('nodes with text', () => { equal(format('{Text 1}'), 'Text 1'); equal(format('span{Text 1}'), 'span Text 1'); equal(format('span{Text 1}>b{Text 2}'), 'span Text 1\n\tb Text 2'); equal(format('span{Text 1\nText 2}>b{Text 3}'), 'span\n\t| Text 1\n\t| Text 2\n\tb Text 3'); equal(format('div>span{Text 1\nText 2}>b{Text 3}'), 'div\n\tspan\n\t\t| Text 1\n\t\t| Text 2\n\t\tb Text 3'); }); it('generate fields', () => { equal(format('a[href]', field), 'a href="${1}" ${2}'); equal(format('a[href]*2', field), 'a href="${1}" ${2}\na href="${3}" ${4}'); equal(format('{${0} ${1:foo} ${2:bar}}*2', field), '${1} ${2:foo} ${3:bar}${4} ${5:foo} ${6:bar}'); equal(format('{${0} ${1:foo} ${2:bar}}*2'), ' foo bar foo bar'); equal(format('ul>li*2', field), 'ul\n\tli ${1}\n\tli ${2}'); equal(format('div>img[src]/', field), 'div\n\timg src="${1}" alt="${2}"/'); }); }); });
the_stack
import { escape, parse, translate, visit, Flavor, Token, TokenType } from '@daiyam/regexp'; import { ExplicitFoldingConfig } from '@zokugun/vscode.explicit-folding-api'; import { basename } from 'path'; import { commands, FoldingRange, FoldingRangeKind, FoldingRangeProvider, OutputChannel, ProviderResult, TextDocument, window } from 'vscode'; interface EndMatch { index: number; regex: string; } type EndMatcher = (escape: (value: string) => string, offset: number, ...args: string[]) => string; type EndMatches = Record<number, EndMatch[]>; enum Marker { BEGIN, MIDDLE, END, DOCSTRING, SEPARATOR, WHILE, } interface GroupContext { index: number; } interface PreviousRegion { begin: number; end: number; indent: number; } interface Position { line: number; offset: number; } interface Rule { index: number; begin?: RegExp; middle?: RegExp; end?: RegExp; loopRegex?: RegExp; while?: RegExp; continuation?: boolean; consumeEnd?: (offset?: number, ...args: string[]) => boolean; foldLastLine: (offset?: number, ...args: string[]) => boolean; foldBOF: boolean; foldEOF: boolean; nested: boolean; kind: FoldingRangeKind; endMatcher?: EndMatcher; parents?: number[]; strict?: boolean; name?: string; autoFold?: boolean; } interface StackItem { rule: Rule; line: number; continuation?: number; endIndex?: number; separator?: boolean; } const Tab = 9; const Space = 32; function computeIndentLevel(line: string, tabSize: number): number { // {{{ let indent = 0; let i = 0; const length = line.length; while(i < length) { const chCode = line.charCodeAt(i); if(chCode === Space) { indent++; } else if(chCode === Tab) { indent = indent - (indent % tabSize) + tabSize; } else { break; } i++; } if(i === length) { return -1; // line only consists of whitespace } return indent; } // }}} function id<T>(value: T): () => T { // {{{ return () => value; } // }}} function shouldFoldLastLine(foldLastLine: boolean[], groupIndex: number, endGroupCount: number): (offset?: number, ...args: string[]) => boolean { // {{{ return (offset, ...args) => { for(let i = groupIndex + 1, l = groupIndex + endGroupCount; i < l; ++i) { if(typeof args[i + offset!] !== 'undefined') { return foldLastLine[i - groupIndex]; } } return foldLastLine[0]; }; } // }}} export class FoldingProvider implements FoldingRangeProvider { public id = 'explicit'; public isManagingLastLine = true; private readonly autoFoldDocuments: TextDocument[]; private readonly debugChannel: OutputChannel | undefined; private readonly mainRegex: RegExp; private offSideIndentation = false; private readonly rules: Rule[] = []; private useIndentation = false; constructor(configuration: ExplicitFoldingConfig[], debugChannel: OutputChannel | undefined, documents: TextDocument[]) { // {{{ this.debugChannel = debugChannel; this.autoFoldDocuments = documents; const groupContext = { index: 0 }; let source = ''; for(const value of configuration) { const src = this.addRegex(value, groupContext, true, []); if(src.length > 0) { if(source.length > 0) { source += '|'; } source += src; } } this.mainRegex = source.length === 0 ? /a^/ : new RegExp(source, 'g'); } // }}} public provideFoldingRanges(document: TextDocument): ProviderResult<FoldingRange[]> { // {{{ if(this.debugChannel) { this.debugChannel.show(true); this.debugChannel.appendLine(`[document] lang: ${document.languageId}, fileName: ${basename(document.fileName)}`); this.debugChannel.appendLine(`[main] regex: ${this.mainRegex.toString()}`); } const foldingRanges: FoldingRange[] = []; const foldLines: number[] = []; const stack: StackItem[] = []; const endMatches = {}; let position: Position = { line: 0, offset: 0 }; try { while(position.line < document.lineCount) { position = this.resolveExplicitRange(document, foldingRanges, 'main', this.mainRegex, stack, endMatches, 0, false, position.line, position.offset, foldLines); } this.doEOF(document, foldingRanges, stack, foldLines); if(this.useIndentation) { this.resolveIndentationRange(document, foldingRanges); } } catch (error: unknown) { if(this.debugChannel && error) { this.debugChannel.appendLine(String(error)); } } if(this.debugChannel) { this.debugChannel.appendLine(`[document] foldings: ${JSON.stringify(foldingRanges)}`); } const index = this.autoFoldDocuments.indexOf(document); if(index !== -1) { this.autoFoldDocuments.splice(index, 1); if(foldLines.length > 0) { void commands.executeCommand('editor.fold', { levels: 1, selectionLines: foldLines, }); } } return foldingRanges; } // }}} private addRegex(configuration: ExplicitFoldingConfig, groupContext: GroupContext, strict: boolean, parents: number[]): string { // {{{ const ruleIndex = this.rules.length; try { const bypassProtection = configuration.bypassProtection ?? false; let begin; if(configuration.beginRegex) { begin = new RegExp(translate(configuration.beginRegex, Flavor.ES2018)); if(configuration.beginRegex === configuration.endRegex) { return this.addDocstringRegex(configuration, ruleIndex, begin, groupContext); } } else if(configuration.begin) { begin = new RegExp(escape(configuration.begin)); if(configuration.begin === configuration.end) { return this.addDocstringRegex(configuration, ruleIndex, begin, groupContext); } } if(begin) { let continuation; let end; let whileRegex; if(configuration.endRegex) { end = new RegExp(translate(configuration.endRegex, Flavor.ES2018)); } else if(configuration.end) { end = new RegExp(escape(configuration.end)); } else if(configuration.continuationRegex) { const src = translate(configuration.continuationRegex, Flavor.ES2018); continuation = new RegExp(`${src}$`); } else if(configuration.continuation) { continuation = new RegExp(`${escape(configuration.continuation)}$`); } else if(configuration.whileRegex) { whileRegex = new RegExp(translate(configuration.whileRegex, Flavor.ES2018)); } else if(configuration.while) { whileRegex = new RegExp(escape(configuration.while)); } if(end) { let middle; if(configuration.middleRegex) { middle = new RegExp(translate(configuration.middleRegex, Flavor.ES2018)); } else if(configuration.middle) { middle = new RegExp(escape(configuration.middle)); } if(this.isSupportedRegex(bypassProtection, begin, middle, end)) { return this.addBeginEndRegex(configuration, ruleIndex, begin, middle, end, groupContext, strict, parents); } } else if(continuation) { if(this.isSupportedRegex(bypassProtection, begin, continuation)) { return this.addContinuationRegex(configuration, ruleIndex, begin, continuation, groupContext); } } else if(whileRegex && this.isSupportedRegex(bypassProtection, begin, whileRegex)) { return this.addBeginWhileRegex(configuration, ruleIndex, begin, whileRegex, groupContext); } } else if(configuration.whileRegex) { const whileRegex = new RegExp(translate(configuration.whileRegex, Flavor.ES2018)); if(this.isSupportedRegex(bypassProtection, whileRegex)) { return this.addWhileRegex(configuration, ruleIndex, whileRegex, groupContext); } } else if(configuration.while) { const whileRegex = new RegExp(escape(configuration.while)); if(this.isSupportedRegex(bypassProtection, whileRegex)) { return this.addWhileRegex(configuration, ruleIndex, whileRegex, groupContext); } } else if(configuration.separatorRegex) { const separator = new RegExp(translate(configuration.separatorRegex, Flavor.ES2018)); if(this.isSupportedRegex(bypassProtection, separator)) { return this.addSeparatorRegex(configuration, ruleIndex, separator, groupContext, strict, parents); } } else if(configuration.separator) { const separator = new RegExp(escape(configuration.separator)); if(this.isSupportedRegex(bypassProtection, separator)) { return this.addSeparatorRegex(configuration, ruleIndex, separator, groupContext, strict, parents); } } else if(configuration.indentation) { this.useIndentation = configuration.indentation; this.offSideIndentation = configuration.offSide ?? false; } } catch (error: unknown) { if(this.debugChannel) { this.debugChannel.appendLine(String(error)); } } return ''; } // }}} private addBeginEndRegex(configuration: ExplicitFoldingConfig, ruleIndex: number, begin: RegExp, middle: RegExp | undefined, end: RegExp, groupContext: GroupContext, strict: boolean, parents: number[]): string { // {{{ const rule: Rule = { index: ruleIndex, begin, middle, end, consumeEnd: typeof configuration.consumeEnd === 'boolean' ? id(configuration.consumeEnd) : id(true), foldLastLine: typeof configuration.foldLastLine === 'boolean' ? id(configuration.foldLastLine) : id(true), foldBOF: false, foldEOF: configuration.foldEOF ?? false, nested: typeof configuration.nested === 'boolean' ? configuration.nested : !Array.isArray(configuration.nested), strict: typeof configuration.strict === 'boolean' ? configuration.strict : (configuration.strict === 'never' ? false : strict), kind: configuration.kind === 'comment' ? FoldingRangeKind.Comment : FoldingRangeKind.Region, autoFold: configuration.autoFold ?? false, }; this.rules.push(rule); let src = `(?<_${Marker.BEGIN}_${ruleIndex}>${rule.begin!.source})`; const groups = this.listCaptureGroups(begin.source); const beginGroupCount = 1 + groups.length; const middleGroupCount = rule.middle ? 1 + this.getCaptureGroupCount(middle!.source) : 0; const endGroupCount = 1 + this.getCaptureGroupCount(end.source); if(groups.length > 0) { let index = groupContext.index + 1; const captures = configuration.endRegex!.split(/\\(\d+)/g); if(captures.length > 0) { const last = captures.length - 1; let src = '""'; for(let i = 0; i <= last; i += 2) { if(i === last) { if(captures[i].length > 0) { src += ` + "${escape(captures[i]).replace(/"/g, '\\"')}"`; } } else { src += ` + "${escape(captures[i]).replace(/"/g, '\\"')}" + escape(args[${++index} + offset])`; } } // eslint-disable-next-line no-eval rule.endMatcher = eval('(function(){return function(escape, offset, ...args) { return ' + src + ';};})()') as EndMatcher; } } groupContext.index += beginGroupCount; if(Array.isArray(configuration.consumeEnd) && configuration.consumeEnd.length === endGroupCount) { const consumeEnd = configuration.consumeEnd; const groupIndex = 1 + (rule.nested ? groupContext.index : 0) + middleGroupCount; rule.consumeEnd = shouldFoldLastLine(consumeEnd, groupIndex, endGroupCount); } if(Array.isArray(configuration.foldLastLine) && configuration.foldLastLine.length === endGroupCount) { const foldLastLine = configuration.foldLastLine; const groupIndex = 1 + (rule.nested ? groupContext.index : 0) + middleGroupCount; rule.foldLastLine = shouldFoldLastLine(foldLastLine, groupIndex, endGroupCount); } if(rule.nested) { if(rule.middle) { src += `|(?<_${Marker.MIDDLE}_${ruleIndex}>${rule.middle.source})`; groupContext.index += middleGroupCount; } if(!rule.endMatcher) { src += `|(?<_${Marker.END}_${ruleIndex}>${rule.end!.source})`; groupContext.index += endGroupCount; } } else { rule.name = configuration.name ?? `loop=${ruleIndex}`; if(Array.isArray(configuration.nested)) { const strictParent = configuration.strict === 'never' ? false : strict; if(!strictParent) { const regexes = configuration.nested.map((config) => this.addRegex(config, groupContext, false, [...parents, ruleIndex])).filter((regex) => regex.length > 0); src += `|${regexes.join('|')}`; } const subgroupContext = { index: 1 }; const regexes = configuration.nested.map((config) => this.addRegex(config, subgroupContext, strictParent, [...parents, ruleIndex])).filter((regex) => regex.length > 0); let loopSource = ''; if(rule.middle) { loopSource += `(?<_${Marker.MIDDLE}_${ruleIndex}>${rule.middle.source})`; } if(!rule.endMatcher) { if(loopSource) { loopSource += '|'; } loopSource += `(?<_${Marker.END}_${ruleIndex}>${rule.end!.source})`; } if(loopSource) { loopSource += '|'; } loopSource += regexes.join('|'); rule.loopRegex = new RegExp(loopSource, 'g'); } else { let loopSource = ''; if(rule.middle) { loopSource += `(?<_${Marker.MIDDLE}_${ruleIndex}>${rule.middle.source})`; } if(!rule.endMatcher) { if(loopSource) { loopSource += '|'; } loopSource += `(?<_${Marker.END}_${ruleIndex}>${rule.end!.source})`; } if(loopSource) { rule.loopRegex = new RegExp(loopSource, 'g'); } } } return src; } // }}} private addBeginWhileRegex(configuration: ExplicitFoldingConfig, ruleIndex: number, begin: RegExp, whileRegex: RegExp, groupContext: GroupContext): string { // {{{ groupContext.index += 1 + this.getCaptureGroupCount(begin.source); const rule = { index: ruleIndex, begin, while: whileRegex, foldLastLine: typeof configuration.foldLastLine === 'boolean' ? id(configuration.foldLastLine) : id(true), foldBOF: false, foldEOF: configuration.foldEOF ?? false, nested: false, kind: configuration.kind === 'comment' ? FoldingRangeKind.Comment : FoldingRangeKind.Region, autoFold: configuration.autoFold ?? false, }; this.rules.push(rule); return `(?<_${Marker.BEGIN}_${ruleIndex}>${rule.begin.source})`; } // }}} private addContinuationRegex(configuration: ExplicitFoldingConfig, ruleIndex: number, begin: RegExp, whileRegex: RegExp, groupContext: GroupContext): string { // {{{ groupContext.index += 1 + this.getCaptureGroupCount(begin.source); const rule = { index: ruleIndex, begin, while: whileRegex, continuation: true, foldLastLine: typeof configuration.foldLastLine === 'boolean' ? id(configuration.foldLastLine) : id(true), foldBOF: false, foldEOF: configuration.foldEOF ?? false, nested: false, kind: configuration.kind === 'comment' ? FoldingRangeKind.Comment : FoldingRangeKind.Region, autoFold: configuration.autoFold ?? false, }; this.rules.push(rule); return `(?<_${Marker.BEGIN}_${ruleIndex}>${rule.begin.source})`; } // }}} private addDocstringRegex(configuration: ExplicitFoldingConfig, ruleIndex: number, begin: RegExp, groupContext: GroupContext): string { // {{{ groupContext.index += 1 + this.getCaptureGroupCount(begin.source); const rule = { index: ruleIndex, begin, foldLastLine: typeof configuration.foldLastLine === 'boolean' ? id(configuration.foldLastLine) : id(true), foldBOF: false, foldEOF: configuration.foldEOF ?? false, nested: typeof configuration.nested === 'boolean' ? configuration.nested : true, kind: configuration.kind === 'comment' ? FoldingRangeKind.Comment : FoldingRangeKind.Region, autoFold: configuration.autoFold ?? false, }; this.rules.push(rule); return `(?<_${Marker.DOCSTRING}_${ruleIndex}>${rule.begin.source})`; } // }}} private addSeparatorRegex(configuration: ExplicitFoldingConfig, ruleIndex: number, separator: RegExp, groupContext: GroupContext, strict: boolean, parents: number[]): string { // {{{ groupContext.index += 1 + this.getCaptureGroupCount(separator.source); const rule = { index: ruleIndex, begin: separator, foldLastLine: id(false), foldBOF: typeof configuration.foldBOF === 'boolean' ? configuration.foldBOF : true, foldEOF: typeof configuration.foldEOF === 'boolean' ? configuration.foldEOF : true, nested: typeof configuration.nested === 'boolean' ? configuration.nested : true, strict: typeof configuration.strict === 'boolean' ? configuration.strict : (configuration.strict === 'never' ? false : strict), kind: configuration.kind === 'comment' ? FoldingRangeKind.Comment : FoldingRangeKind.Region, autoFold: configuration.autoFold ?? false, parents, }; this.rules.push(rule); const nested = configuration.descendants ?? (Array.isArray(configuration.nested) ? configuration.nested : null); if(nested) { const regexes = nested.map((config) => this.addRegex(config, groupContext, configuration.strict === 'never' ? false : strict, [...parents, ruleIndex])).filter((regex) => regex.length > 0); return `(?<_${Marker.SEPARATOR}_${ruleIndex}>${rule.begin.source})|${regexes.join('|')}`; } return `(?<_${Marker.SEPARATOR}_${ruleIndex}>${rule.begin.source})`; } // }}} private addWhileRegex(configuration: ExplicitFoldingConfig, ruleIndex: number, whileRegex: RegExp, groupContext: GroupContext): string { // {{{ groupContext.index += 1 + this.getCaptureGroupCount(whileRegex.source); const rule = { index: ruleIndex, while: whileRegex, foldLastLine: typeof configuration.foldLastLine === 'boolean' ? id(configuration.foldLastLine) : id(true), foldBOF: false, foldEOF: configuration.foldEOF ?? false, nested: false, kind: configuration.kind === 'comment' ? FoldingRangeKind.Comment : FoldingRangeKind.Region, autoFold: configuration.autoFold ?? false, }; this.rules.push(rule); return `(?<_${Marker.WHILE}_${ruleIndex}>${rule.while.source})`; } // }}} private doEOF(document: TextDocument, foldingRanges: FoldingRange[], stack: StackItem[], foldLines: number[]): void { // {{{ const end = document.lineCount; while(stack[0]) { if(stack[0].rule.foldEOF) { const begin = stack[0].line; if(end > begin + 1) { this.pushNewRange(stack[0].rule, begin, end - 1, foldingRanges, foldLines); } } stack.shift(); } } // }}} private doWhile(document: TextDocument, foldingRanges: FoldingRange[], rule: Rule, line: number, continuation: boolean, foldLines: number[]): Position { // {{{ const begin = line; while(++line < document.lineCount) { const text = document.lineAt(line).text; if(!rule.while!.test(text)) { const end = line - (continuation ? 0 : 1); if(rule.foldLastLine()) { if(end > begin) { this.pushNewRange(rule, begin, end, foldingRanges, foldLines); } return { line: end + 1, offset: 0 }; } if(end > begin + 1) { this.pushNewRange(rule, begin, end - 1, foldingRanges, foldLines); } return { line: end, offset: 0 }; } } const end = Math.min(line, document.lineCount - 1); if(rule.foldLastLine()) { if(end > begin) { this.pushNewRange(rule, begin, end, foldingRanges, foldLines); } } else if(end > begin + 1) { this.pushNewRange(rule, begin, end - 1, foldingRanges, foldLines); } return { line, offset: 0 }; } // }}} private * findOfRegexp(regex: RegExp, line: string, offset: number): Generator<{ type: number; index: number; match: RegExpExecArray; nextOffset: number }> { // {{{ // reset regex regex.lastIndex = offset; while(true) { const match = regex.exec(line) as RegExpExecArray | undefined; if(match?.groups) { const index = match.index ?? 0; if(index < offset) { continue; } const nextOffset = index + (match[0].length === 0 ? 1 : match[0].length); for(const key in match.groups) { if(match.groups[key] !== undefined) { const keys = key.split('_').map((x) => Number.parseInt(x, 10)); yield { type: keys[1], index: keys[2], match, nextOffset, }; break; } } regex.lastIndex = nextOffset; } else { break; } } } // }}} private getCaptureGroupCount(regex: string): number { // {{{ const ast = parse(regex); let count = 0; visit(ast.body, { [TokenType.CAPTURE_GROUP]() { ++count; }, }); return count; } // }}} private isSupportedRegex(bypassProtection: boolean, ...regexes: Array<RegExp | undefined>): boolean { // {{{ if(bypassProtection) { return true; } for(const regex of regexes) { if(regex?.test('')) { return false; } } return true; } // }}} private listCaptureGroups(regex: string): Token[] { // {{{ const ast = parse(regex); const groups: Token[] = []; visit(ast.body, { [TokenType.CAPTURE_GROUP](token) { groups.push(token); }, }); return groups; } // }}} private pushNewRange(rule: Rule, begin: number, end: number, foldingRanges: FoldingRange[], foldLines: number[]): void { // {{{ foldingRanges.push(new FoldingRange(begin, end, rule.kind)); if(rule.autoFold) { foldLines.push(begin); } } // }}} private resolveExplicitRange(document: TextDocument, foldingRanges: FoldingRange[], name: string, regexp: RegExp, stack: StackItem[], endMatches: EndMatches, matchOffset: number, secondaryLoop: boolean, line: number, offset: number, foldLines: number[]): Position { // {{{ const text = document.lineAt(line).text; for(const { type, index, match, nextOffset } of this.findOfRegexp(regexp, text, offset)) { const rule = this.rules[index]; if(this.debugChannel) { this.debugChannel.appendLine(`[${name}] line: ${line + 1}, offset: ${offset}, type: ${Marker[type]}, match: ${match[0]}, regex: ${index}`); } switch(type) { case Marker.BEGIN: if(stack.length === 0 || stack[0].rule.nested) { if(!rule.nested && (rule.loopRegex || rule.endMatcher)) { let loopRegex; if(rule.endMatcher) { let src = rule.loopRegex ? rule.loopRegex.source : ''; if(src) { src += '|'; } src += `(?<_${Marker.END}_${index}>${rule.endMatcher(escape, matchOffset, ...match)})`; loopRegex = new RegExp(src, 'g'); } else { loopRegex = rule.loopRegex!; } const name = rule.name!; if(this.debugChannel) { this.debugChannel.appendLine(`[${name}] regex: ${loopRegex.toString()}`); } const stack: StackItem[] = [{ rule, line }]; let position = this.resolveExplicitRange(document, foldingRanges, name, loopRegex, stack, {}, 0, true, line, nextOffset, foldLines); while(stack.length > 0 && position.line < document.lineCount) { position = this.resolveExplicitRange(document, foldingRanges, name, loopRegex, stack, {}, 0, true, position.line, position.offset, foldLines); } if(stack.length > 0 && position.line >= document.lineCount) { this.doEOF(document, foldingRanges, stack, foldLines); } return position; } if(rule.endMatcher) { const endMatch = endMatches[rule.index] ? endMatches[rule.index] : (endMatches[rule.index] = []); const end = rule.endMatcher(escape, matchOffset, ...match); let nf = true; let endIndex = endMatch.length + 1; for(const match of endMatch) { if(end === match.regex) { endIndex = match.index; nf = false; } } let loopRegex; if(nf) { endMatch.push({ regex: end, index: endIndex, }); loopRegex = new RegExp(`(?<_${Marker.END}_${index}_${endIndex}>${end})|${regexp.source}`, 'g'); ++matchOffset; } else { loopRegex = regexp; } const loopStack: StackItem[] = [{ rule, line, endIndex }]; let position = this.resolveExplicitRange(document, foldingRanges, name, loopRegex, loopStack, endMatches, matchOffset, true, line, nextOffset, foldLines); while(loopStack.length > 0 && position.line < document.lineCount) { position = this.resolveExplicitRange(document, foldingRanges, name, loopRegex, loopStack, endMatches, matchOffset, true, position.line, position.offset, foldLines); } if(nf) { const index = endMatch.findIndex(({ index }) => index === endIndex); endMatch.splice(index, 1); } return position; } if(rule.continuation) { if(!rule.while!.test(text)) { return { line: line + 1, offset: 0 }; } return this.doWhile(document, foldingRanges, rule, line, true, foldLines); } if(rule.while) { return this.doWhile(document, foldingRanges, rule, line, false, foldLines); } stack.unshift({ rule, line }); } break; case Marker.MIDDLE: if(stack.length > 0 && stack[0].rule === rule) { const begin = stack[0].line; const end = line; if(end > begin + 1) { this.pushNewRange(rule, begin, end - 1, foldingRanges, foldLines); } stack[0].line = line; } break; case Marker.END: if(secondaryLoop) { const last = stack.length > 0 && stack[stack.length - 1]; if(last && last.rule === rule) { if(last.endIndex && match.groups && !match.groups[`_${Marker.END}_${rule.index}_${last.endIndex}`]) { stack.pop(); return { line, offset }; } const begin = last.line; const end = rule.consumeEnd!() ? line : Math.max(line - 1, begin); while(stack.length > 1) { const begin = stack[0].line; if(end > begin + 1) { this.pushNewRange(stack[0].rule, begin, end - 1, foldingRanges, foldLines); } stack.shift(); } stack.shift(); if(rule.foldLastLine()) { if(end > begin) { this.pushNewRange(rule, begin, end, foldingRanges, foldLines); } } else if(end > begin + 1) { this.pushNewRange(rule, begin, end - 1, foldingRanges, foldLines); } return { line: end, offset: nextOffset }; } } if(stack.length > 0 && stack[0].rule === rule) { const begin = stack[0].line; const end = rule.consumeEnd!() ? line : Math.max(line - 1, begin); if(rule.foldLastLine(matchOffset, ...match)) { if(end > begin) { this.pushNewRange(rule, begin, end, foldingRanges, foldLines); } } else if(end > begin + 1) { this.pushNewRange(rule, begin, end - 1, foldingRanges, foldLines); } stack.shift(); } break; case Marker.DOCSTRING: if(stack.length > 0 && stack[0].rule === rule) { const begin = stack[0].line; const end = line; if(rule.foldLastLine()) { if(end > begin) { this.pushNewRange(rule, begin, end, foldingRanges, foldLines); } } else if(end > begin + 1) { this.pushNewRange(rule, begin, end - 1, foldingRanges, foldLines); } stack.shift(); } else if(stack.length === 0 || stack[0].rule.nested) { stack.unshift({ rule, line }); } break; case Marker.SEPARATOR: if(stack.length === 0) { if(rule.foldBOF) { if(line > 1) { this.pushNewRange(rule, 0, line - 1, foldingRanges, foldLines); } stack.unshift({ rule, line, separator: true }); } else if(!rule.parents || rule.parents.length === 0) { stack.unshift({ rule, line, separator: true }); } } else { while(stack.length > 0 && stack[0].rule.parents && stack[0].rule.parents.includes(index)) { const begin = stack.shift()!.line; const end = line; if(end > begin + 1) { this.pushNewRange(rule, begin, end - 1, foldingRanges, foldLines); } } if(stack.length === 0) { if(!rule.parents || rule.parents.length === 0) { stack.unshift({ rule, line, separator: true }); } } else if(stack[0].rule === rule) { const begin = stack[0].line; const end = line; if(end > begin + 1) { this.pushNewRange(rule, begin, end - 1, foldingRanges, foldLines); } stack[0].line = line; } else if(stack[0].rule.nested || (secondaryLoop && stack.length === 1)) { if(!rule.parents || rule.parents.length === 0) { stack.unshift({ rule, line, separator: true }); } else { const parent = rule.parents[rule.parents.length - 1]; if(this.rules[parent].strict) { if(stack.some(({ rule: { index } }) => parent === index)) { stack.unshift({ rule, line, separator: true }); } } else if(stack.some(({ rule: { index } }) => rule.parents!.includes(index))) { stack.unshift({ rule, line, separator: true }); } } } } break; case Marker.WHILE: return this.doWhile(document, foldingRanges, rule, line, false, foldLines); } } return { line: line + 1, offset: 0 }; } // }}} private resolveIndentationRange(document: TextDocument, foldingRanges: FoldingRange[]): void { // {{{ const tabSize = window.activeTextEditor ? Number.parseInt(`${window.activeTextEditor.options.tabSize ?? 4}`, 10) : 4; const existingRanges: Record<string, boolean> = {}; for(const range of foldingRanges) { existingRanges[range.start] = true; } const previousRegions: PreviousRegion[] = [{ indent: -1, begin: document.lineCount, end: document.lineCount }]; for(let line = document.lineCount - 1; line >= 0; line--) { const lineContent = document.lineAt(line).text; const indent = computeIndentLevel(lineContent, tabSize); let previous = previousRegions[previousRegions.length - 1]; if(indent === -1) { if(this.offSideIndentation) { // for offSide languages, empty lines are associated to the previous block // note: the next block is already written to the results, so this only // impacts the end position of the block before previous.end = line; } continue; // only whitespace } if(previous.indent > indent) { // discard all regions with larger indent do { previousRegions.pop(); previous = previousRegions[previousRegions.length - 1]; } while(previous.indent > indent); // new folding range const endLineNumber = previous.end - 1; if(endLineNumber - line >= 1 // needs at east size 1 && !existingRanges[line]) { foldingRanges.push(new FoldingRange(line, endLineNumber, FoldingRangeKind.Region)); } } if(previous.indent === indent) { previous.end = line; } else { // previous.indent < indent // new region with a bigger indent previousRegions.push({ indent, begin: line, end: line }); } } } // }}} }
the_stack
import { ToError, ServiceClient } from './AzureServiceClient'; import { AzureEndpoint } from './azureModels'; import msRestAzure = require('./azure-arm-common'); import azureServiceClient = require('./AzureServiceClient'); import webClient = require('./webClient'); import tl = require('azure-pipelines-task-lib/task'); import Q = require('q'); export class ResourceManagementClient extends azureServiceClient.ServiceClient { public deployments: Deployments; public resourceGroups: ResourceGroups; constructor(credentials: msRestAzure.ApplicationTokenCredentials, subscriptionId: string, options?: any) { super(credentials, subscriptionId); this.apiVersion = (credentials.isAzureStackEnvironment) ? '2016-06-01' : '2017-05-10'; this.acceptLanguage = 'en-US'; this.generateClientRequestId = true; if (!!options && !!options.longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout; } this.resourceGroups = new ResourceGroups(this); this.deployments = new Deployments(this); } } export class Resources { private _client: ServiceClient; constructor(endpoint: AzureEndpoint) { this._client = new ServiceClient(endpoint.applicationTokenCredentials, endpoint.subscriptionID, 30); } public async getResources(resourceType: string, resourceName: string) { var httpRequest = new webClient.WebRequest(); httpRequest.method = 'GET'; httpRequest.uri = this._client.getRequestUri('//subscriptions/{subscriptionId}/resources', {}, [`$filter=resourceType EQ \'${encodeURIComponent(resourceType)}\' AND name EQ \'${encodeURIComponent(resourceName)}\'`], '2016-07-01'); var result = []; try { var response = await this._client.beginRequest(httpRequest); if (response.statusCode != 200) { throw ToError(response); } result = result.concat(response.body.value); if (response.body.nextLink) { var nextResult = await this._client.accumulateResultFromPagedResult(response.body.nextLink); if (nextResult.error) { throw Error(nextResult.error); } result = result.concat(nextResult.result); } return result; } catch (error) { throw Error(tl.loc('FailedToGetResourceID', resourceType, resourceName, this._client.getFormattedError(error))) } } } export class ResourceGroups { private client: ResourceManagementClient; constructor(armClient: ResourceManagementClient) { this.client = armClient; } public checkExistence(resourceGroupName: string, callback: azureServiceClient.ApiCallback): void { if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); } catch (error) { return callback(error); } // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'HEAD'; httpRequest.uri = this.client.getRequestUri( '//subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}', { '{resourceGroupName}': resourceGroupName } ); // Send Request and process response. this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { return new Promise<azureServiceClient.ApiResult>((resolve, reject) => { if (response.statusCode == 204 || response.statusCode == 404) { resolve(new azureServiceClient.ApiResult(null, response.statusCode == 204)); } else { resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } }); }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public deleteMethod(resourceGroupName: string, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); } catch (error) { return callback(error); } // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'DELETE'; httpRequest.uri = this.client.getRequestUri( '//subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}', { '{resourceGroupName}': resourceGroupName } ); this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { return new Promise<azureServiceClient.ApiResult>((resolve, reject) => { var statusCode = response.statusCode; if (statusCode !== 202 && statusCode !== 200) { resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { // Create Result this.client.getLongRunningOperationResult(response).then((response: webClient.WebResponse) => { if (response.statusCode == 200) { resolve(new azureServiceClient.ApiResult(null, response.body)); } else { resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } }, (error) => reject(error)); } }); }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public createOrUpdate(resourceGroupName: string, parameters, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (parameters === null || parameters === undefined) { throw new Error(tl.loc("ParametersCannotBeNull")); } } catch (error) { return callback(error); } // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'PUT'; httpRequest.headers = {}; httpRequest.uri = this.client.getRequestUri( '//subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}', { '{resourceGroupName}': resourceGroupName, } ); // Serialize Request if (parameters !== null && parameters !== undefined) { httpRequest.body = JSON.stringify(parameters); } // Send Request this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { return new Promise<azureServiceClient.ApiResult>((resolve, reject) => { var statusCode = response.statusCode; if (statusCode !== 200 && statusCode !== 201) { resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { resolve(new azureServiceClient.ApiResult(null, response.body)); } }); }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } } export class Deployments { private client: ResourceManagementClient; constructor(client: ResourceManagementClient) { this.client = client; } public createOrUpdate(resourceGroupName, deploymentName, parameters, callback) { if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (deploymentName === null || deploymentName === undefined || typeof deploymentName.valueOf() !== 'string') { throw new Error(tl.loc("DeploymentNameCannotBeNull")); } if (parameters === null || parameters === undefined) { throw new Error(tl.loc("ParametersCannotBeNull")); } } catch (error) { return callback(error); } // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'PUT'; httpRequest.headers = {}; httpRequest.uri = this.client.getRequestUri( '//subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}', { '{resourceGroupName}': resourceGroupName, '{deploymentName}': deploymentName } ); // Serialize Request if (parameters !== null && parameters !== undefined) { httpRequest.body = JSON.stringify(parameters); } // Send Request this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { return new Promise<azureServiceClient.ApiResult>((resolve, reject) => { var statusCode = response.statusCode; if (statusCode !== 200 && statusCode !== 201) { resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { this.client.getLongRunningOperationResult(response) .then((operationResponse) => { this.get(resourceGroupName, deploymentName, (error, response) => { if (error) { resolve(new azureServiceClient.ApiResult(error)); } else { if (!response.properties) { reject(new Error(tl.loc("ResponseNotValid"))); } else if (response.properties.provisioningState === "Succeeded") { resolve(new azureServiceClient.ApiResult(null, response)); } else { resolve(new azureServiceClient.ApiResult(response.properties.error)); } } }); }).catch((error) => reject(error)); } }); }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public get(resourceGroupName, deploymentName, callback) { // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'GET'; httpRequest.uri = this.client.getRequestUri( '//subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}', { '{resourceGroupName}': resourceGroupName, '{deploymentName}': deploymentName } ); // Send Request and process response. this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { return new Promise<azureServiceClient.ApiResult>((resolve, reject) => { if (response.statusCode != 200) { resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { resolve(new azureServiceClient.ApiResult(null, response.body)); } }); }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public validate(resourceGroupName, deploymentName, parameters, callback) { if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (deploymentName === null || deploymentName === undefined || typeof deploymentName.valueOf() !== 'string') { throw new Error(tl.loc("DeploymentNameCannotBeNull")); } if (parameters === null || parameters === undefined) { throw new Error(tl.loc("ParametersCannotBeNull")); } } catch (error) { return callback(error); } // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'POST'; httpRequest.headers = {}; httpRequest.uri = this.client.getRequestUri( '//subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Resources/deployments/{deploymentName}/validate', { '{resourceGroupName}': resourceGroupName, '{deploymentName}': deploymentName } ); // Serialize Request if (parameters !== null && parameters !== undefined) { httpRequest.body = JSON.stringify(parameters); } // Send Request this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { return new Promise<azureServiceClient.ApiResult>((resolve, reject) => { var statusCode = response.statusCode; if (statusCode !== 200 && statusCode !== 400) { resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { resolve(new azureServiceClient.ApiResult(null, response.body)); } }); }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } }
the_stack
import {Generator, processNavigationUrls} from '../src/generator'; import {AssetGroup} from '../src/in'; import {MockFilesystem} from '../testing/mock'; describe('Generator', () => { beforeEach(() => spyOn(Date, 'now').and.returnValue(1234567890123)); it('generates a correct config', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', '/main.css': 'This is a CSS file', '/main.js': 'This is a JS file', '/main.ts': 'This is a TS file', '/test.txt': 'Another test', '/foo/test.html': 'Another test', '/ignored/x.html': 'should be ignored', }); const gen = new Generator(fs, '/test'); const config = await gen.process({ appData: { test: true, }, index: '/index.html', assetGroups: [{ name: 'test', resources: { files: [ '/**/*.html', '/**/*.?s', '!/ignored/**', '/**/*.txt', ], urls: [ '/absolute/**', '/some/url?with+escaped+chars', 'relative/*.txt', ], }, }], dataGroups: [{ name: 'other', urls: [ '/api/**', 'relapi/**', 'https://example.com/**/*?with+escaped+chars', ], cacheConfig: { maxSize: 100, maxAge: '3d', timeout: '1m', }, }], navigationUrls: [ '/included/absolute/**', '!/excluded/absolute/**', '/included/some/url/with+escaped+chars', '!excluded/relative/*.txt', '!/api/?*', 'http://example.com/included', '!http://example.com/excluded', ], }); expect(config).toEqual({ configVersion: 1, timestamp: 1234567890123, appData: { test: true, }, index: '/test/index.html', assetGroups: [{ name: 'test', installMode: 'prefetch', updateMode: 'prefetch', urls: [ '/test/foo/test.html', '/test/index.html', '/test/main.js', '/test/main.ts', '/test/test.txt', ], patterns: [ '\\/absolute\\/.*', '\\/some\\/url\\?with\\+escaped\\+chars', '\\/test\\/relative\\/[^/]*\\.txt', ], cacheQueryOptions: {ignoreVary: true} }], dataGroups: [{ name: 'other', patterns: [ '\\/api\\/.*', '\\/test\\/relapi\\/.*', 'https:\\/\\/example\\.com\\/(?:.+\\/)?[^/]*\\?with\\+escaped\\+chars', ], strategy: 'performance', maxSize: 100, maxAge: 259200000, timeoutMs: 60000, version: 1, cacheQueryOptions: {ignoreVary: true} }], navigationUrls: [ {positive: true, regex: '^\\/included\\/absolute\\/.*$'}, {positive: false, regex: '^\\/excluded\\/absolute\\/.*$'}, {positive: true, regex: '^\\/included\\/some\\/url\\/with\\+escaped\\+chars$'}, {positive: false, regex: '^\\/test\\/excluded\\/relative\\/[^/]*\\.txt$'}, {positive: false, regex: '^\\/api\\/[^/][^/]*$'}, {positive: true, regex: '^http:\\/\\/example\\.com\\/included$'}, {positive: false, regex: '^http:\\/\\/example\\.com\\/excluded$'}, ], navigationRequestStrategy: 'performance', hashTable: { '/test/foo/test.html': '18f6f8eb7b1c23d2bb61bff028b83d867a9e4643', '/test/index.html': 'a54d88e06612d820bc3be72877c74f257b561b19', '/test/main.js': '41347a66676cdc0516934c76d9d13010df420f2c', '/test/main.ts': '7d333e31f0bfc4f8152732bb211a93629484c035', '/test/test.txt': '18f6f8eb7b1c23d2bb61bff028b83d867a9e4643', }, }); }); it('assigns files to the first matching asset-group (unaffected by file-system access delays)', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', '/foo/script-1.js': 'This is script 1', '/foo/script-2.js': 'This is script 2', '/bar/script-3.js': 'This is script 3', '/bar/script-4.js': 'This is script 4', '/qux/script-5.js': 'This is script 5', }); // Simulate fluctuating file-system access delays. const allFiles = await fs.list('/'); spyOn(fs, 'list') .and.returnValues( new Promise(resolve => setTimeout(resolve, 2000, allFiles.slice())), new Promise(resolve => setTimeout(resolve, 3000, allFiles.slice())), new Promise(resolve => setTimeout(resolve, 1000, allFiles.slice())), ); const gen = new Generator(fs, ''); const config = await gen.process({ index: '/index.html', assetGroups: [ { name: 'group-foo', resources: {files: ['/foo/**/*.js']}, }, { name: 'group-bar', resources: {files: ['/bar/**/*.js']}, }, { name: 'group-fallback', resources: {files: ['/**/*.js']}, }, ], }); expect(config).toEqual({ configVersion: 1, timestamp: 1234567890123, appData: undefined, index: '/index.html', assetGroups: [ { name: 'group-foo', installMode: 'prefetch', updateMode: 'prefetch', cacheQueryOptions: {ignoreVary: true}, urls: [ '/foo/script-1.js', '/foo/script-2.js', ], patterns: [], }, { name: 'group-bar', installMode: 'prefetch', updateMode: 'prefetch', cacheQueryOptions: {ignoreVary: true}, urls: [ '/bar/script-3.js', '/bar/script-4.js', ], patterns: [], }, { name: 'group-fallback', installMode: 'prefetch', updateMode: 'prefetch', cacheQueryOptions: {ignoreVary: true}, urls: [ '/qux/script-5.js', ], patterns: [], }, ], dataGroups: [], hashTable: { '/bar/script-3.js': 'bc0a9b488b5707757c491ddac66f56304310b6b1', '/bar/script-4.js': 'b7782e97a285f1f6e62feca842384babaa209040', '/foo/script-1.js': '3cf257d7ef7e991898f8506fd408cab4f0c2de91', '/foo/script-2.js': '9de2ba54065bb9d610bce51beec62e35bea870a7', '/qux/script-5.js': '3dceafdc0a1b429718e45fbf8e3005dd767892de' }, navigationUrls: [ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ], navigationRequestStrategy: 'performance', }); }); it('uses default `navigationUrls` if not provided', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', }); const gen = new Generator(fs, '/test'); const config = await gen.process({ index: '/index.html', }); expect(config).toEqual({ configVersion: 1, timestamp: 1234567890123, appData: undefined, index: '/test/index.html', assetGroups: [], dataGroups: [], navigationUrls: [ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ], navigationRequestStrategy: 'performance', hashTable: {}, }); }); it('throws if the obsolete `versionedFiles` is used', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', '/main.js': 'This is a JS file', }); const gen = new Generator(fs, '/test'); try { await gen.process({ index: '/index.html', assetGroups: [{ name: 'test', resources: { files: [ '/*.html', ], versionedFiles: [ '/*.js', ], } as AssetGroup['resources'] & {versionedFiles: string[]}, }], }); throw new Error('Processing should have failed due to \'versionedFiles\'.'); } catch (err) { expect(err).toEqual(new Error( 'Asset-group \'test\' in \'ngsw-config.json\' uses the \'versionedFiles\' option, ' + 'which is no longer supported. Use \'files\' instead.')); } }); it('generates a correct config with cacheQueryOptions', async () => { const fs = new MockFilesystem({ '/index.html': 'This is a test', '/main.js': 'This is a JS file', }); const gen = new Generator(fs, '/'); const config = await gen.process({ index: '/index.html', assetGroups: [{ name: 'test', resources: { files: [ '/**/*.html', '/**/*.?s', ] }, cacheQueryOptions: {ignoreSearch: true}, }], dataGroups: [{ name: 'other', urls: ['/api/**'], cacheConfig: { maxAge: '3d', maxSize: 100, strategy: 'performance', timeout: '1m', }, cacheQueryOptions: {ignoreSearch: false}, }] }); expect(config).toEqual({ configVersion: 1, appData: undefined, timestamp: 1234567890123, index: '/index.html', assetGroups: [{ name: 'test', installMode: 'prefetch', updateMode: 'prefetch', urls: [ '/index.html', '/main.js', ], patterns: [], cacheQueryOptions: {ignoreSearch: true, ignoreVary: true} }], dataGroups: [{ name: 'other', patterns: [ '\\/api\\/.*', ], strategy: 'performance', maxSize: 100, maxAge: 259200000, timeoutMs: 60000, version: 1, cacheQueryOptions: {ignoreSearch: false, ignoreVary: true} }], navigationUrls: [ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ], navigationRequestStrategy: 'performance', hashTable: { '/index.html': 'a54d88e06612d820bc3be72877c74f257b561b19', '/main.js': '41347a66676cdc0516934c76d9d13010df420f2c', }, }); }); describe('processNavigationUrls()', () => { const customNavigationUrls = [ 'https://host/positive/external/**', '!https://host/negative/external/**', '/positive/absolute/**', '!/negative/absolute/**', 'positive/relative/**', '!negative/relative/**', ]; it('uses the default `navigationUrls` if not provided', () => { expect(processNavigationUrls('/')).toEqual([ {positive: true, regex: '^\\/.*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*\\.[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*$'}, {positive: false, regex: '^\\/(?:.+\\/)?[^/]*__[^/]*\\/.*$'}, ]); }); it('prepends `baseHref` to relative URL patterns only', () => { expect(processNavigationUrls('/base/href/', customNavigationUrls)).toEqual([ {positive: true, regex: '^https:\\/\\/host\\/positive\\/external\\/.*$'}, {positive: false, regex: '^https:\\/\\/host\\/negative\\/external\\/.*$'}, {positive: true, regex: '^\\/positive\\/absolute\\/.*$'}, {positive: false, regex: '^\\/negative\\/absolute\\/.*$'}, {positive: true, regex: '^\\/base\\/href\\/positive\\/relative\\/.*$'}, {positive: false, regex: '^\\/base\\/href\\/negative\\/relative\\/.*$'}, ]); }); it('strips a leading single `.` from a relative `baseHref`', () => { expect(processNavigationUrls('./relative/base/href/', customNavigationUrls)).toEqual([ {positive: true, regex: '^https:\\/\\/host\\/positive\\/external\\/.*$'}, {positive: false, regex: '^https:\\/\\/host\\/negative\\/external\\/.*$'}, {positive: true, regex: '^\\/positive\\/absolute\\/.*$'}, {positive: false, regex: '^\\/negative\\/absolute\\/.*$'}, {positive: true, regex: '^\\/relative\\/base\\/href\\/positive\\/relative\\/.*$'}, {positive: false, regex: '^\\/relative\\/base\\/href\\/negative\\/relative\\/.*$'}, ]); // We can't correctly handle double dots in `baseHref`, so leave them as literal matches. expect(processNavigationUrls('../double/dots/', customNavigationUrls)).toEqual([ {positive: true, regex: '^https:\\/\\/host\\/positive\\/external\\/.*$'}, {positive: false, regex: '^https:\\/\\/host\\/negative\\/external\\/.*$'}, {positive: true, regex: '^\\/positive\\/absolute\\/.*$'}, {positive: false, regex: '^\\/negative\\/absolute\\/.*$'}, {positive: true, regex: '^\\.\\.\\/double\\/dots\\/positive\\/relative\\/.*$'}, {positive: false, regex: '^\\.\\.\\/double\\/dots\\/negative\\/relative\\/.*$'}, ]); }); }); });
the_stack
import * as cdk from '@aws-cdk/core'; import { Group } from './group'; import { AccountPrincipal, AccountRootPrincipal, AnyPrincipal, ArnPrincipal, CanonicalUserPrincipal, FederatedPrincipal, IPrincipal, PrincipalBase, PrincipalPolicyFragment, ServicePrincipal, ServicePrincipalOpts, } from './principals'; import { LITERAL_STRING_KEY, mergePrincipal } from './util'; const ensureArrayOrUndefined = (field: any) => { if (field === undefined) { return undefined; } if (typeof (field) !== 'string' && !Array.isArray(field)) { throw new Error('Fields must be either a string or an array of strings'); } if (Array.isArray(field) && !!field.find((f: any) => typeof (f) !== 'string')) { throw new Error('Fields must be either a string or an array of strings'); } return Array.isArray(field) ? field : [field]; }; /** * Represents a statement in an IAM policy document. */ export class PolicyStatement { /** * Creates a new PolicyStatement based on the object provided. * This will accept an object created from the `.toJSON()` call * @param obj the PolicyStatement in object form. */ public static fromJson(obj: any) { const ret = new PolicyStatement({ sid: obj.Sid, actions: ensureArrayOrUndefined(obj.Action), resources: ensureArrayOrUndefined(obj.Resource), conditions: obj.Condition, effect: obj.Effect, notActions: ensureArrayOrUndefined(obj.NotAction), notResources: ensureArrayOrUndefined(obj.NotResource), principals: obj.Principal ? [new JsonPrincipal(obj.Principal)] : undefined, notPrincipals: obj.NotPrincipal ? [new JsonPrincipal(obj.NotPrincipal)] : undefined, }); // validate that the PolicyStatement has the correct shape const errors = ret.validateForAnyPolicy(); if (errors.length > 0) { throw new Error('Incorrect Policy Statement: ' + errors.join('\n')); } return ret; } /** * Statement ID for this statement */ public sid?: string; /** * Whether to allow or deny the actions in this statement */ public effect: Effect; private readonly action = new Array<any>(); private readonly notAction = new Array<any>(); private readonly principal: { [key: string]: any[] } = {}; private readonly notPrincipal: { [key: string]: any[] } = {}; private readonly resource = new Array<any>(); private readonly notResource = new Array<any>(); private readonly condition: { [key: string]: any } = { }; private principalConditionsJson?: string; constructor(props: PolicyStatementProps = {}) { // Validate actions for (const action of [...props.actions || [], ...props.notActions || []]) { if (!/^(\*|[a-zA-Z0-9-]+:[a-zA-Z0-9*]+)$/.test(action) && !cdk.Token.isUnresolved(action)) { throw new Error(`Action '${action}' is invalid. An action string consists of a service namespace, a colon, and the name of an action. Action names can include wildcards.`); } } this.sid = props.sid; this.effect = props.effect || Effect.ALLOW; this.addActions(...props.actions || []); this.addNotActions(...props.notActions || []); this.addPrincipals(...props.principals || []); this.addNotPrincipals(...props.notPrincipals || []); this.addResources(...props.resources || []); this.addNotResources(...props.notResources || []); if (props.conditions !== undefined) { this.addConditions(props.conditions); } } // // Actions // /** * Specify allowed actions into the "Action" section of the policy statement. * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html * * @param actions actions that will be allowed. */ public addActions(...actions: string[]) { if (actions.length > 0 && this.notAction.length > 0) { throw new Error('Cannot add \'Actions\' to policy statement if \'NotActions\' have been added'); } this.action.push(...actions); } /** * Explicitly allow all actions except the specified list of actions into the "NotAction" section * of the policy document. * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html * * @param notActions actions that will be denied. All other actions will be permitted. */ public addNotActions(...notActions: string[]) { if (notActions.length > 0 && this.action.length > 0) { throw new Error('Cannot add \'NotActions\' to policy statement if \'Actions\' have been added'); } this.notAction.push(...notActions); } // // Principal // /** * Indicates if this permission has a "Principal" section. */ public get hasPrincipal() { return Object.keys(this.principal).length > 0 || Object.keys(this.notPrincipal).length > 0; } /** * Adds principals to the "Principal" section of a policy statement. * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html * * @param principals IAM principals that will be added */ public addPrincipals(...principals: IPrincipal[]) { if (Object.keys(principals).length > 0 && Object.keys(this.notPrincipal).length > 0) { throw new Error('Cannot add \'Principals\' to policy statement if \'NotPrincipals\' have been added'); } for (const principal of principals) { this.validatePolicyPrincipal(principal); const fragment = principal.policyFragment; mergePrincipal(this.principal, fragment.principalJson); this.addPrincipalConditions(fragment.conditions); } } /** * Specify principals that is not allowed or denied access to the "NotPrincipal" section of * a policy statement. * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notprincipal.html * * @param notPrincipals IAM principals that will be denied access */ public addNotPrincipals(...notPrincipals: IPrincipal[]) { if (Object.keys(notPrincipals).length > 0 && Object.keys(this.principal).length > 0) { throw new Error('Cannot add \'NotPrincipals\' to policy statement if \'Principals\' have been added'); } for (const notPrincipal of notPrincipals) { this.validatePolicyPrincipal(notPrincipal); const fragment = notPrincipal.policyFragment; mergePrincipal(this.notPrincipal, fragment.principalJson); this.addPrincipalConditions(fragment.conditions); } } private validatePolicyPrincipal(principal: IPrincipal) { if (principal instanceof Group) { throw new Error('Cannot use an IAM Group as the \'Principal\' or \'NotPrincipal\' in an IAM Policy'); } } /** * Specify AWS account ID as the principal entity to the "Principal" section of a policy statement. */ public addAwsAccountPrincipal(accountId: string) { this.addPrincipals(new AccountPrincipal(accountId)); } /** * Specify a principal using the ARN identifier of the principal. * You cannot specify IAM groups and instance profiles as principals. * * @param arn ARN identifier of AWS account, IAM user, or IAM role (i.e. arn:aws:iam::123456789012:user/user-name) */ public addArnPrincipal(arn: string) { this.addPrincipals(new ArnPrincipal(arn)); } /** * Adds a service principal to this policy statement. * * @param service the service name for which a service principal is requested (e.g: `s3.amazonaws.com`). * @param opts options for adding the service principal (such as specifying a principal in a different region) */ public addServicePrincipal(service: string, opts?: ServicePrincipalOpts) { this.addPrincipals(new ServicePrincipal(service, opts)); } /** * Adds a federated identity provider such as Amazon Cognito to this policy statement. * * @param federated federated identity provider (i.e. 'cognito-identity.amazonaws.com') * @param conditions The conditions under which the policy is in effect. * See [the IAM documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html). */ public addFederatedPrincipal(federated: any, conditions: Conditions) { this.addPrincipals(new FederatedPrincipal(federated, conditions)); } /** * Adds an AWS account root user principal to this policy statement */ public addAccountRootPrincipal() { this.addPrincipals(new AccountRootPrincipal()); } /** * Adds a canonical user ID principal to this policy document * * @param canonicalUserId unique identifier assigned by AWS for every account */ public addCanonicalUserPrincipal(canonicalUserId: string) { this.addPrincipals(new CanonicalUserPrincipal(canonicalUserId)); } /** * Adds all identities in all accounts ("*") to this policy statement */ public addAnyPrincipal() { this.addPrincipals(new AnyPrincipal()); } // // Resources // /** * Specify resources that this policy statement applies into the "Resource" section of * this policy statement. * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html * * @param arns Amazon Resource Names (ARNs) of the resources that this policy statement applies to */ public addResources(...arns: string[]) { if (arns.length > 0 && this.notResource.length > 0) { throw new Error('Cannot add \'Resources\' to policy statement if \'NotResources\' have been added'); } this.resource.push(...arns); } /** * Specify resources that this policy statement will not apply to in the "NotResource" section * of this policy statement. All resources except the specified list will be matched. * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notresource.html * * @param arns Amazon Resource Names (ARNs) of the resources that this policy statement does not apply to */ public addNotResources(...arns: string[]) { if (arns.length > 0 && this.resource.length > 0) { throw new Error('Cannot add \'NotResources\' to policy statement if \'Resources\' have been added'); } this.notResource.push(...arns); } /** * Adds a ``"*"`` resource to this statement. */ public addAllResources() { this.addResources('*'); } /** * Indicates if this permission has at least one resource associated with it. */ public get hasResource() { return this.resource && this.resource.length > 0; } // // Condition // /** * Add a condition to the Policy */ public addCondition(key: string, value: Condition) { const existingValue = this.condition[key]; this.condition[key] = existingValue ? { ...existingValue, ...value } : value; } /** * Add multiple conditions to the Policy */ public addConditions(conditions: Conditions) { Object.keys(conditions).map(key => { this.addCondition(key, conditions[key]); }); } /** * Add a condition that limits to a given account */ public addAccountCondition(accountId: string) { this.addCondition('StringEquals', { 'sts:ExternalId': accountId }); } /** * JSON-ify the policy statement * * Used when JSON.stringify() is called */ public toStatementJson(): any { return noUndef({ Action: _norm(this.action, { unique: true }), NotAction: _norm(this.notAction, { unique: true }), Condition: _norm(this.condition), Effect: _norm(this.effect), Principal: _normPrincipal(this.principal), NotPrincipal: _normPrincipal(this.notPrincipal), Resource: _norm(this.resource, { unique: true }), NotResource: _norm(this.notResource, { unique: true }), Sid: _norm(this.sid), }); function _norm(values: any, { unique }: { unique: boolean } = { unique: false }) { if (typeof(values) === 'undefined') { return undefined; } if (cdk.Token.isUnresolved(values)) { return values; } if (Array.isArray(values)) { if (!values || values.length === 0) { return undefined; } if (values.length === 1) { return values[0]; } return unique ? [...new Set(values)] : values; } if (typeof(values) === 'object') { if (Object.keys(values).length === 0) { return undefined; } } return values; } function _normPrincipal(principal: { [key: string]: any[] }) { const keys = Object.keys(principal); if (keys.length === 0) { return undefined; } if (LITERAL_STRING_KEY in principal) { return principal[LITERAL_STRING_KEY][0]; } const result: any = {}; for (const key of keys) { const normVal = _norm(principal[key]); if (normVal) { result[key] = normVal; } } return result; } } /** * String representation of this policy statement */ public toString() { return cdk.Token.asString(this, { displayHint: 'PolicyStatement', }); } /** * JSON-ify the statement * * Used when JSON.stringify() is called */ public toJSON() { return this.toStatementJson(); } /** * Add a principal's conditions * * For convenience, principals have been modeled as both a principal * and a set of conditions. This makes it possible to have a single * object represent e.g. an "SNS Topic" (SNS service principal + aws:SourcArn * condition) or an Organization member (* + aws:OrgId condition). * * However, when using multiple principals in the same policy statement, * they must all have the same conditions or the OR samentics * implied by a list of principals cannot be guaranteed (user needs to * add multiple statements in that case). */ private addPrincipalConditions(conditions: Conditions) { // Stringifying the conditions is an easy way to do deep equality const theseConditions = JSON.stringify(conditions); if (this.principalConditionsJson === undefined) { // First principal, anything goes this.principalConditionsJson = theseConditions; } else { if (this.principalConditionsJson !== theseConditions) { throw new Error(`All principals in a PolicyStatement must have the same Conditions (got '${this.principalConditionsJson}' and '${theseConditions}'). Use multiple statements instead.`); } } this.addConditions(conditions); } /** * Validate that the policy statement satisfies base requirements for a policy. */ public validateForAnyPolicy(): string[] { const errors = new Array<string>(); if (this.action.length === 0 && this.notAction.length === 0) { errors.push('A PolicyStatement must specify at least one \'action\' or \'notAction\'.'); } return errors; } /** * Validate that the policy statement satisfies all requirements for a resource-based policy. */ public validateForResourcePolicy(): string[] { const errors = this.validateForAnyPolicy(); if (Object.keys(this.principal).length === 0 && Object.keys(this.notPrincipal).length === 0) { errors.push('A PolicyStatement used in a resource-based policy must specify at least one IAM principal.'); } return errors; } /** * Validate that the policy statement satisfies all requirements for an identity-based policy. */ public validateForIdentityPolicy(): string[] { const errors = this.validateForAnyPolicy(); if (Object.keys(this.principal).length > 0 || Object.keys(this.notPrincipal).length > 0) { errors.push('A PolicyStatement used in an identity-based policy cannot specify any IAM principals.'); } if (Object.keys(this.resource).length === 0 && Object.keys(this.notResource).length === 0) { errors.push('A PolicyStatement used in an identity-based policy must specify at least one resource.'); } return errors; } } /** * The Effect element of an IAM policy * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_effect.html */ export enum Effect { /** * Allows access to a resource in an IAM policy statement. By default, access to resources are denied. */ ALLOW = 'Allow', /** * Explicitly deny access to a resource. By default, all requests are denied implicitly. * * @see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html */ DENY = 'Deny', } /** * Condition for when an IAM policy is in effect. Maps from the keys in a request's context to * a string value or array of string values. See the Conditions interface for more details. */ export type Condition = any; // NOTE! We'd ideally like to type this as `Record<string, any>`, because the // API expects a map which can take either strings or lists of strings. // // However, if we were to change this right now, the Java bindings for CDK would // emit a type of `Map<String, Object>`, but the most common types people would // instantiate would be an `ImmutableMap<String, String>` which would not be // assignable to `Map<String, Object>`. The types don't have a built-in notion // of co-contravariance, you have to indicate that on the type. So jsii would first // need to emit the type as `Map<String, ? extends Object>`. // // Feature request in https://github.com/aws/jsii/issues/1517 /** * Conditions for when an IAM Policy is in effect, specified in the following structure: * * `{ "Operator": { "keyInRequestContext": "value" } }` * * The value can be either a single string value or an array of string values. * * For more information, including which operators are supported, see [the IAM * documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html). */ export type Conditions = Record<string, Condition>; /** * Interface for creating a policy statement */ export interface PolicyStatementProps { /** * The Sid (statement ID) is an optional identifier that you provide for the * policy statement. You can assign a Sid value to each statement in a * statement array. In services that let you specify an ID element, such as * SQS and SNS, the Sid value is just a sub-ID of the policy document's ID. In * IAM, the Sid value must be unique within a JSON policy. * * @default - no sid */ readonly sid?: string; /** * List of actions to add to the statement * * @default - no actions */ readonly actions?: string[]; /** * List of not actions to add to the statement * * @default - no not-actions */ readonly notActions?: string[]; /** * List of principals to add to the statement * * @default - no principals */ readonly principals?: IPrincipal[]; /** * List of not principals to add to the statement * * @default - no not principals */ readonly notPrincipals?: IPrincipal[]; /** * Resource ARNs to add to the statement * * @default - no resources */ readonly resources?: string[]; /** * NotResource ARNs to add to the statement * * @default - no not-resources */ readonly notResources?: string[]; /** * Conditions to add to the statement * * @default - no condition */ readonly conditions?: {[key: string]: any}; /** * Whether to allow or deny the actions in this statement * * @default Effect.ALLOW */ readonly effect?: Effect; } function noUndef(x: any): any { const ret: any = {}; for (const [key, value] of Object.entries(x)) { if (value !== undefined) { ret[key] = value; } } return ret; } class JsonPrincipal extends PrincipalBase { public readonly policyFragment: PrincipalPolicyFragment; constructor(json: any = { }) { super(); // special case: if principal is a string, turn it into a "LiteralString" principal, // so we render the exact same string back out. if (typeof(json) === 'string') { json = { [LITERAL_STRING_KEY]: [json] }; } if (typeof(json) !== 'object') { throw new Error(`JSON IAM principal should be an object, got ${JSON.stringify(json)}`); } this.policyFragment = { principalJson: json, conditions: {}, }; } }
the_stack
import {absoluteFrom, getFileSystem, PathManipulation} from '@angular/compiler-cli/src/ngtsc/file_system'; import {ɵmakeTemplateObject} from '@angular/localize'; import generate from '@babel/generator'; import {NodePath, TransformOptions, transformSync, types as t} from '../src/babel_core'; import template from '@babel/template'; import {isGlobalIdentifier, isNamedIdentifier, isStringLiteralArray, isArrayOfExpressions, unwrapStringLiteralArray, unwrapMessagePartsFromLocalizeCall, wrapInParensIfNecessary, buildLocalizeReplacement, unwrapSubstitutionsFromLocalizeCall, unwrapMessagePartsFromTemplateLiteral, getLocation} from '../src/source_file_utils'; import {runInNativeFileSystem} from './helpers'; runInNativeFileSystem(() => { let fs: PathManipulation; beforeEach(() => fs = getFileSystem()); describe('utils', () => { describe('isNamedIdentifier()', () => { it('should return true if the expression is an identifier with name `$localize`', () => { const taggedTemplate = getTaggedTemplate('$localize ``;'); expect(isNamedIdentifier(taggedTemplate.get('tag'), '$localize')).toBe(true); }); it('should return false if the expression is an identifier without the name `$localize`', () => { const taggedTemplate = getTaggedTemplate('other ``;'); expect(isNamedIdentifier(taggedTemplate.get('tag'), '$localize')).toBe(false); }); it('should return false if the expression is not an identifier', () => { const taggedTemplate = getTaggedTemplate('$localize() ``;'); expect(isNamedIdentifier(taggedTemplate.get('tag'), '$localize')).toBe(false); }); }); describe('isGlobalIdentifier()', () => { it('should return true if the identifier is at the top level and not declared', () => { const taggedTemplate = getTaggedTemplate('$localize ``;'); expect(isGlobalIdentifier(taggedTemplate.get('tag') as NodePath<t.Identifier>)).toBe(true); }); it('should return true if the identifier is in a block scope and not declared', () => { const taggedTemplate = getTaggedTemplate('function foo() { $localize ``; } foo();'); expect(isGlobalIdentifier(taggedTemplate.get('tag') as NodePath<t.Identifier>)).toBe(true); }); it('should return false if the identifier is declared locally', () => { const taggedTemplate = getTaggedTemplate('function $localize() {} $localize ``;'); expect(isGlobalIdentifier(taggedTemplate.get('tag') as NodePath<t.Identifier>)).toBe(false); }); it('should return false if the identifier is a function parameter', () => { const taggedTemplate = getTaggedTemplate('function foo($localize) { $localize ``; }'); expect(isGlobalIdentifier(taggedTemplate.get('tag') as NodePath<t.Identifier>)).toBe(false); }); }); describe('buildLocalizeReplacement', () => { it('should interleave the `messageParts` with the `substitutions`', () => { const messageParts = ɵmakeTemplateObject(['a', 'b', 'c'], ['a', 'b', 'c']); const substitutions = [t.numericLiteral(1), t.numericLiteral(2)]; const expression = buildLocalizeReplacement(messageParts, substitutions); expect(generate(expression).code).toEqual('"a" + 1 + "b" + 2 + "c"'); }); it('should wrap "binary expression" substitutions in parentheses', () => { const messageParts = ɵmakeTemplateObject(['a', 'b'], ['a', 'b']); const binary = t.binaryExpression('+', t.numericLiteral(1), t.numericLiteral(2)); const expression = buildLocalizeReplacement(messageParts, [binary]); expect(generate(expression).code).toEqual('"a" + (1 + 2) + "b"'); }); }); describe('unwrapMessagePartsFromLocalizeCall', () => { it('should return an array of string literals and locations from a direct call to a tag function', () => { const localizeCall = getLocalizeCall(`$localize(['a', 'b\\t', 'c'], 1, 2)`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(locations).toEqual([ { start: {line: 0, column: 11}, end: {line: 0, column: 14}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 0, column: 16}, end: {line: 0, column: 21}, file: absoluteFrom('/test/file.js'), text: `'b\\t'`, }, { start: {line: 0, column: 23}, end: {line: 0, column: 26}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should return an array of string literals and locations from a downleveled tagged template', () => { let localizeCall = getLocalizeCall( `$localize(__makeTemplateObject(['a', 'b\\t', 'c'], ['a', 'b\\\\t', 'c']), 1, 2)`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\\t', 'c']); expect(locations).toEqual([ { start: {line: 0, column: 51}, end: {line: 0, column: 54}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 0, column: 56}, end: {line: 0, column: 62}, file: absoluteFrom('/test/file.js'), text: `'b\\\\t'`, }, { start: {line: 0, column: 64}, end: {line: 0, column: 67}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should return an array of string literals and locations from a (Babel helper) downleveled tagged template', () => { let localizeCall = getLocalizeCall( `$localize(babelHelpers.taggedTemplateLiteral(['a', 'b\\t', 'c'], ['a', 'b\\\\t', 'c']), 1, 2)`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\\t', 'c']); expect(locations).toEqual([ { start: {line: 0, column: 65}, end: {line: 0, column: 68}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 0, column: 70}, end: {line: 0, column: 76}, file: absoluteFrom('/test/file.js'), text: `'b\\\\t'`, }, { start: {line: 0, column: 78}, end: {line: 0, column: 81}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should return an array of string literals and locations from a memoized downleveled tagged template', () => { let localizeCall = getLocalizeCall(` var _templateObject; $localize(_templateObject || (_templateObject = __makeTemplateObject(['a', 'b\\t', 'c'], ['a', 'b\\\\t', 'c'])), 1, 2)`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\\t', 'c']); expect(locations).toEqual([ { start: {line: 2, column: 105}, end: {line: 2, column: 108}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 2, column: 110}, end: {line: 2, column: 116}, file: absoluteFrom('/test/file.js'), text: `'b\\\\t'`, }, { start: {line: 2, column: 118}, end: {line: 2, column: 121}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should return an array of string literals and locations from a memoized (inlined Babel helper) downleveled tagged template', () => { let localizeCall = getLocalizeCall(` var e,t,n; $localize(e || ( t=["a","b\t","c"], n || (n=t.slice(0)), e = Object.freeze( Object.defineProperties(t, { raw: { value: Object.freeze(n) } }) ) ), 1,2 )`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\t', 'c']); expect(locations).toEqual([ { start: {line: 4, column: 21}, end: {line: 4, column: 24}, file: absoluteFrom('/test/file.js'), text: `"a"`, }, { start: {line: 4, column: 25}, end: {line: 4, column: 29}, file: absoluteFrom('/test/file.js'), text: `"b\t"`, }, { start: {line: 4, column: 30}, end: {line: 4, column: 33}, file: absoluteFrom('/test/file.js'), text: `"c"`, }, ]); }); it('should return an array of string literals and locations from a lazy load template helper', () => { let localizeCall = getLocalizeCall(` function _templateObject() { var e = _taggedTemplateLiteral(['a', 'b\\t', 'c'], ['a', 'b\\\\t', 'c']); return _templateObject = function() { return e }, e } $localize(_templateObject(), 1, 2)`); const [parts, locations] = unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(parts).toEqual(['a', 'b\t', 'c']); expect(parts.raw).toEqual(['a', 'b\\t', 'c']); expect(locations).toEqual([ { start: {line: 2, column: 61}, end: {line: 2, column: 64}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 2, column: 66}, end: {line: 2, column: 72}, file: absoluteFrom('/test/file.js'), text: `'b\\\\t'`, }, { start: {line: 2, column: 74}, end: {line: 2, column: 77}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should remove a lazy load template helper', () => { let localizeCall = getLocalizeCall(` function _templateObject() { var e = _taggedTemplateLiteral(['a', 'b', 'c'], ['a', 'b', 'c']); return _templateObject = function() { return e }, e } $localize(_templateObject(), 1, 2)`); const localizeStatement = localizeCall.parentPath as NodePath<t.ExpressionStatement>; const statements = localizeStatement.container as object[]; expect(statements.length).toEqual(2); unwrapMessagePartsFromLocalizeCall(localizeCall, fs); expect(statements.length).toEqual(1); expect(statements[0]).toBe(localizeStatement.node); }); }); describe('unwrapSubstitutionsFromLocalizeCall', () => { it('should return the substitutions and locations from a direct call to a tag function', () => { const call = getLocalizeCall(`$localize(['a', 'b\t', 'c'], 1, 2)`); const [substitutions, locations] = unwrapSubstitutionsFromLocalizeCall(call, fs); expect((substitutions as t.NumericLiteral[]).map(s => s.value)).toEqual([1, 2]); expect(locations).toEqual([ { start: {line: 0, column: 28}, end: {line: 0, column: 29}, file: absoluteFrom('/test/file.js'), text: '1' }, { start: {line: 0, column: 31}, end: {line: 0, column: 32}, file: absoluteFrom('/test/file.js'), text: '2' }, ]); }); it('should return the substitutions and locations from a downleveled tagged template', () => { const call = getLocalizeCall( `$localize(__makeTemplateObject(['a', 'b', 'c'], ['a', 'b', 'c']), 1, 2)`); const [substitutions, locations] = unwrapSubstitutionsFromLocalizeCall(call, fs); expect((substitutions as t.NumericLiteral[]).map(s => s.value)).toEqual([1, 2]); expect(locations).toEqual([ { start: {line: 0, column: 66}, end: {line: 0, column: 67}, file: absoluteFrom('/test/file.js'), text: '1' }, { start: {line: 0, column: 69}, end: {line: 0, column: 70}, file: absoluteFrom('/test/file.js'), text: '2' }, ]); }); }); describe('unwrapMessagePartsFromTemplateLiteral', () => { it('should return a TemplateStringsArray built from the template literal elements', () => { const taggedTemplate = getTaggedTemplate('$localize `a${1}b\\t${2}c`;'); expect( unwrapMessagePartsFromTemplateLiteral(taggedTemplate.get('quasi').get('quasis'), fs)[0]) .toEqual(ɵmakeTemplateObject(['a', 'b\t', 'c'], ['a', 'b\\t', 'c'])); }); }); describe('wrapInParensIfNecessary', () => { it('should wrap the expression in parentheses if it is binary', () => { const ast = template.ast`a + b` as t.ExpressionStatement; const wrapped = wrapInParensIfNecessary(ast.expression); expect(t.isParenthesizedExpression(wrapped)).toBe(true); }); it('should return the expression untouched if it is not binary', () => { const ast = template.ast`a` as t.ExpressionStatement; const wrapped = wrapInParensIfNecessary(ast.expression); expect(t.isParenthesizedExpression(wrapped)).toBe(false); }); }); describe('unwrapStringLiteralArray', () => { it('should return an array of string from an array expression', () => { const array = getFirstExpression(`['a', 'b', 'c']`); const [expressions, locations] = unwrapStringLiteralArray(array, fs); expect(expressions).toEqual(['a', 'b', 'c']); expect(locations).toEqual([ { start: {line: 0, column: 1}, end: {line: 0, column: 4}, file: absoluteFrom('/test/file.js'), text: `'a'`, }, { start: {line: 0, column: 6}, end: {line: 0, column: 9}, file: absoluteFrom('/test/file.js'), text: `'b'`, }, { start: {line: 0, column: 11}, end: {line: 0, column: 14}, file: absoluteFrom('/test/file.js'), text: `'c'`, }, ]); }); it('should throw an error if any elements of the array are not literal strings', () => { const array = getFirstExpression(`['a', 2, 'c']`); expect(() => unwrapStringLiteralArray(array, fs)) .toThrowError( 'Unexpected messageParts for `$localize` (expected an array of strings).'); }); }); describe('isStringLiteralArray()', () => { it('should return true if the ast is an array of strings', () => { const ast = template.ast`['a', 'b', 'c']` as t.ExpressionStatement; expect(isStringLiteralArray(ast.expression)).toBe(true); }); it('should return false if the ast is not an array', () => { const ast = template.ast`'a'` as t.ExpressionStatement; expect(isStringLiteralArray(ast.expression)).toBe(false); }); it('should return false if at least on of the array elements is not a string', () => { const ast = template.ast`['a', 1, 'b']` as t.ExpressionStatement; expect(isStringLiteralArray(ast.expression)).toBe(false); }); }); describe('isArrayOfExpressions()', () => { it('should return true if all the nodes are expressions', () => { const call = getFirstExpression<t.CallExpression>('foo(a, b, c);'); expect(isArrayOfExpressions(call.get('arguments'))).toBe(true); }); it('should return false if any of the nodes is not an expression', () => { const call = getFirstExpression<t.CallExpression>('foo(a, b, ...c);'); expect(isArrayOfExpressions(call.get('arguments'))).toBe(false); }); }); describe('getLocation()', () => { it('should return a plain object containing the start, end and file of a NodePath', () => { const taggedTemplate = getTaggedTemplate('const x = $localize `message`;', { filename: 'src/test.js', sourceRoot: fs.resolve('/project'), }); const location = getLocation(fs, taggedTemplate)!; expect(location).toBeDefined(); expect(location.start).toEqual({line: 0, column: 10}); expect(location.start.constructor.name).toEqual('Object'); expect(location.end).toEqual({line: 0, column: 29}); expect(location.end?.constructor.name).toEqual('Object'); expect(location.file).toEqual(fs.resolve('/project/src/test.js')); }); it('should return `undefined` if the NodePath has no filename', () => { const taggedTemplate = getTaggedTemplate( 'const x = $localize ``;', {sourceRoot: fs.resolve('/project'), filename: undefined}); const location = getLocation(fs, taggedTemplate); expect(location).toBeUndefined(); }); }); }); }); function getTaggedTemplate( code: string, options?: TransformOptions): NodePath<t.TaggedTemplateExpression> { return getExpressions<t.TaggedTemplateExpression>(code, options) .find(e => e.isTaggedTemplateExpression())!; } function getFirstExpression<T extends t.Expression>( code: string, options?: TransformOptions): NodePath<T> { return getExpressions<T>(code, options)[0]; } function getExpressions<T extends t.Expression>( code: string, options?: TransformOptions): NodePath<T>[] { const expressions: NodePath<t.Expression>[] = []; transformSync(code, { code: false, filename: 'test/file.js', cwd: '/', plugins: [{ visitor: { Expression: (path: NodePath<t.Expression>) => { expressions.push(path); } } }], ...options }); return expressions as NodePath<T>[]; } function getLocalizeCall(code: string): NodePath<t.CallExpression> { let callPaths: NodePath<t.CallExpression>[] = []; transformSync(code, { code: false, filename: 'test/file.js', cwd: '/', plugins: [{ visitor: { CallExpression(path) { callPaths.push(path); } } }] }); const localizeCall = callPaths.find(p => { const callee = p.get('callee'); return (callee.isIdentifier() && callee.node.name === '$localize'); }); if (!localizeCall) { throw new Error(`$localize cannot be found in ${code}`); } return localizeCall; }
the_stack
import { AssetType, FileSet, ShellStep, StackAsset, StackDeployment, StageDeployment, Step, Wave } from '../blueprint'; import { PipelineBase } from '../main/pipeline-base'; import { DependencyBuilders, Graph, GraphNode, GraphNodeCollection } from './graph'; import { PipelineQueries } from './pipeline-queries'; export interface PipelineGraphProps { /** * Add a self-mutation step. * * @default false */ readonly selfMutation?: boolean; /** * Publishes the template asset to S3. * * @default false */ readonly publishTemplate?: boolean; /** * Whether to combine asset publishers for the same type into one step * * @default false */ readonly singlePublisherPerAssetType?: boolean; /** * Add a "prepare" step for each stack which can be used to create the change * set. If this is disabled, only the "execute" step will be included. * * @default true */ readonly prepareStep?: boolean; } /** * Logic to turn the deployment blueprint into a graph * * This code makes all the decisions on how to lay out the CodePipeline */ export class PipelineGraph { /** * A Step object that may be used as the producer of FileSets that should not be represented in the graph */ public static readonly NO_STEP: Step = new class extends Step { }('NO_STEP'); public readonly graph: AGraph = Graph.of('', { type: 'group' }); public readonly cloudAssemblyFileSet: FileSet; public readonly queries: PipelineQueries; private readonly added = new Map<Step, AGraphNode>(); private readonly assetNodes = new Map<string, AGraphNode>(); private readonly assetNodesByType = new Map<AssetType, AGraphNode>(); private readonly synthNode?: AGraphNode; private readonly selfMutateNode?: AGraphNode; private readonly stackOutputDependencies = new DependencyBuilders<StackDeployment, any>(); private readonly publishTemplate: boolean; private readonly prepareStep: boolean; private readonly singlePublisher: boolean; private lastPreparationNode?: AGraphNode; private _fileAssetCtr = 0; private _dockerAssetCtr = 0; constructor(public readonly pipeline: PipelineBase, props: PipelineGraphProps = {}) { this.publishTemplate = props.publishTemplate ?? false; this.prepareStep = props.prepareStep ?? true; this.singlePublisher = props.singlePublisherPerAssetType ?? false; this.queries = new PipelineQueries(pipeline); if (pipeline.synth instanceof Step) { this.synthNode = this.addBuildStep(pipeline.synth); if (this.synthNode?.data?.type === 'step') { this.synthNode.data.isBuildStep = true; } } this.lastPreparationNode = this.synthNode; const cloudAssembly = pipeline.synth.primaryOutput?.primaryOutput; if (!cloudAssembly) { throw new Error(`The synth step must produce the cloud assembly artifact, but doesn't: ${pipeline.synth}`); } this.cloudAssemblyFileSet = cloudAssembly; if (props.selfMutation) { const stage: AGraph = Graph.of('UpdatePipeline', { type: 'group' }); this.graph.add(stage); this.selfMutateNode = GraphNode.of('SelfMutate', { type: 'self-update' }); stage.add(this.selfMutateNode); this.selfMutateNode.dependOn(this.synthNode); this.lastPreparationNode = this.selfMutateNode; } const waves = pipeline.waves.map(w => this.addWave(w)); // Make sure the waves deploy sequentially for (let i = 1; i < waves.length; i++) { waves[i].dependOn(waves[i - 1]); } // Add additional dependencies between steps that depend on stack outputs and the stacks // that produce them. } public isSynthNode(node: AGraphNode) { return this.synthNode === node; } private addBuildStep(step: Step) { return this.addAndRecurse(step, this.topLevelGraph('Build')); } private addWave(wave: Wave): AGraph { // If the wave only has one Stage in it, don't add an additional Graph around it const retGraph: AGraph = wave.stages.length === 1 ? this.addStage(wave.stages[0]) : Graph.of(wave.id, { type: 'group' }, wave.stages.map(s => this.addStage(s))); this.addPrePost(wave.pre, wave.post, retGraph); retGraph.dependOn(this.lastPreparationNode); this.graph.add(retGraph); return retGraph; } private addStage(stage: StageDeployment): AGraph { const retGraph: AGraph = Graph.of(stage.stageName, { type: 'group' }); const stackGraphs = new Map<StackDeployment, AGraph>(); for (const stack of stage.stacks) { const stackGraph: AGraph = Graph.of(this.simpleStackName(stack.stackName, stage.stageName), { type: 'stack-group', stack }); const prepareNode: AGraphNode | undefined = this.prepareStep ? GraphNode.of('Prepare', { type: 'prepare', stack }) : undefined; const deployNode: AGraphNode = GraphNode.of('Deploy', { type: 'execute', stack, captureOutputs: this.queries.stackOutputsReferenced(stack).length > 0, }); retGraph.add(stackGraph); stackGraph.add(deployNode); // node or node collection that represents first point of contact in each stack let firstDeployNode; if (prepareNode) { stackGraph.add(prepareNode); deployNode.dependOn(prepareNode); firstDeployNode = prepareNode; } else { firstDeployNode = deployNode; } // add changeset steps at the stack level if (stack.changeSet.length > 0) { if (prepareNode) { this.addChangeSet(stack.changeSet, prepareNode, deployNode, stackGraph); } else { throw new Error('Your pipeline engine does not support changeSet steps'); } } // add pre and post steps at the stack level const preNodes = this.addPrePost(stack.pre, stack.post, stackGraph); if (preNodes.nodes.length > 0) { firstDeployNode = preNodes; } stackGraphs.set(stack, stackGraph); const cloudAssembly = this.cloudAssemblyFileSet; firstDeployNode.dependOn(this.addAndRecurse(cloudAssembly.producer, retGraph)); // add the template asset if (this.publishTemplate) { if (!stack.templateAsset) { throw new Error(`"publishTemplate" is enabled, but stack ${stack.stackArtifactId} does not have a template asset`); } firstDeployNode.dependOn(this.publishAsset(stack.templateAsset)); } // Depend on Assets // FIXME: Custom Cloud Assembly currently doesn't actually help separating // out templates from assets!!! for (const asset of stack.assets) { const assetNode = this.publishAsset(asset); firstDeployNode.dependOn(assetNode); } // Add stack output synchronization point if (this.queries.stackOutputsReferenced(stack).length > 0) { this.stackOutputDependencies.get(stack).dependOn(deployNode); } } for (const stack of stage.stacks) { for (const dep of stack.stackDependencies) { const stackNode = stackGraphs.get(stack); const depNode = stackGraphs.get(dep); if (!stackNode) { throw new Error(`cannot find node for ${stack.stackName}`); } if (!depNode) { throw new Error(`cannot find node for ${dep.stackName}`); } stackNode.dependOn(depNode); } } this.addPrePost(stage.pre, stage.post, retGraph); return retGraph; } private addChangeSet(changeSet: Step[], prepareNode: AGraphNode, deployNode: AGraphNode, graph: AGraph) { for (const c of changeSet) { const changeSetNode = this.addAndRecurse(c, graph); changeSetNode?.dependOn(prepareNode); deployNode.dependOn(changeSetNode); } } private addPrePost(pre: Step[], post: Step[], parent: AGraph) { const currentNodes = new GraphNodeCollection(parent.nodes); const preNodes = new GraphNodeCollection(new Array<AGraphNode>()); for (const p of pre) { const preNode = this.addAndRecurse(p, parent); currentNodes.dependOn(preNode); preNodes.nodes.push(preNode!); } for (const p of post) { const postNode = this.addAndRecurse(p, parent); postNode?.dependOn(...currentNodes.nodes); } return preNodes; } private topLevelGraph(name: string): AGraph { let ret = this.graph.tryGetChild(name); if (!ret) { ret = new Graph<GraphAnnotation>(name); this.graph.add(ret); } return ret as AGraph; } private addAndRecurse(step: Step, parent: AGraph) { if (step === PipelineGraph.NO_STEP) { return undefined; } const previous = this.added.get(step); if (previous) { return previous; } const node: AGraphNode = GraphNode.of(step.id, { type: 'step', step }); // If the step is a source step, change the parent to a special "Source" stage // (CodePipeline wants it that way) if (step.isSource) { parent = this.topLevelGraph('Source'); } parent.add(node); this.added.set(step, node); for (const dep of step.dependencies) { const producerNode = this.addAndRecurse(dep, parent); node.dependOn(producerNode); } // Add stack dependencies (by use of the dependency builder this also works // if we encounter the Step before the Stack has been properly added yet) if (step instanceof ShellStep) { for (const output of Object.values(step.envFromCfnOutputs)) { const stack = this.queries.producingStack(output); this.stackOutputDependencies.get(stack).dependBy(node); } } return node; } private publishAsset(stackAsset: StackAsset): AGraphNode { const assetsGraph = this.topLevelGraph('Assets'); let assetNode = this.assetNodes.get(stackAsset.assetId); if (assetNode) { // If there's already a node publishing this asset, add as a new publishing // destination to the same node. } else if (this.singlePublisher && this.assetNodesByType.has(stackAsset.assetType)) { // If we're doing a single node per type, lookup by that assetNode = this.assetNodesByType.get(stackAsset.assetType)!; } else { // Otherwise add a new one const id = stackAsset.assetType === AssetType.FILE ? (this.singlePublisher ? 'FileAsset' : `FileAsset${++this._fileAssetCtr}`) : (this.singlePublisher ? 'DockerAsset' : `DockerAsset${++this._dockerAssetCtr}`); assetNode = GraphNode.of(id, { type: 'publish-assets', assets: [] }); assetsGraph.add(assetNode); assetNode.dependOn(this.lastPreparationNode); this.assetNodesByType.set(stackAsset.assetType, assetNode); this.assetNodes.set(stackAsset.assetId, assetNode); } const data = assetNode.data; if (data?.type !== 'publish-assets') { throw new Error(`${assetNode} has the wrong data.type: ${data?.type}`); } if (!data.assets.some(a => a.assetSelector === stackAsset.assetSelector)) { data.assets.push(stackAsset); } return assetNode; } /** * Simplify the stack name by removing the `Stage-` prefix if it exists. */ private simpleStackName(stackName: string, stageName: string) { return stripPrefix(stackName, `${stageName}-`); } } type GraphAnnotation = { readonly type: 'group' } | { readonly type: 'stack-group'; readonly stack: StackDeployment } | { readonly type: 'publish-assets'; readonly assets: StackAsset[] } | { readonly type: 'step'; readonly step: Step; isBuildStep?: boolean } | { readonly type: 'self-update' } | { readonly type: 'prepare'; readonly stack: StackDeployment } | { readonly type: 'execute'; readonly stack: StackDeployment; readonly captureOutputs: boolean } ; // Type aliases for the graph nodes tagged with our specific annotation type // (to save on generics in the code above). export type AGraphNode = GraphNode<GraphAnnotation>; export type AGraph = Graph<GraphAnnotation>; function stripPrefix(s: string, prefix: string) { return s.startsWith(prefix) ? s.slice(prefix.length) : s; }
the_stack
import { Texture } from './Drawing/Texture'; import { InitializeEvent, KillEvent, PreUpdateEvent, PostUpdateEvent, PreDrawEvent, PostDrawEvent, PreDebugDrawEvent, PostDebugDrawEvent, PostCollisionEvent, PreCollisionEvent, CollisionStartEvent, CollisionEndEvent, PostKillEvent, PreKillEvent, GameEvent, ExitTriggerEvent, EnterTriggerEvent, EnterViewPortEvent, ExitViewPortEvent } from './Events'; import { PointerEvent, WheelEvent, PointerDragEvent, PointerEventName } from './Input/PointerEvents'; import { Engine } from './Engine'; import { Color } from './Color'; import { Sprite } from './Drawing/Sprite'; import { Animation } from './Drawing/Animation'; import { Trait } from './Interfaces/Trait'; import { Drawable } from './Interfaces/Drawable'; import { CanInitialize, CanUpdate, CanDraw, CanBeKilled } from './Interfaces/LifecycleEvents'; import { Scene } from './Scene'; import { Logger } from './Util/Log'; import { Vector, vec } from './Math/vector'; import { BodyComponent } from './Collision/BodyComponent'; import { Eventable } from './Interfaces/Evented'; import * as Traits from './Traits/Index'; import * as Events from './Events'; import { PointerEvents } from './Interfaces/PointerEventHandlers'; import { CollisionType } from './Collision/CollisionType'; import { Entity } from './EntityComponentSystem/Entity'; import { CanvasDrawComponent } from './Drawing/CanvasDrawComponent'; import { TransformComponent } from './EntityComponentSystem/Components/TransformComponent'; import { MotionComponent } from './EntityComponentSystem/Components/MotionComponent'; import { GraphicsComponent } from './Graphics/GraphicsComponent'; import { Rectangle } from './Graphics/Rectangle'; import { Flags, Legacy } from './Flags'; import { obsolete } from './Util/Decorators'; import { ColliderComponent } from './Collision/ColliderComponent'; import { Shape } from './Collision/Colliders/Shape'; import { watch } from './Util/Watch'; import { Collider, CollisionGroup } from './Collision/Index'; import { Circle } from './Graphics/Circle'; import { CapturePointerConfig } from './Input/CapturePointerConfig'; import { ActionsComponent } from './Actions/ActionsComponent'; /** * Type guard for checking if something is an Actor * @param x */ export function isActor(x: any): x is Actor { return x instanceof Actor; } /** * Actor contructor options */ export interface ActorArgs { /** * Optionally set the name of the actor, default is 'anonymous' */ name?: string; /** * Optionally set the x position of the actor, default is 0 */ x?: number; /** * Optionally set the y position of the actor, default is 0 */ y?: number; /** * Optionaly set the (x, y) position of the actor as a vector, default is (0, 0) */ pos?: Vector; /** * Optionally set the width of a box collider for the actor */ width?: number; /** * Optionally set the height of a box collider for the actor */ height?: number; /** * Optionally set the radius of the circle collider for the actor */ radius?: number; /** * Optionally set the velocity of the actor in pixels/sec */ vel?: Vector; /** * Optionally set the acceleration of the actor in pixels/sec^2 */ acc?: Vector; /** * Optionally se the rotation in radians (180 degrees = Math.PI radians) */ rotation?: number; /** * Optionally set the angular velocity of the actor in radians/sec (180 degrees = Math.PI radians) */ angularVelocity?: number; /** * Optionally set the scale of the actor's transform */ scale?: Vector; /** * Optionally set the z index of the actor, default is 0 */ z?: number; /** * Optionally set the color of an actor, only used if no graphics are present * If a width/height or a radius was set a default graphic will be added */ color?: Color; /** * Optionally set the visibility of the actor */ visible?: boolean; /** * Optionally set the anchor for graphics in the actor */ anchor?: Vector; /** * Optionally set the collision type */ collisionType?: CollisionType; /** * Optionally supply a collider for an actor, if supplied ignores any supplied width/height */ collider?: Collider; /** * Optionally suppy a [[CollisionGroup]] */ collisionGroup?: CollisionGroup; } /** * The most important primitive in Excalibur is an `Actor`. Anything that * can move on the screen, collide with another `Actor`, respond to events, * or interact with the current scene, must be an actor. An `Actor` **must** * be part of a [[Scene]] for it to be drawn to the screen. */ export class Actor extends Entity implements Eventable, PointerEvents, CanInitialize, CanUpdate, CanDraw, CanBeKilled { // #region Properties /** * Set defaults for all Actors */ public static defaults = { anchor: Vector.Half }; /** * The physics body the is associated with this actor. The body is the container for all physical properties, like position, velocity, * acceleration, mass, inertia, etc. */ public get body(): BodyComponent { return this.get(BodyComponent); } /** * Access the Actor's built in [[TransformComponent]] */ public get transform(): TransformComponent { return this.get(TransformComponent); } /** * Access the Actor's built in [[MotionComponent]] */ public get motion(): MotionComponent { return this.get(MotionComponent); } /** * Access to the Actor's built in [[GraphicsComponent]] */ public get graphics(): GraphicsComponent { return this.get(GraphicsComponent); } /** * Access to the Actor's built in [[ColliderComponent]] */ public get collider(): ColliderComponent { return this.get(ColliderComponent); } /** * Useful for quickly scripting actor behavior, like moving to a place, patroling back and forth, blinking, etc. * * Access to the Actor's built in [[ActionsComponent]] which forwards to the * [[ActionContext|Action context]] of the actor. */ public get actions(): ActionsComponent { return this.get(ActionsComponent); } /** * Gets the position vector of the actor in pixels */ public get pos(): Vector { return this.transform.pos; } /** * Sets the position vector of the actor in pixels */ public set pos(thePos: Vector) { this.transform.pos = thePos.clone(); } /** * Gets the position vector of the actor from the last frame */ public get oldPos(): Vector { return this.body.oldPos; } /** * Sets the position vector of the actor in the last frame */ public set oldPos(thePos: Vector) { this.body.oldPos.setTo(thePos.x, thePos.y); } /** * Gets the velocity vector of the actor in pixels/sec */ public get vel(): Vector { return this.motion.vel; } /** * Sets the velocity vector of the actor in pixels/sec */ public set vel(theVel: Vector) { this.motion.vel = theVel.clone(); } /** * Gets the velocity vector of the actor from the last frame */ public get oldVel(): Vector { return this.body.oldVel; } /** * Sets the velocity vector of the actor from the last frame */ public set oldVel(theVel: Vector) { this.body.oldVel.setTo(theVel.x, theVel.y); } /** * Gets the acceleration vector of the actor in pixels/second/second. An acceleration pointing down such as (0, 100) may be * useful to simulate a gravitational effect. */ public get acc(): Vector { return this.motion.acc; } /** * Sets the acceleration vector of teh actor in pixels/second/second */ public set acc(theAcc: Vector) { this.motion.acc = theAcc.clone(); } /** * Sets the acceleration of the actor from the last frame. This does not include the global acc [[Physics.acc]]. */ public set oldAcc(theAcc: Vector) { this.body.oldAcc.setTo(theAcc.x, theAcc.y); } /** * Gets the acceleration of the actor from the last frame. This does not include the global acc [[Physics.acc]]. */ public get oldAcc(): Vector { return this.body.oldAcc; } /** * Gets the rotation of the actor in radians. 1 radian = 180/PI Degrees. */ public get rotation(): number { return this.transform.rotation; } /** * Sets the rotation of the actor in radians. 1 radian = 180/PI Degrees. */ public set rotation(theAngle: number) { this.transform.rotation = theAngle; } /** * Gets the rotational velocity of the actor in radians/second */ public get angularVelocity(): number { return this.motion.angularVelocity; } /** * Sets the rotational velocity of the actor in radians/sec */ public set angularVelocity(angularVelocity: number) { this.motion.angularVelocity = angularVelocity; } public get scale(): Vector { return this.get(TransformComponent).scale; } public set scale(scale: Vector) { this.get(TransformComponent).scale = scale; } /** * The anchor to apply all actor related transformations like rotation, * translation, and scaling. By default the anchor is in the center of * the actor. By default it is set to the center of the actor (.5, .5) * * An anchor of (.5, .5) will ensure that drawings are centered. * * Use `anchor.setTo` to set the anchor to a different point using * values between 0 and 1. For example, anchoring to the top-left would be * `Actor.anchor.setTo(0, 0)` and top-right would be `Actor.anchor.setTo(0, 1)`. */ private _anchor: Vector = watch(Vector.Half, (v) => this._handleAnchorChange(v)); public get anchor(): Vector { return this._anchor; } public set anchor(vec: Vector) { this._anchor = watch(vec, (v) => this._handleAnchorChange(v)); this._handleAnchorChange(vec); } private _handleAnchorChange(v: Vector) { if (this.graphics) { this.graphics.anchor = v; } } /** * Indicates whether the actor is physically in the viewport */ public get isOffScreen(): boolean { return this.hasTag('offscreen'); } /** * The visibility of an actor * @deprecated Use [[GraphicsComponent.visible|Actor.graphics.visible]], will be removed in v0.26.0 */ @obsolete({ message: 'Actor.visible will be removed in v0.26.0', alternateMethod: 'Use Actor.graphics.visible' }) public get visible(): boolean { return this.graphics.visible; } public set visible(isVisible: boolean) { this.graphics.visible = isVisible; } /** * The opacity of an actor. * * @deprecated Actor.opacity will be removed in v0.26.0, use [[GraphicsComponent.opacity|Actor.graphics.opacity]]. */ @obsolete({ message: 'Actor.opacity will be removed in v0.26.0', alternateMethod: 'Use Actor.graphics.opacity' }) public get opacity(): number { return this.graphics.opacity; } public set opacity(opacity: number) { this.graphics.opacity = opacity; } /** * Convenience reference to the global logger */ public logger: Logger = Logger.getInstance(); /** * The scene that the actor is in */ public scene: Scene = null; public frames: { [key: string]: Drawable } = {}; /** * Access to the current drawing for the actor, this can be * an [[Animation]], [[Sprite]], or [[Polygon]]. * Set drawings with [[setDrawing]]. * @deprecated */ public currentDrawing: Drawable = null; /** * Draggable helper */ private _draggable: boolean = false; private _dragging: boolean = false; private _pointerDragStartHandler = () => { this._dragging = true; }; private _pointerDragEndHandler = () => { this._dragging = false; }; private _pointerDragMoveHandler = (pe: PointerEvent) => { if (this._dragging) { this.pos = pe.pointer.lastWorldPos; } }; private _pointerDragLeaveHandler = (pe: PointerEvent) => { if (this._dragging) { this.pos = pe.pointer.lastWorldPos; } }; public get draggable(): boolean { return this._draggable; } public set draggable(isDraggable: boolean) { if (isDraggable) { if (isDraggable && !this._draggable) { this.on('pointerdragstart', this._pointerDragStartHandler); this.on('pointerdragend', this._pointerDragEndHandler); this.on('pointerdragmove', this._pointerDragMoveHandler); this.on('pointerdragleave', this._pointerDragLeaveHandler); } else if (!isDraggable && this._draggable) { this.off('pointerdragstart', this._pointerDragStartHandler); this.off('pointerdragend', this._pointerDragEndHandler); this.off('pointerdragmove', this._pointerDragMoveHandler); this.off('pointerdragleave', this._pointerDragLeaveHandler); } this._draggable = isDraggable; } } /** * Modify the current actor update pipeline. */ public traits: Trait[] = []; /** * Sets the color of the actor. A rectangle of this color will be * drawn if no [[Drawable]] is specified as the actors drawing. * * The default is `null` which prevents a rectangle from being drawn. */ public get color(): Color { return this._color; } public set color(v: Color) { this._color = v.clone(); } private _color: Color; /** * Whether or not to enable the [[Traits.CapturePointer]] trait that propagates * pointer events to this actor */ public enableCapturePointer: boolean = false; /** * Configuration for [[Traits.CapturePointer]] trait */ public capturePointer: CapturePointerConfig = { captureMoveEvents: false, captureDragEvents: false }; // #endregion /** * * @param config */ constructor(config?: ActorArgs) { super(); const { name, x, y, pos, scale, width, height, radius, collider, vel, acc, rotation, angularVelocity, z, color, visible, anchor, collisionType, collisionGroup } = { ...config }; this._setName(name); this.anchor = anchor ?? Actor.defaults.anchor.clone(); this.addComponent(new TransformComponent()); this.pos = pos ?? vec(x ?? 0, y ?? 0); this.rotation = rotation ?? 0; this.scale = scale ?? vec(1, 1); this.z = z ?? 0; this.addComponent(new GraphicsComponent()); this.addComponent(new CanvasDrawComponent((ctx, delta) => this.draw(ctx, delta))); this.addComponent(new MotionComponent()); this.vel = vel ?? Vector.Zero; this.acc = acc ?? Vector.Zero; this.angularVelocity = angularVelocity ?? 0; this.addComponent(new ActionsComponent()); this.addComponent(new BodyComponent()); this.body.collisionType = collisionType ?? CollisionType.Passive; if (collisionGroup) { this.body.group = collisionGroup; } if (collider) { this.addComponent(new ColliderComponent(collider)); } else if (radius) { this.addComponent(new ColliderComponent(Shape.Circle(radius, this.anchor))); } else { if (width > 0 && height > 0) { this.addComponent(new ColliderComponent(Shape.Box(width, height, this.anchor))); } else { this.addComponent(new ColliderComponent()); // no collider } } this.graphics.visible = visible ?? true; if (color) { this.color = color; if (width && height) { this.graphics.add( new Rectangle({ color: color, width, height }) ); } else if (radius) { this.graphics.add( new Circle({ color: color, radius }) ); } } // Build default pipeline if (Flags.isEnabled(Legacy.LegacyDrawing)) { // TODO remove offscreen trait after legacy drawing removed this.traits.push(new Traits.OffscreenCulling()); } this.traits.push(new Traits.CapturePointer()); } /** * `onInitialize` is called before the first update of the actor. This method is meant to be * overridden. This is where initialization of child actors should take place. * * Synonymous with the event handler `.on('initialize', (evt) => {...})` */ public onInitialize(_engine: Engine): void { // Override me } /** * Initializes this actor and all it's child actors, meant to be called by the Scene before first update not by users of Excalibur. * * It is not recommended that internal excalibur methods be overridden, do so at your own risk. * * @internal */ public _initialize(engine: Engine) { super._initialize(engine); for (const child of this.children) { child._initialize(engine); } } // #region Events private _capturePointerEvents: PointerEventName[] = [ 'pointerup', 'pointerdown', 'pointermove', 'pointerenter', 'pointerleave', 'pointerdragstart', 'pointerdragend', 'pointerdragmove', 'pointerdragenter', 'pointerdragleave' ]; private _captureMoveEvents: PointerEventName[] = [ 'pointermove', 'pointerenter', 'pointerleave', 'pointerdragmove', 'pointerdragenter', 'pointerdragleave' ]; private _captureDragEvents: PointerEventName[] = [ 'pointerdragstart', 'pointerdragend', 'pointerdragmove', 'pointerdragenter', 'pointerdragleave' ]; private _checkForPointerOptIn(eventName: string) { if (eventName) { const normalized = <PointerEventName>eventName.toLowerCase(); if (this._capturePointerEvents.indexOf(normalized) !== -1) { this.enableCapturePointer = true; if (this._captureMoveEvents.indexOf(normalized) !== -1) { this.capturePointer.captureMoveEvents = true; } if (this._captureDragEvents.indexOf(normalized) !== -1) { this.capturePointer.captureDragEvents = true; } } } } public on(eventName: Events.exittrigger, handler: (event: ExitTriggerEvent) => void): void; public on(eventName: Events.entertrigger, handler: (event: EnterTriggerEvent) => void): void; /** * The **collisionstart** event is fired when a [[BodyComponent|physics body]], usually attached to an actor, * first starts colliding with another [[BodyComponent|body]], and will not fire again while in contact until * the the pair separates and collides again. * Use cases for the **collisionstart** event may be detecting when an actor has touched a surface * (like landing) or if a item has been touched and needs to be picked up. */ public on(eventName: Events.collisionstart, handler: (event: CollisionStartEvent) => void): void; /** * The **collisionend** event is fired when two [[BodyComponent|physics bodies]] are no longer in contact. * This event will not fire again until another collision and separation. * * Use cases for the **collisionend** event might be to detect when an actor has left a surface * (like jumping) or has left an area. */ public on(eventName: Events.collisionend, handler: (event: CollisionEndEvent) => void): void; /** * The **precollision** event is fired **every frame** where a collision pair is found and two * bodies are intersecting. * * This event is useful for building in custom collision resolution logic in Passive-Passive or * Active-Passive scenarios. For example in a breakout game you may want to tweak the angle of * ricochet of the ball depending on which side of the paddle you hit. */ public on(eventName: Events.precollision, handler: (event: PreCollisionEvent) => void): void; /** * The **postcollision** event is fired for **every frame** where collision resolution was performed. * Collision resolution is when two bodies influence each other and cause a response like bouncing * off one another. It is only possible to have *postcollision* event in Active-Active and Active-Fixed * type collision pairs. * * Post collision would be useful if you need to know that collision resolution is happening or need to * tweak the default resolution. */ public on(eventName: Events.postcollision, handler: (event: PostCollisionEvent) => void): void; public on(eventName: Events.kill, handler: (event: KillEvent) => void): void; public on(eventName: Events.prekill, handler: (event: PreKillEvent) => void): void; public on(eventName: Events.postkill, handler: (event: PostKillEvent) => void): void; public on(eventName: Events.initialize, handler: (event: InitializeEvent<Actor>) => void): void; public on(eventName: Events.preupdate, handler: (event: PreUpdateEvent<Actor>) => void): void; public on(eventName: Events.postupdate, handler: (event: PostUpdateEvent<Actor>) => void): void; public on(eventName: Events.predraw, handler: (event: PreDrawEvent) => void): void; public on(eventName: Events.postdraw, handler: (event: PostDrawEvent) => void): void; public on(eventName: Events.predebugdraw, handler: (event: PreDebugDrawEvent) => void): void; public on(eventName: Events.postdebugdraw, handler: (event: PostDebugDrawEvent) => void): void; public on(eventName: Events.pointerup, handler: (event: PointerEvent) => void): void; public on(eventName: Events.pointerdown, handler: (event: PointerEvent) => void): void; public on(eventName: Events.pointerenter, handler: (event: PointerEvent) => void): void; public on(eventName: Events.pointerleave, handler: (event: PointerEvent) => void): void; public on(eventName: Events.pointermove, handler: (event: PointerEvent) => void): void; public on(eventName: Events.pointercancel, handler: (event: PointerEvent) => void): void; public on(eventName: Events.pointerwheel, handler: (event: WheelEvent) => void): void; public on(eventName: Events.pointerdragstart, handler: (event: PointerDragEvent) => void): void; public on(eventName: Events.pointerdragend, handler: (event: PointerDragEvent) => void): void; public on(eventName: Events.pointerdragenter, handler: (event: PointerDragEvent) => void): void; public on(eventName: Events.pointerdragleave, handler: (event: PointerDragEvent) => void): void; public on(eventName: Events.pointerdragmove, handler: (event: PointerDragEvent) => void): void; public on(eventName: Events.enterviewport, handler: (event: EnterViewPortEvent) => void): void; public on(eventName: Events.exitviewport, handler: (event: ExitViewPortEvent) => void): void; public on(eventName: string, handler: (event: GameEvent<Actor>) => void): void; public on(eventName: string, handler: (event: any) => void): void { this._checkForPointerOptIn(eventName); super.on(eventName, handler); } public once(eventName: Events.exittrigger, handler: (event: ExitTriggerEvent) => void): void; public once(eventName: Events.entertrigger, handler: (event: EnterTriggerEvent) => void): void; /** * The **collisionstart** event is fired when a [[BodyComponent|physics body]], usually attached to an actor, * first starts colliding with another [[BodyComponent|body]], and will not fire again while in contact until * the the pair separates and collides again. * Use cases for the **collisionstart** event may be detecting when an actor has touch a surface * (like landing) or if a item has been touched and needs to be picked up. */ public once(eventName: Events.collisionstart, handler: (event: CollisionStartEvent) => void): void; /** * The **collisionend** event is fired when two [[BodyComponent|physics bodies]] are no longer in contact. * This event will not fire again until another collision and separation. * * Use cases for the **collisionend** event might be to detect when an actor has left a surface * (like jumping) or has left an area. */ public once(eventName: Events.collisionend, handler: (event: CollisionEndEvent) => void): void; /** * The **precollision** event is fired **every frame** where a collision pair is found and two * bodies are intersecting. * * This event is useful for building in custom collision resolution logic in Passive-Passive or * Active-Passive scenarios. For example in a breakout game you may want to tweak the angle of * ricochet of the ball depending on which side of the paddle you hit. */ public once(eventName: Events.precollision, handler: (event: PreCollisionEvent) => void): void; /** * The **postcollision** event is fired for **every frame** where collision resolution was performed. * Collision resolution is when two bodies influence each other and cause a response like bouncing * off one another. It is only possible to have *postcollision* event in Active-Active and Active-Fixed * type collision pairs. * * Post collision would be useful if you need to know that collision resolution is happening or need to * tweak the default resolution. */ public once(eventName: Events.postcollision, handler: (event: PostCollisionEvent) => void): void; public once(eventName: Events.kill, handler: (event: KillEvent) => void): void; public once(eventName: Events.postkill, handler: (event: PostKillEvent) => void): void; public once(eventName: Events.prekill, handler: (event: PreKillEvent) => void): void; public once(eventName: Events.initialize, handler: (event: InitializeEvent<Actor>) => void): void; public once(eventName: Events.preupdate, handler: (event: PreUpdateEvent<Actor>) => void): void; public once(eventName: Events.postupdate, handler: (event: PostUpdateEvent<Actor>) => void): void; public once(eventName: Events.predraw, handler: (event: PreDrawEvent) => void): void; public once(eventName: Events.postdraw, handler: (event: PostDrawEvent) => void): void; public once(eventName: Events.predebugdraw, handler: (event: PreDebugDrawEvent) => void): void; public once(eventName: Events.postdebugdraw, handler: (event: PostDebugDrawEvent) => void): void; public once(eventName: Events.pointerup, handler: (event: PointerEvent) => void): void; public once(eventName: Events.pointerdown, handler: (event: PointerEvent) => void): void; public once(eventName: Events.pointerenter, handler: (event: PointerEvent) => void): void; public once(eventName: Events.pointerleave, handler: (event: PointerEvent) => void): void; public once(eventName: Events.pointermove, handler: (event: PointerEvent) => void): void; public once(eventName: Events.pointercancel, handler: (event: PointerEvent) => void): void; public once(eventName: Events.pointerwheel, handler: (event: WheelEvent) => void): void; public once(eventName: Events.pointerdragstart, handler: (event: PointerDragEvent) => void): void; public once(eventName: Events.pointerdragend, handler: (event: PointerDragEvent) => void): void; public once(eventName: Events.pointerdragenter, handler: (event: PointerDragEvent) => void): void; public once(eventName: Events.pointerdragleave, handler: (event: PointerDragEvent) => void): void; public once(eventName: Events.pointerdragmove, handler: (event: PointerDragEvent) => void): void; public once(eventName: Events.enterviewport, handler: (event: EnterViewPortEvent) => void): void; public once(eventName: Events.exitviewport, handler: (event: ExitViewPortEvent) => void): void; public once(eventName: string, handler: (event: GameEvent<Actor>) => void): void; public once(eventName: string, handler: (event: any) => void): void { this._checkForPointerOptIn(eventName); super.once(eventName, handler); } public off(eventName: Events.exittrigger, handler?: (event: ExitTriggerEvent) => void): void; public off(eventName: Events.entertrigger, handler?: (event: EnterTriggerEvent) => void): void; /** * The **collisionstart** event is fired when a [[BodyComponent|physics body]], usually attached to an actor, * first starts colliding with another [[BodyComponent|body]], and will not fire again while in contact until * the the pair separates and collides again. * Use cases for the **collisionstart** event may be detecting when an actor has touch a surface * (like landing) or if a item has been touched and needs to be picked up. */ public off(eventName: Events.collisionstart, handler?: (event: CollisionStartEvent) => void): void; /** * The **collisionend** event is fired when two [[BodyComponent|physics bodies]] are no longer in contact. * This event will not fire again until another collision and separation. * * Use cases for the **collisionend** event might be to detect when an actor has left a surface * (like jumping) or has left an area. */ public off(eventName: Events.collisionend, handler?: (event: CollisionEndEvent) => void): void; /** * The **precollision** event is fired **every frame** where a collision pair is found and two * bodies are intersecting. * * This event is useful for building in custom collision resolution logic in Passive-Passive or * Active-Passive scenarios. For example in a breakout game you may want to tweak the angle of * ricochet of the ball depending on which side of the paddle you hit. */ public off(eventName: Events.precollision, handler?: (event: PreCollisionEvent) => void): void; /** * The **postcollision** event is fired for **every frame** where collision resolution was performed. * Collision resolution is when two bodies influence each other and cause a response like bouncing * off one another. It is only possible to have *postcollision* event in Active-Active and Active-Fixed * type collision pairs. * * Post collision would be useful if you need to know that collision resolution is happening or need to * tweak the default resolution. */ public off(eventName: Events.postcollision, handler: (event: PostCollisionEvent) => void): void; public off(eventName: Events.pointerup, handler?: (event: PointerEvent) => void): void; public off(eventName: Events.pointerdown, handler?: (event: PointerEvent) => void): void; public off(eventName: Events.pointerenter, handler?: (event: PointerEvent) => void): void; public off(eventName: Events.pointerleave, handler?: (event: PointerEvent) => void): void; public off(eventName: Events.pointermove, handler?: (event: PointerEvent) => void): void; public off(eventName: Events.pointercancel, handler?: (event: PointerEvent) => void): void; public off(eventName: Events.pointerwheel, handler?: (event: WheelEvent) => void): void; public off(eventName: Events.pointerdragstart, handler?: (event: PointerDragEvent) => void): void; public off(eventName: Events.pointerdragend, handler?: (event: PointerDragEvent) => void): void; public off(eventName: Events.pointerdragenter, handler?: (event: PointerDragEvent) => void): void; public off(eventName: Events.pointerdragleave, handler?: (event: PointerDragEvent) => void): void; public off(eventName: Events.pointerdragmove, handler?: (event: PointerDragEvent) => void): void; public off(eventName: Events.prekill, handler?: (event: PreKillEvent) => void): void; public off(eventName: Events.postkill, handler?: (event: PostKillEvent) => void): void; public off(eventName: Events.initialize, handler?: (event: Events.InitializeEvent<Actor>) => void): void; public off(eventName: Events.postupdate, handler?: (event: Events.PostUpdateEvent<Actor>) => void): void; public off(eventName: Events.preupdate, handler?: (event: Events.PreUpdateEvent<Actor>) => void): void; public off(eventName: Events.postdraw, handler?: (event: Events.PostDrawEvent) => void): void; public off(eventName: Events.predraw, handler?: (event: Events.PreDrawEvent) => void): void; public off(eventName: Events.enterviewport, handler?: (event: EnterViewPortEvent) => void): void; public off(eventName: Events.exitviewport, handler?: (event: ExitViewPortEvent) => void): void; public off(eventName: string, handler?: (event: GameEvent<Actor>) => void): void; public off(eventName: string, handler?: (event: any) => void): void { super.off(eventName, handler); } // #endregion /** * It is not recommended that internal excalibur methods be overridden, do so at your own risk. * * Internal _prekill handler for [[onPreKill]] lifecycle event * @internal */ public _prekill(_scene: Scene) { super.emit('prekill', new PreKillEvent(this)); this.onPreKill(_scene); } /** * Safe to override onPreKill lifecycle event handler. Synonymous with `.on('prekill', (evt) =>{...})` * * `onPreKill` is called directly before an actor is killed and removed from its current [[Scene]]. */ public onPreKill(_scene: Scene) { // Override me } /** * It is not recommended that internal excalibur methods be overridden, do so at your own risk. * * Internal _prekill handler for [[onPostKill]] lifecycle event * @internal */ public _postkill(_scene: Scene) { super.emit('postkill', new PostKillEvent(this)); this.onPostKill(_scene); } /** * Safe to override onPostKill lifecycle event handler. Synonymous with `.on('postkill', (evt) => {...})` * * `onPostKill` is called directly after an actor is killed and remove from its current [[Scene]]. */ public onPostKill(_scene: Scene) { // Override me } /** * If the current actor is a member of the scene, this will remove * it from the scene graph. It will no longer be drawn or updated. */ public kill() { if (this.scene) { this._prekill(this.scene); this.emit('kill', new KillEvent(this)); super.kill(); this._postkill(this.scene); } else { this.logger.warn('Cannot kill actor, it was never added to the Scene'); } } /** * If the current actor is killed, it will now not be killed. */ public unkill() { this.active = true; } /** * Indicates wether the actor has been killed. */ public isKilled(): boolean { return !this.active; } /** * Sets the current drawing of the actor to the drawing corresponding to * the key. * @param key The key of the drawing * @deprecated Use [[GraphicsComponent.show|Actor.graphics.show]] or [[GraphicsComponent.use|Actor.graphics.use]] */ public setDrawing(key: string): void; /** * Sets the current drawing of the actor to the drawing corresponding to * an `enum` key (e.g. `Animations.Left`) * @param key The `enum` key of the drawing * @deprecated Use [[GraphicsComponent.show|Actor.graphics.show]] or [[GraphicsComponent.use|Actor.graphics.use]] */ public setDrawing(key: number): void; @obsolete({ message: 'Actor.setDrawing will be removed in v0.26.0', alternateMethod: 'Use Actor.graphics.show() or Actor.graphics.use()' }) public setDrawing(key: any): void { key = key.toString(); if (this.currentDrawing !== this.frames[<string>key]) { if (this.frames[key] != null) { this.frames[key].reset(); this.currentDrawing = this.frames[key]; } else { Logger.getInstance().error(`the specified drawing key ${key} does not exist`); } } if (this.currentDrawing && this.currentDrawing instanceof Animation) { this.currentDrawing.tick(0); } } /** * Adds a whole texture as the "default" drawing. Set a drawing using [[setDrawing]]. * @deprecated Use [[GraphicsComponent.add|Actor.graphics.add]] */ public addDrawing(texture: Texture): void; /** * Adds a whole sprite as the "default" drawing. Set a drawing using [[setDrawing]]. * @deprecated Use [[GraphicsComponent.add|Actor.graphics.add]] */ public addDrawing(sprite: Sprite): void; /** * Adds a drawing to the list of available drawings for an actor. Set a drawing using [[setDrawing]]. * @param key The key to associate with a drawing for this actor * @param drawing This can be an [[Animation]], [[Sprite]], or [[Polygon]]. * @deprecated Use [[GraphicsComponent.add|Actor.graphics.add]] */ public addDrawing(key: any, drawing: Drawable): void; @obsolete({ message: 'Actor.addDrawing will be removed in v0.26.0', alternateMethod: 'Use Actor.graphics.add()' }) public addDrawing(): void { if (arguments.length === 2) { this.frames[<string>arguments[0]] = arguments[1]; if (!this.currentDrawing) { this.currentDrawing = arguments[1]; } } else { if (arguments[0] instanceof Sprite) { this.addDrawing('default', arguments[0]); } if (arguments[0] instanceof Texture) { this.addDrawing('default', arguments[0].asSprite()); } } } /** * Gets the z-index of an actor. The z-index determines the relative order an actor is drawn in. * Actors with a higher z-index are drawn on top of actors with a lower z-index */ public get z(): number { return this.get(TransformComponent).z; } /** * @deprecated Use [[Actor.z]] */ @obsolete({ message: 'Actor.getZIndex will be removed in v0.26.0', alternateMethod: 'Use Actor.transform.z or Actor.z' }) public getZIndex(): number { return this.get(TransformComponent).z; } /** * Sets the z-index of an actor and updates it in the drawing list for the scene. * The z-index determines the relative order an actor is drawn in. * Actors with a higher z-index are drawn on top of actors with a lower z-index * @param newZ new z-index to assign */ public set z(newZ: number) { this.get(TransformComponent).z = newZ; } /** * @param newIndex new z-index to assign * @deprecated Use [[Actor.z]] */ @obsolete({ message: 'Actor.setZIndex will be removed in v0.26.0', alternateMethod: 'Use Actor.transform.z or Actor.z' }) public setZIndex(newIndex: number) { this.get(TransformComponent).z = newIndex; } /** * Get the center point of an actor */ public get center(): Vector { return new Vector(this.pos.x + this.width / 2 - this.anchor.x * this.width, this.pos.y + this.height / 2 - this.anchor.y * this.height); } public get width() { return this.collider.localBounds.width * this.getGlobalScale().x; } public get height() { return this.collider.localBounds.height * this.getGlobalScale().y; } /** * Gets this actor's rotation taking into account any parent relationships * * @returns Rotation angle in radians */ public getGlobalRotation(): number { return this.get(TransformComponent).globalRotation; } /** * Gets an actor's world position taking into account parent relationships, scaling, rotation, and translation * * @returns Position in world coordinates */ public getGlobalPos(): Vector { return this.get(TransformComponent).globalPos; } /** * Gets the global scale of the Actor */ public getGlobalScale(): Vector { return this.get(TransformComponent).globalScale; } // #region Collision /** * Tests whether the x/y specified are contained in the actor * @param x X coordinate to test (in world coordinates) * @param y Y coordinate to test (in world coordinates) * @param recurse checks whether the x/y are contained in any child actors (if they exist). */ public contains(x: number, y: number, recurse: boolean = false): boolean { const point = vec(x, y); const collider = this.get(ColliderComponent); collider.update(); const geom = collider.get(); if (!geom) { return false; } const containment = geom.contains(point); if (recurse) { return ( containment || this.children.some((child: Actor) => { return child.contains(x, y, true); }) ); } return containment; } /** * Returns true if the two actor.collider's surfaces are less than or equal to the distance specified from each other * @param actor Actor to test * @param distance Distance in pixels to test */ public within(actor: Actor, distance: number): boolean { const collider = this.get(ColliderComponent); const otherCollider = actor.get(ColliderComponent); const me = collider.get(); const other = otherCollider.get(); if (me && other) { return me.getClosestLineBetween(other).getLength() <= distance; } return false; } // #endregion // #region Update /** * Called by the Engine, updates the state of the actor * @internal * @param engine The reference to the current game engine * @param delta The time elapsed since the last update in milliseconds */ public update(engine: Engine, delta: number) { this._initialize(engine); this._preupdate(engine, delta); // Tick animations const drawing = this.currentDrawing; if (drawing && drawing instanceof Animation) { drawing.tick(delta, engine.stats.currFrame.id); } // Update actor pipeline (movement, collision detection, event propagation, offscreen culling) for (const trait of this.traits) { trait.update(this, engine, delta); } this._postupdate(engine, delta); } /** * Safe to override onPreUpdate lifecycle event handler. Synonymous with `.on('preupdate', (evt) =>{...})` * * `onPreUpdate` is called directly before an actor is updated. */ public onPreUpdate(_engine: Engine, _delta: number): void { // Override me } /** * Safe to override onPostUpdate lifecycle event handler. Synonymous with `.on('postupdate', (evt) =>{...})` * * `onPostUpdate` is called directly after an actor is updated. */ public onPostUpdate(_engine: Engine, _delta: number): void { // Override me } /** * It is not recommended that internal excalibur methods be overridden, do so at your own risk. * * Internal _preupdate handler for [[onPreUpdate]] lifecycle event * @internal */ public _preupdate(engine: Engine, delta: number): void { this.emit('preupdate', new PreUpdateEvent(engine, delta, this)); this.onPreUpdate(engine, delta); } /** * It is not recommended that internal excalibur methods be overridden, do so at your own risk. * * Internal _preupdate handler for [[onPostUpdate]] lifecycle event * @internal */ public _postupdate(engine: Engine, delta: number): void { this.emit('postupdate', new PreUpdateEvent(engine, delta, this)); this.onPostUpdate(engine, delta); } // endregion // #region Drawing /** * Called by the Engine, draws the actor to the screen * @param ctx The rendering context * @param delta The time since the last draw in milliseconds * * **Warning** only works with Flags.useLegacyDrawing() enabled * @deprecated Use Actor.graphics, will be removed in v0.26.0 */ public draw(ctx: CanvasRenderingContext2D, delta: number) { // translate canvas by anchor offset ctx.save(); if (this.currentDrawing) { ctx.translate(-(this.width * this.anchor.x), -(this.height * this.anchor.y)); this._predraw(ctx, delta); const drawing = this.currentDrawing; // See https://github.com/excaliburjs/Excalibur/pull/619 for discussion on this formula const offsetX = (this.width - drawing.width * drawing.scale.x) * this.anchor.x; const offsetY = (this.height - drawing.height * drawing.scale.y) * this.anchor.y; this.currentDrawing.draw({ ctx, x: offsetX, y: offsetY, opacity: this.graphics.opacity }); } else { this._predraw(ctx, delta); if (this.color && this.collider) { // update collider geometry based on transform const collider = this.get(ColliderComponent); collider.update(); if (collider && !collider.bounds.hasZeroDimensions()) { // Colliders are already shifted by anchor, unshift ctx.globalAlpha = this.graphics.opacity; collider.get()?.draw(ctx, this.color, vec(0, 0)); } } } ctx.restore(); this._postdraw(ctx, delta); } /** * Safe to override onPreDraw lifecycle event handler. Synonymous with `.on('predraw', (evt) =>{...})` * * `onPreDraw` is called directly before an actor is drawn, but after local transforms are made. * * **Warning** only works with Flags.useLegacyDrawing() enabled * @deprecated Use Actor.graphics.onPostDraw, will be removed in v0.26.0 */ public onPreDraw(_ctx: CanvasRenderingContext2D, _delta: number): void { // Override me } /** * Safe to override onPostDraw lifecycle event handler. Synonymous with `.on('postdraw', (evt) =>{...})` * * `onPostDraw` is called directly after an actor is drawn, and before local transforms are removed. * * **Warning** only works with Flags.useLegacyDrawing() enabled * @deprecated Use Actor.graphics.onPostDraw, will be removed in v0.26.0 */ public onPostDraw(_ctx: CanvasRenderingContext2D, _delta: number): void { // Override me } /** * It is not recommended that internal excalibur methods be overridden, do so at your own risk. * * Internal _predraw handler for [[onPreDraw]] lifecycle event * * **Warning** only works with Flags.useLegacyDrawing() enabled * @deprecated Use Actor.graphics.onPreDraw, will be removed in v0.26.0 * @internal */ public _predraw(ctx: CanvasRenderingContext2D, delta: number): void { this.emit('predraw', new PreDrawEvent(ctx, delta, this)); this.onPreDraw(ctx, delta); } /** * It is not recommended that internal excalibur methods be overridden, do so at your own risk. * * Internal _postdraw handler for [[onPostDraw]] lifecycle event * * **Warning** only works with Flags.useLegacyDrawing() enabled * @deprecated Use Actor.graphics.onPostDraw, will be removed in v0.26.0 * @internal */ public _postdraw(ctx: CanvasRenderingContext2D, delta: number): void { this.emit('postdraw', new PreDrawEvent(ctx, delta, this)); this.onPostDraw(ctx, delta); } /** * Called by the Engine, draws the actors debugging to the screen * @param ctx The rendering context * * * **Warning** only works with Flags.useLegacyDrawing() enabled * @deprecated Use Actor.graphics.onPostDraw, will be removed in v0.26.0 * @internal */ /* istanbul ignore next */ public debugDraw(_ctx: CanvasRenderingContext2D) { // pass } // #endregion }
the_stack
import * as assert from "assert"; import { isNode, URLBuilder, URLQuery } from "@azure/ms-rest-js"; import { Aborter } from "../lib/Aborter"; import { BlobURL } from "../lib/BlobURL"; import { BlockBlobURL } from "../lib/BlockBlobURL"; import { ContainerURL } from "../lib/ContainerURL"; import { bodyToString, getBSU, getUniqueName, sleep } from "./utils"; describe("BlobURL", () => { const serviceURL = getBSU(); let containerName: string = getUniqueName("container"); let containerURL = ContainerURL.fromServiceURL(serviceURL, containerName); let blobName: string = getUniqueName("blob"); let blobURL = BlobURL.fromContainerURL(containerURL, blobName); let blockBlobURL = BlockBlobURL.fromBlobURL(blobURL); const content = "Hello World"; beforeEach(async () => { containerName = getUniqueName("container"); containerURL = ContainerURL.fromServiceURL(serviceURL, containerName); await containerURL.create(Aborter.none); blobName = getUniqueName("blob"); blobURL = BlobURL.fromContainerURL(containerURL, blobName); blockBlobURL = BlockBlobURL.fromBlobURL(blobURL); await blockBlobURL.upload(Aborter.none, content, content.length); }); afterEach(async () => { await containerURL.delete(Aborter.none); }); it("download with with default parameters", async () => { const result = await blobURL.download(Aborter.none, 0); assert.deepStrictEqual(await bodyToString(result, content.length), content); }); it("download all parameters set", async () => { const result = await blobURL.download(Aborter.none, 0, 1, { rangeGetContentMD5: true }); assert.deepStrictEqual(await bodyToString(result, 1), content[0]); }); it("setMetadata with new metadata set", async () => { const metadata = { a: "a", b: "b" }; await blobURL.setMetadata(Aborter.none, metadata); const result = await blobURL.getProperties(Aborter.none); assert.deepStrictEqual(result.metadata, metadata); }); it("setMetadata with cleaning up metadata", async () => { const metadata = { a: "a", b: "b" }; await blobURL.setMetadata(Aborter.none, metadata); const result = await blobURL.getProperties(Aborter.none); assert.deepStrictEqual(result.metadata, metadata); await blobURL.setMetadata(Aborter.none); const result2 = await blobURL.getProperties(Aborter.none); assert.deepStrictEqual(result2.metadata, {}); }); it("setHTTPHeaders with default parameters", async () => { await blobURL.setHTTPHeaders(Aborter.none, {}); const result = await blobURL.getProperties(Aborter.none); assert.deepStrictEqual(result.blobType, "BlockBlob"); assert.ok(result.lastModified); assert.deepStrictEqual(result.metadata, {}); assert.ok(!result.cacheControl); assert.ok(!result.contentType); assert.ok(!result.contentMD5); assert.ok(!result.contentEncoding); assert.ok(!result.contentLanguage); assert.ok(!result.contentDisposition); }); it("setHTTPHeaders with all parameters set", async () => { const headers = { blobCacheControl: "blobCacheControl", blobContentDisposition: "blobContentDisposition", blobContentEncoding: "blobContentEncoding", blobContentLanguage: "blobContentLanguage", blobContentMD5: isNode ? Buffer.from([1, 2, 3, 4]) : new Uint8Array([1, 2, 3, 4]), blobContentType: "blobContentType" }; await blobURL.setHTTPHeaders(Aborter.none, headers); const result = await blobURL.getProperties(Aborter.none); assert.ok(result.date); assert.deepStrictEqual(result.blobType, "BlockBlob"); assert.ok(result.lastModified); assert.deepStrictEqual(result.metadata, {}); assert.deepStrictEqual(result.cacheControl, headers.blobCacheControl); assert.deepStrictEqual(result.contentType, headers.blobContentType); assert.deepStrictEqual(result.contentMD5, headers.blobContentMD5); assert.deepStrictEqual(result.contentEncoding, headers.blobContentEncoding); assert.deepStrictEqual(result.contentLanguage, headers.blobContentLanguage); assert.deepStrictEqual( result.contentDisposition, headers.blobContentDisposition ); }); it("acquireLease", async () => { const guid = "ca761232ed4211cebacd00aa0057b223"; const duration = 30; await blobURL.acquireLease(Aborter.none, guid, duration); const result = await blobURL.getProperties(Aborter.none); assert.equal(result.leaseDuration, "fixed"); assert.equal(result.leaseState, "leased"); assert.equal(result.leaseStatus, "locked"); await blobURL.releaseLease(Aborter.none, guid); }); it("releaseLease", async () => { const guid = "ca761232ed4211cebacd00aa0057b223"; const duration = -1; await blobURL.acquireLease(Aborter.none, guid, duration); const result = await blobURL.getProperties(Aborter.none); assert.equal(result.leaseDuration, "infinite"); assert.equal(result.leaseState, "leased"); assert.equal(result.leaseStatus, "locked"); await blobURL.releaseLease(Aborter.none, guid); }); it("renewLease", async () => { const guid = "ca761232ed4211cebacd00aa0057b223"; const duration = 15; await blobURL.acquireLease(Aborter.none, guid, duration); const result = await blobURL.getProperties(Aborter.none); assert.equal(result.leaseDuration, "fixed"); assert.equal(result.leaseState, "leased"); assert.equal(result.leaseStatus, "locked"); await sleep(16 * 1000); const result2 = await blobURL.getProperties(Aborter.none); assert.ok(!result2.leaseDuration); assert.equal(result2.leaseState, "expired"); assert.equal(result2.leaseStatus, "unlocked"); await blobURL.renewLease(Aborter.none, guid); const result3 = await blobURL.getProperties(Aborter.none); assert.equal(result3.leaseDuration, "fixed"); assert.equal(result3.leaseState, "leased"); assert.equal(result3.leaseStatus, "locked"); await blobURL.releaseLease(Aborter.none, guid); }); it("changeLease", async () => { const guid = "ca761232ed4211cebacd00aa0057b223"; const duration = 15; await blobURL.acquireLease(Aborter.none, guid, duration); const result = await blobURL.getProperties(Aborter.none); assert.equal(result.leaseDuration, "fixed"); assert.equal(result.leaseState, "leased"); assert.equal(result.leaseStatus, "locked"); const newGuid = "3c7e72ebb4304526bc53d8ecef03798f"; await blobURL.changeLease(Aborter.none, guid, newGuid); await blobURL.getProperties(Aborter.none); await blobURL.releaseLease(Aborter.none, newGuid); }); it("breakLease", async () => { const guid = "ca761232ed4211cebacd00aa0057b223"; const duration = 15; await blobURL.acquireLease(Aborter.none, guid, duration); const result = await blobURL.getProperties(Aborter.none); assert.equal(result.leaseDuration, "fixed"); assert.equal(result.leaseState, "leased"); assert.equal(result.leaseStatus, "locked"); await blobURL.breakLease(Aborter.none, 3); const result2 = await blobURL.getProperties(Aborter.none); assert.ok(!result2.leaseDuration); assert.equal(result2.leaseState, "breaking"); assert.equal(result2.leaseStatus, "locked"); await sleep(3 * 1000); const result3 = await blobURL.getProperties(Aborter.none); assert.ok(!result3.leaseDuration); assert.equal(result3.leaseState, "broken"); assert.equal(result3.leaseStatus, "unlocked"); }); it("delete", async () => { await blobURL.delete(Aborter.none); }); // The following code illustrates deleting a snapshot after creating one it("delete snapshot", async () => { const result = await blobURL.createSnapshot(Aborter.none); assert.ok(result.snapshot); const blobSnapshotURL = blobURL.withSnapshot(result.snapshot!); await blobSnapshotURL.getProperties(Aborter.none); await blobSnapshotURL.delete(Aborter.none); await blobURL.delete(Aborter.none); const result2 = await containerURL.listBlobFlatSegment( Aborter.none, undefined, { include: ["snapshots"] } ); // Verify that the snapshot is deleted assert.equal(result2.segment.blobItems!.length, 0); }); it("createSnapshot", async () => { const result = await blobURL.createSnapshot(Aborter.none); assert.ok(result.snapshot); const blobSnapshotURL = blobURL.withSnapshot(result.snapshot!); await blobSnapshotURL.getProperties(Aborter.none); const result3 = await containerURL.listBlobFlatSegment( Aborter.none, undefined, { include: ["snapshots"] } ); // As a snapshot doesn't have leaseStatus and leaseState properties but origin blob has, // let assign them to undefined both for other properties' easy comparison // tslint:disable-next-line:max-line-length result3.segment.blobItems![0].properties.leaseState = result3.segment.blobItems![1].properties.leaseState = undefined; // tslint:disable-next-line:max-line-length result3.segment.blobItems![0].properties.leaseStatus = result3.segment.blobItems![1].properties.leaseStatus = undefined; // tslint:disable-next-line:max-line-length result3.segment.blobItems![0].properties.accessTier = result3.segment.blobItems![1].properties.accessTier = undefined; // tslint:disable-next-line:max-line-length result3.segment.blobItems![0].properties.accessTierInferred = result3.segment.blobItems![1].properties.accessTierInferred = undefined; assert.deepStrictEqual( result3.segment.blobItems![0].properties, result3.segment.blobItems![1].properties ); assert.ok( result3.segment.blobItems![0].snapshot || result3.segment.blobItems![1].snapshot ); }); it("undelete", async () => { const properties = await serviceURL.getProperties(Aborter.none); if (!properties.deleteRetentionPolicy!.enabled) { await serviceURL.setProperties(Aborter.none, { deleteRetentionPolicy: { days: 7, enabled: true } }); await sleep(15 * 1000); } await blobURL.delete(Aborter.none); const result = await containerURL.listBlobFlatSegment( Aborter.none, undefined, { include: ["deleted"] } ); assert.ok(result.segment.blobItems![0].deleted); await blobURL.undelete(Aborter.none); const result2 = await containerURL.listBlobFlatSegment( Aborter.none, undefined, { include: ["deleted"] } ); assert.ok(!result2.segment.blobItems![0].deleted); }); it("startCopyFromURL", async () => { const newBlobURL = BlobURL.fromContainerURL( containerURL, getUniqueName("copiedblob") ); const result = await newBlobURL.startCopyFromURL(Aborter.none, blobURL.url); assert.ok(result.copyId); const properties1 = await blobURL.getProperties(Aborter.none); const properties2 = await newBlobURL.getProperties(Aborter.none); assert.deepStrictEqual(properties1.contentMD5, properties2.contentMD5); assert.deepStrictEqual(properties2.copyId, result.copyId); // A service feature is being rolling out which will sanitize the sig field // so we remove it before comparing urls. assert.ok(properties2.copySource, "Expecting valid 'properties2.copySource"); const sanitizedActualUrl = URLBuilder.parse(properties2.copySource!); const sanitizedQuery = URLQuery.parse(sanitizedActualUrl.getQuery()!); sanitizedQuery.set("sig", undefined); sanitizedActualUrl.setQuery(sanitizedQuery.toString()); const sanitizedExpectedUrl = URLBuilder.parse(blobURL.url); const sanitizedQuery2 = URLQuery.parse(sanitizedActualUrl.getQuery()!); sanitizedQuery2.set("sig", undefined); sanitizedExpectedUrl.setQuery(sanitizedQuery.toString()); assert.deepStrictEqual( sanitizedActualUrl.toString(), sanitizedExpectedUrl.toString(), "copySource does not match original source" ); }); it("abortCopyFromURL should failed for a completed copy operation", async () => { const newBlobURL = BlobURL.fromContainerURL( containerURL, getUniqueName("copiedblob") ); const result = await newBlobURL.startCopyFromURL(Aborter.none, blobURL.url); assert.ok(result.copyId); sleep(1 * 1000); try { await newBlobURL.abortCopyFromURL(Aborter.none, result.copyId!); assert.fail( "AbortCopyFromURL should be failed and throw exception for an completed copy operation." ); } catch (err) { assert.ok(true); } }); it("setTier set default to cool", async () => { await blockBlobURL.setTier(Aborter.none, "Cool"); const properties = await blockBlobURL.getProperties(Aborter.none); assert.equal(properties.accessTier!.toLowerCase(), "cool"); }); it("setTier set archive to hot", async () => { await blockBlobURL.setTier(Aborter.none, "Archive"); let properties = await blockBlobURL.getProperties(Aborter.none); assert.equal(properties.accessTier!.toLowerCase(), "archive"); await blockBlobURL.setTier(Aborter.none, "Hot"); properties = await blockBlobURL.getProperties(Aborter.none); if (properties.archiveStatus) { assert.equal( properties.archiveStatus.toLowerCase(), "rehydrate-pending-to-hot" ); } }); });
the_stack
import { CommandOptions, CommandPermissions, LibTextableChannel, LibMember, LibMessage, Command, LibGuild, LibUser, LIBRARY_TYPES, LOGGER_TYPES, DB_TYPES, Utils, ALogger, ADBProvider, AxonConfig, GuildConfig, User, Member, Message, Channel, Guild, Resolver, Embed, COMMAND_EXECUTION_TYPES, LibAllowedMentions, } from '../'; // @ts-ignore import * as djs from 'discord.js'; // @ts-ignore import * as Eris from 'eris'; interface ModuleInfo { /** * The module name */ name: string; /** * The module description */ description: string; /** * The module category */ category?: string; } interface ModuleData { /** * The module label */ label?: string; /** * Whether the module is enabled or not */ enabled?: boolean; /** * Whether the module can be disabled in a server or not */ serverBypass?: boolean; info?: ModuleInfo; /** * The default options for all commands in this module */ options?: CommandOptions; /** * The default poermissions for all commands in this module */ permissions?: CommandPermissions; } interface AxonJSON { id: string; prefix: string; createdAt: string; updatedAt: string; bannedGuilds: string[]; bannedUsers: string[]; } interface GuildJSON { guildID: string; prefixes: string[]; modules: []; commands: []; eventListeners: []; createdAt: string; updatedAt: string; ignoredUsers: string[]; ignoredRoles: string[]; ignoredChannels: string[]; modOnly: false; modRoles: string[]; modUsers: string[]; } interface AConfig { id?: string; prefix?: string; createdAt?: Date; updatedAt?: Date; /** * Array of users that can't use bot commands */ bannedUsers?: string[]; /** * Array of guilds where bot commands cannot be used */ bannedGuilds?: string[]; } interface AxonConfigRaw extends AConfig { id: string; prefix: string; createdAt: Date; updatedAt: Date; bannedUsers: string[]; bannedGuilds: string[]; } interface GConfig { /** * Guild ID */ guildID?: string; /** * Array of prefixes */ prefixes?: string[]; /** * Creation of the guild Config */ createdAt?: Date; /** * Last update of the guild Config */ updatedAt?: Date; /** * Guild disabled modules: Array of modules labels */ modules?: string[]; /** * Guild disabled commands: Array of commands labels */ commands?: string[]; /** * Guild disabled listeners: Array of listeners labels */ eventListeners?: string[]; /** * Users that cannot use commands in this guild: Users ids */ ignoredUsers?: string[]; /** * Roles that cannot use commands in this guild: Roles ids */ ignoredRoles?: string[]; /** * Channels where commands cannot be used in this guild: Channels ids */ ignoredChannels?: string[]; /** * Whether the guild accept commands from only mods+ or everyone */ modOnly?: boolean; /** * Roles able to execute mod commands: Roles ids */ modRoles?: string[]; /** * Users able to execute mod commands: Users ids */ modUsers?: string[]; } interface GuildConfigRaw extends GConfig { guildID: string; prefixes: string[]; createdAt: Date; updatedAt: Date; modules: string[]; commands: string[]; listeners: string[]; ignoredUsers: string[]; ignoredRoles: string[]; ignoredChannels: string[]; modOnly: boolean; modRoles: string[]; modUsers: string[]; } interface CommandInfo { /** * Command authors */ owners?: string[]; /** * Command description */ description?: string; /** * Array of command examples */ examples?: string[]; /** * Command usage */ usage?: string; /** * Full command name */ name?: string; } interface ACommandOptions { /** * Whether to allow executing this command outside of guilds */ guildOnly?: boolean; /** * Minimum arguments required to execute the command */ argsMin?: number; /** * What the invalid usage message should be */ invalidUsageMessage?: string; /** * Whether to trigger the help command on invalid usage (not enough arguments) */ sendUsageMessage?: boolean; /** * What the invalid permission message should be */ invalidPermissionMessage?: ( (channel: LibTextableChannel, member: LibMember) => string) | null; /** * Whether to trigger an error message on invalid permission (bot / user / custom etc) */ sendPermissionMessage?: boolean; /** * What the invalid permission message deletion timeout should be */ invalidPermissionMessageTimeout?: number; /** * Whether to delete the command input after trigger */ deleteCommand?: boolean; /** * Whether to hide this command from help command (general / subcommands) */ hidden?: boolean; /** * Cooldown between each usage of this command for a specific user (in ms) */ cooldown?: number; } interface CommandPerms { /** * Discord permissions that the bot needs to have in order to execute the command */ bot?: string[]; /** * Axoncore server moderator */ serverMod?: boolean; /** * Discord server manager (manageServer) */ serverManager?: boolean; /** * Discord server administrator (administrator) */ serverAdmin?: boolean; /** * Discord server owner */ serverOwner?: boolean; /** * Discord permissions for the author */ author?: { /** * Discord permissions that the author needs to have in order to execute the command */ needed?: string[]; /** * Discord permissions that will allow the author to execute the command no matter what */ bypass?: string[]; }; /** * User IDs */ users?: { /** * Discord user ids that the user needs to have in order to execute the command */ needed?: string[]; /** * Discord user ids that will allow the user to execute the command no matter what */ bypass?: string[]; }; /** * Role IDs for the user */ roles?: { /** * Discord role ids that the user needs to have in order to execute the command */ needed?: string[]; /** * Discord role ids that will allow the user to execute the command no matter what */ bypass?: string[]; }; /** * Channel IDs */ channels?: { /** * Discord channel ids that the user needs to have in order to execute the command */ needed?: string[]; /** * Discord channel ids that will allow the user to execute the command no matter what */ bypass?: string[]; }; /** * Guild IDs */ guilds?: { /** * Discord guild ids that the user needed to have in order to execute the command */ needed?: string[]; /** * Discord guild ids that will allow the user to execute the command no matter what */ bypass?: string[]; }; /** * AxonCore staff */ staff?: { /** * Axoncore staff ids that the user needs to have in order to execute the command */ needed?: string[]; /** * Axoncore staff ids that will allow the user to execute the command no matter what */ bypass?: string[]; }; /** * Custom function that returns a boolean. True will let the command execute, False will prevent the command from executing */ custom?: (i: LibMessage) => boolean; } interface CommandData { /** * Command label (name/id) */ label?: string; /** * Array of commands aliases (including the command label) */ aliases?: string[]; /** * Whether the command HAS subcommands */ hasSubcmd?: boolean; /** * Whether the command is enabled */ enabled?: boolean; /** * Whether the command can be disabled */ serverBypass?: boolean; /** * Array of subcommand objects (deleted after init) */ subcmds?: (new (...args: any[] ) => Command)[] | null; /** * Default info about the command */ info?: CommandInfo; /** * Options Object for the command (manage all command options) */ options?: CommandOptions; /** * Permissions Object for the command (manage all command permissions) */ permissions?: CommandPermissions; } interface AxonTemplate { embeds: {[key: string]: number;}; emotes: {[key: string]: string;}; [key: string]: {[key: string]: unknown;}; } interface ListenerInfo { /** * Listener owners/authors */ owners?: string[]; /** * Listener description */ description?: string; } interface ListenerData { /** * The Discord event name */ eventName?: string; /** * The listener name */ label?: string; /** * Whether to load this event on start up or not */ load?: boolean; /** * Whether the event is enabled or not */ enabled?: boolean; /** * Can the event be disabled? */ serverBypass?: boolean; /** * Default infos about the event */ info?: ListenerInfo; } interface APIAxonMSGCont { embed?: EmbedData; content?: string; } type AxonMSGCont = APIAxonMSGCont | string; interface AxonMSGOpt { /** * Whether to delete the message or not */ delete?: boolean; /** * Custom allowed mentions object */ allowedMentions?: LibAllowedMentions; /** * Delay after which the message will be deleted */ delay?: number; } interface PermissionObject { CREATE_INSTANT_INVITE?: boolean; KICK_MEMBERS?: boolean; BAN_MEMBERS?: boolean; ADMINISTRATOR?: boolean; MANAGE_CHANNELS?: boolean; MANAGE_GUILD?: boolean; ADD_REACTIONS?: boolean; VIEW_AUDIT_LOG?: boolean; PRIORITY_SPEAKER?: boolean; STREAM?: boolean; VIEW_CHANNEL?: boolean; SEND_MESSAGES?: boolean; SEND_TTS_MESSAGES?: boolean; MANAGE_MESSAGES?: boolean; EMBED_LINKS?: boolean; ATTACH_FILES?: boolean; READ_MESSAGE_HISTORY?: boolean; MENTION_EVERYONE?: boolean; USE_EXTERNAL_EMOJIS?: boolean; VIEW_GUILD_ANALYTICS?: boolean; CONNECT?: boolean; SPEAK?: boolean; MUTE_MEMBERS?: boolean; DEAFEN_MEMBERS?: boolean; MOVE_MEMBERS?: boolean; USE_VAD?: boolean; CHANGE_NICKNAME?: boolean; MANAGE_NICKNAMES?: boolean; MANAGE_ROLES?: boolean; MANAGE_WEBHOOKS?: boolean; MANAGE_EMOJIS?: boolean; } interface Ctx { guild: LibGuild|string; cmd: string; user: LibUser|string; } interface EmbedFields { name: string; value: string; inline?: boolean; } interface EmbedAuthor { name: string; url?: string; icon_url?: string; } interface EmbedThumbnail { url: string; } interface EmbedImage { url: string; } interface EmbedFooter { text: string; icon_url?: string; } interface EmbedData { title?: string; url?: string; description?: string; color?: number; author?: EmbedAuthor; thumbnail?: EmbedThumbnail; fields?: EmbedFields[]; image?: EmbedImage; footer?: EmbedFooter; timestamp?: Date; } interface PromptOptions { /** * An array of strings allow to pass as the prompt */ allowed?: string[]; /** * Whether or not the message content can contain allowed or must match allowed. */ wildcard?: boolean; /** * Makes it so the prompt is case insensitive, returns the message lowercase content. */ caseSensitive?: boolean; /** * Whether or not you want the prompt to be deleted */ deletePrompt?: boolean; /** * Whether or not you want a message to be sent when invalid */ sendInvalid?: boolean; /** * The message to send when a prompt is invalid */ invalidMessage?: string; /** * The time in milliseconds to wait before deleting the invalid message */ deleteInvalidMessage?: boolean | number; /** * The time to wait for the prompt to timeout */ timeoutTime?: number; /** * Whether or not you want a message to be sent when timeout */ sendTimeout?: boolean; /** * The message to send when the prompt times out. */ timeoutMessage?: string; /** * The time to wait in milliseconds before deleting the timeout message */ deleteTimeoutMsg?: boolean | number; /** * Whether or not to resend when the prompt got a invalid returned message, does not send invalid message */ resendWhenInvalid?: boolean; } interface PromptOptionsData extends PromptOptions { allowed: string[]; wildcard: boolean; caseSensitive: boolean; deletePrompt: boolean; sendInvalid: boolean; invalidMessage: string; deleteInvalidMessage: boolean|number; timeoutTime: number; sendTimeout: boolean; timeoutMessage: string; deleteTimeoutMsg: boolean|number; resendWhenInvalid: boolean; } interface CollectorOptions { /** * The time before the collector times out in milliseconds */ timeout?: number; /** * The amount of messages to collect before automatically ending */ count?: number; /** * Whether or not to ignore bots */ ignoreBots?: boolean; /** * The user id to listen for (listens to all messages if not specified) */ userID?: string; /** * Whether or not to return messages with lowercase content. Default: content unchanged */ caseInsensitive?: boolean; } interface ReactionCollectorOptions extends CollectorOptions { emojis: string[]; } interface AxonOptionsSettings { /** * Default lang for the bot */ lang?: string; /** * Whether to run the bot in debugMode (additional info) */ debugMode?: boolean; /** * Library type */ library?: LIBRARY_TYPES; /** * Logger type */ logger?: LOGGER_TYPES; /** * DB type */ db?: DB_TYPES; /** * Max amount of guildConfigs cached at the same time (LRUCache) */ guildConfigCache?: number; } interface AOptionsSettings extends AxonOptionsSettings { lang: string; debugMode: boolean; library: LIBRARY_TYPES; logger: LOGGER_TYPES; db: DB_TYPES; guildConfigCache: number; } interface AxonLanguageResponse { [p: string]: string; } interface DefaultLanguageResponse extends AxonLanguageResponse { ERR_BOT_PERM: string; ERR_CALLER_PERM: string; ERR_DESTINATION_PERM: string; ERR_COOLDOWN: string; ERR_GENERAL: string; } interface Languages<L extends AxonLanguageResponse = DefaultLanguageResponse> { [language: string]: L; } interface AxonOptionsBase { token?: string; /** * Bot prefixes */ prefixes?: AxonOptionsPrefixes; /** * Bot settings */ settings?: AxonOptionsSettings; /** * Translation file */ lang?: Languages; /** * Custom function that will log a custom logo on startup */ logo?: () => void; /** * General info about the bot */ info?: AxonOptionsInfo; /** * The bot staff */ staff?: AxonOptionsStaff; /** * Template information (colors / formatting / emojis) */ template?: AxonTemplate; /** * Custom configs that can be provided */ custom?: object | null; } interface WebhookConfig { id: string; token: string; } interface Webhooks { FATAL: WebhookConfig; ERROR: WebhookConfig; WARN: WebhookConfig; DEBUG: WebhookConfig; NOTICE: WebhookConfig; INFO: WebhookConfig; VERBOSE: WebhookConfig; [key: string]: WebhookConfig; } interface AxonOptionsPrefixes { /** General Bot prefix */ general: string; /** Admin prefix */ admin: string; /** Owner prefix */ owner: string; } interface AxonOptionsInfo { /** The application name */ name: string; /** The application description */ description: string; /** The application version */ version: string; [key: string]: string; } interface AxonOptionsStaff { owners: {name: string; id: string;}[]; admins: {name: string; id: string;}[]; [key: string]: {name: string; id: string;}[]; } interface AxonOptionsExtensions { /** Custom utils. Needs to be an instance of AxonCore.Utils */ utils?: new (...args: any[] ) => Utils; /** Custom logger */ logger?: ALogger; /** DBProvider. Needs to be an instance of DBProvider */ DBProvider?: new (...args: any[] ) => ADBProvider; /** Path to use as default location for usage of the JSONProvider */ DBLocation?: string; /** Custom AxonConfig object to use instead of default AxonConfig */ axonConfig?: new (...args: any[] ) => AxonConfig; /** Custom GuildConfig object to use instead of default GuildConfig */ guildConfig?: new (...args: any[] ) => GuildConfig; } interface AxonConfs { /** Webhooks configs with all webhooks id and tokens */ webhooks: Webhooks; /** Template config */ template: AxonTemplate; /** Custom config object optionally passed via AxonOptions */ custom: object | null; } interface AxonParams { /** Enable to show commands latency and debug informations */ debugMode: boolean; /** Default bot prefixes */ prefixes: string[]; /** Admins prefix : override perms/cd except Owner */ ownerPrefix: string; /** Owner prefix : override perms/cd */ adminPrefix: string; /** Default lang for the bot */ lang: string; /** Max amount of guildConfigs cached at the same time (LRUCache) */ guildConfigCache: number; } interface Info { /** Bot name */ name: string; /** Bot description */ description: string; /** Bot version */ version: string; /** Bot owners (array of names) */ owners: string[]; } interface AxonInfo { version: string; author: string; github: string; } interface AxonStaffIDs { /** Array of user IDs with BotOwner permissions */ owners: string[]; /** Array of user IDs with BotAdmin permissions */ admins: string[]; /** Any other names you want */ [key: string]: string[]; } interface LibraryInterfaceStructs { User: new (...args: any[] ) => User; Member: new (...args: any[] ) => Member; Message: new (...args: any[] ) => Message; Channel: new (...args: any[] ) => Channel; Guild: new (...args: any[] ) => Guild; Resolver: new (...args: any[] ) => Resolver; } interface PresenceGame { name?: string; url?: string; type?: string | number; } interface RawAttachment { url: string; filename: string; id: string; size: number; proxy_url: string; height?: number; width?: number; } interface RawUser { id: string; username: string; avatar: string; discriminator: string; } interface WebhookResponse { id: string; type: number; content: string; channel_id: string; author: { bot: true; id: string; username: string; avatar: string | null; discriminator: '0000'; }; attachments: RawAttachment[]; embeds: EmbedData[]; mentions: RawUser[]; mention_roles: string[]; pinned: false; mention_everyone: boolean; tts: boolean; timestamp: string; edited_timestamp: null; flags: number; nonce: null; webhook_id: string; } interface DjsContent { content?: string; tts?: boolean; nonce?: string; embed?: Embed | djs.MessageEmbed | EmbedData; allowedMentions?: djs.MessageMentionOptions; files?: (djs.FileOptions | djs.BufferResolvable | djs.MessageAttachment)[]; code?: string | boolean; split?: boolean | djs.SplitOptions; reply?: djs.UserResolvable; } interface DjsWebhookContent extends DjsContent { username?: string; avatarURL?: string; embed?: undefined; embeds?: (Embed | djs.MessageEmbed | EmbedData)[]; reply?: undefined; } interface DjsPresenceGame extends PresenceGame { type: djs.ActivityType | 0 | 1 | 2 | 3 | 4; } interface ErisContent { content?: string; tts?: boolean; allowedMentions?: Eris.AllowedMentions; embed?: Embed | EmbedData; file: Eris.MessageFile | Eris.MessageFile[]; } interface ErisWebhookContent extends ErisContent { embed?: undefined; embeds?: (Embed | EmbedData)[]; username?: string; avatarURL?: string; wait?: boolean; } interface ErisPresenceGame extends PresenceGame { type: 0 | 1 | 2 | 3 | 4; } interface CommandEnvironmentBase<T extends LibTextableChannel = LibTextableChannel> { /** The message object from the lib */ msg: LibMessage<T>; /** The array of arguments */ args: string[]; /** The prefix used for this command */ prefix: string; command: Command|string; /** The GuildConfig data-structure with all DB saved settings */ guildConfig: GuildConfig; /** Execution type: admin, owner, regular */ executionType: COMMAND_EXECUTION_TYPES; } interface CommandEnvironmentProps extends CommandEnvironmentBase { /** The full label of the command being executed */ command: string; } interface CommandEnvironmentParams extends CommandEnvironmentBase { /** The command object */ command: Command; } interface CollectorContainer<T> { id: string; collected: Map<string, T>; options: object; resolve<U>(value: U | PromiseLike<U>): Promise<U>; resolve(): Promise<void>; reject<U = never>(reason?: any): Promise<U>; } interface Timeout { id: string; timeout: number; } interface ExtentionInitReturn { Utils: new (...args: any[] ) => Utils; DBProvider: new (...args: any[] ) => ADBProvider; AxonConfig: new (...args: any[] ) => AxonConfig; GuildConfig: new (...args: any[] ) => GuildConfig; DBLocation: string; } export { ModuleInfo, ModuleData, AxonJSON, GuildJSON, AConfig, AxonConfigRaw, GConfig, GuildConfigRaw, CommandInfo, ACommandOptions, CommandPerms, CommandData, AxonTemplate, ListenerInfo, ListenerData, APIAxonMSGCont, AxonMSGCont, AxonMSGOpt, PermissionObject, Ctx, EmbedFields, EmbedAuthor, EmbedThumbnail, EmbedImage, EmbedFooter, EmbedData, PromptOptions, PromptOptionsData, CollectorOptions, ReactionCollectorOptions, AxonOptionsSettings, AOptionsSettings, AxonLanguageResponse, DefaultLanguageResponse, Languages, AxonOptionsBase, WebhookConfig, Webhooks, AxonOptionsPrefixes, AxonOptionsInfo, AxonOptionsStaff, AxonOptionsExtensions, AxonConfs, AxonParams, Info, AxonInfo, AxonStaffIDs, LibraryInterfaceStructs, PresenceGame, RawAttachment, RawUser, WebhookResponse, DjsContent, DjsWebhookContent, DjsPresenceGame, ErisContent, ErisWebhookContent, ErisPresenceGame, CommandEnvironmentProps, CommandEnvironmentParams, CollectorContainer, Timeout, ExtentionInitReturn, };
the_stack
* @module node-opcua-address-space */ import { assert } from "node-opcua-assert"; import { NodeClass } from "node-opcua-data-model"; import { StatusCodes } from "node-opcua-status-code"; import { CallMethodResultOptions } from "node-opcua-types"; import { lowerFirstLetter } from "node-opcua-utils"; import { VariantLike, DataType } from "node-opcua-variant"; import { UAFolder, UAAnalogItem } from "node-opcua-nodeset-ua"; import { AddressSpace, BaseNode, InstantiateObjectOptions, Namespace, UATransitionEventType, UAMethod, UAObject, UAObjectType, UAReferenceType, UAVariable, promoteToStateMachine, ISessionContext, UAProgramStateMachineEx } from ".."; import { UAStateMachineImpl } from "../src/state_machine/finite_state_machine"; export interface FlowToReference extends UAReferenceType {} export interface HotFlowToReference extends UAReferenceType {} export interface SignalToReference extends UAReferenceType {} export interface BoilerHaltedEventType extends UATransitionEventType {} export interface CustomControllerB { input1: UAVariable; input2: UAVariable; input3: UAVariable; controlOut: UAVariable; // conflict here ! description: UAVariable; } export interface CustomControllerType extends CustomControllerB, UAObjectType {} export interface CustomController extends CustomControllerB, UAObject {} export interface GenericSensorB { output: UAAnalogItem<number, DataType.Double>; } export interface GenericSensorType extends GenericSensorB, UAObjectType {} export interface GenericSensor extends GenericSensorB, UAObject {} export interface GenericControllerB { controlOut: UAVariable; measurement: UAVariable; setPoint: UAVariable; } export interface GenericControllerType extends GenericControllerB, UAObjectType {} export interface GenericController extends GenericControllerB, UAObject {} export interface FlowControllerType extends GenericControllerType {} export interface FlowController extends GenericController {} export interface LevelControllerType extends GenericControllerType {} export interface LevelController extends GenericController {} export interface FlowTransmitterType extends GenericSensorType {} export interface FlowTransmitter extends GenericSensor {} export interface LevelIndicatorType extends GenericSensorType {} export interface LevelIndicator extends GenericSensor {} export interface GenericActuatorType extends UAObjectType { input: UAAnalogItem<number, DataType.Double>; } export interface GenericActuator extends UAObject { input: UAAnalogItem<number, DataType.Double>; } export interface ValveType extends GenericActuatorType {} export interface Valve extends GenericActuator {} export interface BoilerInputPipeType extends UAObjectType { flowTransmitter: FlowTransmitter; valve: Valve; } export interface BoilerInputPipe extends UAFolder { flowTransmitter: FlowTransmitter; valve: Valve; } export interface BoilerOutputPipeType extends UAObjectType { flowTransmitter: FlowTransmitter; } export interface BoilerOutputPipe extends UAFolder { flowTransmitter: FlowTransmitter; } export interface BoilerDrumType extends UAObjectType { levelIndicator: LevelIndicator; } export interface BoilerDrum extends UAFolder { levelIndicator: LevelIndicator; } export interface BoilerStateMachineType extends UAObjectType {} export interface BoilerStateMachine extends UAObject, UAProgramStateMachineEx {} export interface BoilerType extends UAObjectType { customController: CustomController; flowController: FlowController; levelController: LevelController; inputPipe: BoilerInputPipe; boilerDrum: BoilerDrum; outputPipe: BoilerOutputPipe; boilerDrum2: BoilerDrum; simulation: BoilerStateMachine; instantiate(options: InstantiateObjectOptions): Boiler; } export interface Boiler extends UAObject { customController: CustomController; flowController: FlowController; levelController: LevelController; inputPipe: BoilerInputPipe; boilerDrum: BoilerDrum; outputPipe: BoilerOutputPipe; boilerDrum2: BoilerDrum; simulation: BoilerStateMachine; } function MygetExecutableFlag(method: UAMethod, toState: string, methodName: string) { const stateMachineW = promoteToStateMachine(method.parent!); return stateMachineW.isValidTransition(toState); } function implementProgramStateMachine(programStateMachine: UAObject): void { function installMethod(methodName: string, toState: string) { let method = programStateMachine.getMethodByName(methodName); if (!method) { // 'method' has ModellingRule=OptionalPlaceholder and should be created from the type definition let methodToClone = programStateMachine.typeDefinitionObj.getMethodByName(methodName); if (!methodToClone) { methodToClone = programStateMachine.typeDefinitionObj!.subtypeOfObj!.getMethodByName(methodName)!; } methodToClone.clone({ namespace: programStateMachine.namespace, componentOf: programStateMachine }); method = programStateMachine.getMethodByName(methodName)!; assert(method !== null, "Method clone should cause parent object to be extended"); } assert(method.nodeClass === NodeClass.Method); method._getExecutableFlag = function (/* sessionContext: SessionContext */) { // must use a function here to capture 'this' return MygetExecutableFlag(this as UAMethod, toState, methodName); }; method.bindMethod(function ( this: UAMethod, inputArguments: VariantLike[], context: ISessionContext, callback: (err: Error | null, callMethodResult: CallMethodResultOptions) => void ) { const stateMachineW = this.parent! as UAStateMachineImpl; stateMachineW.setState(toState); callback(null, { outputArguments: [], statusCode: StatusCodes.Good }); }); assert( programStateMachine.getMethodByName(methodName) !== null, "Method " + methodName + " should be added to parent object (checked with getMethodByName)" ); const lc_name = lowerFirstLetter(methodName); } installMethod("Halt", "Halted"); installMethod("Reset", "Ready"); installMethod("Start", "Running"); installMethod("Suspend", "Suspended"); installMethod("Resume", "Running"); } function addRelation(srcNode: BaseNode, referenceType: UAReferenceType | string, targetNode: BaseNode) { assert(srcNode, "expecting srcNode !== null"); assert(targetNode, "expecting targetNode !== null"); if (typeof referenceType === "string") { const nodes = srcNode.findReferencesAsObject(referenceType, true); assert(nodes.length === 1); referenceType = nodes[0] as UAReferenceType; } srcNode.addReference({ referenceType: referenceType.nodeId, nodeId: targetNode }); } export function createBoilerType(namespace: Namespace): BoilerType { // istanbul ignore next if (namespace.findObjectType("BoilerType")) { console.warn("createBoilerType has already been called"); return namespace.findObjectType("BoilerType") as BoilerType; } // -------------------------------------------------------- // referenceTypes // -------------------------------------------------------- // create new reference Type FlowTo HotFlowTo & SignalTo const flowTo = namespace.addReferenceType({ browseName: "FlowTo", description: "a reference that indicates a flow between two objects", inverseName: "FlowFrom", subtypeOf: "NonHierarchicalReferences" }) as FlowToReference; const hotFlowTo = namespace.addReferenceType({ browseName: "HotFlowTo", description: "a reference that indicates a high temperature flow between two objects", inverseName: "HotFlowFrom", subtypeOf: flowTo }) as HotFlowToReference; const signalTo = namespace.addReferenceType({ browseName: "SignalTo", description: "a reference that indicates an electrical signal between two variables", inverseName: "SignalFrom", subtypeOf: "NonHierarchicalReferences" }) as SignalToReference; const addressSpace = namespace.addressSpace; flowTo.isSupertypeOf(addressSpace.findReferenceType("References")!); flowTo.isSupertypeOf(addressSpace.findReferenceType("NonHierarchicalReferences")!); hotFlowTo.isSupertypeOf(addressSpace.findReferenceType("References")!); hotFlowTo.isSupertypeOf(addressSpace.findReferenceType("NonHierarchicalReferences")!); hotFlowTo.isSupertypeOf(addressSpace.findReferenceType("FlowTo", namespace.index)!); const NonHierarchicalReferences = addressSpace.findReferenceType("NonHierarchicalReferences"); // -------------------------------------------------------- // EventTypes // -------------------------------------------------------- const boilerHaltedEventType = namespace.addEventType({ browseName: "BoilerHaltedEventType", subtypeOf: "TransitionEventType" }) as BoilerHaltedEventType; // -------------------------------------------------------- // CustomControllerType // -------------------------------------------------------- const customControllerType = namespace.addObjectType({ browseName: "CustomControllerType", description: "a custom PID controller with 3 inputs" }) as CustomControllerType; const input1: UAVariable = namespace.addVariable({ browseName: "Input1", dataType: "Double", description: "a reference that indicates an electrical signal between two variables", modellingRule: "Mandatory", propertyOf: customControllerType }); const input2: UAVariable = namespace.addVariable({ browseName: "Input2", dataType: "Double", modellingRule: "Mandatory", propertyOf: customControllerType }); const input3: UAVariable = namespace.addVariable({ browseName: "Input3", dataType: "Double", modellingRule: "Mandatory", propertyOf: customControllerType }); const controlOut: UAVariable = namespace.addVariable({ browseName: "ControlOut", dataType: "Double", modellingRule: "Mandatory", propertyOf: customControllerType }); const description: UAVariable = namespace.addVariable({ browseName: "Description", dataType: "LocalizedText", modellingRule: "Mandatory", propertyOf: customControllerType }); // -------------------------------------------------------- // GenericSensorType // -------------------------------------------------------- const genericSensorType = namespace.addObjectType({ browseName: "GenericSensorType" }); namespace.addAnalogDataItem({ browseName: "Output", componentOf: genericSensorType, dataType: "Double", engineeringUnitsRange: { low: -100, high: 200 }, modellingRule: "Mandatory" }); genericSensorType.install_extra_properties(); genericSensorType.getComponentByName("Output"); assert(genericSensorType.getComponentByName("Output")!.modellingRule === "Mandatory"); // -------------------------------------------------------- // GenericSensorType <---- GenericControllerType // -------------------------------------------------------- const genericControllerType = namespace.addObjectType({ browseName: "GenericControllerType" }); namespace.addVariable({ browseName: "ControlOut", dataType: "Double", modellingRule: "Mandatory", propertyOf: genericControllerType }); namespace.addVariable({ browseName: "Measurement", dataType: "Double", modellingRule: "Mandatory", propertyOf: genericControllerType }); namespace.addVariable({ browseName: "SetPoint", dataType: "Double", modellingRule: "Mandatory", propertyOf: genericControllerType }); // -------------------------------------------------------------------------------- // GenericSensorType <---- GenericControllerType <--- FlowControllerType // -------------------------------------------------------------------------------- const flowControllerType = namespace.addObjectType({ browseName: "FlowControllerType", subtypeOf: genericControllerType }); // -------------------------------------------------------------------------------- // GenericSensorType <---- GenericControllerType <--- LevelControllerType // -------------------------------------------------------------------------------- const levelControllerType = namespace.addObjectType({ browseName: "LevelControllerType", subtypeOf: genericControllerType }); // -------------------------------------------------------------------------------- // GenericSensorType <---- FlowTransmitterType // -------------------------------------------------------------------------------- const flowTransmitterType = namespace.addObjectType({ browseName: "FlowTransmitterType", subtypeOf: genericSensorType }); // -------------------------------------------------------------------------------- // GenericSensorType <---- LevelIndicatorType // -------------------------------------------------------------------------------- const levelIndicatorType = namespace.addObjectType({ browseName: "LevelIndicatorType", subtypeOf: genericSensorType }); // -------------------------------------------------------------------------------- // GenericActuatorType // -------------------------------------------------------------------------------- const genericActuatorType = namespace.addObjectType({ browseName: "GenericActuatorType" }); namespace.addAnalogDataItem({ browseName: "Input", componentOf: genericActuatorType, dataType: "Double", engineeringUnitsRange: { low: -100, high: 200 }, modellingRule: "Mandatory" }); // -------------------------------------------------------------------------------- // GenericActuatorType <---- ValveType // -------------------------------------------------------------------------------- const valveType = namespace.addObjectType({ browseName: "ValveType", subtypeOf: genericActuatorType }); // -------------------------------------------------------------------------------- // FolderType <---- BoilerInputPipeType // -------------------------------------------------------------------------------- const boilerInputPipeType = namespace.addObjectType({ browseName: "BoilerInputPipeType", subtypeOf: "FolderType" }); const ftx1 = flowTransmitterType.instantiate({ browseName: "FlowTransmitter", componentOf: boilerInputPipeType, modellingRule: "Mandatory", notifierOf: boilerInputPipeType }) as FlowTransmitter; assert(ftx1.output.browseName.toString() === `${namespace.index}:Output`); const valve1 = valveType.instantiate({ browseName: "Valve", componentOf: boilerInputPipeType, modellingRule: "Mandatory" }) as Valve; // -------------------------------------------------------------------------------- // FolderType <---- BoilerOutputPipeType // -------------------------------------------------------------------------------- const boilerOutputPipeType = namespace.addObjectType({ browseName: "BoilerOutputPipeType", subtypeOf: "FolderType" }); const ftx2 = flowTransmitterType.instantiate({ browseName: "FlowTransmitter", componentOf: boilerOutputPipeType, modellingRule: "Mandatory", notifierOf: boilerOutputPipeType }) as FlowTransmitter; ftx2.getComponentByName("Output")!.browseName.toString(); // --------------------------------)------------------------------------------------ // FolderType <---- BoilerDrumType // -------------------------------------------------------------------------------- const boilerDrumType = namespace.addObjectType({ browseName: "BoilerDrumType", subtypeOf: "FolderType" }); const levelIndicator = levelIndicatorType.instantiate({ browseName: "LevelIndicator", componentOf: boilerDrumType, modellingRule: "Mandatory", notifierOf: boilerDrumType }) as LevelIndicator; const programFiniteStateMachineType = addressSpace.findObjectType("ProgramStateMachineType")!; // -------------------------------------------------------- // define boiler State Machine // -------------------------------------------------------- const boilerStateMachineType = namespace.addObjectType({ browseName: "BoilerStateMachineType", postInstantiateFunc: implementProgramStateMachine, subtypeOf: programFiniteStateMachineType! }) as BoilerStateMachineType; // programStateMachineType has Optional placeHolder for method "Halt", "Reset","Start","Suspend","Resume") function addMethod(baseType: UAObjectType, objectType: UAObjectType, methodName: string) { assert(!objectType.getMethodByName(methodName)); const method = baseType.getMethodByName(methodName)!; const m = method.clone({ namespace, componentOf: objectType, modellingRule: "Mandatory" }); assert(objectType.getMethodByName(methodName)); assert(objectType.getMethodByName(methodName)!.modellingRule === "Mandatory"); } addMethod(programFiniteStateMachineType, boilerStateMachineType, "Halt"); addMethod(programFiniteStateMachineType, boilerStateMachineType, "Reset"); addMethod(programFiniteStateMachineType, boilerStateMachineType, "Start"); addMethod(programFiniteStateMachineType, boilerStateMachineType, "Suspend"); addMethod(programFiniteStateMachineType, boilerStateMachineType, "Resume"); // -------------------------------------------------------------------------------- // BoilerType // -------------------------------------------------------------------------------- const boilerType = namespace.addObjectType({ browseName: "BoilerType", eventNotifier: 0x1 }) as BoilerType; // BoilerType.CustomController (CustomControllerType) const customController = customControllerType.instantiate({ browseName: "CustomController", componentOf: boilerType, modellingRule: "Mandatory" }) as CustomController; // BoilerType.FlowController (FlowController) const flowController = flowControllerType.instantiate({ browseName: "FlowController", componentOf: boilerType, modellingRule: "Mandatory" }) as FlowController; // BoilerType.LevelController (LevelControllerType) const levelController = levelControllerType.instantiate({ browseName: "LevelController", componentOf: boilerType, modellingRule: "Mandatory" }) as LevelController; // BoilerType.LevelIndicator (BoilerInputPipeType) const inputPipe = boilerInputPipeType.instantiate({ browseName: "InputPipe", componentOf: boilerType, modellingRule: "Mandatory", notifierOf: boilerType }) as BoilerInputPipe; // BoilerType.BoilerDrum (BoilerDrumType) const boilerDrum = boilerDrumType.instantiate({ browseName: "BoilerDrum", componentOf: boilerType, modellingRule: "Mandatory", notifierOf: boilerType }) as BoilerDrum; // BoilerType.OutputPipe (BoilerOutputPipeType) const outputPipe = boilerOutputPipeType.instantiate({ browseName: "OutputPipe", componentOf: boilerType, modellingRule: "Mandatory", notifierOf: boilerType }) as BoilerOutputPipe; // BoilerType.Simulation (BoilerStateMachineType) const simulation = boilerStateMachineType.instantiate({ browseName: "Simulation", componentOf: boilerType, eventSourceOf: boilerType, modellingRule: "Mandatory" }) as BoilerStateMachine; addRelation(inputPipe, flowTo, boilerDrum); addRelation(boilerDrum, hotFlowTo, outputPipe); assert(boilerType.inputPipe.flowTransmitter); assert(boilerType.inputPipe.flowTransmitter.output); assert(boilerType.flowController.measurement); addRelation(boilerType.inputPipe.flowTransmitter.output, signalTo, boilerType.flowController.measurement); addRelation(boilerType.inputPipe.flowTransmitter.output, signalTo, boilerType.customController.input2); addRelation(boilerType.flowController.controlOut, signalTo, boilerType.inputPipe.valve.input); // indicates that the level controller gets its measurement from the drum's level indicator. addRelation(boilerType.boilerDrum.levelIndicator.output, signalTo, boilerType.levelController.measurement); addRelation(boilerType.outputPipe.flowTransmitter.output, signalTo, boilerType.customController.input3); addRelation(boilerType.levelController.controlOut, signalTo, boilerType.customController.input1); addRelation(boilerType.customController.controlOut, signalTo, boilerType.flowController.setPoint); return boilerType; } export function makeBoiler( addressSpace: AddressSpace, options: { browseName: string; organizedBy: BaseNode; } ): Boiler { const namespace = addressSpace.getOwnNamespace(); assert(options); let boilerType: UAObjectType | null; boilerType = namespace.findObjectType("BoilerType"); // istanbul ignore next if (!boilerType) { createBoilerType(namespace); boilerType = namespace.findObjectType("BoilerType")!; } // now instantiate boiler const boiler1 = boilerType.instantiate({ browseName: options.browseName, organizedBy: addressSpace.rootFolder.objects }) as Boiler; promoteToStateMachine(boiler1.simulation); const boilerStateMachine = boiler1.simulation; const readyState = boilerStateMachine.getStateByName("Ready")!; boilerStateMachine.setState(readyState); return boiler1; }
the_stack
import "jasmine"; import { Deferred } from "../Deferred"; import { FullDuplexStream } from "../FullDuplexStream"; import { MultiplexingStream } from "../MultiplexingStream"; import { getBufferFrom } from "../Utilities"; import { startJsonRpc } from "./jsonRpcStreams"; import { timeout } from "./Timeout"; import { Channel } from "../Channel"; import CancellationToken from "cancellationtoken"; import * as assert from "assert"; [1, 2, 3].forEach(protocolMajorVersion => { describe(`MultiplexingStream v${protocolMajorVersion}`, () => { let mx1: MultiplexingStream; let mx2: MultiplexingStream; beforeEach(async () => { const underlyingPair = FullDuplexStream.CreatePair(); const mxs = await Promise.all([ MultiplexingStream.CreateAsync(underlyingPair.first, { protocolMajorVersion }), MultiplexingStream.CreateAsync(underlyingPair.second, { protocolMajorVersion }), ]); mx1 = mxs.pop()!; mx2 = mxs.pop()!; }); afterEach(async () => { if (mx1) { mx1.dispose(); await mx1.completion; } if (mx2) { mx2.dispose(); await mx2.completion; } }); it("rejects null stream", async () => { expectThrow(MultiplexingStream.CreateAsync(null!)); expectThrow(MultiplexingStream.CreateAsync(undefined!)); }); it("isDisposed set upon disposal", async () => { expect(mx1.isDisposed).toBe(false); mx1.dispose(); expect(mx1.isDisposed).toBe(true); }); it("Completion should not complete before disposal", async () => { await expectThrow(timeout(mx1.completion, 10)); mx1.dispose(); await timeout(mx1.completion, 10); }); it("An offered channel is accepted", async () => { await Promise.all([ mx1.offerChannelAsync("test"), mx2.acceptChannelAsync("test"), ]); }); it("An offered anonymous channel is accepted", async () => { const rpcChannels = await Promise.all([ mx1.offerChannelAsync("test"), mx2.acceptChannelAsync("test"), ]); const offer = mx1.createChannel(); // Send a few bytes on the anonymous channel. offer.stream.write(new Buffer([1, 2, 3])); // await until we've confirmed the ID could have propagated // to the remote party. rpcChannels[0].stream.write(new Buffer(1)); await getBufferFrom(rpcChannels[1].stream, 1); const accept = mx2.acceptChannel(offer.id); // Receive the few bytes on the new channel. const recvOnChannel = await getBufferFrom(accept.stream, 3); expect(recvOnChannel).toEqual(new Buffer([1, 2, 3])); // Confirm the original party recognizes acceptance. await offer.acceptance; }); it("An offered anonymous channel is rejected", async () => { const rpcChannels = await Promise.all([ mx1.offerChannelAsync("test"), mx2.acceptChannelAsync("test"), ]); const offer = mx1.createChannel(); // Send a few bytes on the anonymous channel. offer.stream.write(new Buffer([1, 2, 3])); // await until we've confirmed the ID could have propagated // to the remote party. rpcChannels[0].stream.write(new Buffer(1)); await getBufferFrom(rpcChannels[1].stream, 1); mx2.rejectChannel(offer.id); // Confirm the original party recognizes rejection. await expectThrow(offer.acceptance); }); it("Channel offer is canceled by sender", async () => { const cts = CancellationToken.create(); const offer = mx1.offerChannelAsync('', undefined, cts.token); cts.cancel(); await assert.rejects(offer); }); it("Channel offer is rejected by event handler", async () => { const handler = new Deferred<void>(); mx2.on("channelOffered", (args) => { try { expect(args.name).toEqual("myname"); expect(args.isAccepted).toEqual(false); mx2.rejectChannel(args.id); handler.resolve(); } catch (error) { handler.reject(error); } }); await expectThrow(mx1.offerChannelAsync("myname")); await handler.promise; // rethrow any failures in the handler. }); it("Channel offer is accepted by event handler", async () => { const handler = new Deferred<Channel>(); mx2.on("channelOffered", (args) => { try { expect(args.name).toEqual("myname"); expect(args.isAccepted).toEqual(false); const channel = mx2.acceptChannel(args.id); handler.resolve(channel); } catch (error) { handler.reject(error); } }); const offer = mx1.offerChannelAsync("myname"); const offeredChannel = await offer; const acceptedChannel = await handler.promise; // rethrow any failures in the handler. offeredChannel.stream.end(); acceptedChannel.stream.end(); }); it("Channel offer is observed by event handler as accepted", async () => { const handler = new Deferred<void>(); mx2.on("channelOffered", (args) => { try { expect(args.name).toEqual("myname"); expect(args.isAccepted).toEqual(true); handler.resolve(); } catch (error) { handler.reject(error); } }); const accept = mx2.acceptChannelAsync("myname"); const offeredChannel = await mx1.offerChannelAsync("myname"); await accept; await handler.promise; // rethrow any failures in the handler. offeredChannel.stream.end(); }); it("Can use JSON-RPC over a channel", async () => { const rpcChannels = await Promise.all([ mx1.offerChannelAsync("test"), mx2.acceptChannelAsync("test"), ]); const rpc1 = startJsonRpc(rpcChannels[0]); const rpc2 = startJsonRpc(rpcChannels[1]); rpc2.onRequest("add", (a: number, b: number) => a + b); rpc2.listen(); rpc1.listen(); const sum = await rpc1.sendRequest("add", 1, 2); expect(sum).toEqual(3); }); it("Can exchange data over channel", async () => { const channels = await Promise.all([ mx1.offerChannelAsync("test"), mx2.acceptChannelAsync("test"), ]); channels[0].stream.write("abc"); expect(await getBufferFrom(channels[1].stream, 3)).toEqual(new Buffer("abc")); }); it("Can exchange data over two channels", async () => { const channels = await Promise.all([ mx1.offerChannelAsync("test"), mx1.offerChannelAsync("test2"), mx2.acceptChannelAsync("test"), mx2.acceptChannelAsync("test2"), ]); channels[0].stream.write("abc"); channels[3].stream.write("def"); channels[3].stream.write("ghi"); expect(await getBufferFrom(channels[2].stream, 3)).toEqual(new Buffer("abc")); expect(await getBufferFrom(channels[1].stream, 6)).toEqual(new Buffer("defghi")); }); it("end of channel", async () => { const channels = await Promise.all([ mx1.offerChannelAsync("test"), mx2.acceptChannelAsync("test"), ]); channels[0].stream.end("finished"); expect(await getBufferFrom(channels[1].stream, 8)).toEqual(new Buffer("finished")); expect(await getBufferFrom(channels[1].stream, 1, true)).toBeNull(); }); it("channel terminated", async () => { const channels = await Promise.all([ mx1.offerChannelAsync("test"), mx2.acceptChannelAsync("test"), ]); channels[0].dispose(); expect(await getBufferFrom(channels[1].stream, 1, true)).toBeNull(); await channels[1].completion; }); it("channels complete when mxstream is disposed", async () => { const channels = await Promise.all([ mx1.offerChannelAsync("test"), mx2.acceptChannelAsync("test"), ]); mx1.dispose(); // Verify that both mxstream's complete when one does. await mx1.completion; await mx2.completion; // Verify that the disposed mxstream completes its own channels. await channels[0].completion; // Verify that the mxstream that closes because its counterpart closed also completes its own channels. await channels[1].completion; }); it("offered channels must have names", async () => { await expectThrow(mx1.offerChannelAsync(null!)); await expectThrow(mx1.offerChannelAsync(undefined!)); }); it("offered channel name may be blank", async () => { await Promise.all([ mx1.offerChannelAsync(""), mx2.acceptChannelAsync(""), ]); }); it("accepted channels must have names", async () => { await expectThrow(mx1.acceptChannelAsync(null!)); await expectThrow(mx1.acceptChannelAsync(undefined!)); }); if (protocolMajorVersion < 3) { it("Rejects seeded channels", async () => { const underlyingPair = FullDuplexStream.CreatePair(); await expectThrow<MultiplexingStream>(MultiplexingStream.CreateAsync(underlyingPair.first, { protocolMajorVersion, seededChannels: [{}] })); }); } }); async function expectThrow<T>(promise: Promise<T>): Promise<any> { try { await promise; fail("Expected error not thrown."); } catch (error) { return error; } } });
the_stack
import { AxiosInstance } from 'axios' import { SdkOptions } from './config' export interface LoginCustomerInput { email: string password: string } export interface RegisterCustomerInput { email: string categories: string[] accepted_terms_and_conditions: boolean password: string } export interface ForgotPasswordInput { email: string } export interface ResetPasswordInput { token: string password: string } export interface TokenStorage { name: string set<T>(value: T): void get<T>(): T | null clear: () => void } export interface TokenStorageValue { accessTokenExpiresIn: number refreshToken: string currentTime: string } export interface AccessTokenStorageValue { accessTokenExpiresAt: string accessToken: string currentTime: string expiresIn: number } export interface DataResponse<Response> { data: Response } export interface AuthResponse { customer: any accessToken: string expiresIn: number refreshToken: string } export type ResetPasswordResponse = true export type ForgotPasswordResponse = true function getUrlParameter(name: string) { name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]') var regex = new RegExp('[\\?&]' + name + '=([^&#]*)') var results = regex.exec(location.search) return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' ')) } export class LocalStorageStore implements TokenStorage { constructor(public name: string) {} set<T>(value: T) { localStorage.setItem(this.name, JSON.stringify(value)) } get<T>() { try { return JSON.parse(localStorage.getItem(this.name) || '') as T } catch (error) { return null } } clear() { return localStorage.removeItem(this.name) } } function isBrowser() { return typeof window !== 'undefined' && typeof window.document !== 'undefined' } function getLocation(href: string) { var match = href.match( /^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/ ) return ( match && { protocol: match[1], host: match[2] } ) } export class AuthAPI { private storage: TokenStorage private session_interval: any = null private auth_response?: AuthResponse private on_auth_update?: (response?: AuthResponse) => void constructor(public instance: AxiosInstance, public options?: SdkOptions) { this.storage = new LocalStorageStore('___tensei__session___') } public async loadExistingSession() { if (this.usesRefreshTokens()) { this.silentLogin() } if (this.usesAccessTokens()) { await this.me() } } public async me() { const session = this.storage.get<AccessTokenStorageValue>() if (!session || !this.isSessionValid(session)) { this.logout() return null } let response try { response = await this.instance.get('me', { headers: { Authorization: `Bearer ${session.accessToken}` } }) } catch (errors) { this.logout() throw errors } this.auth_response = { accessToken: session.accessToken, expiresIn: session.expiresIn } as any this.updateUser(response.data.data) this.setAuthorizationHeader() return this.auth_response } private getUserKey() { return 'user' } session() { return this.auth_response } async login(payload: { object: LoginCustomerInput skipAuthentication?: boolean }) { const response = await this.instance.post<DataResponse<AuthResponse>>( 'login', payload.object ) this.auth_response = response.data.data this.invokeAuthChange() if (payload.skipAuthentication) { return response } this.setAuthorizationHeader() this.authenticateWithRefreshTokens() this.authenticateWithAccessTokens() return response } private usesRefreshTokens() { return this.options?.refreshTokens } private usesAccessTokens() { return !this.options?.refreshTokens } async silentLogin() { if (!isBrowser()) { return } const session = this.storage.get<TokenStorageValue>() if (!session || !this.isRefreshSessionValid(session)) { return this.logout() } try { const response = await this.refreshToken({ token: session.refreshToken }) this.auth_response = response.data.data this.invokeAuthChange() this.authenticateWithRefreshTokens() this.authenticateWithAccessTokens() } catch (errors) { this.logout() } } listen = (fn: (auth?: AuthResponse) => void) => { this.on_auth_update = fn } private invokeAuthChange() { if (this.on_auth_update) { this.on_auth_update(this.auth_response) } } private setAuthorizationHeader() { this.instance.defaults.headers.common = { Authorization: `Bearer ${this.auth_response?.accessToken}` } } private authenticateWithAccessTokens() { this.setAuthorizationHeader() if (!isBrowser()) { return } if (!this.usesAccessTokens()) { return } if (!this.auth_response) { return } const token_expires_at = new Date() token_expires_at.setSeconds( token_expires_at.getSeconds() + this.auth_response.expiresIn ) this.storage.set<AccessTokenStorageValue>({ currentTime: new Date().toISOString(), expiresIn: this.auth_response.expiresIn, accessToken: this.auth_response.accessToken, accessTokenExpiresAt: token_expires_at.toISOString() }) } private authenticateWithRefreshTokens() { this.setAuthorizationHeader() if (!this.usesRefreshTokens()) { return } if (!isBrowser()) { return } // if refresh tokens are not turned on on the API: if (!this.auth_response?.refreshToken || !this.auth_response?.accessToken) { return } const currentTime = new Date().toISOString() this.storage.set<TokenStorageValue>({ currentTime, refreshToken: this.auth_response.refreshToken, accessTokenExpiresIn: this.auth_response.expiresIn }) if (this.session_interval) { return } // Trigger a token refresh 10 seconds before the current access token expires. this.session_interval = setInterval(() => { this.silentLogin() }, (this.auth_response.expiresIn - 10) * 1000) } refreshToken(payload: { token: string }) { return this.instance.get('refresh-token', { headers: { 'x-tensei-refresh-token': payload.token } }) } private isSessionValid(session: AccessTokenStorageValue) { const token_expires_at = new Date(session.accessTokenExpiresAt) return token_expires_at > new Date() } isRefreshSessionValid(session: TokenStorageValue) { const token_created_at = new Date(session.currentTime) token_created_at.setSeconds( token_created_at.getSeconds() + session.accessTokenExpiresIn ) return token_created_at > new Date() } logout() { if (this.session_interval) { clearInterval(this.session_interval) } if (isBrowser()) { this.storage.clear() } this.auth_response = undefined this.invokeAuthChange() delete this.instance.defaults.headers.common['Authorization'] } async register(payload: { object: any; skipAuthentication?: boolean }) { const response = await this.instance.post<DataResponse<AuthResponse>>( 'register', payload.object ) this.auth_response = response.data.data this.invokeAuthChange() if (payload.skipAuthentication) { return response } this.authenticateWithRefreshTokens() this.authenticateWithAccessTokens() return response } forgotPassword(payload: { object: ForgotPasswordInput }) { return this.instance.post<DataResponse<ForgotPasswordResponse>>( 'passwords/email', payload.object ) } resetPassword(payload: { object: ResetPasswordInput }) { return this.instance.post('passwords/reset', payload.object) } async resendVerificationEmail() { return this.instance.post('emails/verification/resend') } async confirmEmail(payload: { object: any }) { const response = await this.instance.post( 'emails/verification/confirm', payload.object ) this.updateUser(response.data.data) return response } async enableTwoFactor() { const response = await this.instance.post('two-factor/enable') this.updateUser(response.data.data) return response } private updateUser(user: any) { if (!this.auth_response) { return } const key = this.getUserKey() ;(this.auth_response as any)[key] = user[key] ? user[key] : user this.invokeAuthChange() } async confirmEnableTwoFactor(payload: { object: any }) { const response = await this.instance.post('two-factor/confirm', { token: payload?.object?.token }) this.updateUser(response.data.data) return response } async disableTwoFactor(payload: { object: any }) { const response = await this.instance.post('two-factor/disable', { token: payload?.object?.token }) this.updateUser(response.data.data) return response } socialRedirectUrl(provider: string) { const { protocol, host } = getLocation(this.instance.defaults.baseURL!)! return `${protocol}//${host}/connect/${provider}` } private async handleSocial(type: string, payload: any) { let response try { response = await this.instance.post(`social/${type}`, payload.object) } catch (errors) { this.logout() throw errors } this.auth_response = response.data.data this.invokeAuthChange() if (payload.skipAuthentication) { return response } this.setAuthorizationHeader() this.authenticateWithRefreshTokens() this.authenticateWithAccessTokens() return response } async socialLogin(payload: any) { return this.handleSocial('login', this.getSocialPayload(payload)) } async socialRegister(payload: any) { return this.handleSocial('register', this.getSocialPayload(payload)) } private getSocialPayload(payload: any) { if (!payload?.object) { return { ...(payload || {}), object: { accessToken: getUrlParameter('accessToken') } } } return payload } socialConfirm(payload: any) { try { return this.handleSocial('confirm', this.getSocialPayload(payload)) } catch (errors) { this.logout() throw errors } } }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config'; interface Blob {} declare class MediaPackage extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: MediaPackage.Types.ClientConfiguration) config: Config & MediaPackage.Types.ClientConfiguration; /** * Creates a new Channel. */ createChannel(params: MediaPackage.Types.CreateChannelRequest, callback?: (err: AWSError, data: MediaPackage.Types.CreateChannelResponse) => void): Request<MediaPackage.Types.CreateChannelResponse, AWSError>; /** * Creates a new Channel. */ createChannel(callback?: (err: AWSError, data: MediaPackage.Types.CreateChannelResponse) => void): Request<MediaPackage.Types.CreateChannelResponse, AWSError>; /** * Creates a new OriginEndpoint record. */ createOriginEndpoint(params: MediaPackage.Types.CreateOriginEndpointRequest, callback?: (err: AWSError, data: MediaPackage.Types.CreateOriginEndpointResponse) => void): Request<MediaPackage.Types.CreateOriginEndpointResponse, AWSError>; /** * Creates a new OriginEndpoint record. */ createOriginEndpoint(callback?: (err: AWSError, data: MediaPackage.Types.CreateOriginEndpointResponse) => void): Request<MediaPackage.Types.CreateOriginEndpointResponse, AWSError>; /** * Deletes an existing Channel. */ deleteChannel(params: MediaPackage.Types.DeleteChannelRequest, callback?: (err: AWSError, data: MediaPackage.Types.DeleteChannelResponse) => void): Request<MediaPackage.Types.DeleteChannelResponse, AWSError>; /** * Deletes an existing Channel. */ deleteChannel(callback?: (err: AWSError, data: MediaPackage.Types.DeleteChannelResponse) => void): Request<MediaPackage.Types.DeleteChannelResponse, AWSError>; /** * Deletes an existing OriginEndpoint. */ deleteOriginEndpoint(params: MediaPackage.Types.DeleteOriginEndpointRequest, callback?: (err: AWSError, data: MediaPackage.Types.DeleteOriginEndpointResponse) => void): Request<MediaPackage.Types.DeleteOriginEndpointResponse, AWSError>; /** * Deletes an existing OriginEndpoint. */ deleteOriginEndpoint(callback?: (err: AWSError, data: MediaPackage.Types.DeleteOriginEndpointResponse) => void): Request<MediaPackage.Types.DeleteOriginEndpointResponse, AWSError>; /** * Gets details about a Channel. */ describeChannel(params: MediaPackage.Types.DescribeChannelRequest, callback?: (err: AWSError, data: MediaPackage.Types.DescribeChannelResponse) => void): Request<MediaPackage.Types.DescribeChannelResponse, AWSError>; /** * Gets details about a Channel. */ describeChannel(callback?: (err: AWSError, data: MediaPackage.Types.DescribeChannelResponse) => void): Request<MediaPackage.Types.DescribeChannelResponse, AWSError>; /** * Gets details about an existing OriginEndpoint. */ describeOriginEndpoint(params: MediaPackage.Types.DescribeOriginEndpointRequest, callback?: (err: AWSError, data: MediaPackage.Types.DescribeOriginEndpointResponse) => void): Request<MediaPackage.Types.DescribeOriginEndpointResponse, AWSError>; /** * Gets details about an existing OriginEndpoint. */ describeOriginEndpoint(callback?: (err: AWSError, data: MediaPackage.Types.DescribeOriginEndpointResponse) => void): Request<MediaPackage.Types.DescribeOriginEndpointResponse, AWSError>; /** * Returns a collection of Channels. */ listChannels(params: MediaPackage.Types.ListChannelsRequest, callback?: (err: AWSError, data: MediaPackage.Types.ListChannelsResponse) => void): Request<MediaPackage.Types.ListChannelsResponse, AWSError>; /** * Returns a collection of Channels. */ listChannels(callback?: (err: AWSError, data: MediaPackage.Types.ListChannelsResponse) => void): Request<MediaPackage.Types.ListChannelsResponse, AWSError>; /** * Returns a collection of OriginEndpoint records. */ listOriginEndpoints(params: MediaPackage.Types.ListOriginEndpointsRequest, callback?: (err: AWSError, data: MediaPackage.Types.ListOriginEndpointsResponse) => void): Request<MediaPackage.Types.ListOriginEndpointsResponse, AWSError>; /** * Returns a collection of OriginEndpoint records. */ listOriginEndpoints(callback?: (err: AWSError, data: MediaPackage.Types.ListOriginEndpointsResponse) => void): Request<MediaPackage.Types.ListOriginEndpointsResponse, AWSError>; /** * Changes the Channel ingest username and password. */ rotateChannelCredentials(params: MediaPackage.Types.RotateChannelCredentialsRequest, callback?: (err: AWSError, data: MediaPackage.Types.RotateChannelCredentialsResponse) => void): Request<MediaPackage.Types.RotateChannelCredentialsResponse, AWSError>; /** * Changes the Channel ingest username and password. */ rotateChannelCredentials(callback?: (err: AWSError, data: MediaPackage.Types.RotateChannelCredentialsResponse) => void): Request<MediaPackage.Types.RotateChannelCredentialsResponse, AWSError>; /** * Updates an existing Channel. */ updateChannel(params: MediaPackage.Types.UpdateChannelRequest, callback?: (err: AWSError, data: MediaPackage.Types.UpdateChannelResponse) => void): Request<MediaPackage.Types.UpdateChannelResponse, AWSError>; /** * Updates an existing Channel. */ updateChannel(callback?: (err: AWSError, data: MediaPackage.Types.UpdateChannelResponse) => void): Request<MediaPackage.Types.UpdateChannelResponse, AWSError>; /** * Updates an existing OriginEndpoint. */ updateOriginEndpoint(params: MediaPackage.Types.UpdateOriginEndpointRequest, callback?: (err: AWSError, data: MediaPackage.Types.UpdateOriginEndpointResponse) => void): Request<MediaPackage.Types.UpdateOriginEndpointResponse, AWSError>; /** * Updates an existing OriginEndpoint. */ updateOriginEndpoint(callback?: (err: AWSError, data: MediaPackage.Types.UpdateOriginEndpointResponse) => void): Request<MediaPackage.Types.UpdateOriginEndpointResponse, AWSError>; } declare namespace MediaPackage { export type AdMarkers = "NONE"|"SCTE35_ENHANCED"|"PASSTHROUGH"|string; export interface Channel { /** * The Amazon Resource Name (ARN) assigned to the Channel. */ Arn?: __string; /** * A short text description of the Channel. */ Description?: __string; HlsIngest?: HlsIngest; /** * The ID of the Channel. */ Id?: __string; } export interface ChannelCreateParameters { /** * A short text description of the Channel. */ Description?: __string; /** * The ID of the Channel. The ID must be unique within the region and it cannot be changed after a Channel is created. */ Id?: __string; } export interface ChannelList { /** * A list of Channel records. */ Channels?: ListOfChannel; /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: __string; } export interface ChannelUpdateParameters { /** * A short text description of the Channel. */ Description?: __string; } export interface CreateChannelRequest { /** * A short text description of the Channel. */ Description?: __string; /** * The ID of the Channel. The ID must be unique within the region and it cannot be changed after a Channel is created. */ Id: __string; } export interface CreateChannelResponse { /** * The Amazon Resource Name (ARN) assigned to the Channel. */ Arn?: __string; /** * A short text description of the Channel. */ Description?: __string; HlsIngest?: HlsIngest; /** * The ID of the Channel. */ Id?: __string; } export interface CreateOriginEndpointRequest { /** * The ID of the Channel that the OriginEndpoint will be associated with. This cannot be changed after the OriginEndpoint is created. */ ChannelId: __string; DashPackage?: DashPackage; /** * A short text description of the OriginEndpoint. */ Description?: __string; HlsPackage?: HlsPackage; /** * The ID of the OriginEndpoint. The ID must be unique within the region and it cannot be changed after the OriginEndpoint is created. */ Id: __string; /** * A short string that will be used as the filename of the OriginEndpoint URL (defaults to "index"). */ ManifestName?: __string; MssPackage?: MssPackage; /** * Maximum duration (seconds) of content to retain for startover playback. If not specified, startover playback will be disabled for the OriginEndpoint. */ StartoverWindowSeconds?: __integer; /** * Amount of delay (seconds) to enforce on the playback of live content. If not specified, there will be no time delay in effect for the OriginEndpoint. */ TimeDelaySeconds?: __integer; /** * A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint. */ Whitelist?: ListOf__string; } export interface CreateOriginEndpointResponse { /** * The Amazon Resource Name (ARN) assigned to the OriginEndpoint. */ Arn?: __string; /** * The ID of the Channel the OriginEndpoint is associated with. */ ChannelId?: __string; DashPackage?: DashPackage; /** * A short text description of the OriginEndpoint. */ Description?: __string; HlsPackage?: HlsPackage; /** * The ID of the OriginEndpoint. */ Id?: __string; /** * A short string appended to the end of the OriginEndpoint URL. */ ManifestName?: __string; MssPackage?: MssPackage; /** * Maximum duration (seconds) of content to retain for startover playback. If not specified, startover playback will be disabled for the OriginEndpoint. */ StartoverWindowSeconds?: __integer; /** * Amount of delay (seconds) to enforce on the playback of live content. If not specified, there will be no time delay in effect for the OriginEndpoint. */ TimeDelaySeconds?: __integer; /** * The URL of the packaged OriginEndpoint for consumption. */ Url?: __string; /** * A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint. */ Whitelist?: ListOf__string; } export interface DashEncryption { /** * Time (in seconds) between each encryption key rotation. */ KeyRotationIntervalSeconds?: __integer; SpekeKeyProvider: SpekeKeyProvider; } export interface DashPackage { Encryption?: DashEncryption; /** * Time window (in seconds) contained in each manifest. */ ManifestWindowSeconds?: __integer; /** * Minimum duration (in seconds) that a player will buffer media before starting the presentation. */ MinBufferTimeSeconds?: __integer; /** * Minimum duration (in seconds) between potential changes to the Dynamic Adaptive Streaming over HTTP (DASH) Media Presentation Description (MPD). */ MinUpdatePeriodSeconds?: __integer; /** * The Dynamic Adaptive Streaming over HTTP (DASH) profile type. When set to "HBBTV_1_5", HbbTV 1.5 compliant output is enabled. */ Profile?: Profile; /** * Duration (in seconds) of each segment. Actual segments will be rounded to the nearest multiple of the source segment duration. */ SegmentDurationSeconds?: __integer; StreamSelection?: StreamSelection; /** * Duration (in seconds) to delay live content before presentation. */ SuggestedPresentationDelaySeconds?: __integer; } export interface DeleteChannelRequest { /** * The ID of the Channel to delete. */ Id: __string; } export interface DeleteChannelResponse { } export interface DeleteOriginEndpointRequest { /** * The ID of the OriginEndpoint to delete. */ Id: __string; } export interface DeleteOriginEndpointResponse { } export interface DescribeChannelRequest { /** * The ID of a Channel. */ Id: __string; } export interface DescribeChannelResponse { /** * The Amazon Resource Name (ARN) assigned to the Channel. */ Arn?: __string; /** * A short text description of the Channel. */ Description?: __string; HlsIngest?: HlsIngest; /** * The ID of the Channel. */ Id?: __string; } export interface DescribeOriginEndpointRequest { /** * The ID of the OriginEndpoint. */ Id: __string; } export interface DescribeOriginEndpointResponse { /** * The Amazon Resource Name (ARN) assigned to the OriginEndpoint. */ Arn?: __string; /** * The ID of the Channel the OriginEndpoint is associated with. */ ChannelId?: __string; DashPackage?: DashPackage; /** * A short text description of the OriginEndpoint. */ Description?: __string; HlsPackage?: HlsPackage; /** * The ID of the OriginEndpoint. */ Id?: __string; /** * A short string appended to the end of the OriginEndpoint URL. */ ManifestName?: __string; MssPackage?: MssPackage; /** * Maximum duration (seconds) of content to retain for startover playback. If not specified, startover playback will be disabled for the OriginEndpoint. */ StartoverWindowSeconds?: __integer; /** * Amount of delay (seconds) to enforce on the playback of live content. If not specified, there will be no time delay in effect for the OriginEndpoint. */ TimeDelaySeconds?: __integer; /** * The URL of the packaged OriginEndpoint for consumption. */ Url?: __string; /** * A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint. */ Whitelist?: ListOf__string; } export type EncryptionMethod = "AES_128"|"SAMPLE_AES"|string; export interface HlsEncryption { /** * A constant initialization vector for encryption (optional). When not specified the initialization vector will be periodically rotated. */ ConstantInitializationVector?: __string; /** * The encryption method to use. */ EncryptionMethod?: EncryptionMethod; /** * Interval (in seconds) between each encryption key rotation. */ KeyRotationIntervalSeconds?: __integer; /** * When enabled, the EXT-X-KEY tag will be repeated in output manifests. */ RepeatExtXKey?: __boolean; SpekeKeyProvider: SpekeKeyProvider; } export interface HlsIngest { /** * A list of endpoints to which the source stream should be sent. */ IngestEndpoints?: ListOfIngestEndpoint; } export interface HlsPackage { /** * This setting controls how ad markers are included in the packaged OriginEndpoint. "NONE" will omit all SCTE-35 ad markers from the output. "PASSTHROUGH" causes the manifest to contain a copy of the SCTE-35 ad markers (comments) taken directly from the input HTTP Live Streaming (HLS) manifest. "SCTE35_ENHANCED" generates ad markers and blackout tags based on SCTE-35 messages in the input source. */ AdMarkers?: AdMarkers; Encryption?: HlsEncryption; /** * When enabled, an I-Frame only stream will be included in the output. */ IncludeIframeOnlyStream?: __boolean; /** * The HTTP Live Streaming (HLS) playlist type. When either "EVENT" or "VOD" is specified, a corresponding EXT-X-PLAYLIST-TYPE entry will be included in the media playlist. */ PlaylistType?: PlaylistType; /** * Time window (in seconds) contained in each parent manifest. */ PlaylistWindowSeconds?: __integer; /** * The interval (in seconds) between each EXT-X-PROGRAM-DATE-TIME tag inserted into manifests. Additionally, when an interval is specified ID3Timed Metadata messages will be generated every 5 seconds using the ingest time of the content. If the interval is not specified, or set to 0, then no EXT-X-PROGRAM-DATE-TIME tags will be inserted into manifests and no ID3Timed Metadata messages will be generated. Note that irrespective of this parameter, if any ID3 Timed Metadata is found in HTTP Live Streaming (HLS) input, it will be passed through to HLS output. */ ProgramDateTimeIntervalSeconds?: __integer; /** * Duration (in seconds) of each fragment. Actual fragments will be rounded to the nearest multiple of the source fragment duration. */ SegmentDurationSeconds?: __integer; StreamSelection?: StreamSelection; /** * When enabled, audio streams will be placed in rendition groups in the output. */ UseAudioRenditionGroup?: __boolean; } export interface IngestEndpoint { /** * The system generated password for ingest authentication. */ Password?: __string; /** * The ingest URL to which the source stream should be sent. */ Url?: __string; /** * The system generated username for ingest authentication. */ Username?: __string; } export interface ListChannelsRequest { /** * Upper bound on number of records to return. */ MaxResults?: MaxResults; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: __string; } export interface ListChannelsResponse { /** * A list of Channel records. */ Channels?: ListOfChannel; /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: __string; } export type ListOfChannel = Channel[]; export type ListOfIngestEndpoint = IngestEndpoint[]; export type ListOfOriginEndpoint = OriginEndpoint[]; export type ListOf__string = __string[]; export interface ListOriginEndpointsRequest { /** * When specified, the request will return only OriginEndpoints associated with the given Channel ID. */ ChannelId?: __string; /** * The upper bound on the number of records to return. */ MaxResults?: MaxResults; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: __string; } export interface ListOriginEndpointsResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: __string; /** * A list of OriginEndpoint records. */ OriginEndpoints?: ListOfOriginEndpoint; } export type MaxResults = number; export interface MssEncryption { SpekeKeyProvider: SpekeKeyProvider; } export interface MssPackage { Encryption?: MssEncryption; /** * The time window (in seconds) contained in each manifest. */ ManifestWindowSeconds?: __integer; /** * The duration (in seconds) of each segment. */ SegmentDurationSeconds?: __integer; StreamSelection?: StreamSelection; } export interface OriginEndpoint { /** * The Amazon Resource Name (ARN) assigned to the OriginEndpoint. */ Arn?: __string; /** * The ID of the Channel the OriginEndpoint is associated with. */ ChannelId?: __string; DashPackage?: DashPackage; /** * A short text description of the OriginEndpoint. */ Description?: __string; HlsPackage?: HlsPackage; /** * The ID of the OriginEndpoint. */ Id?: __string; /** * A short string appended to the end of the OriginEndpoint URL. */ ManifestName?: __string; MssPackage?: MssPackage; /** * Maximum duration (seconds) of content to retain for startover playback. If not specified, startover playback will be disabled for the OriginEndpoint. */ StartoverWindowSeconds?: __integer; /** * Amount of delay (seconds) to enforce on the playback of live content. If not specified, there will be no time delay in effect for the OriginEndpoint. */ TimeDelaySeconds?: __integer; /** * The URL of the packaged OriginEndpoint for consumption. */ Url?: __string; /** * A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint. */ Whitelist?: ListOf__string; } export interface OriginEndpointCreateParameters { /** * The ID of the Channel that the OriginEndpoint will be associated with. This cannot be changed after the OriginEndpoint is created. */ ChannelId?: __string; DashPackage?: DashPackage; /** * A short text description of the OriginEndpoint. */ Description?: __string; HlsPackage?: HlsPackage; /** * The ID of the OriginEndpoint. The ID must be unique within the region and it cannot be changed after the OriginEndpoint is created. */ Id?: __string; /** * A short string that will be used as the filename of the OriginEndpoint URL (defaults to "index"). */ ManifestName?: __string; MssPackage?: MssPackage; /** * Maximum duration (seconds) of content to retain for startover playback. If not specified, startover playback will be disabled for the OriginEndpoint. */ StartoverWindowSeconds?: __integer; /** * Amount of delay (seconds) to enforce on the playback of live content. If not specified, there will be no time delay in effect for the OriginEndpoint. */ TimeDelaySeconds?: __integer; /** * A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint. */ Whitelist?: ListOf__string; } export interface OriginEndpointList { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: __string; /** * A list of OriginEndpoint records. */ OriginEndpoints?: ListOfOriginEndpoint; } export interface OriginEndpointUpdateParameters { DashPackage?: DashPackage; /** * A short text description of the OriginEndpoint. */ Description?: __string; HlsPackage?: HlsPackage; /** * A short string that will be appended to the end of the Endpoint URL. */ ManifestName?: __string; MssPackage?: MssPackage; /** * Maximum duration (in seconds) of content to retain for startover playback. If not specified, startover playback will be disabled for the OriginEndpoint. */ StartoverWindowSeconds?: __integer; /** * Amount of delay (in seconds) to enforce on the playback of live content. If not specified, there will be no time delay in effect for the OriginEndpoint. */ TimeDelaySeconds?: __integer; /** * A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint. */ Whitelist?: ListOf__string; } export type PlaylistType = "NONE"|"EVENT"|"VOD"|string; export type Profile = "NONE"|"HBBTV_1_5"|string; export interface RotateChannelCredentialsRequest { /** * The ID of the channel to update. */ Id: __string; } export interface RotateChannelCredentialsResponse { /** * The Amazon Resource Name (ARN) assigned to the Channel. */ Arn?: __string; /** * A short text description of the Channel. */ Description?: __string; HlsIngest?: HlsIngest; /** * The ID of the Channel. */ Id?: __string; } export interface SpekeKeyProvider { /** * The resource ID to include in key requests. */ ResourceId: __string; /** * An Amazon Resource Name (ARN) of an IAM role that AWS Elemental MediaPackage will assume when accessing the key provider service. */ RoleArn: __string; /** * The system IDs to include in key requests. */ SystemIds: ListOf__string; /** * The URL of the external key provider service. */ Url: __string; } export type StreamOrder = "ORIGINAL"|"VIDEO_BITRATE_ASCENDING"|"VIDEO_BITRATE_DESCENDING"|string; export interface StreamSelection { /** * The maximum video bitrate (bps) to include in output. */ MaxVideoBitsPerSecond?: __integer; /** * The minimum video bitrate (bps) to include in output. */ MinVideoBitsPerSecond?: __integer; /** * A directive that determines the order of streams in the output. */ StreamOrder?: StreamOrder; } export interface UpdateChannelRequest { /** * A short text description of the Channel. */ Description?: __string; /** * The ID of the Channel to update. */ Id: __string; } export interface UpdateChannelResponse { /** * The Amazon Resource Name (ARN) assigned to the Channel. */ Arn?: __string; /** * A short text description of the Channel. */ Description?: __string; HlsIngest?: HlsIngest; /** * The ID of the Channel. */ Id?: __string; } export interface UpdateOriginEndpointRequest { DashPackage?: DashPackage; /** * A short text description of the OriginEndpoint. */ Description?: __string; HlsPackage?: HlsPackage; /** * The ID of the OriginEndpoint to update. */ Id: __string; /** * A short string that will be appended to the end of the Endpoint URL. */ ManifestName?: __string; MssPackage?: MssPackage; /** * Maximum duration (in seconds) of content to retain for startover playback. If not specified, startover playback will be disabled for the OriginEndpoint. */ StartoverWindowSeconds?: __integer; /** * Amount of delay (in seconds) to enforce on the playback of live content. If not specified, there will be no time delay in effect for the OriginEndpoint. */ TimeDelaySeconds?: __integer; /** * A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint. */ Whitelist?: ListOf__string; } export interface UpdateOriginEndpointResponse { /** * The Amazon Resource Name (ARN) assigned to the OriginEndpoint. */ Arn?: __string; /** * The ID of the Channel the OriginEndpoint is associated with. */ ChannelId?: __string; DashPackage?: DashPackage; /** * A short text description of the OriginEndpoint. */ Description?: __string; HlsPackage?: HlsPackage; /** * The ID of the OriginEndpoint. */ Id?: __string; /** * A short string appended to the end of the OriginEndpoint URL. */ ManifestName?: __string; MssPackage?: MssPackage; /** * Maximum duration (seconds) of content to retain for startover playback. If not specified, startover playback will be disabled for the OriginEndpoint. */ StartoverWindowSeconds?: __integer; /** * Amount of delay (seconds) to enforce on the playback of live content. If not specified, there will be no time delay in effect for the OriginEndpoint. */ TimeDelaySeconds?: __integer; /** * The URL of the packaged OriginEndpoint for consumption. */ Url?: __string; /** * A list of source IP CIDR blocks that will be allowed to access the OriginEndpoint. */ Whitelist?: ListOf__string; } export type __boolean = boolean; export type __double = number; export type __integer = number; export type __string = string; export type __timestamp = Date; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2017-10-12"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the MediaPackage client. */ export import Types = MediaPackage; } export = MediaPackage;
the_stack
import type { ReactNode } from 'react'; import React, { useRef, useEffect, useState } from 'react'; import { PageHeaderWrapper } from '@ant-design/pro-layout'; import ProTable from '@ant-design/pro-table'; import type { ProColumns, ActionType } from '@ant-design/pro-table'; import { Button, Popconfirm, notification, Tag, Space, Select, Radio, Form, Upload, Modal, Divider, Menu, Dropdown, } from 'antd'; import { history, useIntl } from 'umi'; import { PlusOutlined, ExportOutlined, ImportOutlined, DownOutlined } from '@ant-design/icons'; import { js_beautify } from 'js-beautify'; import yaml from 'js-yaml'; import moment from 'moment'; import { saveAs } from 'file-saver'; import querystring from 'query-string'; import { omit } from 'lodash'; import { DELETE_FIELDS } from '@/constants'; import { timestampToLocaleString } from '@/helpers'; import type { RcFile } from 'antd/lib/upload'; import { update, create, fetchList, remove, fetchLabelList, updateRouteStatus, exportRoutes, importRoutes, } from './service'; import { DebugDrawView } from './components/DebugViews'; import { RawDataEditor } from '@/components/RawDataEditor'; import { EXPORT_FILE_MIME_TYPE_SUPPORTED } from './constants'; const { OptGroup, Option } = Select; const Page: React.FC = () => { const ref = useRef<ActionType>(); const { formatMessage } = useIntl(); const [exportFileTypeForm] = Form.useForm(); enum RouteStatus { Offline = 0, Publish, } enum ExportFileType { JSON = 0, YAML, } const [labelList, setLabelList] = useState<LabelList>({}); const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]); const [uploadFileList, setUploadFileList] = useState<RcFile[]>([]); const [showImportModal, setShowImportModal] = useState(false); const [visible, setVisible] = useState(false); const [rawData, setRawData] = useState<Record<string, any>>({}); const [id, setId] = useState(''); const [editorMode, setEditorMode] = useState<'create' | 'update'>('create'); const [paginationConfig, setPaginationConfig] = useState({ pageSize: 10, current: 1 }); const [debugDrawVisible, setDebugDrawVisible] = useState(false); const savePageList = (page = 1, pageSize = 10) => { history.replace(`/routes/list?page=${page}&pageSize=${pageSize}`); }; useEffect(() => { fetchLabelList().then(setLabelList); }, []); useEffect(() => { const { page = 1, pageSize = 10 } = querystring.parse(window.location.search); setPaginationConfig({ pageSize: Number(pageSize), current: Number(page) }); }, [window.location.search]); const rowSelection: any = { selectedRowKeys, onChange: (currentSelectKeys: string[]) => { setSelectedRowKeys(currentSelectKeys); }, preserveSelectedRowKeys: true, }; const handleTableActionSuccessResponse = (msgTip: string) => { notification.success({ message: msgTip, }); ref.current?.reload(); }; const handlePublishOffline = (rid: string, status: RouteModule.RouteStatus) => { updateRouteStatus(rid, status).then(() => { const actionName = status ? formatMessage({ id: 'page.route.publish' }) : formatMessage({ id: 'page.route.offline' }); handleTableActionSuccessResponse( `${actionName} ${formatMessage({ id: 'menu.routes', })} ${formatMessage({ id: 'component.status.success' })}`, ); }); }; const handleExport = (exportFileType: ExportFileType) => { exportRoutes(selectedRowKeys.join(',')).then((resp) => { let exportFile: string; let exportFileName = `APISIX_routes_${moment().format('YYYYMMDDHHmmss')}`; switch (exportFileType) { case ExportFileType.YAML: exportFile = yaml.dump(resp.data); exportFileName = `${exportFileName}.${ExportFileType[ ExportFileType.YAML ].toLocaleLowerCase()}`; break; case ExportFileType.JSON: default: exportFile = js_beautify(JSON.stringify(resp.data), { indent_size: 2, }); exportFileName = `${exportFileName}.${ExportFileType[ ExportFileType.JSON ].toLocaleLowerCase()}`; break; } const blob = new Blob([exportFile], { type: EXPORT_FILE_MIME_TYPE_SUPPORTED[exportFileType], }); saveAs(window.URL.createObjectURL(blob), exportFileName); }); }; const handleImport = () => { const formData = new FormData(); if (!uploadFileList[0]) { notification.warn({ message: formatMessage({ id: 'page.route.button.selectFile' }), }); return; } formData.append('file', uploadFileList[0]); importRoutes(formData).then(() => { handleTableActionSuccessResponse( `${formatMessage({ id: 'page.route.button.importOpenApi' })} ${formatMessage({ id: 'component.status.success', })}`, ); setShowImportModal(false); }); }; const ListToolbar = () => { const tools = [ { name: formatMessage({ id: 'page.route.pluginTemplateConfig' }), icon: <PlusOutlined />, onClick: () => { history.push('/plugin-template/list'); }, }, { name: formatMessage({ id: 'component.global.data.editor' }), icon: <PlusOutlined />, onClick: () => { setVisible(true); setEditorMode('create'); setRawData({}); }, }, { name: formatMessage({ id: 'page.route.button.importOpenApi' }), icon: <ImportOutlined />, onClick: () => { setUploadFileList([]); setShowImportModal(true); }, }, ]; return ( <Dropdown overlay={ <Menu> {tools.map((item) => ( <Menu.Item key={item.name} onClick={item.onClick}> {item.icon} {item.name} </Menu.Item> ))} </Menu> } > <Button type="dashed"> <DownOutlined /> {formatMessage({ id: 'menu.advanced-feature' })} </Button> </Dropdown> ); }; const RecordActionDropdown: React.FC<{ record: any }> = ({ record }) => { const tools: { name: string; onClick: () => void; icon?: ReactNode; }[] = [ { name: formatMessage({ id: 'component.global.view' }), onClick: () => { setId(record.id); setRawData(omit(record, DELETE_FIELDS)); setVisible(true); setEditorMode('update'); }, }, { name: formatMessage({ id: 'component.global.duplicate' }), onClick: () => { history.push(`/routes/${record.id}/duplicate`); }, }, { name: formatMessage({ id: 'component.global.delete' }), onClick: () => { Modal.confirm({ type: 'warning', title: formatMessage({ id: 'component.global.popconfirm.title.delete' }), content: ( <> {formatMessage({ id: 'component.global.name' })} - {record.name} <br /> ID - {record.id} </> ), onOk: () => { remove(record.id!).then(() => { handleTableActionSuccessResponse( `${formatMessage({ id: 'component.global.delete' })} ${formatMessage({ id: 'menu.routes', })} ${formatMessage({ id: 'component.status.success' })}`, ); }); }, }); }, }, ]; return ( <Dropdown overlay={ <Menu> {tools.map((item) => ( <Menu.Item key={item.name} onClick={item.onClick}> {item.icon && item.icon} {item.name} </Menu.Item> ))} </Menu> } > <Button type="dashed"> <DownOutlined /> {formatMessage({ id: 'menu.more' })} </Button> </Dropdown> ); }; const ListFooter: React.FC = () => { return ( <Popconfirm title={ <Form form={exportFileTypeForm} initialValues={{ fileType: ExportFileType.JSON }}> <div style={{ marginBottom: 8 }}> {formatMessage({ id: 'page.route.exportRoutesTips' })} </div> <Form.Item name="fileType" noStyle> <Radio.Group> <Radio value={ExportFileType.JSON}>Json</Radio> <Radio value={ExportFileType.YAML}>Yaml</Radio> </Radio.Group> </Form.Item> </Form> } onConfirm={() => { handleExport(exportFileTypeForm.getFieldValue('fileType')); }} okText={formatMessage({ id: 'component.global.confirm' })} cancelText={formatMessage({ id: 'component.global.cancel' })} disabled={selectedRowKeys.length === 0} > <Button type="primary" disabled={selectedRowKeys.length === 0}> <ExportOutlined /> {formatMessage({ id: 'page.route.button.exportOpenApi' })} </Button> </Popconfirm> ); }; const columns: ProColumns<RouteModule.ResponseBody>[] = [ { title: formatMessage({ id: 'component.global.name' }), dataIndex: 'name', fixed: 'left', }, { title: formatMessage({ id: 'page.route.host' }), hideInSearch: true, render: (_, record) => { const list = record.hosts || (record.host && [record.host]) || []; return list.map((item) => ( <Tag key={item} color="geekblue"> {item} </Tag> )); }, }, { title: formatMessage({ id: 'page.route.path' }), dataIndex: 'uri', render: (_, record) => { const list = record.uris || (record.uri && [record.uri]) || []; return list.map((item) => ( <Tag key={item} color="geekblue"> {item} </Tag> )); }, }, { title: formatMessage({ id: 'component.global.description' }), dataIndex: 'desc', hideInSearch: true, }, { title: formatMessage({ id: 'component.global.labels' }), dataIndex: 'labels', render: (_, record) => { return Object.keys(record.labels || {}) .filter((item) => item !== 'API_VERSION') .map((item) => ( <Tag key={Math.random().toString(36).slice(2)}> {item}:{record.labels[item]} </Tag> )); }, renderFormItem: (_, { type }) => { if (type === 'form') { return null; } return ( <Select mode="tags" style={{ width: '100%' }} placeholder={formatMessage({ id: 'component.global.pleaseChoose' })} tagRender={(props) => { const { value, closable, onClose } = props; return ( <Tag closable={closable} onClose={onClose} style={{ marginRight: 3 }}> {value} </Tag> ); }} > {Object.keys(labelList) .filter((item) => item !== 'API_VERSION') .map((key) => { return ( <OptGroup label={key} key={Math.random().toString(36).slice(2)}> {(labelList[key] || []).map((value: string) => ( <Option key={Math.random().toString(36).slice(2)} value={`${key}:${value}`}> {' '} {value}{' '} </Option> ))} </OptGroup> ); })} </Select> ); }, }, { title: formatMessage({ id: 'component.global.version' }), dataIndex: 'API_VERSION', render: (_, record) => { return Object.keys(record.labels || {}) .filter((item) => item === 'API_VERSION') .map((item) => record.labels[item]); }, renderFormItem: (_, { type }) => { if (type === 'form') { return null; } return ( <Select style={{ width: '100%' }} placeholder={formatMessage({ id: 'component.global.pleaseChoose' })} allowClear > {Object.keys(labelList) .filter((item) => item === 'API_VERSION') .map((key) => { return ( <OptGroup label={key} key={Math.random().toString(36).slice(2)}> {(labelList[key] || []).map((value: string) => ( <Option key={Math.random().toString(36).slice(2)} value={`${key}:${value}`}> {' '} {value}{' '} </Option> ))} </OptGroup> ); })} </Select> ); }, }, { title: formatMessage({ id: 'page.route.status' }), dataIndex: 'status', render: (_, record) => ( <> {record.status ? ( <Tag color="green">{formatMessage({ id: 'page.route.published' })}</Tag> ) : ( <Tag color="red">{formatMessage({ id: 'page.route.unpublished' })}</Tag> )} </> ), renderFormItem: (_, { type }) => { if (type === 'form') { return null; } return ( <Select style={{ width: '100%' }} placeholder={`${formatMessage({ id: 'page.route.unpublished' })}/${formatMessage({ id: 'page.route.published', })}`} allowClear > <Option key={RouteStatus.Offline} value={RouteStatus.Offline}> {formatMessage({ id: 'page.route.unpublished' })} </Option> <Option key={RouteStatus.Publish} value={RouteStatus.Publish}> {formatMessage({ id: 'page.route.published' })} </Option> </Select> ); }, }, { title: formatMessage({ id: 'component.global.updateTime' }), dataIndex: 'update_time', hideInSearch: true, render: (text) => timestampToLocaleString(text as number), }, { title: formatMessage({ id: 'component.global.operation' }), valueType: 'option', fixed: 'right', hideInSearch: true, render: (_, record) => ( <> <Space align="baseline"> {!record.status ? ( <Button type="primary" onClick={() => { handlePublishOffline(record.id, RouteStatus.Publish); }} > {formatMessage({ id: 'page.route.publish' })} </Button> ) : null} {record.status ? ( <Popconfirm title={formatMessage({ id: 'page.route.popconfirm.title.offline' })} onConfirm={() => { handlePublishOffline(record.id, RouteStatus.Offline); }} okButtonProps={{ danger: true, }} okText={formatMessage({ id: 'component.global.confirm' })} cancelText={formatMessage({ id: 'component.global.cancel' })} > <Button type="primary" danger disabled={Boolean(!record.status)}> {formatMessage({ id: 'page.route.offline' })} </Button> </Popconfirm> ) : null} <Button type="primary" onClick={() => history.push(`/routes/${record.id}/edit`)}> {formatMessage({ id: 'component.global.edit' })} </Button> <RecordActionDropdown record={record} /> </Space> </> ), }, ]; return ( <PageHeaderWrapper title={formatMessage({ id: 'page.route.list' })} content={formatMessage({ id: 'page.route.list.description' })} > <ProTable<RouteModule.ResponseBody> actionRef={ref} rowKey="id" columns={columns} request={fetchList} pagination={{ onChange: (page, pageSize?) => savePageList(page, pageSize), pageSize: paginationConfig.pageSize, current: paginationConfig.current, }} search={{ searchText: formatMessage({ id: 'component.global.search' }), resetText: formatMessage({ id: 'component.global.reset' }), }} toolBarRender={() => [ <Button type="primary" onClick={() => history.push(`/routes/create`)}> <PlusOutlined /> {formatMessage({ id: 'component.global.create' })} </Button>, <ListToolbar />, ]} rowSelection={rowSelection} footer={() => <ListFooter />} tableAlertRender={false} scroll={{ x: 1300 }} /> <DebugDrawView visible={debugDrawVisible} onClose={() => { setDebugDrawVisible(false); }} /> <RawDataEditor visible={visible} type="route" readonly={false} data={rawData} onClose={() => { setVisible(false); }} onSubmit={(data: any) => { (editorMode === 'create' ? create(data, 'RawData') : update(id, data, 'RawData')).then( () => { setVisible(false); ref.current?.reload(); }, ); }} /> <Modal title={formatMessage({ id: 'page.route.button.importOpenApi' })} visible={showImportModal} okText={formatMessage({ id: 'component.global.confirm' })} onOk={handleImport} onCancel={() => { setShowImportModal(false); }} > <Upload fileList={uploadFileList as any} beforeUpload={(file) => { setUploadFileList([file]); return false; }} onRemove={() => { setUploadFileList([]); }} > <Button type="primary" icon={<ImportOutlined />}> {formatMessage({ id: 'page.route.button.selectFile' })} </Button> </Upload> <Divider /> <div> <p>{formatMessage({ id: 'page.route.instructions' })}:</p> <p> <a href="https://apisix.apache.org/docs/dashboard/IMPORT_OPENAPI_USER_GUIDE" target="_blank" > 1.{' '} {`${formatMessage({ id: 'page.route.import' })} ${formatMessage({ id: 'page.route.instructions', })}`} </a> </p> </div> </Modal> </PageHeaderWrapper> ); }; export default Page;
the_stack
import { isNullOrUndefined } from '@syncfusion/ej2-base'; /** * `Selection` module is used to handle RTE Selections. */ export class NodeSelection { public range: Range; public rootNode: Node; public body: HTMLBodyElement; public html: string; public startContainer: number[]; public endContainer: number[]; public startOffset: number; public endOffset: number; public startNodeName: string[] = []; public endNodeName: string[] = []; private saveInstance(range: Range, body: HTMLBodyElement): NodeSelection { this.range = range.cloneRange(); this.rootNode = this.documentFromRange(range); this.body = body; this.startContainer = this.getNodeArray(range.startContainer, true); this.endContainer = this.getNodeArray(range.endContainer, false); this.startOffset = range.startOffset; this.endOffset = range.endOffset; this.html = this.body.innerHTML; return this; } private documentFromRange(range: Range): Node { return (9 === range.startContainer.nodeType) ? range.startContainer : range.startContainer.ownerDocument; } public getRange(docElement: Document): Range { const select: Selection = this.get(docElement); const range: Range = select && select.rangeCount > 0 ? select.getRangeAt(select.rangeCount - 1) : docElement.createRange(); return (range.startContainer !== docElement || range.endContainer !== docElement || range.startOffset || range.endOffset || (range.setStart(docElement.body, 0), range.collapse(!0)), range); } /** * get method * * @param {Document} docElement - specifies the get function * @returns {void} * @hidden * @deprecated */ public get(docElement: Document): Selection { return docElement.defaultView.getSelection(); } /** * save method * * @param {Range} range - range value. * @param {Document} docElement - specifies the document. * @returns {void} * @hidden * @deprecated */ public save(range: Range, docElement: Document): NodeSelection { range = (range) ? range.cloneRange() : this.getRange(docElement); return this.saveInstance(range, docElement.body as HTMLBodyElement); } /** * getIndex method * * @param {Node} node - specifies the node value. * @returns {void} * @hidden * @deprecated */ public getIndex(node: Node): number { let index: number; let num: number = 0; node = !node.previousSibling && (node as Element).tagName === 'BR' ? node : node.previousSibling; if (node) { for (let type: number = node.nodeType; node; null) { index = node.nodeType; num++; //eslint-disable-next-line type = index; node = node.previousSibling; } } return num; } private isChildNode(nodeCollection: Node[], parentNode: Node): boolean { for (let index: number = 0; index < parentNode.childNodes.length; index++) { if (nodeCollection.indexOf(parentNode.childNodes[index]) > -1) { return true; } } return false; } private getNode(startNode: Node, endNode: Node, nodeCollection: Node[]): Node { if (endNode === startNode && (startNode.nodeType === 3 || !startNode.firstChild || nodeCollection.indexOf(startNode.firstChild) !== -1 || this.isChildNode(nodeCollection, startNode))) { return null; } if (nodeCollection.indexOf(startNode.firstChild) === -1 && startNode.firstChild && !this.isChildNode(nodeCollection, startNode)) { return startNode.firstChild; } if (startNode.nextSibling) { return startNode.nextSibling; } if (!startNode.parentNode) { return null; } else { return startNode.parentNode; } } /** * getNodeCollection method * * @param {Range} range -specifies the range. * @returns {void} * @hidden * @deprecated */ public getNodeCollection(range: Range): Node[] { let startNode: Node = range.startContainer.childNodes[range.startOffset] || range.startContainer; const endNode: Node = range.endContainer.childNodes[ (range.endOffset > 0) ? (range.endOffset - 1) : range.endOffset] || range.endContainer; if ((startNode === endNode || (startNode.nodeName === 'BR' && startNode === range.endContainer.childNodes[range.endOffset])) && startNode.childNodes.length === 0) { return [startNode]; } if (range.startOffset === range.endOffset && range.startOffset !== 0 && range.startContainer.nodeName === 'PRE') { return [startNode.nodeName === 'BR' || startNode.nodeName === '#text' ? startNode : startNode.childNodes[0]]; } const nodeCollection: Node[] = []; do { if (nodeCollection.indexOf(startNode) === -1) { nodeCollection.push(startNode); } startNode = this.getNode(startNode, endNode, nodeCollection); } while (startNode); return nodeCollection; } /** * getParentNodeCollection method * * @param {Range} range - specifies the range value. * @returns {void} * @hidden * @deprecated */ public getParentNodeCollection(range: Range): Node[] { return this.getParentNodes(this.getNodeCollection(range), range); } /** * getParentNodes method * * @param {Node[]} nodeCollection - specifies the collection of nodes. * @param {Range} range - specifies the range values. * @returns {void} * @hidden * @deprecated */ public getParentNodes(nodeCollection: Node[], range: Range): Node[] { nodeCollection = nodeCollection.reverse(); for (let index: number = 0; index < nodeCollection.length; index++) { if ((nodeCollection.indexOf(nodeCollection[index].parentNode) !== -1) || (nodeCollection[index].nodeType === 3 && range.startContainer !== range.endContainer && range.startContainer.parentNode !== range.endContainer.parentNode)) { nodeCollection.splice(index, 1); index--; } else if (nodeCollection[index].nodeType === 3) { nodeCollection[index] = nodeCollection[index].parentNode; } } return nodeCollection; } /** * getSelectionNodeCollection method * * @param {Range} range - specifies the range value. * @returns {void} * @hidden * @deprecated */ public getSelectionNodeCollection(range: Range): Node[] { return this.getSelectionNodes(this.getNodeCollection(range)); } /** * getSelectionNodeCollection along with BR node method * * @param {Range} range - specifies the range value. * @returns {void} * @hidden * @deprecated */ public getSelectionNodeCollectionBr(range: Range): Node[] { return this.getSelectionNodesBr(this.getNodeCollection(range)); } /** * getParentNodes method * * @param {Node[]} nodeCollection - specifies the collection of nodes. * @returns {void} * @hidden * @deprecated */ public getSelectionNodes(nodeCollection: Node[]): Node[] { nodeCollection = nodeCollection.reverse(); const regEx: RegExp = new RegExp(String.fromCharCode(8203), 'g'); for (let index: number = 0; index < nodeCollection.length; index++) { if (nodeCollection[index].nodeType !== 3 || (nodeCollection[index].textContent.trim() === '' || (nodeCollection[index].textContent.length === 1 && nodeCollection[index].textContent.match(regEx)))) { nodeCollection.splice(index, 1); index--; } } return nodeCollection.reverse(); } /** * Get selection text nodes with br method. * * @param {Node[]} nodeCollection - specifies the collection of nodes. * @returns {void} * @hidden * @deprecated */ public getSelectionNodesBr(nodeCollection: Node[]): Node[] { nodeCollection = nodeCollection.reverse(); const regEx: RegExp = new RegExp(String.fromCharCode(8203), 'g'); for (let index: number = 0; index < nodeCollection.length; index++) { if (nodeCollection[index].nodeName !== 'BR' && (nodeCollection[index].nodeType !== 3 || (nodeCollection[index].textContent.trim() === '' || (nodeCollection[index].textContent.length === 1 && nodeCollection[index].textContent.match(regEx))))) { nodeCollection.splice(index, 1); index--; } } return nodeCollection.reverse(); } /** * getInsertNodeCollection method * * @param {Range} range - specifies the range value. * @returns {void} * @hidden * @deprecated */ public getInsertNodeCollection(range: Range): Node[] { return this.getInsertNodes(this.getNodeCollection(range)); } /** * getInsertNodes method * * @param {Node[]} nodeCollection - specifies the collection of nodes. * @returns {void} * @hidden * @deprecated */ public getInsertNodes(nodeCollection: Node[]): Node[] { nodeCollection = nodeCollection.reverse(); for (let index: number = 0; index < nodeCollection.length; index++) { if ((nodeCollection[index].childNodes.length !== 0 && nodeCollection[index].nodeType !== 3) || (nodeCollection[index].nodeType === 3 && nodeCollection[index].textContent === '')) { nodeCollection.splice(index, 1); index--; } } return nodeCollection.reverse(); } /** * getNodeArray method * * @param {Node} node - specifies the node content. * @param {boolean} isStart - specifies the boolean value. * @param {Document} root - specifies the root document. * @returns {void} * @hidden * @deprecated */ public getNodeArray(node: Node, isStart: boolean, root?: Document): number[] { const array: number[] = []; // eslint-disable-next-line ((isStart) ? (this.startNodeName = []) : (this.endNodeName = [])); for (; node !== (root ? root : this.rootNode); null) { if (isNullOrUndefined(node)) { break; } // eslint-disable-next-line (isStart) ? this.startNodeName.push(node.nodeName.toLowerCase()) : this.endNodeName.push(node.nodeName.toLowerCase()); array.push(this.getIndex(node)); node = node.parentNode; } return array; } private setRangePoint(range: Range, isvalid: boolean, num: number[], size: number): Range { let node: Node = this.rootNode; let index: number = num.length; let constant: number = size; for (; index--; null) { node = node && node.childNodes[num[index]]; } if (node && constant >= 0 && node.nodeName !== 'html') { if (node.nodeType === 3 && node.nodeValue.replace(/\u00a0/g, '&nbsp;') === '&nbsp;') { constant = node.textContent.length; } range[isvalid ? 'setStart' : 'setEnd'](node, constant); } return range; } /** * restore method * * @returns {void} * @hidden * @deprecated */ public restore(): Range { let range: Range = this.range.cloneRange(); range = this.setRangePoint(range, true, this.startContainer, this.startOffset); range = this.setRangePoint(range, false, this.endContainer, this.endOffset); this.selectRange(this.rootNode as Document, range); return range; } public selectRange(docElement: Document, range: Range): void { this.setRange(docElement, range); this.save(range, docElement); } /** * setRange method * * @param {Document} docElement - specifies the document. * @param {Range} range - specifies the range. * @returns {void} * @hidden * @deprecated */ public setRange(docElement: Document, range: Range): void { const selection: Selection = this.get(docElement); selection.removeAllRanges(); selection.addRange(range); } /** * setSelectionText method * * @param {Document} docElement - specifies the documrent * @param {Node} startNode - specifies the starting node. * @param {Node} endNode - specifies the the end node. * @param {number} startIndex - specifies the starting index. * @param {number} endIndex - specifies the end index. * @returns {void} * @hidden * @deprecated */ public setSelectionText(docElement: Document, startNode: Node, endNode: Node, startIndex: number, endIndex: number ): void { const range: Range = docElement.createRange(); range.setStart(startNode, startIndex); range.setEnd(endNode, endIndex); this.setRange(docElement, range); } /** * setSelectionContents method * * @param {Document} docElement - specifies the document. * @param {Node} element - specifies the node. * @returns {void} * @hidden * @deprecated */ public setSelectionContents(docElement: Document, element: Node): void { const range: Range = docElement.createRange(); range.selectNode(element); this.setRange(docElement, range); } /** * setSelectionNode method * * @param {Document} docElement - specifies the document. * @param {Node} element - specifies the node. * @returns {void} * @hidden * @deprecated */ public setSelectionNode(docElement: Document, element: Node): void { const range: Range = docElement.createRange(); range.selectNodeContents(element); this.setRange(docElement, range); } /** * getSelectedNodes method * * @param {Document} docElement - specifies the document. * @returns {void} * @hidden * @deprecated */ public getSelectedNodes(docElement: Document): Node[] { return this.getNodeCollection(this.getRange(docElement)); } /** * Clear method * * @param {Document} docElement - specifies the document. * @returns {void} * @hidden * @deprecated */ public Clear(docElement: Document): void { this.get(docElement).removeAllRanges(); } /** * insertParentNode method * * @param {Document} docElement - specifies the document. * @param {Node} newNode - specicfies the new node. * @param {Range} range - specifies the range. * @returns {void} * @hidden * @deprecated */ public insertParentNode(docElement: Document, newNode: Node, range: Range): void { range.surroundContents(newNode); this.selectRange(docElement, range); } /** * setCursorPoint method * * @param {Document} docElement - specifies the document. * @param {Element} element - specifies the element. * @param {number} point - specifies the point. * @returns {void} * @hidden * @deprecated */ public setCursorPoint(docElement: Document, element: Element, point: number): void { const range: Range = docElement.createRange(); const selection: Selection = docElement.defaultView.getSelection(); range.setStart(element, point); range.collapse(true); selection.removeAllRanges(); selection.addRange(range); } }
the_stack
import 'neuroglancer/data_panel_layout.css'; import debounce from 'lodash/debounce'; import {ChunkManager} from 'neuroglancer/chunk_manager/frontend'; import {DisplayContext} from 'neuroglancer/display_context'; import {LayerManager, MouseSelectionState, SelectedLayerState, TrackableDataSelectionState} from 'neuroglancer/layer'; import * as L from 'neuroglancer/layout'; import {DisplayPose, LinkedOrientationState, LinkedPosition, linkedStateLegacyJsonView, LinkedZoomState, NavigationState, OrientationState, TrackableZoomInterface} from 'neuroglancer/navigation_state'; import {PerspectivePanel} from 'neuroglancer/perspective_view/panel'; import {RenderedDataPanel} from 'neuroglancer/rendered_data_panel'; import {RenderLayerRole} from 'neuroglancer/renderlayer'; import {SliceView} from 'neuroglancer/sliceview/frontend'; import {SliceViewerState, SliceViewPanel} from 'neuroglancer/sliceview/panel'; import {TrackableBoolean} from 'neuroglancer/trackable_boolean'; import {TrackableValue, WatchableSet, WatchableValueInterface} from 'neuroglancer/trackable_value'; import {TrackableRGB} from 'neuroglancer/util/color'; import {Borrowed, Owned, RefCounted} from 'neuroglancer/util/disposable'; import {removeChildren, removeFromParent} from 'neuroglancer/util/dom'; import {EventActionMap, registerActionListener} from 'neuroglancer/util/event_action_map'; import {quat} from 'neuroglancer/util/geom'; import {verifyObject, verifyObjectProperty, verifyPositiveInt} from 'neuroglancer/util/json'; import {NullarySignal} from 'neuroglancer/util/signal'; import {optionallyRestoreFromJsonMember, Trackable} from 'neuroglancer/util/trackable'; import {WatchableMap} from 'neuroglancer/util/watchable_map'; import {VisibilityPrioritySpecification} from 'neuroglancer/viewer_state'; import {DisplayDimensionsWidget} from 'neuroglancer/widget/display_dimensions_widget'; import {ScaleBarOptions} from 'neuroglancer/widget/scale_bar'; export interface SliceViewViewerState { chunkManager: ChunkManager; navigationState: NavigationState; layerManager: LayerManager; wireFrame: WatchableValueInterface<boolean>; } export class InputEventBindings { perspectiveView = new EventActionMap(); sliceView = new EventActionMap(); } export interface ViewerUIState extends SliceViewViewerState, VisibilityPrioritySpecification { display: DisplayContext; mouseState: MouseSelectionState; perspectiveNavigationState: NavigationState; selectionDetailsState: TrackableDataSelectionState; showPerspectiveSliceViews: TrackableBoolean; showAxisLines: TrackableBoolean; wireFrame: TrackableBoolean; showScaleBar: TrackableBoolean; scaleBarOptions: TrackableValue<ScaleBarOptions>; visibleLayerRoles: WatchableSet<RenderLayerRole>; selectedLayer: SelectedLayerState; inputEventBindings: InputEventBindings; crossSectionBackgroundColor: TrackableRGB; perspectiveViewBackgroundColor: TrackableRGB; } export interface DataDisplayLayout extends RefCounted { rootElement: HTMLElement; container: DataPanelLayoutContainer; } type NamedAxes = 'xy'|'xz'|'yz'; const AXES_RELATIVE_ORIENTATION = new Map<NamedAxes, quat|undefined>([ ['xy', undefined], ['xz', quat.rotateX(quat.create(), quat.create(), Math.PI / 2)], ['yz', quat.rotateY(quat.create(), quat.create(), Math.PI / 2)], ]); const oneSquareSymbol = '◻'; const LAYOUT_SYMBOLS = new Map<string, string>([ ['4panel', '◱'], ['3d', oneSquareSymbol], ]); export function makeSliceView(viewerState: SliceViewViewerState, baseToSelf?: quat) { let navigationState: NavigationState; if (baseToSelf === undefined) { navigationState = viewerState.navigationState.addRef(); } else { navigationState = new NavigationState( new DisplayPose( viewerState.navigationState.pose.position.addRef(), viewerState.navigationState.pose.displayDimensionRenderInfo.addRef(), OrientationState.makeRelative( viewerState.navigationState.pose.orientation, baseToSelf)), viewerState.navigationState.zoomFactor.addRef(), viewerState.navigationState.depthRange.addRef()); } return new SliceView( viewerState.chunkManager, viewerState.layerManager, navigationState, viewerState.wireFrame); } export function makeNamedSliceView(viewerState: SliceViewViewerState, axes: NamedAxes) { return makeSliceView(viewerState, AXES_RELATIVE_ORIENTATION.get(axes)!); } export function makeOrthogonalSliceViews(viewerState: SliceViewViewerState) { return new Map<NamedAxes, SliceView>([ ['xy', makeNamedSliceView(viewerState, 'xy')], ['xz', makeNamedSliceView(viewerState, 'xz')], ['yz', makeNamedSliceView(viewerState, 'yz')], ]); } export function getCommonViewerState(viewer: ViewerUIState) { return { crossSectionBackgroundColor: viewer.crossSectionBackgroundColor, perspectiveViewBackgroundColor: viewer.perspectiveViewBackgroundColor, selectionDetailsState: viewer.selectionDetailsState, mouseState: viewer.mouseState, layerManager: viewer.layerManager, showAxisLines: viewer.showAxisLines, wireFrame: viewer.wireFrame, visibleLayerRoles: viewer.visibleLayerRoles, selectedLayer: viewer.selectedLayer, visibility: viewer.visibility, scaleBarOptions: viewer.scaleBarOptions, }; } function getCommonPerspectiveViewerState(container: DataPanelLayoutContainer) { const {viewer} = container; return { ...getCommonViewerState(viewer), navigationState: viewer.perspectiveNavigationState, inputEventMap: viewer.inputEventBindings.perspectiveView, orthographicProjection: container.specification.orthographicProjection, showScaleBar: viewer.showScaleBar, rpc: viewer.chunkManager.rpc!, }; } function getCommonSliceViewerState(viewer: ViewerUIState) { return { ...getCommonViewerState(viewer), navigationState: viewer.navigationState, inputEventMap: viewer.inputEventBindings.sliceView, }; } function addDisplayDimensionsWidget(layout: DataDisplayLayout, panel: RenderedDataPanel) { const {navigationState} = panel; panel.element.appendChild( layout .registerDisposer(new DisplayDimensionsWidget( navigationState.pose.displayDimensionRenderInfo.addRef(), navigationState.zoomFactor, navigationState.depthRange.addRef(), (panel instanceof SliceViewPanel) ? 'px' : 'vh')) .element); } function registerRelatedLayouts( layout: DataDisplayLayout, panel: RenderedDataPanel, relatedLayouts: string[]) { const controls = document.createElement('div'); controls.className = 'neuroglancer-data-panel-layout-controls'; layout.registerDisposer(() => removeFromParent(controls)); for (let i = 0; i < 2; ++i) { const relatedLayout = relatedLayouts[Math.min(relatedLayouts.length - 1, i)]; layout.registerDisposer(registerActionListener( panel.element, i === 0 ? 'toggle-layout' : 'toggle-layout-alternative', (event: Event) => { layout.container.name = relatedLayout; event.stopPropagation(); })); } for (const relatedLayout of relatedLayouts) { const button = document.createElement('button'); const innerDiv = document.createElement('div'); button.appendChild(innerDiv); innerDiv.textContent = LAYOUT_SYMBOLS.get(relatedLayout)!; button.title = `Switch to ${relatedLayout} layout.`; button.addEventListener('click', () => { layout.container.name = relatedLayout; }); controls.appendChild(button); } panel.element.appendChild(controls); } function makeSliceViewFromSpecification( viewer: SliceViewViewerState, specification: Borrowed<CrossSectionSpecification>) { const sliceView = new SliceView( viewer.chunkManager, viewer.layerManager, specification.navigationState.addRef(), viewer.wireFrame); const updateViewportSize = () => { const {width: {value: width}, height: {value: height}} = specification; sliceView.projectionParameters.setViewport({ width, height, logicalWidth: width, logicalHeight: height, visibleLeftFraction: 0, visibleTopFraction: 0, visibleWidthFraction: 1, visibleHeightFraction: 1 }); }; sliceView.registerDisposer(specification.width.changed.add(updateViewportSize)); sliceView.registerDisposer(specification.height.changed.add(updateViewportSize)); updateViewportSize(); return sliceView; } function addUnconditionalSliceViews( viewer: SliceViewViewerState, panel: PerspectivePanel, crossSections: Borrowed<CrossSectionSpecificationMap>) { const previouslyAdded = new Map<Borrowed<CrossSectionSpecification>, Borrowed<SliceView>>(); const update = () => { const currentCrossSections = new Set<Borrowed<CrossSectionSpecification>>(); // Add missing cross sections. for (const crossSection of crossSections.values()) { currentCrossSections.add(crossSection); if (previouslyAdded.has(crossSection)) { continue; } const sliceView = makeSliceViewFromSpecification(viewer, crossSection); panel.sliceViews.set(sliceView, true); previouslyAdded.set(crossSection, sliceView); } // Remove extra cross sections. for (const [crossSection, sliceView] of previouslyAdded) { if (currentCrossSections.has(crossSection)) { continue; } panel.sliceViews.delete(sliceView); } }; update(); } export class FourPanelLayout extends RefCounted { constructor( public container: DataPanelLayoutContainer, public rootElement: HTMLElement, public viewer: ViewerUIState, crossSections: Borrowed<CrossSectionSpecificationMap>) { super(); let sliceViews = makeOrthogonalSliceViews(viewer); let {display} = viewer; const perspectiveViewerState = { ...getCommonPerspectiveViewerState(container), showSliceViews: viewer.showPerspectiveSliceViews, showSliceViewsCheckbox: true, }; const sliceViewerState = { ...getCommonSliceViewerState(viewer), showScaleBar: viewer.showScaleBar, }; const sliceViewerStateWithoutScaleBar = { ...getCommonSliceViewerState(viewer), showScaleBar: new TrackableBoolean(false, false), }; const makeSliceViewPanel = (axes: NamedAxes, element: HTMLElement, state: SliceViewerState, displayDimensionsWidget: boolean) => { const panel = this.registerDisposer( new SliceViewPanel(display, element, sliceViews.get(axes)!, state)); if (displayDimensionsWidget) { addDisplayDimensionsWidget(this, panel); } registerRelatedLayouts(this, panel, [axes, `${axes}-3d`]); return panel; }; let mainDisplayContents = [ L.withFlex(1, L.box('column', [ L.withFlex(1, L.box('row', [ L.withFlex(1, element => { makeSliceViewPanel('xy', element, sliceViewerState, true); }), L.withFlex(1, element => { makeSliceViewPanel('xz', element, sliceViewerStateWithoutScaleBar, false); }) ])), L.withFlex(1, L.box('row', [ L.withFlex(1, element => { let panel = this.registerDisposer( new PerspectivePanel(display, element, perspectiveViewerState)); for (let sliceView of sliceViews.values()) { panel.sliceViews.set(sliceView.addRef(), false); } addDisplayDimensionsWidget(this, panel); addUnconditionalSliceViews(viewer, panel, crossSections); registerRelatedLayouts(this, panel, ['3d']); }), L.withFlex(1, element => { makeSliceViewPanel('yz', element, sliceViewerStateWithoutScaleBar, false); }) ])), ])) ]; L.box('row', mainDisplayContents)(rootElement); } disposed() { removeChildren(this.rootElement); super.disposed(); } } export class SliceViewPerspectiveTwoPanelLayout extends RefCounted { constructor( public container: DataPanelLayoutContainer, public rootElement: HTMLElement, public viewer: ViewerUIState, public direction: 'row'|'column', axes: NamedAxes, crossSections: Borrowed<CrossSectionSpecificationMap>) { super(); let sliceView = makeNamedSliceView(viewer, axes); let {display} = viewer; const perspectiveViewerState = { ...getCommonPerspectiveViewerState(container), showSliceViews: viewer.showPerspectiveSliceViews, showSliceViewsCheckbox: true, }; const sliceViewerState = { ...getCommonSliceViewerState(viewer), showScaleBar: viewer.showScaleBar, }; L.withFlex(1, L.box(direction, [ L.withFlex( 1, element => { const panel = this.registerDisposer( new SliceViewPanel(display, element, sliceView, sliceViewerState)); addDisplayDimensionsWidget(this, panel); registerRelatedLayouts(this, panel, [axes, '4panel']); }), L.withFlex( 1, element => { let panel = this.registerDisposer( new PerspectivePanel(display, element, perspectiveViewerState)); panel.sliceViews.set(sliceView.addRef(), false); addUnconditionalSliceViews(viewer, panel, crossSections); addDisplayDimensionsWidget(this, panel); registerRelatedLayouts(this, panel, ['3d', '4panel']); }), ]))(rootElement); } disposed() { removeChildren(this.rootElement); super.disposed(); } } export class SinglePanelLayout extends RefCounted { constructor( public container: DataPanelLayoutContainer, public rootElement: HTMLElement, public viewer: ViewerUIState, axes: NamedAxes) { super(); let sliceView = makeNamedSliceView(viewer, axes); const sliceViewerState = { ...getCommonSliceViewerState(viewer), showScaleBar: viewer.showScaleBar, }; L.box('row', [L.withFlex(1, element => { const panel = this.registerDisposer( new SliceViewPanel(viewer.display, element, sliceView, sliceViewerState)); addDisplayDimensionsWidget(this, panel); registerRelatedLayouts(this, panel, ['4panel', `${axes}-3d`]); })])(rootElement); } disposed() { removeChildren(this.rootElement); super.disposed(); } } export class SinglePerspectiveLayout extends RefCounted { constructor( public container: DataPanelLayoutContainer, public rootElement: HTMLElement, public viewer: ViewerUIState, crossSections: Borrowed<CrossSectionSpecificationMap>) { super(); let perspectiveViewerState = { ...getCommonPerspectiveViewerState(container), showSliceViews: new TrackableBoolean(false, false), }; L.box('row', [L.withFlex(1, element => { const panel = this.registerDisposer( new PerspectivePanel(viewer.display, element, perspectiveViewerState)); addUnconditionalSliceViews(viewer, panel, crossSections); addDisplayDimensionsWidget(this, panel); registerRelatedLayouts(this, panel, ['4panel']); })])(rootElement); } disposed() { removeChildren(this.rootElement); super.disposed(); } } export const LAYOUTS = new Map<string, { factory: (container: DataPanelLayoutContainer, element: HTMLElement, viewer: ViewerUIState, crossSections: Borrowed<CrossSectionSpecificationMap>) => DataDisplayLayout }>( [ [ '4panel', { factory: (container, element, viewer, crossSections) => new FourPanelLayout(container, element, viewer, crossSections) } ], [ '3d', { factory: (container, element, viewer, crossSections) => new SinglePerspectiveLayout(container, element, viewer, crossSections) } ], ], ); for (const axes of AXES_RELATIVE_ORIENTATION.keys()) { LAYOUTS.set(axes, { factory: (container, element, viewer) => new SinglePanelLayout(container, element, viewer, <NamedAxes>axes) }); const splitLayout = `${axes}-3d`; LAYOUT_SYMBOLS.set(axes, oneSquareSymbol); LAYOUT_SYMBOLS.set(splitLayout, '◫'); LAYOUTS.set(splitLayout, { factory: (container, element, viewer, crossSections) => new SliceViewPerspectiveTwoPanelLayout( container, element, viewer, 'row', <NamedAxes>axes, crossSections) }); } export function getLayoutByName(obj: any) { let layout = LAYOUTS.get(obj); if (layout === undefined) { throw new Error(`Invalid layout name: ${JSON.stringify(obj)}.`); } return layout; } export function validateLayoutName(obj: any) { getLayoutByName(obj); return <string>obj; } export class CrossSectionSpecification extends RefCounted implements Trackable { width = new TrackableValue<number>(1000, verifyPositiveInt); height = new TrackableValue<number>(1000, verifyPositiveInt); position: LinkedPosition; orientation: LinkedOrientationState; scale: LinkedZoomState<TrackableZoomInterface>; navigationState: NavigationState; changed = new NullarySignal(); constructor(parent: Borrowed<NavigationState>) { super(); this.position = new LinkedPosition(parent.position.addRef()); this.position.changed.add(this.changed.dispatch); this.orientation = new LinkedOrientationState(parent.pose.orientation.addRef()); this.orientation.changed.add(this.changed.dispatch); this.width.changed.add(this.changed.dispatch); this.height.changed.add(this.changed.dispatch); this.scale = new LinkedZoomState( parent.zoomFactor.addRef(), parent.zoomFactor.displayDimensionRenderInfo.addRef()); this.scale.changed.add(this.changed.dispatch); this.navigationState = this.registerDisposer(new NavigationState( new DisplayPose( this.position.value, parent.pose.displayDimensionRenderInfo.addRef(), this.orientation.value), this.scale.value, parent.depthRange.addRef())); } restoreState(obj: any) { verifyObject(obj); optionallyRestoreFromJsonMember(obj, 'width', this.width); optionallyRestoreFromJsonMember(obj, 'height', this.height); optionallyRestoreFromJsonMember(obj, 'position', linkedStateLegacyJsonView(this.position)); optionallyRestoreFromJsonMember(obj, 'orientation', this.orientation); optionallyRestoreFromJsonMember(obj, 'scale', this.scale); optionallyRestoreFromJsonMember(obj, 'zoom', linkedStateLegacyJsonView(this.scale)); } reset() { this.width.reset(); this.height.reset(); this.position.reset(); this.orientation.reset(); this.scale.reset(); } toJSON() { return { width: this.width.toJSON(), height: this.height.toJSON(), position: this.position.toJSON(), orientation: this.orientation.toJSON(), scale: this.scale.toJSON(), }; } } export class CrossSectionSpecificationMap extends WatchableMap<string, CrossSectionSpecification> { constructor(private parentNavigationState: Owned<NavigationState>) { super( (context, spec) => context.registerDisposer( context.registerDisposer(spec).changed.add(this.changed.dispatch)), ); this.registerDisposer(parentNavigationState); } restoreState(obj: any) { verifyObject(obj); for (const key of Object.keys(obj)) { const state = new CrossSectionSpecification(this.parentNavigationState); try { this.set(key, state.addRef()); state.restoreState(obj[key]); } finally { state.dispose(); } } } reset() { this.clear(); } toJSON() { if (this.size === 0) return undefined; const obj: {[key: string]: any} = {}; for (const [k, v] of this) { obj[k] = v.toJSON(); } return obj; } } export class DataPanelLayoutSpecification extends RefCounted implements Trackable { changed = new NullarySignal(); type: TrackableValue<string>; crossSections: CrossSectionSpecificationMap; orthographicProjection = new TrackableBoolean(false); constructor(parentNavigationState: Owned<NavigationState>, defaultLayout: string) { super(); this.type = new TrackableValue<string>(defaultLayout, validateLayoutName); this.type.changed.add(this.changed.dispatch); this.crossSections = this.registerDisposer(new CrossSectionSpecificationMap(parentNavigationState.addRef())); this.crossSections.changed.add(this.changed.dispatch); this.orthographicProjection.changed.add(this.changed.dispatch); this.registerDisposer(parentNavigationState); } reset() { this.crossSections.clear(); this.orthographicProjection.reset(); this.type.reset(); } restoreState(obj: any) { this.crossSections.clear(); this.orthographicProjection.reset(); if (typeof obj === 'string') { this.type.restoreState(obj); } else { verifyObject(obj); verifyObjectProperty(obj, 'type', x => this.type.restoreState(x)); verifyObjectProperty( obj, 'orthographicProjection', x => this.orthographicProjection.restoreState(x)); verifyObjectProperty( obj, 'crossSections', x => x !== undefined && this.crossSections.restoreState(x)); } } toJSON() { const {type, crossSections, orthographicProjection} = this; const orthographicProjectionJson = orthographicProjection.toJSON(); if (crossSections.size === 0 && orthographicProjectionJson === undefined) { return type.value; } return { type: type.value, crossSections: crossSections.toJSON(), orthographicProjection: orthographicProjectionJson, }; } } export class DataPanelLayoutContainer extends RefCounted { element = document.createElement('div'); specification: Owned<DataPanelLayoutSpecification>; private layout: DataDisplayLayout|undefined; get name() { return this.specification.type.value; } set name(value: string) { this.specification.type.value = value; } constructor(public viewer: ViewerUIState, defaultLayout: string) { super(); this.specification = this.registerDisposer( new DataPanelLayoutSpecification(this.viewer.navigationState.addRef(), defaultLayout)); this.element.style.flex = '1'; const scheduleUpdateLayout = this.registerCancellable(debounce(() => this.updateLayout(), 0)); this.specification.type.changed.add(scheduleUpdateLayout); registerActionListener( this.element, 'toggle-orthographic-projection', () => this.specification.orthographicProjection.toggle()); // Ensure the layout is updated before drawing begins to avoid flicker. this.registerDisposer( this.viewer.display.updateStarted.add(() => scheduleUpdateLayout.flush())); scheduleUpdateLayout(); } get changed() { return this.specification.changed; } toJSON() { return this.specification.toJSON(); } restoreState(obj: any) { this.specification.restoreState(obj); } reset() { this.specification.reset(); } private disposeLayout() { let {layout} = this; if (layout !== undefined) { layout.dispose(); this.layout = undefined; } } private updateLayout() { this.disposeLayout(); this.layout = getLayoutByName(this.name).factory( this, this.element, this.viewer, this.specification.crossSections); } disposed() { this.disposeLayout(); super.disposed(); } }
the_stack
import { ethers, upgrades, waffle } from "hardhat"; import { Signer, constants, BigNumber } from "ethers"; import chai from "chai"; import { solidity } from "ethereum-waffle"; import "@openzeppelin/test-helpers"; import { AlpacaToken, CakeToken, DebtToken, FairLaunch, FairLaunch__factory, MockContractContext, MockContractContext__factory, MockERC20, MockERC20__factory, MockWBNB, PancakeFactory, PancakeMasterChef, PancakeMasterChef__factory, PancakePair, PancakePair__factory, PancakeRouterV2, PancakeswapV2RestrictedStrategyAddBaseTokenOnly, PancakeswapV2RestrictedStrategyLiquidate, PancakeswapV2RestrictedStrategyPartialCloseLiquidate, PancakeswapV2Worker, PancakeswapV2Worker__factory, PancakeswapV2Worker02, PancakeswapV2Worker02__factory, SimpleVaultConfig, SyrupBar, Vault, Vault__factory, WNativeRelayer, MockBeneficialVault__factory, MockBeneficialVault, PancakeswapV2RestrictedStrategyAddTwoSidesOptimal, PancakeswapV2RestrictedStrategyWithdrawMinimizeTrading, PancakeswapV2RestrictedStrategyPartialCloseMinimizeTrading, MasterChef, } from "../../../../../typechain"; import * as AssertHelpers from "../../../../helpers/assert"; import * as TimeHelpers from "../../../../helpers/time"; import { parseEther } from "ethers/lib/utils"; import { DeployHelper } from "../../../../helpers/deploy"; import { SwapHelper } from "../../../../helpers/swap"; import { Worker02Helper } from "../../../../helpers/worker"; chai.use(solidity); const { expect } = chai; describe("Vault - PancakeswapV202", () => { const FOREVER = "2000000000"; const ALPACA_BONUS_LOCK_UP_BPS = 7000; const ALPACA_REWARD_PER_BLOCK = ethers.utils.parseEther("5000"); const CAKE_REWARD_PER_BLOCK = ethers.utils.parseEther("0.076"); const REINVEST_BOUNTY_BPS = "100"; // 1% reinvest bounty const RESERVE_POOL_BPS = "1000"; // 10% reserve pool const KILL_PRIZE_BPS = "1000"; // 10% Kill prize const INTEREST_RATE = "3472222222222"; // 30% per year const MIN_DEBT_SIZE = ethers.utils.parseEther("1"); // 1 BTOKEN min debt size const WORK_FACTOR = "7000"; const KILL_FACTOR = "8000"; const MAX_REINVEST_BOUNTY: string = "900"; const DEPLOYER = "0xC44f82b07Ab3E691F826951a6E335E1bC1bB0B51"; const BENEFICIALVAULT_BOUNTY_BPS = "1000"; const REINVEST_THRESHOLD = ethers.utils.parseEther("1"); // If pendingCake > 1 $CAKE, then reinvest const KILL_TREASURY_BPS = "100"; const POOL_ID = 1; /// Pancakeswap-related instance(s) let factoryV2: PancakeFactory; let routerV2: PancakeRouterV2; let wbnb: MockWBNB; let lp: PancakePair; /// Token-related instance(s) let baseToken: MockERC20; let farmToken: MockERC20; let cake: CakeToken; let syrup: SyrupBar; let debtToken: DebtToken; /// Strategy-ralted instance(s) let addStrat: PancakeswapV2RestrictedStrategyAddBaseTokenOnly; let twoSidesStrat: PancakeswapV2RestrictedStrategyAddTwoSidesOptimal; let liqStrat: PancakeswapV2RestrictedStrategyLiquidate; let minimizeStrat: PancakeswapV2RestrictedStrategyWithdrawMinimizeTrading; let partialCloseStrat: PancakeswapV2RestrictedStrategyPartialCloseLiquidate; let partialCloseMinimizeStrat: PancakeswapV2RestrictedStrategyPartialCloseMinimizeTrading; /// Vault-related instance(s) let simpleVaultConfig: SimpleVaultConfig; let wNativeRelayer: WNativeRelayer; let vault: Vault; /// FairLaunch-related instance(s) let fairLaunch: FairLaunch; let alpacaToken: AlpacaToken; /// PancakeswapMasterChef-related instance(s) let masterChef: PancakeMasterChef; let pancakeswapV2Worker: PancakeswapV2Worker02; let pancakeswapV2Worker01: PancakeswapV2Worker; /// Timelock instance(s) let whitelistedContract: MockContractContext; let evilContract: MockContractContext; // Accounts let deployer: Signer; let alice: Signer; let bob: Signer; let eve: Signer; let deployerAddress: string; let aliceAddress: string; let bobAddress: string; let eveAddress: string; // Contract Signer let baseTokenAsAlice: MockERC20; let baseTokenAsBob: MockERC20; let farmTokenAsAlice: MockERC20; let fairLaunchAsAlice: FairLaunch; let lpAsAlice: PancakePair; let lpAsBob: PancakePair; let pancakeMasterChefAsAlice: PancakeMasterChef; let pancakeMasterChefAsBob: PancakeMasterChef; let pancakeswapV2WorkerAsEve: PancakeswapV2Worker02; let pancakeswapV2Worker01AsEve: PancakeswapV2Worker; let vaultAsAlice: Vault; let vaultAsBob: Vault; let vaultAsEve: Vault; // Test Helper let swapHelper: SwapHelper; let workerHelper: Worker02Helper; async function fixture() { [deployer, alice, bob, eve] = await ethers.getSigners(); [deployerAddress, aliceAddress, bobAddress, eveAddress] = await Promise.all([ deployer.getAddress(), alice.getAddress(), bob.getAddress(), eve.getAddress(), ]); const deployHelper = new DeployHelper(deployer); // Setup MockContractContext const MockContractContext = (await ethers.getContractFactory( "MockContractContext", deployer )) as MockContractContext__factory; whitelistedContract = await MockContractContext.deploy(); await whitelistedContract.deployed(); evilContract = await MockContractContext.deploy(); await evilContract.deployed(); /// Setup token stuffs [baseToken, farmToken] = await deployHelper.deployBEP20([ { name: "BTOKEN", symbol: "BTOKEN", decimals: "18", holders: [ { address: deployerAddress, amount: ethers.utils.parseEther("1000") }, { address: aliceAddress, amount: ethers.utils.parseEther("1000") }, { address: bobAddress, amount: ethers.utils.parseEther("1000") }, ], }, { name: "FTOKEN", symbol: "FTOKEN", decimals: "18", holders: [ { address: deployerAddress, amount: ethers.utils.parseEther("1000") }, { address: aliceAddress, amount: ethers.utils.parseEther("1000") }, { address: bobAddress, amount: ethers.utils.parseEther("1000") }, ], }, ]); wbnb = await deployHelper.deployWBNB(); [factoryV2, routerV2, cake, syrup, masterChef] = await deployHelper.deployPancakeV2(wbnb, CAKE_REWARD_PER_BLOCK, [ { address: deployerAddress, amount: ethers.utils.parseEther("100") }, ]); [alpacaToken, fairLaunch] = await deployHelper.deployAlpacaFairLaunch( ALPACA_REWARD_PER_BLOCK, ALPACA_BONUS_LOCK_UP_BPS, 132, 137 ); [vault, simpleVaultConfig, wNativeRelayer] = await deployHelper.deployVault( wbnb, { minDebtSize: MIN_DEBT_SIZE, interestRate: INTEREST_RATE, reservePoolBps: RESERVE_POOL_BPS, killPrizeBps: KILL_PRIZE_BPS, killTreasuryBps: KILL_TREASURY_BPS, killTreasuryAddress: DEPLOYER, }, fairLaunch, baseToken ); // Setup strategies [addStrat, liqStrat, twoSidesStrat, minimizeStrat, partialCloseStrat, partialCloseMinimizeStrat] = await deployHelper.deployPancakeV2Strategies(routerV2, vault, wbnb, wNativeRelayer); // whitelisted contract to be able to call work await simpleVaultConfig.setWhitelistedCallers([whitelistedContract.address], true); // whitelisted to be able to call kill await simpleVaultConfig.setWhitelistedLiquidators([await alice.getAddress(), await eve.getAddress()], true); // Set approved add strategies await simpleVaultConfig.setApprovedAddStrategy([addStrat.address, twoSidesStrat.address], true); // Setup BTOKEN-FTOKEN pair on Pancakeswap // Add lp to masterChef's pool await factoryV2.createPair(baseToken.address, farmToken.address); lp = PancakePair__factory.connect(await factoryV2.getPair(farmToken.address, baseToken.address), deployer); await masterChef.add(1, lp.address, true); /// Setup PancakeswapV2Worker02 pancakeswapV2Worker = await deployHelper.deployPancakeV2Worker02( vault, baseToken, masterChef, routerV2, POOL_ID, WORK_FACTOR, KILL_FACTOR, addStrat, liqStrat, REINVEST_BOUNTY_BPS, [eveAddress], DEPLOYER, [cake.address, wbnb.address, baseToken.address], [twoSidesStrat.address, minimizeStrat.address, partialCloseStrat.address, partialCloseMinimizeStrat.address], simpleVaultConfig ); pancakeswapV2Worker01 = await deployHelper.deployPancakeV2Worker( vault, baseToken, masterChef, routerV2, POOL_ID, WORK_FACTOR, KILL_FACTOR, addStrat, liqStrat, REINVEST_BOUNTY_BPS, [eveAddress], [twoSidesStrat.address, minimizeStrat.address, partialCloseStrat.address, partialCloseMinimizeStrat.address], simpleVaultConfig ); swapHelper = new SwapHelper( factoryV2.address, routerV2.address, BigNumber.from(9975), BigNumber.from(10000), deployer ); await swapHelper.addLiquidities([ { token0: baseToken, token1: farmToken, amount0desired: ethers.utils.parseEther("1"), amount1desired: ethers.utils.parseEther("0.1"), }, { token0: cake, token1: wbnb, amount0desired: ethers.utils.parseEther("0.1"), amount1desired: ethers.utils.parseEther("1"), }, { token0: baseToken, token1: wbnb, amount0desired: ethers.utils.parseEther("1"), amount1desired: ethers.utils.parseEther("1"), }, { token0: farmToken, token1: wbnb, amount0desired: ethers.utils.parseEther("1"), amount1desired: ethers.utils.parseEther("1"), }, ]); // Contract signer baseTokenAsAlice = MockERC20__factory.connect(baseToken.address, alice); baseTokenAsBob = MockERC20__factory.connect(baseToken.address, bob); farmTokenAsAlice = MockERC20__factory.connect(farmToken.address, alice); lpAsAlice = PancakePair__factory.connect(lp.address, alice); lpAsBob = PancakePair__factory.connect(lp.address, bob); fairLaunchAsAlice = FairLaunch__factory.connect(fairLaunch.address, alice); pancakeMasterChefAsAlice = PancakeMasterChef__factory.connect(masterChef.address, alice); pancakeMasterChefAsBob = PancakeMasterChef__factory.connect(masterChef.address, bob); vaultAsAlice = Vault__factory.connect(vault.address, alice); vaultAsBob = Vault__factory.connect(vault.address, bob); vaultAsEve = Vault__factory.connect(vault.address, eve); pancakeswapV2WorkerAsEve = PancakeswapV2Worker02__factory.connect(pancakeswapV2Worker.address, eve); pancakeswapV2Worker01AsEve = PancakeswapV2Worker__factory.connect(pancakeswapV2Worker01.address, eve); } beforeEach(async () => { await waffle.loadFixture(fixture); // reassign SwapHelper here due to provider will be different for each test-case workerHelper = new Worker02Helper(pancakeswapV2Worker.address, masterChef.address); }); context("when worker is initialized", async () => { it("should has FTOKEN as a farmingToken in PancakeswapWorker", async () => { expect(await pancakeswapV2Worker.farmingToken()).to.be.equal(farmToken.address); }); it("should initialized the correct fee and feeDenom", async () => { expect(await pancakeswapV2Worker.fee()).to.be.eq("9975"); expect(await pancakeswapV2Worker.feeDenom()).to.be.eq("10000"); }); it("should give rewards out when you stake LP tokens", async () => { // Deployer sends some LP tokens to Alice and Bob await lp.transfer(aliceAddress, ethers.utils.parseEther("0.05")); await lp.transfer(bobAddress, ethers.utils.parseEther("0.05")); // Alice and Bob stake 0.01 LP tokens and waits for 1 day await lpAsAlice.approve(masterChef.address, ethers.utils.parseEther("0.01")); await lpAsBob.approve(masterChef.address, ethers.utils.parseEther("0.02")); await pancakeMasterChefAsAlice.deposit(POOL_ID, ethers.utils.parseEther("0.01")); await pancakeMasterChefAsBob.deposit(POOL_ID, ethers.utils.parseEther("0.02")); // alice +1 Reward // Alice and Bob withdraw stake from the pool await pancakeMasterChefAsBob.withdraw(POOL_ID, ethers.utils.parseEther("0.02")); // alice +1/3 Reward Bob + 2/3 Reward await pancakeMasterChefAsAlice.withdraw(POOL_ID, ethers.utils.parseEther("0.01")); // alice +1 Reward AssertHelpers.assertAlmostEqual( (await cake.balanceOf(aliceAddress)).toString(), CAKE_REWARD_PER_BLOCK.mul(BigNumber.from(7)).div(BigNumber.from(3)).toString() ); AssertHelpers.assertAlmostEqual( (await cake.balanceOf(bobAddress)).toString(), CAKE_REWARD_PER_BLOCK.mul(2).div(3).toString() ); }); }); context("when owner is setting worker", async () => { describe("#reinvestConfig", async () => { it("should set reinvest config correctly", async () => { await expect( pancakeswapV2Worker.setReinvestConfig(250, ethers.utils.parseEther("1"), [cake.address, baseToken.address]) ) .to.be.emit(pancakeswapV2Worker, "SetReinvestConfig") .withArgs(deployerAddress, 250, ethers.utils.parseEther("1"), [cake.address, baseToken.address]); expect(await pancakeswapV2Worker.reinvestBountyBps()).to.be.eq(250); expect(await pancakeswapV2Worker.reinvestThreshold()).to.be.eq(ethers.utils.parseEther("1")); expect(await pancakeswapV2Worker.getReinvestPath()).to.deep.eq([cake.address, baseToken.address]); }); it("should revert when owner set reinvestBountyBps > max", async () => { await expect( pancakeswapV2Worker.setReinvestConfig(1000, "0", [cake.address, baseToken.address]) ).to.be.revertedWith( "PancakeswapV2Worker02::setReinvestConfig:: _reinvestBountyBps exceeded maxReinvestBountyBps" ); expect(await pancakeswapV2Worker.reinvestBountyBps()).to.be.eq(100); }); it("should revert when owner set reinvest path that doesn't start with $CAKE and end with $BTOKN", async () => { await expect( pancakeswapV2Worker.setReinvestConfig(200, "0", [baseToken.address, cake.address]) ).to.be.revertedWith( "PancakeswapV2Worker02::setReinvestConfig:: _reinvestPath must start with CAKE, end with BTOKEN" ); }); }); describe("#setMaxReinvestBountyBps", async () => { it("should set max reinvest bounty", async () => { await pancakeswapV2Worker.setMaxReinvestBountyBps(200); expect(await pancakeswapV2Worker.maxReinvestBountyBps()).to.be.eq(200); }); it("should revert when new max reinvest bounty over 30%", async () => { await expect(pancakeswapV2Worker.setMaxReinvestBountyBps("3001")).to.be.revertedWith( "PancakeswapV2Worker02::setMaxReinvestBountyBps:: _maxReinvestBountyBps exceeded 30%" ); expect(await pancakeswapV2Worker.maxReinvestBountyBps()).to.be.eq(MAX_REINVEST_BOUNTY); }); }); describe("#setTreasuryConfig", async () => { it("should successfully set a treasury account", async () => { const aliceAddr = aliceAddress; await pancakeswapV2Worker.setTreasuryConfig(aliceAddr, REINVEST_BOUNTY_BPS); expect(await pancakeswapV2Worker.treasuryAccount()).to.eq(aliceAddr); }); it("should successfully set a treasury bounty", async () => { await pancakeswapV2Worker.setTreasuryConfig(DEPLOYER, 499); expect(await pancakeswapV2Worker.treasuryBountyBps()).to.eq(499); }); it("should revert when a new treasury bounty > max reinvest bounty bps", async () => { await expect( pancakeswapV2Worker.setTreasuryConfig(DEPLOYER, parseInt(MAX_REINVEST_BOUNTY) + 1) ).to.revertedWith( "PancakeswapV2Worker02::setTreasuryConfig:: _treasuryBountyBps exceeded maxReinvestBountyBps" ); expect(await pancakeswapV2Worker.treasuryBountyBps()).to.eq(REINVEST_BOUNTY_BPS); }); }); describe("#setStrategyOk", async () => { it("should set strat ok", async () => { await pancakeswapV2Worker.setStrategyOk([aliceAddress], true); expect(await pancakeswapV2Worker.okStrats(aliceAddress)).to.be.eq(true); }); }); }); context("when user uses LYF", async () => { context("when user is contract", async () => { it("should revert if evil contract try to call onlyEOAorWhitelisted function", async () => { await expect( evilContract.executeTransaction( vault.address, 0, "work(uint256,address,uint256,uint256,uint256,bytes)", ethers.utils.defaultAbiCoder.encode( ["uint256", "address", "uint256", "uint256", "uint256", "bytes"], [ 0, pancakeswapV2Worker.address, ethers.utils.parseEther("0.3"), "0", "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ), ] ) ) ).to.be.revertedWith("not eoa"); }); it("should allow whitelisted contract to open position without debt", async () => { // Deployer deposit 3 BTOKEN to the vault await baseToken.approve(vault.address, ethers.utils.parseEther("3")); await vault.deposit(ethers.utils.parseEther("3")); // Deployer funds whitelisted contract await baseToken.transfer(whitelistedContract.address, ethers.utils.parseEther("1")); // whitelisted contract approve Alpaca to to take BTOKEN await whitelistedContract.executeTransaction( baseToken.address, "0", "approve(address,uint256)", ethers.utils.defaultAbiCoder.encode(["address", "uint256"], [vault.address, ethers.utils.parseEther("0.3")]) ); expect(await baseToken.allowance(whitelistedContract.address, vault.address)).to.be.eq( ethers.utils.parseEther("0.3") ); // whitelisted contract should able to open position with 0 debt await whitelistedContract.executeTransaction( vault.address, 0, "work(uint256,address,uint256,uint256,uint256,bytes)", ethers.utils.defaultAbiCoder.encode( ["uint256", "address", "uint256", "uint256", "uint256", "bytes"], [ 0, pancakeswapV2Worker.address, ethers.utils.parseEther("0.3"), "0", "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ), ] ) ); const [worker, owner] = await vault.positions(1); expect(owner).to.be.eq(whitelistedContract.address); expect(worker).to.be.eq(pancakeswapV2Worker.address); }); it("should revert if evil contract try to call onlyWhitelistedLiquidators function", async () => { await expect( evilContract.executeTransaction( vault.address, 0, "kill(uint256)", ethers.utils.defaultAbiCoder.encode(["uint256"], [0]) ) ).to.be.revertedWith("!whitelisted liquidator"); }); }); context("when user is EOA", async () => { context("#work", async () => { it("should allow to open a position without debt", async () => { // Deployer deposits 3 BTOKEN to the bank await baseToken.approve(vault.address, ethers.utils.parseEther("3")); await vault.deposit(ethers.utils.parseEther("3")); // Alice can take 0 debt ok await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.3")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("0.3"), ethers.utils.parseEther("0"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); }); it("should not allow to open a position with debt less than MIN_DEBT_SIZE", async () => { // Deployer deposits 3 BTOKEN to the bank await baseToken.approve(vault.address, ethers.utils.parseEther("3")); await vault.deposit(ethers.utils.parseEther("3")); // Alice cannot take 0.3 debt because it is too small await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.3")); await expect( vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("0.3"), ethers.utils.parseEther("0.3"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("too small debt size"); }); it("should not allow to open the position with bad work factor", async () => { // Deployer deposits 3 BTOKEN to the bank await baseToken.approve(vault.address, ethers.utils.parseEther("3")); await vault.deposit(ethers.utils.parseEther("3")); // Alice cannot take 1 BTOKEN loan because she only put 0.3 BTOKEN as a collateral await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.3")); await expect( vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("0.3"), ethers.utils.parseEther("1"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("bad work factor"); }); it("should not allow positions if Vault has less BaseToken than requested loan", async () => { // Alice cannot take 1 BTOKEN loan because the contract does not have it await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await expect( vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("1"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("insufficient funds in the vault"); }); it("should not able to liquidate healthy position", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her position should have ~2 BTOKEN health (minus some small trading fee) await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await pancakeswapV2WorkerAsEve.reinvest(); await vault.deposit(0); // Random action to trigger interest computation // You can't liquidate her position yet await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); }); it("should work", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her position should have ~2 NATIVE health (minus some small trading fee) expect(await pancakeswapV2Worker.health(1)).to.be.eq(ethers.utils.parseEther("1.997883397660681282")); // Eve comes and trigger reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await pancakeswapV2WorkerAsEve.reinvest(); AssertHelpers.assertAlmostEqual( CAKE_REWARD_PER_BLOCK.mul("2").mul(REINVEST_BOUNTY_BPS).div("10000").toString(), (await cake.balanceOf(eveAddress)).toString() ); await vault.deposit(0); // Random action to trigger interest computation const healthDebt = await vault.positionInfo("1"); expect(healthDebt[0]).to.be.above(ethers.utils.parseEther("2")); const interest = ethers.utils.parseEther("0.3"); // 30% interest rate AssertHelpers.assertAlmostEqual(healthDebt[1].toString(), interest.add(loan).toString()); AssertHelpers.assertAlmostEqual( (await baseToken.balanceOf(vault.address)).toString(), deposit.sub(loan).toString() ); AssertHelpers.assertAlmostEqual((await vault.vaultDebtVal()).toString(), interest.add(loan).toString()); const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual(reservePool.toString(), (await vault.reservePool()).toString()); AssertHelpers.assertAlmostEqual( deposit.add(interest).sub(reservePool).toString(), (await vault.totalToken()).toString() ); }); it("should has correct interest rate growth", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await pancakeswapV2WorkerAsEve.reinvest(); await vault.deposit(0); // Random action to trigger interest computation await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await vault.deposit(0); // Random action to trigger interest computation const interest = ethers.utils.parseEther("0.3"); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); }); it("should close position correctly when user holds multiple positions", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); // Set Reinvest bounty to 10% of the reward await pancakeswapV2Worker.setReinvestConfig("100", "0", [cake.address, wbnb.address, baseToken.address]); const [path, reinvestPath] = await Promise.all([ pancakeswapV2Worker.getPath(), pancakeswapV2Worker.getReinvestPath(), ]); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Alice deposits 12 BTOKEN await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("12")); await vaultAsAlice.deposit(ethers.utils.parseEther("12")); // Position#1: Bob borrows 10 BTOKEN await swapHelper.loadReserves(path); let accumLp = BigNumber.from(0); let workerLpBefore = BigNumber.from(0); let totalShare = BigNumber.from(0); let shares: Array<BigNumber> = []; await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Pre-compute expectation let [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("20"), path ); accumLp = accumLp.add(expectedLp); let expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); // Expect let [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${expectedLp}` ).to.be.eq(expectedLp); expect(await pancakeswapV2Worker.totalShare(), `expect totalShare = ${totalShare}`).to.be.eq(totalShare); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); // Position#2: Bob borrows another 2 BTOKEN [workerLpBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); let eveCakeBefore = await cake.balanceOf(eveAddress); let deployerCakeBefore = await cake.balanceOf(DEPLOYER); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("2"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); let eveCakeAfter = await cake.balanceOf(eveAddress); let deployerCakeAfter = await cake.balanceOf(DEPLOYER); let totalRewards = swapHelper.computeTotalRewards(workerLpBefore, CAKE_REWARD_PER_BLOCK, BigNumber.from(2)); let reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); let reinvestLeft = totalRewards.sub(reinvestFees); let reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); let reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); let reinvestLp = BigNumber.from(0); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("3"), path ); accumLp = accumLp.add(expectedLp); expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore.add(reinvestLp)); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await pancakeswapV2Worker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect( deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER to get ${reinvestFees} CAKE as treasury fees` ).to.be.eq(reinvestFees); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve's CAKE to remain the same`).to.be.eq("0"); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); // ---------------- Reinvest#1 ------------------- // Wait for 1 day and someone calls reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); let [workerLPBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); deployerCakeBefore = await cake.balanceOf(DEPLOYER); eveCakeBefore = await cake.balanceOf(eveAddress); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await pancakeswapV2WorkerAsEve.reinvest(); deployerCakeAfter = await cake.balanceOf(DEPLOYER); eveCakeAfter = await cake.balanceOf(eveAddress); [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); totalRewards = swapHelper.computeTotalRewards(workerLPBefore, CAKE_REWARD_PER_BLOCK, BigNumber.from(2)); reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); reinvestLeft = totalRewards.sub(reinvestFees); reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await pancakeswapV2Worker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect(deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER's CAKE to remain the same`).to.be.eq("0"); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve to get ${reinvestFees}`).to.be.eq(reinvestFees); expect(workerLpAfter).to.be.eq(accumLp); // Check Position#1 info let [bob1Health, bob1DebtToShare] = await vault.positionInfo("1"); const bob1ExpectedHealth = await swapHelper.computeLpHealth( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), baseToken.address, farmToken.address ); expect(bob1Health, `expect Pos#1 health = ${bob1ExpectedHealth}`).to.be.eq(bob1ExpectedHealth); expect(bob1Health).to.be.gt(ethers.utils.parseEther("20")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("10").toString(), bob1DebtToShare.toString()); // Check Position#2 info let [bob2Health, bob2DebtToShare] = await vault.positionInfo("2"); const bob2ExpectedHealth = await swapHelper.computeLpHealth( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), baseToken.address, farmToken.address ); expect(bob2Health, `expect Pos#2 health = ${bob2ExpectedHealth}`).to.be.eq(bob2ExpectedHealth); expect(bob2Health).to.be.gt(ethers.utils.parseEther("3")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("2").toString(), bob2DebtToShare.toString()); let bobBefore = await baseToken.balanceOf(bobAddress); let bobAlpacaBefore = await alpacaToken.balanceOf(bobAddress); // Bob close position#1 await vaultAsBob.work( 1, pancakeswapV2Worker.address, "0", "0", "1000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); let bobAfter = await baseToken.balanceOf(bobAddress); let bobAlpacaAfter = await alpacaToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as he earn more from yield expect(bobAlpacaAfter).to.be.gt(bobAlpacaBefore); expect(bobAfter).to.be.gt(bobBefore); // Bob add another 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 2, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), 0, "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); bobBefore = await baseToken.balanceOf(bobAddress); bobAlpacaBefore = await alpacaToken.balanceOf(bobAddress); // Bob close position#2 await vaultAsBob.work( 2, pancakeswapV2Worker.address, "0", "0", "1000000000000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); bobAfter = await baseToken.balanceOf(bobAddress); bobAlpacaAfter = await alpacaToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as she earned from leverage yield farm without getting liquidated expect(bobAfter).to.be.gt(bobBefore); expect(bobAlpacaAfter).to.be.gt(bobAlpacaBefore); }); it("should close position correctly when user holds mix positions of leveraged and non-leveraged", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); const [path, reinvestPath] = await Promise.all([ pancakeswapV2Worker.getPath(), pancakeswapV2Worker.getReinvestPath(), ]); // Set Reinvest bounty to 10% of the reward await pancakeswapV2Worker.setReinvestConfig("100", "0", [cake.address, wbnb.address, baseToken.address]); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Alice deposits 12 BTOKEN await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("12")); await vaultAsAlice.deposit(ethers.utils.parseEther("12")); // Position#1: Bob borrows 10 BTOKEN await swapHelper.loadReserves(path); let accumLp = BigNumber.from(0); let workerLpBefore = BigNumber.from(0); let totalShare = BigNumber.from(0); let shares: Array<BigNumber> = []; await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Pre-compute expectation let [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("20"), path ); accumLp = accumLp.add(expectedLp); let expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); // Expect let [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${expectedLp}` ).to.be.eq(expectedLp); expect(await pancakeswapV2Worker.totalShare(), `expect totalShare = ${totalShare}`).to.be.eq(totalShare); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); // Position#2: Bob borrows another 2 BTOKEN [workerLpBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); let eveCakeBefore = await cake.balanceOf(eveAddress); let deployerCakeBefore = await cake.balanceOf(DEPLOYER); // Position#2: Bob open 1x position with 3 BTOKEN await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("3")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("3"), "0", "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); let eveCakeAfter = await cake.balanceOf(eveAddress); let deployerCakeAfter = await cake.balanceOf(DEPLOYER); let totalRewards = swapHelper.computeTotalRewards(workerLpBefore, CAKE_REWARD_PER_BLOCK, BigNumber.from(2)); let reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); let reinvestLeft = totalRewards.sub(reinvestFees); let reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); let reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); let reinvestLp = BigNumber.from(0); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("3"), path ); accumLp = accumLp.add(expectedLp); expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore.add(reinvestLp)); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await pancakeswapV2Worker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect( deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER to get ${reinvestFees} CAKE as treasury fees` ).to.be.eq(reinvestFees); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve's CAKE to remain the same`).to.be.eq("0"); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); // ---------------- Reinvest#1 ------------------- // Wait for 1 day and someone calls reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); let [workerLPBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); deployerCakeBefore = await cake.balanceOf(DEPLOYER); eveCakeBefore = await cake.balanceOf(eveAddress); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await pancakeswapV2WorkerAsEve.reinvest(); deployerCakeAfter = await cake.balanceOf(DEPLOYER); eveCakeAfter = await cake.balanceOf(eveAddress); [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); totalRewards = swapHelper.computeTotalRewards(workerLPBefore, CAKE_REWARD_PER_BLOCK, BigNumber.from(2)); reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); reinvestLeft = totalRewards.sub(reinvestFees); reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await pancakeswapV2Worker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect(deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER's CAKE to remain the same`).to.be.eq("0"); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve to get ${reinvestFees}`).to.be.eq(reinvestFees); expect(workerLpAfter).to.be.eq(accumLp); // Check Position#1 info let [bob1Health, bob1DebtToShare] = await vault.positionInfo("1"); const bob1ExpectedHealth = await swapHelper.computeLpHealth( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), baseToken.address, farmToken.address ); expect(bob1Health, `expect Pos#1 health = ${bob1ExpectedHealth}`).to.be.eq(bob1ExpectedHealth); expect(bob1Health).to.be.gt(ethers.utils.parseEther("20")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("10").toString(), bob1DebtToShare.toString()); // Check Position#2 info let [bob2Health, bob2DebtToShare] = await vault.positionInfo("2"); const bob2ExpectedHealth = await swapHelper.computeLpHealth( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), baseToken.address, farmToken.address ); expect(bob2Health, `expect Pos#2 health = ${bob2ExpectedHealth}`).to.be.eq(bob2ExpectedHealth); expect(bob2Health).to.be.gt(ethers.utils.parseEther("3")); AssertHelpers.assertAlmostEqual("0", bob2DebtToShare.toString()); let bobBefore = await baseToken.balanceOf(bobAddress); let bobAlpacaBefore = await alpacaToken.balanceOf(bobAddress); // Bob close position#1 await vaultAsBob.work( 1, pancakeswapV2Worker.address, "0", "0", "1000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); let bobAfter = await baseToken.balanceOf(bobAddress); let bobAlpacaAfter = await alpacaToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as he earn more from yield expect(bobAlpacaAfter).to.be.gt(bobAlpacaBefore); expect(bobAfter).to.be.gt(bobBefore); // Bob add another 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 2, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), 0, "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); bobBefore = await baseToken.balanceOf(bobAddress); bobAlpacaBefore = await alpacaToken.balanceOf(bobAddress); // Bob close position#2 await vaultAsBob.work( 2, pancakeswapV2Worker.address, "0", "0", "1000000000000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); bobAfter = await baseToken.balanceOf(bobAddress); bobAlpacaAfter = await alpacaToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as she earned from leverage yield farm without getting liquidated // But bob shouldn't earn more ALPACAs from closing position#2 expect(bobAfter).to.be.gt(bobBefore); expect(bobAlpacaAfter).to.be.eq(bobAlpacaBefore); }); }); context("#kill", async () => { it("should not allow user not whitelisted to liquidate", async () => { await expect(vaultAsBob.kill("1")).to.be.revertedWith("!whitelisted liquidator"); }); it("should be able to liquidate bad position", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await pancakeswapV2WorkerAsEve.reinvest(); await vault.deposit(0); // Random action to trigger interest computation await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await vault.deposit(0); // Random action to trigger interest computation const interest = ethers.utils.parseEther("0.3"); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); // Calculate the expected result. // set interest rate to be 0 to be easy for testing. await simpleVaultConfig.setParams( MIN_DEBT_SIZE, 0, RESERVE_POOL_BPS, KILL_PRIZE_BPS, wbnb.address, wNativeRelayer.address, fairLaunch.address, KILL_TREASURY_BPS, deployerAddress ); const toBeLiquidatedValue = await pancakeswapV2Worker.health(1); const liquidationBounty = toBeLiquidatedValue.mul(KILL_PRIZE_BPS).div(10000); const treasuryKillFees = toBeLiquidatedValue.mul(KILL_TREASURY_BPS).div(10000); const totalLiquidationFees = liquidationBounty.add(treasuryKillFees); const eveBalanceBefore = await baseToken.balanceOf(eveAddress); const aliceAlpacaBefore = await alpacaToken.balanceOf(aliceAddress); const aliceBalanceBefore = await baseToken.balanceOf(aliceAddress); const vaultBalanceBefore = await baseToken.balanceOf(vault.address); const deployerBalanceBefore = await baseToken.balanceOf(deployerAddress); const vaultDebtVal = await vault.vaultDebtVal(); const debt = await vault.debtShareToVal((await vault.positions(1)).debtShare); const left = debt.gte(toBeLiquidatedValue.sub(totalLiquidationFees)) ? ethers.constants.Zero : toBeLiquidatedValue.sub(totalLiquidationFees).sub(debt); // Now eve kill the position await expect(vaultAsEve.kill("1")).to.emit(vaultAsEve, "Kill"); // Getting balances after killed const eveBalanceAfter = await baseToken.balanceOf(eveAddress); const aliceBalanceAfter = await baseToken.balanceOf(aliceAddress); const vaultBalanceAfter = await baseToken.balanceOf(vault.address); const deployerBalanceAfter = await baseToken.balanceOf(deployerAddress); AssertHelpers.assertAlmostEqual( deposit.add(interest).add(interest.mul(13).div(10)).add(interest.mul(13).div(10)).toString(), (await baseToken.balanceOf(vault.address)).toString() ); expect(await vault.vaultDebtVal()).to.be.eq(ethers.utils.parseEther("0")); AssertHelpers.assertAlmostEqual( reservePool.add(reservePool.mul(13).div(10)).add(reservePool.mul(13).div(10)).toString(), (await vault.reservePool()).toString() ); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); expect(eveBalanceAfter.sub(eveBalanceBefore), "expect Eve to get her liquidation bounty").to.be.eq( liquidationBounty ); expect( deployerBalanceAfter.sub(deployerBalanceBefore), "expect Deployer to get treasury liquidation fees" ).to.be.eq(treasuryKillFees); expect(aliceBalanceAfter.sub(aliceBalanceBefore), "expect Alice to get her leftover back").to.be.eq(left); expect(vaultBalanceAfter.sub(vaultBalanceBefore), "expect Vault to get its funds + interest").to.be.eq( vaultDebtVal ); expect((await vault.positions(1)).debtShare, "expect Pos#1 debt share to be 0").to.be.eq(0); expect( await alpacaToken.balanceOf(aliceAddress), "expect Alice to get some ALPACA from holding LYF position" ).to.be.gt(aliceAlpacaBefore); // Alice creates a new position again await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("1"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // She can close position await vaultAsAlice.work( 2, pancakeswapV2Worker.address, "0", "0", "115792089237316195423570985008687907853269984665640564039457584007913129639935", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); }); it("should liquidate user position correctly", async () => { // Bob deposits 20 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("20")); await vaultAsBob.deposit(ethers.utils.parseEther("20")); // Position#1: Alice borrows 10 BTOKEN loan await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); await farmToken.mint(deployerAddress, ethers.utils.parseEther("100")); await farmToken.approve(routerV2.address, ethers.utils.parseEther("100")); // Price swing 10% // Add more token to the pool equals to sqrt(10*((0.1)**2) / 9) - 0.1 = 0.005409255338945984, (0.1 is the balance of token in the pool) await routerV2.swapExactTokensForTokens( ethers.utils.parseEther("0.005409255338945984"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); // Price swing 20% // Add more token to the pool equals to // sqrt(10*((0.10540925533894599)**2) / 8) - 0.10540925533894599 = 0.012441874858811944 // (0.10540925533894599 is the balance of token in the pool) await routerV2.swapExactTokensForTokens( ethers.utils.parseEther("0.012441874858811944"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); // Price swing 23.43% // Existing token on the pool = 0.10540925533894599 + 0.012441874858811944 = 0.11785113019775793 // Add more token to the pool equals to // sqrt(10*((0.11785113019775793)**2) / 7.656999999999999) - 0.11785113019775793 = 0.016829279312591913 await routerV2.swapExactTokensForTokens( ethers.utils.parseEther("0.016829279312591913"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); await expect(vaultAsEve.kill("1")).to.be.revertedWith("can't liquidate"); // Price swing 30% // Existing token on the pool = 0.11785113019775793 + 0.016829279312591913 = 0.13468040951034985 // Add more token to the pool equals to // sqrt(10*((0.13468040951034985)**2) / 7) - 0.13468040951034985 = 0.026293469053292218 await routerV2.swapExactTokensForTokens( ethers.utils.parseEther("0.026293469053292218"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); // Now you can liquidate because of the price fluctuation const eveBefore = await baseToken.balanceOf(eveAddress); await expect(vaultAsEve.kill("1")).to.emit(vaultAsEve, "Kill"); expect(await baseToken.balanceOf(eveAddress)).to.be.gt(eveBefore); }); }); context("#onlyApprovedHolder", async () => { it("should be not allow user to emergencyWithdraw debtToken on FairLaunch", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await pancakeswapV2WorkerAsEve.reinvest(); await vault.deposit(0); // Random action to trigger interest computation await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); await vault.deposit(0); // Random action to trigger interest computation const interest = ethers.utils.parseEther("0.3"); //30% interest rate const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); // Alice emergencyWithdraw from FairLaunch await expect(fairLaunchAsAlice.emergencyWithdraw(0)).to.be.revertedWith("only funder"); const eveBefore = await baseToken.balanceOf(eveAddress); // Now you can liquidate because of the insane interest rate await expect(vaultAsEve.kill("1")).to.emit(vaultAsEve, "Kill"); expect(await baseToken.balanceOf(eveAddress)).to.be.gt(eveBefore); AssertHelpers.assertAlmostEqual( deposit.add(interest).add(interest.mul(13).div(10)).add(interest.mul(13).div(10)).toString(), (await baseToken.balanceOf(vault.address)).toString() ); expect(await vault.vaultDebtVal()).to.be.eq(ethers.utils.parseEther("0")); AssertHelpers.assertAlmostEqual( reservePool.add(reservePool.mul(13).div(10)).add(reservePool.mul(13).div(10)).toString(), (await vault.reservePool()).toString() ); AssertHelpers.assertAlmostEqual( deposit .add(interest.sub(reservePool)) .add(interest.sub(reservePool).mul(13).div(10)) .add(interest.sub(reservePool).mul(13).div(10)) .toString(), (await vault.totalToken()).toString() ); // Alice creates a new position again await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("1"), "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // She can close position await vaultAsAlice.work( 2, pancakeswapV2Worker.address, "0", "0", "115792089237316195423570985008687907853269984665640564039457584007913129639935", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); }); }); context("#deposit-#withdraw", async () => { it("should deposit and withdraw BTOKEN from Vault (bad debt case)", async () => { // Deployer deposits 10 BTOKEN to the Vault const deposit = ethers.utils.parseEther("10"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); expect(await vault.balanceOf(deployerAddress)).to.be.equal(deposit); // Bob borrows 2 BTOKEN loan const loan = ethers.utils.parseEther("2"); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), loan, "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); expect(await baseToken.balanceOf(vault.address)).to.be.equal(deposit.sub(loan)); expect(await vault.vaultDebtVal()).to.be.equal(loan); expect(await vault.totalToken()).to.be.equal(deposit); // Alice deposits 2 BTOKEN const aliceDeposit = ethers.utils.parseEther("2"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("2")); await vaultAsAlice.deposit(aliceDeposit); AssertHelpers.assertAlmostEqual( deposit.sub(loan).add(aliceDeposit).toString(), (await baseToken.balanceOf(vault.address)).toString() ); // check Alice ibBTOKEN balance = 2/10 * 10 = 2 ibBTOKEN AssertHelpers.assertAlmostEqual(aliceDeposit.toString(), (await vault.balanceOf(aliceAddress)).toString()); AssertHelpers.assertAlmostEqual(deposit.add(aliceDeposit).toString(), (await vault.totalSupply()).toString()); // Simulate BTOKEN price is very high by swap FTOKEN to BTOKEN (reduce BTOKEN supply) await farmToken.mint(deployerAddress, ethers.utils.parseEther("100")); await farmToken.approve(routerV2.address, ethers.utils.parseEther("100")); await routerV2.swapExactTokensForTokens( ethers.utils.parseEther("100"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); // Alice liquidates Bob position#1 let aliceBefore = await baseToken.balanceOf(aliceAddress); await expect(vaultAsAlice.kill("1")).to.emit(vaultAsAlice, "Kill"); let aliceAfter = await baseToken.balanceOf(aliceAddress); // Bank balance is increase by liquidation AssertHelpers.assertAlmostEqual( ethers.utils.parseEther("10.002702699312215556").toString(), (await baseToken.balanceOf(vault.address)).toString() ); // Alice is liquidator, Alice should receive 10% Kill prize // BTOKEN back from liquidation 0.00300199830261993, 10% of it is 0.000300199830261993 AssertHelpers.assertAlmostEqual( ethers.utils.parseEther("0.000300199830261993").toString(), aliceAfter.sub(aliceBefore).toString() ); // Alice withdraws 2 BOKTEN aliceBefore = await baseToken.balanceOf(aliceAddress); await vaultAsAlice.withdraw(await vault.balanceOf(aliceAddress)); aliceAfter = await baseToken.balanceOf(aliceAddress); // alice gots 2/12 * 10.002702699312215556 = 1.667117116552036 AssertHelpers.assertAlmostEqual( ethers.utils.parseEther("1.667117116552036").toString(), aliceAfter.sub(aliceBefore).toString() ); }); }); context("#reinvest", async () => { it("should reinvest correctly", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); // Set Reinvest bounty to 10% of the reward await pancakeswapV2Worker.setReinvestConfig("100", "0", [cake.address, wbnb.address, baseToken.address]); const [path, reinvestPath] = await Promise.all([ pancakeswapV2Worker.getPath(), pancakeswapV2Worker.getReinvestPath(), ]); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Alice deposits 12 BTOKEN await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("12")); await vaultAsAlice.deposit(ethers.utils.parseEther("12")); // Position#1: Bob borrows 10 BTOKEN await swapHelper.loadReserves(path); let accumLp = BigNumber.from(0); let workerLpBefore = BigNumber.from(0); let totalShare = BigNumber.from(0); let shares: Array<BigNumber> = []; await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Pre-compute expectation let [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("20"), path ); accumLp = accumLp.add(expectedLp); let expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); // Expect let [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${expectedLp}` ).to.be.eq(expectedLp); expect(await pancakeswapV2Worker.totalShare(), `expect totalShare = ${totalShare}`).to.be.eq(totalShare); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); // Position#2: Bob borrows another 2 BTOKEN [workerLpBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); let eveCakeBefore = await cake.balanceOf(eveAddress); let deployerCakeBefore = await cake.balanceOf(DEPLOYER); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), ethers.utils.parseEther("2"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); let eveCakeAfter = await cake.balanceOf(eveAddress); let deployerCakeAfter = await cake.balanceOf(DEPLOYER); let totalRewards = swapHelper.computeTotalRewards(workerLpBefore, CAKE_REWARD_PER_BLOCK, BigNumber.from(2)); let reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); let reinvestLeft = totalRewards.sub(reinvestFees); let reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); let reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); let reinvestLp = BigNumber.from(0); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); [expectedLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("3"), path ); accumLp = accumLp.add(expectedLp); expectedShare = workerHelper.computeBalanceToShare(expectedLp, totalShare, workerLpBefore.add(reinvestLp)); shares.push(expectedShare); totalShare = totalShare.add(expectedShare); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await pancakeswapV2Worker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect( deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER to get ${reinvestFees} CAKE as treasury fees` ).to.be.eq(reinvestFees); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve's CAKE to remain the same`).to.be.eq("0"); expect(workerLpAfter, `expect Worker to stake ${accumLp} LP`).to.be.eq(accumLp); expect( await baseToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisBtoken} BTOKEN debris` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(addStrat.address), `expect add BTOKEN strat to have ${debrisFtoken} FTOKEN debris` ).to.be.eq(debrisFtoken); // ---------------- Reinvest#1 ------------------- // Wait for 1 day and someone calls reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); let [workerLPBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); deployerCakeBefore = await cake.balanceOf(DEPLOYER); eveCakeBefore = await cake.balanceOf(eveAddress); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await pancakeswapV2WorkerAsEve.reinvest(); deployerCakeAfter = await cake.balanceOf(DEPLOYER); eveCakeAfter = await cake.balanceOf(eveAddress); [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); totalRewards = swapHelper.computeTotalRewards(workerLPBefore, CAKE_REWARD_PER_BLOCK, BigNumber.from(2)); reinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); reinvestLeft = totalRewards.sub(reinvestFees); reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debrisBtoken); [reinvestLp, debrisBtoken, debrisFtoken] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); expect(await pancakeswapV2Worker.shares(1), `expect Pos#1 has ${shares[0]} shares`).to.be.eq(shares[0]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Pos#1 LPs = ${workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[0], totalShare, workerLpAfter)); expect(await pancakeswapV2Worker.shares(2), `expect Pos#2 has ${shares[1]} shares`).to.be.eq(shares[1]); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), `expect Pos#2 LPs = ${workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)}` ).to.be.eq(workerHelper.computeShareToBalance(shares[1], totalShare, workerLpAfter)); expect(deployerCakeAfter.sub(deployerCakeBefore), `expect DEPLOYER's CAKE to remain the same`).to.be.eq("0"); expect(eveCakeAfter.sub(eveCakeBefore), `expect eve to get ${reinvestFees}`).to.be.eq(reinvestFees); expect(workerLpAfter).to.be.eq(accumLp); // Check Position#1 info let [bob1Health, bob1DebtToShare] = await vault.positionInfo("1"); const bob1ExpectedHealth = await swapHelper.computeLpHealth( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), baseToken.address, farmToken.address ); expect(bob1Health, `expect Pos#1 health = ${bob1ExpectedHealth}`).to.be.eq(bob1ExpectedHealth); expect(bob1Health).to.be.gt(ethers.utils.parseEther("20")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("10").toString(), bob1DebtToShare.toString()); // Check Position#2 info let [alice2Health, alice2DebtToShare] = await vault.positionInfo("2"); const alice2ExpectedHealth = await swapHelper.computeLpHealth( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(2)), baseToken.address, farmToken.address ); expect(alice2Health, `expect Pos#2 health = ${alice2ExpectedHealth}`).to.be.eq(alice2ExpectedHealth); expect(alice2Health).to.be.gt(ethers.utils.parseEther("3")); AssertHelpers.assertAlmostEqual(ethers.utils.parseEther("2").toString(), alice2DebtToShare.toString()); const bobBefore = await baseToken.balanceOf(bobAddress); // Bob close position#1 await vaultAsBob.work( 1, pancakeswapV2Worker.address, "0", "0", "1000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const bobAfter = await baseToken.balanceOf(bobAddress); // Check Bob account, Bob must be richer as he earn more from yield expect(bobAfter).to.be.gt(bobBefore); // Alice add another 10 BTOKEN await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsAlice.work( 2, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), 0, "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const aliceBefore = await baseToken.balanceOf(aliceAddress); // Alice close position#2 await vaultAsAlice.work( 2, pancakeswapV2Worker.address, "0", "0", "1000000000000000000000000000000", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const aliceAfter = await baseToken.balanceOf(aliceAddress); // Check Alice account, Alice must be richer as she earned from leverage yield farm without getting liquidated expect(aliceAfter).to.be.gt(aliceBefore); }); }); context("#partialclose", async () => { context("#liquidate", async () => { context("when maxReturn is lessDebt", async () => { // back cannot be less than lessDebt as less debt is Min(debt, back, maxReturn) = maxReturn it("should pay debt 'maxReturn' BTOKEN and return 'liquidatedAmount - maxReturn' BTOKEN to user", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); const [path, reinvestPath] = await Promise.all([ pancakeswapV2Worker.getPath(), pancakeswapV2Worker.getReinvestPath(), ]); // Set Reinvest bounty to 1% of the reward await pancakeswapV2Worker.setReinvestConfig("100", "0", [cake.address, wbnb.address, baseToken.address]); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Position#1: Bob borrows 10 BTOKEN loan and supply another 10 BToken // Thus, Bob's position value will be worth 20 BTOKEN // After calling `work()` // 20 BTOKEN needs to swap 3.587061715703192586 BTOKEN to FTOKEN // new reserve after swap will be 4.587061715703192586 0.021843151027158060 // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 16.412938284296807414 BTOKEN - 0.078156848972841940 FTOKEN // new reserve after adding liquidity 21.000000000000000000 BTOKEN - 0.100000000000000000 FTOKEN // lp amount from adding liquidity will be 1.131492691639043045 LP const borrowedAmount = ethers.utils.parseEther("10"); const principalAmount = ethers.utils.parseEther("10"); let [workerLpBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, principalAmount, borrowedAmount, "0", // max return = 0, don't return NATIVE to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); let [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); const [expectedLp, debrisBtoken] = await swapHelper.computeOneSidedOptimalLp( borrowedAmount.add(principalAmount), path ); expect(workerLpAfter.sub(workerLpBefore)).to.eq(expectedLp); const deployerCakeBefore = await cake.balanceOf(DEPLOYER); const bobBefore = await baseToken.balanceOf(bobAddress); const [bobHealthBefore] = await vault.positionInfo("1"); const lpUnderBobPosition = await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)); const liquidatedLp = lpUnderBobPosition.div(2); const returnDebt = ethers.utils.parseEther("6"); [workerLpBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); // Pre-compute await swapHelper.loadReserves(path); await swapHelper.loadReserves(reinvestPath); // Compute reinvest const [reinvestFees, reinvestLp] = await swapHelper.computeReinvestLp( workerLpBefore, debrisBtoken, CAKE_REWARD_PER_BLOCK, BigNumber.from(REINVEST_BOUNTY_BPS), reinvestPath, path, BigNumber.from(1) ); // Compute liquidate const [btokenAmount, ftokenAmount] = await swapHelper.computeRemoveLiquidiy( baseToken.address, farmToken.address, liquidatedLp ); const sellFtokenAmounts = await swapHelper.computeSwapExactTokensForTokens( ftokenAmount, await pancakeswapV2Worker.getReversedPath(), true ); const liquidatedBtoken = sellFtokenAmounts[sellFtokenAmounts.length - 1] .add(btokenAmount) .sub(returnDebt); await vaultAsBob.work( 1, pancakeswapV2Worker.address, "0", "0", returnDebt, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ partialCloseStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [liquidatedLp, returnDebt, liquidatedBtoken] ), ] ) ); const bobAfter = await baseToken.balanceOf(bobAddress); const deployerCakeAfter = await cake.balanceOf(DEPLOYER); expect(deployerCakeAfter.sub(deployerCakeBefore), `expect Deployer to get ${reinvestFees}`).to.be.eq( reinvestFees ); expect(bobAfter.sub(bobBefore), `expect Bob get ${liquidatedBtoken}`).to.be.eq(liquidatedBtoken); // Check Bob position info const [bobHealth, bobDebtToShare] = await vault.positionInfo("1"); // Bob's health after partial close position must be 50% less than before // due to he exit half of lp under his position expect(bobHealth).to.be.lt(bobHealthBefore.div(2)); // Bob's debt should be left only 4 BTOKEN due he said he wants to return at max 4 BTOKEN expect(bobDebtToShare).to.be.eq(borrowedAmount.sub(returnDebt)); // Check LP deposited by Worker on MasterChef [workerLpAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); // LP tokens + 0.000207570473714694 LP from reinvest of worker should be decreased by lpUnderBobPosition/2 // due to Bob execute StrategyClosePartialLiquidate expect(workerLpAfter).to.be.eq(workerLpBefore.add(reinvestLp).sub(lpUnderBobPosition.div(2))); }); }); context("when debt is lessDebt", async () => { // back cannot be less than lessDebt as less debt is Min(debt, back, maxReturn) = debt it("should pay back all debt and return 'liquidatedAmount - debt' BTOKEN to user", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Position#1: Bob borrows 10 BTOKEN loan and supply another 10 BToken // Thus, Bob's position value will be worth 20 BTOKEN // After calling `work()` // 20 BTOKEN needs to swap 3.587061715703192586 BTOKEN to FTOKEN // new reserve after swap will be 4.587061715703192586 0.021843151027158060 // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 16.412938284296807414 BTOKEN - 0.078156848972841940 FTOKEN // new reserve after adding liquidity 21.000000000000000000 BTOKEN - 0.100000000000000000 FTOKEN // lp amount from adding liquidity will be 1.131492691639043045 LP let [workerLPBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); let [workerLPAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); expect(workerLPAfter.sub(workerLPBefore)).to.eq(parseEther("1.131492691639043045")); // Bob think he made enough. He now wants to close position partially. // He close 50% of his position and return all debt const bobBefore = await baseToken.balanceOf(bobAddress); const [bobHealthBefore] = await vault.positionInfo("1"); const lpUnderBobPosition = await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)); [workerLPBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); // Bob think he made enough. He now wants to close position partially. // After calling `work()`, the `_reinvest()` is invoked // since 1 blocks have passed since approve and work now reward will be 0.076 * 1 =~ 0.075999999998831803 ~ CAKE // reward without bounty will be 0.075999999998831803 - 0.000759999999988318 =~ 0.0752399999988435 CAKE // 0.0752399999988435 CAKE can be converted into: // (0.0752399999988435 * 0.9975 * 1) / (0.1 + 0.0752399999988435 * 0.9975) = 0.428740847712892766 WBNB // 0.428740847712892766 WBNB can be converted into (0.428740847712892766 * 0.9975 * 1) / (1 + 0.428740847712892766 * 0.9975) = 0.299557528330150526 BTOKEN // based on optimal swap formula, 0.299557528330150526 BTOKEN needs to swap 0.149435199790075736 BTOKEN // new reserve after swap will be 21.149435199790075736 BTOKEN - 0.099295185694161018 FTOKEN // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 0.150122328540074790 BTOKEN - 0.000704814305838982 FTOKEN // new reserve after adding liquidity receiving from `_reinvest()` is 21.299557528330150526 BTOKEN - 0.100000000000000000 FTOKEN // more LP amount after executing add strategy will be 0.010276168801924356 LP // accumulated LP of the worker will be 1.131492691639043045 + 0.010276168801924356 = 1.1417688604409675 LP // bob close 50% of his position, thus he will close 1.131492691639043045 * (1.131492691639043045 / (1.131492691639043045)) =~ 1.131492691639043045 / 2 = 0.5657463458195215 LP // 0.5657463458195215 LP will be converted into 8.264866063854500749 BTOKEN - 0.038802994160144191 FTOKEN // 0.038802994160144191 FTOKEN will be converted into (0.038802994160144191 * 0.9975 * 13.034691464475649777) / (0.061197005839855809 + 0.038802994160144191 * 0.9975) = 5.050104921127982573 BTOKEN // thus, Bob will receive 8.264866063854500749 + 5.050104921127982573 = 13.314970984982483322 BTOKEN await vaultAsBob.work( 1, pancakeswapV2Worker.address, "0", "0", ethers.utils.parseEther("5000000000"), ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ partialCloseStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [ lpUnderBobPosition.div(2), ethers.utils.parseEther("5000000000"), ethers.utils.parseEther("3.314970984982483322"), ] ), ] ) ); const bobAfter = await baseToken.balanceOf(bobAddress); // After Bob liquidate half of his position which worth // 13.314970984982483322 BTOKEN (price impact+trading fee included) // Bob wish to return 5,000,000,000 BTOKEN (when maxReturn > debt, return all debt) // The following criteria must be stratified: // - Bob should get 13.314970984982483322 - 10 = 3.314970984982483322 BTOKEN back. // - Bob's position debt must be 0 expect( bobBefore.add(ethers.utils.parseEther("3.314970984982483322")), "Expect BTOKEN in Bob's account after close position to increase by ~3.32 BTOKEN" ).to.be.eq(bobAfter); // Check Bob position info const [bobHealth, bobDebtVal] = await vault.positionInfo("1"); // Bob's health after partial close position must be 50% less than before // due to he exit half of lp under his position expect(bobHealth).to.be.lt(bobHealthBefore.div(2)); // Bob's debt should be 0 BTOKEN due he said he wants to return at max 5,000,000,000 BTOKEN (> debt, return all debt) expect(bobDebtVal).to.be.eq("0"); // Check LP deposited by Worker on MasterChef [workerLPAfter] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); // LP tokens + LP tokens from reinvest of worker should be decreased by lpUnderBobPosition/2 // due to Bob execute StrategyClosePartialLiquidate expect(workerLPAfter).to.be.eq( workerLPBefore.add(parseEther("0.010276168801924356")).sub(lpUnderBobPosition.div(2)) ); }); }); context("when worker factor is not satisfy", async () => { it("should revert bad work factor", async () => { // Set interests to 0% per year for easy testing await simpleVaultConfig.setParams( ethers.utils.parseEther("1"), // 1 BTOKEN min debt size, "0", // 0% per year "1000", // 10% reserve pool "1000", // 10% Kill prize wbnb.address, wNativeRelayer.address, fairLaunch.address, "0", ethers.constants.AddressZero ); // Bob deposits 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.deposit(ethers.utils.parseEther("10")); // Position#1: Bob borrows 10 BTOKEN await baseTokenAsBob.approve(vault.address, ethers.utils.parseEther("10")); await vaultAsBob.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("10"), ethers.utils.parseEther("10"), "0", // max return = 0, don't return BTOKEN to the debt ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Bob think he made enough. He now wants to close position partially. // He liquidate all of his position but not payback the debt. const lpUnderBobPosition = await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)); // Bob closes position with maxReturn 0 and liquidate all of his position // Expect that Bob will not be able to close his position as he liquidate all underlying assets but not paydebt // which made his position debt ratio higher than allow work factor await expect( vaultAsBob.work( 1, pancakeswapV2Worker.address, "0", "0", "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ partialCloseStrat.address, ethers.utils.defaultAbiCoder.encode( ["uint256", "uint256", "uint256"], [lpUnderBobPosition, "0", "0"] ), ] ) ) ).revertedWith("bad work factor"); }); }); }); }); context("When the treasury Account and treasury bounty bps haven't been set", async () => { it("should not auto reinvest", async () => { await pancakeswapV2Worker.setTreasuryConfig(constants.AddressZero, 0); // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her position should have ~2 NATIVE health (minus some small trading fee) expect(await pancakeswapV2Worker.shares(1)).to.eq(ethers.utils.parseEther("0.231205137369691323")); expect(await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1))).to.eq( ethers.utils.parseEther("0.231205137369691323") ); // Alice opens another position. await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her LP under that 1st position must still remain the same expect(await pancakeswapV2Worker.shares(1)).to.eq(ethers.utils.parseEther("0.231205137369691323")); expect(await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1))).to.eq( ethers.utils.parseEther("0.231205137369691323") ); }); }); context("when the worker is an older version", async () => { context("when upgrade is during the tx flow", async () => { context("when beneficialVault == operator", async () => { it("should work with the new upgraded worker", async () => { // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); // Position#1: Bob borrows 1 BTOKEN loan and supply another 1 BToken // Thus, Bob's position value will be worth 20 BTOKEN // After calling `work()` // 2 BTOKEN needs to swap 0.0732967258967755614 BTOKEN to 0.042234424701074812 FTOKEN // new reserve after swap will be 1.732967258967755614 ฺBTOKEN 0.057765575298925188 FTOKEN // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 1.267032741032244386 BTOKEN - 0.042234424701074812 FTOKEN // lp amount from adding liquidity will be (0.042234424701074812 / 0.057765575298925188) * 0.316227766016837933(first total supply) = 0.231205137369691323 LP // new reserve after adding liquidity 2.999999999999999954 BTOKEN - 0.100000000000000000 FTOKEN await vaultAsAlice.work( 0, pancakeswapV2Worker01.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her position should have ~2 NATIVE health (minus some small trading fee) expect(await pancakeswapV2Worker01.health(1)).to.be.eq(ethers.utils.parseEther("1.997883397660681282")); expect(await pancakeswapV2Worker01.shares(1)).to.eq(ethers.utils.parseEther("0.231205137369691323")); expect(await pancakeswapV2Worker01.shareToBalance(await pancakeswapV2Worker01.shares(1))).to.eq( ethers.utils.parseEther("0.231205137369691323") ); // PancakeswapV2Worker needs to be updated to PancakeswapV2Worker02 const PancakeswapV2Worker02 = (await ethers.getContractFactory( "PancakeswapV2Worker02", deployer )) as PancakeswapV2Worker02__factory; const pancakeswapV2Worker02 = (await upgrades.upgradeProxy( pancakeswapV2Worker01.address, PancakeswapV2Worker02 )) as PancakeswapV2Worker02; await pancakeswapV2Worker02.deployed(); // except that important states must be the same. // - health(1) should return the same value as before upgrade // - shares(1) should return the same value as before upgrade // - shareToBalance(shares(1)) should return the same value as before upgrade // - reinvestPath[0] should be reverted as reinvestPath.lenth == 0 // - reinvestPath should return default reinvest path ($CAKE->$WBNB->$BTOKEN) expect(await pancakeswapV2Worker02.health(1)).to.be.eq(ethers.utils.parseEther("1.997883397660681282")); expect(await pancakeswapV2Worker02.shares(1)).to.eq(ethers.utils.parseEther("0.231205137369691323")); expect(await pancakeswapV2Worker02.shareToBalance(await pancakeswapV2Worker01.shares(1))).to.eq( ethers.utils.parseEther("0.231205137369691323") ); expect(pancakeswapV2Worker02.address).to.eq(pancakeswapV2Worker01.address); await expect(pancakeswapV2Worker02.reinvestPath(0)).to.be.reverted; expect(await pancakeswapV2Worker02.getReinvestPath()).to.be.deep.eq([ cake.address, wbnb.address, baseToken.address, ]); const pancakeswapV2Worker02AsEve = PancakeswapV2Worker02__factory.connect( pancakeswapV2Worker02.address, eve ); // set beneficialVaultConfig await pancakeswapV2Worker02.setBeneficialVaultConfig(BENEFICIALVAULT_BOUNTY_BPS, vault.address, [ cake.address, wbnb.address, baseToken.address, ]); expect( await pancakeswapV2Worker02.beneficialVault(), "expect beneficialVault to be equal to input vault" ).to.eq(vault.address); expect( await pancakeswapV2Worker02.beneficialVaultBountyBps(), "expect beneficialVaultBountyBps to be equal to BENEFICIALVAULT_BOUNTY_BPS" ).to.eq(BENEFICIALVAULT_BOUNTY_BPS); expect( await pancakeswapV2Worker02.getRewardPath(), "expect CAKE->WBNB->BTOKEN as reward path" ).to.be.deep.eq([cake.address, wbnb.address, baseToken.address]); // Eve comes and trigger reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); // Eve calls reinvest to increase the LP size and receive portion of rewards // it's 4 blocks apart since the first tx, thus 0.0076 * 4 = 0.303999999999841411 CAKE // 1% of 0.303999999999841411 will become a bounty, thus eve shall get 90% of 0.003039999999998414 CAKE // 10% of 0.003039999999998414 will increase a beneficial vault's totalToken, this beneficial vault will get 0.0003039999999998414 CAKE // thus, 0.002735999999998573 will be returned to eve // 0.000303999999999841 CAKE is converted to (0.000303999999999841 * 0.9975 * 1) / (0.1 + 0.000303999999999841 * 0.9975) = 0.003023232350219612 WBNB // 0.003023232350219612 WBNB is converted to (0.003023232350219612 * 0.9975 * 1) / (1 + 0.003023232350219612 * 0.9975) = 0.003006607321008077 FTOKEN // 0.003006607321008077 will be returned to beneficial vault // total reward left to be added to lp is~ 0.300959999999842997 CAKE // 0.300959999999842997 CAKE is converted to (0.300959999999842997 * 0.9975 * 0.996976767649780388) / (0.100303999999999841 + 0.300959999999842997 * 0.9975) = 0.747294217375624642 WBNB // 0.747294217375624642 WBNB is converted to (0.747294217375624642 * 0.9975 * 0.996993392678991923) / (1.003023232350219612 + 0.747294217375624642 * 0.9975) = 0.425053683338158027 BTOKEN // 0.425053683338158027 BTOKEN will be added to add strat to increase an lp size // after optimal swap, 0.425053683338158027 needs to swap 0.205746399352533711 BTOKEN to get the pair // thus (0.205746399352533711 * 0.9975 * 0.1) / (2.999999999999999954 + 0.205746399352533711 * 0.9975) = 0.006403032018227551 // 0.205746399352533711 BTOKEN + 0.006403032018227551 FTOKEN to be added to the pool // LP from adding the pool will be (0.006403032018227551 / 0.09359696798177246) * 0.547432903386529256 = 0.037450255962328211 LP // Accumulated LP will be 0.231205137369691323 + 0.037450255962328211 = 0.268655393332019534 // now her balance based on share will be equal to (2.31205137369691323 / 2.31205137369691323) * 0.268655393332019534 = 0.268655393332019534 LP let vaultBalanceBefore = await baseToken.balanceOf(vault.address); await pancakeswapV2Worker02AsEve.reinvest(); let vaultBalanceAfter = await baseToken.balanceOf(vault.address); AssertHelpers.assertAlmostEqual( vaultBalanceAfter.sub(vaultBalanceBefore).toString(), ethers.utils.parseEther("0.003006607321008077").toString() ); AssertHelpers.assertAlmostEqual( CAKE_REWARD_PER_BLOCK.mul("4") .mul(REINVEST_BOUNTY_BPS) .div("10000") .sub( CAKE_REWARD_PER_BLOCK.mul("4") .mul(REINVEST_BOUNTY_BPS) .mul(BENEFICIALVAULT_BOUNTY_BPS) .div("10000") .div("10000") ) .toString(), (await cake.balanceOf(eveAddress)).toString() ); await vault.deposit(0); // Random action to trigger interest computation const healthDebt = await vault.positionInfo("1"); expect(healthDebt[0]).to.be.above(ethers.utils.parseEther("2")); const interest = ethers.utils.parseEther("0.3"); // 30% interest rate AssertHelpers.assertAlmostEqual(healthDebt[1].toString(), interest.add(loan).toString()); AssertHelpers.assertAlmostEqual( (await baseToken.balanceOf(vault.address)).toString(), deposit.sub(loan).add(ethers.utils.parseEther("0.003006607321008077")).toString() ); AssertHelpers.assertAlmostEqual((await vault.vaultDebtVal()).toString(), interest.add(loan).toString()); const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual(reservePool.toString(), (await vault.reservePool()).toString()); AssertHelpers.assertAlmostEqual( deposit.add(ethers.utils.parseEther("0.003006607321008077")).add(interest).sub(reservePool).toString(), (await vault.totalToken()).toString() ); expect(await pancakeswapV2Worker01.shares(1)).to.eq(ethers.utils.parseEther("0.231205137369691323")); expect(await pancakeswapV2Worker01.shareToBalance(await pancakeswapV2Worker01.shares(1))).to.eq( ethers.utils.parseEther("0.268655393332019534") ); // Tresuary config has been set. await pancakeswapV2Worker02.setTreasuryConfig(DEPLOYER, REINVEST_BOUNTY_BPS); // Alice closes position. This will trigger _reinvest in work function. Hence, positions get reinvested. // Reinvest fees should be transferred to DEPLOYER account. // it's 3 blocks apart since the last tx, thus 0.076 * 3 = 0.227999999999845997 CAKE // -------- // ***** Total fees: 0.227999999999845997 * 1% = 0.002279999999998459 CAKE // ***** Beneficial Vault gets: 0.002279999999998459 * 10% = 0.000227999999999845 CAKE // ***** thus DEPLOYER will receive 0.002279999999998459 - 0.000227999999999845 = 0.002051999999998614 CAKE as a bounty ***** // ***** Eve's CAKE should still be the same. ***** // -------- // 0.000227999999999845 CAKE is converted to (0.000227999999999845 * 0.9975 * 0.249682550274155746) / (0.401263999999842838 + 0.000227999999999845 * 0.9975) = 0.000141435901655073 WBNB // 0.000141435901655073 WBNB is converted to (0.000141435901655073 * 0.9975 * 0.571939709340833896) / (1.750317449725844254 + 0.000141435901655073 * 0.9975) = 0.000046096822623852 BTOKEN // -------- // ***** CAKE-WBNB reserve: 0.401491999999842683 CAKE + 0.249541114372500673 WBNB // ***** BTOKEN-WBNB reserve: 0.571893612518210044 BTOKEN + 1.750458885627499327 WBNB // ***** 0.000046096822623852 BTOKEN will be returned to beneficial vault ***** // ***** However, beneficialVault is operator. Hence, this amount will be hold with in contract first. ***** // -------- // total bounty left to be added to lp is ~0.225719999999847538 CAKE // 0.225719999999847538 CAKE is converted to (0.225719999999847538 * 0.9975 * 0.249541114372500673) / (0.401491999999842683 + 0.225719999999847538 * 0.9975) = 0.089660592842374176 WBNB // 0.089660592842374176 WBNB is converted to (0.089660592842374176 * 0.9975 * 0.571893612518210044) / (1.750458885627499327 + 0.089660592842374176 * 0.9975) = 0.027799477932277456 BTOKEN // 0.027799477932277456 BTOKEN will be added to add strat to increase an lp size // after optimal swap, 0.027799477932277456 needs to swap 0.013889009817279503 BTOKEN to get the pair // thus (0.013889009817279503 * 0.9975 * 0.1) / (3.425053683338158027 + 0.013889009817279503 * 0.9975) = 0.000402868800533636 // 0.013910468114997953 BTOKEN + 0.000402868800533636 FTOKEN to be added to the pool // -------- // LP from adding the pool will be (0.000402868800533636 / 0.099597131199466364) * 0.584883159348857467 = 0.002365843011956756 LP // BTOKEN-FTOKEN reserve: 3.452853161270435483 BTOKEN 0.100000000000000000 FTOKEN // BTOKEN-FTOKEN's LP total supply: 0.584883159348857467 + 0.002365843011956756 = 0.587249002360814223 LPs // Accumulated LP: 0.26865539333201954 + 0.002365843011956756 = 0.271021236343976296 LPs // now her balance based on share will be equal to (2.31205137369691323 / 2.31205137369691323) * 0.271021236343976296 = 0.271021236343976296 LPs // -------- // now she removes 0.271021236343976296 of her lp to BTOKEN-FTOKEN pair // (0.271021236343976296 / 0.587249002360814223) * 0.1 = 0.046150991360468409 FTOKEN // (0.271021236343976296 / 0.587249002360814223) * 3.452853161270435483 = 1.593525964147579025 BTOKEN // 0.046150991360468409 FTOKEN will be converted to // (0.046150991360468409 * 0.9975 * 1.859327197122856458) / (0.053849008639531591 + 0.046150991360468409 * 0.9975) = 0.856941406658119048 BTOKEN // -------- // ***** BTOKEN-FTOKEN reserve: 1.00238579046473741 BTOKEN 0.100000000000000000 FTOKEN // ***** thus, alice will receive 1.593525964147579025 + 0.856941406658119048 - 1.3 (debt + interest) = 1.150467370805698073 BTOKEN ***** // -------- vaultBalanceBefore = await baseToken.balanceOf(vault.address); const aliceBaseTokenBefore = await baseToken.balanceOf(aliceAddress); const aliceFarmingTokenBefore = await farmToken.balanceOf(aliceAddress); const eveCakeBefore = await cake.balanceOf(eveAddress); await vaultAsAlice.work( 1, pancakeswapV2Worker02.address, "0", "0", "115792089237316195423570985008687907853269984665640564039457584007913129639935", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); vaultBalanceAfter = await baseToken.balanceOf(vault.address); const aliceBaseTokenAfter = await baseToken.balanceOf(aliceAddress); const aliceFarmingTokenAfter = await farmToken.balanceOf(aliceAddress); expect(await cake.balanceOf(eveAddress), "Eve's CAKE must stay the same").to.be.eq(eveCakeBefore); expect(await cake.balanceOf(DEPLOYER), "Deployer should get 0.002051999999998614 CAKE").to.be.eq( ethers.utils.parseEther("0.002051999999998614") ); expect( await pancakeswapV2Worker02.buybackAmount(), "worker.buybackAmount should be 0.000046096822623852" ).to.be.eq(ethers.utils.parseEther("0.000046096822623852")); expect( await baseToken.balanceOf(pancakeswapV2Worker02.address), "worker should has 0.000046096822623852 BTOKEN" ).to.be.eq(ethers.utils.parseEther("0.000046096822623852")); expect(await pancakeswapV2Worker02.shares(1), "expect shares(1) = 0").to.eq(ethers.utils.parseEther("0")); expect( await pancakeswapV2Worker02.shareToBalance(await pancakeswapV2Worker02.shares(1)), "expect balance of shares(1) = 0" ).to.eq(ethers.utils.parseEther("0")); AssertHelpers.assertAlmostEqual( aliceBaseTokenAfter.sub(aliceBaseTokenBefore).toString(), ethers.utils .parseEther("1.593525964147579025") .add(ethers.utils.parseEther("0.856941406658119048")) .sub(interest.add(loan)) .toString() ); expect( aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore), "expect Alice's FTOKEN remain the same" ).to.eq("0"); }); }); context("when beneficialVault != operator", async () => { it("should work with the new upgraded worker", async () => { // Deploy MockBeneficialVault const MockBeneficialVault = (await ethers.getContractFactory( "MockBeneficialVault", deployer )) as MockBeneficialVault__factory; const mockFtokenVault = (await upgrades.deployProxy(MockBeneficialVault, [ farmToken.address, ])) as MockBeneficialVault; // Deployer deposits 3 BTOKEN to the bank const deposit = ethers.utils.parseEther("3"); await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can take 1 BTOKEN loan + 1 BTOKEN of her to create a new position const loan = ethers.utils.parseEther("1"); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); // Position#1: Bob borrows 1 BTOKEN loan and supply another 1 BToken // Thus, Bob's position value will be worth 20 BTOKEN // After calling `work()` // 2 BTOKEN needs to swap 0.0732967258967755614 BTOKEN to 0.042234424701074812 FTOKEN // new reserve after swap will be 1.732967258967755614 ฺBTOKEN 0.057765575298925188 FTOKEN // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 1.267032741032244386 BTOKEN - 0.042234424701074812 FTOKEN // lp amount from adding liquidity will be (0.042234424701074812 / 0.057765575298925188) * 0.316227766016837933(first total supply) = 0.231205137369691323 LP // new reserve after adding liquidity 2.999999999999999954 BTOKEN - 0.100000000000000000 FTOKEN await vaultAsAlice.work( 0, pancakeswapV2Worker01.address, ethers.utils.parseEther("1"), loan, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); // Her position should have ~2 NATIVE health (minus some small trading fee) expect(await pancakeswapV2Worker01.health(1)).to.be.eq(ethers.utils.parseEther("1.997883397660681282")); expect(await pancakeswapV2Worker01.shares(1)).to.eq(ethers.utils.parseEther("0.231205137369691323")); expect(await pancakeswapV2Worker01.shareToBalance(await pancakeswapV2Worker01.shares(1))).to.eq( ethers.utils.parseEther("0.231205137369691323") ); // PancakeswapV2Worker needs to be updated to PancakeswapV2Worker02 const PancakeswapV2Worker02 = (await ethers.getContractFactory( "PancakeswapV2Worker02", deployer )) as PancakeswapV2Worker02__factory; const pancakeswapV2Worker02 = (await upgrades.upgradeProxy( pancakeswapV2Worker01.address, PancakeswapV2Worker02 )) as PancakeswapV2Worker02; await pancakeswapV2Worker02.deployed(); // except that important states must be the same. // - health(1) should return the same value as before upgrade // - shares(1) should return the same value as before upgrade // - shareToBalance(shares(1)) should return the same value as before upgrade // - reinvestPath[0] should be reverted as reinvestPath.lenth == 0 // - reinvestPath should return default reinvest path ($CAKE->$WBNB->$BTOKEN) expect(await pancakeswapV2Worker02.health(1)).to.be.eq(ethers.utils.parseEther("1.997883397660681282")); expect(await pancakeswapV2Worker02.shares(1)).to.eq(ethers.utils.parseEther("0.231205137369691323")); expect(await pancakeswapV2Worker02.shareToBalance(await pancakeswapV2Worker01.shares(1))).to.eq( ethers.utils.parseEther("0.231205137369691323") ); expect(pancakeswapV2Worker02.address).to.eq(pancakeswapV2Worker01.address); await expect(pancakeswapV2Worker02.reinvestPath(0)).to.be.reverted; expect(await pancakeswapV2Worker02.getReinvestPath()).to.be.deep.eq([ cake.address, wbnb.address, baseToken.address, ]); const pancakeswapV2Worker02AsEve = PancakeswapV2Worker02__factory.connect( pancakeswapV2Worker02.address, eve ); // set beneficialVaultConfig await pancakeswapV2Worker02.setBeneficialVaultConfig( BENEFICIALVAULT_BOUNTY_BPS, mockFtokenVault.address, [cake.address, wbnb.address, farmToken.address] ); expect( await pancakeswapV2Worker02.beneficialVault(), "expect beneficialVault to be equal to input vault" ).to.eq(mockFtokenVault.address); expect( await pancakeswapV2Worker02.beneficialVaultBountyBps(), "expect beneficialVaultBountyBps to be equal to BENEFICIALVAULT_BOUNTY_BPS" ).to.eq(BENEFICIALVAULT_BOUNTY_BPS); expect(await pancakeswapV2Worker02.getRewardPath(), "expect CAKE->WBNB->FTOKEN path").to.be.deep.eq([ cake.address, wbnb.address, farmToken.address, ]); // Eve comes and trigger reinvest await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); // Eve calls reinvest to increase the LP size and receive portion of rewards // it's 4 blocks apart since the first tx, thus 0.0076 * 4 = 0.303999999999841411 CAKE // 1% of 0.303999999999841411 will become a bounty, thus eve shall get 90% of 0.003039999999998414 CAKE // 10% of 0.003039999999998414 will increase a beneficial vault's totalToken, this beneficial vault will get 0.0003039999999998414 CAKE // -------- // ******* thus, 0.002735999999998573 will be returned to eve ******* // -------- // 0.000303999999999841 CAKE is converted to (0.000303999999999841 * 0.9975 * 1) / (0.1 + 0.000303999999999841 * 0.9975) = 0.003023232350219612 WBNB // 0.003023232350219612 WBNB is converted to (0.003023232350219612 * 0.9975 * 1) / (1 + 0.003023232350219612 * 0.9975) = 0.003006607321008077 FTOKEN // -------- // ******* 0.003006607321008077 FTOKEN will be returned to beneficial vault ******* // -------- // total reward left to be added to lp is~ 0.300959999999842997 CAKE // 0.300959999999842997 CAKE is converted to (0.300959999999842997 * 0.9975 * 0.996976767649780388) / (1.00303999999999841 * 0.9975) = 0.747294217375624642 WBNB // 0.747294217375624642 WBNB is converted to (0.747294217375624642 * 0.9975 * 1) / (1 + 0.747294217375624642 * 0.9975) = 0.427073957641965907 BTOKEN // 0.427073957641965907 BTOKEN will be added to add strat to increase an lp size // after optimal swap, 0.427073957641965907 needs to swap 0.206692825002604811 BTOKEN to get the pair // thus (0.206692825002604811 * 0.9975 * 0.1) / (2.999999999999999954 + 0.206692825002604811 * 0.9975) = 0.006430591675675324 // 0.220381132639361117 BTOKEN + 0.006430591675675324 FTOKEN to be added to the pool // LP from adding the pool will be (0.006430591675675324 / 0.093569408324324676) * 0.547432903386529256 = 0.037622525722362969 LP // -------- // ******* LP total supply = 0.547432903386529256 + 0.037622525722362969 = 0.585055429108892225 LPs // ******* Accumulated LP will be 0.231205137369691323 + 0.037622525722362969 = 0.268827663092054292 LPs ******* // ******* now her balance based on share will be equal to (0.231205137369691323 / 0.231205137369691323) * 0.268827663092054292 = 0.268827663092054292 LP ******* // -------- await pancakeswapV2Worker02AsEve.reinvest(); expect(await farmToken.balanceOf(mockFtokenVault.address)).to.be.eq( ethers.utils.parseEther("0.003006607321008077") ); AssertHelpers.assertAlmostEqual( CAKE_REWARD_PER_BLOCK.mul("4") .mul(REINVEST_BOUNTY_BPS) .div("10000") .sub( CAKE_REWARD_PER_BLOCK.mul("4") .mul(REINVEST_BOUNTY_BPS) .mul(BENEFICIALVAULT_BOUNTY_BPS) .div("10000") .div("10000") ) .toString(), (await cake.balanceOf(eveAddress)).toString() ); await vault.deposit(0); // Random action to trigger interest computation const healthDebt = await vault.positionInfo("1"); expect(healthDebt[0]).to.be.above(ethers.utils.parseEther("2")); const interest = ethers.utils.parseEther("0.300001"); // 30% interest rate + 0.000001 for margin AssertHelpers.assertAlmostEqual(healthDebt[1].toString(), interest.add(loan).toString()); AssertHelpers.assertAlmostEqual((await vault.vaultDebtVal()).toString(), interest.add(loan).toString()); // add 0.000001 for error-margin const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual(reservePool.toString(), (await vault.reservePool()).toString()); expect(await pancakeswapV2Worker02.shares(1)).to.eq(ethers.utils.parseEther("0.231205137369691323")); expect(await pancakeswapV2Worker02.shareToBalance(await pancakeswapV2Worker02.shares(1))).to.eq( ethers.utils.parseEther("0.268827663092054292") ); // Treasury config set. await pancakeswapV2Worker02.setTreasuryConfig(DEPLOYER, REINVEST_BOUNTY_BPS); // Alice closes position. This will trigger _reinvest in work function. Hence, positions get reinvested. // Reinvest fees should be transferred to DEPLOYER account. // it's 3 blocks apart since the first tx, thus 0.076 * 3 = 0.227999999999974897 CAKE // -------- // ***** Total fees: 0.227999999999974897 * 1% = 0.002279999999999748 CAKE // ***** Beneficial Vault gets: 0.002279999999999748 * 10% = 0.000227999999999974 CAKE // ***** thus DEPLOYER will receive 0.002279999999999748 - 0.000227999999999974 = 0.002051999999999774 CAKE as a bounty ***** // ***** Eve's CAKE should still be the same. ***** // -------- // 0.000227999999999974 CAKE is converted to (0.000227999999999974 * 0.9975 * 0.249682550274155746) / (0.401263999999842838 + 0.000227999999999974 * 0.9975) = 0.000141435901655153 WBNB // 0.000141435901655153 WBNB is converted to (0.000141435901655153 * 0.9975 * 0.996993392678991923) / (1.003023232350219612 + 0.000141435901655153 * 0.9975) = 0.000140214450148741 FTOKEN // -------- // ***** CAKE-WBNB reserve: 0.401491999999842812 CAKE + 0.249541114372500593 WBNB // ***** FTOKEN-WBNB reserve: 0.997133607129140664 FTOKEN + 1.003164668251874765 WBNB // ***** 0.000140214450148741 FTOKEN will be returned to beneficial vault ***** // ***** Combined FTOKEN before = 0.003006607321008077 + 0.000140214450148741 = 0.003146821771156818 FTOKEN // -------- // total bounty left to be added to lp is ~0.225719999999975149 CAKE // 0.225719999999975149 CAKE is converted to (0.225719999999975149 * 0.9975 * 0.249541114372500593) / (0.401491999999842812 + 0.225719999999975149 * 0.9975) = 0.089660592842406605 WBNB // 0.089660592842406605 WBNB is converted to (0.089660592842406605 * 0.9975 * 0.572926042358034093) / (1.747294217375624642 + 0.089660592842406605 * 0.9975) = 0.027897648546035661 BTOKEN // 0.027897648546035661 BTOKEN will be added to add strat to increase an lp size // after optimal swap, 0.027897648546035661 needs to swap 0.013937974595638415 BTOKEN to get the pair // thus (0.013937974595638415 * 0.9975 * 0.1) / (3.427073957641965907 + 0.013937974595638415 * 0.9975) = 0.000404045981894464 FTOKEN // 0.013959673950397246 BTOKEN + 0.000404045981894464 FTOKEN to be added to the pool // -------- // ***** LP from adding the pool will be (0.000404045981894464 / 0.099595954018105536) * 0.585055429108892225 = 0.002373482915521007 LP // ***** latest balance of BTOKEN-FTOKEN pair will be 3.454971606188001568 BTOKEN 0.100000000000000000 FTOKEN // ***** latest BTOKEN-FTOKEN's LP total supply will be 0.585055429108892225 + 0.002373482915521007 = 0.587428912024413232 LPs // ***** Accumulated LP will be 0.268827663092054292 + 0.002373482915521007 = 0.271201146007575299 LPs // ***** now her balance based on share will be equal to (2.31205137369691323 / 2.31205137369691323) * 0.271201146007575299 = 0.271201146007575299 LPs // -------- // now she removes 0.271201146007575299 of her lp to BTOKEN-FTOKEN pair // (0.271201146007575299 / 0.587428912024413232) * 0.1 = 0.046167483495654760 FTOKEN // (0.271201146007575299 / 0.587428912024413232) * 3.454971606188001568 = 1.595073446066403795 BTOKEN // 0.046167483495654760 FTOKEN will be converted to (0.046167483495654760 * 0.9975 * 1.859898160121597773) / (0.05383251650434524 + 0.046167483495654760 * 0.9975) = 0.857511234063499008 BTOKEN // -------- // ***** latest balance of BTOKEN-FTOKEN pair will be 1.002386926058098765 BTOKEN 0.100000000000000000 FTOKEN // ***** thus, alice will receive 1.595073446066403795 + 0.857511234063499008 - 1.3 (interest + debt) = 1.152584680129902803 BTOKEN ***** // -------- const aliceBaseTokenBefore = await baseToken.balanceOf(aliceAddress); const aliceFarmingTokenBefore = await farmToken.balanceOf(aliceAddress); const eveCakeBefore = await cake.balanceOf(eveAddress); await vaultAsAlice.work( 1, pancakeswapV2Worker02.address, "0", "0", "115792089237316195423570985008687907853269984665640564039457584007913129639935", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [liqStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const aliceBaseTokenAfter = await baseToken.balanceOf(aliceAddress); const aliceFarmingTokenAfter = await farmToken.balanceOf(aliceAddress); expect(await cake.balanceOf(eveAddress), "expect Eve's CAKE stay the same").to.be.eq(eveCakeBefore); expect(await cake.balanceOf(DEPLOYER), "expect deployer get 0.002051999999999774 CAKE").to.be.eq( ethers.utils.parseEther("0.002051999999999774") ); expect( await farmToken.balanceOf(mockFtokenVault.address), "expect mockFtokenVault get 0.003146821771156818 FTOKEN from buyback & redistribute" ).to.be.eq(ethers.utils.parseEther("0.003146821771156818")); expect( await baseToken.balanceOf(pancakeswapV2Worker02.address), "expect worker shouldn't has any BTOKEN due to operator != beneficialVault" ).to.be.eq(ethers.utils.parseEther("0")); expect( await farmToken.balanceOf(pancakeswapV2Worker02.address), "expect worker shouldn't has any FTOKEN due to it is automatically redistribute to ibFTOKEN holder" ).to.be.eq(ethers.utils.parseEther("0")); expect(await pancakeswapV2Worker02.shares(1), "expect shares(1) is 0 as Alice closed position").to.eq( ethers.utils.parseEther("0") ); expect( await pancakeswapV2Worker02.shareToBalance(await pancakeswapV2Worker02.shares(1)), "expect shareToBalance(shares(1) is 0 as Alice closed position" ).to.eq(ethers.utils.parseEther("0")); AssertHelpers.assertAlmostEqual( aliceBaseTokenAfter.sub(aliceBaseTokenBefore).toString(), ethers.utils .parseEther("1.595073446066403795") .add(ethers.utils.parseEther("0.857511234063499008")) .sub(interest.add(loan)) .toString() ); expect( aliceFarmingTokenAfter.sub(aliceFarmingTokenBefore), "expect Alice's FTOKEN remain the same" ).to.eq("0"); }); }); }); }); context("#addCollateral", async () => { const deposit = ethers.utils.parseEther("3"); const borrowedAmount = ethers.utils.parseEther("1"); beforeEach(async () => { // Deployer deposits 3 BTOKEN to the bank await baseToken.approve(vault.address, deposit); await vault.deposit(deposit); // Now Alice can borrow 1 BTOKEN + 1 BTOKEN of her to create a new position await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); // Position#1: Alice borrows 1 BTOKEN and supply another 1 BTOKEN // After calling `work()` // 2 BTOKEN needs to swap 0.0732967258967755614 BTOKEN to 0.042234424701074812 FTOKEN // new reserve after swap will be 1.732967258967755614 BTOKEN 0.057765575298925188 FTOKEN // based on optimal swap formula, BTOKEN-FTOKEN to be added into the LP will be 1.267032741032244386 BTOKEN + 0.042234424701074812 FTOKEN // lp amount from adding liquidity will be (0.042234424701074812 / 0.057765575298925188) * 0.316227766016837933(first total supply) = 0.231205137369691323 LP // new reserve after adding liquidity 2.999999999999999954 BTOKEN + 0.100000000000000000 FTOKEN // ---------------- // BTOKEN-FTOKEN reserve = 2.999999999999999954 BTOKEN + 0.100000000000000000 FTOKEN // BTOKEN-FTOKEN total supply = 0.547432903386529256 BTOKEN-FTOKEN LP // ---------------- await swapHelper.loadReserves(await pancakeswapV2Worker.getPath()); await vaultAsAlice.work( 0, pancakeswapV2Worker.address, ethers.utils.parseEther("1"), borrowedAmount, "0", ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const [expectedLp] = await swapHelper.computeOneSidedOptimalLp( ethers.utils.parseEther("1").add(borrowedAmount), await pancakeswapV2Worker.getPath() ); const expectedHealth = await swapHelper.computeLpHealth(expectedLp, baseToken.address, farmToken.address); expect(await pancakeswapV2Worker.health(1)).to.be.eq(expectedHealth); expect(await pancakeswapV2Worker.shares(1)).to.eq(expectedLp); expect(await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1))).to.eq(expectedLp); }); async function successBtokenOnly(lastWorkBlock: BigNumber, goRouge: boolean) { await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); let accumLp = await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)); const [workerLpBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); const debris = await baseToken.balanceOf(addStrat.address); const reinvestPath = await pancakeswapV2Worker.getReinvestPath(); const path = await pancakeswapV2Worker.getPath(); let reserves = await swapHelper.loadReserves(reinvestPath); reserves.push(...(await swapHelper.loadReserves(path))); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ); const blockAfter = await TimeHelpers.latestBlockNumber(); const blockDiff = blockAfter.sub(lastWorkBlock); const totalRewards = workerLpBefore .mul(CAKE_REWARD_PER_BLOCK.mul(blockDiff).mul(1e12).div(workerLpBefore)) .div(1e12); const totalReinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); const reinvestLeft = totalRewards.sub(totalReinvestFees); const reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); const reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debris); const [reinvestLp] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); // Compute add collateral const addCollateralBtoken = ethers.utils.parseEther("1"); const [addCollateralLp] = await swapHelper.computeOneSidedOptimalLp(addCollateralBtoken, path); accumLp = accumLp.add(addCollateralLp); const [health, debt] = await vault.positionInfo("1"); expect(health).to.be.above(ethers.utils.parseEther("3")); const interest = ethers.utils.parseEther("0.3"); // 30% interest rate AssertHelpers.assertAlmostEqual(debt.toString(), interest.add(borrowedAmount).toString()); AssertHelpers.assertAlmostEqual( (await baseToken.balanceOf(vault.address)).toString(), deposit.sub(borrowedAmount).toString() ); AssertHelpers.assertAlmostEqual( (await vault.vaultDebtVal()).toString(), interest.add(borrowedAmount).toString() ); const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual(reservePool.toString(), (await vault.reservePool()).toString()); AssertHelpers.assertAlmostEqual( deposit.add(interest).sub(reservePool).toString(), (await vault.totalToken()).toString() ); expect(await pancakeswapV2Worker.shares(1), `expect Alice's shares = ${accumLp}`).to.be.eq(accumLp); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Alice's staked LPs = ${accumLp}` ).to.be.eq(accumLp); expect( await cake.balanceOf(DEPLOYER), `expect Deployer gets ${ethers.utils.formatEther(totalReinvestFees)} CAKE` ).to.be.eq(totalReinvestFees); } async function successTwoSides(lastWorkBlock: BigNumber, goRouge: boolean) { await TimeHelpers.increase(TimeHelpers.duration.days(ethers.BigNumber.from("1"))); // Random action to trigger interest computation await vault.deposit("0"); // Set intertest rate to 0 for easy testing await simpleVaultConfig.setParams( MIN_DEBT_SIZE, 0, RESERVE_POOL_BPS, KILL_PRIZE_BPS, wbnb.address, wNativeRelayer.address, fairLaunch.address, KILL_TREASURY_BPS, deployerAddress ); let accumLp = await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)); const [workerLpBefore] = await masterChef.userInfo(POOL_ID, pancakeswapV2Worker.address); const debris = await baseToken.balanceOf(addStrat.address); const reinvestPath = await pancakeswapV2Worker.getReinvestPath(); const path = await pancakeswapV2Worker.getPath(); let reserves = await swapHelper.loadReserves(reinvestPath); reserves.push(...(await swapHelper.loadReserves(path))); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await farmTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.1")); await vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [ twoSidesStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256", "uint256"], [ethers.utils.parseEther("0.1"), "0"]), ] ) ); const blockAfter = await TimeHelpers.latestBlockNumber(); const blockDiff = blockAfter.sub(lastWorkBlock); const totalRewards = workerLpBefore .mul(CAKE_REWARD_PER_BLOCK.mul(blockDiff).mul(1e12).div(workerLpBefore)) .div(1e12); const totalReinvestFees = totalRewards.mul(REINVEST_BOUNTY_BPS).div(10000); const reinvestLeft = totalRewards.sub(totalReinvestFees); const reinvestAmts = await swapHelper.computeSwapExactTokensForTokens(reinvestLeft, reinvestPath, true); const reinvestBtoken = reinvestAmts[reinvestAmts.length - 1].add(debris); const [reinvestLp] = await swapHelper.computeOneSidedOptimalLp(reinvestBtoken, path); accumLp = accumLp.add(reinvestLp); // Compute add collateral const addCollateralBtoken = ethers.utils.parseEther("1"); const addCollateralFtoken = ethers.utils.parseEther("0.1"); const [addCollateralLp, debrisBtoken, debrisFtoken] = await swapHelper.computeTwoSidesOptimalLp( addCollateralBtoken, addCollateralFtoken, path ); accumLp = accumLp.add(addCollateralLp); const [health, debt] = await vault.positionInfo("1"); expect(health).to.be.above(ethers.utils.parseEther("3")); const interest = ethers.utils.parseEther("0.3"); // 30% interest rate AssertHelpers.assertAlmostEqual(debt.toString(), interest.add(borrowedAmount).toString()); AssertHelpers.assertAlmostEqual( (await baseToken.balanceOf(vault.address)).toString(), deposit.sub(borrowedAmount).toString() ); AssertHelpers.assertAlmostEqual( (await vault.vaultDebtVal()).toString(), interest.add(borrowedAmount).toString() ); const reservePool = interest.mul(RESERVE_POOL_BPS).div("10000"); AssertHelpers.assertAlmostEqual(reservePool.toString(), (await vault.reservePool()).toString()); AssertHelpers.assertAlmostEqual( deposit.add(interest).sub(reservePool).toString(), (await vault.totalToken()).toString() ); expect(await pancakeswapV2Worker.shares(1), `expect Alice's shares = ${accumLp}`).to.be.eq(accumLp); expect( await pancakeswapV2Worker.shareToBalance(await pancakeswapV2Worker.shares(1)), `expect Alice's staked LPs = ${accumLp}` ).to.be.eq(accumLp); expect(await cake.balanceOf(DEPLOYER), `expect Deployer gets ${totalReinvestFees} CAKE`).to.be.eq( totalReinvestFees ); expect( await baseToken.balanceOf(twoSidesStrat.address), `expect TwoSides to have debris ${debrisBtoken} BTOKEN` ).to.be.eq(debrisBtoken); expect( await farmToken.balanceOf(twoSidesStrat.address), `expect TwoSides to have debris ${debrisFtoken} FTOKEN` ).to.be.eq(debrisFtoken); } async function revertNotEnoughCollateral(goRouge: boolean, stratAddress: string) { // Simulate price swing to make position under water await farmToken.approve(routerV2.address, ethers.utils.parseEther("888")); await routerV2.swapExactTokensForTokens( ethers.utils.parseEther("888"), "0", [farmToken.address, baseToken.address], deployerAddress, FOREVER ); // Add super small collateral that it would still under the water after collateral is getting added await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("0.000000000000000001")); await expect( vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("0.000000000000000001"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [stratAddress, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("debtRatio > killFactor margin"); } async function revertUnapprovedStrat(goRouge: boolean, stratAddress: string) { await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("88")); await expect( vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [stratAddress, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("!approved strat"); } async function revertReserveNotConsistent(goRouge: boolean, stratAddress: string) { await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("88")); await expect( vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), goRouge, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [stratAddress, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("reserve !consistent"); } context("when go rouge is false", async () => { context("when worker is stable", async () => { it("should increase health when add BTOKEN only strat is choosen", async () => { await successBtokenOnly(await TimeHelpers.latestBlockNumber(), false); }); it("should increase health when twosides strat is choosen", async () => { await successTwoSides(await TimeHelpers.latestBlockNumber(), false); }); it("should revert when not enough collateral to pass kill factor", async () => { await revertNotEnoughCollateral(false, addStrat.address); }); it("should revert when using liquidate strat", async () => { await revertUnapprovedStrat(false, liqStrat.address); }); it("should revert when using minimize trading strat", async () => { await revertUnapprovedStrat(false, minimizeStrat.address); }); it("should revert when using partial close liquidate start", async () => { await revertUnapprovedStrat(false, partialCloseStrat.address); }); it("should revert when using partial close minimize start", async () => { await revertUnapprovedStrat(false, partialCloseMinimizeStrat.address); }); }); context("when worker is unstable", async () => { it("should revert", async () => { // Set worker to unstable simpleVaultConfig.setWorker( pancakeswapV2Worker.address, true, true, WORK_FACTOR, KILL_FACTOR, false, true ); await baseTokenAsAlice.approve(vault.address, ethers.utils.parseEther("1")); await expect( vaultAsAlice.addCollateral( 1, ethers.utils.parseEther("1"), false, ethers.utils.defaultAbiCoder.encode( ["address", "bytes"], [addStrat.address, ethers.utils.defaultAbiCoder.encode(["uint256"], ["0"])] ) ) ).to.be.revertedWith("worker !stable"); }); }); }); context("when go rouge is true", async () => { context("when worker is unstable", async () => { beforeEach(async () => { // Set worker to unstable await simpleVaultConfig.setWorker( pancakeswapV2Worker.address, true, true, WORK_FACTOR, KILL_FACTOR, false, true ); }); it("should increase health when add BTOKEN only strat is choosen", async () => { await successBtokenOnly((await TimeHelpers.latestBlockNumber()).sub(1), true); }); it("should increase health when twosides strat is choosen", async () => { await successTwoSides((await TimeHelpers.latestBlockNumber()).sub(1), true); }); it("should revert when not enough collateral to pass kill factor", async () => { await revertNotEnoughCollateral(true, addStrat.address); }); it("should revert when using liquidate strat", async () => { await revertUnapprovedStrat(true, liqStrat.address); }); it("should revert when using minimize trading strat", async () => { await revertUnapprovedStrat(true, minimizeStrat.address); }); it("should revert when using partial close liquidate start", async () => { await revertUnapprovedStrat(true, partialCloseStrat.address); }); it("should revert when using partial close minimize start", async () => { await revertUnapprovedStrat(true, partialCloseMinimizeStrat.address); }); }); context("when reserve is inconsistent", async () => { beforeEach(async () => { // Set worker to unstable await simpleVaultConfig.setWorker( pancakeswapV2Worker.address, true, true, WORK_FACTOR, KILL_FACTOR, false, false ); }); it("should revert", async () => { await revertReserveNotConsistent(true, addStrat.address); }); }); }); }); }); }); });
the_stack
import {createElement as $, PureComponent} from 'react'; import { Linking, Platform, StyleSheet, Text, TextProps, View, ViewProps, } from 'react-native'; import {Palette} from '../global-styles/palette'; import {Dimensions} from '../global-styles/dimens'; import {Typography} from '../global-styles/typography'; import {GlobalEventBus} from '../drivers/eventbus'; import ZoomableImage from './ZoomableImage'; import AudioPlayer from './AudioPlayer'; import { isFeedSSBURI, isMessageSSBURI, isSSBURI, toFeedSigil, toMessageSigil, } from 'ssb-uri2'; const gemojiToEmoji = require('remark-gemoji-to-emoji'); const imagesToSsbServeBlobs = require('remark-images-to-ssb-serve-blobs'); const linkifyRegex = require('remark-linkify-regex'); const normalizeForReactNative = require('mdast-normalize-react-native'); const ReactMarkdown = require('react-markdown'); const Ref = require('ssb-ref'); const remark = require('remark'); const ELLIPSIS = '\u2026'; const textProps: TextProps = { selectable: true, textBreakStrategy: 'simple', }; const styles = StyleSheet.create({ text: { ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, heading1: { fontWeight: '700', color: Palette.text, fontSize: Typography.fontSizeLarger, lineHeight: Typography.lineHeightLarger, marginVertical: Dimensions.verticalSpaceSmall, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, heading2: { fontWeight: '700', color: Palette.text, fontSize: Typography.fontSizeLarge, lineHeight: Typography.lineHeightLarge, marginVertical: Dimensions.verticalSpaceSmall, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, heading3: { fontWeight: '700', color: Palette.text, fontSize: Typography.fontSizeBig, lineHeight: Typography.lineHeightBig, marginVertical: Dimensions.verticalSpaceSmall, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, heading4: { fontWeight: '700', color: Palette.text, fontSize: Typography.fontSizeNormal, lineHeight: Typography.lineHeightNormal, marginVertical: Dimensions.verticalSpaceSmall, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, heading5: { fontWeight: '700', color: Palette.text, fontSize: Typography.fontSizeSmall, lineHeight: Typography.lineHeightSmall, marginVertical: Dimensions.verticalSpaceSmall, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, heading6: { fontWeight: '700', color: Palette.text, fontSize: Typography.fontSizeTiny, lineHeight: Typography.lineHeightTiny, marginVertical: Dimensions.verticalSpaceSmall, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, paragraph: { flexWrap: 'wrap', flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'flex-start', marginVertical: Dimensions.verticalSpaceSmall, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, paragraphText: { flexWrap: 'wrap', overflow: 'visible', color: Palette.text, fontSize: Typography.fontSizeNormal, lineHeight: Typography.lineHeightNormal, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, strong: { fontWeight: '700', }, em: { fontStyle: 'italic', }, strikethrough: { textDecorationLine: 'line-through', }, link: { textDecorationLine: 'underline', }, cypherlink: { color: Palette.textBrand, textDecorationLine: 'underline', }, listItemText: { color: Palette.text, fontSize: Typography.fontSizeNormal, lineHeight: Typography.lineHeightNormal, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, orderedBullet: { fontWeight: '700', }, inlineCode: { backgroundColor: Palette.backgroundTextWeak, fontFamily: Typography.fontFamilyMonospace, color: Palette.textWeak, ...Platform.select({ web: { wordBreak: 'break-all', }, }), }, codeBlock: { backgroundColor: Palette.backgroundTextWeak, marginVertical: Dimensions.verticalSpaceSmall, padding: Dimensions.verticalSpaceSmall, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-all', }, }), }, codeText: { fontWeight: '400', color: Palette.textWeak, fontSize: Typography.fontSizeSmall, lineHeight: Typography.lineHeightSmall, fontFamily: Typography.fontFamilyMonospace, ...Platform.select({ web: { wordBreak: 'break-all', }, }), }, blockquote: { backgroundColor: Palette.backgroundTextWeak, borderLeftWidth: 3, borderLeftColor: Palette.backgroundTextWeakStrong, marginVertical: Dimensions.verticalSpaceSmall, paddingLeft: Dimensions.horizontalSpaceSmall, paddingRight: 1, ...Platform.select({ web: { fontFamily: Typography.fontFamilyReadableText, wordBreak: 'break-word', }, }), }, horizontalLine: { backgroundColor: Palette.textLine, marginVertical: Dimensions.verticalSpaceSmall, height: 2, }, }); function makeRenderers(onLayout?: ViewProps['onLayout']) { const renderers = { root: (props: {children: any}) => $(View, {onLayout}, props.children), paragraph: (props: {children: any}) => $( View, {style: styles.paragraph}, $(Text, {...textProps, style: styles.paragraphText}, props.children), ), text: (props: {children: any}) => $(Text, {...textProps, style: styles.text}, props.children), heading: (props: {children: any; level: 1 | 2 | 3 | 4 | 5 | 6}) => $( Text, {...textProps, style: styles['heading' + props.level]}, props.children, ), emphasis: (props: {children: any}) => $(Text, {...textProps, style: styles.em}, props.children), strong: (props: {children: any}) => $(Text, {...textProps, style: styles.strong}, props.children), link: (props: {children: any; href: string}) => { if (!props.href) return renderers.text(props); const feedId = Ref.isFeedId(props.href) ? props.href : isFeedSSBURI(props.href) ? toFeedSigil(props.href) : null; const msgId = Ref.isMsgId(props.href) ? props.href : isMessageSSBURI(props.href) ? toMessageSigil(props.href) : null; const hashtag = props.href.startsWith('#') ? props.href : null; const isCypherlink = !!feedId || !!msgId || !!hashtag; let child: string | null = null; if (isCypherlink) { child = typeof props.children?.[0] === 'string' ? props.children[0] : typeof props.children?.[0]?.props?.children === 'string' ? props.children[0].props.children : null; } if (child) { if (Ref.isFeedId(child) || Ref.isMsgId(child)) { child = child.slice(0, 10) + ELLIPSIS; } else if (isFeedSSBURI(child)) { child = child.slice(0, 26) + ELLIPSIS; } else if (isMessageSSBURI(child)) { child = child.slice(0, 28) + ELLIPSIS; } } if (isCypherlink) { return $( Text, { ...textProps, style: styles.cypherlink, onPress: () => { if (feedId) { GlobalEventBus.dispatch({ type: 'triggerFeedCypherlink', feedId, }); } else if (msgId) { GlobalEventBus.dispatch({type: 'triggerMsgCypherlink', msgId}); } else if (hashtag) { GlobalEventBus.dispatch({type: 'triggerHashtagLink', hashtag}); } else { throw new Error('unreachable'); } }, }, child ?? props.children, ); } else if (Platform.OS === 'web') { return $( 'a', { style: {textDecoration: 'underline', color: Palette.text}, href: props.href, }, child ?? props.children, ); } else { return $( Text, { ...textProps, style: styles.link, onPress: () => { Linking.openURL(props.href); }, }, child ?? props.children, ); } }, inlineCode: (props: {children: any}) => $(Text, {...textProps, style: styles.inlineCode}, props.children), delete: (props: {children: any}) => $(Text, {...textProps, style: styles.strikethrough}, props.children), blockquote: (props: {children: any}) => $(View, {style: styles.blockquote}, props.children), code: (props: {value: string; language: string}) => $( View, {style: styles.codeBlock}, $(Text, {...textProps, style: styles.codeText}, props.value), ), thematicBreak: () => $(View, {style: styles.horizontalLine}), image: (props: {src: string; title?: string; alt?: string}) => { // Audio and video are recognized as images but their caption start with `audio:` or `video:` if (props.alt?.startsWith('audio:')) { if (Platform.OS === 'web') { return $('audio', { src: props.src, controls: true, style: { width: '100%', margin: `${Dimensions.verticalSpaceSmall}px 0`, }, }); } else { return $(AudioPlayer, {src: props.src}); } } return $(ZoomableImage, { src: props.src, title: props.title ?? props.alt, }); }, list: (props: {children: any; depth: number; ordered: boolean}) => $( View, { style: { paddingLeft: Dimensions.horizontalSpaceNormal * (props.depth + 1), }, }, props.children, ), listItem: (props: {children: any; index: number; ordered: boolean}) => { return $( Text, {...textProps, style: styles.listItemText}, props.ordered ? $(Text, {style: styles.orderedBullet}, `${props.index + 1}. `) : $(Text, null, `\u2022 `), props.children, ); }, }; return renderers; } export type Props = { text: string; onLayout?: ViewProps['onLayout']; }; export default class Markdown extends PureComponent<Props> { public render() { const linkifySsbFeeds = linkifyRegex(Ref.feedIdRegex); const linkifySsbMsgs = linkifyRegex(Ref.msgIdRegex); const linkifyHashtags = linkifyRegex(/#[\w-]+/g); const renderers = makeRenderers(this.props.onLayout); return $<any>(ReactMarkdown, { source: remark() .use(gemojiToEmoji) .use(linkifySsbFeeds) .use(linkifySsbMsgs) .use(linkifyHashtags) .use(imagesToSsbServeBlobs) .processSync(this.props.text).contents, astPlugins: [normalizeForReactNative()], allowedTypes: Object.keys(renderers), transformLinkUri: (uri: string) => { if (isSSBURI(uri)) return uri; // don't interfere with SSB URIs return ReactMarkdown.uriTransformer(uri); // interfere with all others }, renderers, }); } }
the_stack
import * as React from "react"; import { storiesOf } from "@storybook/react"; import { Gitgraph, Mode, Branch } from "@gitgraph/react"; import { GitgraphCore } from "@gitgraph/core"; import { createFixedHashGenerator, hashPrefix } from "../helpers"; storiesOf("gitgraph-react/1. Basic usage", module) .add("default", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master").commit("Initial commit"); const develop = gitgraph.branch("develop"); develop.commit("one"); master.commit("two"); develop.commit("three"); master.merge(develop); }} </Gitgraph> )) .add("pass graph instance as a prop", () => { const graph = new GitgraphCore<React.ReactElement<SVGElement>>({ generateCommitHash: createFixedHashGenerator(), }); const gitgraph = graph.getUserApi(); const master = gitgraph .branch("master") .commit("Initial commit (from graph props)"); const develop = gitgraph.branch("develop"); develop.commit("one"); master.commit("two"); develop.commit("three"); master.merge(develop); return <Gitgraph graph={graph} />; }) .add("stop on last commit", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master").commit("Initial commit"); const develop = gitgraph.branch("develop"); const feat = gitgraph.branch("feat"); feat.commit(); master.commit("five"); develop.commit("six"); master.merge(develop); }} </Gitgraph> )) .add("commit after merge", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph .branch("master") .commit("one") .commit("two") .commit("three"); const develop = gitgraph.branch("develop").commit("four"); master.commit("five"); develop.commit("six"); master.merge(develop); develop.commit("seven"); }} </Gitgraph> )) .add("multiple merges", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master"); master.commit().commit(); const develop = gitgraph.branch("develop"); develop.commit(); const feat1 = gitgraph.branch("feat1"); feat1.commit().commit(); develop.commit(); develop.merge(feat1); master.commit().commit(); master.merge(develop, "Release new version"); }} </Gitgraph> )) .add("multiple merges in master", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master"); master.commit("one").commit("two"); const develop = gitgraph.branch("develop"); const feat = gitgraph.branch("feat"); develop.commit("three").commit("four"); master.commit("five"); develop.merge(master); master.commit("six"); develop.commit("seven"); feat.commit("eight"); master.merge(feat); master.merge(develop); }} </Gitgraph> )) .add("multiple merges from same commit", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master"); master.commit("Initial version"); const develop = gitgraph.branch("develop").commit("Do something"); const fix = gitgraph.branch("fix"); const release = gitgraph.branch("release"); const feature = develop.branch("feature"); fix.commit("Bug fixed."); release.merge(fix); feature.merge(fix); develop.merge(fix, "Bugfixes are always merged back to develop"); master.merge(develop, "New release"); }} </Gitgraph> )) .add("merge with fast-forward", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master"); master.commit(); // Branch that can be fast-forward on merge. const feat1 = gitgraph.branch("feat1"); feat1 .commit("First commit of `feat1` branch") .commit("Master will fast-forward here"); master.merge({ branch: feat1, fastForward: true }); master.commit(); // Another branch which merge can't be fast-forward. const feat2 = gitgraph.branch("feat2"); feat2.commit().commit(); master.commit("This commit prevent fast-forward merge"); master.merge({ branch: feat2, fastForward: true }); }} </Gitgraph> )) .add("tags", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master"); // Tag on branch master.commit().tag("v1.0").tag("first release"); master.commit(); master.tag("v1.1"); master.commit({ tag: "v1.2" }); // Tag on gitgraph master.commit(); gitgraph.tag("v2.0"); // Custom tags const customTagStyle = { bgColor: "orange", strokeColor: "orange", borderRadius: 0, pointerWidth: 0, }; gitgraph.tag({ name: "last release", style: customTagStyle, }); gitgraph .branch("feat1") .commit() .tag({ name: "something cool", style: customTagStyle }); }} </Gitgraph> )) .add("branch colors", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master").commit("one"); const develop = gitgraph.branch("develop").commit("two"); const feat1 = gitgraph.branch("feat1").commit("three"); const feat2 = gitgraph.branch("feat2").commit("four"); master.commit("five"); develop.commit("six"); feat1.commit("seven"); feat2.commit("height"); }} </Gitgraph> )) .add("branch with style", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch({ name: "master", style: { label: { bgColor: "#ffce52", color: "black", strokeColor: "#ce9b00", borderRadius: 0, font: "italic 12pt serif", }, }, }); master.commit().commit().commit(); gitgraph.branch("feat1").commit().commit(); }} </Gitgraph> )) .add("branch label on every commit", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator(), branchLabelOnEveryCommit: true, }} > {(gitgraph) => { const master = gitgraph.branch("master").commit(); const develop = gitgraph.branch("develop").commit().commit(); master.commit(); gitgraph.branch("feat1").commit().commit(); master.merge(develop); }} </Gitgraph> )) .add("branching from a past commit hash", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master"); master.commit(); const feat1 = gitgraph.branch("feat1"); feat1.commit().commit(); const feat2 = gitgraph.branch({ name: "feat2", from: `${hashPrefix}1`, }); feat2.commit(); }} </Gitgraph> )) .add("branching from a past reference", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master"); master.commit(); const feat1 = gitgraph.branch("feat1"); feat1.commit().commit(); const feat2 = gitgraph.branch({ name: "feat2", from: master, }); feat2.commit(); const feat1Part2 = feat1.branch("feat1/part2"); feat1Part2.commit().commit(); }} </Gitgraph> )) .add("compact mode", () => ( <Gitgraph options={{ mode: Mode.Compact, generateCommitHash: createFixedHashGenerator(), }} > {(gitgraph) => { const master = gitgraph.branch("master").commit().commit(); // Branch has more commits. const develop = gitgraph.branch("develop").commit(); master.merge(develop); // Branch & master have as much commits. const feat1 = gitgraph.branch("feat1").commit(); master.commit(); master.merge(feat1); // Master has more commits. const feat2 = gitgraph.branch("feat2").commit(); master.commit().commit(); master.merge(feat2); }} </Gitgraph> )) .add("commit dot text", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { gitgraph .commit({ subject: "Initial commit", dotText: "1" }) .commit({ subject: "Another commit", dotText: "2", style: { dot: { font: "italic 12pt Calibri" } }, }) .commit({ subject: "Do something crazy", dotText: "🙀" }); }} </Gitgraph> )) .add("commit message body", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { gitgraph .commit("Initial commit") .commit({ subject: "Commit with a body", body: "Your bones don't break, mine do. That's clear. Your cells react to bacteria and viruses differently than mine. You don't get sick, I do. That's also clear. But for some reason, you and I react the exact same way to water. We swallow it too fast, we choke. We get some in our lungs, we drown. However unreal it may seem, we are connected, you and I. We're on the same curve, just on opposite ends.", }) .commit({ body: "This is to explain the rationale behind this commit.", }) .commit(); }} </Gitgraph> )) .add("custom branch order", () => { const branchesOrder = ["feat1", "develop", "master"]; const compareBranchesOrder = (a: Branch["name"], b: Branch["name"]) => branchesOrder.indexOf(a) - branchesOrder.indexOf(b); return ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator(), compareBranchesOrder, }} > {(gitgraph) => { const master = gitgraph.branch("master").commit("Initial commit"); const develop = gitgraph.branch("develop").commit(); const feat1 = gitgraph.branch("feat1").commit().commit(); master.commit(); develop.commit(); master.merge(develop); feat1.commit(); }} </Gitgraph> ); }) .add("delete a branch", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master").commit("Initial commit"); const develop = gitgraph.branch("develop"); develop.commit("one"); master.commit("two"); master.checkout(); develop.delete(); }} </Gitgraph> )) .add("delete a branch after merging it", () => ( <Gitgraph options={{ generateCommitHash: createFixedHashGenerator() }}> {(gitgraph) => { const master = gitgraph.branch("master").commit("Initial commit"); const develop = gitgraph.branch("develop"); develop.commit("one"); master.commit("two"); master.checkout(); master.merge(develop); develop.delete(); }} </Gitgraph> ));
the_stack
import { GridLayoutBase, ItemSpec } from './grid-layout-common'; import { View } from '../../core/view'; import { layout } from '../../../utils'; export * from './grid-layout-common'; export class GridLayout extends GridLayoutBase { private helper: MeasureHelper; private columnOffsets = new Array<number>(); private rowOffsets = new Array<number>(); private map = new Map<View, MeasureSpecs>(); constructor() { super(); this.helper = new MeasureHelper(this); } public _onRowAdded(itemSpec: ItemSpec) { this.helper.rows.push(new ItemGroup(itemSpec)); } public _onColumnAdded(itemSpec: ItemSpec) { this.helper.columns.push(new ItemGroup(itemSpec)); } public _onRowRemoved(itemSpec: ItemSpec, index: number) { this.helper.rows[index].children.length = 0; this.helper.rows.splice(index, 1); } public _onColumnRemoved(itemSpec: ItemSpec, index: number) { this.helper.columns[index].children.length = 0; this.helper.columns.splice(index, 1); } public _registerLayoutChild(child: View) { this.addToMap(child); } public _unregisterLayoutChild(child: View) { this.removeFromMap(child); } protected invalidate(): void { super.invalidate(); this.requestLayout(); } private getColumnIndex(view: View): number { return Math.max(0, Math.min(GridLayout.getColumn(view), this.columnsInternal.length - 1)); } private getRowIndex(view: View): number { return Math.max(0, Math.min(GridLayout.getRow(view), this.rowsInternal.length - 1)); } private getColumnSpan(view: View, columnIndex: number): number { return Math.max(1, Math.min(GridLayout.getColumnSpan(view), this.columnsInternal.length - columnIndex)); } private getRowSpan(view: View, rowIndex: number): number { return Math.max(1, Math.min(GridLayout.getRowSpan(view), this.rowsInternal.length - rowIndex)); } private getColumnSpec(view: View): ItemSpec { return this.columnsInternal[this.getColumnIndex(view)] || this.helper.singleColumn; } private getRowSpec(view: View): ItemSpec { return this.rowsInternal[this.getRowIndex(view)] || this.helper.singleRow; } private updateMeasureSpecs(child: View, measureSpec: MeasureSpecs): void { const column = this.getColumnSpec(child); const columnIndex = this.getColumnIndex(child); const columnSpan = this.getColumnSpan(child, columnIndex); const row = this.getRowSpec(child); const rowIndex = this.getRowIndex(child); const rowSpan = this.getRowSpan(child, rowIndex); measureSpec.setColumn(column); measureSpec.setColumnIndex(columnIndex); measureSpec.setColumnSpan(columnSpan); measureSpec.setRow(row); measureSpec.setRowIndex(rowIndex); measureSpec.setRowSpan(rowSpan); measureSpec.autoColumnsCount = 0; measureSpec.autoRowsCount = 0; measureSpec.measured = false; measureSpec.pixelHeight = 0; measureSpec.pixelWidth = 0; measureSpec.starColumnsCount = 0; measureSpec.starRowsCount = 0; } private addToMap(child: View): void { this.map.set(child, new MeasureSpecs(child)); } private removeFromMap(child: View): void { this.map.delete(child); } public onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void { super.onMeasure(widthMeasureSpec, heightMeasureSpec); let measureWidth = 0; let measureHeight = 0; const width = layout.getMeasureSpecSize(widthMeasureSpec); const widthMode = layout.getMeasureSpecMode(widthMeasureSpec); const height = layout.getMeasureSpecSize(heightMeasureSpec); const heightMode = layout.getMeasureSpecMode(heightMeasureSpec); const horizontalPaddingsAndMargins = this.effectivePaddingLeft + this.effectivePaddingRight + this.effectiveBorderLeftWidth + this.effectiveBorderRightWidth; const verticalPaddingsAndMargins = this.effectivePaddingTop + this.effectivePaddingBottom + this.effectiveBorderTopWidth + this.effectiveBorderBottomWidth; const infinityWidth = widthMode === layout.UNSPECIFIED; const infinityHeight = heightMode === layout.UNSPECIFIED; this.helper.width = Math.max(0, width - horizontalPaddingsAndMargins); this.helper.height = Math.max(0, height - verticalPaddingsAndMargins); this.helper.stretchedHorizontally = widthMode === layout.EXACTLY || (this.horizontalAlignment === 'stretch' && !infinityWidth); this.helper.stretchedVertically = heightMode === layout.EXACTLY || (this.verticalAlignment === 'stretch' && !infinityHeight); this.helper.setInfinityWidth(infinityWidth); this.helper.setInfinityHeight(infinityHeight); this.helper.clearMeasureSpecs(); this.helper.init(); this.eachLayoutChild((child, last) => { const measureSpecs = this.map.get(child); if (!measureSpecs) { return; } this.updateMeasureSpecs(child, measureSpecs); this.helper.addMeasureSpec(measureSpecs); }); this.helper.measure(); // Add in our padding measureWidth = this.helper.measuredWidth + horizontalPaddingsAndMargins; measureHeight = this.helper.measuredHeight + verticalPaddingsAndMargins; // Check against our minimum sizes measureWidth = Math.max(measureWidth, this.effectiveMinWidth); measureHeight = Math.max(measureHeight, this.effectiveMinHeight); const widthSizeAndState = View.resolveSizeAndState(measureWidth, width, widthMode, 0); const heightSizeAndState = View.resolveSizeAndState(measureHeight, height, heightMode, 0); this.setMeasuredDimension(widthSizeAndState, heightSizeAndState); } public onLayout(left: number, top: number, right: number, bottom: number): void { super.onLayout(left, top, right, bottom); const insets = this.getSafeAreaInsets(); const paddingLeft = this.effectiveBorderLeftWidth + this.effectivePaddingLeft + insets.left; const paddingTop = this.effectiveBorderTopWidth + this.effectivePaddingTop + insets.top; this.columnOffsets.length = 0; this.rowOffsets.length = 0; this.columnOffsets.push(paddingLeft); this.rowOffsets.push(paddingTop); let offset = this.columnOffsets[0]; let roundedOffset = paddingLeft; let roundedLength = 0; let actualLength = 0; for (let i = 0, size = this.helper.columns.length; i < size; i++) { const columnGroup = this.helper.columns[i]; offset += columnGroup.length; actualLength = offset - roundedOffset; roundedLength = Math.round(actualLength); columnGroup.rowOrColumn._actualLength = layout.round(layout.toDeviceIndependentPixels(roundedLength)); roundedOffset += roundedLength; this.columnOffsets.push(roundedOffset); } offset = this.rowOffsets[0]; roundedOffset = paddingTop; roundedLength = 0; actualLength = 0; for (let i = 0, size = this.helper.rows.length; i < size; i++) { const rowGroup = this.helper.rows[i]; offset += rowGroup.length; actualLength = offset - roundedOffset; roundedLength = Math.round(actualLength); rowGroup.rowOrColumn._actualLength = layout.round(layout.toDeviceIndependentPixels(roundedLength)); roundedOffset += roundedLength; this.rowOffsets.push(roundedOffset); } for (let i = 0, columns = this.helper.columns.length; i < columns; i++) { const columnGroup = this.helper.columns[i]; for (let j = 0, children = columnGroup.children.length; j < children; j++) { const measureSpec = columnGroup.children[j]; const childLeft = this.columnOffsets[measureSpec.getColumnIndex()]; const childRight = this.columnOffsets[measureSpec.getColumnIndex() + measureSpec.getColumnSpan()]; const childTop = this.rowOffsets[measureSpec.getRowIndex()]; const childBottom = this.rowOffsets[measureSpec.getRowIndex() + measureSpec.getRowSpan()]; // No need to include margins in the width, height View.layoutChild(this, measureSpec.child, childLeft, childTop, childRight, childBottom); } } } } class MeasureSpecs { private _columnSpan = 1; private _rowSpan = 1; public pixelWidth = 0; public pixelHeight = 0; public starColumnsCount = 0; public starRowsCount = 0; public autoColumnsCount = 0; public autoRowsCount = 0; public measured = false; public child: View; private column: ItemSpec; private row: ItemSpec; private columnIndex = 0; private rowIndex = 0; constructor(child: View) { this.child = child; } public getSpanned(): boolean { return this._columnSpan > 1 || this._rowSpan > 1; } public getIsStar(): boolean { return this.starRowsCount > 0 || this.starColumnsCount > 0; } public getColumnSpan(): number { return this._columnSpan; } public getRowSpan(): number { return this._rowSpan; } public setRowSpan(value: number): void { // cannot have zero rowSpan. this._rowSpan = Math.max(1, value); } public setColumnSpan(value: number): void { // cannot have zero colSpan. this._columnSpan = Math.max(1, value); } public getRowIndex(): number { return this.rowIndex; } public getColumnIndex(): number { return this.columnIndex; } public setRowIndex(value: number): void { this.rowIndex = value; } public setColumnIndex(value: number): void { this.columnIndex = value; } public getRow(): ItemSpec { return this.row; } public getColumn(): ItemSpec { return this.column; } public setRow(value: ItemSpec): void { this.row = value; } public setColumn(value: ItemSpec): void { this.column = value; } } class ItemGroup { public length = 0; public measuredCount = 0; public rowOrColumn: ItemSpec; public children: Array<MeasureSpecs> = new Array<MeasureSpecs>(); public measureToFix = 0; public currentMeasureToFixCount = 0; private infinityLength = false; constructor(spec: ItemSpec) { this.rowOrColumn = spec; } public setIsLengthInfinity(infinityLength: boolean): void { this.infinityLength = infinityLength; } public init(density): void { this.measuredCount = 0; this.currentMeasureToFixCount = 0; this.length = this.rowOrColumn.isAbsolute ? this.rowOrColumn.value * density : 0; } public getAllMeasured(): boolean { return this.measuredCount === this.children.length; } public getCanBeFixed(): boolean { return this.currentMeasureToFixCount === this.measureToFix; } public getIsAuto(): boolean { return this.rowOrColumn.isAuto || (this.rowOrColumn.isStar && this.infinityLength); } public getIsStar(): boolean { return this.rowOrColumn.isStar && !this.infinityLength; } public getIsAbsolute(): boolean { return this.rowOrColumn.isAbsolute; } } class MeasureHelper { singleRow: ItemSpec; singleColumn: ItemSpec; grid: GridLayout; infinity: number = layout.makeMeasureSpec(0, layout.UNSPECIFIED); rows: Array<ItemGroup> = new Array<ItemGroup>(); columns: Array<ItemGroup> = new Array<ItemGroup>(); width = 0; height = 0; stretchedHorizontally = false; stretchedVertically = false; infinityWidth = false; infinityHeight = false; private minColumnStarValue = 0; private maxColumnStarValue = 0; private minRowStarValue = 0; private maxRowStarValue = 0; measuredWidth = 0; measuredHeight = 0; private fakeRowAdded = false; private fakeColumnAdded = false; private singleRowGroup: ItemGroup; private singleColumnGroup: ItemGroup; constructor(grid: GridLayout) { this.grid = grid; this.singleRow = new ItemSpec(); this.singleColumn = new ItemSpec(); this.singleRowGroup = new ItemGroup(this.singleRow); this.singleColumnGroup = new ItemGroup(this.singleColumn); } public setInfinityWidth(value: boolean): void { this.infinityWidth = value; for (let i = 0, size = this.columns.length; i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; columnGroup.setIsLengthInfinity(value); } } public setInfinityHeight(value: boolean): void { this.infinityHeight = value; for (let i = 0, size = this.rows.length; i < size; i++) { const rowGroup: ItemGroup = this.rows[i]; rowGroup.setIsLengthInfinity(value); } } public addMeasureSpec(measureSpec: MeasureSpecs): void { // Get column stats let size = measureSpec.getColumnIndex() + measureSpec.getColumnSpan(); for (let i = measureSpec.getColumnIndex(); i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; if (columnGroup.getIsAuto()) { measureSpec.autoColumnsCount++; } else if (columnGroup.getIsStar()) { measureSpec.starColumnsCount += columnGroup.rowOrColumn.value; } else if (columnGroup.getIsAbsolute()) { measureSpec.pixelWidth += layout.toDevicePixels(columnGroup.rowOrColumn.value); } } if (measureSpec.autoColumnsCount > 0 && measureSpec.starColumnsCount === 0) { // Determine which auto columns are affected by this element for (let i = measureSpec.getColumnIndex(); i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; if (columnGroup.getIsAuto()) { columnGroup.measureToFix++; } } } // Get row stats size = measureSpec.getRowIndex() + measureSpec.getRowSpan(); for (let i = measureSpec.getRowIndex(); i < size; i++) { const rowGroup: ItemGroup = this.rows[i]; if (rowGroup.getIsAuto()) { measureSpec.autoRowsCount++; } else if (rowGroup.getIsStar()) { measureSpec.starRowsCount += rowGroup.rowOrColumn.value; } else if (rowGroup.getIsAbsolute()) { measureSpec.pixelHeight += layout.toDevicePixels(rowGroup.rowOrColumn.value); } } if (measureSpec.autoRowsCount > 0 && measureSpec.starRowsCount === 0) { // Determine which auto rows are affected by this element for (let i = measureSpec.getRowIndex(); i < size; i++) { const rowGroup: ItemGroup = this.rows[i]; if (rowGroup.getIsAuto()) { rowGroup.measureToFix++; } } } this.columns[measureSpec.getColumnIndex()].children.push(measureSpec); this.rows[measureSpec.getRowIndex()].children.push(measureSpec); } public clearMeasureSpecs(): void { for (let i = 0, size = this.columns.length; i < size; i++) { this.columns[i].children.length = 0; } for (let i = 0, size = this.rows.length; i < size; i++) { this.rows[i].children.length = 0; } } private static initList(list: Array<ItemGroup>): void { const density = layout.getDisplayDensity(); for (let i = 0, size = list.length; i < size; i++) { const item: ItemGroup = list[i]; item.init(density); } } init(): void { const rows = this.rows.length; if (rows === 0) { this.singleRowGroup.setIsLengthInfinity(this.infinityHeight); this.rows.push(this.singleRowGroup); this.fakeRowAdded = true; } else if (rows > 1 && this.fakeRowAdded) { this.rows.splice(0, 1); this.fakeRowAdded = false; } const cols = this.columns.length; if (cols === 0) { this.fakeColumnAdded = true; this.singleColumnGroup.setIsLengthInfinity(this.infinityWidth); this.columns.push(this.singleColumnGroup); } else if (cols > 1 && this.fakeColumnAdded) { this.columns.splice(0, 1); this.fakeColumnAdded = false; } MeasureHelper.initList(this.rows); MeasureHelper.initList(this.columns); this.minColumnStarValue = -1; this.minRowStarValue = -1; this.maxColumnStarValue = -1; this.maxRowStarValue = -1; } private itemMeasured(measureSpec: MeasureSpecs, isFakeMeasure: boolean): void { if (!isFakeMeasure) { this.columns[measureSpec.getColumnIndex()].measuredCount++; this.rows[measureSpec.getRowIndex()].measuredCount++; measureSpec.measured = true; } if (measureSpec.autoColumnsCount > 0 && measureSpec.starColumnsCount === 0) { const size = measureSpec.getColumnIndex() + measureSpec.getColumnSpan(); for (let i = measureSpec.getColumnIndex(); i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; if (columnGroup.getIsAuto()) { columnGroup.currentMeasureToFixCount++; } } } if (measureSpec.autoRowsCount > 0 && measureSpec.starRowsCount === 0) { const size = measureSpec.getRowIndex() + measureSpec.getRowSpan(); for (let i = measureSpec.getRowIndex(); i < size; i++) { const rowGroup: ItemGroup = this.rows[i]; if (rowGroup.getIsAuto()) { rowGroup.currentMeasureToFixCount++; } } } } private fixColumns(): void { let currentColumnWidth = 0; let columnStarCount = 0; const columnCount = this.columns.length; for (let i = 0; i < columnCount; i++) { const item: ItemGroup = this.columns[i]; if (item.rowOrColumn.isStar) { columnStarCount += item.rowOrColumn.value; } else { // Star columns are still zeros (not calculated). currentColumnWidth += item.length; } } const widthForStarColumns = Math.max(0, this.width - currentColumnWidth); this.maxColumnStarValue = columnStarCount > 0 ? widthForStarColumns / columnStarCount : 0; MeasureHelper.updateStarLength(this.columns, this.maxColumnStarValue); } private fixRows(): void { let currentRowHeight = 0; let rowStarCount = 0; const rowCount = this.rows.length; for (let i = 0; i < rowCount; i++) { const item: ItemGroup = this.rows[i]; if (item.rowOrColumn.isStar) { rowStarCount += item.rowOrColumn.value; } else { // Star rows are still zeros (not calculated). currentRowHeight += item.length; } } const heightForStarRows = Math.max(0, this.height - currentRowHeight); this.maxRowStarValue = rowStarCount > 0 ? heightForStarRows / rowStarCount : 0; MeasureHelper.updateStarLength(this.rows, this.maxRowStarValue); } private static updateStarLength(list: Array<ItemGroup>, starValue: number): void { let offset = 0; let roundedOffset = 0; for (let i = 0, rowCount = list.length; i < rowCount; i++) { const item = list[i]; if (item.getIsStar()) { offset += item.rowOrColumn.value * starValue; const actualLength = offset - roundedOffset; const roundedLength = Math.round(actualLength); item.length = roundedLength; roundedOffset += roundedLength; } } } private fakeMeasure(): void { // Fake measure - measure all elements that have star rows and auto columns - with infinity Width and infinity Height for (let i = 0, size = this.columns.length; i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; if (columnGroup.getAllMeasured()) { continue; } for (let j = 0, childrenCount = columnGroup.children.length; j < childrenCount; j++) { const measureSpec: MeasureSpecs = columnGroup.children[j]; if (measureSpec.starRowsCount > 0 && measureSpec.autoColumnsCount > 0 && measureSpec.starColumnsCount === 0) { this.measureChild(measureSpec, true); } } } } private measureFixedColumnsNoStarRows(): void { for (let i = 0, size = this.columns.length; i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; for (let j = 0, childrenCount = columnGroup.children.length; j < childrenCount; j++) { const measureSpec: MeasureSpecs = columnGroup.children[j]; if (measureSpec.starColumnsCount > 0 && measureSpec.starRowsCount === 0) { this.measureChildFixedColumns(measureSpec); } } } } private measureNoStarColumnsFixedRows(): void { for (let i = 0, size = this.columns.length; i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; for (let j = 0, childrenCount = columnGroup.children.length; j < childrenCount; j++) { const measureSpec: MeasureSpecs = columnGroup.children[j]; if (measureSpec.starRowsCount > 0 && measureSpec.starColumnsCount === 0) { this.measureChildFixedRows(measureSpec); } } } } private static canFix(list: Array<ItemGroup>): boolean { for (let i = 0, size = list.length; i < size; i++) { const item: ItemGroup = list[i]; if (!item.getCanBeFixed()) { return false; } } return true; } private static getMeasureLength(list: Array<ItemGroup>): number { let result = 0; for (let i = 0, size = list.length; i < size; i++) { const item: ItemGroup = list[i]; result += item.length; } return result; } public measure(): void { // Measure auto & pixel columns and rows (no spans). let size = this.columns.length; for (let i = 0; i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; for (let j = 0, childrenCount = columnGroup.children.length; j < childrenCount; j++) { const measureSpec: MeasureSpecs = columnGroup.children[j]; if (measureSpec.getIsStar() || measureSpec.getSpanned()) { continue; } this.measureChild(measureSpec, false); } } // Measure auto & pixel columns and rows (with spans). for (let i = 0; i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; for (let j = 0, childrenCount = columnGroup.children.length; j < childrenCount; j++) { const measureSpec = columnGroup.children[j]; if (measureSpec.getIsStar() || !measureSpec.getSpanned()) { continue; } this.measureChild(measureSpec, false); } } // try fix stars! const fixColumns: boolean = MeasureHelper.canFix(this.columns); const fixRows: boolean = MeasureHelper.canFix(this.rows); if (fixColumns) { this.fixColumns(); } if (fixRows) { this.fixRows(); } if (!fixColumns && !fixRows) { // Fake measure - measure all elements that have star rows and auto columns - with infinity Width and infinity Height // should be able to fix rows after that this.fakeMeasure(); this.fixColumns(); // Measure all elements that have star columns(already fixed), but no stars at the rows this.measureFixedColumnsNoStarRows(); this.fixRows(); } else if (fixColumns && !fixRows) { // Measure all elements that have star columns(already fixed) but no stars at the rows this.measureFixedColumnsNoStarRows(); // Then this.fixRows(); } else if (!fixColumns && fixRows) { // Measure all elements that have star rows(already fixed) but no star at the columns this.measureNoStarColumnsFixedRows(); // Then this.fixColumns(); } // Rows and columns are fixed here - measure remaining elements size = this.columns.length; for (let i = 0; i < size; i++) { const columnGroup: ItemGroup = this.columns[i]; for (let j = 0, childCount = columnGroup.children.length; j < childCount; j++) { const measureSpec: MeasureSpecs = columnGroup.children[j]; if (!measureSpec.measured) { this.measureChildFixedColumnsAndRows(measureSpec); } } } // If we are not stretched and minColumnStarValue is less than maxColumnStarValue // we need to reduce the width of star columns. if (!this.stretchedHorizontally && this.minColumnStarValue !== -1 && this.minColumnStarValue < this.maxColumnStarValue) { MeasureHelper.updateStarLength(this.columns, this.minColumnStarValue); } // If we are not stretched and minRowStarValue is less than maxRowStarValue // we need to reduce the height of star maxRowStarValue. if (!this.stretchedVertically && this.minRowStarValue !== -1 && this.minRowStarValue < this.maxRowStarValue) { MeasureHelper.updateStarLength(this.rows, this.minRowStarValue); } this.measuredWidth = MeasureHelper.getMeasureLength(this.columns); this.measuredHeight = MeasureHelper.getMeasureLength(this.rows); } private measureChild(measureSpec: MeasureSpecs, isFakeMeasure: boolean): void { const widthMeasureSpec = measureSpec.autoColumnsCount > 0 ? this.infinity : layout.makeMeasureSpec(measureSpec.pixelWidth, layout.EXACTLY); const heightMeasureSpec = isFakeMeasure || measureSpec.autoRowsCount > 0 ? this.infinity : layout.makeMeasureSpec(measureSpec.pixelHeight, layout.EXACTLY); const childSize = View.measureChild(this.grid, measureSpec.child, widthMeasureSpec, heightMeasureSpec); const childMeasuredWidth: number = childSize.measuredWidth; const childMeasuredHeight: number = childSize.measuredHeight; const columnSpanEnd: number = measureSpec.getColumnIndex() + measureSpec.getColumnSpan(); const rowSpanEnd: number = measureSpec.getRowIndex() + measureSpec.getRowSpan(); if (measureSpec.autoColumnsCount > 0) { let remainingSpace = childMeasuredWidth; for (let i = measureSpec.getColumnIndex(); i < columnSpanEnd; i++) { const columnGroup: ItemGroup = this.columns[i]; remainingSpace -= columnGroup.length; } if (remainingSpace > 0) { const growSize = remainingSpace / measureSpec.autoColumnsCount; for (let i = measureSpec.getColumnIndex(); i < columnSpanEnd; i++) { const columnGroup: ItemGroup = this.columns[i]; if (columnGroup.getIsAuto()) { columnGroup.length += growSize; } } } } if (!isFakeMeasure && measureSpec.autoRowsCount > 0) { let remainingSpace: number = childMeasuredHeight; for (let i = measureSpec.getRowIndex(); i < rowSpanEnd; i++) { const rowGroup: ItemGroup = this.rows[i]; remainingSpace -= rowGroup.length; } if (remainingSpace > 0) { const growSize = remainingSpace / measureSpec.autoRowsCount; for (let i = measureSpec.getRowIndex(); i < rowSpanEnd; i++) { const rowGroup: ItemGroup = this.rows[i]; if (rowGroup.getIsAuto()) { rowGroup.length += growSize; } } } } this.itemMeasured(measureSpec, isFakeMeasure); } private measureChildFixedColumns(measureSpec: MeasureSpecs): void { const columnIndex = measureSpec.getColumnIndex(); const columnSpanEnd = columnIndex + measureSpec.getColumnSpan(); const rowIndex = measureSpec.getRowIndex(); const rowSpanEnd = rowIndex + measureSpec.getRowSpan(); let measureWidth = 0; let growSize = 0; for (let i = columnIndex; i < columnSpanEnd; i++) { const columnGroup: ItemGroup = this.columns[i]; measureWidth += columnGroup.length; } const widthMeasureSpec = layout.makeMeasureSpec(measureWidth, this.stretchedHorizontally ? layout.EXACTLY : layout.AT_MOST); const heightMeasureSpec = measureSpec.autoRowsCount > 0 ? this.infinity : layout.makeMeasureSpec(measureSpec.pixelHeight, layout.EXACTLY); const childSize = View.measureChild(this.grid, measureSpec.child, widthMeasureSpec, heightMeasureSpec); const childMeasuredWidth = childSize.measuredWidth; const childMeasuredHeight = childSize.measuredHeight; this.updateMinColumnStarValueIfNeeded(measureSpec, childMeasuredWidth); // Distribute height over auto rows if (measureSpec.autoRowsCount > 0) { let remainingSpace = childMeasuredHeight; for (let i = rowIndex; i < rowSpanEnd; i++) { const rowGroup: ItemGroup = this.rows[i]; remainingSpace -= rowGroup.length; } if (remainingSpace > 0) { growSize = remainingSpace / measureSpec.autoRowsCount; for (let i = rowIndex; i < rowSpanEnd; i++) { const rowGroup: ItemGroup = this.rows[i]; if (rowGroup.getIsAuto()) { rowGroup.length += growSize; } } } } this.itemMeasured(measureSpec, false); } private measureChildFixedRows(measureSpec: MeasureSpecs): void { const columnIndex = measureSpec.getColumnIndex(); const columnSpanEnd = columnIndex + measureSpec.getColumnSpan(); const rowIndex = measureSpec.getRowIndex(); const rowSpanEnd = rowIndex + measureSpec.getRowSpan(); let measureHeight = 0; for (let i = rowIndex; i < rowSpanEnd; i++) { const rowGroup: ItemGroup = this.rows[i]; measureHeight += rowGroup.length; } const widthMeasureSpec = measureSpec.autoColumnsCount > 0 ? this.infinity : layout.makeMeasureSpec(measureSpec.pixelWidth, layout.EXACTLY); const heightMeasureSpec = layout.makeMeasureSpec(measureHeight, this.stretchedVertically ? layout.EXACTLY : layout.AT_MOST); const childSize = View.measureChild(this.grid, measureSpec.child, widthMeasureSpec, heightMeasureSpec); const childMeasuredWidth = childSize.measuredWidth; const childMeasuredHeight = childSize.measuredHeight; let remainingSpace = 0; let growSize = 0; // Distribute width over auto columns if (measureSpec.autoColumnsCount > 0) { remainingSpace = childMeasuredWidth; for (let i = columnIndex; i < columnSpanEnd; i++) { const columnGroup: ItemGroup = this.columns[i]; remainingSpace -= columnGroup.length; } if (remainingSpace > 0) { growSize = remainingSpace / measureSpec.autoColumnsCount; for (let i = columnIndex; i < columnSpanEnd; i++) { const columnGroup: ItemGroup = this.columns[i]; if (columnGroup.getIsAuto()) { columnGroup.length += growSize; } } } } this.updateMinRowStarValueIfNeeded(measureSpec, childMeasuredHeight); this.itemMeasured(measureSpec, false); } private measureChildFixedColumnsAndRows(measureSpec: MeasureSpecs): void { const columnIndex = measureSpec.getColumnIndex(); const columnSpanEnd = columnIndex + measureSpec.getColumnSpan(); const rowIndex = measureSpec.getRowIndex(); const rowSpanEnd = rowIndex + measureSpec.getRowSpan(); let measureWidth = 0; for (let i = columnIndex; i < columnSpanEnd; i++) { const columnGroup: ItemGroup = this.columns[i]; measureWidth += columnGroup.length; } let measureHeight = 0; for (let i = rowIndex; i < rowSpanEnd; i++) { const rowGroup: ItemGroup = this.rows[i]; measureHeight += rowGroup.length; } // if (have stars) & (not stretch) - at most const widthMeasureSpec = layout.makeMeasureSpec(measureWidth, measureSpec.starColumnsCount > 0 && !this.stretchedHorizontally ? layout.AT_MOST : layout.EXACTLY); const heightMeasureSpec = layout.makeMeasureSpec(measureHeight, measureSpec.starRowsCount > 0 && !this.stretchedVertically ? layout.AT_MOST : layout.EXACTLY); const childSize = View.measureChild(this.grid, measureSpec.child, widthMeasureSpec, heightMeasureSpec); const childMeasuredWidth = childSize.measuredWidth; const childMeasuredHeight = childSize.measuredHeight; this.updateMinColumnStarValueIfNeeded(measureSpec, childMeasuredWidth); this.updateMinRowStarValueIfNeeded(measureSpec, childMeasuredHeight); this.itemMeasured(measureSpec, false); } private updateMinRowStarValueIfNeeded(measureSpec: MeasureSpecs, childMeasuredHeight: number): void { if (!this.stretchedVertically && measureSpec.starRowsCount > 0) { let remainingSpace = childMeasuredHeight; const rowIndex = measureSpec.getRowIndex(); const rowSpanEnd = rowIndex + measureSpec.getRowSpan(); for (let i = rowIndex; i < rowSpanEnd; i++) { const rowGroup = this.rows[i]; if (!rowGroup.getIsStar()) { remainingSpace -= rowGroup.length; } } if (remainingSpace > 0) { this.minRowStarValue = Math.max(remainingSpace / measureSpec.starRowsCount, this.minRowStarValue); } } } private updateMinColumnStarValueIfNeeded(measureSpec: MeasureSpecs, childMeasuredWidth: number): void { // When not stretched star columns are not fixed so we may grow them here // if there is an element that spans on multiple columns if (!this.stretchedHorizontally && measureSpec.starColumnsCount > 0) { let remainingSpace = childMeasuredWidth; const columnIndex = measureSpec.getColumnIndex(); const columnSpanEnd = columnIndex + measureSpec.getColumnSpan(); for (let i = columnIndex; i < columnSpanEnd; i++) { const columnGroup = this.columns[i]; if (!columnGroup.getIsStar()) { remainingSpace -= columnGroup.length; } } if (remainingSpace > 0) { this.minColumnStarValue = Math.max(remainingSpace / measureSpec.starColumnsCount, this.minColumnStarValue); } } } }
the_stack
import { compareDates, DateInfoBase, DateInfoBase1, DateStr, fillTo, getMonthByStep, getMonthLen, parseDate, parseTime, TimeInfo, TimeStr, } from '@livelybone/date-generator' export const dateReg = /^((\d{4})-?(\d{1,2})?-?(\d{1,2})?)/ export const timeReg = /^((\d{1,2}):?(\d{1,2})?:?(\d{1,2})?)/ export const AllTypes = ['year', 'month', 'date', 'time'] as const export const AllTimeTypes = ['hour', 'minute', 'second'] as const export type TAllTypes = typeof AllTypes extends Readonly<(infer A)[]> ? A : never export type TAllTimeTypes = typeof AllTimeTypes extends Readonly<(infer A)[]> ? A : never export function sliceUtilEqual<T extends any>(arr: T[], val: T) { const index = Object.keys(arr).find(i => arr[+i] === val) if (!index) return arr return arr.slice(0, +index + 1) } // flag: // -1 - 如果 d1 小于等于 d2,返回 true // 1 - 如果 d1 大于等于 d2,返回 true // 0 - 如果 d1 等于 d2,返回 true export function dateCompare< T extends Partial<DateInfoBase1>, U extends Partial<DateInfoBase1> >( date: T | DateStr | undefined | null, targetDate: U | DateStr | undefined | null, flag = 1, type: Exclude<TAllTypes, 'time'> = 'date', ) { const $date = typeof date === 'string' ? parseDate(date) : date ? { ...date } : undefined const $targetDate = typeof targetDate === 'string' ? parseDate(targetDate) : targetDate ? { ...targetDate } : undefined if (!$date) return false if (!$targetDate) return true if (type === 'year') { $date.month = '01' $date.date = '01' $targetDate.month = '01' $targetDate.date = '01' } else if (type === 'month') { $date.date = '01' $targetDate.date = '01' } const compare = compareDates($date as any, $targetDate as any) return flag === 0 ? compare === 0 : compare * flag >= 0 } // flag: // -1 - 如果 t1 小于等于 t2,返回 true // 1 - 如果 t1 大于等于 t2,返回 true // 0 - 如果 t1 等于 t2,返回 true export function timeCompare( time?: TimeInfo | string, targetTime?: TimeInfo | string, flag = 1, type: TAllTimeTypes = 'second', ) { const $time = typeof time === 'string' ? parseTime(time) : time ? { ...time } : undefined const $targetTime = typeof targetTime === 'string' ? parseTime(targetTime) : targetTime ? { ...targetTime } : undefined if (!$time) return false if (!$targetTime) return true if (type === 'hour') { $time.minute = '00' $time.second = '00' $targetTime.minute = '00' $targetTime.second = '00' } else if (type === 'minute') { $time.second = '00' $targetTime.second = '00' } const get = (t: TimeInfo) => +`${fillTo(2, t.hour)}${fillTo(2, t.minute)}${fillTo(2, t.second)}` const compare = get($time) - get($targetTime) return flag === 0 ? compare === 0 : compare * flag >= 0 } export function datetimeCompare( datetime: (DateInfoBase & Partial<TimeInfo>) | undefined, targetDatetime: (DateInfoBase & TimeInfo) | undefined, flag = 1, type: TAllTimeTypes = 'second', ) { if (!datetime) return false if (!targetDatetime) return true if (flag === 0) return ( dateCompare(datetime, targetDatetime, flag) && (datetime.hour === undefined || timeCompare(datetime as TimeInfo, targetDatetime, flag)) ) const compare = dateCompare(datetime, targetDatetime, flag) if (!compare) return false const compareReverse = dateCompare(datetime, targetDatetime, -flag) if (compareReverse) return ( datetime.hour === undefined || timeCompare(datetime as TimeInfo, targetDatetime, flag, type) ) return true } function $fillTo(width: number, num?: string | number) { return num !== undefined ? fillTo(width, num) : '' } export function getTenYears(val: DateInfoBase) { if (!val) return '' const tenYear = Math.floor(+val.year / 10 - 0.5) return `${tenYear * 10 + 1} - ${(tenYear + 1) * 10}` } export function createEmptyTimeObj() { return { year: '', month: '', date: '', hour: '', minute: '', second: '' } } export function createNowTimeObj() { const now = new Date() return { year: now.getFullYear(), month: now.getMonth() + 1, date: now.getDate(), hour: now.getHours(), minute: now.getMinutes(), second: now.getSeconds(), } } export function formatDateObj(val: DateInfoBase1) { return { year: (val.year && fillTo(4, val.year)) || '', month: (val.month && fillTo(2, val.month)) || '', date: (val.date && fillTo(2, val.date)) || '', } } export function formatTimeObj( val: { [key in keyof TimeInfo]: number | string }, ) { return { hour: (val.hour && fillTo(2, val.hour)) || '', minute: (val.minute && fillTo(2, val.minute)) || '', second: (val.second && fillTo(2, val.second)) || '', } } export function formatDate(d: DateInfoBase, type: TAllTypes = 'date') { if (!d) return '' const arr = [] const year = d.year && $fillTo(4, d.year) if (year) { arr.push(year) const month = d.month && $fillTo(2, d.month) if (month) { arr.push(month) const date = d.date && $fillTo(2, d.date) if (date) arr.push(date) } } return arr.slice(0, sliceUtilEqual(AllTypes as any, type).length).join('-') } export function formatTime(t: TimeInfo, type: TAllTimeTypes = 'second') { if (!t) return '' const arr = [] const hour = t.hour && $fillTo(2, t.hour) if (hour) { arr.push(hour) const minute = t.minute && $fillTo(2, t.minute) if (minute) { arr.push(minute) const second = t.second && $fillTo(2, t.second) if (second) arr.push(second) } } return arr .slice(0, sliceUtilEqual(AllTimeTypes as any, type).length) .join(':') } function mergePropExceptEmpty(o1: any, o2: any) { return Object.keys({ ...o1, ...o2 }).reduce( (pre, k) => ({ ...pre, [k]: (o2 && o2[k]) || (o1 && o1[k]) }), o1, ) } export function dealDateLimit( min: DateStr | undefined, max: DateStr | undefined, ) { const error: string[] = [] const minDate = (min && parseDate(min)) || undefined if (min && !minDate) error.push(`Prop min(${min}) is invalid`) const maxDate = (max && parseDate(max)) || undefined if (max && !maxDate) error.push(`Prop max(${max}) is invalid`) return { minDate: formatDateObj( mergePropExceptEmpty({ year: '0000', month: '01', date: '01' }, minDate), ), maxDate: formatDateObj( mergePropExceptEmpty({ year: '9999', month: '12', date: '31' }, maxDate), ), error: error.join(';'), } } export function dealTimeLimit( min: TimeStr | undefined, max: TimeStr | undefined, ) { const error: string[] = [] const minTime = (min && parseTime(min)) || undefined if (min && !minTime) error.push(`Prop min(${min}) is invalid`) const maxTime = (max && parseTime(max)) || undefined if (max && !maxTime) error.push(`Prop max(${max}) is invalid`) return { minTime: formatTimeObj( mergePropExceptEmpty({ hour: '00', minute: '00', second: '00' }, minTime), ), maxTime: formatTimeObj( mergePropExceptEmpty({ hour: '23', minute: '59', second: '59' }, maxTime), ), error: error.join(';'), } } export function dealDatetimeLimit( min: string | undefined, max: string | undefined, selectedDate?: DateInfoBase, ) { const minArr = (min || '').trim().split(/\s+/) const maxArr = (max || '').trim().split(/\s+/) const { minDate, maxDate } = dealDateLimit(minArr[0], maxArr[0]) const compare = { toMin: minDate && selectedDate ? compareDates(selectedDate, minDate) : 1, toMax: maxDate && selectedDate ? compareDates(selectedDate, maxDate) : -1, } const { minTime: $minTime, maxTime: $maxTime } = dealTimeLimit( minArr[1], maxArr[1], ) const error: string[] = [] const minDatetime = minDate ? { ...minDate, ...$minTime } : undefined if (min && !minDatetime) error.push(`Prop min(${min}) is invalid`) const maxDatetime = maxDate ? { ...maxDate, ...$maxTime } : undefined if (max && !maxDatetime) error.push(`Prop min(${max}) is invalid`) const minTime = (() => { if (compare.toMin === 0) return $minTime if (compare.toMin < 0) return { hour: '23', minute: '59', second: '59' } return { hour: '00', minute: '00', second: '00' } })() const maxTime = (() => { if (compare.toMax === 0) return $maxTime if (compare.toMax > 0) return { hour: '00', minute: '00', second: '00' } return { hour: '23', minute: '59', second: '59' } })() return { minArr, maxArr, minDate, maxDate, minTime, maxTime, minDatetime, maxDatetime, error: error.join(';'), } } export function getNextMonthFirstDate( dateInfo?: DateInfoBase1, ): typeof dateInfo extends undefined ? undefined : DateInfoBase { if (!dateInfo) return undefined as any const month = getMonthByStep(dateInfo, 1) return { ...month, date: fillTo(2, 1) } } export function getPrevMonthLastDate( dateInfo?: DateInfoBase1, ): typeof dateInfo extends undefined ? undefined : DateInfoBase { if (!dateInfo) return undefined as any const month = getMonthByStep(dateInfo, -1) return { ...month, date: fillTo(2, getMonthLen(month.year, month.month)) } } export function getCurrMonthLastDate( dateInfo?: DateInfoBase1, ): typeof dateInfo extends undefined ? undefined : DateInfoBase { if (!dateInfo) return undefined as any return formatDateObj({ ...dateInfo, date: fillTo(2, getMonthLen(dateInfo.year, dateInfo.month)), }) } export function getPrevYearLastDate(year: string | number) { if (!year) return undefined return { year: fillTo(4, +year - 1), month: '12', date: '31' } } export function getCurrYearLastDate(year: string | number) { if (!year) return undefined return { year: fillTo(4, +year), month: '12', date: '31' } } export function getPrevTenYearLastDate(year: string | number) { if (!year) return undefined return { year: fillTo(4, (Math.ceil(+year / 10) - 1) * 10), month: '12', date: '31', } } export function getCurrTenYearLastDate(year: string | number) { if (!year) return undefined return { year: fillTo(4, Math.ceil(+year / 10) * 10), month: '12', date: '31', } } export function getNextYearFirstDate(year: string | number) { if (!year) return undefined return { year: fillTo(4, +year + 1), month: '01', date: '01' } } export function getNextTenYearFirstDate(year: string | number) { if (!year) return undefined return { year: fillTo(4, Math.ceil(+year / 10) * 10 + 1), month: '01', date: '01', } } export function getFirstMaxDate( val: DateInfoBase1, type: Exclude<TAllTypes, 'time'> = 'date', ) { if (!val) return undefined if (type === 'year') return getPrevTenYearLastDate(val.year) if (type === 'month') return getPrevYearLastDate(val.year) return getPrevMonthLastDate(val) } export function getLastMinDate( val: DateInfoBase1, type: Exclude<TAllTypes, 'time'> = 'date', ) { if (!val) return undefined if (type === 'year') return getNextTenYearFirstDate(val.year) if (type === 'month') return getNextYearFirstDate(val.year) return getNextMonthFirstDate(val) } export function dateValidator( val?: string | DateInfoBase1, type: Exclude<TAllTypes, 'time'> = 'date', min: any = '', max: any = '', ) { if (!val) return '' const date = typeof val === 'string' ? parseDate(val) : val const checkProps = sliceUtilEqual(AllTypes as any, type) if (!date || !checkProps.every(k => date[k])) return `Value(${val}) is invalid` if ( !( (!min || dateCompare(date, min, 1, type)) && (!max || dateCompare(date, max, -1, type)) ) ) { return `Value${val} is out of range` } return '' } export function timeValidator( val?: string | TimeInfo, type: TAllTimeTypes = 'second', min: any = '', max: any = '', ) { if (!val) return '' const time = typeof val === 'string' ? parseTime(val) : val const checkProps = sliceUtilEqual(AllTimeTypes as any, type) if (!time || !checkProps.every(k => time[k])) return `Value(${val}) is invalid` if ( !( (!min || timeCompare(time, min, 1, type)) && (!max || timeCompare(time, max, -1, type)) ) ) { return `Value${val} is out of range` } return '' } export function parseDatetime(val: string) { const $val = val || '' if (!$val.trim()) return null const arr = $val.trim().split(/\s+/) return { ...parseDate(arr[0]), ...parseTime(arr[1]), } } export function datetimeValidator( val?: any, type: TAllTimeTypes = 'second', min: any = '', max: any = '', ) { if (!val) return '' const time = typeof val === 'string' ? parseDatetime(val) : val const checkProps = AllTypes.slice(0, 3).concat( sliceUtilEqual(AllTimeTypes as any, type) as any[], ) if (!time || !checkProps.every(k => time[k])) return `Value(${val}) is invalid` if ( !( (!min || datetimeCompare(time, min, 1, type)) && (!max || datetimeCompare(time, max, -1, type)) ) ) { return `Value${val} is out of range` } return '' } export function isInSameTenYear(v1: DateInfoBase1, v2: DateInfoBase1) { return dateCompare(v1, v2, 0, 'year') } export function isInSameYear(v1: DateInfoBase1, v2: DateInfoBase1) { return dateCompare(v1, v2, 0, 'year') } export function isInSameMonth(v1: DateInfoBase1, v2: DateInfoBase1) { return dateCompare(v1, v2, 0, 'month') } export function isInSamePage( [v1, v2]: [DateInfoBase1, DateInfoBase1], type?: Exclude<TAllTypes, 'time'>, ) { if (type === 'year') return isInSameTenYear(v1, v2) if (type === 'month') return isInSameYear(v1, v2) return isInSameMonth(v1, v2) } export function formatDatetime(val: any, type?: TAllTimeTypes) { let str = '' const d = formatDate(val) str += d if (!str) return '' const t = formatTime(val, type) return t ? `${str} ${t}` : '' }
the_stack
import type { Keybinding } from '../public/options'; export const DEFAULT_KEYBINDINGS: Keybinding[] = [ { key: 'left', command: 'moveToPreviousChar' }, { key: 'right', command: 'moveToNextChar' }, { key: 'up', command: 'moveUp' }, { key: 'down', command: 'moveDown' }, { key: 'shift+[ArrowLeft]', command: 'extendSelectionBackward' }, { key: 'shift+[ArrowRight]', command: 'extendSelectionForward' }, { key: 'shift+[ArrowUp]', command: 'extendSelectionUpward' }, { key: 'shift+[ArrowDown]', command: 'extendSelectionDownward' }, { key: '[Backspace]', command: 'deleteBackward' }, { key: 'alt+[Delete]', command: 'deleteBackward' }, { key: '[Delete]', command: 'deleteForward' }, { key: 'alt+[Backspace]', command: 'deleteForward' }, { key: 'alt+[ArrowLeft]', command: 'moveToPreviousWord' }, { key: 'alt+[ArrowRight]', command: 'moveToNextWord' }, { key: 'shift+alt+[ArrowLeft]', command: 'extendToPreviousWord' }, { key: 'shift+alt+[ArrowRight]', command: 'extendToNextWord' }, { key: 'ctrl+[ArrowLeft]', command: 'moveToGroupStart' }, { key: 'ctrl+[ArrowRight]', command: 'moveToGroupEnd' }, { key: 'shift+ctrl+[ArrowLeft]', command: 'extendToGroupStart' }, { key: 'shift+ctrl+[ArrowRight]', command: 'extendToGroupEnd' }, { key: '[Space]', ifMode: 'math', command: 'moveAfterParent' }, { key: 'shift+[Space]', ifMode: 'math', command: 'moveBeforeParent' }, { key: '[Home]', command: 'moveToMathFieldStart' }, { key: 'cmd+[ArrowLeft]', command: 'moveToMathFieldStart' }, { key: 'shift+[Home]', command: 'extendToMathFieldStart' }, { key: 'shift+cmd+[ArrowLeft]', command: 'extendToMathFieldStart' }, { key: '[End]', command: 'moveToMathFieldEnd' }, { key: 'cmd+[ArrowRight]', command: 'moveToMathFieldEnd' }, { key: 'shift+[End]', command: 'extendToMathFieldEnd' }, { key: 'shift+cmd+[ArrowRight]', command: 'extendToMathFieldEnd' }, { key: '[Pageup]', command: 'moveToGroupStart' }, { key: '[Pagedown]', command: 'moveToGroupEnd' }, { key: '[Tab]', ifMode: 'math', command: 'moveToNextPlaceholder' }, { key: 'shift+[Tab]', ifMode: 'math', command: 'moveToPreviousPlaceholder', }, { key: '[Tab]', ifMode: 'text', command: 'moveToNextPlaceholder' }, { key: 'shift+[Tab]', ifMode: 'text', command: 'moveToPreviousPlaceholder', }, { key: '[Escape]', ifMode: 'math', command: ['switchMode', 'latex'] }, { key: '[Escape]', ifMode: 'text', command: ['switchMode', 'latex'] }, { key: '\\', ifMode: 'math', command: ['switchMode', 'latex', '\\'], }, // { key: '[Backslash]', ifMode: 'math', command: ['switchMode', 'latex'] }, { key: '[IntlBackslash]', ifMode: 'math', command: ['switchMode', 'latex', '\\'], }, // On UK QWERTY keyboards { key: '[Escape]', ifMode: 'latex', command: ['complete', 'complete', { selectItem: 'true' }], }, // Accept the entry (without the suggestion) and select { key: '[Tab]', ifMode: 'latex', command: ['complete', 'accept-suggestion'], }, // Complete the suggestion { key: '[Return]', ifMode: 'latex', command: 'complete' }, { key: '[Enter]', ifMode: 'latex', command: 'complete' }, { key: 'shift+[Escape]', ifMode: 'latex', command: ['complete', 'reject'], }, // Some keyboards can't generate // this combination, for example in 60% keyboards it is mapped to ~ { key: '[ArrowDown]', ifMode: 'latex', command: 'nextSuggestion' }, // { key: 'ios:command:[Tab]', ifMode: 'latex',command: 'nextSuggestion' }, { key: '[ArrowUp]', ifMode: 'latex', command: 'previousSuggestion' }, { key: 'ctrl+a', ifPlatform: '!macos', command: 'selectAll' }, { key: 'cmd+a', command: 'selectAll' }, // Rare keys on some extended keyboards { key: '[Cut]', command: 'cutToClipboard' }, { key: '[Copy]', command: 'copyToClipboard' }, { key: '[Paste]', command: 'pasteFromClipboard' }, { key: '[Clear]', command: 'deleteBackward' }, { key: 'ctrl+z', ifPlatform: '!macos', command: 'undo' }, { key: 'cmd+z', command: 'undo' }, { key: '[Undo]', command: 'undo' }, { key: 'ctrl+y', ifPlatform: '!macos', command: 'redo' }, // ARIA recommendation { key: 'shift+cmd+y', command: 'redo' }, { key: 'shift+ctrl+z', ifPlatform: '!macos', command: 'redo' }, { key: 'shift+cmd+z', command: 'redo' }, { key: '[Redo]', command: 'redo' }, { key: '[EraseEof]', command: 'deleteToGroupEnd' }, // EMACS/MACOS BINDINGS { key: 'ctrl+b', ifPlatform: 'macos', command: 'moveToPreviousChar' }, { key: 'ctrl+f', ifPlatform: 'macos', command: 'moveToNextChar' }, { key: 'ctrl+p', ifPlatform: 'macos', command: 'moveUp' }, { key: 'ctrl+n', ifPlatform: 'macos', command: 'moveDown' }, { key: 'ctrl+a', ifPlatform: 'macos', command: 'moveToMathFieldStart' }, { key: 'ctrl+e', ifPlatform: 'macos', command: 'moveToMathFieldEnd' }, { key: 'shift+ctrl+b', ifPlatform: 'macos', command: 'extendSelectionBackward', }, { key: 'shift+ctrl+f', ifPlatform: 'macos', command: 'extendSelectionForward', }, { key: 'shift+ctrl+p', ifPlatform: 'macos', command: 'extendSelectionUpward', }, { key: 'shift+ctrl+n', ifPlatform: 'macos', command: 'extendSelectionDownward', }, { key: 'shift+ctrl+a', ifPlatform: 'macos', command: 'extendToMathFieldStart', }, { key: 'shift+ctrl+e', ifPlatform: 'macos', command: 'extendToMathFieldEnd', }, { key: 'alt+ctrl+b', ifPlatform: 'macos', command: 'moveToPreviousWord' }, { key: 'alt+ctrl+f', ifPlatform: 'macos', command: 'moveToNextWord' }, { key: 'shift+alt+ctrl+b', ifPlatform: 'macos', command: 'extendToPreviousWord', }, { key: 'shift+alt+ctrl+f', ifPlatform: 'macos', command: 'extendToNextWord', }, { key: 'ctrl+h', ifPlatform: 'macos', command: 'deleteBackward' }, { key: 'ctrl+d', ifPlatform: 'macos', command: 'deleteForward' }, { key: 'ctrl+l', ifPlatform: 'macos', command: 'scrollIntoView' }, // { key: 'ctrl+t', ifPlatform: 'macos', command: 'transpose' }, // WOLFRAM MATHEMATICA BINDINGS { key: 'ctrl+[Digit2]', ifMode: 'math', command: ['insert', '\\sqrt{#0}'], }, { key: 'ctrl+[Digit5]', ifMode: 'math', command: 'moveToOpposite' }, { key: 'ctrl+[Digit6]', ifMode: 'math', command: 'moveToSuperscript' }, { key: 'ctrl+[Return]', ifMode: 'math', command: 'addRowAfter' }, { key: 'ctrl+[Enter]', ifMode: 'math', command: 'addRowAfter' }, { key: 'cmd+[Return]', ifMode: 'math', command: 'addRowAfter' }, { key: 'cmd+[Enter]', ifMode: 'math', command: 'addRowAfter' }, // Excel keybindings: // shift+space: select entire row, ctrl+space: select an entire column // shift+ctrl++ or ctrl+numpad+ // ctrl+- to delete a row or columns // MATHLIVE BINDINGS // { key: 'alt+a', command: ['insert', '\\theta'] }, { key: 'alt+p', ifMode: 'math', command: ['insert', '\\pi'] }, { key: 'alt+v', ifMode: 'math', command: ['insert', '\\sqrt{#0}'] }, { key: 'alt+w', ifMode: 'math', command: ['insert', '\\sum_{i=#?}^{#?}'], }, { key: 'alt+b', command: ['insert', '\\int_{#?}^{#?}'] }, { key: 'alt+u', ifMode: 'math', command: ['insert', '\\cup'] }, { key: 'alt+n', ifMode: 'math', command: ['insert', '\\cap'] }, { key: 'alt+o', ifMode: 'math', command: ['insert', '\\emptyset'] }, { key: 'alt+d', ifMode: 'math', command: ['insert', '\\differentialD'], }, { key: 'shift+alt+o', ifMode: 'math', command: ['insert', '\\varnothing'], }, { key: 'shift+alt+d', ifMode: 'math', command: ['insert', '\\partial'], }, { key: 'shift+alt+p', ifMode: 'math', command: ['insert', '\\prod_{i=#?}^{#?}'], }, { key: 'shift+alt+u', ifMode: 'math', command: ['insert', '\\bigcup'] }, { key: 'shift+alt+n', ifMode: 'math', command: ['insert', '\\bigcap'] }, { key: 'shift+alt+a', ifMode: 'math', command: ['insert', '\\forall'] }, { key: 'shift+alt+e', ifMode: 'math', command: ['insert', '\\exists'] }, { key: 'alt+[Backslash]', ifMode: 'math', command: ['insert', '\\backslash'], }, // "|" key} override command mode { key: '[NumpadDivide]', ifMode: 'math', command: ['insert', '\\frac{#@}{#?}'], }, // ?? { key: 'alt+[NumpadDivide]', ifMode: 'math', command: ['insert', '\\frac{#?}{#@}'], }, // ?? // Accessibility { key: 'shift+alt+k', command: 'toggleKeystrokeCaption' }, { key: 'alt+[Space]', command: 'toggleVirtualKeyboard' }, // Note: On Mac OS (as of 10.12), there is a bug/behavior that causes // a beep to be generated with certain command+control key combinations. // The workaround is to create a default binding file to silence them. // In ~/Library/KeyBindings/DefaultKeyBinding.dict add these entries: // // { // "^@\UF701" = "noop:"; // "^@\UF702" = "noop:"; // "^@\UF703" = "noop:"; // } { key: 'alt+ctrl+[ArrowUp]', command: ['speak', 'all', { withHighlighting: false }], }, { key: 'alt+ctrl+[ArrowDown]', command: ['speak', 'selection', { withHighlighting: false }], }, // // Punctuations and some non-alpha key combinations // only work with specific keyboard layouts // { key: 'alt+[Equal]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['applyStyle', { mode: 'text' }], }, { key: 'alt+[Equal]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'text', command: ['applyStyle', { mode: 'math' }], }, { key: 'shift+[Quote]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['switchMode', 'text', '', '“'], }, // ?? { key: 'shift+[Quote]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'text', command: ['switchMode', 'math', '”', ''], }, // ?? { key: '/', ifMode: 'math', command: ['insert', '\\frac{#@}{#?}'], }, { key: 'alt+/', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '\\/'], }, { key: 'alt+[BracketLeft]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '\\left\\lbrack #0 \\right\\rbrack'], }, // ?? { key: 'ctrl+[Minus]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'moveToSubscript', }, // ?? { key: 'shift+alt+[BracketLeft]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '\\left\\lbrace #0 \\right\\rbrace'], }, // ?? { key: 'ctrl+;', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'addRowAfter', }, { key: 'cmd+;', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'addRowAfter', }, { key: 'shift+ctrl+;', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'addRowBefore', }, { key: 'shift+cmd+;', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'addRowBefore', }, { key: 'ctrl+[Comma]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'addColumnAfter', }, { key: 'cmd+[Comma]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'addColumnAfter', }, { key: 'shift+ctrl+[Comma]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'addColumnAfter', }, { key: 'shift+cmd+[Comma]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: 'addColumnAfter', }, { key: 'alt+[Digit5]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '$\\infty'], }, // "%" key { key: 'alt+[Digit6]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '\\wedge'], }, // "^" key { key: 'shift+alt+[Digit6]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '\\vee'], }, // "^" key { key: 'alt+[Digit9]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '('], }, // "(" key} override smartFence { key: 'alt+[Digit0]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', ')'], }, // ")" key} override smartFence { key: 'alt+|', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '|'], }, // "|" key} override smartFence { key: 'shift+[Backquote]', ifLayout: ['apple.en-intl', 'windows.en-intl', 'linux.en'], ifMode: 'math', command: ['insert', '\\~'], }, // ?? ]; /** * Most commands can be associated to their keyboard shortcuts from the * DEFAULT_KEYBINDINGS table above, for example 'speakSelection' -> 'ctrl+KeyR' * However, those that contain complex commands are more ambiguous. * For example, '\sqrt' -> 'math:alt+KeyV'. This table provides the reverse * mapping for those more complex commands. It is used when displaying * keybindings for specific commands in the popover. */ export const REVERSE_KEYBINDINGS = { '\\theta': 'alt+q', '\\sqrt': ['alt+v', 'ctrl+[Digit2]'], '\\pi': 'alt+p', '\\prod': 'shift+alt+p', '\\sum': 'alt+w', '\\int': 'alt+b', '\\cup': 'alt+u', '\\cap': 'alt+n', '\\bigcup': 'shift+alt+u', '\\bigcap': 'shift+alt+n', '\\forall': 'shift+alt+a', '\\exists': 'shift+alt+e', '\\infty': 'alt+[Digit5]', '\\wedge': 'alt+[Digit5]', '\\vee': 'shift+alt+[Digit6]', '\\differentialD': 'alt+d', '\\partial': 'shift+alt+d', '\\frac': 'Slash', '\\emptyset': 'alt+o', '\\varnothing': 'shift+alt+o', '\\~': '~', };
the_stack
import {ipcRenderer, remote} from "electron" import jwtDecode from "jwt-decode" import Workspaces from "src/js/state/Workspaces" import WorkspaceStatuses from "src/js/state/WorkspaceStatuses" import {mocked} from "ts-jest/utils" import {createZealotMock} from "zealot" import Auth0Client from "../../auth0" import {AuthType} from "../../state/Workspaces/types" import initTestStore from "../../../../test/unit/helpers/initTestStore" import { buildAndAuthenticateWorkspace, ConnectionError, LoginError } from "./buildAndAuthenticateWorkspace" jest.mock("jwt-decode") jest.mock("../../auth0") jest.mock("electron", () => ({ ipcRenderer: { invoke: jest.fn(), once: jest.fn(), removeListener: jest.fn() }, remote: { dialog: { showMessageBox: jest.fn() } } })) const fixtures = { secureMethodAuth: { kind: "auth0", auth0: { client_id: "testClientId", domain: "testDomain" } }, publicMethodAuth: { kind: "none" }, newWorkspace: { id: "1", name: "testWorkspaceName", host: "testHost", port: "testPort" }, accessToken: "testAccessToken", refreshToken: "testRefreshToken", validDate: Math.floor(Date.now() / 1000 + 60), expiredDate: Math.floor(Date.now() / 1000 - 60), version: {version: "1"} } let store, zealot, ctl let auth0ClientMock, jwtDecodeMock, ipcRendererMock, remoteMock beforeEach(() => { auth0ClientMock = mocked(Auth0Client) jwtDecodeMock = mocked(jwtDecode) remoteMock = mocked(remote) ipcRendererMock = mocked(ipcRenderer) zealot = createZealotMock() store = initTestStore(zealot.zealot) ctl = new AbortController() }) const expectWorkspace = (ws, status) => { const state = store.getState() expect(Workspaces.id(ws.id)(state)).toEqual(ws) expect(WorkspaceStatuses.get(ws.id)(state)).toEqual(status) } describe("success cases", () => { beforeEach(() => { zealot .stubPromise("version", fixtures.version) .stubPromise("pools.list", [{name: "dataPool", id: "1"}], "always") .stubPromise("pools.stats", {}, "always") }) test("new public workspace", async () => { zealot.stubPromise("authMethod", fixtures.publicMethodAuth) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(fixtures.newWorkspace, ctl.signal) ) expect(cancelled).toEqual(false) expect(error).toBeNull() expectWorkspace( { ...fixtures.newWorkspace, ...fixtures.version, authType: "none" }, "connected" ) }) test("existing public workspace, updated version", async () => { const existingWs = { ...fixtures.newWorkspace, version: "0", authType: "none" as AuthType } store.dispatch(Workspaces.add(existingWs)) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(existingWs, ctl.signal) ) expect(cancelled).toEqual(false) expect(error).toBeNull() expect(Workspaces.all(store.getState())).toHaveLength(1) expectWorkspace( { ...existingWs, ...fixtures.version }, "connected" ) }) test("existing secure workspace -> valid token from secrets", async () => { const existingWs = { ...fixtures.newWorkspace, ...fixtures.version, authType: "auth0" as AuthType, authData: { clientId: fixtures.secureMethodAuth.auth0.client_id, domain: fixtures.secureMethodAuth.auth0.domain } } store.dispatch(Workspaces.add(existingWs)) ipcRendererMock.invoke.mockReturnValueOnce(fixtures.accessToken) jwtDecodeMock.mockReturnValueOnce({ exp: fixtures.validDate }) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(existingWs, ctl.signal) ) expect(cancelled).toEqual(false) expect(error).toBeNull() expect(Workspaces.all(store.getState())).toHaveLength(1) expectWorkspace( { ...existingWs, authData: {...existingWs.authData, accessToken: fixtures.accessToken} }, "connected" ) }) test("existing secure workspace -> no token -> succeed refresh", async () => { const existingWs = { ...fixtures.newWorkspace, ...fixtures.version, authType: "auth0" as AuthType, authData: { clientId: fixtures.secureMethodAuth.auth0.client_id, domain: fixtures.secureMethodAuth.auth0.domain } } store.dispatch(Workspaces.add(existingWs)) // no access token in secrets ipcRendererMock.invoke.mockReturnValueOnce("") // do have refresh token though ipcRendererMock.invoke.mockReturnValueOnce(fixtures.refreshToken) auth0ClientMock.mockImplementationOnce(() => ({ refreshAccessToken: jest.fn().mockReturnValueOnce(fixtures.accessToken) })) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(existingWs, ctl.signal) ) expect(cancelled).toEqual(false) expect(error).toBeNull() expectWorkspace( { ...existingWs, authData: {...existingWs.authData, accessToken: fixtures.accessToken} }, "connected" ) }) test("existing secure workspace -> expired token -> succeed refresh", async () => { const existingWs = { ...fixtures.newWorkspace, ...fixtures.version, authType: "auth0" as AuthType, authData: { clientId: fixtures.secureMethodAuth.auth0.client_id, domain: fixtures.secureMethodAuth.auth0.domain } } store.dispatch(Workspaces.add(existingWs)) ipcRendererMock.invoke.mockReturnValueOnce("expiredToken") jwtDecodeMock.mockReturnValueOnce({exp: fixtures.expiredDate}) ipcRendererMock.invoke.mockReturnValueOnce(fixtures.refreshToken) auth0ClientMock.mockImplementationOnce(() => ({ refreshAccessToken: jest.fn().mockReturnValueOnce(fixtures.accessToken) })) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(existingWs, ctl.signal) ) expect(cancelled).toEqual(false) expect(error).toBeNull() expect(Workspaces.all(store.getState())).toHaveLength(1) expectWorkspace( { ...existingWs, authData: {...existingWs.authData, accessToken: fixtures.accessToken} }, "connected" ) }) test("new secure workspace -> login required -> cancel dialog", async () => { zealot.stubPromise("authMethod", fixtures.secureMethodAuth) ipcRendererMock.invoke.mockReturnValueOnce("") ipcRendererMock.invoke.mockReturnValueOnce("") remoteMock.dialog.showMessageBox.mockReturnValueOnce({response: 1}) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(fixtures.newWorkspace, ctl.signal) ) expect(cancelled).toEqual(true) expect(error).toBeNull() expect(Workspaces.all(store.getState())).toHaveLength(0) }) test("new secure workspace -> login required -> abort login", async () => { zealot.stubPromise("authMethod", fixtures.secureMethodAuth) ipcRendererMock.invoke.mockReturnValueOnce("") ipcRendererMock.invoke.mockReturnValueOnce("") remoteMock.dialog.showMessageBox.mockReturnValueOnce({response: 0}) setTimeout(() => ctl.abort(), 20) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(fixtures.newWorkspace, ctl.signal) ) expect(cancelled).toEqual(true) expect(error).toBeNull() expect(Workspaces.all(store.getState())).toHaveLength(0) }) test("new secure workspace -> login required -> succeed login", async () => { zealot.stubPromise("authMethod", fixtures.secureMethodAuth) ipcRendererMock.invoke.mockReturnValueOnce("") ipcRendererMock.invoke.mockReturnValueOnce("") remoteMock.dialog.showMessageBox.mockReturnValueOnce({response: 0}) ipcRendererMock.once = async (_channel, handleAuthCb) => { await handleAuthCb("mockEvent", { workspaceId: fixtures.newWorkspace.id, code: "mockCode" }) } auth0ClientMock.mockImplementationOnce(() => ({ openLoginUrl: jest.fn(), exchangeCode: jest.fn().mockReturnValueOnce({ accessToken: fixtures.accessToken, refreshToken: fixtures.refreshToken }) })) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(fixtures.newWorkspace, ctl.signal) ) expect(cancelled).toEqual(false) expect(error).toBeNull() const {domain, client_id: clientId} = fixtures.secureMethodAuth.auth0 expectWorkspace( { ...fixtures.newWorkspace, ...fixtures.version, authType: fixtures.secureMethodAuth.kind, authData: {clientId, domain, accessToken: fixtures.accessToken} }, "connected" ) }) }) describe("failure cases", () => { test("new generic workspace -> connection failure", async () => { // no version mock setup -> connection error const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(fixtures.newWorkspace, ctl.signal) ) expect(cancelled).toEqual(false) expect(error).toBeInstanceOf(ConnectionError) expect(Workspaces.all(store.getState())).toHaveLength(0) }) test("new secure workspace -> login required -> login failure", async () => { zealot.stubPromise("version", fixtures.version) zealot.stubPromise("authMethod", fixtures.secureMethodAuth) ipcRendererMock.invoke.mockReturnValueOnce("") ipcRendererMock.invoke.mockReturnValueOnce("") remoteMock.dialog.showMessageBox.mockReturnValueOnce({response: 0}) ipcRendererMock.once = async (_channel, handleAuthCb) => { await handleAuthCb("mockEvent", { workspaceId: fixtures.newWorkspace.id, // no code, login failed code: undefined }) } auth0ClientMock.mockImplementationOnce(() => ({ openLoginUrl: jest.fn() })) const [cancelled, error] = await store.dispatch( buildAndAuthenticateWorkspace(fixtures.newWorkspace, ctl.signal) ) expect(cancelled).toEqual(false) expect(error).toBeInstanceOf(LoginError) expect(Workspaces.all(store.getState())).toHaveLength(0) }) })
the_stack
// This code is written with trying new technology in mind ( virtual-dom), // and not necessarily the simplest solution. // In fact, using html directly would be easier. /// <reference path='./typings/browser.d.ts' /> import $ = require('jquery') import _ = require('lodash') import V = require('virtual-dom') let {h, diff, patch, create} = V declare var require: (s: string) => any; let foo = require('jquery-ui') let _VText = require('virtual-dom/vnode/vtext') import pie = require('./pie') function VText(t: string){ return addTags(new _VText(t)) } // A pair of Id and distance type IdDist=[string, number] interface GroupResult{ exploit : IdDist[], explore : IdDist[], prev : IdDist[], } // The response from /similar interface SimilarResponse { a: GroupResult, b: GroupResult, sample: IdDist[], deploy_id: string, } function SimilarResponse2State(s: SimilarResponse) : State { return { samples : s.sample, a : s.a.prev.concat(s.a.exploit), b : s.b.prev.concat(s.b.exploit), maybeA : s.a.explore, maybeB : s.b.explore, } as State } function sendSimilar(deploy: boolean){ $("#spinner").show() let f = (id: string ) => $(`#${id} img`).map((idx:number, o: Element) => o.id).get() let data = {a: f('panelA'), b: f('panelB')} let numRndFeats = $("#numRndFeats").val(); let numBags = $("#numBags").val(); let dataset = QueryString['dataset']; let prefix = QueryString['prefix']; let formData = { dataset: dataset, prefix: prefix, deploy: deploy, numBags: numBags, numRndFeats: numRndFeats, input: JSON.stringify(data) }; let w = deploy ? window.open('rt_prediction.html') : null $.ajax({ "dataType": "json", "processData": false, "data": JSON.stringify(formData), "url": "../similar", "method": "POST" }).done((ret: SimilarResponse) =>{ let s = SimilarResponse2State(ret) let u = ui(s) let cs = document.body.children document.body.replaceChild(create(u), $('#main')[0]) InitSortable() $("#spinner").hide() $(".startedHidden").show() if(deploy){ w.location.assign(`rt_prediction.html?deploy_id=${ret.deploy_id}`) } }) } function onClick(evt: MouseEvent){ sendSimilar(false) } function onDeploy(evt: MouseEvent){ sendSimilar(true) } function addAllToA(evt: MouseEvent){ $('#panelMaybeA > span').appendTo('#panelA') } function addAllToB(evt: MouseEvent){ $('#panelMaybeB > span').appendTo('#panelB') } type Row = [string] interface State{ samples : IdDist[] a : IdDist[] maybeA : IdDist[] b : IdDist[] maybeB : IdDist[] } const Img = ([imgId, dist]: IdDist) => { let dataset = QueryString['dataset']; let prefix = QueryString['prefix']; let img = h(`img#${imgId}`, { src: `${prefix}/${dataset}/${imgId}.jpg`, id: imgId, style: { margin: "4px", borderRadius: "25%", maxWidth: "200px", } } ,[] ) let color = HSVtoRGB(dist * 0.333, 1, 1) let p = pie(dist, color) return h('span', {style:{}}, [img, p]) } function Panel(id: string, style: any, idDists: IdDist[], title: string, backgroundImg?: string){ let o1 = idDists.map(Img) let o = addTags(o1) let style2 = JSON.parse(JSON.stringify(style)) if(backgroundImg) { style2["background"] = "url("+backgroundImg+") center center" style2["backgroundRepeat"] = "no-repeat" } return o.DIVp({id: id, className: 'sortable', style: style2}) } // Add HTML tag as a function into array, so for an array like a = ['abc', 'def'] // a.TD = TD(a) // a.mapTD = [TD('abc', TD('def'))] // a.TDp(prop: dict) = TD(a, prop) // a.mapTDp(prop: dict) = [TD('abc', prop), TD('def', prop)] // where TD is h('td', ...) from hyperscript function addTags(o: any): any{ if(o.hasOwnProperty('TD')){ return o } const add = (tag: string) => { let r: any = {} r[tag] = { get: function() { return addTags(h(tag, this)) } } r[tag + 'p'] = { value: function(p: VirtualDOM.createProperties) { return addTags(h(tag, p, this)) } } r['map' + tag] = { get: function() { return addTags(this.map(function(e: any) { return h(tag, e) })) } } r['map' + tag + 'p'] = { value: function(p: VirtualDOM.createProperties) { return addTags(this.map(function(e: any) { return h(tag, p, e) })) } } return r } 'TD TR TABLE H1 H2 H3 H4 H5 H6 DIV'.split(' ').forEach((tag: string) => Object.defineProperties(o, add(tag))) return o } let btnStyle = {float: 'right', margin: '5px 30px'} const createButton = (f: any) => h('button', { "onclick":f , className: 'btn btn-info' , style: btnStyle } , "Add All") // This function creates the whole ui function ui (s: State){ let pStyle = { minHeight: "300px", width: "48vw", border: "2px solid #ccc", borderRadius: "25px", borderCollapse: "separate", margin: "0 10px", display: "inline-block", height: "100%", padding: "10px" } let sampleStyle = _.clone(pStyle) sampleStyle['width'] = '96vw' //This modify array's prototype. addTags(Array.prototype) let aStyle = { maxHeight: "500px", overflow: "auto", marginBottom: "15px", minHeight: "100px"} let pa = Panel('panelA', pStyle, s.a, 'Target', 'drag_pos.png') let pb = Panel('panelB', pStyle, s.b, 'Not Target', 'drag_neg.png') let pa1 = Panel('panelMaybeA', pStyle, s.maybeA, 'Maybe Target') let pb1 = Panel('panelMaybeB', pStyle, s.maybeB, 'Probably Not Target') let ps = Panel('panelSamples', sampleStyle, s.samples, 'Samples') let btn = addTags( h('button', {"onclick": onClick, className: 'btn btn-primary', style: btnStyle }, "Find Similar")) let btnDeploy = addTags( h('button', {"onclick": onDeploy, className: 'btn', style: btnStyle }, "Deploy")) let btn2 = createButton(addAllToA) let btn3 = createButton(addAllToB) let h2p = {style: { textAlign: "center", fontSize: "25px"}} let hidden = {className: 'startedHidden', style: {display: "none"}} let c2 = {colSpan: 2, vAlign: "top"} let c3 = {colSpan: 3} let c4 = {colSpan: 4} return h('table#main', [ ([VText('Samples'), [btnDeploy, btn]] as any).mapDIVp(h2p).mapTDp(c2).TR , ([ps] as any).mapTDp(c4).TR , ([VText('Target').DIVp(h2p), VText(""), VText('Not Target').DIVp(h2p)] as any).mapTD.TR, , ([pa, pb] as any).mapTDp(c2).TR , ([VText('Maybe Target').DIVp(h2p), btn2, VText('Probably Not Target').DIVp(h2p), btn3] as any).mapDIVp(hidden).mapTD.TR, , ([pa1, pb1] as any).mapDIVp(hidden).mapTDp(c2).TR ]) } function rows2State(rows: Row[]): State{ return { samples: rows.map(row => [row[0], 0]), a: [], b: [], maybeA: [], maybeB: [] } as State } function handleReceive(event: JQueryEventObject, ui: JQueryUI.SortableUIParams){ let sid = ui.sender[0].id if(this.id == 'panelA' && sid == 'panelB' || this.id == 'panelB' && sid == 'panelA'){ ui.item.find('svg').hide() } } function InitSortable(){ $(".sortable").sortable({ connectWith: ".sortable", helper: "clone", cursorAt: {left: 50, top: 50}, receive: handleReceive }).disableSelection() } // parse the query string and return a dictionary. var QueryString = function () { // This function is anonymous, is executed immediately and // the return value is assigned to QueryString! var query_string = {}; var query = window.location.search.substring(1); var vars = query.split("&"); for (var i=0;i<vars.length;i++) { var pair = vars[i].split("="); // If first entry with this name if (typeof query_string[pair[0]] === "undefined") { query_string[pair[0]] = decodeURIComponent(pair[1]); // If second entry with this name } else if (typeof query_string[pair[0]] === "string") { var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ]; query_string[pair[0]] = arr; // If third or later entry with this name } else { query_string[pair[0]].push(decodeURIComponent(pair[1])); } } return query_string; }(); export function init(){ let dataset = QueryString['dataset']; $.ajax({ url: "../../../../../v1/query?q=select count(*) from "+dataset+"&format=table&rowNames=false&headers=false" }).done(function (rows) { var num_images = rows[0][0]; var sample_size = Math.min(num_images, 10); $.ajax({ url: "../../../../../v1/query?q=select regex_replace(regex_replace(location, '/.*/', ''), '.jpg', '') from sample(" + dataset + ",{rows:"+sample_size+"})&format=table&rowNames=false&headers=false" }).done((rows: Row[]) => { let s = rows2State(rows) let u = ui(s) document.body.appendChild(create(u)) InitSortable() }) }); } function HSVtoRGB(h: number, s: number, v: number) { let i = Math.floor(h * 6) let f = h * 6 - i let p = v * (1 - s) let q = v * (1 - f * s) let t = v * (1 - (1 - f) * s) var r: number, g: number, b : number switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } let he = (x: number) => ('0' + Math.round( x * 255).toString(16)).substr(-2) return `#${he(r)}${he(g)}${he(b)}` } $(init)
the_stack
import { expect } from 'chai'; import 'mocha'; import * as path from 'path'; import * as fs from 'fs'; import { TestSuiteInfo } from 'vscode-test-adapter-api'; import { isFileExists } from '../../src/utilities/fs'; import { IWorkspaceConfiguration } from '../../src/configuration/workspaceConfiguration'; import { PytestTestRunner } from '../../src/pytest/pytestTestRunner'; import { createPytestConfiguration, extractExpectedState, extractErroredTests, findTestSuiteByLabel, logger } from '../utils/helpers'; import { PYTEST_EXPECTED_SUITES_LIST_WITHOUT_ERRORS } from '../utils/pytest'; suite('Pytest test discovery with additional arguments', async () => { const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--rootdir=test/inner_tests', '--trace', '--cache-show', '--doctest-modules', '--collect-only', '--junitxml=sample.xml', '--ignore=test/import_error_tests' ]); const runner = new PytestTestRunner('some-id', logger()); test('should discover tests', async () => { const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; const labels = mainSuite!.children.map(x => x.label); expect(labels).to.have.members(PYTEST_EXPECTED_SUITES_LIST_WITHOUT_ERRORS); }); }); suite('Run pytest tests with additional arguments', () => { const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--rootdir', 'test/inner_tests', '--trace', '--doctest-modules', '--collect-only', '--junitxml=sample.xml', '--exitfirst', '--ignore=test/import_error_tests' ]); const runner = new PytestTestRunner('some-id', logger()); test('should run all tests', async () => { const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; expect(mainSuite!.label).to.be.eq('Pytest tests'); const states = await runner.run(config, runner.adapterId); expect(states).to.be.not.empty; states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); }); [ { suite: 'arithmetic.py', cases: [ { file: 'src/arithmetic.py', case: '::arithmetic.add_failed' }, { file: 'src/arithmetic.py', case: '::arithmetic.mul_passed' } ], } ].forEach(({ suite, cases }) => { test(`should run doctest ${suite} suite`, async () => { const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; const suiteToRun = findTestSuiteByLabel(mainSuite!, suite); expect(suiteToRun).to.be.not.undefined; const states = await runner.run(config, suiteToRun!.id); expect(states).to.be.not.empty; const cwd = config.getCwd(); expect(states.map(s => s.test)).to.have.deep.members( cases.map(c => path.resolve(cwd, c.file) + c.case) ); states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); }); }); [ 'arithmetic.mul_passed', 'arithmetic.add_failed' ].forEach(testMethod => { test(`should run doctest ${testMethod} test`, async () => { const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; const suite = findTestSuiteByLabel(mainSuite!, testMethod); expect(suite).to.be.not.undefined; const states = await runner.run(config, suite!.id); expect(states).to.be.not.empty; states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); }); }); }); suite('Filter pytest tests by mark arguments', () => { const runner = new PytestTestRunner('some-id', logger()); const markedTests = [ { module: path.join('test', 'inner_tests', 'add_test.py'), case: '::test_one_plus_two_is_three_passed' }, { module: path.join('test', 'other_tests', 'add_test.py'), case: '::test_same_filename_one_plus_two_is_three_passed' } ]; test('should discover only tests with specific mark', async () => { const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--ignore=test/import_error_tests', '-m', 'add_test_passed' ]); const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; expect(mainSuite!.label).to.be.eq('Pytest tests'); const labels = mainSuite!.children.map(x => x.file); expect(labels).to.have.members(markedTests.map(t => path.join(config.getCwd(), t.module))); }); test('should run only tests with specific mark', async () => { const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--ignore=test/import_error_tests', '-m', 'add_test_passed' ]); const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; expect(mainSuite!.label).to.be.eq('Pytest tests'); const states = await runner.run(config, runner.adapterId); expect(states).to.be.not.empty; const labels = states.map(x => x.test); expect(labels).to.have.members(markedTests.map(t => path.join(config.getCwd(), t.module) + t.case)); states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); }); test('should not run tests with specific mark', async () => { const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--ignore=test/import_error_tests', '-m', 'not add_test_passed' ]); const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; expect(mainSuite!.label).to.be.eq('Pytest tests'); const states = await runner.run(config, runner.adapterId); expect(states).to.be.not.empty; const labels = states.map(x => x.test); expect(labels).not.to.have.members(markedTests.map(t => path.join(config.getCwd(), t.module) + t.case)); states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); }); }); suite('Pytest tests with additional positional arguments', () => { const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--rootdir', 'test/inner_tests', 'test/inner_tests', 'test/other_tests' ]); const runner = new PytestTestRunner('some-id', logger()); test('should discover tests', async () => { const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; const expectedSuites = [ 'add_test.py', 'add_test.py' ]; const labels = mainSuite!.children.map(x => x.label); expect(labels).to.have.members(expectedSuites); }); test('should run all tests', async () => { const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; expect(mainSuite!.label).to.be.eq('Pytest tests'); const states = await runner.run(config, runner.adapterId); expect(states).to.be.not.empty; const labels = states.map(x => x.test); expect(labels).to.have.members([ path.join(config.getCwd(), 'test', 'inner_tests', 'add_test.py') + '::test_one_plus_two_is_three_passed', path.join(config.getCwd(), 'test', 'inner_tests', 'add_test.py') + '::test_two_plus_two_is_five_failed', path.join(config.getCwd(), 'test', 'other_tests', 'add_test.py') + '::test_same_filename_one_plus_two_is_three_passed', path.join(config.getCwd(), 'test', 'other_tests', 'add_test.py') + '::test_same_filename_two_plus_two_is_five_failed' ]); states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); }); }); suite('Use junit-xml argument for pytest tests', () => { const runner = new PytestTestRunner('some-id', logger()); test('should create junit-xml report by custom path', async () => { const now = new Date().getTime(); const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--ignore=test/import_error_tests', `--junitxml=example_${now}.xml` ]); const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; const states = await runner.run(config, runner.adapterId); expect(states).to.be.not.empty; states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); const reportFilePath = path.resolve(config.getCwd(), `example_${now}.xml`); expect(await isFileExists(reportFilePath)).to.be.true; try { fs.unlinkSync(reportFilePath); } catch { /* intentionally ignored */ } }); }); suite('Run pytest suite with pytest.ini in subdirectory', () => { /** * In the first test we run all pytest tests and * expect that both tests from test_simple.py will be executed. * This is similar to running * $ pytest -v --ignore=test/import_error_tests * ... * test/submodule/test_simple.py::test_submodule_addition_passed PASSED * test/submodule/test_simple.py::test_submodule_subtraction_passed PASSED * ... * from root folder (test/test_samples/pytest). * * In the second case we run tests from test/submodule/test_simple.py and * expect that _only one of two tests_ will be executed. * This is similar to running * $ pytest -v --ignore=test/import_error_tests test/submodule/test_simple.py * ... * test/submodule/test_simple.py::test_submodule_subtraction_passed PASSED * ... * from root folder (test/test_samples/pytest). * * This is how rootdir detection in pytest works: * https://docs.pytest.org/en/stable/customize.html#finding-the-rootdir */ const runner = new PytestTestRunner('some-id', logger()); test('should discover and run all tests', async () => { const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--ignore=test/import_error_tests' ]); const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; const submoduleSuite = findTestSuiteByLabel(mainSuite!, 'test_simple.py') as TestSuiteInfo; expect(submoduleSuite).to.be.not.undefined; expect(submoduleSuite.type).to.be.eq('suite'); expect(submoduleSuite.children).to.be.not.empty; const submoduleTestToSkip = findTestSuiteByLabel(mainSuite!, 'test_submodule_addition_passed')!.id; const submoduleTestToRun = findTestSuiteByLabel(mainSuite!, 'test_submodule_subtraction_passed')!.id; const states = await runner.run(config, runner.adapterId); expect(states).to.be.not.empty; expect(states.map(s => s.test)) .and.to.include(submoduleTestToRun) .and.to.include(submoduleTestToSkip); states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); }); test('should run suite in submodule', async () => { const config: IWorkspaceConfiguration = createPytestConfiguration( 'pytest', [ '--ignore=test/import_error_tests' ]); const mainSuite = await runner.load(config); expect(mainSuite).to.be.not.undefined; expect(extractErroredTests(mainSuite!)).to.be.empty; const submoduleSuite = findTestSuiteByLabel(mainSuite!, 'test_simple.py') as TestSuiteInfo; expect(submoduleSuite).to.be.not.undefined; expect(submoduleSuite.type).to.be.eq('suite'); expect(submoduleSuite.children).to.be.not.empty; const submoduleTestToRun = findTestSuiteByLabel(mainSuite!, 'test_submodule_subtraction_passed')!.id; const states = await runner.run(config, submoduleSuite.id); expect(states).to.be.not.empty; expect(states.map(s => s.test)).to.be.lengthOf(1).and.to.include(submoduleTestToRun); states.forEach(state => { const expectedState = extractExpectedState(state.test as string); expect(state.state).to.be.eq(expectedState); }); }); });
the_stack
import React, { Children } from "react"; import { RouteComponentProps } from "react-router-dom"; import "./List.less"; import TankComponent from "../../common/component/TankComponent"; import Pager from "../../common/model/base/Pager"; import Matter from "../../common/model/matter/Matter"; import Moon from "../../common/model/global/Moon"; import Director from "./widget/Director"; import SortDirection from "../../common/model/base/SortDirection"; import MatterPanel from "./widget/MatterPanel"; import UploadMatterPanel from "./widget/UploadMatterPanel"; import { Button, Col, Empty, Input, Modal, Pagination, Row, Space, Upload, } from "antd"; import MessageBoxUtil from "../../common/util/MessageBoxUtil"; import { CloudUploadOutlined, DeleteOutlined, DownloadOutlined, DragOutlined, ExclamationCircleFilled, FolderOutlined, MinusSquareOutlined, PlusSquareOutlined, ShareAltOutlined, SyncOutlined, } from "@ant-design/icons"; import ImagePreviewer from "../widget/previewer/ImagePreviewer"; import Sun from "../../common/model/global/Sun"; import { UserRole } from "../../common/model/user/UserRole"; import StringUtil from "../../common/util/StringUtil"; import MoveBatchModal from "./widget/MoveBatchModal"; import ShareOperationModal from "./widget/ShareOperationModal"; import MatterDeleteModal from "./widget/MatterDeleteModal"; import Share from "../../common/model/share/Share"; import ShareDialogModal from "../share/widget/ShareDialogModal"; import BreadcrumbModel from "../../common/model/base/option/BreadcrumbModel"; import BreadcrumbPanel from "../widget/BreadcrumbPanel"; import Lang from "../../common/model/global/Lang"; import FileUtil from "../../common/util/FileUtil"; import SafeUtil from "../../common/util/SafeUtil"; import MatterSortPanel from "./widget/MatterSortPanel"; import { RcCustomRequestOptions } from "antd/lib/upload/interface"; interface IProps extends RouteComponentProps {} interface IState {} export default class List extends TankComponent<IProps, IState> { //当前文件夹信息。 matter = new Matter(); //准备新建的文件。 newMatter = new Matter(); //当前选中的文件 selectedMatters: Matter[] = []; //搜索的文字 searchText: string | null = null; //获取分页的一个帮助器 pager = new Pager<Matter>(this, Matter, Pager.MAX_PAGE_SIZE); user = Moon.getSingleton().user; preference = Moon.getSingleton().preference; //导演 director = new Director(); //当前面包屑模型数组。 breadcrumbModels: BreadcrumbModel[] = []; //分享 share = new Share(); newMatterRef = React.createRef<MatterPanel>(); //用来判断是否展示遮罩层 dragEnterCount = 0; //临时文件list,用于上传文件夹功能 tempUploadList: File[] = []; //上传错误日志 uploadErrorLogs: [string, string, string][] = []; //准备上传的一系列文件 static uploadMatters: Matter[] = []; //持有全局唯一的实例。 static instance: List | null = null; constructor(props: IProps) { super(props); List.instance = this; } //拖拽上传 drag = { dragEnterListener: (e: DragEvent) => { e.preventDefault(); this.dragEnterCount++; if (this.dragEnterCount > 0) this.updateUI(); }, dragleaveListener: (e: DragEvent) => { e.preventDefault(); this.dragEnterCount--; if (this.dragEnterCount <= 0) this.updateUI(); }, dragoverListener: (e: DragEvent) => { e.preventDefault(); }, dropListener: (e: DragEvent) => { e.preventDefault(); this.dragEnterCount = 0; this.launchUpload(e.dataTransfer!.files); this.updateUI(); }, register: () => { const { dragEnterListener, dragleaveListener, dragoverListener, dropListener, } = this.drag; const el = document.getElementById("layout-content")!; el.addEventListener("dragenter", dragEnterListener); el.addEventListener("dragleave", dragleaveListener); el.addEventListener("dragover", dragoverListener); el.addEventListener("drop", dropListener); }, remove: () => { const { dragEnterListener, dragleaveListener, dragoverListener, dropListener, } = this.drag; const el = document.getElementById("layout-content")!; el.removeEventListener("dragenter", dragEnterListener); el.removeEventListener("dragleave", dragleaveListener); el.removeEventListener("dragover", dragoverListener); el.removeEventListener("drop", dropListener); }, }; componentDidMount() { //刷新一下列表 if (this.user.role === UserRole.ADMINISTRATOR) { this.pager.getFilter("userUuid")!.visible = true; } else { this.pager.setFilterValue("userUuid", this.user.uuid); } this.pager.enableHistory(); this.refresh(); this.drag.register(); } componentWillReceiveProps(nextProps: Readonly<IProps>, nextContext: any) { if (this.props.location.search !== nextProps.location.search) { this.pager.enableHistory(); this.refresh(); } } componentWillUnmount() { this.drag.remove(); } refresh() { // 清空暂存区 this.selectedMatters = []; // 刷新文件列表 this.refreshPager(); // 刷新面包屑 this.refreshBreadcrumbs(); } refreshPager() { // 初始化当前matter uuid if (this.matter.uuid !== this.pager.getFilterValue("puuid")) { this.matter.uuid = this.pager.getFilterValue("puuid") || Matter.MATTER_ROOT; } this.pager.setFilterValue("puuid", this.matter.uuid); //如果没有任何的排序,默认使用时间倒序和文件夹在顶部 if (!this.pager.getCurrentSortFilter()) { this.pager.setFilterValue("orderCreateTime", SortDirection.DESC); this.pager.setFilterValue("orderDir", SortDirection.DESC); } // 过滤掉被软删除的文件 this.pager.setFilterValue("deleted", false); this.pager.httpList(); } checkMatter(matter?: Matter) { if (matter) { if (matter.check) { this.selectedMatters.push(matter); } else { const index = this.selectedMatters.findIndex( (item) => item.uuid === matter.uuid ); this.selectedMatters.splice(index, 1); } } else { //统计所有的勾选 this.selectedMatters = []; this.pager.data.forEach((matter) => { if (matter.check) { this.selectedMatters.push(matter); } }); } this.updateUI(); } checkAll() { this.pager.data.forEach((i) => { i.check = true; }); this.checkMatter(); } checkNone() { this.pager.data.forEach((i) => { i.check = false; }); this.checkMatter(); } deleteBatch() { const uuids = this.selectedMatters.map((i) => i.uuid).toString(); MatterDeleteModal.open( () => { this.matter.httpSoftDeleteBatch(uuids, () => { MessageBoxUtil.success(Lang.t("operationSuccess")); this.refresh(); }); }, () => { this.matter.httpDeleteBatch(uuids, () => { MessageBoxUtil.success(Lang.t("operationSuccess")); this.refresh(); }); } ); } downloadZip() { const uuids = this.selectedMatters.map((i) => i.uuid).toString(); Matter.downloadZip(uuids); } toggleMoveBatch() { MoveBatchModal.open((targetUuid) => { const uuids = this.selectedMatters.map((i) => i.uuid).join(","); this.matter.httpMove(uuids, targetUuid, () => { MessageBoxUtil.success(Lang.t("operationSuccess")); this.refresh(); }); }); } triggerUpload(fileObj: RcCustomRequestOptions) { const { file } = fileObj; if (file) this.launchUpload(file); } debounce(func: Function, wait: number) { let timer: any = null; return (fileObj: any) => { const { file } = fileObj; this.tempUploadList.push(file); if (timer) { clearTimeout(timer); } timer = setTimeout(func, wait); }; } triggerUploadDir = this.debounce(async () => { await this.uploadDirectory(); if (!this.uploadErrorLogs.length) { MessageBoxUtil.success(Lang.t("matter.uploaded")); } else { // 上传错误弹出提示框 const url = FileUtil.getErrorLogsToCSVUrl(this.uploadErrorLogs); Modal.confirm({ title: Lang.t("matter.uploadInfo"), icon: <ExclamationCircleFilled twoToneColor="#FFDC00" />, content: Lang.t("matter.uploadErrorInfo"), okText: Lang.t("matter.exportCSV"), onOk: () => { if (url) { window.open(url); } else { MessageBoxUtil.warn(Lang.t("matter.unCompatibleBrowser")); } }, }); } this.tempUploadList = []; this.uploadErrorLogs = []; this.refresh(); }, 0); async uploadDirectory() { const dirPathUuidMap: any = {}; // 存储已经创建好的文件夹map for (let i = 0; i < this.tempUploadList.length; i++) { const file: File = this.tempUploadList[i]; const paths = file.webkitRelativePath.split("/"); const pPaths = paths.slice(0, paths.length - 1); const pPathStr = pPaths.join("/"); if (!dirPathUuidMap[pPathStr]) { // 递归创建其父文件夹 for (let j = 1; j <= pPaths.length; j++) { const midPaths = pPaths.slice(0, j); const midPathStr = midPaths.join("/"); if (!dirPathUuidMap[midPathStr]) { const m = new Matter(this); m.name = midPaths[midPaths.length - 1]; m.puuid = j > 1 ? dirPathUuidMap[midPaths.slice(0, j - 1).join("/")] : this.matter.uuid!; m.userUuid = this.user.uuid!; await m.httpCreateDirectory( () => { dirPathUuidMap[midPathStr] = m.uuid; }, (msg: string) => { this.uploadErrorLogs.push([ file.name, file.webkitRelativePath, msg, ]); } ); } } } if (dirPathUuidMap[pPathStr]) { this.launchUpload(file, dirPathUuidMap[pPathStr], (msg?: string) => { this.uploadErrorLogs.push([ file.name, file.webkitRelativePath, `${msg}`, ]); }); } } } launchUpload( f: File | FileList, puuid = this.matter.uuid!, errHandle = () => {} ) { const files = f instanceof FileList ? f : [f]; for (let i = 0; i < files.length; i++) { const file = files[i]; const m = new Matter(this); m.dir = false; m.puuid = puuid; m.userUuid = this.user.uuid!; //判断文件大小。 if (this.user.sizeLimit >= 0) { if (file.size > this.user.sizeLimit) { MessageBoxUtil.error( Lang.t( "matter.sizeExceedLimit", StringUtil.humanFileSize(file.size), StringUtil.humanFileSize(this.user.sizeLimit) ) ); } } m.file = file; m.httpUpload( () => { const index = List.uploadMatters.findIndex((matter) => matter === m); List.uploadMatters.splice(index, 1); List.instance!.refresh(); }, (msg: string) => { List.instance!.updateUI(); SafeUtil.safeCallback(errHandle)(msg); } ); List.uploadMatters.push(m); } } shareBatch() { const uuids = this.selectedMatters.map((i) => i.uuid).join(","); ShareOperationModal.open((share: Share) => { share.httpCreate(uuids, () => { ShareDialogModal.open(share); }); }); }; searchFile(value?: string) { this.pager.resetFilter(); if (value) { this.pager.setFilterValue("orderCreateTime", SortDirection.DESC); this.pager.setFilterValue("orderDir", SortDirection.DESC); this.pager.setFilterValue("name", value); this.pager.httpList(); } else { this.refresh(); } }; changeSearch(e: any) { if (!e.currentTarget.value) this.searchFile(); }; changePage(page: number) { this.pager.page = page - 1; // page的页数0基 this.pager.httpList(); this.updateUI(); }; createDirectory() { this.newMatter.name = "matter.allFiles"; this.newMatter.dir = true; this.newMatter.editMode = true; this.newMatter.puuid = this.matter.uuid || "root"; this.newMatter.userUuid = this.user.uuid!; this.director.createMode = true; this.updateUI(); setTimeout(() => this.newMatterRef.current!.highLight()); }; previewImage(matter: Matter) { let imageArray: string[] = []; let startIndex = -1; this.pager.data.forEach((item) => { if (item.isImage()) { imageArray.push(item.getPreviewUrl()); if (item.uuid === matter.uuid) { startIndex = imageArray.length - 1; } } }); ImagePreviewer.showMultiPhoto(imageArray, startIndex); }; goToDirectory(id: string) { this.searchText = null; this.pager.setFilterValue("puuid", id); this.pager.page = 0; const query = this.pager.getParams(); Sun.navigateQueryTo({ path: "/matter/list", query }); this.refresh(); }; //刷新面包屑 refreshBreadcrumbs() { const uuid = this.pager.getFilterValue("puuid") || Matter.MATTER_ROOT; //根目录简单处理即可。 if (uuid === Matter.MATTER_ROOT) { this.matter.uuid = Matter.MATTER_ROOT; this.breadcrumbModels = [ { name: Lang.t("matter.allFiles"), path: "/matter/list", query: {}, displayDirect: true, }, ]; } else { this.matter.uuid = uuid; this.matter.httpDetail(() => { const arr = []; let cur: Matter | null = this.matter; do { arr.push(cur); cur = cur.parent; } while (cur); this.breadcrumbModels = arr.reduceRight( (t: any, item: Matter, i: number) => { const query = this.pager.getParams(); query["puuid"] = item.uuid!; t.push({ name: item.name, path: "/matter/list", query: query, displayDirect: !i, // 当前目录不需要导航 }); return t; }, [ { name: Lang.t("matter.allFiles"), path: "/matter/list", query: {}, displayDirect: false, }, ] ); this.updateUI(); }); } }; render() { const { pager, director, selectedMatters, dragEnterCount } = this; return ( <div className="matter-list"> {dragEnterCount > 0 ? ( <div className="obscure"> <CloudUploadOutlined className="white f50" /> </div> ) : null} <BreadcrumbPanel breadcrumbModels={this.breadcrumbModels} /> <Row className="mt10"> <Col xs={24} sm={24} md={14} lg={16}> <Space className="buttons"> {selectedMatters.length !== pager.data.length ? ( <Button type="primary" className="mb10" onClick={() => this.checkAll()} > <PlusSquareOutlined /> {Lang.t("selectAll")} </Button> ) : null} {pager.data.length && selectedMatters.length === pager.data.length ? ( <Button type="primary" className="mb10" onClick={() => this.checkNone()} > <MinusSquareOutlined /> {Lang.t("cancel")} </Button> ) : null} {selectedMatters.length ? ( <> <Button type="primary" className="mb10" onClick={() => this.deleteBatch()} > <DeleteOutlined /> {Lang.t("delete")} </Button> <Button type="primary" className="mb10" onClick={() => this.downloadZip()} > <DownloadOutlined /> {Lang.t("download")} </Button> <Button type="primary" className="mb10" onClick={() => this.toggleMoveBatch()} > <DragOutlined /> {Lang.t("matter.move")} </Button> <Button type="primary" className="mb10" onClick={() => this.shareBatch()} > <ShareAltOutlined /> {Lang.t("matter.share")} </Button> </> ) : null} <Upload className="ant-upload" customRequest={(e) => this.triggerUpload(e)} showUploadList={false} multiple > <Button type="primary" className="mb10"> <CloudUploadOutlined /> {Lang.t("matter.upload")} </Button> </Upload> <Upload className="ant-upload" customRequest={this.triggerUploadDir} showUploadList={false} directory > <Button type="primary" className="mb10"> <CloudUploadOutlined /> {Lang.t("matter.uploadDir")} </Button> </Upload> <Button type="primary" className="mb10" onClick={() => this.createDirectory()} > <FolderOutlined /> {Lang.t("matter.create")} </Button> <Button type="primary" className="mb10" onClick={() => this.refresh()} > <SyncOutlined /> {Lang.t("refresh")} </Button> </Space> </Col> <Col xs={24} sm={24} md={10} lg={8}> <Input.Search className="mb10" placeholder={Lang.t("matter.searchFile")} onSearch={(value) => this.searchFile(value)} onChange={e => this.changeSearch(e)} enterButton /> </Col> </Row> {Children.toArray( List.uploadMatters.map((m) => <UploadMatterPanel matter={m} />) )} {pager.data.length ? ( <MatterSortPanel pager={pager} refresh={() => this.refresh()} /> ) : null} {director.createMode ? ( <MatterPanel ref={this.newMatterRef} matter={this.newMatter} director={director} onCreateDirectoryCallback={() => this.refresh()} /> ) : null} <div> {pager.loading || pager.data.length ? ( pager.data.map((matter) => ( <MatterPanel key={matter.uuid!} director={director} matter={matter} onGoToDirectory={id => this.goToDirectory(id)} onDeleteSuccess={() => this.refresh()} onCheckMatter={m => this.checkMatter(m)} onPreviewImage={m => this.previewImage(m)} /> )) ) : ( <Empty description={Lang.t("matter.noContentYet")} /> )} </div> <Pagination className="mt10 pull-right" onChange={page => this.changePage(page)} current={pager.page + 1} total={pager.totalItems} pageSize={pager.pageSize} hideOnSinglePage /> </div> ); } }
the_stack
import * as React from 'react'; import identity from 'lodash/identity'; import { render, configure, cleanup, wait, fireEvent } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import { SlugEditor } from './SlugEditor'; import { createFakeFieldAPI, createFakeLocalesAPI } from '@contentful/field-editor-test-utils'; configure({ testIdAttribute: 'data-test-id', }); jest.mock( 'lodash/throttle', () => ({ default: identity, }), { virtual: true } ); jest.mock('use-debounce', () => ({ useDebounce: (text: string) => [text], })); function createMocks( initialValues: { field?: string; titleField?: string; descriptionField?: string } = {} ) { const [field] = createFakeFieldAPI( (field) => ({ ...field, id: 'slug-id', onValueChanged: jest.fn().mockImplementation(field.onValueChanged), setValue: jest.fn().mockImplementation(field.setValue), }), initialValues.field || '' ); const [titleField] = createFakeFieldAPI( (field) => ({ ...field, id: 'title-id', setValue: jest.fn().mockImplementation(field.setValue), getValue: jest.fn().mockImplementation(field.getValue), onValueChanged: jest.fn().mockImplementation(field.onValueChanged), }), initialValues.titleField || '' ); const [descriptionField] = createFakeFieldAPI( (field) => ({ ...field, id: 'description-id', setValue: jest.fn().mockImplementation(field.setValue), getValue: jest.fn().mockImplementation(field.getValue), onValueChanged: jest.fn().mockImplementation(field.onValueChanged), }), initialValues.descriptionField || '' ); const sdk = { locales: createFakeLocalesAPI(), space: { getEntries: jest.fn().mockResolvedValue({ total: 0 }), }, entry: { getSys: jest.fn().mockReturnValue({ id: 'entry-id', publishedVersion: undefined, createdAt: '2020-01-24T15:33:47.906Z', contentType: { sys: { id: 'content-type-id', }, }, }), onSysChanged: jest.fn(), fields: { 'title-id': titleField, 'entry-id': field, 'description-id': descriptionField, }, }, contentType: { displayField: 'title-id', }, }; return { field, titleField, descriptionField, sdk, }; } describe('SlugEditor', () => { afterEach(cleanup); describe('should not subscribe to title changes', () => { it('when entry is published', async () => { const { field, titleField, sdk } = createMocks(); sdk.entry.getSys.mockReturnValue({ publishedVersion: 2, }); render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); expect(field.setValue).not.toHaveBeenCalled(); expect(titleField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(sdk.space.getEntries).not.toHaveBeenCalled(); expect(sdk.entry.fields['title-id'].getValue).toHaveBeenCalledTimes(1); expect(sdk.entry.getSys).toHaveBeenCalledTimes(2); }); it('when title and slug are the same field', async () => { const { field, titleField, sdk } = createMocks(); sdk.contentType.displayField = 'entry-id'; render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); expect(titleField.onValueChanged).not.toHaveBeenCalled(); expect(field.setValue).not.toHaveBeenCalled(); }); it('when a saved slug is different from a title at the render', async () => { const { field, titleField, sdk } = createMocks({ titleField: 'Hello world!', field: 'something-different', }); render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); expect(titleField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(field.setValue).not.toHaveBeenCalled(); }); }); describe('should check for uniqueness', () => { it('if it is published', async () => { const { field, titleField, sdk } = createMocks({ titleField: 'Slug value', field: 'slug-value', }); sdk.entry.getSys.mockReturnValue({ id: 'entry-id', publishedVersion: 2, contentType: { sys: { id: 'content-type-id', }, }, }); sdk.space.getEntries.mockResolvedValue({ total: 0 }); const { queryByTestId, queryByText } = render( <SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} /> ); await wait(); expect(titleField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(sdk.space.getEntries).toHaveBeenLastCalledWith({ content_type: 'content-type-id', 'fields.slug-id.en-US': 'slug-value', limit: 0, 'sys.id[ne]': 'entry-id', 'sys.publishedAt[exists]': true, }); expect(sdk.space.getEntries).toHaveBeenCalledTimes(1); expect(queryByTestId('slug-editor-spinner')).not.toBeInTheDocument(); expect( queryByText('This slug has already been published in another entry') ).not.toBeInTheDocument(); }); it('if it is not published', async () => { const { field, titleField, sdk } = createMocks({ titleField: 'Slug value', field: 'slug-value', }); sdk.entry.getSys.mockReturnValue({ id: 'entry-id', publishedVersion: undefined, contentType: { sys: { id: 'content-type-id', }, }, }); sdk.space.getEntries.mockResolvedValue({ total: 2 }); const { queryByTestId, queryByText, getByTestId } = render( <SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} /> ); await wait(); expect(titleField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(sdk.space.getEntries).toHaveBeenLastCalledWith({ content_type: 'content-type-id', 'fields.slug-id.en-US': 'slug-value', limit: 0, 'sys.id[ne]': 'entry-id', 'sys.publishedAt[exists]': true, }); expect(sdk.space.getEntries).toHaveBeenCalledTimes(1); expect(queryByTestId('slug-editor-spinner')).not.toBeInTheDocument(); expect( queryByText('This slug has already been published in another entry') ).toBeInTheDocument(); expect(getByTestId('cf-ui-text-input')).toHaveValue('slug-value'); sdk.space.getEntries.mockResolvedValue({ total: 0 }); fireEvent.change(getByTestId('cf-ui-text-input'), { target: { value: '123' } }); await wait(); expect(field.setValue).toHaveBeenCalledTimes(1); expect(field.setValue).toHaveBeenCalledWith('123'); expect(sdk.space.getEntries).toHaveBeenCalledTimes(2); expect(sdk.space.getEntries).toHaveBeenLastCalledWith({ content_type: 'content-type-id', 'fields.slug-id.en-US': '123', limit: 0, 'sys.id[ne]': 'entry-id', 'sys.publishedAt[exists]': true, }); expect( queryByText('This slug has already been published in another entry') ).not.toBeInTheDocument(); }); }); describe('should react to title changes', () => { it('when field is disabled', async () => { const { field, titleField, sdk } = createMocks({ field: '', titleField: '', }); render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={true} />); await wait(); expect(field.setValue).toHaveBeenCalled(); expect(titleField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(sdk.space.getEntries).toHaveBeenCalled(); expect(sdk.entry.fields['title-id'].getValue).toHaveBeenCalledTimes(1); expect(sdk.entry.getSys).toHaveBeenCalledTimes(2); }); it('should generate unique value with date if title is empty', async () => { const { field, titleField, sdk } = createMocks({ field: '', titleField: '', }); render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); expect(titleField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(field.setValue).toHaveBeenCalledTimes(1); expect(field.setValue).toHaveBeenLastCalledWith('untitled-entry-2020-01-24-at-15-33-47'); await sdk.entry.fields['title-id'].setValue('Hello world!'); await wait(); expect(field.setValue).toHaveBeenCalledTimes(2); expect(field.setValue).toHaveBeenLastCalledWith('hello-world'); expect(sdk.space.getEntries).toHaveBeenCalledTimes(2); await sdk.entry.fields['title-id'].setValue('фраза написанная по русски'); await wait(); expect(field.setValue).toHaveBeenCalledTimes(3); expect(field.setValue).toHaveBeenLastCalledWith('fraza-napisannaya-po-russki'); expect(sdk.space.getEntries).toHaveBeenCalledTimes(3); }); it('should generate value from title if it is not empty', async () => { const { field, titleField, sdk } = createMocks({ field: '', titleField: 'This is initial title value', }); render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); expect(titleField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(field.setValue).toHaveBeenCalledTimes(1); expect(field.setValue).toHaveBeenLastCalledWith('this-is-initial-title-value'); await sdk.entry.fields['title-id'].setValue('Hello world!'); await wait(); expect(field.setValue).toHaveBeenCalledTimes(2); expect(field.setValue).toHaveBeenLastCalledWith('hello-world'); expect(sdk.space.getEntries).toHaveBeenCalledTimes(2); }); it('should stop tracking value after user intentionally changes slug value', async () => { const { field, titleField, sdk } = createMocks({ field: '', titleField: '', }); const { getByTestId } = render( <SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} /> ); await wait(); await sdk.entry.fields['title-id'].setValue('Hello world!'); await wait(); expect(titleField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(field.setValue).toHaveBeenCalledTimes(2); expect(field.setValue).toHaveBeenCalledWith('untitled-entry-2020-01-24-at-15-33-47'); expect(field.setValue).toHaveBeenLastCalledWith('hello-world'); expect(sdk.space.getEntries).toHaveBeenCalledTimes(2); fireEvent.change(getByTestId('cf-ui-text-input'), { target: { value: 'new-custom-slug' } }); await wait(); expect(field.setValue).toHaveBeenCalledTimes(3); expect(field.setValue).toHaveBeenLastCalledWith('new-custom-slug'); await sdk.entry.fields['title-id'].setValue('I decided to update my title'); await wait(); expect(field.setValue).toHaveBeenCalledTimes(3); await sdk.entry.fields['title-id'].setValue('I decided to update my title again'); await wait(); expect(field.setValue).toHaveBeenCalledTimes(3); }); it('should start tracking again after potential slug equals real one', async () => { const { field, sdk } = createMocks({ field: '', titleField: '', }); const { getByTestId } = render( <SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} /> ); await wait(); /* Type title "ABC DEF" -> Slug changes to "abc-def" */ await sdk.entry.fields['title-id'].setValue('ABC DEF'); await wait(); expect(field.setValue).toHaveBeenLastCalledWith('abc-def'); expect(field.setValue).toHaveBeenCalledTimes(2); /* Change slug to custom one "abc" */ fireEvent.change(getByTestId('cf-ui-text-input'), { target: { value: 'abc' } }); /* Change title to "ABC D" -> Slug does not change */ await sdk.entry.fields['title-id'].setValue('ABC D'); await wait(); expect(field.setValue).toHaveBeenLastCalledWith('abc'); expect(field.setValue).toHaveBeenCalledTimes(3); /* Change title to "ABC" first and change title to "ABC ABC" -> Slug should change to "abc-abc" as it should have started tracking again */ await sdk.entry.fields['title-id'].setValue('ABC'); await sdk.entry.fields['title-id'].setValue('ABC ABC'); await wait(); expect(field.setValue).toHaveBeenLastCalledWith('abc-abc'); expect(field.setValue).toHaveBeenCalledTimes(4); await wait(); }); }); describe('for non default locales', () => { it('locale is not optional and has no fallback then it should track default locale changes & current locale changes', async () => { const { sdk, field, titleField } = createMocks(); field.locale = 'ru-RU'; field.required = false; sdk.locales.available = ['de-DE', 'ru-RU']; sdk.locales.default = 'de-DE'; sdk.locales.optional = { 'de-DE': false, 'ru-RU': false, }; sdk.locales.fallbacks = { 'de-DE': undefined, 'ru-RU': undefined, }; render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); expect(field.setValue).toHaveBeenCalledWith('untitled-entry-2020-01-24-at-15-33-47'); expect(titleField.onValueChanged).toHaveBeenCalledWith('ru-RU', expect.any(Function)); expect(titleField.onValueChanged).toHaveBeenCalledWith('de-DE', expect.any(Function)); }); it('locale is optional and has a fallback then it should track only current locale changes', async () => { const { sdk, field, titleField } = createMocks(); field.locale = 'ru-RU'; field.required = false; sdk.locales.available = ['de-DE', 'ru-RU']; sdk.locales.default = 'de-DE'; sdk.locales.optional = { 'de-DE': false, 'ru-RU': true, }; sdk.locales.fallbacks = { 'de-DE': undefined, 'ru-RU': 'de-DE', }; render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); expect(field.setValue).not.toHaveBeenCalled(); expect(titleField.onValueChanged).toHaveBeenCalledWith('ru-RU', expect.any(Function)); expect(titleField.onValueChanged).not.toHaveBeenCalledWith('de-DE', expect.any(Function)); }); }); it('slug suggestion is limited to 75 symbols', async () => { const { field, sdk } = createMocks({ field: '', titleField: '', }); render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); await sdk.entry.fields['title-id'].setValue('a'.repeat(80)); await wait(); const expectedSlug = 'a'.repeat(75); expect(field.setValue).toHaveBeenLastCalledWith(expectedSlug); }); it('slug suggestion does not contain cut-off words', async () => { const { field, sdk } = createMocks({ field: '', titleField: '', }); render(<SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} />); await wait(); await sdk.entry.fields['title-id'].setValue(`one two three ${'a'.repeat(80)}`); await wait(); const expectedSlug = 'one-two-three'; expect(field.setValue).toHaveBeenLastCalledWith(expectedSlug); }); it('should subscribe for changes in custom field id', async () => { const { field, titleField, descriptionField, sdk } = createMocks({ field: '', titleField: 'This is initial title value', descriptionField: 'This is initial description value', }); render( <SlugEditor field={field} baseSdk={sdk as any} isInitiallyDisabled={false} parameters={{ instance: { trackingFieldId: 'description-id' } }} /> ); await wait(); expect(titleField.onValueChanged).not.toHaveBeenCalled(); expect(descriptionField.onValueChanged).toHaveBeenCalledWith('en-US', expect.any(Function)); expect(field.setValue).toHaveBeenCalledTimes(1); expect(field.setValue).toHaveBeenLastCalledWith('this-is-initial-description-value'); await sdk.entry.fields['description-id'].setValue('Hello world!'); await wait(); expect(field.setValue).toHaveBeenCalledTimes(2); expect(field.setValue).toHaveBeenLastCalledWith('hello-world'); expect(sdk.space.getEntries).toHaveBeenCalledTimes(2); }); });
the_stack
import {luma, Device, DeviceProps} from '@luma.gl/api'; import {requestAnimationFrame, cancelAnimationFrame} from '@luma.gl/api'; import {Timeline} from '../animation/timeline'; import {AnimationProps} from '../lib/animation-props'; import {Stats, Stat} from '@probe.gl/stats'; import {isBrowser} from '@probe.gl/env'; const isPage = isBrowser() && typeof document !== 'undefined'; let statIdCounter = 0; type ContextProps = DeviceProps; /** AnimationLoop properties */ export type AnimationLoopProps = { onCreateDevice?: (props: DeviceProps) => Promise<Device>; onAddHTML?: (div: HTMLDivElement) => string; // innerHTML onInitialize?: (animationProps: AnimationProps) => void; onRender?: (animationProps: AnimationProps) => void; onFinalize?: (animationProps: AnimationProps) => void; onError?: (reason: Error) => void; device?: Device; deviceProps?: DeviceProps; stats?: Stats; // view parameters debug?: boolean; autoResizeViewport?: boolean; autoResizeDrawingBuffer?: boolean; useDevicePixels?: number | boolean; }; const DEFAULT_ANIMATION_LOOP_PROPS: Required<AnimationLoopProps> = { onCreateDevice: (props: DeviceProps): Promise<Device> => luma.createDevice(props), onAddHTML: undefined, onInitialize: () => ({}), onRender: () => {}, onFinalize: () => {}, onError: (error) => console.error(error), // eslint-disable-line no-console device: undefined, deviceProps: {}, debug: false, stats: luma.stats.get(`animation-loop-${statIdCounter++}`), // view parameters useDevicePixels: true, autoResizeViewport: true, autoResizeDrawingBuffer: true, }; /** Convenient animation loop */ export default class AnimationLoop { device: Device; canvas: HTMLCanvasElement; // | OffscreenCanvas; props: Required<AnimationLoopProps>; animationProps: AnimationProps; timeline: Timeline = null; stats: Stats; cpuTime: Stat; gpuTime: Stat; frameRate: Stat; display: any; needsRedraw: string | null = 'initialized'; _initialized: boolean = false; _running: boolean = false; _animationFrameId = null; _nextFramePromise: Promise<AnimationLoop> | null = null; _resolveNextFrame: ((AnimationLoop) => void) | null = null; _cpuStartTime: number = 0; // _gpuTimeQuery: Query | null = null; /* * @param {HTMLCanvasElement} canvas - if provided, width and height will be passed to context */ constructor(props: AnimationLoopProps = {}) { this.props = {...DEFAULT_ANIMATION_LOOP_PROPS, ...props}; props = this.props; let {useDevicePixels = true} = this.props; // state this.device = props.device; // @ts-expect-error this.gl = (this.device && this.device.gl) || props.gl; this.stats = props.stats; this.cpuTime = this.stats.get('CPU Time'); this.gpuTime = this.stats.get('GPU Time'); this.frameRate = this.stats.get('Frame Rate'); this.setProps({ autoResizeViewport: props.autoResizeViewport, autoResizeDrawingBuffer: props.autoResizeDrawingBuffer, useDevicePixels }); // Bind methods this.start = this.start.bind(this); this.stop = this.stop.bind(this); this._onMousemove = this._onMousemove.bind(this); this._onMouseleave = this._onMouseleave.bind(this); } destroy(): void { this.stop(); this._setDisplay(null); } /** @deprecated Use .destroy() */ delete(): void { this.destroy(); } setNeedsRedraw(reason: string): this { this.needsRedraw = this.needsRedraw || reason; return this; } // TODO - move to CanvasContext setProps(props: AnimationLoopProps): this { if ('autoResizeViewport' in props) { this.props.autoResizeViewport = props.autoResizeViewport; } if ('autoResizeDrawingBuffer' in props) { this.props.autoResizeDrawingBuffer = props.autoResizeDrawingBuffer; } if ('useDevicePixels' in props) { this.props.useDevicePixels = props.useDevicePixels; } return this; } /** Starts a render loop if not already running */ async start() { if (this._running) { return this; } this._running = true; try { // check that we haven't been stopped if (!this._running) { return null; } let appContext; if (!this._initialized) { this._initialized = true; // Create the WebGL context await this._createDevice(); this._initialize(); // Note: onIntialize can return a promise (e.g. in case app needs to load resources) await this.onInitialize(this.animationProps); } // check that we haven't been stopped if (!this._running) { return null; } // Start the loop if (appContext !== false) { // cancel any pending renders to ensure only one loop can ever run this._cancelAnimationFrame(); this._requestAnimationFrame(); } return this; } catch (err: unknown) { const error = err instanceof Error ? err : new Error('Unknown error') this.props.onError(error); // this._running = false; // TODO throw error; } } /** Explicitly draw a frame */ redraw(): this { if (this.device.isLost) { return this; } this._beginTimers(); this._setupFrame(); this._updateCallbackData(); this._renderFrame(this.animationProps); // clear needsRedraw flag this._clearNeedsRedraw(); if (this._resolveNextFrame) { this._resolveNextFrame(this); this._nextFramePromise = null; this._resolveNextFrame = null; } this._endTimers(); return this; } // Stops a render loop if already running, finalizing stop() { // console.debug(`Stopping ${this.constructor.name}`); if (this._running) { // call callback this.onFinalize(this.animationProps); this._cancelAnimationFrame(); this._nextFramePromise = null; this._resolveNextFrame = null; this._running = false; } return this; } attachTimeline(timeline: Timeline): Timeline { this.timeline = timeline; return this.timeline; } detachTimeline(): void { this.timeline = null; } waitForRender(): Promise<AnimationLoop> { this.setNeedsRedraw('waitForRender'); if (!this._nextFramePromise) { this._nextFramePromise = new Promise((resolve) => { this._resolveNextFrame = resolve; }); } return this._nextFramePromise; } async toDataURL() { this.setNeedsRedraw('toDataURL'); await this.waitForRender(); return this.canvas.toDataURL(); } onCreateDevice(deviceProps: DeviceProps): Promise<Device> { return this.props.onCreateDevice(deviceProps); } onInitialize(animationProps: AnimationProps): {} | void { return this.props.onInitialize(animationProps); } onRender(animationProps: AnimationProps) { return this.props.onRender(animationProps); } onFinalize(animationProps: AnimationProps) { return this.props.onFinalize(animationProps); } // PRIVATE METHODS _initialize() { this._startEventHandling(); // Initialize the callback data this._initializeCallbackData(); this._updateCallbackData(); // Default viewport setup, in case onInitialize wants to render this._resizeCanvasDrawingBuffer(); this._resizeViewport(); // this._gpuTimeQuery = Query.isSupported(this.gl, ['timers']) ? new Query(this.gl) : null; } _setDisplay(display) { if (this.display) { this.display.delete(); this.display.animationLoop = null; } // store animation loop on the display if (display) { display.animationLoop = this; } this.display = display; } _requestAnimationFrame() { if (!this._running) { return; } // VR display has a separate animation frame to sync with headset // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/ // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame // if (this.display && this.display.requestAnimationFrame) { // this._animationFrameId = this.display.requestAnimationFrame(this._animationFrame.bind(this)); // } this._animationFrameId = requestAnimationFrame(this._animationFrame.bind(this)); } _cancelAnimationFrame() { if (this._animationFrameId !== null) { return; } // VR display has a separate animation frame to sync with headset // TODO WebVR API discontinued, replaced by WebXR: https://immersive-web.github.io/webxr/ // See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/requestAnimationFrame // if (this.display && this.display.cancelAnimationFrame) { // this.display.cancelAnimationFrame(this._animationFrameId); // } cancelAnimationFrame(this._animationFrameId); this._animationFrameId = null; } _animationFrame() { if (!this._running) { return; } this.redraw(); this._requestAnimationFrame(); } // Called on each frame, can be overridden to call onRender multiple times // to support e.g. stereoscopic rendering _renderFrame(props: AnimationProps) { // Allow e.g. VR display to render multiple frames. if (this.display) { this.display._renderFrame(props); return; } // call callback this.onRender(props); // end callback } _clearNeedsRedraw() { this.needsRedraw = null; } _setupFrame() { this._resizeCanvasDrawingBuffer(); this._resizeViewport(); } // Initialize the object that will be passed to app callbacks _initializeCallbackData() { this.animationProps = { animationLoop: this, device: this.device, canvas: this.device.canvasContext.canvas, timeline: this.timeline, // Initial values useDevicePixels: this.props.useDevicePixels, needsRedraw: null, // Placeholders width: 1, height: 1, aspect: 1, // Animation props time: 0, startTime: Date.now(), engineTime: 0, tick: 0, tock: 0, // Experimental _mousePosition: null // Event props }; } // Update the context object that will be passed to app callbacks _updateCallbackData() { const {width, height, aspect} = this._getSizeAndAspect(); if (width !== this.animationProps.width || height !== this.animationProps.height) { this.setNeedsRedraw('drawing buffer resized'); } if (aspect !== this.animationProps.aspect) { this.setNeedsRedraw('drawing buffer aspect changed'); } this.animationProps.width = width; this.animationProps.height = height; this.animationProps.aspect = aspect; this.animationProps.needsRedraw = this.needsRedraw; // Update time properties this.animationProps.engineTime = Date.now() - this.animationProps.startTime; if (this.timeline) { this.timeline.update(this.animationProps.engineTime); } this.animationProps.tick = Math.floor((this.animationProps.time / 1000) * 60); this.animationProps.tock++; // For back compatibility this.animationProps.time = this.timeline ? this.timeline.getTime() : this.animationProps.engineTime; } /** Either uses supplied or existing context, or calls provided callback to create one */ async _createDevice() { const deviceProps = {...this.props, ...this.props.deviceProps}; this.device = await this.onCreateDevice(deviceProps); // @ts-expect-error this.canvas = this.device.canvasContext.canvas; this._createInfoDiv(); } _createInfoDiv() { if (this.canvas && this.props.onAddHTML) { const wrapperDiv = document.createElement('div'); document.body.appendChild(wrapperDiv); wrapperDiv.style.position = 'relative'; const div = document.createElement('div'); div.style.position = 'absolute'; div.style.left = '10px'; div.style.bottom = '10px'; div.style.width = '300px'; div.style.background = 'white'; wrapperDiv.appendChild(this.canvas); wrapperDiv.appendChild(div); const html = this.props.onAddHTML(div); if (html) { div.innerHTML = html; } } } _getSizeAndAspect() { // https://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html const [width, height] = this.device.canvasContext.getPixelSize(); // https://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html let aspect = 1; const canvas = this.device.canvasContext.canvas; // @ts-expect-error if (canvas && canvas.clientHeight) { // @ts-expect-error aspect = canvas.clientWidth / canvas.clientHeight; } else if (width > 0 && height > 0) { aspect = width / height; } return {width, height, aspect}; } /** Default viewport setup */ _resizeViewport() { // @ts-expect-error Expose on canvasContext if (this.props.autoResizeViewport && this.device.gl) { // @ts-expect-error Expose canvasContext this.device.gl.viewport(0, 0, this.device.gl.drawingBufferWidth, this.device.gl.drawingBufferHeight); } } /** * Resize the render buffer of the canvas to match canvas client size * Optionally multiplying with devicePixel ratio */ _resizeCanvasDrawingBuffer() { if (this.props.autoResizeDrawingBuffer) { this.device.canvasContext.resize({useDevicePixels: this.props.useDevicePixels}); } } _beginTimers() { this.frameRate.timeEnd(); this.frameRate.timeStart(); // Check if timer for last frame has completed. // GPU timer results are never available in the same // frame they are captured. // if ( // this._gpuTimeQuery && // this._gpuTimeQuery.isResultAvailable() && // !this._gpuTimeQuery.isTimerDisjoint() // ) { // this.stats.get('GPU Time').addTime(this._gpuTimeQuery.getTimerMilliseconds()); // } // if (this._gpuTimeQuery) { // // GPU time query start // this._gpuTimeQuery.beginTimeElapsedQuery(); // } // this.cpuTime.timeStart(); } _endTimers() { this.cpuTime.timeEnd(); // if (this._gpuTimeQuery) { // // GPU time query end. Results will be available on next frame. // this._gpuTimeQuery.end(); // } } // Event handling _startEventHandling() { if (this.canvas) { this.canvas.addEventListener('mousemove', this._onMousemove); this.canvas.addEventListener('mouseleave', this._onMouseleave); } } _onMousemove(e) { this.animationProps._mousePosition = [e.offsetX, e.offsetY]; } _onMouseleave(e) { this.animationProps._mousePosition = null; } }
the_stack
import { ModelInit, MutableModel, Schema, InternalSchema, SchemaModel, } from '../src/types'; /** * Convenience function to wait for a number of ms. * * Intended as a cheap way to wait for async operations to settle. * * @param ms number of ms to pause for */ export async function pause(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } /** * Case insensitive regex that matches GUID's and UUID's. * It does NOT permit whitespace on either end of the string. The caller must `trim()` first as-needed. */ export const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** * Tests a mutation for expected values. If values are present on the mutation * that are not expected, throws an error. Expected values can be listed as a * literal value, a regular expression, or a function (v => bool). * * `id` is automatically tested and expected to be a UUID unless an alternative * matcher is provided. * * @param mutation A mutation record to check * @param values An object for specific values to test. Format of key: value | regex | v => bool */ export function expectMutation(mutation, values) { const data = JSON.parse(mutation.data); const matchers = { id: UUID_REGEX, ...values, }; const errors = [ ...errorsFrom(data, matchers), ...extraFieldsFrom(data, matchers).map(f => `Unexpected field: ${f}`), ]; if (errors.length > 0) { throw new Error( `Bad mutation: ${JSON.stringify(data, null, 2)}\n${errors.join('\n')}` ); } } /** * Checks an object for adherence to expected values from a set of matchers. * Returns a list of erroneous key-value pairs. * @param data the object to validate. * @param matchers the matcher functions/values/regexes to test the object with */ export function errorsFrom(data, matchers) { return Object.entries(matchers).reduce((errors, [property, matcher]) => { const value = data[property]; if ( !( (typeof matcher === 'function' && matcher(value)) || (matcher instanceof RegExp && matcher.test(value)) || value === matcher ) ) { errors.push( `Property '${property}' value "${value}" does not match "${matcher}"` ); } return errors; }, []); } /** * Checks to see if a given object contains any extra, unexpected properties. * If any are present, it returns the list of unexpectd fields. * * @param data the object that MIGHT contain extra fields. * @param template the authorative template object. */ export function extraFieldsFrom(data, template) { const fields = Object.keys(data); const expectedFields = new Set(Object.keys(template)); return fields.filter(name => !expectedFields.has(name)); } export declare class Model { public readonly id: string; public readonly field1: string; public readonly optionalField1?: string; public readonly dateCreated: string; public readonly emails?: string[]; public readonly ips?: (string | null)[]; public readonly metadata?: Metadata; public readonly createdAt?: string; public readonly updatedAt?: string; constructor(init: ModelInit<Model>); static copyOf( src: Model, mutator: (draft: MutableModel<Model>) => void | Model ): Model; } export declare class Metadata { readonly author: string; readonly tags?: string[]; readonly rewards: string[]; readonly penNames: string[]; readonly nominations?: string[]; readonly misc?: (string | null)[]; constructor(init: Metadata); } export declare class Post { public readonly id: string; public readonly title: string; } export declare class Comment { public readonly id: string; public readonly content: string; public readonly post: Post; } export declare class User { public readonly id: string; public readonly name: string; public readonly profile?: Profile; public readonly profileID?: string; } export declare class Profile { public readonly id: string; public readonly firstName: string; public readonly lastName: string; } export declare class PostComposite { public readonly id: string; public readonly title: string; public readonly description: string; public readonly created: string; public readonly sort: number; } export declare class PostCustomPK { public readonly id: string; public readonly postId: number; public readonly title: string; public readonly description?: string; } export declare class PostCustomPKSort { public readonly id: string; public readonly postId: number; public readonly title: string; public readonly description?: string; } export declare class PostCustomPKComposite { public readonly id: string; public readonly postId: number; public readonly title: string; public readonly description?: string; public readonly sort: number; } export function testSchema(): Schema { return { enums: {}, models: { Model: { name: 'Model', pluralName: 'Models', syncable: true, fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, }, field1: { name: 'field1', isArray: false, type: 'String', isRequired: true, }, optionalField1: { name: 'optionalField1', isArray: false, type: 'String', isRequired: false, }, dateCreated: { name: 'dateCreated', isArray: false, type: 'AWSDateTime', isRequired: true, attributes: [], }, emails: { name: 'emails', isArray: true, type: 'AWSEmail', isRequired: true, attributes: [], isArrayNullable: true, }, ips: { name: 'ips', isArray: true, type: 'AWSIPAddress', isRequired: false, attributes: [], isArrayNullable: true, }, metadata: { name: 'metadata', isArray: false, type: { nonModel: 'Metadata', }, isRequired: false, attributes: [], }, createdAt: { name: 'createdAt', isArray: false, type: 'AWSDateTime', isRequired: false, attributes: [], isReadOnly: true, }, updatedAt: { name: 'updatedAt', isArray: false, type: 'AWSDateTime', isRequired: false, attributes: [], isReadOnly: true, }, }, }, Post: { name: 'Post', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, comments: { name: 'comments', isArray: true, type: { model: 'Comment', }, isRequired: true, attributes: [], isArrayNullable: true, association: { connectionType: 'HAS_MANY', associatedWith: 'postId', }, }, }, syncable: true, pluralName: 'Posts', attributes: [ { type: 'model', properties: {}, }, ], }, Comment: { name: 'Comment', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, content: { name: 'content', isArray: false, type: 'String', isRequired: true, attributes: [], }, post: { name: 'post', isArray: false, type: { model: 'Post', }, isRequired: false, attributes: [], association: { connectionType: 'BELONGS_TO', targetName: 'postId', }, }, }, syncable: true, pluralName: 'Comments', attributes: [ { type: 'model', properties: {}, }, { type: 'key', properties: { name: 'byPost', fields: ['postId'], }, }, ], }, LocalModel: { name: 'LocalModel', pluralName: 'LocalModels', syncable: false, fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, }, field1: { name: 'field1', isArray: false, type: 'String', isRequired: true, }, }, }, User: { name: 'User', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, name: { name: 'name', isArray: false, type: 'String', isRequired: false, attributes: [], }, profileID: { name: 'profileID', isArray: false, type: 'ID', isRequired: true, attributes: [], }, profile: { name: 'profile', isArray: false, type: { model: 'Profile', }, isRequired: false, attributes: [], association: { connectionType: 'HAS_ONE', associatedWith: 'id', targetName: 'profileID', }, }, }, syncable: true, pluralName: 'Users', attributes: [ { type: 'model', properties: {}, }, ], }, Profile: { name: 'Profile', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, firstName: { name: 'firstName', isArray: false, type: 'String', isRequired: true, attributes: [], }, lastName: { name: 'lastName', isArray: false, type: 'String', isRequired: true, attributes: [], }, }, syncable: true, pluralName: 'Profiles', attributes: [ { type: 'model', properties: {}, }, ], }, PostComposite: { name: 'PostComposite', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, description: { name: 'description', isArray: false, type: 'String', isRequired: false, attributes: [], }, created: { name: 'created', isArray: false, type: 'String', isRequired: false, attributes: [], }, sort: { name: 'sort', isArray: false, type: 'Int', isRequired: false, attributes: [], }, }, syncable: true, pluralName: 'PostComposites', attributes: [ { type: 'model', properties: {}, }, { type: 'key', properties: { name: 'titleCreatedSort', fields: ['title', 'created', 'sort'], }, }, ], }, PostCustomPK: { name: 'PostCustomPK', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, postId: { name: 'postId', isArray: false, type: 'Int', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, description: { name: 'description', isArray: false, type: 'String', isRequired: false, attributes: [], }, }, syncable: true, pluralName: 'PostCustomPKS', attributes: [ { type: 'model', properties: {}, }, { type: 'key', properties: { fields: ['postId'], }, }, ], }, PostCustomPKSort: { name: 'PostCustomPKSort', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, postId: { name: 'postId', isArray: false, type: 'Int', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, description: { name: 'description', isArray: false, type: 'String', isRequired: false, attributes: [], }, }, syncable: true, pluralName: 'PostCustomPKSorts', attributes: [ { type: 'model', properties: {}, }, { type: 'key', properties: { fields: ['id', 'postId'], }, }, ], }, PostCustomPKComposite: { name: 'PostCustomPKComposite', fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, attributes: [], }, postId: { name: 'postId', isArray: false, type: 'Int', isRequired: true, attributes: [], }, title: { name: 'title', isArray: false, type: 'String', isRequired: true, attributes: [], }, description: { name: 'description', isArray: false, type: 'String', isRequired: false, attributes: [], }, sort: { name: 'sort', isArray: false, type: 'Int', isRequired: true, attributes: [], }, }, syncable: true, pluralName: 'PostCustomPKComposites', attributes: [ { type: 'model', properties: {}, }, { type: 'key', properties: { fields: ['id', 'postId', 'sort'], }, }, ], }, }, nonModels: { Metadata: { name: 'Metadata', fields: { author: { name: 'author', isArray: false, type: 'String', isRequired: true, attributes: [], }, tags: { name: 'tags', isArray: true, type: 'String', isRequired: false, isArrayNullable: true, attributes: [], }, rewards: { name: 'rewards', isArray: true, type: 'String', isRequired: true, attributes: [], }, penNames: { name: 'penNames', isArray: true, type: 'String', isRequired: true, isArrayNullable: true, attributes: [], }, nominations: { name: 'nominations', isArray: true, type: 'String', isRequired: false, attributes: [], }, misc: { name: 'misc', isArray: true, type: 'String', isRequired: false, isArrayNullable: true, attributes: [], }, }, }, }, version: '1', }; } export function internalTestSchema(): InternalSchema { return { namespaces: { datastore: { name: 'datastore', relationships: { Setting: { indexes: [], relationTypes: [], }, }, enums: {}, nonModels: {}, models: { Setting: { name: 'Setting', pluralName: 'Settings', syncable: false, fields: { id: { name: 'id', type: 'ID', isRequired: true, isArray: false, }, key: { name: 'key', type: 'String', isRequired: true, isArray: false, }, value: { name: 'value', type: 'String', isRequired: true, isArray: false, }, }, }, }, }, user: { name: 'user', enums: {}, models: { Model: { name: 'Model', pluralName: 'Models', syncable: true, fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, }, field1: { name: 'field1', isArray: false, type: 'String', isRequired: true, }, optionalField1: { name: 'optionalField1', isArray: false, type: 'String', isRequired: false, }, dateCreated: { name: 'dateCreated', isArray: false, type: 'AWSDateTime', isRequired: true, attributes: [], }, emails: { name: 'emails', isArray: true, type: 'AWSEmail', isRequired: true, attributes: [], isArrayNullable: true, }, ips: { name: 'ips', isArray: true, type: 'AWSIPAddress', isRequired: false, attributes: [], isArrayNullable: true, }, metadata: { name: 'metadata', isArray: false, type: { nonModel: 'Metadata', }, isRequired: false, attributes: [], }, }, }, LocalModel: { name: 'LocalModel', pluralName: 'LocalModels', syncable: false, fields: { id: { name: 'id', isArray: false, type: 'ID', isRequired: true, }, field1: { name: 'field1', isArray: false, type: 'String', isRequired: true, }, }, }, }, nonModels: { Metadata: { name: 'Metadata', fields: { author: { name: 'author', isArray: false, type: 'String', isRequired: true, attributes: [], }, tags: { name: 'tags', isArray: true, type: 'String', isRequired: false, isArrayNullable: true, attributes: [], }, rewards: { name: 'rewards', isArray: true, type: 'String', isRequired: true, attributes: [], }, penNames: { name: 'penNames', isArray: true, type: 'String', isRequired: true, isArrayNullable: true, attributes: [], }, nominations: { name: 'nominations', isArray: true, type: 'String', isRequired: false, attributes: [], }, misc: { name: 'misc', isArray: true, type: 'String', isRequired: false, isArrayNullable: true, attributes: [], }, }, }, }, relationships: { Model: { indexes: [], relationTypes: [], }, LocalModel: { indexes: [], relationTypes: [], }, }, }, sync: { name: 'sync', relationships: { MutationEvent: { indexes: [], relationTypes: [], }, ModelMetadata: { indexes: [], relationTypes: [], }, }, enums: { OperationType: { name: 'OperationType', values: ['CREATE', 'UPDATE', 'DELETE'], }, }, nonModels: {}, models: { MutationEvent: { name: 'MutationEvent', pluralName: 'MutationEvents', syncable: false, fields: { id: { name: 'id', type: 'ID', isRequired: true, isArray: false, }, model: { name: 'model', type: 'String', isRequired: true, isArray: false, }, data: { name: 'data', type: 'String', isRequired: true, isArray: false, }, modelId: { name: 'modelId', type: 'String', isRequired: true, isArray: false, }, operation: { name: 'operation', type: { enum: 'Operationtype', }, isArray: false, isRequired: true, }, condition: { name: 'condition', type: 'String', isArray: false, isRequired: true, }, }, }, ModelMetadata: { name: 'ModelMetadata', pluralName: 'ModelsMetadata', syncable: false, fields: { id: { name: 'id', type: 'ID', isRequired: true, isArray: false, }, namespace: { name: 'namespace', type: 'String', isRequired: true, isArray: false, }, model: { name: 'model', type: 'String', isRequired: true, isArray: false, }, lastSync: { name: 'lastSync', type: 'Int', isRequired: false, isArray: false, }, lastFullSync: { name: 'lastFullSync', type: 'Int', isRequired: false, isArray: false, }, fullSyncInterval: { name: 'fullSyncInterval', type: 'Int', isRequired: true, isArray: false, }, }, }, }, }, }, version: '1', }; }
the_stack
module Fayde.Data { export class BindingExpressionBase extends Expression implements IPropertyPathWalkerListener { //read-only properties ParentBinding: Data.Binding; Target: DependencyObject; Property: DependencyProperty; private PropertyPathWalker: PropertyPathWalker; private _PropertyListener: Providers.IPropertyChangedListener; private _SourceAvailableMonitor: IIsAttachedMonitor; private _IsDataContextBound: boolean; private _DataContext: any; private _TwoWayLostFocusElement: UIElement = null; private _CurrentNotifyError: Data.INotifyDataErrorInfo = null; private _CurrentError: Validation.ValidationError = null; get DataItem (): any { return this.PropertyPathWalker.Source; } private _Cached: boolean = false; private _CachedValue: any = undefined; constructor (binding: Data.Binding) { super(); if (!Object.isFrozen(binding)) Object.freeze(binding); Object.defineProperty(this, "ParentBinding", { value: binding, writable: false }); } private _IsSealed = false; Seal (owner: DependencyObject, prop: any) { if (this._IsSealed) return; this._IsSealed = true; Object.defineProperty(this, "Target", { value: owner, writable: false }); var propd = <DependencyProperty>prop; Object.defineProperty(this, "Property", { value: propd, writable: false }); var binding = this.ParentBinding; var path = binding.Path.Path; if ((!path || path === ".") && binding.Mode === Data.BindingMode.TwoWay) throw new ArgumentException("TwoWay bindings require a non-empty Path."); if (binding.Mode === BindingMode.TwoWay && (owner instanceof Controls.TextBox || owner instanceof Controls.PasswordBox)) this._TwoWayLostFocusElement = <UIElement>owner; this._IsDataContextBound = !binding.ElementName && !binding.Source && !binding.RelativeSource; var bindsToView = propd === DependencyObject.DataContextProperty || propd.GetTargetType() === <any>nullstone.IEnumerable_ || propd.GetTargetType() === <any>Data.ICollectionView_; var walker = this.PropertyPathWalker = new PropertyPathWalker(binding.Path.ParsePath, binding.BindsDirectlyToSource, bindsToView, this._IsDataContextBound); if (binding.Mode !== BindingMode.OneTime) walker.Listen(this); } OnAttached (element: DependencyObject) { if (this.IsAttached) return; if (this.Target && this.Target !== element) throw new Error("Cannot attach BindingExpression to another DependencyObject."); if (Fayde.Data.Debug && window.console) console.log("[BINDING] OnAttached: [" + (<any>element).constructor.name + "] {Path=" + this.ParentBinding.Path.Path + "}"); super.OnAttached(element); this._SourceAvailableMonitor = this.Target.XamlNode.MonitorIsAttached((newIsAttached) => this._OnSourceAvailable()); var source = this._FindSource(); this.PropertyPathWalker.Update(source); if (this._TwoWayLostFocusElement) this._TwoWayLostFocusElement.LostFocus.on(this._TargetLostFocus, this); if (this.ParentBinding.Mode === BindingMode.TwoWay && this.Property.IsCustom) { this._PropertyListener = this.Property.Store.ListenToChanged(this.Target, this.Property, this._UpdateSourceCallback, this); } } GetValue (propd: DependencyProperty): any { if (this._Cached) return this._CachedValue; if (this.PropertyPathWalker.IsPathBroken) { var target = this.Target; if (Data.WarnBrokenPath && target && target.XamlNode.IsAttached) { var fe: FrameworkElement = target instanceof FrameworkElement ? <FrameworkElement>target : null; if (!fe || fe.XamlNode.IsLoaded) console.warn("[BINDING] Path Broken --> Path='" + this.PropertyPathWalker.Path + "'"); } this._CachedValue = null; } else { this._CachedValue = this.PropertyPathWalker.ValueInternal; } this._CachedValue = this._ConvertToType(propd, this._CachedValue); this._Cached = true; return this._CachedValue; } private _OnSourceAvailable () { this._SourceAvailableMonitor.Detach(); var source = this._FindSource(); if (source) this.PropertyPathWalker.Update(source); this._Invalidate(); this.Target.SetValue(this.Property, this); } private _FindSource (): any { if (this.ParentBinding.Source) { return this.ParentBinding.Source; } else if (this.ParentBinding.ElementName != null) { return this._FindSourceByElementName(); } else if (this.ParentBinding.RelativeSource) { return this.ParentBinding.RelativeSource.Find(this.Target); } return this._DataContext; } private _FindSourceByElementName (): XamlObject { var name = this.ParentBinding.ElementName; var xobj: XamlObject = this.Target; if (!xobj) return undefined; var source = xobj.FindName(name, true); if (source) return source; //TODO: Crawl out of ListBoxItem? return undefined; } OnDetached (element: DependencyObject) { if (!this.IsAttached) return; if (Fayde.Data.Debug && window.console) console.log("[BINDING] OnDetached: [" + (<any>element).constructor.name + "] {Path=" + this.ParentBinding.Path.Path + "}"); super.OnDetached(element); if (this._TwoWayLostFocusElement) this._TwoWayLostFocusElement.LostFocus.off(this._TargetLostFocus, this); if (this._CurrentError != null) { var fe = getMentor(element); if (fe) Validation.RemoveError(fe, this._CurrentError); this._CurrentError = null; } if (this._PropertyListener) { this._PropertyListener.Detach(); this._PropertyListener = null; } this.PropertyPathWalker.Update(null); this.Target = undefined; } IsBrokenChanged () { this.Refresh(); } ValueChanged () { this.Refresh(); } UpdateSource () { return this._UpdateSourceObject(); } _TryUpdateSourceObject (value: any) { if (this._ShouldUpdateSource()) this._UpdateSourceObject(value); } private _UpdateSourceCallback (sender, args: IDependencyPropertyChangedEventArgs) { try { if (this._ShouldUpdateSource()) this._UpdateSourceObject(this.Target.GetValue(this.Property)); } catch (err) { console.warn("[BINDING] UpdateSource: " + err.toString()); } } private _TargetLostFocus (sender: any, e: nullstone.IEventArgs) { if (this.ParentBinding.UpdateSourceTrigger === UpdateSourceTrigger.Explicit) return; this._UpdateSourceObject(); } private _ShouldUpdateSource () { if (this.IsUpdating) return false; if (!this._TwoWayLostFocusElement) return this.ParentBinding.UpdateSourceTrigger !== UpdateSourceTrigger.Explicit; return this.ParentBinding.UpdateSourceTrigger === UpdateSourceTrigger.PropertyChanged; } private _UpdateSourceObject (value?: any) { if (value === undefined) value = this.Target.GetValue(this.Property); var binding = this.ParentBinding; if (binding.Mode !== BindingMode.TwoWay) return; var dataError: string = null; var exception: Exception; var oldUpdating = this.IsUpdating; var walker = this.PropertyPathWalker; var node = this.PropertyPathWalker.FinalNode; try { if (this.PropertyPathWalker.IsPathBroken) return; value = this._ConvertFromTargetToSource(binding, node, value); if (this._CachedValue === undefined && value === undefined) return; this.IsUpdating = true; node.SetValue(value); this._CachedValue = value; } catch (err) { if (binding.ValidatesOnExceptions) { if (err instanceof TargetInvocationException) exception = err.InnerException; exception = err; } } finally { this.IsUpdating = oldUpdating; if (binding.ValidatesOnDataErrors && !exception) { dataError = getDataError(walker); } } if (binding.ValidatesOnExceptions) this._MaybeEmitError(null, exception); else if (binding.ValidatesOnDataErrors) this._MaybeEmitError(dataError, exception); } OnDataContextChanged (newDataContext: any) { if (Fayde.Data.Debug && window.console) console.log("[BINDING] DataContextChanged: [" + (<any>this.Target)._ID + ":" + (<any>this.Target).constructor.name + "] {Path=" + this.ParentBinding.Path.Path + "}"); if (this._DataContext === newDataContext) return; this._DataContext = newDataContext; if (!this._IsDataContextBound) return; if (Fayde.Data.IsCounterEnabled) Fayde.Data.DataContextCounter++; try { this.PropertyPathWalker.Update(newDataContext); if (this.ParentBinding.Mode === BindingMode.OneTime) this.Refresh(); } catch (err) { console.warn("[BINDING] DataContextChanged Error: " + err.message); } } private _Invalidate () { this._Cached = false; this._CachedValue = undefined; } Refresh () { var dataError: string = null; var exception: Exception; if (!this.IsAttached) return; var walker = this.PropertyPathWalker; this._AttachToNotifyError(walker.FinalNode.GetSource()); var binding = this.ParentBinding; if (!this.IsUpdating && binding.ValidatesOnDataErrors) dataError = getDataError(walker); var oldUpdating = this.IsUpdating; try { this.IsUpdating = true; this._Invalidate(); this.Target.SetValue(this.Property, this); } catch (err) { if (binding.ValidatesOnExceptions) { exception = err; if (exception instanceof TargetInvocationException) exception = (<TargetInvocationException>exception).InnerException; } else { console.warn(err); } } finally { this.IsUpdating = oldUpdating; } if (binding.ValidatesOnExceptions) this._MaybeEmitError(null, exception); else if (binding.ValidatesOnDataErrors) this._MaybeEmitError(dataError, exception); } private _ConvertFromTargetToSource (binding: Data.Binding, node: IPropertyPathNode, value: any): any { if (binding.TargetNullValue && binding.TargetNullValue === value) value = null; var converter = binding.Converter; if (converter) { value = converter.ConvertBack(value, node.ValueType, binding.ConverterParameter, binding.ConverterCulture); } //TODO: attempt to parse string for target type // We don't have a target type for plain objects //if (value instanceof String) { } return value; } private _ConvertToType (propd: DependencyProperty, value: any): any { var targetType = this.Property.GetTargetType(); try { var binding = this.ParentBinding; if (!this.PropertyPathWalker.IsPathBroken && binding.Converter) { value = binding.Converter.Convert(value, targetType, binding.ConverterParameter, binding.ConverterCulture); } if (value === DependencyProperty.UnsetValue || this.PropertyPathWalker.IsPathBroken) { value = binding.FallbackValue; if (value === undefined) value = propd.DefaultValue; } else if (value == null) { value = binding.TargetNullValue; if (value == null && this._IsDataContextBound && !binding.Path.Path) value = propd.DefaultValue; } else { var format = binding.StringFormat; if (format) { if (format.indexOf("{0") < 0) format = "{0:" + format + "}"; value = Localization.Format(format, value); } } } catch (err) { console.warn("[BINDING]" + err.toString()); value = binding.FallbackValue; } return nullstone.convertAnyToType(value, <Function>targetType); } private _MaybeEmitError (message: string, exception: Exception) { var fe = getMentor(this.Target); if (!fe) return; var error = (exception instanceof Exception || exception instanceof Error) ? exception : null; if (message === "") message = null; var oldError = this._CurrentError; if (message != null) this._CurrentError = new Validation.ValidationError(message, null, this.PropertyPathWalker.FinalPropertyName); else if (error) this._CurrentError = new Validation.ValidationError(null, error, this.PropertyPathWalker.FinalPropertyName); else this._CurrentError = null; Validation.Emit(fe, this.ParentBinding, oldError, this._CurrentError); } private _AttachToNotifyError (element: Data.INotifyDataErrorInfo) { if (!Data.INotifyDataErrorInfo_.is(element)) return; if (element === this._CurrentNotifyError || !this.ParentBinding.ValidatesOnNotifyDataErrors) return; var property = this.PropertyPathWalker.FinalPropertyName; if (this._CurrentNotifyError) { this._CurrentNotifyError.ErrorsChanged.off(this._NotifyErrorsChanged, this); this._MaybeEmitError(null, null); } this._CurrentNotifyError = element; if (element) { element.ErrorsChanged.on(this._NotifyErrorsChanged, this); if (element.HasErrors) { var enu = element.GetErrors(property); if (enu) { for (var en = enu.getEnumerator(); en.moveNext();) { this._MaybeEmitError(en.current, en.current); } } } else { this._MaybeEmitError(null, null); } } } private _NotifyErrorsChanged (sender: any, e: Data.DataErrorsChangedEventArgs) { var property = this.PropertyPathWalker.FinalPropertyName; if (e.PropertyName !== property) return; var errors = this._CurrentNotifyError ? this._CurrentNotifyError.GetErrors(property) : null; if (!errors) { this._MaybeEmitError(null, null); return; } var arr = nullstone.IEnumerable_.toArray(errors); if (arr.length <= 0) { this._MaybeEmitError(null, null); return; } for (var i = 0; i < arr.length; i++) { var cur = arr[i]; this._MaybeEmitError(cur, cur); } } } function getMentor (dobj: DependencyObject): FrameworkElement { for (var cur = <XamlObject>dobj; cur; cur = cur.Parent) { if (cur instanceof FrameworkElement) return <FrameworkElement>cur; } return null; } function getDataError (walker: PropertyPathWalker): string { var info = IDataErrorInfo_.as(walker.FinalNode.GetSource()); var name = walker.FinalPropertyName; return (info && name) ? info.GetError(name) : null; } }
the_stack
import React from 'react' import { store } from '../../../../../store' import { StoreContext } from 'storeon/react' import { object, withKnobs, select, boolean, files, text } from '@storybook/addon-knobs' import uiManagmentApi from '../../../../../api/uiManagment/uiManagmentApi' import stylesApi from '../../../../../api/styles/stylesApi' // import { darkTheme, lightTheme } from '../../../../../configs/styles' // import { ru, en } from '../../../../../configs/languages' import languagesApi from '../../../../../api/languages/languagesApi' // import { settings } from '../../../../../configs/settings' import settingsApi from '../../../../../api/settings/settingsApi' import Message from '../Message' import { iconsList } from '../../../../../configs/icons' import '../../../../../styles/storyBookContainer.css' import { withInfo } from '@storybook/addon-info' // import info from '../stories/MessageInfo.md' import info from './MessageInfo.md' export default { title: 'Message', decorators: [withKnobs, withInfo], parameters: { info: { text: info, source: false, propTables: false, }, }, } const groupUIManagment = 'UIManagment' const groupStyles = 'Styles' const groupLanguages = 'Languages' const groupSettings = 'Settings' const userMessage = { text: 'Hello', sender: 'user', date: new Date(), } const responseMessage = { text: 'Hello, how can I help you ?:)', sender: 'response', date: new Date(), showRate: true, } // const userDark = { // mainContainer: { // width: '50%', // padding: '10px', // marginLeft: '40%', // marginTop: '5%', // marginBottom: '5%', // }, // rateMessageButton: { // border: 'none', // display: 'flex', // justifyContent: 'space-between', // width: '30%', // borderRadius: '10px', // backgroundColor: '#575757', // outline: 'none', // color: '#9b9b9b', // fontSize: '12px', // }, // avatarContainer: {}, // audioMessageButton: { // border: 'none', // display: 'flex', // borderRadius: '10px', // width: '60%', // justifyContent: 'space-around', // backgroundColor: '#575757', // outline: 'none', // color: '#9b9b9b', // fontSize: '12px', // }, // image: { // display: 'none', // }, // dataContainer: { // fontSize: '12px', // color: '#9b9b9b', // textAlign: 'right', // }, // textContainer: { // minHeight: '40px', // padding: '5px', // '& a': { // color: '#5271fe', // }, // }, // bubbleContainer: { // width: '100%', // backgroundColor: '#575757', // borderRadius: '10px', // color: 'white', // padding: '10px', // textAlign: 'left', // }, // buttonsContainer: { // display: 'flex', // borderRadius: '10px', // width: '100%', // marginBottom: '10px', // }, // } // const responseDark = { // mainContainer: { // width: '70%', // padding: '10px', // marginRight: '40%', // marginTop: '5%', // marginBottom: '5%', // display: 'flex', // }, // rateMessageButton: { // border: 'none', // display: 'flex', // justifyContent: 'space-between', // width: '30%', // borderRadius: '10px', // backgroundColor: '#575757', // outline: 'none', // color: '#9b9b9b', // fontSize: '12px', // }, // avatarContainer: { // width: '50px', // height: '50px', // borderRadius: '50px', // backgroundColor: '#575757', // border: '3px solid #575757', // marginRight: '4px', // }, // audioMessageButton: { // border: 'none', // display: 'flex', // borderRadius: '10px', // width: '60%', // justifyContent: 'space-around', // backgroundColor: '#575757', // outline: 'none', // color: '#9b9b9b', // fontSize: '12px', // }, // image: { // width: '50px', // height: '50px', // }, // dataContainer: { // fontSize: '12px', // color: '#9b9b9b', // textAlign: 'right', // }, // textContainer: { // minHeight: '40px', // padding: '5px', // '& a': { // color: '#5271fe', // }, // }, // bubbleContainer: { // width: '100%', // backgroundColor: '#575757', // borderRadius: '10px', // color: 'white', // padding: '10px', // textAlign: 'left', // }, // buttonsContainer: { // display: 'flex', // borderRadius: '10px', // width: '100%', // marginBottom: '10px', // }, // } // const userLight = { // mainContainer: { // width: '50%', // padding: '10px', // marginLeft: '40%', // marginTop: '5%', // marginBottom: '5%', // }, // rateMessageButton: { // border: 'none', // display: 'flex', // justifyContent: 'space-between', // width: '30%', // borderRadius: '10px', // backgroundColor: '#edf0f5', // outline: 'none', // color: '#9b9b9b', // fontSize: '12px', // }, // avatarContainer: {}, // audioMessageButton: { // border: 'none', // display: 'flex', // borderRadius: '10px', // width: '60%', // justifyContent: 'space-around', // backgroundColor: '#edf0f5', // outline: 'none', // color: '#9b9b9b', // fontSize: '12px', // }, // image: { // display: 'none', // }, // dataContainer: { // fontSize: '12px', // color: '#9b9b9b', // textAlign: 'right', // }, // textContainer: { // minHeight: '40px', // padding: '5px', // '& a': { // color: '#5271fe', // }, // }, // bubbleContainer: { // width: '100%', // backgroundColor: '#edf0f5', // borderRadius: '10px', // color: '#373737', // padding: '10px', // textAlign: 'left', // }, // buttonsContainer: { // display: 'flex', // borderRadius: '10px', // width: '100%', // marginBottom: '10px', // }, // } // const responseLight = { // mainContainer: { // width: '70%', // padding: '10px', // marginRight: '40%', // marginTop: '5%', // marginBottom: '5%', // display: 'flex', // }, // rateMessageButton: { // border: 'none', // display: 'flex', // justifyContent: 'space-between', // width: '30%', // borderRadius: '10px', // backgroundColor: '#edf0f5', // outline: 'none', // color: '#9b9b9b', // fontSize: '12px', // }, // avatarContainer: { // width: '50px', // height: '50px', // borderRadius: '50px', // backgroundColor: '#edf0f5', // border: '3px solid #edf0f5', // marginRight: '4px', // }, // audioMessageButton: { // border: 'none', // display: 'flex', // borderRadius: '10px', // width: '60%', // justifyContent: 'space-around', // backgroundColor: '#edf0f5', // outline: 'none', // color: '#9b9b9b', // fontSize: '12px', // }, // image: { // width: '50px', // height: '50px', // }, // dataContainer: { // fontSize: '12px', // color: '#9b9b9b', // textAlign: 'right', // }, // textContainer: { // minHeight: '40px', // padding: '5px', // '& a': { // color: '#5271fe', // }, // }, // bubbleContainer: { // width: '100%', // backgroundColor: '#edf0f5', // borderRadius: '10px', // color: '#373737', // padding: '10px', // textAlign: 'left', // }, // buttonsContainer: { // display: 'flex', // borderRadius: '10px', // width: '100%', // marginBottom: '10px', // }, // } // stylesApi.styles('changeUserMessage', { themeName: 'lightTheme', data: userLight }) // stylesApi.styles('changeUserMessage', { themeName: 'darkTheme', data: userDark }) // stylesApi.styles('changeResponseMessage', { themeName: 'lightTheme', data: responseLight }) // stylesApi.styles('changeResponseMessage', { themeName: 'darkTheme', data: responseDark }) // export const MessageComponent = () => { // const avatar = files('avatar', '.png', [], groupSettings) // settingsApi.settings('changeAvatar', avatar[0]) // const audioMessageButton = object('audioMessageButton', uiManagmentMessage.audioMessage, groupUIManagment) // const rateMessageButton = object('rateMessageButton', uiManagmentMessage.rateMessage, groupUIManagment) // const rateMessageIcon = object('rateMessageIcon', settings.media.icons.rateIcon, groupSettings) // settingsApi.settings('changeIcon', { iconName: 'rateIcon', iconData: rateMessageIcon }) // const audioMessageIcon = object('audioMessageIcon', settings.media.icons.playMessageIcon, groupSettings) // settingsApi.settings('changeIcon', { iconName: 'playMessageIcon', iconData: audioMessageIcon }) // const showAvatar = boolean('showAvatar', uiManagmentMessage.showAvatar, groupUIManagment) // const showDate = boolean('showDate', uiManagmentMessage.showDate, groupUIManagment) // uiManagmentApi.uiManagment('setUpMessage', { // showAvatar: showAvatar, // showDate: showDate, // audioMessage: audioMessageButton, // rateMessage: rateMessageButton, // }) // const activeLanguage = select('active', { en: 'en', ru: 'ru' }, 'en', groupLanguages) // languagesApi.languages('changeLanguage', activeLanguage) // const russian = object('Russian', ru.packet.Message, groupLanguages) // languagesApi.languages('changeMessage', { language: 'ru', data: russian }) // const english = object('English', en.packet.Message, groupLanguages) // languagesApi.languages('changeMessage', { language: 'en', data: english }) // const activeTheme = select('active', { darkTheme: 'darkTheme', lightTheme: 'lightTheme' }, 'darkTheme', groupStyles) // stylesApi.styles('switchTheme', activeTheme) // const stylesDarkTheme = object( // 'darkTheme', // { ResponseMessage: darkTheme.data.ResponseMessage, UserMessage: darkTheme.data.UserMessage }, // groupStyles // ) // stylesApi.styles('changeResponseMessage', { themeName: 'darkTheme', data: stylesDarkTheme.ResponseMessage }) // stylesApi.styles('changeUserMessage', { themeName: 'darkTheme', data: stylesDarkTheme.UserMessage }) // const stylesLightTheme = object( // 'lightTheme', // { ResponseMessage: lightTheme.data.ResponseMessage, UserMessage: lightTheme.data.UserMessage }, // groupStyles // ) // stylesApi.styles('changeUserMessage', { themeName: 'lightTheme', data: stylesLightTheme.UserMessage }) // stylesApi.styles('changeResponseMessage', { themeName: 'lightTheme', data: stylesLightTheme.ResponseMessage }) // return ( // <StoreContext.Provider value={store}> // <Message message={userMessage} /> // <Message message={responseMessage} /> // </StoreContext.Provider> // ) // } const languagePacket = { rateButtonTitle: (language: string, title: string) => text(`${language}/rateButtonTitle`, title, groupLanguages), audioMessageButtonTitle: (language: string, title: string) => text(`${language}/audioMessageButtonTitle`, title, groupLanguages), } const stylesPacket = { mainContainer: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/mainContainer`, data, groupStyles), textContainer: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/textContainer`, data, groupStyles), avatarContainer: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/avatarContainer`, data, groupStyles), image: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/image`, data, groupStyles), negativeRateMessageButton: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/negativeRateMessageButton`, data, groupStyles), positiveRateMessageButton: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/positiveRateMessageButton`, data, groupStyles), audioMessageButton: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/audioMessageButton`, data, groupStyles), dataContainer: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/dataContainer`, data, groupStyles), bubbleContainer: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/bubbleContainer`, data, groupStyles), buttonsContainer: (themeName: string, sender: string, data: any) => object(`${themeName}/${sender}/buttonsContainer`, data, groupStyles), } export const MessageComponent = () => { //settings start const avatar = files('avatar', '.png', [], groupSettings) settingsApi.settings('changeAvatar', avatar[0]) const positiveRateIcon = select('positiveRateIcon', iconsList, 'fas thumbs-up', groupSettings) settingsApi.settings('changeIcon', { iconName: 'positiveRateIcon', iconData: { icon: positiveRateIcon.split(' ') } }) const negativeRateIcon = select('negativeRateIcon', iconsList, 'far thumbs-down', groupSettings) settingsApi.settings('changeIcon', { iconName: 'negativeRateIcon', iconData: { icon: negativeRateIcon.split(' ') } }) const audioMessageIcon = select('audioMessageIcon', iconsList, 'play', groupSettings) settingsApi.settings('changeIcon', { iconName: 'playMessageIcon', iconData: { icon: audioMessageIcon.split(' ') } }) // settings end //ui managment start const uiManagmentMessage = store.get().managment.getIn(['components', 'Message']) const audioMessageButton = boolean( 'audioMessageButton enabled', uiManagmentMessage.audioMessage.enabled, groupUIManagment ) const titleAudioMessage = boolean( 'show audioMessageTitle', uiManagmentMessage.audioMessage.withTitle, groupUIManagment ) const iconAudioMessage = boolean('show audioMessageIcon', uiManagmentMessage.audioMessage.withIcon, groupUIManagment) const positiveRateMessageButton = boolean( 'positiveRateMessage enabled', uiManagmentMessage.positiveRateMessage.enabled, groupUIManagment ) const titlePositiveRateMessage = boolean( 'show positiveRateMessageTitle', uiManagmentMessage.positiveRateMessage.withTitle, groupUIManagment ) const iconPositiveRateMessage = boolean( 'show positiveRateMessageIcon', uiManagmentMessage.positiveRateMessage.withIcon, groupUIManagment ) const negativeRateMessageButton = boolean( 'negativeRateMessage enabled', uiManagmentMessage.negativeRateMessage.enabled, groupUIManagment ) const titleNegativeRateMessage = boolean( 'show negativeRateMessageTitle', uiManagmentMessage.negativeRateMessage.withTitle, groupUIManagment ) const iconNegativeRateMessage = boolean( 'shownegativeRateMessageIcon', uiManagmentMessage.negativeRateMessage.withIcon, groupUIManagment ) const showAvatar = boolean('showAvatar', uiManagmentMessage.showAvatar, groupUIManagment) const showDate = boolean('showDate', uiManagmentMessage.showDate, groupUIManagment) uiManagmentApi.uiManagment('setUpMessage', { positiveRateMessage: { enabled: positiveRateMessageButton, withTitle: titlePositiveRateMessage, withIcon: iconPositiveRateMessage, }, negativeRateMessage: { enabled: negativeRateMessageButton, withTitle: titleNegativeRateMessage, withIcon: iconNegativeRateMessage, }, audioMessage: { enabled: audioMessageButton, withTitle: titleAudioMessage, withIcon: iconAudioMessage }, showAvatar, showDate, }) // ui managment end // languages start const language = select('language', { en: 'en', ru: 'ru' }, 'en', groupLanguages) languagesApi.languages('changeLanguage', language) const activeLanguagePacket = store.get().languages.getIn(['stack', language, 'Message']) const audioMessageButtonTitle = languagePacket.audioMessageButtonTitle( language, activeLanguagePacket.audioMessageButtonTitle ) const rateButtonTitle = languagePacket.rateButtonTitle(language, activeLanguagePacket.rateButtonTitle) languagesApi.languages('changeMessage', { language: language, data: { audioMessageButtonTitle, rateButtonTitle } }) // languages end //styles start const themeName = select( 'theme', { sovaDark: 'sovaDark', sovaLight: 'sovaLight', sovaGray: 'sovaGray' }, 'sovaLight', groupStyles ) stylesApi.styles('switchTheme', themeName) const sender = select('sender', { user: 'User', response: 'Response' }, 'User', groupStyles) const action = sender === 'User' ? 'changeUserMessage' : 'changeResponseMessage' const activeThemePacket = store.get().styles.getIn(['stack', themeName, `${sender}Message`]) const mainContainer = stylesPacket.mainContainer(themeName, sender, activeThemePacket.mainContainer) const positiveRate = stylesPacket.positiveRateMessageButton( themeName, sender, activeThemePacket.positiveRateMessageButton ) const negativeRate = stylesPacket.negativeRateMessageButton( themeName, sender, activeThemePacket.negativeRateMessageButton ) const avatarContainer = stylesPacket.avatarContainer(themeName, sender, activeThemePacket.avatarContainer) const audioMessage = stylesPacket.audioMessageButton(themeName, sender, activeThemePacket.audioMessageButton) const image = stylesPacket.image(themeName, sender, activeThemePacket.image) const dataContainer = stylesPacket.dataContainer(themeName, sender, activeThemePacket.dataContainer) const textContainer = stylesPacket.textContainer(themeName, sender, activeThemePacket.textContainer) const bubbleContainer = stylesPacket.bubbleContainer(themeName, sender, activeThemePacket.bubbleContainer) const buttonsContainer = stylesPacket.buttonsContainer(themeName, sender, activeThemePacket.buttonsContainer) stylesApi.styles(action, { themeName: themeName, data: { mainContainer, avatarContainer, positiveRateMessageButton: positiveRate, negativeRateMessageButton: negativeRate, audioMessageButton: audioMessage, image, dataContainer, textContainer, bubbleContainer, buttonsContainer, }, }) //styles end return ( <StoreContext.Provider value={store}> <div className="sova-ck-main"> <div className="sova-ck-chat"> <Message message={userMessage} /> <Message message={responseMessage} /> </div> </div> </StoreContext.Provider> ) }
the_stack
import { MachineCreationOptions, MachineState, } from "@abstractions/vm-core-types"; import { ICpuState } from "@abstractions/abstract-cpu"; import { KliveProcess } from "@abstractions/command-definitions"; import { CodeToInject } from "@abstractions/code-runner-service"; import { KliveAction } from "@core/state/state-core"; import { AppState, DirectoryContent, RegisteredMachine, } from "@core/state/AppState"; import { KliveConfiguration } from "@abstractions/klive-configuration"; import { CompilerOptions, CompilerOutput } from "@abstractions/z80-compiler-service"; /** * Potential message sources */ export type MessageSource = "emu" | "ide" | "main"; export type Channel = | "MainStateRequest" | "RendererStateResponse" | "RendererStateRequest" | "MainStateResponse" | "MainToEmuRequest" | "MainToEmuResponse" | "MainToIdeRequest" | "MainToIdeResponse" | "EmuToMainRequest" | "EmuToMainResponse" | "IdeToEmuMainRequest" | "IdeToEmuMainResponse" | "IdeToEmuEmuRequest" | "IdeToEmuEmuResponse"; /** * The common base for all message types */ export interface MessageBase { type: AnyMessage["type"]; correlationId?: number; sourceId?: MessageSource; } /** * The Emu or IDE processes forward state changes to the main process */ export interface ForwardActionRequest extends MessageBase { type: "ForwardAction"; action: KliveAction; } /** * The main process forwards the application configuration to the Emu or IDE * processes */ export interface ForwardAppConfigRequest extends MessageBase { type: "ForwardAppConfig"; config: KliveConfiguration; } /** * The main process asks the Emu process to create a virtual machine */ export interface CreateMachineRequest extends MessageBase { type: "CreateMachine"; machineId: string; options: MachineCreationOptions; } /** * The main process sends this message to Emu to start the VM */ export interface StartVmRequest extends MessageBase { type: "StartVm"; } /** * The main process sends this message to Emu to start the VM and * run to till it reaches the specified termination point */ export interface RunCodeRequest extends MessageBase { type: "RunCode"; codeToInject: CodeToInject; debug: boolean; } /** * The main process sends this message to Emu to pause the VM */ export interface PauseVmRequest extends MessageBase { type: "PauseVm"; } /** * The main process sends this message to Emu to stop the VM */ export interface StopVmRequest extends MessageBase { type: "StopVm"; } /** * The main process sends this message to Emu to restart the VM */ export interface RestartVmRequest extends MessageBase { type: "RestartVm"; } /** * The main process sends this message to Emu to start debugging the VM */ export interface DebugVmRequest extends MessageBase { type: "DebugVm"; } /** * The main process sends this message to Emu to step-into the VM */ export interface StepIntoVmRequest extends MessageBase { type: "StepIntoVm"; } /** * The main process sends this message to Emu to step-over the VM */ export interface StepOverVmRequest extends MessageBase { type: "StepOverVm"; } /** * The main process sends this message to Emu to step-out the VM */ export interface StepOutVmRequest extends MessageBase { type: "StepOutVm"; } /** * The main process sends this message to Emu to execute a machine-specific command */ export interface ExecuteMachineCommandRequest extends MessageBase { type: "ExecuteMachineCommand"; command: string; args?: unknown; } /** * The main process sends its entire state to the IDE window */ export interface SyncMainStateRequest extends MessageBase { type: "SyncMainState"; mainState: AppState; } /** * The main process sends a new project request to the IDE window */ export interface NewProjectRequest extends MessageBase { type: "NewProjectRequest"; } /** * The Emu ask the main for a file open dialog */ export interface EmuOpenFileDialogRequest extends MessageBase { type: "EmuOpenFileDialog"; title?: string; filters?: { name: string; extensions: string[] }[]; } /** * The Emu asks the main for Manage Z88 Cards command */ export interface ManageZ88CardsRequest extends MessageBase { type: "ManageZ88Cards"; } /** * The Ide asks Emu for the contents of the Z80 registers */ export interface GetCpuStateRequest extends MessageBase { type: "GetCpuState"; } /** * The Ide asks Emu for the state of the virtual machine */ export interface GetMachineStateRequest extends MessageBase { type: "GetMachineState"; } /** * The Ide asks Emu for the memory contents of the virtual machine */ export interface GetMemoryContentsRequest extends MessageBase { type: "GetMemoryContents"; } /** * The Ide asks Emu for the code injection support flag */ export interface SupportsCodeInjectionRequest extends MessageBase { type: "SupportsCodeInjection"; mode?: string; } /** * The Ide asks Emu to inject the specified code */ export interface InjectCodeRequest extends MessageBase { type: "InjectCode"; codeToInject: CodeToInject; } /** * The Ide asks the main process for the contents of a folder */ export interface GetRegisteredMachinesRequest extends MessageBase { type: "GetRegisteredMachines"; } /** * The Ide asks the main process to create a Klive project */ export interface CreateKliveProjectRequest extends MessageBase { type: "CreateKliveProject"; machineType: string; rootFolder: string | null; projectFolder: string; } /** * The Ide asks the main process to open a folder */ export interface OpenProjectFolderRequest extends MessageBase { type: "OpenProjectFolder"; } /** * The Ide ask the main for a file open dialog */ export interface GetFolderDialogRequest extends MessageBase { type: "GetFolderDialog"; title?: string; root?: string; } /** * The Ide ask the main for checking the existence of a file */ export interface FileExistsRequest extends MessageBase { type: "FileExists"; name: string; } /** * The Ide ask the main for obtaining the contents of a folder */ export interface GetFolderContentsRequest extends MessageBase { type: "GetFolderContents"; name: string; } /** * The Ide ask the main for creating a folder */ export interface CreateFolderRequest extends MessageBase { type: "CreateFolder"; name: string; } /** * The Ide ask the main for creating a file */ export interface CreateFileRequest extends MessageBase { type: "CreateFile"; name: string; } /** * The Ide ask the main for displaying a confirm dialog */ export interface ConfirmDialogRequest extends MessageBase { type: "ConfirmDialog"; title?: string; question: string; defaultYes?: boolean; } /** * The Ide ask the main for deleting a folder */ export interface DeleteFolderRequest extends MessageBase { type: "DeleteFolder"; name: string; } /** * The Ide ask the main for deleting a file */ export interface DeleteFileRequest extends MessageBase { type: "DeleteFile"; name: string; } /** * The Ide ask the main for renaming a file */ export interface RenameFileRequest extends MessageBase { type: "RenameFile"; oldName: string; newName: string; } /** * The Ide ask the main for getting the contents of a file */ export interface GetFileContentsRequest extends MessageBase { type: "GetFileContents"; name: string; asBuffer?: boolean; } /** * The Ide ask the main for getting the contents of a file */ export interface SaveFileContentsRequest extends MessageBase { type: "SaveFileContents"; name: string; contents: string; } /** * The Ide ask the main for getting the contents of a file */ export interface CompileFileRequest extends MessageBase { type: "CompileFile"; filename: string; options?: CompilerOptions; } /** * The Ide ask the main to show a message box */ export interface ShowMessageBoxRequest extends MessageBase { type: "ShowMessageBox"; process: KliveProcess; message: string; title?: string; asError?: boolean; } /** * All requests */ export type RequestMessage = | ForwardingMessage | MainToEmuRequests | MainToIdeRequests | EmuToMainRequests | IdeToEmuRequests | IdeToMainRequests; /** * Requests that forward information among the main, Emu, and IDE processes */ type ForwardingMessage = ForwardActionRequest | ForwardAppConfigRequest; /** * Requests send by the main process to Emu */ type MainToEmuRequests = | CreateMachineRequest | StartVmRequest | PauseVmRequest | StopVmRequest | RestartVmRequest | DebugVmRequest | StepIntoVmRequest | StepOverVmRequest | StepOutVmRequest | RunCodeRequest | ExecuteMachineCommandRequest; /** * Requests from Emu to Main */ type EmuToMainRequests = EmuOpenFileDialogRequest | ManageZ88CardsRequest; /** * Requests for IDE to Emu */ type IdeToEmuRequests = | GetCpuStateRequest | GetMachineStateRequest | GetMemoryContentsRequest | SupportsCodeInjectionRequest | InjectCodeRequest; /** * Requests for IDE to Main */ type IdeToMainRequests = | GetRegisteredMachinesRequest | CreateKliveProjectRequest | OpenProjectFolderRequest | GetFolderDialogRequest | FileExistsRequest | GetFolderContentsRequest | CreateFolderRequest | CreateFileRequest | ConfirmDialogRequest | DeleteFolderRequest | DeleteFileRequest | RenameFileRequest | GetFileContentsRequest | SaveFileContentsRequest | CompileFileRequest | ShowMessageBoxRequest; /** * Requests send by the main process to Ide */ type MainToIdeRequests = SyncMainStateRequest | NewProjectRequest; /** * Default response for actions */ export interface DefaultResponse extends MessageBase { type: "Ack"; } /** * Response for CreateMachineRequest */ export interface CreateMachineResponse extends MessageBase { type: "CreateMachineResponse"; error: string | null; } /** * The emulator process ask for a file open dialog */ export interface ExecuteMachineCommandResponse extends MessageBase { type: "ExecuteMachineCommandResponse"; result: unknown; } /** * The emulator process ask for a file open dialog */ export interface EmuOpenFileDialogResponse extends MessageBase { type: "EmuOpenFileDialogResponse"; filename?: string; } /** * The Ide asks Emu for the contents of the Z80 registers */ export interface GetCpuStateResponse extends MessageBase { type: "GetCpuStateResponse"; state: ICpuState; } /** * The Ide asks Emu for the state of the virtual machine */ export interface GetMachineStateResponse extends MessageBase { type: "GetMachineStateResponse"; state: MachineState; } /** * The Ide asks Emu for the memory contents of the virtual machine */ export interface GetMemoryContentsResponse extends MessageBase { type: "GetMemoryContentsResponse"; contents: Uint8Array; } /** * The Ide asks Emu for the code injection support flag */ export interface SupportsCodeInjectionResponse extends MessageBase { type: "SupportsCodeInjectionResponse"; supports: boolean; } /** * The Ide asks the main process for the contents of a folder */ export interface GetRegisteredMachinesResponse extends MessageBase { type: "GetRegisteredMachinesResponse"; machines: RegisteredMachine[]; } /** * The Ide asks the main process to create a Klive project */ export interface CreateKliveProjectResponse extends MessageBase { type: "CreateKliveProjectResponse"; error?: string; targetFolder: string; } /** * The main process sends a new project request to the IDE window */ export interface NewProjectResponse extends MessageBase { type: "NewProjectResponse"; project?: NewProjectData; } /** * The emulator process ask for a file open dialog */ export interface GetFolderDialogResponse extends MessageBase { type: "GetFolderDialogResponse"; filename?: string; } /** * The Emu ask the main for checking the existence of a file */ export interface FileExistsResponse extends MessageBase { type: "FileExistsResponse"; exists: boolean; } /** * The Emu ask the main for obtaining the contents of a folder */ export interface GetFolderContentsResponse extends MessageBase { type: "GetFolderContentsResponse"; contents: DirectoryContent; } /** * The Emu ask the main for creating a folder */ export interface FileOperationResponse extends MessageBase { type: "FileOperationResponse"; error?: string; } /** * The Emu ask the main for displaying a confirm dialog */ export interface ConfirmDialogResponse extends MessageBase { type: "ConfirmDialogResponse"; confirmed?: boolean; } /** * The Emu ask the main for getting the contents of a file */ export interface GetFileContentsResponse extends MessageBase { type: "GetFileContentsResponse"; contents?: string | Buffer; } /** * The Ide ask the main for getting the contents of a file */ export interface CompileFileResponse extends MessageBase { type: "CompileFileResponse"; result: CompilerOutput; } export type ResponseMessage = | DefaultResponse | CreateMachineResponse | ExecuteMachineCommandResponse | EmuOpenFileDialogResponse | GetCpuStateResponse | GetMachineStateResponse | GetMemoryContentsResponse | GetRegisteredMachinesResponse | CreateKliveProjectResponse | NewProjectResponse | GetFolderDialogResponse | FileExistsResponse | GetFolderContentsResponse | FileOperationResponse | ConfirmDialogResponse | GetFileContentsResponse | CompileFileResponse | SupportsCodeInjectionResponse; /** * All messages */ export type AnyMessage = RequestMessage | ResponseMessage; // ---------------------------------------------------------------------------- // Message DTOs /** * Represents the contents of the new project data */ export type NewProjectData = { machineType: string; projectPath: string; projectName: string; open: boolean; }; // ---------------------------------------------------------------------------- // Message creators export function defaultResponse(): DefaultResponse { return { type: "Ack" }; } export function emuOpenFileDialogResponse( filename?: string ): EmuOpenFileDialogResponse { return { type: "EmuOpenFileDialogResponse", filename, }; } export function getRegisteredMachinesResponse( machines: RegisteredMachine[] ): GetRegisteredMachinesResponse { return { type: "GetRegisteredMachinesResponse", machines, }; } export function createKliveProjectResponse( targetFolder: string, error?: string ): CreateKliveProjectResponse { return { type: "CreateKliveProjectResponse", error, targetFolder }; } export function getFolderDialogResponse( filename?: string ): GetFolderDialogResponse { return { type: "GetFolderDialogResponse", filename, }; } export function fileExistsResponse(exists: boolean): FileExistsResponse { return { type: "FileExistsResponse", exists, }; } export function getFolderContentsResponse( contents: DirectoryContent ): GetFolderContentsResponse { return { type: "GetFolderContentsResponse", contents, }; } export function fileOperationResponse(error?: string): FileOperationResponse { return { type: "FileOperationResponse", error, }; } export function confirmDialogResponse( confirmed?: boolean ): ConfirmDialogResponse { return { type: "ConfirmDialogResponse", confirmed, }; } export function getFileContentsResponse( contents?: string | Buffer ): GetFileContentsResponse { return { type: "GetFileContentsResponse", contents, }; } export function compileFileResponse( result: CompilerOutput ): CompileFileResponse { return { type: "CompileFileResponse", result, }; } export function executeMachineCommand( command: string, args?: unknown ): ExecuteMachineCommandRequest { return { type: "ExecuteMachineCommand", command, args, }; }
the_stack
import "mocha"; import * as expect from "expect"; import * as fs from "fs"; import * as path from "path"; import { MachineApi } from "../../../src/renderer/machines/wa-api"; import { ZxSpectrum48 } from "../../../src/renderer/machines/spectrum/ZxSpectrum48"; import { ExecuteCycleOptions, EmulationMode, SpectrumMachineStateBase, } from "../../../src/shared/machines/machine-state"; import { MemoryHelper } from "../../../src/renderer/machines/memory-helpers"; import { importObject } from "../../import-object"; import { PIXEL_RENDERING_BUFFER, COLORIZATION_BUFFER, } from "../../../src/renderer/machines/memory-map"; const buffer = fs.readFileSync( path.join(__dirname, "../../../build/sp48.wasm") ); const romBuffer = fs.readFileSync( path.join(__dirname, "../../../roms/sp48/sp48.rom") ); let api: MachineApi; let machine: ZxSpectrum48; describe("ZX Spectrum 48 - Screen", () => { before(async () => { const wasm = await WebAssembly.instantiate(buffer, importObject); api = (wasm.instance.exports as unknown) as MachineApi; machine = new ZxSpectrum48(api, [romBuffer]); }); beforeEach(() => { machine.reset(); }); it("ULA frame tact is OK", () => { const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.tactsInFrame).toBe(69888); }); it("Flash toggle rate is OK", () => { const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.flashFrames).toBe(25); }); it("Setting border value does not change invisible area", () => { machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x10, 0x00, // LD BC,$0010 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0xfb, // EI 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeCycle(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState(); expect(s.pc).toBe(0x800e); expect(s.tacts).toBe(451); expect(s.frameCompleted).toBe(false); const mh = new MemoryHelper(api, PIXEL_RENDERING_BUFFER); let sum = 0x00; for (let row = 0; row < s.screenLines; row++) { for (let col = 0; col < s.screenWidth; col++) { sum += mh.readByte(row * s.screenWidth + col); } } expect(sum).toBe(0xff * s.screenLines * s.screenWidth); }); it("Setting border value changes border area #1", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x8d, 0x00, // LD BC,$008C 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeCycle(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; console.log(s.executionCompletionReason); console.log(s.tacts); expect(s.pc).toBe(0x800d); expect(s.tacts).toBe(3697); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let col = 0; col < 220; col++) { const pixel = mh.readByte(col); sum += pixel; } expect(sum).toBe(0x05 * 220); // --- Remaining line should be 0xff sum = 0; for (let col = 220; col < s.screenWidth; col++) { const pixel = mh.readByte(col); sum += pixel; } expect(sum).toBe(0xff * (s.screenWidth - 220)); // --- Remaining screen part should be 0xff sum = 0x00; for (let row = 1; row < s.screenLines; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0xff * s.screenWidth * (s.screenLines - 1)); }); it("Setting border value changes border area #2", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x26, 0x02, // LD BC,$0226 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeCycle(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.pc).toBe(0x800d); expect(s.tacts).toBe(14331); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 47; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 47); // --- Remaining line should be 0xff sum = 0; for (let col = 220; col < s.screenWidth; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0xff * (s.screenWidth - 220)); // --- Remaining screen part should be 0xff sum = 0x00; const lastLine = s.lastDisplayLine + s.borderBottomLines; for (let row = 48; row < lastLine; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0xff * s.screenWidth * (lastLine - 48)); }); it("Setting border value changes border area #3", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x29, 0x02, // LD BC,$0229 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0xfb, // EI 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeCycle(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.pc).toBe(0x800e); expect(s.tacts).toBe(14413); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 47; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 47); // --- The left border of row 48 should be set to 0x05 sum = 0; for (let col = 0; col < 48; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * 48); // --- The first 112 pixels of the first display row (48) should be set to 0 sum = 0; for (let col = 48; col < 148; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x00); // --- Remaining screen part should be 0xff sum = 0x00; const lastLine = s.lastDisplayLine + s.borderBottomLines; for (let row = 49; row < lastLine; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0xff * s.screenWidth * (lastLine - 49)); }); it("Border + empty pixels", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x75, 0x0a, // LD BC,$0A75 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeCycle(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.pc).toBe(0x800d); expect(s.tacts).toBe(69633); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 48; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 48); // --- The left border of row 48 should be set to 0x05 sum = 0; for (let col = 0; col < 48; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * 48); // --- Display rows should have a border value of 0x05 and a pixel value of 0x00 for (let row = 48; row < 48 + 192; row++) { sum = 0x00; for (let col = 0; col < s.borderLeftPixels; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderLeftPixels); sum = 0x00; for ( let col = s.borderLeftPixels; col < s.screenWidth - s.borderRightPixels; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x00); sum = 0x00; for ( let col = s.screenWidth - s.borderRightPixels; col < s.screenWidth; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderRightPixels); } sum = 0; for (let row = 48 + 192; row < s.screenLines; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * (s.screenLines - 192 - 48)); }); it("Rendering with pattern #1", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x75, 0x0a, // LD BC,$0A75 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); let mh = new MemoryHelper(api, 0); for (let addr = 0x4000; addr < 0x5800; addr++) { machine.writeMemory(addr, addr & 0x0100 ? 0xaa : 0x55); } for (let addr = 0x5800; addr < 0x5b00; addr++) { machine.writeMemory(addr, 0x51); } machine.executeCycle(new ExecuteCycleOptions(EmulationMode.UntilHalt)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.pc).toBe(0x800d); expect(s.tacts).toBe(69633); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); mh = new MemoryHelper(api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 48; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 48); // --- The left border of row 48 should be set to 0x05 sum = 0; for (let col = 0; col < 48; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * 48); // --- Display rows should have a border value of 0x05 and a pixel value of 0x00 for (let row = 48; row < 48 + 192; row++) { sum = 0x00; for (let col = 0; col < s.borderLeftPixels; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderLeftPixels); sum = 0x00; let expectedSum = 0x00; for ( let col = s.borderLeftPixels; col < s.screenWidth - s.borderRightPixels; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; expectedSum += (row + col) % 2 ? 0x09 : 0x0a; } expect(sum).toBe(expectedSum); sum = 0x00; for ( let col = s.screenWidth - s.borderRightPixels; col < s.screenWidth; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderRightPixels); } sum = 0; for (let row = 48 + 192; row < s.screenLines; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * (s.screenLines - 192 - 48)); }); it("Rendering until frame ends", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x75, 0x0a, // LD BC,$0A75 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); let mh = new MemoryHelper(api, 0); for (let addr = 0x4000; addr < 0x5800; addr++) { machine.writeMemory(addr, addr & 0x0100 ? 0xaa : 0x55); } for (let addr = 0x5800; addr < 0x5b00; addr++) { machine.writeMemory(addr, 0x51); } machine.executeCycle(new ExecuteCycleOptions(EmulationMode.UntilFrameEnds)); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.pc).toBe(0x800d); expect(s.frameCompleted).toBe(true); expect(s.borderColor).toBe(0x05); mh = new MemoryHelper(api, PIXEL_RENDERING_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 48; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * 48); // --- The left border of row 48 should be set to 0x05 sum = 0; for (let col = 0; col < 48; col++) { const pixel = mh.readByte(48 * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * 48); // --- Display rows should have a border value of 0x05 and a pixel value of 0x00 for (let row = 48; row < 48 + 192; row++) { sum = 0x00; for (let col = 0; col < s.borderLeftPixels; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderLeftPixels); sum = 0x00; let expectedSum = 0x00; for ( let col = s.borderLeftPixels; col < s.screenWidth - s.borderRightPixels; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; expectedSum += (row + col) % 2 ? 0x09 : 0x0a; } expect(sum).toBe(expectedSum); sum = 0x00; for ( let col = s.screenWidth - s.borderRightPixels; col < s.screenWidth; col++ ) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } expect(sum).toBe(0x05 * s.borderRightPixels); } sum = 0; for (let row = 48 + 192; row < s.screenLines; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readByte(row * s.screenWidth + col); sum += pixel; } } expect(sum).toBe(0x05 * s.screenWidth * (s.screenLines - 192 - 48)); }); it("Colorize border + empty pixels", () => { machine.api.setupMachine(); machine.injectCode([ 0xf3, // DI 0x3e, 0x05, // LD A,$05 0xd3, 0xfe, // OUT ($FE),A 0x01, 0x75, 0x0a, // LD BC,$0A75 0x0b, // DECLB: DEC BC 0x78, // LD A,B 0xb1, // OR C 0x20, 0xfb, // JR NZ,DECLB 0x76, // HALT ]); fillPixelBuffer(0xff); machine.executeCycle(new ExecuteCycleOptions(EmulationMode.UntilHalt)); machine.api.colorize(); const s = machine.getMachineState() as SpectrumMachineStateBase; expect(s.pc).toBe(0x800d); expect(s.tacts).toBe(69633); expect(s.frameCompleted).toBe(false); expect(s.borderColor).toBe(0x05); const mh = new MemoryHelper(api, COLORIZATION_BUFFER); // --- Border pixels should be 0x05 let sum = 0; for (let row = 0; row < 48; row++) { for (let col = 0; col < s.screenWidth; col++) { const pixel = mh.readUint32((row * s.screenWidth + col) * 4); if (pixel === 0xffaaaa00 - 0x100000000) { sum++; } } } }); }); /** * * @param data Pixel buffer data */ function fillPixelBuffer(data: number): void { const s = machine.getMachineState() as SpectrumMachineStateBase; const mh = new MemoryHelper(api, PIXEL_RENDERING_BUFFER); const visibleLines = s.screenLines - s.nonVisibleBorderTopLines - s.nonVisibleBorderTopLines; const visibleColumns = (s.screenLineTime - s.nonVisibleBorderRightTime) * 2; const pixels = visibleLines * visibleColumns; for (let i = 0; i < pixels; i++) { mh.writeByte(i, data); } }
the_stack
import * as path from 'path'; import {IConfusionMatrix} from '@microsoft/bf-dispatcher'; import {MultiLabelObjectConfusionMatrixExact} from '@microsoft/bf-dispatcher'; import {MultiLabelObjectConfusionMatrixSubset} from '@microsoft/bf-dispatcher'; import {ILabelArrayAndMap} from '@microsoft/bf-dispatcher'; import {ITextUtteranceLabelMapDataStructure} from '@microsoft/bf-dispatcher'; import {Label} from '@microsoft/bf-dispatcher'; import {LabelType} from '@microsoft/bf-dispatcher'; import {PredictionStructureWithScoreLabelString} from '@microsoft/bf-dispatcher'; import {PredictionStructureWithScoreLabelObject} from '@microsoft/bf-dispatcher'; import {StructTextNumber} from '@microsoft/bf-dispatcher'; import {StructTextStringSet} from '@microsoft/bf-dispatcher'; import {StructTextText} from '@microsoft/bf-dispatcher'; import {LabelResolver} from './labelresolver'; import {OrchestratorHelper} from './orchestratorhelper'; import {UtilityLabelResolver} from './utilitylabelresolver'; import {Utility} from './utility'; import {Utility as UtilityDispatcher} from '@microsoft/bf-dispatcher'; export class OrchestratorTest { public static readonly testingSetIntentScoresOutputFilename: string = 'orchestrator_testing_set_intent_scores.txt'; public static readonly testingSetIntentGroundTruthJsonContentOutputFilename: string = 'orchestrator_testing_set_intent_ground_truth_instances.json'; public static readonly testingSetIntentPredictionJsonContentOutputFilename: string = 'orchestrator_testing_set_intent_prediction_instances.json'; public static readonly testingSetIntentSummaryHtmlOutputFilename: string = 'orchestrator_testing_set_intent_summary.html'; public static readonly testingSetIntentLabelsOutputFilename: string = 'orchestrator_testing_set_intent_labels.txt'; public static readonly testingSetEntityScoresOutputFilename: string = 'orchestrator_testing_set_entity_scores.txt'; public static readonly testingSetEntityGroundTruthJsonContentOutputFilename: string = 'orchestrator_testing_set_entity_ground_truth_instances.json'; public static readonly testingSetEntityPredictionJsonContentOutputFilename: string = 'orchestrator_testing_set_entity_prediction_instances.json'; public static readonly testingSetEntitySummaryHtmlOutputFilename: string = 'orchestrator_testing_set_entity_summary.html'; public static readonly testingSetEntityLabelsOutputFilename: string = 'orchestrator_testing_set_entity_labels.txt'; // eslint-disable-next-line complexity // eslint-disable-next-line max-params public static async runAsync( baseModelPath: string, entityBaseModelPath: string, inputPathConfiguration: string, testPathConfiguration: string, outputPath: string, ambiguousClosenessThresholdParameter: number, lowConfidenceScoreThresholdParameter: number, multiLabelPredictionThresholdParameter: number, unknownLabelPredictionThresholdParameter: number, fullEmbeddings: boolean = false, obfuscateEvaluationReport: boolean = false): Promise<void> { // ----------------------------------------------------------------------- // ---- NOTE ---- process arguments if (Utility.isEmptyString(inputPathConfiguration)) { Utility.debuggingThrow(`Please provide path to an input .blu file, CWD=${process.cwd()}, called from OrchestratorTest.runAsync()`); } if (Utility.isEmptyString(testPathConfiguration)) { Utility.debuggingThrow(`Please provide a test file, CWD=${process.cwd()}, called from OrchestratorTest.runAsync()`); } if (Utility.isEmptyString(outputPath)) { Utility.debuggingThrow(`Please provide an output directory, CWD=${process.cwd()}, called from OrchestratorTest.runAsync()`); } if (Utility.isEmptyString(baseModelPath)) { Utility.debuggingThrow(`The baseModelPath argument is empty, CWD=${process.cwd()}, called from OrchestratorTest.runAsync()`); } /** ---- NOTE-FOR-REFERENCE-entity-model-is-optional ---- * if (Utility.isEmptyString(entityBaseModelPath)) { * Utility.debuggingThrow(`The entityBaseModelPath argument is empty, CWD=${process.cwd()}, called from OrchestratorTest.runAsync()`); * } */ if (baseModelPath) { baseModelPath = path.resolve(baseModelPath); } else { baseModelPath = ''; } if (entityBaseModelPath) { entityBaseModelPath = path.resolve(entityBaseModelPath); } else { entityBaseModelPath = ''; } const ambiguousClosenessThreshold: number = ambiguousClosenessThresholdParameter; const lowConfidenceScoreThreshold: number = lowConfidenceScoreThresholdParameter; const multiLabelPredictionThreshold: number = multiLabelPredictionThresholdParameter; const unknownLabelPredictionThreshold: number = unknownLabelPredictionThresholdParameter; Utility.debuggingLog(`inputPath=${inputPathConfiguration}`); Utility.debuggingLog(`testPath=${testPathConfiguration}`); Utility.debuggingLog(`outputPath=${outputPath}`); Utility.debuggingLog(`baseModelPath=${baseModelPath}`); Utility.debuggingLog(`entityBaseModelPath=${entityBaseModelPath}`); Utility.debuggingLog(`ambiguousClosenessThreshold=${ambiguousClosenessThreshold}`); Utility.debuggingLog(`lowConfidenceScoreThreshold=${lowConfidenceScoreThreshold}`); Utility.debuggingLog(`multiLabelPredictionThreshold=${multiLabelPredictionThreshold}`); Utility.debuggingLog(`unknownLabelPredictionThreshold=${unknownLabelPredictionThreshold}`); Utility.debuggingLog(`fullEmbeddings=${fullEmbeddings}`); Utility.debuggingLog(`obfuscateEvaluationReport=${obfuscateEvaluationReport}`); Utility.toObfuscateLabelTextInReportUtility = obfuscateEvaluationReport; UtilityLabelResolver.toObfuscateLabelTextInReportUtilityLabelResolver = obfuscateEvaluationReport; // ----------------------------------------------------------------------- // ---- NOTE ---- process arguments const snapshotFile: string = inputPathConfiguration; if (!Utility.exists(snapshotFile)) { Utility.debuggingThrow(`snapshot set file does not exist, snapshotFile=${snapshotFile}`); } const testingSetIntentScoresOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetIntentScoresOutputFilename); const testingSetIntentGroundTruthJsonContentOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetIntentGroundTruthJsonContentOutputFilename); const testingSetIntentPredictionJsonContentOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetIntentPredictionJsonContentOutputFilename); const testingSetIntentSummaryHtmlOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetIntentSummaryHtmlOutputFilename); const testingSetIntentLabelsOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetIntentLabelsOutputFilename); const testingSetEntityScoresOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetEntityScoresOutputFilename); const testingSetEntityGroundTruthJsonContentOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetEntityGroundTruthJsonContentOutputFilename); const testingSetEntityPredictionJsonContentOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetEntityPredictionJsonContentOutputFilename); const testingSetEntitySummaryHtmlOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetEntitySummaryHtmlOutputFilename); const testingSetEntityLabelsOutputFilename: string = path.join(outputPath, OrchestratorTest.testingSetEntityLabelsOutputFilename); // ----------------------------------------------------------------------- // ---- NOTE ---- create a LabelResolver object and load the snapshot set. Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call LabelResolver.createAsync()'); await LabelResolver.createAsync(baseModelPath, entityBaseModelPath); Utility.debuggingLog('OrchestratorTest.runAsync(), after calling LabelResolver.createAsync()'); Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()'); UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings(fullEmbeddings); Utility.debuggingLog('OrchestratorTest.runAsync(), after calling UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()'); Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call OrchestratorHelper.getSnapshotFromFile()'); const snapshot: Uint8Array = OrchestratorHelper.getSnapshotFromFile(snapshotFile); Utility.debuggingLog(`LabelResolver.createWithSnapshotAsync(): typeof(snapshot)=${typeof snapshot}`); Utility.debuggingLog(`LabelResolver.createWithSnapshotAsync(): snapshot.byteLength=${snapshot.byteLength}`); Utility.debuggingLog('OrchestratorTest.runAsync(), after calling OrchestratorHelper.getSnapshotFromFile()'); Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call LabelResolver.addSnapshot()'); await LabelResolver.addSnapshot(snapshot); Utility.debuggingLog('OrchestratorTest.runAsync(), after calling LabelResolver.addSnapshot()'); // ----------------------------------------------------------------------- // ---- NOTE ---- retrieve intent labels const snapshotSetLabels: string[] = LabelResolver.getLabels(LabelType.Intent); const snapshotSetLabelSet: Set<string> = new Set<string>(snapshotSetLabels); // ---- NOTE ---- retrieve entity labels const snapshotSetEntityLabels: string[] = LabelResolver.getLabels(LabelType.Entity); const snapshotSetEntityLabelSet: Set<string> = new Set<string>(snapshotSetEntityLabels); // ----------------------------------------------------------------------- // ---- NOTE ---- load the testing set. const processedUtteranceLabelsMap: ITextUtteranceLabelMapDataStructure = await OrchestratorHelper.getUtteranceLabelsMap(testPathConfiguration, false); // Utility.debuggingLog(`OrchestratorTest.runAsync(), processedUtteranceLabelsMap.utteranceLabelsMap.keys()=${[...processedUtteranceLabelsMap.utteranceLabelsMap.keys()]}`); // Utility.debuggingLog(`OrchestratorTest.runAsync(), processedUtteranceLabelsMap.utteranceEntityLabelsMap.keys()=${[...processedUtteranceLabelsMap.utteranceEntityLabelsMap.keys()]}`); // ----------------------------------------------------------------------- // ---- NOTE ---- process testing set intent labels. const unknownSpuriousLabelsProcessed: { 'utteranceUnknownLabelsMap': Map<string, Set<string>>; 'utteranceUnknownLabelDuplicateMap': Map<string, Set<string>>; 'utteranceSpuriousLabelsMap': Map<string, Set<string>>; 'utteranceSpuriousLabelDuplicateMap': Map<string, Set<string>>; 'utteranceLabelMapSetAddedWithUnknownLabel': boolean; 'utteranceLabelDuplicateMapSetAddedWithUnknownLabel': boolean; } = Utility.processUnknownSpuriousLabelsInUtteranceLabelsMapUsingLabelSet( processedUtteranceLabelsMap, snapshotSetLabelSet); const utteranceLabelsMap: Map<string, Set<string>> = processedUtteranceLabelsMap.utteranceLabelsMap; const utteranceLabelDuplicateMap: Map<string, Set<string>> = processedUtteranceLabelsMap.utteranceLabelDuplicateMap; Utility.debuggingLog('OrchestratorTest.runAsync(), after calling OrchestratorHelper.getUtteranceLabelsMap() for testing set'); // Utility.debuggingLog(`OrchestratorTest.runAsync(), utteranceLabelsMap=${Utility.jsonStringify(utteranceLabelsMap)}`); // ---- Utility.debuggingLog(`OrchestratorTest.runAsync(), Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(utteranceLabelDuplicateMap)=${Utility.jsonStringify(Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(utteranceLabelDuplicateMap))}`); Utility.debuggingLog(`OrchestratorTest.runAsync(), number of unique utterances=${utteranceLabelsMap.size}`); Utility.debuggingLog(`OrchestratorTest.runAsync(), number of duplicate utterance/label pairs=${utteranceLabelDuplicateMap.size}`); if (utteranceLabelsMap.size <= 0) { Utility.debuggingThrow('There is no example, something wrong?'); } // ----------------------------------------------------------------------- // ---- NOTE ---- process testing set entity labels. const unknownSpuriousEntityLabelsProcessed: { 'utteranceUnknownEntityLabelsMap': Map<string, Label[]>; 'utteranceUnknownEntityLabelDuplicateMap': Map<string, Label[]>; 'utteranceSpuriousEntityLabelsMap': Map<string, Label[]>; 'utteranceSpuriousEntityLabelDuplicateMap': Map<string, Label[]>; 'utteranceLabelMapSetAddedWithUnknownLabel': boolean; 'utteranceLabelDuplicateMapSetAddedWithUnknownLabel': boolean; } = Utility.processUnknownSpuriousEntityLabelsInUtteranceEntityLabelsMapUsingLabelSet( processedUtteranceLabelsMap, snapshotSetEntityLabelSet); const utteranceEntityLabelsMap: Map<string, Label[]> = processedUtteranceLabelsMap.utteranceEntityLabelsMap; const utteranceEntityLabelDuplicateMap: Map<string, Label[]> = processedUtteranceLabelsMap.utteranceEntityLabelDuplicateMap; Utility.debuggingLog('OrchestratorTest.runAsync(), after calling OrchestratorHelper.getUtteranceEntityLabelsMap() for testing set'); // Utility.debuggingLog(`OrchestratorTest.runAsync(), utteranceEntityLabelsMap=${Utility.jsonStringify(utteranceEntityLabelsMap)}`); // ---- Utility.debuggingLog(`OrchestratorTest.runAsync(), Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(utteranceEntityLabelDuplicateMap)=${Utility.jsonStringify(Utility.convertStringKeyGenericSetNativeMapToDictionary<string>(utteranceEntityLabelDuplicateMap))}`); Utility.debuggingLog(`OrchestratorTest.runAsync(), number of unique utterances=${utteranceEntityLabelsMap.size}`); Utility.debuggingLog(`OrchestratorTest.runAsync(), number of duplicate utterance/label pairs=${utteranceEntityLabelDuplicateMap.size}`); /** ---- NOTE-FOR-REFERENCE-entity-model-is-optional ---- * if (utteranceEntityLabelsMap.size <= 0) { * Utility.debuggingThrow('There is no example, something wrong?'); * } */ // ----------------------------------------------------------------------- // ---- NOTE ---- integrated step to produce intent analysis reports. Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample("false")'); UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample(false); Utility.debuggingLog('OrchestratorTest.runAsync(), finished calling UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample()'); Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call UtilityLabelResolver.generateLabelStringEvaluationReport()'); const evaluationOutputLabelString: { 'evaluationReportLabelUtteranceStatistics': { 'evaluationSummary': string; 'labelArrayAndMap': ILabelArrayAndMap; 'labelStatisticsAndHtmlTable': { 'labelUtterancesMap': Map<string, Set<string>>; 'labelUtterancesTotal': number; 'labelStatistics': string[][]; 'labelStatisticsHtml': string;}; 'utteranceStatisticsAndHtmlTable': { 'utteranceStatisticsMap': Map<number, number>; 'utteranceStatistics': StructTextNumber[]; 'utteranceCount': number; 'utteranceStatisticsHtml': string;}; 'spuriousLabelStatisticsAndHtmlTable': { 'spuriousLabelUtterancesMap': StructTextStringSet[]; 'spuriousLabelUtterancesTotal': number; 'spuriousLabelStatistics': string[][]; 'spuriousLabelStatisticsHtml': string; }; 'utterancesMultiLabelArrays': StructTextText[]; 'utterancesMultiLabelArraysHtml': string; 'utteranceLabelDuplicateHtml': string; }; 'evaluationReportAnalyses': { 'evaluationSummary': string; 'ambiguousAnalysis': { 'scoringAmbiguousUtterancesArrays': string[][]; 'scoringAmbiguousUtterancesArraysHtml': string; 'scoringAmbiguousUtteranceSimpleArrays': string[][];}; 'misclassifiedAnalysis': { 'scoringMisclassifiedUtterancesArrays': string[][]; 'scoringMisclassifiedUtterancesArraysHtml': string; 'scoringMisclassifiedUtterancesSimpleArrays': string[][];}; 'lowConfidenceAnalysis': { 'scoringLowConfidenceUtterancesArrays': string[][]; 'scoringLowConfidenceUtterancesArraysHtml': string; 'scoringLowConfidenceUtterancesSimpleArrays': string[][];}; 'confusionMatrixAnalysis': { 'confusionMatrix': IConfusionMatrix; 'multiLabelObjectConfusionMatrixExact': MultiLabelObjectConfusionMatrixExact; 'multiLabelObjectConfusionMatrixSubset': MultiLabelObjectConfusionMatrixSubset; 'predictingConfusionMatrixOutputLines': string[][]; 'confusionMatrixMetricsHtml': string; 'confusionMatrixAverageMetricsHtml': string; 'confusionMatrixAverageDescriptionMetricsHtml': string;};}; 'predictionStructureWithScoreLabelStringArray': PredictionStructureWithScoreLabelString[]; 'scoreOutputLines': string[][]; 'groundTruthJsonContent': string; 'predictionJsonContent': string; } = Utility.generateLabelStringEvaluationReport( UtilityLabelResolver.scoreBatchStringLabels, // ---- NOTE-FOR-REFERENCE-ALTERNATIVE-LOGIC ---- UtilityLabelResolver.scoreStringLabels, snapshotSetLabels, utteranceLabelsMap, utteranceLabelDuplicateMap, ambiguousClosenessThreshold, lowConfidenceScoreThreshold, multiLabelPredictionThreshold, unknownLabelPredictionThreshold, unknownSpuriousLabelsProcessed); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`evaluationOutputLabelString=${Utility.jsonStringify(evaluationOutputLabelString)}`); } Utility.debuggingLog('OrchestratorTest.runAsync(), finished calling Utility.generateLabelStringEvaluationReport()'); // ----------------------------------------------------------------------- // ---- NOTE ---- integrated step to produce analysis report output files. Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call Utility.generateEvaluationReportFiles()'); let evaluationSummaryLabelString: string = evaluationOutputLabelString.evaluationReportAnalyses.evaluationSummary; evaluationSummaryLabelString = evaluationSummaryLabelString.replace( '{APP_NAME}', ''); evaluationSummaryLabelString = evaluationSummaryLabelString.replace( '{MODEL_SPECIFICATION}', ''); // ----------------------------------------------------------------------- Utility.generateEvaluationReportFiles( evaluationOutputLabelString.evaluationReportLabelUtteranceStatistics.labelArrayAndMap.stringArray, evaluationOutputLabelString.scoreOutputLines, evaluationOutputLabelString.groundTruthJsonContent, evaluationOutputLabelString.predictionJsonContent, evaluationSummaryLabelString, testingSetIntentLabelsOutputFilename, testingSetIntentScoresOutputFilename, testingSetIntentGroundTruthJsonContentOutputFilename, testingSetIntentPredictionJsonContentOutputFilename, testingSetIntentSummaryHtmlOutputFilename); Utility.debuggingLog('OrchestratorTest.runAsync(), finished calling Utility.generateEvaluationReportFiles()'); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`evaluationOutputLabelString=${Utility.jsonStringify(evaluationOutputLabelString)}`); } // ----------------------------------------------------------------------- // ---- NOTE ---- Transfer non-object-label utterance from // ---- NOTE ---- utteranceLabelsMap to utteranceEntityLabelsMap // ---- NOTE ---- only do this when there is a entity model for evaluation. if (!UtilityDispatcher.isEmptyString(entityBaseModelPath)) { const numberUtterancesCopied: number = Utility.copyNonExistentUtteranceLabelsFromStringToObjectStructure( utteranceLabelsMap, utteranceEntityLabelsMap); UtilityDispatcher.debuggingNamedLog1('OrchestratorEvaluate.runAsync()', numberUtterancesCopied, 'numberUtterancesCopied'); } // ----------------------------------------------------------------------- // ---- NOTE ---- integrated step to produce entity analysis reports. Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample("false")'); UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample(false); Utility.debuggingLog('OrchestratorTest.runAsync(), finished calling UtilityLabelResolver.resetLabelResolverSettingIgnoreSameExample()'); Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call UtilityLabelResolver.generateLabelObjectEvaluationReport()'); const evaluationOutputLabelObject: { 'evaluationReportLabelUtteranceStatistics': { 'evaluationSummary': string; 'labelArrayAndMap': ILabelArrayAndMap; 'labelStatisticsAndHtmlTable': { 'labelUtterancesMap': Map<string, Set<string>>; 'labelUtterancesTotal': number; 'labelStatistics': string[][]; 'labelStatisticsHtml': string;}; 'utteranceStatisticsAndHtmlTable': { 'utteranceStatisticsMap': Map<number, number>; 'utteranceStatistics': StructTextNumber[]; 'utteranceCount': number; 'utteranceStatisticsHtml': string;}; 'spuriousLabelStatisticsAndHtmlTable': { 'spuriousLabelUtterancesMap': StructTextStringSet[]; 'spuriousLabelUtterancesTotal': number; 'spuriousLabelStatistics': string[][]; 'spuriousLabelStatisticsHtml': string; }; 'utterancesMultiLabelArrays': StructTextText[]; 'utterancesMultiLabelArraysHtml': string; 'utteranceLabelDuplicateHtml': string; }; 'evaluationReportAnalyses': { 'evaluationSummary': string; 'ambiguousAnalysis': { 'scoringAmbiguousUtterancesArrays': string[][]; 'scoringAmbiguousUtterancesArraysHtml': string; 'scoringAmbiguousUtteranceSimpleArrays': string[][];}; 'misclassifiedAnalysis': { 'scoringMisclassifiedUtterancesArrays': string[][]; 'scoringMisclassifiedUtterancesArraysHtml': string; 'scoringMisclassifiedUtterancesSimpleArrays': string[][];}; 'lowConfidenceAnalysis': { 'scoringLowConfidenceUtterancesArrays': string[][]; 'scoringLowConfidenceUtterancesArraysHtml': string; 'scoringLowConfidenceUtterancesSimpleArrays': string[][];}; 'confusionMatrixAnalysis': { 'confusionMatrix': IConfusionMatrix; 'multiLabelObjectConfusionMatrixExact': MultiLabelObjectConfusionMatrixExact; 'multiLabelObjectConfusionMatrixSubset': MultiLabelObjectConfusionMatrixSubset; 'predictingConfusionMatrixOutputLines': string[][]; 'confusionMatrixMetricsHtml': string; 'confusionMatrixAverageMetricsHtml': string; 'confusionMatrixAverageDescriptionMetricsHtml': string;};}; 'predictionStructureWithScoreLabelObjectArray': PredictionStructureWithScoreLabelObject[]; 'scoreOutputLines': string[][]; 'groundTruthJsonContent': string; 'predictionJsonContent': string; } = Utility.generateLabelObjectEvaluationReport( UtilityLabelResolver.scoreBatchObjectLabels, // ---- NOTE-FOR-REFERENCE-ALTERNATIVE-LOGIC ---- UtilityLabelResolver.scoreObjectLabels, snapshotSetEntityLabels, utteranceEntityLabelsMap, utteranceEntityLabelDuplicateMap, ambiguousClosenessThreshold, lowConfidenceScoreThreshold, multiLabelPredictionThreshold, unknownLabelPredictionThreshold, unknownSpuriousEntityLabelsProcessed); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`evaluationOutputLabelObject=${Utility.jsonStringify(evaluationOutputLabelObject)}`); } Utility.debuggingLog('OrchestratorTest.runAsync(), finished calling Utility.generateLabelObjectEvaluationReport()'); // ----------------------------------------------------------------------- // ---- NOTE ---- integrated step to produce analysis report output files. Utility.debuggingLog('OrchestratorTest.runAsync(), ready to call Utility.generateEvaluationReportFiles()'); let evaluationSummaryLabelObject: string = evaluationOutputLabelObject.evaluationReportAnalyses.evaluationSummary; evaluationSummaryLabelObject = evaluationSummaryLabelObject.replace( '{APP_NAME}', ''); evaluationSummaryLabelObject = evaluationSummaryLabelObject.replace( '{MODEL_SPECIFICATION}', ''); // ----------------------------------------------------------------------- Utility.generateEvaluationReportFiles( evaluationOutputLabelObject.evaluationReportLabelUtteranceStatistics.labelArrayAndMap.stringArray, evaluationOutputLabelObject.scoreOutputLines, evaluationOutputLabelObject.groundTruthJsonContent, evaluationOutputLabelObject.predictionJsonContent, evaluationSummaryLabelObject, testingSetEntityLabelsOutputFilename, testingSetEntityScoresOutputFilename, testingSetEntityGroundTruthJsonContentOutputFilename, testingSetEntityPredictionJsonContentOutputFilename, testingSetEntitySummaryHtmlOutputFilename); Utility.debuggingLog('OrchestratorTest.runAsync(), finished calling Utility.generateEvaluationReportFiles()'); if (Utility.toPrintDetailedDebuggingLogToConsole) { Utility.debuggingLog(`evaluationOutputLabelObject=${Utility.jsonStringify(evaluationOutputLabelObject)}`); } // ----------------------------------------------------------------------- // ---- NOTE ---- THE END Utility.debuggingLog('OrchestratorTest.runAsync(), THE END'); } }
the_stack
import { of, throwError, interval, Subject } from "rxjs"; import { eachValueFrom, bufferedValuesFrom, latestValueFrom, nextValueFrom, } from ".."; import { take, finalize } from "rxjs/operators"; describe("eachValueFrom", () => { test("should work for sync observables", async () => { const source = of(1, 2, 3); const results: number[] = []; for await (const value of eachValueFrom(source)) { results.push(value); } expect(results).toEqual([1, 2, 3]); }); test("should throw if the observable errors", async () => { const source = throwError(new Error("bad")); let error: any; try { for await (const _ of eachValueFrom(source)) { // do nothing } } catch (err) { error = err; } expect(error).toBeInstanceOf(Error); expect(error.message).toBe("bad"); }); test("should support async observables", async () => { const source = interval(1).pipe(take(3)); const results: number[] = []; for await (const value of eachValueFrom(source)) { results.push(value); } expect(results).toEqual([0, 1, 2]); }); test("should do something clever if the loop exits", async () => { let finalized = false; const source = interval(1).pipe( take(10), finalize(() => (finalized = true)) ); const results: number[] = []; try { for await (const value of eachValueFrom(source)) { results.push(value); if (value === 1) { throw new Error("bad"); } } } catch (err) { // ignore } expect(results).toEqual([0, 1]); expect(finalized).toBe(true); }); test("a more advanced test", async () => { const results: number[] = []; const source = new Subject<number>(); const advancer = createAdvancer(); async function executeTest() { for await (const value of eachValueFrom(source)) { results.push(value); await advancer; } } const complete = executeTest(); source.next(0); source.next(1); source.next(2); await advancer.next(); // A loop was waiting by the time 0 was sent, so it // will resolve, then the advancer causes it to loop // again. expect(results).toEqual([0, 1]); await advancer.next(); expect(results).toEqual([0, 1, 2]); // Nothing arrived, start the loop waiting again. await advancer.next(); expect(results).toEqual([0, 1, 2]); source.next(3); source.next(4); source.next(5); await advancer.next(); // We were waiting for 3 already, so that was resolved, // then the advancer caused the loop back around to // get 4 expect(results).toEqual([0, 1, 2, 3, 4]); await advancer.next(); expect(results).toEqual([0, 1, 2, 3, 4, 5]); // end the loop source.complete(); await complete; expect(results).toEqual([0, 1, 2, 3, 4, 5]); }); }); describe("bufferedValuesFrom", () => { test("should work for sync observables", async () => { const source = of(1, 2, 3); const results: number[][] = []; for await (const value of bufferedValuesFrom(source)) { results.push(value); } expect(results).toEqual([[1, 2, 3]]); }); test("should throw if the observable errors", async () => { const source = throwError(new Error("bad")); let error: any; try { for await (const _ of bufferedValuesFrom(source)) { // do nothing } } catch (err) { error = err; } expect(error).toBeInstanceOf(Error); expect(error.message).toBe("bad"); }); test("should support async observables", async () => { const source = interval(1).pipe(take(3)); const results: number[][] = []; for await (const value of bufferedValuesFrom(source)) { results.push(value); } expect(results).toEqual([[0], [1], [2]]); }); test("should do something clever if the loop exits", async () => { let finalized = false; const source = interval(1).pipe( take(10), finalize(() => (finalized = true)) ); const results: number[][] = []; try { for await (const value of bufferedValuesFrom(source)) { results.push(value); if (value[0] === 1) { throw new Error("bad"); } } } catch (err) { // ignore } expect(results).toEqual([[0], [1]]); expect(finalized).toBe(true); }); test("a more in-depth test", async () => { const results: number[][] = []; const source = new Subject<number>(); const advancer = createAdvancer(); async function executeTest() { for await (let buffer of bufferedValuesFrom(source)) { results.push(buffer); await advancer; } } const complete = executeTest(); source.next(0); source.next(1); source.next(2); await advancer.next(); expect(results).toEqual([[0, 1, 2]]); // Next batch source.next(3); source.next(4); await advancer.next(); expect(results).toEqual([ [0, 1, 2], [3, 4], ]); // end the loop source.complete(); await complete; expect(results).toEqual([ [0, 1, 2], [3, 4], ]); }); }); describe("latestValueFrom", () => { test("should work for sync observables", async () => { const source = of(1, 2, 3); const results: number[] = []; for await (const value of latestValueFrom(source)) { results.push(value); } expect(results).toEqual([3]); }); test("should throw if the observable errors", async () => { const source = throwError(new Error("bad")); let error: any; try { for await (const _ of latestValueFrom(source)) { // do nothing } } catch (err) { error = err; } expect(error).toBeInstanceOf(Error); expect(error.message).toBe("bad"); }); test("should support async observables", async () => { const source = interval(1).pipe(take(3)); const results: number[] = []; for await (const value of latestValueFrom(source)) { results.push(value); } expect(results).toEqual([0, 1, 2]); }); test("a more in-depth test", async () => { const results: number[] = []; const source = new Subject<number>(); const advancer = createAdvancer(); async function executeTest() { for await (let buffer of latestValueFrom(source)) { results.push(buffer); await advancer; } } const complete = executeTest(); source.next(0); source.next(1); source.next(2); await advancer.next(); expect(results).toEqual([2]); // Next batch source.next(3); source.next(4); await advancer.next(); expect(results).toEqual([2, 4]); source.next(5); source.next(6); // end the loop source.complete(); await complete; expect(results).toEqual([2, 4, 6]); }); test("a more in-depth with early exit", async () => { const results: number[] = []; const source = new Subject<number>(); const advancer = createAdvancer(); async function executeTest() { let i = 0; for await (let buffer of latestValueFrom(source)) { if (i++ === 2) { // cause an early exit here. return; } results.push(buffer); await advancer; } } const complete = executeTest(); source.next(0); source.next(1); source.next(2); await advancer.next(); expect(results).toEqual([2]); // Next batch source.next(3); source.next(4); await advancer.next(); // exit expect(results).toEqual([2, 4]); // loop would have already exited here. source.next(5); source.next(6); await advancer.next(); expect(results).toEqual([2, 4]); await complete; expect(results).toEqual([2, 4]); }); }); describe("nextValueFrom", () => { test("should work for sync observables", async () => { const source = of(1, 2, 3); const results: number[] = []; for await (const value of nextValueFrom(source)) { results.push(value); } // sync observable would have already completed. expect(results).toEqual([]); }); test("should throw if the observable errors", async () => { const source = throwError(new Error("bad")); let error: any; try { for await (const _ of nextValueFrom(source)) { // do nothing } } catch (err) { error = err; } expect(error).toBeInstanceOf(Error); expect(error.message).toBe("bad"); }); test("should support async observables", async () => { const source = interval(1).pipe(take(3)); const results: number[] = []; for await (const value of nextValueFrom(source)) { results.push(value); } expect(results).toEqual([0, 1, 2]); }); test("a more in-depth test", async () => { const results: number[] = []; const source = new Subject<number>(); const advancer = createAdvancer(); async function executeTest() { for await (let buffer of nextValueFrom(source)) { results.push(buffer); await advancer; } } const complete = executeTest(); source.next(0); source.next(1); source.next(2); await advancer.next(); expect(results).toEqual([0]); // Next batch source.next(3); source.next(4); await advancer.next(); expect(results).toEqual([0, 3]); source.next(5); source.next(6); // end the loop source.complete(); await complete; expect(results).toEqual([0, 3, 5]); }); test("a more in-depth with early exit", async () => { const results: number[] = []; const source = new Subject<number>(); const advancer = createAdvancer(); async function executeTest() { let i = 0; for await (let buffer of nextValueFrom(source)) { if (i++ === 2) { // cause an early exit here. return; } results.push(buffer); await advancer; } } const complete = executeTest(); source.next(0); source.next(1); source.next(2); await advancer.next(); expect(results).toEqual([0]); // Next batch source.next(3); source.next(4); await advancer.next(); // exit expect(results).toEqual([0, 3]); // loop would have already exited here. source.next(5); source.next(6); await advancer.next(); expect(results).toEqual([0, 3]); await complete; expect(results).toEqual([0, 3]); }); }); /** * A little trick to get the test to manually advance from * one test to the next. */ function createAdvancer() { const factory = async function*(): AsyncGenerator<any, never, any> { let prev: any; while (true) { prev = yield prev; } }; const advancer = factory(); // prime it advancer.next(); const _next = advancer.next.bind(advancer); advancer.next = async () => { return _next().then((x) => Promise.resolve(x)); }; return advancer; }
the_stack
import { ComponentClass } from "react"; import Taro, { Component, Config } from "@tarojs/taro"; import { View, Image, Text, ScrollView } from "@tarojs/components"; import { AtSearchBar, AtTabs, AtTabsPane, AtIcon } from "taro-ui"; import classnames from "classnames"; import CLoading from "../../components/CLoading"; import { connect } from "@tarojs/redux"; import CMusic from "../../components/CMusic"; import CWhiteSpace from "../../components/CWhiteSpace"; import { injectPlaySong } from "../../utils/decorators"; import { updateCanplayList, getSongInfo, updatePlayStatus } from "../../actions/song"; import { songType } from "../../constants/commonType"; import { setKeywordInHistory, formatCount, formatNumber, formatTimeStampToTime } from "../../utils/common"; import api from "../../services/api"; import "./index.scss"; type PageStateProps = { song: songType; }; type PageDispatchProps = { updateCanplayList: (object) => any; getSongInfo: (object) => any; updatePlayStatus: (object) => any; }; type IProps = PageStateProps & PageDispatchProps; type PageState = { keywords: string; activeTab: number; totalInfo: { loading: boolean; noData: boolean; songInfo: { // 单曲 songs: Array<{ id: number; name: string; al: { id: number; name: string; }; ar: Array<{ name: string; }>; }>; more: boolean; moreText?: string; }; videoInfo: { // 视频 videos: Array<{ title: string; vid: string; coverUrl: string; creator: Array<{ userName: string; }>; durationms: number; playTime: number; }>; more: boolean; moreText: string; }; userListInfo: { // 用户 users: Array<{ nickname: string; userId: number; avatarUrl: string; gender: number; signature: string; }>; more: boolean; moreText: string; }; djRadioInfo: { // 电台 djRadios: Array<{ name: string; id: number; picUrl: string; desc: string; }>; more: boolean; moreText: string; }; playListInfo: { // 歌单 playLists: Array<{ name: string; id: number; coverImgUrl: string; trackCount: number; playCount: number; creator: { nickname: string; }; }>; more: boolean; moreText?: string; }; albumInfo: { // 专辑 albums: Array<{ name: string; id: number; publishTime: number; picUrl: string; artist: { name: string; }; containedSong: string; }>; more: boolean; moreText: string; }; artistInfo: { // 歌手 artists: Array<{ name: string; id: number; picUrl: string; alias: Array<string>; }>; more: boolean; moreText: string; }; sim_query: { sim_querys: Array<{ keyword: string; }>; more: boolean; }; }; tabList: Array<{ title: string; }>; albumInfo: { // 专辑 albums: Array<{ name: string; id: number; publishTime: number; picUrl: string; artist: { name: string; }; containedSong: string; }>; more: boolean; }; artistInfo: { // 歌手 artists: Array<{ name: string; id: number; picUrl: string; alias: Array<string>; }>; more: boolean; }; djRadioInfo: { // 电台 djRadios: Array<{ name: string; id: number; picUrl: string; desc: string; }>; more: boolean; }; playListInfo: { // 歌单 playLists: Array<{ name: string; id: number; coverImgUrl: string; trackCount: number; playCount: number; creator: { nickname: string; }; }>; more: boolean; moreText?: string; }; videoInfo: { // 视频 videos: Array<{ title: string; vid: string; coverUrl: string; creator: Array<{ userName: string; }>; durationms: number; playTime: number; }>; more: boolean; }; mvInfo: { // 视频 mvs: Array<{ name: string; id: string; cover: string; artists: Array<{ name: string; }>; duration: number; playCount: number; }>; more: boolean; }; userListInfo: { // 用户 users: Array<{ nickname: string; userId: number; avatarUrl: string; gender: number; signature: string; }>; more: boolean; }; songInfo: { // 单曲 songs: Array<{ id: number; name: string; al: { id: number; name: string; }; ar: Array<{ name: string; }>; }>; more: boolean; }; sim_query: Array<{ keyword: string; }>; }; @injectPlaySong() @connect( ({ song }) => ({ song: song }), dispatch => ({ updateCanplayList(object) { dispatch(updateCanplayList(object)); }, getSongInfo(object) { dispatch(getSongInfo(object)); }, updatePlayStatus(object) { dispatch(updatePlayStatus(object)); } }) ) class Page extends Component<IProps, PageState> { /** * 指定config的类型声明为: Taro.Config * * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型 * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型 */ config: Config = { navigationBarTitleText: "搜索" }; constructor(props) { super(props); const { keywords } = this.$router.params; this.state = { // keywords: '海阔天空', keywords, activeTab: 0, totalInfo: { loading: true, noData: false, userListInfo: { users: [], more: false, moreText: "" }, videoInfo: { videos: [], more: false, moreText: "" }, playListInfo: { playLists: [], more: false, moreText: "" }, songInfo: { songs: [], more: false, moreText: "" }, albumInfo: { albums: [], more: false, moreText: "" }, djRadioInfo: { djRadios: [], more: false, moreText: "" }, artistInfo: { artists: [], more: false, moreText: "" }, sim_query: { sim_querys: [], more: false } }, tabList: [ { title: "综合" }, { title: "单曲" }, { title: "歌单" }, { title: "视频" }, { title: "歌手" }, { title: "专辑" }, { title: "主播电台" }, { title: "用户" }, { title: "MV" } ], userListInfo: { users: [], more: true }, videoInfo: { videos: [], more: true }, mvInfo: { mvs: [], more: true }, playListInfo: { playLists: [], more: true, moreText: "" }, songInfo: { songs: [], more: true }, albumInfo: { albums: [], more: true }, djRadioInfo: { djRadios: [], more: true }, artistInfo: { artists: [], more: true }, sim_query: [] }; } componentWillMount() { const { keywords } = this.state; Taro.setNavigationBarTitle({ title: `${keywords}的搜索结果` }); this.getResult(); } componentWillReceiveProps(nextProps) { console.log(this.props, nextProps); } componentWillUnmount() {} componentDidShow() {} componentDidHide() {} getResult() { const { keywords, totalInfo } = this.state; Taro.setNavigationBarTitle({ title: `${keywords}的搜索结果` }); this.setState({ totalInfo: Object.assign(totalInfo, { loading: true }) }); api .get("/search", { keywords, type: 1018 }) .then(res => { if (!res.data || !res.data.result) { this.setState({ totalInfo: Object.assign(this.state.totalInfo, { loading: false, noData: true }) }); return; } const result = res.data.result; if (result) { this.setState({ totalInfo: { loading: false, noData: !result.album && !result.artist && !result.djRadio && !result.playList && !result.song && !result.user && !result.video && !result.sim_query, albumInfo: result.album || { albums: [] }, artistInfo: result.artist || { artists: [] }, djRadioInfo: result.djRadio || { djRadios: [] }, playListInfo: result.playList || { playLists: [] }, songInfo: result.song || { songs: [] }, userListInfo: result.user || { users: [] }, videoInfo: result.video || { videos: [] }, sim_query: result.sim_query || { sim_querys: [] } } }); // this.props.updateCanplayList({ // canPlayList: res.data.result.songs // }) } }); } playSong(songId) { api .get("/check/music", { id: songId }) .then(res => { if (res.data.success) { Taro.navigateTo({ url: `/pages/songDetail/index?id=${songId}` }); } else { Taro.showToast({ title: res.data.message, icon: "none" }); } }); } goVideoDetail(id, type) { let apiUrl = "/video/url"; if (type === "mv") { apiUrl = "/mv/url"; } api .get(apiUrl, { id }) .then(({ data }) => { console.log("data", data); if ( (type === "video" && data.urls && data.urls.length) || (type === "mv" && data.data.url) ) { Taro.navigateTo({ url: `/pages/videoDetail/index?id=${id}&type=${type}` }); } else { Taro.showToast({ title: `该${type === "mv" ? "mv" : "视频"}暂无版权播放`, icon: "none" }); } }); } // 获取单曲列表 getSongList() { const { keywords, songInfo } = this.state; if (!songInfo.more) return; api .get("/search", { keywords, type: 1, limit: 30, offset: songInfo.songs.length }) .then(({ data }) => { console.log("getSongList=>data", data); if (data.result && data.result.songs) { let tempSongList = data.result.songs.map(item => { item.al = item.album; item.ar = item.artists; return item; }); this.setState({ songInfo: { songs: songInfo.songs.concat(tempSongList), more: songInfo.songs.concat(data.result.songs).length < data.result.songCount } }); } }); } // 获取歌单列表 getPlayList() { const { keywords, playListInfo } = this.state; if (!playListInfo.more) return; api .get("/search", { keywords, type: 1000, limit: 30, offset: playListInfo.playLists.length }) .then(({ data }) => { console.log("getPlayList=>data", data); if (data.result && data.result.playlists) { this.setState({ playListInfo: { playLists: playListInfo.playLists.concat(data.result.playlists), more: playListInfo.playLists.concat(data.result.playlists).length < data.result.playlistCount } }); } }); } // 获取视频列表 getVideoList() { const { keywords, videoInfo } = this.state; if (!videoInfo.more) return; api .get("/search", { keywords, type: 1014, limit: 30, offset: videoInfo.videos.length }) .then(({ data }) => { console.log("getVideoList=>data", data); if (data.result && data.result.videos) { this.setState({ videoInfo: { videos: videoInfo.videos.concat(data.result.videos), more: videoInfo.videos.concat(data.result.videos).length < data.result.videoCount } }); } }); } // 获取mv列表 getMvList() { const { keywords, mvInfo } = this.state; if (!mvInfo.more) return; api .get("/search", { keywords, type: 1004, limit: 30, offset: mvInfo.mvs.length }) .then(({ data }) => { console.log("getMvList=>data", data); if (data.result && data.result.mvs) { this.setState({ mvInfo: { mvs: mvInfo.mvs.concat(data.result.mvs), more: mvInfo.mvs.concat(data.result.mvs).length < data.result.mvCount } }); } }); } // 获取歌手列表 getArtistList() { const { keywords, artistInfo } = this.state; if (!artistInfo.more) return; api .get("/search", { keywords, type: 100, limit: 30, offset: artistInfo.artists.length }) .then(({ data }) => { console.log("getArtistList=>data", data); if (data.result && data.result.artists) { this.setState({ artistInfo: { artists: artistInfo.artists.concat(data.result.artists), more: artistInfo.artists.concat(data.result.artists).length < data.result.artistCount } }); } }); } // 获取用户列表 getUserList() { const { keywords, userListInfo } = this.state; if (!userListInfo.more) return; api .get("/search", { keywords, type: 1002, limit: 30, offset: userListInfo.users.length }) .then(({ data }) => { console.log("getUserList=>data", data); if (data.result && data.result.userprofiles) { this.setState({ userListInfo: { users: userListInfo.users.concat(data.result.userprofiles), more: userListInfo.users.concat(data.result.userprofiles).length < data.result.userprofileCount } }); } }); } // 获取专辑列表 getAlbumList() { const { keywords, albumInfo } = this.state; if (!albumInfo.more) return; api .get("/search", { keywords, type: 10, limit: 30, offset: albumInfo.albums.length }) .then(({ data }) => { console.log("getUserList=>data", data); if (data.result && data.result.albums) { this.setState({ albumInfo: { albums: albumInfo.albums.concat(data.result.albums), more: albumInfo.albums.concat(data.result.albums).length < data.result.albumCount } }); } }); } // 获取电台列表 getDjRadioList() { const { keywords, djRadioInfo } = this.state; if (!djRadioInfo.more) return; api .get("/search", { keywords, type: 1009, limit: 30, offset: djRadioInfo.djRadios.length }) .then(({ data }) => { console.log("getUserList=>data", data); if (data.result && data.result.djRadios) { this.setState({ djRadioInfo: { djRadios: djRadioInfo.djRadios.concat(data.result.djRadios), more: djRadioInfo.djRadios.concat(data.result.djRadios).length < data.result.djRadiosCount } }); } }); } goPlayListDetail(item) { Taro.navigateTo({ url: `/pages/playListDetail/index?id=${item.id}&name=${item.name}` }); } showMore() { Taro.showToast({ title: "暂未实现,敬请期待", icon: "none" }); } searchTextChange(val) { this.setState({ keywords: val }); } resetInfo() { this.setState({ userListInfo: { users: [], more: true }, videoInfo: { videos: [], more: true }, playListInfo: { playLists: [], more: true, moreText: "" }, songInfo: { songs: [], more: true }, albumInfo: { albums: [], more: true }, djRadioInfo: { djRadios: [], more: true }, artistInfo: { artists: [], more: true } }); } searchResult() { setKeywordInHistory(this.state.keywords); this.setState( { totalInfo: Object.assign(this.state.totalInfo, { loading: true }) }, () => { this.switchTab(0); this.resetInfo(); } ); } queryResultBySim(keyword) { setKeywordInHistory(keyword); this.setState( { keywords: keyword }, () => { this.getResult(); } ); } showTip() { Taro.showToast({ title: "正在开发,敬请期待", icon: "none" }); } switchTab(activeTab) { console.log("activeTab", activeTab); switch (activeTab) { case 0: this.getResult(); break; case 1: this.getSongList(); break; case 2: this.getPlayList(); break; case 3: this.getVideoList(); break; case 4: this.getArtistList(); break; case 5: this.getAlbumList(); break; case 6: this.getDjRadioList(); break; case 7: this.getUserList(); break; case 8: this.getMvList(); break; } this.setState({ activeTab }); } formatDuration(ms: number) { // @ts-ignore let minutes: string = formatNumber(parseInt(ms / 60000)); // @ts-ignore let seconds: string = formatNumber(parseInt((ms / 1000) % 60)); return `${minutes}:${seconds}`; } render() { const { keywords, activeTab, tabList, songInfo, playListInfo, totalInfo, videoInfo, artistInfo, userListInfo, albumInfo, djRadioInfo, mvInfo } = this.state; const { currentSongInfo, isPlaying, canPlayList } = this.props.song; return ( <View className={classnames({ searchResult_container: true, hasMusicBox: !!this.props.song.currentSongInfo.name })} > <CMusic songInfo={{ currentSongInfo, isPlaying, canPlayList }} onUpdatePlayStatus={this.props.updatePlayStatus.bind(this)} /> <AtSearchBar actionName="搜一下" value={keywords} onChange={this.searchTextChange.bind(this)} onActionClick={this.searchResult.bind(this)} onConfirm={this.searchResult.bind(this)} className="search__input" fixed={true} /> <View className="search_content"> <AtTabs current={activeTab} scroll tabList={tabList} onClick={this.switchTab.bind(this)} > <AtTabsPane current={activeTab} index={0}> {totalInfo.loading ? ( <CLoading /> ) : ( <ScrollView scrollY className="search_content__scroll"> {totalInfo.noData ? ( <View className="search_content__nodata">暂无数据</View> ) : ( "" )} {totalInfo.songInfo.songs.length ? ( <View> <View className="search_content__title">单曲</View> {totalInfo.songInfo.songs.map(item => ( <View key={item.id} className="searchResult__music"> <View className="searchResult__music__info" onClick={this.playSong.bind(this, item.id)} > <View className="searchResult__music__info__name"> {item.name} </View> <View className="searchResult__music__info__desc"> {`${item.ar[0] ? item.ar[0].name : ""} - ${ item.al.name }`} </View> </View> <View className="fa fa-ellipsis-v searchResult__music__icon" onClick={this.showMore.bind(this)} ></View> </View> ))} {totalInfo.songInfo.moreText ? ( <View className="search_content__more" onClick={this.switchTab.bind(this, 1)} > {totalInfo.songInfo.moreText} <AtIcon value="chevron-right" size="16" color="#ccc" ></AtIcon> </View> ) : ( "" )} </View> ) : ( "" )} {totalInfo.playListInfo.playLists.length ? ( <View> <View className="search_content__title">歌单</View> <View> {totalInfo.playListInfo.playLists.map((item, index) => ( <View className="search_content__playList__item" key={item.id} onClick={this.goPlayListDetail.bind(this, item)} > <View> <Image src={item.coverImgUrl} className="search_content__playList__item__cover" /> </View> <View className="search_content__playList__item__info"> <View className="search_content__playList__item__info__title"> {item.name} </View> <View className="search_content__playList__item__info__desc"> <Text>{item.trackCount}首音乐</Text> <Text className="search_content__playList__item__info__desc__nickname"> by {item.creator.nickname} </Text> <Text>{formatCount(item.playCount)}次</Text> </View> </View> </View> ))} {totalInfo.playListInfo.moreText ? ( <View className="search_content__more" onClick={this.switchTab.bind(this, 2)} > {totalInfo.playListInfo.moreText} <AtIcon value="chevron-right" size="16" color="#ccc" ></AtIcon> </View> ) : ( "" )} </View> </View> ) : ( "" )} {totalInfo.videoInfo.videos.length ? ( <View> <View className="search_content__title">视频</View> <View> {totalInfo.videoInfo.videos.map(item => ( <View className="search_content__video__item" key={item.vid} onClick={this.goVideoDetail.bind( this, item.vid, "video" )} > <View className="search_content__video__item__cover--wrap"> <View className="search_content__video__item__cover--playtime"> <Text className="at-icon at-icon-play"></Text> <Text>{formatCount(item.playTime)}</Text> </View> <Image src={item.coverUrl} className="search_content__video__item__cover" /> </View> <View className="search_content__video__item__info"> <View className="search_content__video__item__info__title"> {item.title} </View> <View className="search_content__video__item__info__desc"> <Text> {this.formatDuration(item.durationms)}, </Text> <Text className="search_content__video__item__info__desc__nickname"> by {item.creator[0].userName} </Text> </View> </View> </View> ))} {totalInfo.videoInfo.moreText ? ( <View className="search_content__more" onClick={this.switchTab.bind(this, 3)} > {totalInfo.videoInfo.moreText} <AtIcon value="chevron-right" size="16" color="#ccc" ></AtIcon> </View> ) : ( "" )} </View> </View> ) : ( "" )} {totalInfo.sim_query.sim_querys.length ? ( <View> <View className="search_content__title">相关搜索</View> <View className="search_content__simquery"> {totalInfo.sim_query.sim_querys.map(item => ( <Text key={item.keyword} onClick={this.queryResultBySim.bind( this, item.keyword )} className="search_content__simquery__item" > {item.keyword} </Text> ))} </View> </View> ) : ( "" )} {totalInfo.artistInfo.artists.length ? ( <View> <View className="search_content__title">歌手</View> <View> {totalInfo.artistInfo.artists.map(item => ( <View className="search_content__artist__item" key={item.id} onClick={this.showTip.bind(this)} > <Image src={item.picUrl} className="search_content__artist__item__cover" /> <Text> {item.name} {item.alias[0] ? `(${item.alias[0]})` : ""} </Text> </View> ))} {totalInfo.artistInfo.moreText ? ( <View className="search_content__more" onClick={this.switchTab.bind(this, 4)} > {totalInfo.artistInfo.moreText} <AtIcon value="chevron-right" size="16" color="#ccc" ></AtIcon> </View> ) : ( "" )} </View> </View> ) : ( "" )} {totalInfo.albumInfo.albums.length ? ( <View> <View className="search_content__title">专辑</View> <View> {totalInfo.albumInfo.albums.map(item => ( <View className="search_content__playList__item" key={item.id} onClick={this.showTip.bind(this)} > <View> <Image src={item.picUrl} className="search_content__playList__item__cover" /> </View> <View className="search_content__playList__item__info"> <View className="search_content__playList__item__info__title"> {item.name} </View> <View className="search_content__playList__item__info__desc"> <Text>{item.artist.name}</Text> <Text className="search_content__playList__item__info__desc__nickname"> {item.containedSong ? `包含单曲:${item.containedSong}` : formatTimeStampToTime(item.publishTime)} </Text> </View> </View> </View> ))} {totalInfo.albumInfo.moreText ? ( <View className="search_content__more" onClick={this.switchTab.bind(this, 5)} > {totalInfo.albumInfo.moreText} <AtIcon value="chevron-right" size="16" color="#ccc" ></AtIcon> </View> ) : ( "" )} </View> </View> ) : ( "" )} {totalInfo.djRadioInfo.djRadios.length ? ( <View> <View className="search_content__title">电台</View> <View> {totalInfo.djRadioInfo.djRadios.map(item => ( <View className="search_content__playList__item" key={item.id} onClick={this.showTip.bind(this)} > <View> <Image src={item.picUrl} className="search_content__playList__item__cover" /> </View> <View className="search_content__playList__item__info"> <View className="search_content__playList__item__info__title"> {item.name} </View> <View className="search_content__playList__item__info__desc"> <Text>{item.desc}</Text> </View> </View> </View> ))} {totalInfo.djRadioInfo.moreText ? ( <View className="search_content__more" onClick={this.switchTab.bind(this, 6)} > {totalInfo.djRadioInfo.moreText} <AtIcon value="chevron-right" size="16" color="#ccc" ></AtIcon> </View> ) : ( "" )} </View> </View> ) : ( "" )} {totalInfo.userListInfo.users.length ? ( <View> <View className="search_content__title">用户</View> <View> {totalInfo.userListInfo.users.map(item => ( <View className="search_content__artist__item" key={item.userId} onClick={this.showTip.bind(this)} > <Image src={item.avatarUrl} className="search_content__artist__item__cover" /> <View className="search_content__artist__item__info"> <View> {item.nickname} {item.gender === 1 ? ( <AtIcon prefixClass="fa" value="mars" size="12" color="#5cb8e7" ></AtIcon> ) : ( "" )} {item.gender === 2 ? ( <AtIcon prefixClass="fa" value="venus" size="12" color="#f88fb8" ></AtIcon> ) : ( "" )} </View> {item.signature ? ( <View className="search_content__artist__item__desc"> {item.signature} </View> ) : ( "" )} </View> </View> ))} {totalInfo.userListInfo.moreText ? ( <View className="search_content__more" onClick={this.switchTab.bind(this, 7)} > {totalInfo.userListInfo.moreText} <AtIcon value="chevron-right" size="16" color="#ccc" ></AtIcon> </View> ) : ( "" )} </View> </View> ) : ( "" )} </ScrollView> )} </AtTabsPane> <AtTabsPane current={activeTab} index={1}> <ScrollView scrollY onScrollToLower={this.getSongList.bind(this)} className="search_content__scroll" > {songInfo.songs.map(item => ( <View key={item.id} className="searchResult__music"> <View className="searchResult__music__info" onClick={this.playSong.bind(this, item.id)} > <View className="searchResult__music__info__name"> {item.name} </View> <View className="searchResult__music__info__desc"> {`${item.ar[0] ? item.ar[0].name : ""} - ${ item.al.name }`} </View> </View> <View className="fa fa-ellipsis-v searchResult__music__icon" onClick={this.showMore.bind(this)} ></View> </View> ))} {songInfo.more ? <CLoading /> : ""} </ScrollView> </AtTabsPane> <AtTabsPane current={activeTab} index={2}> <ScrollView scrollY onScrollToLower={this.getPlayList.bind(this)} className="search_content__scroll" > <CWhiteSpace size="sm" color="#fff" /> {playListInfo.playLists.map(item => ( <View className="search_content__playList__item" key={item.id} onClick={this.goPlayListDetail.bind(this, item)} > <View> <Image src={item.coverImgUrl} className="search_content__playList__item__cover" /> </View> <View className="search_content__playList__item__info"> <View className="search_content__playList__item__info__title"> {item.name} </View> <View className="search_content__playList__item__info__desc"> <Text>{item.trackCount}首音乐</Text> <Text className="search_content__playList__item__info__desc__nickname"> by {item.creator.nickname} </Text> <Text>{formatCount(item.playCount)}次</Text> </View> </View> </View> ))} {playListInfo.more ? <CLoading /> : ""} </ScrollView> </AtTabsPane> <AtTabsPane current={activeTab} index={3}> <ScrollView scrollY onScrollToLower={this.getVideoList.bind(this)} className="search_content__scroll" > <CWhiteSpace size="sm" color="#fff" /> {videoInfo.videos.map((item, index) => ( <View className="search_content__video__item" key={item.vid} onClick={this.goVideoDetail.bind(this, item.vid, "video")} > <View className="search_content__video__item__cover--wrap"> <View className="search_content__video__item__cover--playtime"> <Text className="at-icon at-icon-play"></Text> <Text>{formatCount(item.playTime)}</Text> </View> <Image src={item.coverUrl} className="search_content__video__item__cover" /> </View> <View className="search_content__video__item__info"> <View className="search_content__video__item__info__title"> {item.title} </View> <View className="search_content__video__item__info__desc"> <Text>{this.formatDuration(item.durationms)},</Text> <Text className="search_content__video__item__info__desc__nickname"> by {item.creator[0].userName} </Text> </View> </View> </View> ))} {videoInfo.more ? <CLoading /> : ""} </ScrollView> </AtTabsPane> <AtTabsPane current={activeTab} index={4}> <ScrollView scrollY onScrollToLower={this.getArtistList.bind(this)} className="search_content__scroll" > <CWhiteSpace size="sm" color="#fff" /> {artistInfo.artists.map(item => ( <View className="search_content__artist__item" key={item.id} onClick={this.showTip.bind(this)} > <Image src={item.picUrl} className="search_content__artist__item__cover" /> <Text> {item.name} {item.alias[0] ? `(${item.alias[0]})` : ""} </Text> </View> ))} {artistInfo.more ? <CLoading /> : ""} </ScrollView> </AtTabsPane> <AtTabsPane current={activeTab} index={5}> <ScrollView scrollY onScrollToLower={this.getAlbumList.bind(this)} className="search_content__scroll" > <CWhiteSpace size="sm" color="#fff" /> {albumInfo.albums.map(item => ( <View className="search_content__playList__item" key={item.id} onClick={this.showTip.bind(this)} > <View> <Image src={item.picUrl} className="search_content__playList__item__cover" /> </View> <View className="search_content__playList__item__info"> <View className="search_content__playList__item__info__title"> {item.name} </View> <View className="search_content__playList__item__info__desc"> <Text>{item.artist.name}</Text> <Text className="search_content__playList__item__info__desc__nickname"> {item.containedSong ? `包含单曲:${item.containedSong}` : formatTimeStampToTime(item.publishTime)} </Text> </View> </View> </View> ))} {albumInfo.more ? <CLoading /> : ""} </ScrollView> </AtTabsPane> <AtTabsPane current={activeTab} index={6}> <ScrollView scrollY onScrollToLower={this.getDjRadioList.bind(this)} className="search_content__scroll" > <CWhiteSpace size="sm" color="#fff" /> {djRadioInfo.djRadios.map(item => ( <View className="search_content__playList__item" key={item.id} onClick={this.showTip.bind(this)} > <View> <Image src={item.picUrl} className="search_content__playList__item__cover" /> </View> <View className="search_content__playList__item__info"> <View className="search_content__playList__item__info__title"> {item.name} </View> <View className="search_content__playList__item__info__desc"> <Text>{item.desc}</Text> </View> </View> </View> ))} {djRadioInfo.more ? <CLoading /> : ""} </ScrollView> </AtTabsPane> <AtTabsPane current={activeTab} index={7}> <ScrollView scrollY onScrollToLower={this.getUserList.bind(this)} className="search_content__scroll" > <CWhiteSpace size="sm" color="#fff" /> {userListInfo.users.map(item => ( <View className="search_content__artist__item" key={item.userId} onClick={this.showTip.bind(this)} > <Image src={item.avatarUrl} className="search_content__artist__item__cover" /> <View className="search_content__artist__item__info"> <View> {item.nickname} {item.gender === 1 ? ( <AtIcon prefixClass="fa" value="mars" size="12" color="#5cb8e7" ></AtIcon> ) : ( "" )} {item.gender === 2 ? ( <AtIcon prefixClass="fa" value="venus" size="12" color="#f88fb8" ></AtIcon> ) : ( "" )} </View> <View className="search_content__artist__item__desc"> {item.signature} </View> </View> </View> ))} {userListInfo.more ? <CLoading /> : ""} </ScrollView> </AtTabsPane> <AtTabsPane current={activeTab} index={8}> <ScrollView scrollY onScrollToLower={this.getVideoList.bind(this)} className="search_content__scroll" > <CWhiteSpace size="sm" color="#fff" /> {mvInfo.mvs.map(item => ( <View className="search_content__video__item" key={item.id} onClick={this.goVideoDetail.bind(this, item.id, "mv")} > <View className="search_content__video__item__cover--wrap"> <View className="search_content__video__item__cover--playtime"> <Text className="at-icon at-icon-play"></Text> <Text>{formatCount(item.playCount)}</Text> </View> <Image src={item.cover} className="search_content__video__item__cover" /> </View> <View className="search_content__video__item__info"> <View className="search_content__video__item__info__title"> {item.name} </View> <View className="search_content__video__item__info__desc"> <Text>{this.formatDuration(item.duration)},</Text> <Text className="search_content__video__item__info__desc__nickname"> by {item.artists[0].name} </Text> </View> </View> </View> ))} {mvInfo.more ? <CLoading /> : ""} </ScrollView> </AtTabsPane> </AtTabs> </View> </View> ); } } // #region 导出注意 // // 经过上面的声明后需要将导出的 Taro.Component 子类修改为子类本身的 props 属性 // 这样在使用这个子类时 Ts 才不会提示缺少 JSX 类型参数错误 // // #endregion export default Page as ComponentClass;
the_stack
interface JQueryStatic { api: SemanticUI.Api; } interface JQuery { api: SemanticUI.Api; } declare namespace SemanticUI { interface Api { settings: ApiSettings; /** * Execute query using existing API settings */ (behavior: 'query'): JQuery; /** * Adds data to existing templated url and returns full url string */ (behavior: 'add url data', url: string, data: any): string; /** * Gets promise for current API request */ (behavior: 'get request'): JQueryDeferred<any> | false; /** * Aborts current API request */ (behavior: 'abort'): JQuery; /** * Removes loading and error state from element */ (behavior: 'reset'): JQuery; /** * Returns whether last request was cancelled */ (behavior: 'was cancelled'): boolean; /** * Returns whether last request was failure */ (behavior: 'was failure'): boolean; /** * Returns whether last request was successful */ (behavior: 'was successful'): boolean; /** * Returns whether last request was completed */ (behavior: 'was complete'): boolean; /** * Returns whether element is disabled */ (behavior: 'is disabled'): boolean; /** * Returns whether element response is mocked */ (behavior: 'is mocked'): boolean; /** * Returns whether element is loading */ (behavior: 'is loading'): boolean; /** * Sets loading state to element */ (behavior: 'set loading'): JQuery; /** * Sets error state to element */ (behavior: 'set error'): JQuery; /** * Removes loading state to element */ (behavior: 'remove loading'): JQuery; /** * Removes error state to element */ (behavior: 'remove error'): JQuery; /** * Gets event that API request will occur on */ (behavior: 'get event'): string; /** * Returns encodeURIComponent value only if value passed is not already encoded */ (behavior: 'get url encoded value', value: any): string; /** * Reads a locally cached response for a URL */ (behavior: 'read cached response', url: string): any; /** * Writes a cached response for a URL */ (behavior: 'write cached response', url: string, response: any): JQuery; /** * Creates new cache, removing all locally cached URLs */ (behavior: 'create cache'): JQuery; /** * Removes API settings from the page and all events */ (behavior: 'destroy'): JQuery; <K extends keyof ApiSettings>(behavior: 'setting', name: K, value?: undefined): ApiSettings._Impl[K]; <K extends keyof ApiSettings>(behavior: 'setting', name: K, value: ApiSettings._Impl[K]): JQuery; (behavior: 'setting', value: ApiSettings): JQuery; (settings?: ApiSettings): JQuery; } /** * @see {@link http://semantic-ui.com/behaviors/api.html#/settings} */ type ApiSettings = ApiSettings.Param; namespace ApiSettings { type Param = (Pick<_Impl, 'api'> | Pick<_Impl, 'on'> | Pick<_Impl, 'cache'> | Pick<_Impl, 'stateContext'> | Pick<_Impl, 'encodeParameters'> | Pick<_Impl, 'defaultData'> | Pick<_Impl, 'serializeForm'> | Pick<_Impl, 'throttle'> | Pick<_Impl, 'throttleFirstRequest'> | Pick<_Impl, 'interruptRequests'> | Pick<_Impl, 'loadingDuration'> | Pick<_Impl, 'hideError'> | Pick<_Impl, 'errorDuration'> | Pick<_Impl, 'action'> | Pick<_Impl, 'url'> | Pick<_Impl, 'urlData'> | Pick<_Impl, 'response'> | Pick<_Impl, 'responseAsync'> | Pick<_Impl, 'mockResponse'> | Pick<_Impl, 'mockResponseAsync'> | Pick<_Impl, 'method'> | Pick<_Impl, 'dataType'> | Pick<_Impl, 'data'> | Pick<_Impl, 'beforeSend'> | Pick<_Impl, 'beforeXHR'> | Pick<_Impl, 'onRequest'> | Pick<_Impl, 'onResponse'> | Pick<_Impl, 'successTest'> | Pick<_Impl, 'onSuccess'> | Pick<_Impl, 'onComplete'> | Pick<_Impl, 'onFailure'> | Pick<_Impl, 'onError'> | Pick<_Impl, 'onAbort'> | Pick<_Impl, 'regExp'> | Pick<_Impl, 'selector'> | Pick<_Impl, 'className'> | Pick<_Impl, 'metadata'> | Pick<_Impl, 'error'> | Pick<_Impl, 'namespace'> | Pick<_Impl, 'name'> | Pick<_Impl, 'silent'> | Pick<_Impl, 'debug'> | Pick<_Impl, 'performance'> | Pick<_Impl, 'verbose'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { api: { [action: string]: string; }; // region Behavior /** * When API event should occur * * @default 'auto' */ on: string; /** * Can be set to 'local' to cache successful returned AJAX responses when using a JSON API. * This helps avoid server round trips when API endpoints will return the same results when accessed repeatedly. * Setting to false, will add cache busting parameters to the URL. * * @default true */ cache: 'local' | boolean; /** * UI state will be applied to this element, defaults to triggering element. */ stateContext: string | JQuery; /** * Whether to encode parameters with encodeURIComponent before adding into url string * * @default true */ encodeParameters: boolean; /** * Whether to automatically include default data like {value} and {text} * * @default true */ defaultData: boolean; /** * Whether to serialize closest form and include in request * * @default false */ serializeForm: boolean; /** * How long to wait when a request is made before triggering request, useful for rate limiting oninput * * @default 0 */ throttle: number; /** * When set to false will not delay the first request made, when no others are queued * * @default true */ throttleFirstRequest: boolean; /** * Whether an API request can occur while another request is still pending * * @default false */ interruptRequests: boolean; /** * Minimum duration to show loading indication * * @default 0 */ loadingDuration: number; /** * The default auto will automatically remove error state after error duration, unless the element is a form * * @default 'auto' */ hideError: 'auto' | boolean; /** * Setting to true, will not remove error. * Setting to a duration in milliseconds to show error state after request error. * * @default 2000 */ errorDuration: true | number; // endregion // region Request Settings /** * Named API action for query, originally specified in $.fn.settings.api */ action: string | false; /** * Templated URL for query, will override specified action */ url: string | false; /** * Variables to use for replacement */ urlData: any | false; /** * Can be set to a Javascript object which will be returned automatically instead of requesting JSON from server */ response: any | false; /** * When specified, this function can be used to retrieve content from a server and return it asynchronously instead of a standard AJAX call. * The callback function should return the server response. * * @default false */ responseAsync: ((settings: ApiSettings, callback: (response: any) => void) => void) | false; /** * @see response */ mockResponse: any | false; /** * @see responseAsync */ mockResponseAsync: ((settings: ApiSettings, callback: (response: any) => void) => void) | false; /** * Method for transmitting request to server */ method: 'post' | 'get' | 'put' | 'delete' | 'head' | 'options' | 'patch'; /** * Expected data type of response */ dataType: 'xml' | 'json' | 'jsonp' | 'script' | 'html' | 'text'; /** * POST/GET Data to Send with Request */ data: any; // endregion // region Callbacks /** * Allows modifying settings before request, or cancelling request */ beforeSend(settings: ApiSettings): any; /** * Allows modifying XHR object for request */ beforeXHR(xhrObject: JQuery.jqXHR): any; /** * Callback that occurs when request is made. Receives both the API success promise and the XHR request promise. */ onRequest(promise: JQuery.Deferred<any>, xhr: JQuery.jqXHR): void; /** * Allows modifying the server's response before parsed by other callbacks to determine API event success */ onResponse(response: any): void; /** * Determines whether completed JSON response should be treated as successful * * @see {@link http://semantic-ui.com/behaviors/api.html#determining-json-success} */ successTest(response: any): boolean; /** * Callback after successful response, JSON response must pass successTest */ onSuccess(response: any, element: JQuery, xhr: JQuery.jqXHR): void; /** * Callback on request complete regardless of conditions */ onComplete(response: any, element: JQuery, xhr: JQuery.jqXHR): void; /** * Callback on failed response, or JSON response that fails successTest */ onFailure(response: any, element: JQuery): void; /** * Callback on server error from returned status code, or XHR failure. */ onError(errorMessage: string, element: JQuery, xhr: JQuery.jqXHR): void; /** * Callback on abort caused by user clicking a link or manually cancelling request. */ onAbort(errorMessage: string, element: JQuery, xhr: JQuery.jqXHR): void; // endregion // region DOM Settings /** * Regular expressions used for template matching */ regExp: Api.RegExpSettings; /** * Selectors used to find parts of a module */ selector: Api.SelectorSettings; /** * Class names used to determine element state */ className: Api.ClassNameSettings; /** * Metadata used to store XHR and response promise */ metadata: Api.MetadataSettings; // endregion // region Debug Settings error: Api.ErrorSettings; // endregion // region Component Settings // region DOM Settings /** * Event namespace. Makes sure module teardown does not effect other events attached to an element. */ namespace: string; // endregion // region Debug Settings /** * Name used in log statements */ name: string; /** * Silences all console output including error messages, regardless of other debug settings. */ silent: boolean; /** * Debug output to console */ debug: boolean; /** * Show console.table output with performance metrics */ performance: boolean; /** * Debug output includes all internal behaviors */ verbose: boolean; // endregion // endregion } } namespace Api { type RegExpSettings = RegExpSettings.Param; namespace RegExpSettings { type Param = (Pick<_Impl, 'required'> | Pick<_Impl, 'optional'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default /\{\$*[A-z0-9]+\}/g */ required: RegExp; /** * @default /\{\/\$*[A-z0-9]+\}/g */ optional: RegExp; } } type SelectorSettings = SelectorSettings.Param; namespace SelectorSettings { type Param = (Pick<_Impl, 'disabled'> | Pick<_Impl, 'form'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default '.disabled' */ disabled: string; /** * @default 'form' */ form: string; } } type ClassNameSettings = ClassNameSettings.Param; namespace ClassNameSettings { type Param = (Pick<_Impl, 'loading'> | Pick<_Impl, 'error'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'loading' */ loading: string; /** * @default 'error' */ error: string; } } type MetadataSettings = MetadataSettings.Param; namespace MetadataSettings { type Param = (Pick<_Impl, 'action'> | Pick<_Impl, 'url'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'action' */ action: string; /** * @default 'url' */ url: string; } } type ErrorSettings = ErrorSettings.Param; namespace ErrorSettings { type Param = (Pick<_Impl, 'beforeSend'> | Pick<_Impl, 'error'> | Pick<_Impl, 'exitConditions'> | Pick<_Impl, 'JSONParse'> | Pick<_Impl, 'legacyParameters'> | Pick<_Impl, 'missingAction'> | Pick<_Impl, 'missingSerialize'> | Pick<_Impl, 'missingURL'> | Pick<_Impl, 'noReturnedValue'> | Pick<_Impl, 'parseError'> | Pick<_Impl, 'requiredParameter'> | Pick<_Impl, 'statusMessage'> | Pick<_Impl, 'timeout'>) & Partial<Pick<_Impl, keyof _Impl>>; interface _Impl { /** * @default 'The before send function has aborted the request' */ beforeSend: string; /** * @default 'There was an error with your request' */ error: string; /** * @default 'API Request Aborted. Exit conditions met' */ exitConditions: string; /** * @default 'JSON could not be parsed during error handling' */ JSONParse: string; /** * @default 'You are using legacy API success callback names' */ legacyParameters: string; /** * @default 'API action used but no url was defined' */ missingAction: string; /** * @default 'Required dependency jquery-serialize-object missing, using basic serialize' */ missingSerialize: string; /** * @default 'No URL specified for API event' */ missingURL: string; /** * @default 'The beforeSend callback must return a settings object, beforeSend ignored.' */ noReturnedValue: string; /** * @default 'There was an error parsing your request' */ parseError: string; /** * @default 'Missing a required URL parameter: ' */ requiredParameter: string; /** * @default 'Server gave an error: ' */ statusMessage: string; /** * @default 'Your request timed out' */ timeout: string; } } } }
the_stack
import { BaseState } from "../baseState"; import { WebGlConstants, WebGlConstantsByName, WebGlConstant, WebGlConstantsByValue } from "../../types/webglConstants"; import { DrawCallTextureInputState } from "./drawCallTextureInputState"; import { DrawCallUboInputState } from "./drawCallUboInputState"; import { ProgramRecompilerHelper } from "../../utils/programRecompilerHelper"; import { drawCommands } from "../../utils/drawCommands"; import { Program } from "../../webGlObjects/webGlObjects"; import { IContextInformation } from "../../types/contextInformation"; import { IRenderBufferRecorderData } from "../../recorders/renderBufferRecorder"; import { IBufferRecorderData } from "../../recorders/bufferRecorder"; import { ReadProgramHelper } from "../../utils/readProgramHelper"; export class DrawCallState extends BaseState { public static readonly stateName = "DrawCall"; public get stateName(): string { return DrawCallState.stateName; } private static samplerTypes = { [WebGlConstants.SAMPLER_2D.value]: WebGlConstants.TEXTURE_2D, [WebGlConstants.SAMPLER_CUBE.value]: WebGlConstants.TEXTURE_CUBE_MAP, [WebGlConstants.SAMPLER_3D.value]: WebGlConstants.TEXTURE_3D, [WebGlConstants.SAMPLER_2D_SHADOW.value]: WebGlConstants.TEXTURE_2D, [WebGlConstants.SAMPLER_2D_ARRAY.value]: WebGlConstants.TEXTURE_2D_ARRAY, [WebGlConstants.SAMPLER_2D_ARRAY_SHADOW.value]: WebGlConstants.TEXTURE_2D_ARRAY, [WebGlConstants.SAMPLER_CUBE_SHADOW.value]: WebGlConstants.TEXTURE_CUBE_MAP, [WebGlConstants.INT_SAMPLER_2D.value]: WebGlConstants.TEXTURE_2D, [WebGlConstants.INT_SAMPLER_3D.value]: WebGlConstants.TEXTURE_3D, [WebGlConstants.INT_SAMPLER_CUBE.value]: WebGlConstants.TEXTURE_CUBE_MAP, [WebGlConstants.INT_SAMPLER_2D_ARRAY.value]: WebGlConstants.TEXTURE_2D_ARRAY, [WebGlConstants.UNSIGNED_INT_SAMPLER_2D.value]: WebGlConstants.TEXTURE_2D, [WebGlConstants.UNSIGNED_INT_SAMPLER_3D.value]: WebGlConstants.TEXTURE_3D, [WebGlConstants.UNSIGNED_INT_SAMPLER_CUBE.value]: WebGlConstants.TEXTURE_CUBE_MAP, [WebGlConstants.UNSIGNED_INT_SAMPLER_2D_ARRAY.value]: WebGlConstants.TEXTURE_2D_ARRAY, }; public get requireStartAndStopStates(): boolean { return false; } private readonly drawCallTextureInputState: DrawCallTextureInputState; private readonly drawCallUboInputState: DrawCallUboInputState; constructor(options: IContextInformation) { super(options); this.drawCallTextureInputState = new DrawCallTextureInputState(options); this.drawCallUboInputState = new DrawCallUboInputState(options); } protected getConsumeCommands(): string[] { return drawCommands; } protected getChangeCommandsByState(): { [key: string]: string[] } { return {}; } protected readFromContext(): void { const program = this.context.getParameter(WebGlConstants.CURRENT_PROGRAM.value); if (!program) { return; } this.currentState.frameBuffer = this.readFrameBufferFromContext(); const programCapture = program.__SPECTOR_Object_CustomData ? program.__SPECTOR_Object_CustomData : ReadProgramHelper.getProgramData(this.context, program); this.currentState.programStatus = { ...programCapture.programStatus }; this.currentState.programStatus.program = this.getSpectorData(program); this.currentState.programStatus.RECOMPILABLE = ProgramRecompilerHelper.isBuildableProgram(program); if (this.currentState.programStatus.RECOMPILABLE) { Program.saveInGlobalStore(program); } this.currentState.shaders = programCapture.shaders; if (this.lastCommandName?.indexOf("Elements") >= 0) { const elementArrayBuffer = this.context.getParameter(this.context.ELEMENT_ARRAY_BUFFER_BINDING); if (elementArrayBuffer) { this.currentState.elementArray = {}; this.currentState.elementArray.arrayBuffer = this.getSpectorData(elementArrayBuffer); } } const attributes = this.context.getProgramParameter(program, WebGlConstants.ACTIVE_ATTRIBUTES.value); this.currentState.attributes = []; for (let i = 0; i < attributes; i++) { const attributeState = this.readAttributeFromContext(program, i); this.currentState.attributes.push(attributeState); } const uniforms = this.context.getProgramParameter(program, WebGlConstants.ACTIVE_UNIFORMS.value); this.currentState.uniforms = []; const uniformIndices = []; for (let i = 0; i < uniforms; i++) { uniformIndices.push(i); const uniformState = this.readUniformFromContext(program, i); this.currentState.uniforms.push(uniformState); } if (this.contextVersion > 1) { const uniformBlocks = this.context.getProgramParameter(program, WebGlConstants.ACTIVE_UNIFORM_BLOCKS.value); this.currentState.uniformBlocks = []; for (let i = 0; i < uniformBlocks; i++) { const uniformBlockState = this.readUniformBlockFromContext(program, i); this.currentState.uniformBlocks.push(uniformBlockState); } this.readUniformsFromContextIntoState(program, uniformIndices, this.currentState.uniforms, this.currentState.uniformBlocks); const transformFeedbackActive = this.context.getParameter(WebGlConstants.TRANSFORM_FEEDBACK_ACTIVE.value); if (transformFeedbackActive) { const transformFeedbackModeValue = this.context.getProgramParameter(program, WebGlConstants.TRANSFORM_FEEDBACK_BUFFER_MODE.value); this.currentState.transformFeedbackMode = this.getWebGlConstant(transformFeedbackModeValue); this.currentState.transformFeedbacks = []; const transformFeedbacks = this.context.getProgramParameter(program, WebGlConstants.TRANSFORM_FEEDBACK_VARYINGS.value); for (let i = 0; i < transformFeedbacks; i++) { const transformFeedbackState = this.readTransformFeedbackFromContext(program, i); this.currentState.transformFeedbacks.push(transformFeedbackState); } } } // Insert texture state at the end of the uniform datas. for (let i = 0; i < uniformIndices.length; i++) { const uniformState = this.currentState.uniforms[i]; if (uniformState.value !== null && uniformState.value !== undefined) { const textureTarget = DrawCallState.samplerTypes[uniformState.typeValue]; if (textureTarget) { if (uniformState.value.length) { uniformState.textures = []; for (let j = 0; j < uniformState.value.length; j++) { uniformState.textures.push(this.readTextureFromContext(uniformState.value[j], textureTarget)); } } else { uniformState.texture = this.readTextureFromContext(uniformState.value, textureTarget); } } } delete uniformState.typeValue; } } protected readFrameBufferFromContext(): any { const frameBuffer = this.context.getParameter(WebGlConstants.FRAMEBUFFER_BINDING.value); if (!frameBuffer) { return null; } const frameBufferState: any = {}; frameBufferState.frameBuffer = this.getSpectorData(frameBuffer); const depthAttachment = this.readFrameBufferAttachmentFromContext(WebGlConstants.DEPTH_ATTACHMENT.value); if (depthAttachment) { frameBufferState.depthAttachment = this.readFrameBufferAttachmentFromContext(WebGlConstants.DEPTH_ATTACHMENT.value); } const stencilAttachment = this.readFrameBufferAttachmentFromContext(WebGlConstants.STENCIL_ATTACHMENT.value); if (stencilAttachment) { frameBufferState.stencilAttachment = this.readFrameBufferAttachmentFromContext(WebGlConstants.STENCIL_ATTACHMENT.value); } const drawBuffersExtension = this.extensions[WebGlConstants.MAX_DRAW_BUFFERS_WEBGL.extensionName]; if (drawBuffersExtension) { frameBufferState.colorAttachments = []; const maxDrawBuffers = this.context.getParameter(WebGlConstants.MAX_DRAW_BUFFERS_WEBGL.value); for (let i = 0; i < maxDrawBuffers; i++) { const attachment = this.readFrameBufferAttachmentFromContext(WebGlConstantsByName["COLOR_ATTACHMENT" + i + "_WEBGL"].value); if (attachment) { frameBufferState.colorAttachments.push(attachment); } } } else if (this.contextVersion > 1) { const context2 = this.context as WebGL2RenderingContext; // Already covered ny the introspection of depth and stencil. // frameBufferState.depthStencilAttachment = this.readFrameBufferAttachmentFromContext(WebGlConstants.DEPTH_STENCIL_ATTACHMENT.value); frameBufferState.colorAttachments = []; const maxDrawBuffers = context2.getParameter(WebGlConstants.MAX_DRAW_BUFFERS.value); for (let i = 0; i < maxDrawBuffers; i++) { const attachment = this.readFrameBufferAttachmentFromContext(WebGlConstantsByName["COLOR_ATTACHMENT" + i].value); if (attachment) { frameBufferState.colorAttachments.push(attachment); } } } else { const attachment = this.readFrameBufferAttachmentFromContext(WebGlConstantsByName["COLOR_ATTACHMENT0"].value); if (attachment) { frameBufferState.colorAttachments = [attachment]; } } return frameBufferState; } protected readFrameBufferAttachmentFromContext(attachment: number): any { const target = WebGlConstants.FRAMEBUFFER.value; const type = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE.value); if (type === WebGlConstants.NONE.value) { return undefined; } const attachmentState: any = {}; const storage = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME.value); if (type === WebGlConstants.RENDERBUFFER.value) { attachmentState.type = "RENDERBUFFER"; attachmentState.buffer = this.getSpectorData(storage); // Check for custom data. if (storage) { const customData: IRenderBufferRecorderData = (storage as any).__SPECTOR_Object_CustomData; if (customData) { if (customData.internalFormat) { attachmentState.internalFormat = this.getWebGlConstant(customData.internalFormat); } attachmentState.width = customData.width; attachmentState.height = customData.height; attachmentState.msaaSamples = customData.samples; } } } else if (type === WebGlConstants.TEXTURE.value) { attachmentState.type = "TEXTURE"; attachmentState.texture = this.getSpectorData(storage); attachmentState.textureLevel = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL.value); const cubeMapFace = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE.value); attachmentState.textureCubeMapFace = this.getWebGlConstant(cubeMapFace); this.drawCallTextureInputState.appendTextureState(attachmentState, storage, null, this.fullCapture); } if (this.extensions["EXT_sRGB"]) { attachmentState.encoding = this.getWebGlConstant(this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT.value)); } if (this.contextVersion > 1) { attachmentState.alphaSize = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE.value); attachmentState.blueSize = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_BLUE_SIZE.value); attachmentState.encoding = this.getWebGlConstant(this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING.value)); attachmentState.componentType = this.getWebGlConstant(this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE.value)); attachmentState.depthSize = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE.value); attachmentState.greenSize = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_GREEN_SIZE.value); attachmentState.redSize = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_RED_SIZE.value); attachmentState.stencilSize = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE.value); if (type === WebGlConstants.TEXTURE.value) { attachmentState.textureLayer = this.context.getFramebufferAttachmentParameter(target, attachment, WebGlConstants.FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER.value); } } return attachmentState; } protected readAttributeFromContext(program: WebGLProgram, activeAttributeIndex: number): {} { const info = this.context.getActiveAttrib(program, activeAttributeIndex); const location = this.context.getAttribLocation(program, info.name); if (location === -1) { return { name: info.name, size: info.size, type: this.getWebGlConstant(info.type), location: -1, }; } const unbufferedValue = this.context.getVertexAttrib(location, WebGlConstants.CURRENT_VERTEX_ATTRIB.value); const boundBuffer = this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING.value); const attributeState: any = { name: info.name, size: info.size, type: this.getWebGlConstant(info.type), location, offsetPointer: this.context.getVertexAttribOffset(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_POINTER.value), bufferBinding: this.getSpectorData(boundBuffer), enabled: this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_ENABLED.value), arraySize: this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_SIZE.value), stride: this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_STRIDE.value), arrayType: this.getWebGlConstant(this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_TYPE.value)), normalized: this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_NORMALIZED.value), vertexAttrib: Array.prototype.slice.call(unbufferedValue), }; if (this.extensions[WebGlConstants.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE.extensionName]) { attributeState.divisor = this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE.value); } else if (this.contextVersion > 1) { attributeState.integer = this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_INTEGER.value); attributeState.divisor = this.context.getVertexAttrib(location, WebGlConstants.VERTEX_ATTRIB_ARRAY_DIVISOR.value); } this.appendBufferCustomData(attributeState, boundBuffer); return attributeState; } protected readUniformFromContext(program: WebGLProgram, activeUniformIndex: number): {} { const info = this.context.getActiveUniform(program, activeUniformIndex); const location = this.context.getUniformLocation(program, info.name); if (location) { if (info.size > 1 && info.name && info.name.indexOf("[0]") === info.name.length - 3) { const values: any = []; for (let i = 0; i < info.size; i++) { const locationInArray = this.context.getUniformLocation(program, info.name.replace("[0]", "[" + i + "]")); if (locationInArray) { let value = this.context.getUniform(program, locationInArray); if (value.length) { value = Array.prototype.slice.call(value); } values.push({ value }); } } const uniformState: any = { name: info.name.replace("[0]", ""), size: info.size, type: this.getWebGlConstant(info.type), typeValue: info.type, location: this.getSpectorData(location), values, }; return uniformState; } else { let value = this.context.getUniform(program, location); if (value.length) { value = Array.prototype.slice.call(value); } const uniformState: any = { name: info.name, size: info.size, type: this.getWebGlConstant(info.type), typeValue: info.type, location: this.getSpectorData(location), value, }; return uniformState; } } else { const uniformState: any = { name: info.name, size: info.size, type: this.getWebGlConstant(info.type), typeValue: info.type, }; return uniformState; } } protected readTextureFromContext(textureUnit: number, target: WebGlConstant): {} { const activeTexture = this.context.getParameter(WebGlConstants.ACTIVE_TEXTURE.value); this.context.activeTexture(WebGlConstants.TEXTURE0.value + textureUnit); const textureState: any = { magFilter: this.getWebGlConstant(this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_MAG_FILTER.value)), minFilter: this.getWebGlConstant(this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_MIN_FILTER.value)), wrapS: this.getWebGlConstant(this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_WRAP_S.value)), wrapT: this.getWebGlConstant(this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_WRAP_T.value)), }; if (this.extensions[WebGlConstants.TEXTURE_MAX_ANISOTROPY_EXT.extensionName]) { textureState.anisotropy = this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_MAX_ANISOTROPY_EXT.value); } if (this.contextVersion > 1) { textureState.baseLevel = this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_BASE_LEVEL.value); textureState.immutable = this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_IMMUTABLE_FORMAT.value); textureState.immutableLevels = this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_IMMUTABLE_LEVELS.value); textureState.maxLevel = this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_MAX_LEVEL.value); const sampler = this.context.getParameter(WebGlConstants.SAMPLER_BINDING.value); if (sampler) { textureState.sampler = this.getSpectorData(sampler); const context2 = this.context as WebGL2RenderingContext; textureState.samplerMaxLod = context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_MAX_LOD.value); textureState.samplerMinLod = context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_MIN_LOD.value); textureState.samplerCompareFunc = this.getWebGlConstant(context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_COMPARE_FUNC.value)); textureState.samplerCompareMode = this.getWebGlConstant(context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_COMPARE_MODE.value)); textureState.samplerWrapS = this.getWebGlConstant(context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_WRAP_S.value)); textureState.samplerWrapT = this.getWebGlConstant(context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_WRAP_T.value)); textureState.samplerWrapR = this.getWebGlConstant(context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_WRAP_R.value)); textureState.samplerMagFilter = this.getWebGlConstant(context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_MAG_FILTER.value)); textureState.samplerMinFilter = this.getWebGlConstant(context2.getSamplerParameter(sampler, WebGlConstants.TEXTURE_MIN_FILTER.value)); } else { textureState.maxLod = this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_MAX_LOD.value); textureState.minLod = this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_MIN_LOD.value); textureState.compareFunc = this.getWebGlConstant(this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_COMPARE_FUNC.value)); textureState.compareMode = this.getWebGlConstant(this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_COMPARE_MODE.value)); textureState.wrapR = this.getWebGlConstant(this.context.getTexParameter(target.value, WebGlConstants.TEXTURE_WRAP_R.value)); } } const storage = this.getTextureStorage(target); if (storage) { // Null will prevent the visual target to be captured. const textureStateTarget = this.quickCapture ? null : target; this.drawCallTextureInputState.appendTextureState(textureState, storage, textureStateTarget, this.fullCapture); } this.context.activeTexture(activeTexture); return textureState; } protected getTextureStorage(target: WebGlConstant): any { if (target === WebGlConstants.TEXTURE_2D) { return this.context.getParameter(WebGlConstants.TEXTURE_BINDING_2D.value); } else if (target === WebGlConstants.TEXTURE_CUBE_MAP) { return this.context.getParameter(WebGlConstants.TEXTURE_BINDING_CUBE_MAP.value); } else if (target === WebGlConstants.TEXTURE_3D) { return this.context.getParameter(WebGlConstants.TEXTURE_BINDING_3D.value); } else if (target === WebGlConstants.TEXTURE_2D_ARRAY) { return this.context.getParameter(WebGlConstants.TEXTURE_BINDING_2D_ARRAY.value); } return undefined; } protected readUniformsFromContextIntoState(program: WebGLProgram, uniformIndices: number[], uniformsState: any[], uniformBlockState: any[]) { const context2 = this.context as WebGL2RenderingContext; const typeValues = context2.getActiveUniforms(program, uniformIndices, WebGlConstants.UNIFORM_TYPE.value); const sizes = context2.getActiveUniforms(program, uniformIndices, WebGlConstants.UNIFORM_SIZE.value); const blockIndices = context2.getActiveUniforms(program, uniformIndices, WebGlConstants.UNIFORM_BLOCK_INDEX.value); const offsets = context2.getActiveUniforms(program, uniformIndices, WebGlConstants.UNIFORM_OFFSET.value); const arrayStrides = context2.getActiveUniforms(program, uniformIndices, WebGlConstants.UNIFORM_ARRAY_STRIDE.value); const matrixStrides = context2.getActiveUniforms(program, uniformIndices, WebGlConstants.UNIFORM_MATRIX_STRIDE.value); const rowMajors = context2.getActiveUniforms(program, uniformIndices, WebGlConstants.UNIFORM_IS_ROW_MAJOR.value); for (let i = 0; i < uniformIndices.length; i++) { const uniformState = uniformsState[i]; uniformState.type = this.getWebGlConstant(typeValues[i]); uniformState.size = sizes[i]; uniformState.blockIndice = blockIndices[i]; if (uniformState.blockIndice > -1) { uniformState.blockName = context2.getActiveUniformBlockName(program, uniformState.blockIndice); } uniformState.offset = offsets[i]; uniformState.arrayStride = arrayStrides[i]; uniformState.matrixStride = matrixStrides[i]; uniformState.rowMajor = rowMajors[i]; if (uniformState.blockIndice > -1) { const bindingPoint = uniformBlockState[blockIndices[i]].bindingPoint; uniformState.value = this.drawCallUboInputState.getUboValue(bindingPoint, uniformState.offset, uniformState.size, typeValues[i]); } } } protected readTransformFeedbackFromContext(program: WebGLProgram, index: number): {} { const context2 = this.context as WebGL2RenderingContext; const info = context2.getTransformFeedbackVarying(program, index); const boundBuffer = context2.getIndexedParameter(WebGlConstants.TRANSFORM_FEEDBACK_BUFFER_BINDING.value, index); const transformFeedbackState = { name: info.name, size: info.size, type: this.getWebGlConstant(info.type), buffer: this.getSpectorData(boundBuffer), bufferSize: context2.getIndexedParameter(WebGlConstants.TRANSFORM_FEEDBACK_BUFFER_SIZE.value, index), bufferStart: context2.getIndexedParameter(WebGlConstants.TRANSFORM_FEEDBACK_BUFFER_START.value, index), }; this.appendBufferCustomData(transformFeedbackState, boundBuffer); return transformFeedbackState; } protected readUniformBlockFromContext(program: WebGLProgram, index: number): {} { const context2 = this.context as WebGL2RenderingContext; const bindingPoint = context2.getActiveUniformBlockParameter(program, index, WebGlConstants.UNIFORM_BLOCK_BINDING.value); const boundBuffer = context2.getIndexedParameter(WebGlConstants.UNIFORM_BUFFER_BINDING.value, bindingPoint); const uniformBlockState = { name: context2.getActiveUniformBlockName(program, index), bindingPoint, size: context2.getActiveUniformBlockParameter(program, index, WebGlConstants.UNIFORM_BLOCK_DATA_SIZE.value), activeUniformCount: context2.getActiveUniformBlockParameter(program, index, WebGlConstants.UNIFORM_BLOCK_ACTIVE_UNIFORMS.value), vertex: context2.getActiveUniformBlockParameter(program, index, WebGlConstants.UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER.value), fragment: context2.getActiveUniformBlockParameter(program, index, WebGlConstants.UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER.value), buffer: this.getSpectorData(boundBuffer), // Do not display Ptr data. // bufferSize: context2.getIndexedParameter(WebGlConstants.UNIFORM_BUFFER_SIZE.value, bindingPoint), // bufferStart: context2.getIndexedParameter(WebGlConstants.UNIFORM_BUFFER_START.value, bindingPoint), }; this.appendBufferCustomData(uniformBlockState, boundBuffer); return uniformBlockState; } private appendBufferCustomData(state: any, buffer: WebGLBuffer) { if (buffer) { // Check for custom data. const customData: IBufferRecorderData = (buffer as any).__SPECTOR_Object_CustomData; if (customData) { if (customData.usage) { state.bufferUsage = this.getWebGlConstant(customData.usage); } state.bufferLength = customData.length; if (customData.offset) { state.bufferOffset = customData.offset; } if (customData.sourceLength) { state.bufferSourceLength = customData.sourceLength; } } } } private getWebGlConstant(value: number) { const constant = WebGlConstantsByValue[value]; return constant ? constant.name : value; } }
the_stack
import contentList from '../../resources/content_list'; import ContentType from '../../resources/content_type'; import { isLang, Lang, langToLocale } from '../../resources/languages'; import { UnreachableCode } from '../../resources/not_reached'; import ZoneInfo from '../../resources/zone_info'; import { LocaleText } from '../../types/trigger'; import { Coverage, CoverageEntry, CoverageTotalEntry, CoverageTotals } from './coverage.d'; import { coverage, coverageTotals } from './coverage_report'; import './coverage.css'; const emptyTotal: CoverageTotalEntry = { raidboss: 0, oopsy: 0, total: 0, }; // TODO: these tables are pretty wide, add some sort of alternating highlight? // TODO: make it possible to click on a zone row and highlight/link to it. // TODO: borrowed from ui/config/config.js // Probably this should live somewhere else. const exVersionToName = { '0': { en: 'A Realm Reborn (ARR 2.x)', de: 'A Realm Reborn (ARR 2.x)', fr: 'A Realm Reborn (ARR 2.x)', ja: '新生エオルゼア (2.x)', cn: '重生之境 (2.x)', ko: '신생 에오르제아 (2.x)', }, '1': { en: 'Heavensward (HW 3.x)', de: 'Heavensward (HW 3.x)', fr: 'Heavensward (HW 3.x)', ja: '蒼天のイシュガルド (3.x)', cn: '苍穹之禁城 (3.x)', ko: '창천의 이슈가르드 (3.x)', }, '2': { en: 'Stormblood (SB 4.x)', de: 'Stormblood (SB 4.x)', fr: 'Stormblood (SB 4.x)', ja: '紅蓮のリベレーター (4.x)', cn: '红莲之狂潮 (4.x)', ko: '홍련의 해방자 (4.x)', }, '3': { en: 'Shadowbringers (ShB 5.x)', de: 'Shadowbringers (ShB 5.x)', fr: 'Shadowbringers (ShB 5.x)', ja: '漆黒のヴィランズ (5.x)', cn: '暗影之逆焰 (5.x)', ko: '칠흑의 반역자 (5.x)', }, '4': { en: 'Endwalker (EW 6.x)', de: 'Endwalker (EW 6.x)', fr: 'Endwalker (EW 6.x)', ja: '暁月のフィナーレ (6.x)', ko: '효월의 종언 (6.x)', }, } as const; const exVersionToShortName: { [exVersion: string]: LocaleText } = { '0': { en: 'ARR', de: 'ARR', fr: 'ARR', ja: '新生', cn: '2.X', ko: '신생', }, '1': { en: 'HW', de: 'HW', fr: 'HW', ja: '蒼天', cn: '3.X', ko: '창천', }, '2': { en: 'SB', de: 'SB', fr: 'SB', ja: '紅蓮', cn: '4.X', ko: '홍련', }, '3': { en: 'ShB', de: 'ShB', fr: 'ShB', ja: '漆黒', cn: '5.X', ko: '칠흑', }, '4': { en: 'EW', de: 'EW', fr: 'EW', ja: '暁月', cn: '6.X', ko: '효월', }, }; const contentTypeToLabel: { [contentType: number]: LocaleText } = { [ContentType.Raids]: { en: 'Raid', de: 'Raid', fr: 'Raid', ja: 'レイド', cn: '大型任务', ko: '레이드', }, [ContentType.Trials]: { en: 'Trial', de: 'Prfng', fr: 'Défi', ja: '討伐戦', cn: '讨伐战', ko: '토벌전', }, [ContentType.UltimateRaids]: { en: 'Ult', de: 'Ult', fr: 'Fatal', ja: '絶', cn: '绝境战', ko: '절', }, [ContentType.Dungeons]: { en: 'Dgn', de: 'Dgn', fr: 'Djn', ja: 'ID', cn: '迷宫挑战', ko: '던전', }, [ContentType.Guildhests]: { en: 'Hest', de: 'Gldgh', fr: 'Op. Guilde', ja: 'ギルド', cn: '行会令', ko: '길드작전', }, } as const; const contentTypeLabelOrder = [ ContentType.UltimateRaids, ContentType.Raids, ContentType.Trials, ContentType.Dungeons, ContentType.Guildhests, ] as const; // This is also the order of the table columns. const zoneGridHeaders = { expansion: { en: 'Ex', de: 'Ex', fr: 'Ext', ja: 'パッチ', cn: '资料片', ko: '확장팩', }, type: { en: 'Type', de: 'Art', fr: 'Type', ja: 'タイプ', cn: '类型', ko: '분류', }, name: { en: 'Name', de: 'Name', fr: 'Nom', ja: '名前', cn: '名称', ko: '이름', }, triggers: { en: 'Triggers', de: 'Triggers', fr: 'Triggers', ja: 'トリガー', cn: '触发器', ko: '트리거', }, timeline: { en: 'Timeline', de: 'Timeline', fr: 'Timeline', ja: 'タイムライン', cn: '时间轴', ko: '타임라인', }, oopsy: { en: 'Oopsy', de: 'Oopsy', fr: 'Oopsy', ja: 'Oopsy', cn: '犯错监控', ko: 'Oopsy', }, // TODO: missing translation items } as const; const miscStrings = { // Title at the top of the page. title: { en: 'Cactbot Content Coverage', de: 'Cactbot Inhaltsabdeckung', fr: 'Contenus présents dans Cactbot', ja: 'Cactbot コンテンツ完成度', cn: 'Cactbot 内容覆盖率', ko: 'Cactbot 컨텐츠 커버리지', }, // Overall label for the expansion table. overall: { en: 'Overall', de: 'Insgesamt', fr: 'Total', ja: '概要', cn: '总览', ko: '전체', }, // Oopsy label for the expansion table. oopsy: { ...zoneGridHeaders.oopsy, }, // Description about release and latest version differences. description: { en: 'This list may contain content that is in development and is not yet included in the latest cactbot release. Anything that is listed as covered here will be included in the next release of cactbot. If you are using the <a href="https://github.com/quisquous/cactbot/blob/main/CONTRIBUTING.md#validating-changes-via-remote-urls">quisquous.github.io version</a> as the url for your overlays, this list will be up to date.', de: 'Diese Liste kann Inhalte enthalten, welche momentan in Entwicklung sind uns sich noch nicht im aktuellstem Cactbot Release befinden. Alles was hier aufgelistet ist, wird sich im nächsten Release von Cactbot befinden. Wenn du <a href="https://github.com/quisquous/cactbot/blob/main/CONTRIBUTING.md#validating-changes-via-remote-urls">quisquous.github.io version</a> als URL für dein Overlay benutzt, sind die Inhalte in dieser Liste bereits für dich verfügbar.', ja: 'このリストは開発中機能や最新リリースバージョンに公開されていないコンテンツを含まれています。リストに含まれているコンテンツは次バージョンに公開される予定があります。また、OverlayPluginのURL欄に<a href="https://github.com/quisquous/cactbot/blob/main/CONTRIBUTING.md#validating-changes-via-remote-urls">「quisquous.github.io」のページのURL</a>を入力している場合はこのリストに含まれているコンテンツと一致し、すべてのコンテンツを使えるようになります。', cn: '该列表中可能存在正在开发中的功能及未发布在cactbot最新发行版中的更新内容。该列表中显示的更新将会在下一个版本的cactbot发行版中发布。若您在OverlayPlugin中使用的是<a href="https://github.com/quisquous/cactbot/blob/main/CONTRIBUTING.md#validating-changes-via-remote-urls">「quisquous.github.io」开头的URL</a>,则更新进度与该列表一致,即该列表中的所有内容均可用。', ko: '이 목록에는 아직 개발 중인 컨텐츠가 포함되어 있을 수 있고 최신 cactbot 릴리즈에 포함되어 있지 않을 수 있습니다. 여기에 나열된 컨텐츠 목록은 최소한 다음 릴리즈에는 포함되게 됩니다. 만약 <a href="https://github.com/quisquous/cactbot/blob/main/CONTRIBUTING.md#validating-changes-via-remote-urls">quisquous.github.io 버전</a>을 오버레이 url로 연결해서 사용하고 계시다면, 이 목록이 오버레이의 컨텐츠 커버리지와 일치합니다.', }, // Warning when generator hasn't been run. runGenerator: { en: 'Error: Run npm run coverage-report to generate data.', de: 'Error: Führe npm run coverage-report aus um die Daten zu generieren.', fr: 'Erreur : Lancez npm run coverage-report pour générer des données.', ja: 'エラー:npm run coverage-report を実行し、データを生成しよう。', cn: '错误:请先运行 npm run coverage-report 以生成数据。', ko: '에러: 데이터를 생성하려면 node npm run coverage-report를 실행하세요.', }, } as const; const translate = (obj: LocaleText, lang: Lang) => obj[lang] ?? obj['en']; const addDiv = (container: HTMLElement, cls: string, text?: string) => { const div = document.createElement('div'); div.classList.add(cls); if (text) div.innerHTML = text; container.appendChild(div); }; const buildExpansionGrid = (container: HTMLElement, lang: Lang, totals: CoverageTotals) => { // Labels. addDiv(container, 'label'); addDiv(container, 'label', translate(miscStrings.overall, lang)); for (const contentType of contentTypeLabelOrder) { const label = contentTypeToLabel[contentType]; const text = label !== undefined ? translate(label, lang) : undefined; addDiv(container, 'label', text); } addDiv(container, 'label', translate(miscStrings.oopsy, lang)); // By expansion. for (const [exVersion, name] of Object.entries(exVersionToName)) { const expansionName = translate(name, lang); addDiv(container, 'header', expansionName); const versionInfo = totals.byExpansion[exVersion]; const overall = versionInfo?.overall ?? emptyTotal; addDiv(container, 'data', `${overall.raidboss} / ${overall.total}`); for (const contentType of contentTypeLabelOrder) { const accum: CoverageTotalEntry = versionInfo?.byContentType[contentType] ?? emptyTotal; const text = accum.total ? `${accum.raidboss} / ${accum.total}` : undefined; addDiv(container, 'data', text); } addDiv(container, 'data', `${overall.oopsy} / ${overall.total}`); } // Totals. addDiv(container, 'label'); addDiv(container, 'data', `${totals.overall.raidboss} / ${totals.overall.total}`); for (const contentType of contentTypeLabelOrder) { const accum = totals.byContentType[contentType] ?? emptyTotal; const text = accum.total ? `${accum.raidboss} / ${accum.total}` : undefined; addDiv(container, 'data', text); } addDiv(container, 'data', `${totals.overall.oopsy} / ${totals.overall.total}`); }; const buildZoneGrid = (container: HTMLElement, lang: Lang, coverage: Coverage) => { for (const header of Object.values(zoneGridHeaders)) addDiv(container, 'label', translate(header, lang)); // By expansion, then content list. for (const exVersion in exVersionToName) { for (const zoneId of contentList) { if (zoneId === null) continue; const zone = ZoneInfo[zoneId]; if (!zone) continue; if (zone.exVersion.toString() !== exVersion) continue; const zoneCoverage: CoverageEntry = coverage[zoneId] ?? { oopsy: { num: 0 }, triggers: { num: 0 }, timeline: {}, }; // Build in order of zone grid headers, so the headers can be rearranged // and the data will follow. const headerFuncs: Record<keyof typeof zoneGridHeaders, () => void> = { expansion: () => { const shortName = exVersionToShortName[zone.exVersion.toString()]; const text = shortName !== undefined ? translate(shortName, lang) : undefined; addDiv(container, 'text', text); }, type: () => { const label = zone.contentType !== undefined ? contentTypeToLabel[zone.contentType] : undefined; const text = label !== undefined ? translate(label, lang) : undefined; addDiv(container, 'text', text); }, name: () => { let name = translate(zone.name, lang); name = name.replace('<Emphasis>', '<i>'); name = name.replace('</Emphasis>', '</i>'); addDiv(container, 'text', name); }, triggers: () => { const emoji = zoneCoverage.triggers && zoneCoverage.triggers.num > 0 ? '✔️' : undefined; addDiv(container, 'emoji', emoji); }, timeline: () => { let emoji = undefined; if (zoneCoverage.timeline) { if (zoneCoverage.timeline.hasNoTimeline) emoji = '➖'; else if (zoneCoverage.timeline.timelineNeedsFixing) emoji = '⚠️'; else if (zoneCoverage.timeline.hasFile) emoji = '✔️'; } addDiv(container, 'emoji', emoji); }, oopsy: () => { const emoji = zoneCoverage.oopsy && zoneCoverage.oopsy.num > 0 ? '✔️' : undefined; addDiv(container, 'emoji', emoji); }, }; for (const func of Object.values(headerFuncs)) func(); } } }; const buildLanguageSelect = (container: HTMLElement, lang: Lang) => { const langMap = { en: 'English', de: 'Deutsch', fr: 'Français', ja: '日本語', cn: '中文', ko: '한국어', }; for (const [key, langStr] of Object.entries(langMap)) { let html = ''; if (lang === key) html = `[${langStr}]`; else html = `[<a href="?lang=${key}">${langStr}</a>]`; const div = document.createElement('div'); div.innerHTML = html; container.appendChild(div); } }; document.addEventListener('DOMContentLoaded', () => { // Allow for `coverage.html?lang=de` style constructions. const params = new URLSearchParams(window.location.search); const langStr = params.get('lang') ?? 'en'; // TODO: left for now as backwards compatibility with user css. Remove this later?? document.body.classList.add(`lang-${langStr}`); const lang = langStr !== null && isLang(langStr) ? langStr : 'en'; document.documentElement.lang = langToLocale(lang); const title = document.getElementById('title'); if (!title) throw new UnreachableCode(); title.innerText = translate(miscStrings.title, lang); const languageSelect = document.getElementById('language-select'); if (!languageSelect) throw new UnreachableCode(); buildLanguageSelect(languageSelect, lang); const description = document.getElementById('description-text'); if (!description) throw new UnreachableCode(); description.innerHTML = translate(miscStrings.description, lang); if (coverageTotals.overall.total === 0) { const warning = document.getElementById('warning'); if (!warning) throw new UnreachableCode(); warning.innerText = translate(miscStrings.runGenerator, lang); return; } const expansionGrid = document.getElementById('expansion-grid'); if (!expansionGrid) throw new UnreachableCode(); buildExpansionGrid(expansionGrid, lang, coverageTotals); const zoneGrid = document.getElementById('zone-grid'); if (!zoneGrid) throw new UnreachableCode(); buildZoneGrid(zoneGrid, lang, coverage); });
the_stack
import passport from 'passport'; import {Strategy as LocalStrategy} from 'passport-local'; import session from 'express-session'; import sessionKnex from 'connect-session-knex'; import {Express, RequestHandler} from 'express'; import {Strategy as BearerStrategy} from 'passport-http-bearer'; import * as bcrypt from 'bcrypt'; import {Issuer as OIDCIssuer, Strategy as OIDCStrategy, TokenSet } from 'openid-client'; import { AuthRoles } from './authEntities/interfaces'; import db from './db'; import {SettingsService} from "./settings/services/SettingsService"; import {SettingKeys} from "./settings/interfaces"; import urljoin from 'url-join'; export interface User { authEntityId: number; identifier: string; role: string; } export default (app: Express, settingsService: SettingsService, config: any): RequestHandler[] => { const SessionKnex = sessionKnex(session); const sessionConfig = Object.assign({ resave: false, saveUninitialized: false, cookie: {httpOnly: true, secure: false}, store: new SessionKnex({ knex: db, createTable: false, tablename: 'sessions' }), }, config.session); if (app.get('env') === 'production') { app.set('trust proxy', 1); // trust first proxy //sessionConfig.cookie.secure = true; // serve secure cookies } app.use(session(sessionConfig)); passport.use(new LocalStrategy(async function(username, password, done) { try { const user = await getEntityWithCreds('local', username, password); if (!user) { return done(null, false); } return done(null, user); } catch (e) { return done(e); } })); passport.use(new BearerStrategy(async function(token, done) { try { const tokenParts = token.split(':'); if (tokenParts.length !== 2) { return done(null, false); } const id = Buffer.from(tokenParts[0], 'base64').toString('utf8'); const secret = Buffer.from(tokenParts[1], 'base64').toString('utf8'); const user = await getEntityWithCreds('bearer', id, secret); if (!user) { return done(null, false); } return done(null, user); } catch (e) { return done(e); } })); // This can be used to keep a smaller payload passport.serializeUser(function(user: Express.User, done) { done(null, user); }); passport.deserializeUser(function(user: Express.User, done) { done(null, user); }); // ... app.use(passport.initialize()); app.use(passport.session()); // Accept the OpenID identifier and redirect the user to their OpenID // provider for authentication. When complete, the provider will redirect // the user back to the application at: // /auth/openid/return app.get('/auth/openid', async (req, res, next) => { if (await settingsService.get(SettingKeys.AuthOpenIdEnabled) === false) { return res.sendStatus(404); } if (req.user) { return res.redirect('/'); } const callerId = 'auth'; const keysToWatch = [ SettingKeys.AuthOpenIdClientId, SettingKeys.AuthOpenIdClientSecret, SettingKeys.BaseUrl, SettingKeys.AuthOpenIdResponseMode, SettingKeys.AuthOpenIdIdentifierClaimName, SettingKeys.AuthOpenIdUniqueIdentifierClaimName, SettingKeys.AuthOpenIdRequestedScopes, ]; if (await settingsService.hasChanged(callerId, keysToWatch)) { console.log('Change of the OpenID authentication config detected. Reinitializing auth backend...'); passport.unuse('openid'); const issuer = await OIDCIssuer.discover(await settingsService.get(SettingKeys.AuthOpenIdDiscoveryUrl, callerId)); // => Promise //console.log('Discovered issuer %s %O', issuer.issuer, issuer.metadata); const client = new issuer.Client({ client_id: await settingsService.get(SettingKeys.AuthOpenIdClientId, callerId), client_secret: await settingsService.get(SettingKeys.AuthOpenIdClientSecret, callerId), redirect_uris: [urljoin(await settingsService.get(SettingKeys.BaseUrl, callerId), '/auth/openid/return')], response_types: ['code'], }); passport.use('openid', new OIDCStrategy( { client, params: { scope: await settingsService.get(SettingKeys.AuthOpenIdRequestedScopes, callerId), response_mode: await settingsService.get(SettingKeys.AuthOpenIdResponseMode, callerId), } }, async function(tokenSet: TokenSet/*, userinfo: UserinfoResponse*/, done: any) { try { if (tokenSet.expired()) { return done(null, false, { message: 'Expired OpenID token' }); } const claims = tokenSet.claims(); const idClaimName = await settingsService.get(SettingKeys.AuthOpenIdIdentifierClaimName, callerId); const uidClaimName = await settingsService.get(SettingKeys.AuthOpenIdUniqueIdentifierClaimName, callerId); let identifiers: string[] = claims[idClaimName] as any; if (!identifiers) { return done(null, false, { message: 'Can\'t find user identifier using IdentityClaimName' }); } else if (!Array.isArray(identifiers)) { identifiers = [identifiers]; } let user: any; for (let id of identifiers) { user = await getEntityWithCreds('openid', id, null); if (user) { break; } } if (!user) { return done(null, false, { message: `Can\'t find presented identifiers "${identifiers.toString()}" in auth entities list` }); } if (uidClaimName && claims[uidClaimName]) { user.identifier = claims[uidClaimName]; } return done(null, user); } catch (e) { return done(e); } }) ); } next(); }, passport.authenticate('openid')); const openidReturnHandlers: RequestHandler[] = [ async (req, res, next) => { if (await settingsService.get(SettingKeys.AuthOpenIdEnabled) === true) { return next(); } res.sendStatus(404); }, (req, res, next) => { passport.authenticate('openid', function(err, user, info) { if (err) { return next(err); } if (!user) { res.status(401); res.header('Content-type', 'text/html'); return res.end(`<pre>${info.message}</pre><br><a href="/">Go to main page</a>`); } req.logIn(user, function(err) { if (err) { return next(err); } res.cookie('ilc:userInfo', JSON.stringify(user)); return res.redirect('/'); }); })(req, res, next); } ]; // The OpenID provider has redirected the user back to the application. // Finish the authentication process by verifying the assertion. If valid, // the user will be logged in. Otherwise, authentication has failed. app.get('/auth/openid/return', openidReturnHandlers); //Regular flow app.post('/auth/openid/return', openidReturnHandlers); //response_mode: 'form_post' flow // Accept passed username/password pair & perform an attempt to authenticate against local DB app.post('/auth/local', passport.authenticate(['local']), (req, res) => { res.cookie('ilc:userInfo', JSON.stringify(req.user)); res.send('ok'); }); app.get('/auth/logout', (req, res, next) => { req.logout(); res.clearCookie('ilc:userInfo'); if (req.session) { req.session.regenerate((err) => { if (err) { next(err); } res.redirect('/'); }); } else { res.redirect('/'); } }); app.get('/auth/available-methods', async (req, res) => { const availableMethods = ['local']; if (await settingsService.get(SettingKeys.AuthOpenIdEnabled) === true) { availableMethods.push('openid'); } res.json(availableMethods); }); const rolesMiddleware = (req: any, res: any, next: any) => { if (req.user.role === AuthRoles.readonly && req.method !== 'GET') { return res.status(403).send({ message: `Access denied. "${req.user.identifier}" has "readonly" access.` }); } return next(); }; return [(req: any, res: any, next: any) => { if (!req.user) { return passport.authenticate('bearer', { session: false })(req, res, next); } return next(); }, rolesMiddleware]; } async function getEntityWithCreds(provider: string, identifier: string, secret: string|null):Promise<User|null> { const user = await db.select().from('auth_entities') .first('identifier', 'id', 'role', 'secret') .where({ provider, identifier }); if (!user) { return null; } if (secret !== null || user.secret !== null) { //Support of the password less auth methods, like OpenID Connect if (!await bcrypt.compare(secret, user.secret)) { return null; } } return { authEntityId: user.id, identifier: user.identifier, role: user.role, }; }
the_stack
import { assert } from "node-opcua-assert"; import { BrowseDirection, NodeClass } from "node-opcua-data-model"; import { checkDebugFlag, make_debugLog } from "node-opcua-debug"; import { NodeId } from "node-opcua-nodeid"; import { Variant } from "node-opcua-variant"; import { DataType } from "node-opcua-variant"; import { VariantArrayType } from "node-opcua-variant"; import { ExtensionObject } from "node-opcua-extension-object"; import { UADataType, UADynamicVariableArray, UAObject, UAReferenceType, UAVariable } from "node-opcua-address-space-base"; import { UAVariableImpl } from "./ua_variable_impl"; const doDebug = checkDebugFlag(__filename); const debugLog = make_debugLog(__filename); /* * define a complex Variable containing a array of extension objects * each element of the array is also accessible as a component variable. * */ function getExtObjArrayNodeValue(this: any) { return new Variant({ arrayType: VariantArrayType.Array, dataType: DataType.ExtensionObject, value: this.$$extensionObjectArray }); } function removeElementByIndex<T extends ExtensionObject>(uaArrayVariableNode: UADynamicVariableArray<T>, elementIndex: number) { const _array = uaArrayVariableNode.$$extensionObjectArray; assert(typeof elementIndex === "number"); const addressSpace = uaArrayVariableNode.addressSpace; const extObj = _array[elementIndex]; const browseName = uaArrayVariableNode.$$getElementBrowseName(extObj); // remove element from global array (inefficient) uaArrayVariableNode.$$extensionObjectArray.splice(elementIndex, 1); // remove matching component const node = uaArrayVariableNode.getComponentByName(browseName); if (!node) { throw new Error(" cannot find component "); } const hasComponent = uaArrayVariableNode.addressSpace.findReferenceType("HasComponent")! as UAReferenceType; // remove the hasComponent reference toward node uaArrayVariableNode.removeReference({ isForward: true, nodeId: node.nodeId, referenceType: hasComponent.nodeId }); // now check if node has still some parent const parents = node.findReferencesEx("HasChild", BrowseDirection.Inverse); if (parents.length === 0) { addressSpace.deleteNode(node.nodeId); } } /** * * create a node Variable that contains a array of ExtensionObject of a given type * @method createExtObjArrayNode * @param parentFolder * @param options * @param options.browseName * @param options.complexVariableType * @param options.variableType the type of Extension objects stored in the array. * @param options.indexPropertyName * @return {Object|UAVariable} */ export function createExtObjArrayNode<T extends ExtensionObject>(parentFolder: UAObject, options: any): UADynamicVariableArray<T> { assert(typeof options.variableType === "string"); assert(typeof options.indexPropertyName === "string"); const addressSpace = parentFolder.addressSpace; const namespace = parentFolder.namespace; const complexVariableType = addressSpace.findVariableType(options.complexVariableType); if (!complexVariableType) { throw new Error("cannot find complex variable type"); } assert(!complexVariableType.nodeId.isEmpty()); const variableType = addressSpace.findVariableType(options.variableType); if (!variableType) { throw new Error("cannot find variable Type"); } assert(!variableType.nodeId.isEmpty()); const structure = addressSpace.findDataType("Structure"); assert(structure, "Structure Type not found: please check your nodeset file"); const dataType = addressSpace.findDataType(variableType.dataType); if (!dataType) { throw new Error("cannot find Data Type"); } assert(dataType.isSupertypeOf(structure as any), "expecting a structure (= ExtensionObject) here "); const inner_options = { componentOf: parentFolder, browseName: options.browseName, dataType: dataType.nodeId, typeDefinition: complexVariableType.nodeId, value: { dataType: DataType.ExtensionObject, value: [], arrayType: VariantArrayType.Array }, valueRank: 1 }; const uaArrayVariableNode = namespace.addVariable(inner_options) as UADynamicVariableArray<T>; bindExtObjArrayNode(uaArrayVariableNode, options.variableType, options.indexPropertyName); return uaArrayVariableNode; } /** * @method bindExtObjArrayNode * @param uaArrayVariableNode * @param variableTypeNodeId * @param indexPropertyName * @return */ export function bindExtObjArrayNode<T extends ExtensionObject>( uaArrayVariableNode: UADynamicVariableArray<T>, variableTypeNodeId: string | NodeId, indexPropertyName: string ): UAVariable { const addressSpace = uaArrayVariableNode.addressSpace; const variableType = addressSpace.findVariableType(variableTypeNodeId); if (!variableType) { throw new Error("Cannot find VariableType " + variableTypeNodeId.toString()); } assert(!variableType.nodeId.isEmpty()); let structure = addressSpace.findDataType("Structure"); assert(structure, "Structure Type not found: please check your nodeset file"); let dataType = addressSpace.findDataType(variableType.dataType); if (!dataType) { throw new Error("Cannot find DataType " + variableType.dataType.toString()); } assert(dataType.isSupertypeOf(structure as any), "expecting a structure (= ExtensionObject) here "); assert(!uaArrayVariableNode.$$variableType, "uaArrayVariableNode has already been bound !"); uaArrayVariableNode.$$variableType = variableType; structure = addressSpace.findDataType("Structure"); assert(structure, "Structure Type not found: please check your nodeset file"); // verify that an object with same doesn't already exist dataType = addressSpace.findDataType(variableType.dataType)! as UADataType; assert(dataType!.isSupertypeOf(structure as any), "expecting a structure (= ExtensionObject) here "); uaArrayVariableNode.$$dataType = dataType; uaArrayVariableNode.$$extensionObjectArray = []; uaArrayVariableNode.$$indexPropertyName = indexPropertyName; uaArrayVariableNode.$$getElementBrowseName = function (this: UADynamicVariableArray<T>, extObj: ExtensionObject) { const indexPropertyName1 = this.$$indexPropertyName; if (!Object.prototype.hasOwnProperty.call(extObj, indexPropertyName1)) { console.log(" extension object do not have ", indexPropertyName1, extObj); } // assert(extObj.constructor === addressSpace.constructExtensionObject(dataType)); assert(Object.prototype.hasOwnProperty.call(extObj, indexPropertyName1)); const browseName = (extObj as any)[indexPropertyName1].toString(); return browseName; }; const options = { get: getExtObjArrayNodeValue, set: undefined // readonly }; // bind the readonly uaArrayVariableNode.bindVariable(options, true); return uaArrayVariableNode; } /** * @method addElement * add a new element in a ExtensionObject Array variable * @param options {Object} data used to construct the underlying ExtensionObject * @param uaArrayVariableNode {UAVariable} * @return {UAVariable} * * @method addElement * add a new element in a ExtensionObject Array variable * @param nodeVariable a variable already exposing an extension objects * @param uaArrayVariableNode {UAVariable} * @return {UAVariable} * * @method addElement * add a new element in a ExtensionObject Array variable * @param constructor constructor of the extension object to create * @param uaArrayVariableNode {UAVariable} * @return {UAVariable} */ export function addElement<T extends ExtensionObject>( options: any /* ExtensionObjectConstructor | ExtensionObject | UAVariable*/, uaArrayVariableNode: UADynamicVariableArray<T> ): UAVariable { assert(uaArrayVariableNode, " must provide an UAVariable containing the array"); // verify that arr has been created correctly assert( !!uaArrayVariableNode.$$variableType && !!uaArrayVariableNode.$$dataType, "did you create the array Node with createExtObjArrayNode ?" ); assert(uaArrayVariableNode.$$dataType.nodeClass === NodeClass.DataType); const addressSpace = uaArrayVariableNode.addressSpace; const Constructor = addressSpace.getExtensionObjectConstructor(uaArrayVariableNode.$$dataType); assert(Constructor instanceof Function); let extensionObject: T; let elVar = null; let browseName; if (options instanceof UAVariableImpl) { elVar = options; extensionObject = elVar.$extensionObject; // get shared extension object assert( extensionObject instanceof Constructor, "the provided variable must expose a Extension Object of the expected type " ); // add a reference uaArrayVariableNode.addReference({ isForward: true, nodeId: elVar.nodeId, referenceType: "HasComponent" }); // xx elVar.bindExtensionObject(); } else { if (options instanceof Constructor) { // extension object has already been created extensionObject = options as T; } else { extensionObject = addressSpace.constructExtensionObject(uaArrayVariableNode.$$dataType, options) as T; } browseName = uaArrayVariableNode.$$getElementBrowseName(extensionObject); elVar = uaArrayVariableNode.$$variableType.instantiate({ browseName, componentOf: uaArrayVariableNode.nodeId, value: { dataType: DataType.ExtensionObject, value: extensionObject } }) as UAVariableImpl; elVar.bindExtensionObject(); elVar.$extensionObject = extensionObject; } // also add the value inside uaArrayVariableNode.$$extensionObjectArray.push(extensionObject); return elVar; } /** * * @method removeElement * @param uaArrayVariableNode {UAVariable} * @param element {number} index of element to remove in array * * * @method removeElement * @param uaArrayVariableNode {UAVariable} * @param element {UAVariable} node of element to remove in array * * @method removeElement * @param uaArrayVariableNode {UAVariable} * @param element {ExtensionObject} extension object of the node of element to remove in array * */ export function removeElement<T extends ExtensionObject>( uaArrayVariableNode: UADynamicVariableArray<T>, element: any /* number | UAVariable | (a any) => boolean | ExtensionObject */ ): void { assert(element, "element must exist"); const _array = uaArrayVariableNode.$$extensionObjectArray; if (_array.length === 0) { throw new Error(" cannot remove an element from an empty array "); } let elementIndex = -1; if (typeof element === "number") { // find element by index elementIndex = element; assert(elementIndex >= 0 && elementIndex < _array.length); } else if (element && element.nodeClass) { // find element by name const browseNameToFind = element.browseName.name!.toString(); elementIndex = _array.findIndex((obj: any, i: number) => { const browseName = uaArrayVariableNode.$$getElementBrowseName(obj).toString(); return browseName === browseNameToFind; }); } else if (typeof element === "function") { // find element by functor elementIndex = _array.findIndex(element); } else { // find element by inner extension object assert(_array[0].constructor.name === (element as any).constructor.name, "element must match"); elementIndex = _array.findIndex((x: any) => x === element); } if (elementIndex < 0) { throw new Error(" cannot find element matching " + element.toString()); } return removeElementByIndex(uaArrayVariableNode, elementIndex); }
the_stack
import type { SendOptions } from '../client'; import Device, { isBulbSysinfo } from '../device'; import type { CommonSysinfo, DeviceConstructorOptions } from '../device'; import Cloud from '../shared/cloud'; import Emeter, { RealtimeNormalized } from '../shared/emeter'; import Lighting, { LightState } from './lighting'; import Schedule from './schedule'; import Time from '../shared/time'; type BulbSysinfoLightState = { on_off: 0 | 1; }; export type BulbSysinfo = CommonSysinfo & { mic_type: string; // 'IOT.SMARTBULB'; mic_mac: string; description: string; light_state: BulbSysinfoLightState; is_dimmable: 0 | 1; is_color: 0 | 1; is_variable_color_temp: 0 | 1; }; export interface BulbConstructorOptions extends DeviceConstructorOptions { sysInfo: BulbSysinfo; } export interface BulbEventEmitter { on( event: 'emeter-realtime-update', listener: (value: RealtimeNormalized) => void ): this; /** * @deprecated This will be removed in a future release. */ on(event: 'polling-error', listener: (error: Error) => void): this; /** * Bulb was turned on (`lightstate.on_off`). * @event Bulb#lightstate-on * @property {object} value lightstate */ on(event: 'lightstate-on', listener: (value: LightState) => void): this; /** * Bulb was turned off (`lightstate.on_off`). * @event Bulb#lightstate-off * @property {object} value lightstate */ on(event: 'lightstate-off', listener: (value: LightState) => void): this; /** * Bulb's lightstate was changed. * @event Bulb#lightstate-change * @property {object} value lightstate */ on(event: 'lightstate-change', listener: (value: LightState) => void): this; /** * Bulb's lightstate state was updated from device. Fired regardless if status was changed. * @event Bulb#lightstate-update * @property {object} value lightstate */ on(event: 'lightstate-update', listener: (value: LightState) => void): this; emit(event: 'polling-error', error: Error): boolean; emit(event: 'emeter-realtime-update', value: RealtimeNormalized): boolean; emit(event: 'lightstate-on', value: LightState): boolean; emit(event: 'lightstate-off', value: LightState): boolean; emit(event: 'lightstate-change', value: LightState): boolean; emit(event: 'lightstate-update', value: LightState): boolean; } /** * Bulb Device. * * @fires Bulb#emeter-realtime-update * @fires Bulb#lightstate-on * @fires Bulb#lightstate-off * @fires Bulb#lightstate-change * @fires Bulb#lightstate-update */ export default class Bulb extends Device implements BulbEventEmitter { protected _sysInfo: BulbSysinfo; /** * @internal */ lastState = { inUse: false, powerOn: false }; readonly supportsEmeter = true; static readonly apiModules = { system: 'smartlife.iot.common.system', cloud: 'smartlife.iot.common.cloud', schedule: 'smartlife.iot.common.schedule', timesetting: 'smartlife.iot.common.timesetting', emeter: 'smartlife.iot.common.emeter', netif: 'netif', lightingservice: 'smartlife.iot.smartbulb.lightingservice', }; /** * @borrows Cloud#getInfo as Bulb.cloud#getInfo * @borrows Cloud#bind as Bulb.cloud#bind * @borrows Cloud#unbind as Bulb.cloud#unbind * @borrows Cloud#getFirmwareList as Bulb.cloud#getFirmwareList * @borrows Cloud#setServerUrl as Bulb.cloud#setServerUrl */ readonly cloud = new Cloud(this, 'smartlife.iot.common.cloud'); /** * @borrows Emeter#realtime as Bulb.emeter#realtime * @borrows Emeter#getRealtime as Bulb.emeter#getRealtime * @borrows Emeter#getDayStats as Bulb.emeter#getDayStats * @borrows Emeter#getMonthStats as Bulb.emeter#getMonthStats * @borrows Emeter#eraseStats as Bulb.emeter#eraseStats */ readonly emeter = new Emeter(this, 'smartlife.iot.common.emeter'); /** * @borrows Lighting#lightState as Bulb.lighting#lightState * @borrows Lighting#getLightState as Bulb.lighting#getLightState * @borrows Lighting#setLightState as Bulb.lighting#setLightState */ readonly lighting = new Lighting( this, 'smartlife.iot.smartbulb.lightingservice' ); /** * @borrows Schedule#getNextAction as Bulb.schedule#getNextAction * @borrows Schedule#getRules as Bulb.schedule#getRules * @borrows Schedule#getRule as Bulb.schedule#getRule * @borrows BulbSchedule#addRule as Bulb.schedule#addRule * @borrows BulbSchedule#editRule as Bulb.schedule#editRule * @borrows Schedule#deleteAllRules as Bulb.schedule#deleteAllRules * @borrows Schedule#deleteRule as Bulb.schedule#deleteRule * @borrows Schedule#setOverallEnable as Bulb.schedule#setOverallEnable * @borrows Schedule#getDayStats as Bulb.schedule#getDayStats * @borrows Schedule#getMonthStats as Bulb.schedule#getMonthStats * @borrows Schedule#eraseStats as Bulb.schedule#eraseStats */ readonly schedule = new Schedule(this, 'smartlife.iot.common.schedule'); /** * @borrows Time#getTime as Bulb.time#getTime * @borrows Time#getTimezone as Bulb.time#getTimezone */ readonly time = new Time(this, 'smartlife.iot.common.timesetting'); /** * Created by {@link Client} - Do not instantiate directly. * * See [Device constructor]{@link Device} for common options. * @see Device * @param options - */ constructor(options: BulbConstructorOptions) { super({ client: options.client, _sysInfo: options.sysInfo, host: options.host, port: options.port, logger: options.logger, defaultSendOptions: options.defaultSendOptions, }); this.lastState = Object.assign(this.lastState, { powerOn: null, inUse: null, }); this.setSysInfo(options.sysInfo); this._sysInfo = options.sysInfo; } /** * Returns cached results from last retrieval of `system.sysinfo`. * @returns system.sysinfo */ get sysInfo(): BulbSysinfo { return this._sysInfo; } /** * @internal */ setSysInfo(sysInfo: BulbSysinfo): void { super.setSysInfo(sysInfo); // TODO / XXX Verify that sysInfo.light_state can be set here to trigger events this.lighting.lightState = sysInfo.light_state; } protected setAliasProperty(alias: string): void { this.sysInfo.alias = alias; } /** * Cached value of `sysinfo.[description|dev_name]`. */ get description(): string | undefined { return this.sysInfo.description; } // eslint-disable-next-line class-methods-use-this get deviceType(): 'bulb' { return 'bulb'; } /** * Cached value of `sysinfo.is_dimmable === 1` * @returns Cached value of `sysinfo.is_dimmable === 1` */ get supportsBrightness(): boolean { return this.sysInfo.is_dimmable === 1; } /** * Cached value of `sysinfo.is_color === 1` * @returns Cached value of `sysinfo.is_color === 1` */ get supportsColor(): boolean { return this.sysInfo.is_color === 1; } /** * Cached value of `sysinfo.is_variable_color_temp === 1` * @returns Cached value of `sysinfo.is_variable_color_temp === 1` */ get supportsColorTemperature(): boolean { return this.sysInfo.is_variable_color_temp === 1; } /** * Returns array with min and max supported color temperatures * @returns range in kelvin `{min,max}` or `null` if not supported */ get colorTemperatureRange(): { min: number; max: number } | null { if (!this.supportsColorTemperature) return null; switch (true) { case /LB130/i.test(this.sysInfo.model): return { min: 2500, max: 9000 }; default: return { min: 2700, max: 6500 }; } } /** * Returns array with min and max supported color temperatures * @returns range in kelvin `{min,max}` or `null` if not supported * * @deprecated Renamed, use {@link Bulb.colorTemperatureRange} */ get getColorTemperatureRange(): { min: number; max: number } | null { return this.colorTemperatureRange; } /** * Gets bulb's SysInfo. * * Requests `system.sysinfo` from device. * @returns parsed JSON response */ async getSysInfo(sendOptions?: SendOptions): Promise<BulbSysinfo> { const response = await super.getSysInfo(sendOptions); if (!isBulbSysinfo(response)) { throw new Error(`Unexpected Response: ${response}`); } return this.sysInfo; } /** * Requests common Bulb status details in a single request. * - `system.get_sysinfo` * - `cloud.get_sysinfo` * - `emeter.get_realtime` * - `schedule.get_next_action` * * This command is likely to fail on some devices when using UDP transport. * This defaults to TCP transport unless overridden in sendOptions. * * @returns parsed JSON response */ async getInfo(sendOptions?: SendOptions): Promise<Record<string, unknown>> { // force TCP unless overridden here const sendOptionsForGetInfo: SendOptions = sendOptions == null ? {} : sendOptions; if (!('transport' in sendOptionsForGetInfo)) sendOptionsForGetInfo.transport = 'tcp'; // TODO switch to sendCommand, but need to handle error for devices that don't support emeter const response = await this.send( `{"${this.apiModules.emeter}":{"get_realtime":{}},"${this.apiModules.lightingservice}":{"get_light_state":{}},"${this.apiModules.schedule}":{"get_next_action":{}},"system":{"get_sysinfo":{}},"${this.apiModules.cloud}":{"get_info":{}}}`, sendOptionsForGetInfo ); const data = JSON.parse(response); this.setSysInfo(data.system.get_sysinfo); this.cloud.info = data[this.apiModules.cloud].get_info; this.emeter.setRealtime(data[this.apiModules.emeter].get_realtime); this.schedule.nextAction = data[this.apiModules.schedule].get_next_action; this.lighting.lightState = data[this.apiModules.lightingservice].get_light_state; return { sysInfo: this.sysInfo, cloud: { info: this.cloud.info }, emeter: { realtime: this.emeter.realtime }, schedule: { nextAction: this.schedule.nextAction }, lighting: { lightState: this.lighting.lightState }, }; } /** * Gets on/off state of Bulb. * * Requests `lightingservice.get_light_state` and returns true if `on_off === 1`. * @throws {@link ResponseError} */ async getPowerState(sendOptions?: SendOptions): Promise<boolean> { const lightState = await this.lighting.getLightState(sendOptions); return lightState.on_off === 1; } /** * Sets on/off state of Bulb. * * Sends `lightingservice.transition_light_state` command with on_off `value`. * @param value - true: on, false: off * @throws {@link ResponseError} */ async setPowerState( value: boolean, sendOptions?: SendOptions ): Promise<boolean> { return this.lighting.setLightState({ on_off: value ? 1 : 0 }, sendOptions); } /** * Toggles state of Bulb. * * Requests `lightingservice.get_light_state` sets the power state to the opposite of `on_off === 1` and returns the new power state. * @throws {@link ResponseError} */ async togglePowerState(sendOptions?: SendOptions): Promise<boolean> { const powerState = await this.getPowerState(sendOptions); await this.setPowerState(!powerState, sendOptions); return !powerState; } }
the_stack
import * as vscode from 'vscode'; import { TknElementType } from '../model/element-type'; import { TknDocument } from '../model/document'; import { PipelineTask } from '../model/pipeline/pipeline-model'; import { tektonFSUri, tektonVfsProvider } from '../util/tekton-vfs'; import { TektonYamlType } from './tkn-yaml'; import { VirtualDocument, yamlLocator } from './yaml-locator'; import * as jsYaml from 'js-yaml'; import { Task } from '../tekton'; import { telemetryLogError } from '../telemetry'; import { ContextType } from '../context-type'; import * as _ from 'lodash'; interface ProviderMetadata { getProviderMetadata(): vscode.CodeActionProviderMetadata; } const INLINE_TASK = vscode.CodeActionKind.RefactorInline.append('TektonTask'); const EXTRACT_TASK = vscode.CodeActionKind.RefactorExtract.append('TektonTask'); interface InlineTaskAction extends vscode.CodeAction { taskRefStartPosition?: vscode.Position; taskRefEndPosition?: vscode.Position; taskRefName?: string; taskKind?: string; documentUri?: vscode.Uri; } function isTaskInlineAction(action: vscode.CodeAction): action is InlineTaskAction { return action.kind.contains(INLINE_TASK); } interface ExtractTaskAction extends vscode.CodeAction { documentUri?: vscode.Uri; taskSpecText?: string; taskSpecStartPosition?: vscode.Position; taskSpecEndPosition?: vscode.Position; } class PipelineCodeActionProvider implements vscode.CodeActionProvider { provideCodeActions(document: vscode.TextDocument, range: vscode.Range | vscode.Selection): vscode.ProviderResult<vscode.CodeAction[]> { const result = []; const tknDocs = yamlLocator.getTknDocuments(document); for (const tknDoc of tknDocs) { const selectedElement = this.findTask(tknDoc, range.start); if (selectedElement) { const inlineAction = this.getInlineAction(selectedElement, document); if (inlineAction) { result.push(inlineAction); } const extractAction = this.getExtractTaskAction(selectedElement, document); if (extractAction) { result.push(extractAction); } } } return result; } resolveCodeAction?(codeAction: vscode.CodeAction): Thenable<vscode.CodeAction> { if (isTaskInlineAction(codeAction)){ return this.resolveInlineAction(codeAction); } if (codeAction.kind.contains(EXTRACT_TASK)) { return this.resolveExtractTaskAction(codeAction); } } getProviderMetadata(): vscode.CodeActionProviderMetadata { return { providedCodeActionKinds: [INLINE_TASK, EXTRACT_TASK], } } findTask(doc: TknDocument, pos: vscode.Position): PipelineTask | undefined { const selectedElement = doc.findElementAt(pos); if (!selectedElement) { return undefined; } if (selectedElement.type === TknElementType.PIPELINE_TASK) { return selectedElement as PipelineTask; } let parent = selectedElement.parent; while (parent) { if (parent.type === TknElementType.PIPELINE_TASK) { return parent as PipelineTask; } parent = parent.parent; } return undefined; } private getInlineAction(selectedElement: PipelineTask, document: vscode.TextDocument): InlineTaskAction | undefined { const taskRefName = selectedElement.taskRef?.name.value if (!taskRefName){ return; } const action: InlineTaskAction = new vscode.CodeAction(`Inline '${taskRefName}' Task spec`, INLINE_TASK); const startPos = document.positionAt(selectedElement.taskRef?.keyNode?.startPosition); const endPos = document.positionAt(selectedElement.taskRef?.endPosition); action.taskRefStartPosition = startPos; action.taskRefEndPosition = endPos; action.taskRefName = taskRefName; action.taskKind = selectedElement.taskRef?.kind.value; action.documentUri = document.uri; return action; } private async resolveInlineAction(codeAction: InlineTaskAction): Promise<InlineTaskAction> { return vscode.window.withProgress({location: vscode.ProgressLocation.Notification, cancellable: false, title: `Loading '${codeAction.taskRefName}' Task...` }, async (): Promise<vscode.CodeAction> => { const uri = tektonFSUri(codeAction.taskKind === TektonYamlType.ClusterTask ? ContextType.CLUSTERTASK : ContextType.TASK , codeAction.taskRefName, 'yaml'); try { const taskDoc = await tektonVfsProvider.loadTektonDocument(uri, false); codeAction.edit = new vscode.WorkspaceEdit(); codeAction.edit.replace(codeAction.documentUri, new vscode.Range(codeAction.taskRefStartPosition, codeAction.taskRefEndPosition), this.extractTaskDef(taskDoc, codeAction.taskRefStartPosition.character, codeAction.taskRefEndPosition.character)); } catch (err){ vscode.window.showErrorMessage('Cannot get Tekton Task definition: ' + err.toString()); telemetryLogError('resolveCodeAction', `Cannot get '${codeAction.taskRefName}' Task definition`); } return codeAction; }); } private getExtractTaskAction(selectedElement: PipelineTask, document: vscode.TextDocument): ExtractTaskAction | undefined { const taskSpec = selectedElement.taskSpec; if (!taskSpec) { return; } const startPos = document.positionAt(taskSpec.keyNode?.startPosition); let taskSpecStartPos = document.positionAt(taskSpec.startPosition); // start replace from stat of the line taskSpecStartPos = document.lineAt(taskSpecStartPos.line).range.start; let endPos = document.positionAt(taskSpec.endPosition); // if last line is contains only spaces then replace til previous line const lastLine = document.getText(new vscode.Range(endPos.line, 0, endPos.line, endPos.character)); if (lastLine.trim().length === 0) { endPos = document.lineAt(endPos.line - 1).range.end; } const action: ExtractTaskAction = new vscode.CodeAction(`Extract '${selectedElement.name.value}' Task spec`, EXTRACT_TASK); action.documentUri = document.uri; action.taskSpecStartPosition = startPos; action.taskSpecEndPosition = endPos; action.taskSpecText = document.getText(new vscode.Range(taskSpecStartPos, endPos)); return action; } private async resolveExtractTaskAction(action: ExtractTaskAction): Promise<vscode.CodeAction> { const name = await vscode.window.showInputBox({ignoreFocusOut: true, prompt: 'Provide Task Name' }); const type = await vscode.window.showQuickPick(['Task', 'ClusterTask'], {placeHolder: 'Select Task Type:', canPickMany: false, ignoreFocusOut: true}); if (!type || !name) { return; } return vscode.window.withProgress({location: vscode.ProgressLocation.Notification, cancellable: false, title: 'Extracting Task...' }, async (): Promise<vscode.CodeAction> => { try { const virtDoc = this.getDocForExtractedTask(name, type, action.taskSpecText); const saveError = await tektonVfsProvider.saveTektonDocument(virtDoc); if (saveError) { console.error(saveError); throw new Error(saveError); } const newUri = tektonFSUri(type, name, 'yaml'); await vscode.commands.executeCommand('vscode.open', newUri); const indentation = ' '.repeat(action.taskSpecStartPosition.character); action.edit = new vscode.WorkspaceEdit(); action.edit.replace(action.documentUri, new vscode.Range(action.taskSpecStartPosition, action.taskSpecEndPosition), `taskRef: ${indentation}name: ${name} ${indentation}kind: ${type}`); } catch (err) { console.error(err); } return action; }); } private getDocForExtractedTask(name: string, type: string, content: string): VirtualDocument { const lines = content.split('\n'); const firstLine = lines[0].trimLeft(); const indentation = lines[0].length - firstLine.length; lines[0] = firstLine; for (let i = 1; i < lines.length; i++) { lines[i] = lines[i].slice(indentation); } content = lines.join('\n'); const taskPart = jsYaml.load(content); let metadataPart: {} = undefined; if (taskPart.metadata) { metadataPart = taskPart.metadata; delete taskPart['metadata']; } let metadataPartStr: string = undefined; if (metadataPart && !_.isEmpty(metadataPart)) { metadataPartStr = jsYaml.dump(metadataPart, {indent: 2}); metadataPartStr = metadataPartStr.trimRight().split('\n').map(it => ' ' + it).join('\n'); } let specContent = jsYaml.dump(taskPart, {indent: 2, noArrayIndent: false}); specContent = specContent.trimRight().split('\n').map(it => ' ' + it).join('\n'); return { version: 1, uri: vscode.Uri.file(`file:///extracted/task/${name}.yaml`), getText: () => { return `apiVersion: tekton.dev/v1beta1 kind: ${type} metadata: name: ${name}\n${metadataPartStr ? metadataPartStr : ''} spec: ${specContent} `; } } } private extractTaskDef(taskDoc: VirtualDocument, startPos: number, endPos): string { const task: Task = jsYaml.safeLoad(taskDoc.getText()) as Task; if (!task){ throw new Error('Task is empty!'); } if (task.metadata){ if (task.metadata.managedFields){ delete task.metadata.managedFields; } if (task.metadata.namespace){ delete task.metadata.namespace; } if (task.metadata.resourceVersion){ delete task.metadata.resourceVersion; } if (task.metadata.selfLink){ delete task.metadata.selfLink; } if (task.metadata.uid){ delete task.metadata.uid; } if (task.metadata.generation){ delete task.metadata.generation; } if (task.metadata.creationTimestamp){ delete task.metadata.creationTimestamp; } if (task.metadata.name){ delete task.metadata.name; } if (task.metadata.ownerReferences){ delete task.metadata.ownerReferences; } if (task.metadata.annotations && task.metadata.annotations['kubectl.kubernetes.io/last-applied-configuration']){ delete task.metadata.annotations['kubectl.kubernetes.io/last-applied-configuration']; } } const tabSize: number = vscode.workspace.getConfiguration('editor',{languageId: 'yaml'} ).get('tabSize'); let result = 'taskSpec:\n'; const content = jsYaml.dump({metadata:task.metadata, ...task.spec}, {indent: tabSize}); const lines = content.split('\n').map(it => it ? ' '.repeat(startPos + tabSize) + it : '').join('\n'); result += lines + ' '.repeat(endPos); return result; } } export class TknCodeActionProviders { private providers = new Map<TektonYamlType, vscode.CodeActionProvider & ProviderMetadata>(); constructor() { this.providers.set(TektonYamlType.Pipeline, new PipelineCodeActionProvider()); } getProviderMetadata(type: TektonYamlType): vscode.CodeActionProviderMetadata { return this.providers.get(type).getProviderMetadata(); } getProvider(type: TektonYamlType): vscode.CodeActionProvider { return this.providers.get(type); } isSupports(type: TektonYamlType): boolean { return this.providers.has(type); } } export const codeActionProvider = new TknCodeActionProviders();
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { DisasterRecoveryConfigs } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ServiceBusManagementClient } from "../serviceBusManagementClient"; import { ArmDisasterRecovery, DisasterRecoveryConfigsListNextOptionalParams, DisasterRecoveryConfigsListOptionalParams, SBAuthorizationRule, DisasterRecoveryConfigsListAuthorizationRulesNextOptionalParams, DisasterRecoveryConfigsListAuthorizationRulesOptionalParams, CheckNameAvailability, DisasterRecoveryConfigsCheckNameAvailabilityOptionalParams, DisasterRecoveryConfigsCheckNameAvailabilityResponse, DisasterRecoveryConfigsListResponse, DisasterRecoveryConfigsCreateOrUpdateOptionalParams, DisasterRecoveryConfigsCreateOrUpdateResponse, DisasterRecoveryConfigsDeleteOptionalParams, DisasterRecoveryConfigsGetOptionalParams, DisasterRecoveryConfigsGetResponse, DisasterRecoveryConfigsBreakPairingOptionalParams, DisasterRecoveryConfigsFailOverOptionalParams, DisasterRecoveryConfigsListAuthorizationRulesResponse, DisasterRecoveryConfigsGetAuthorizationRuleOptionalParams, DisasterRecoveryConfigsGetAuthorizationRuleResponse, DisasterRecoveryConfigsListKeysOptionalParams, DisasterRecoveryConfigsListKeysResponse, DisasterRecoveryConfigsListNextResponse, DisasterRecoveryConfigsListAuthorizationRulesNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing DisasterRecoveryConfigs operations. */ export class DisasterRecoveryConfigsImpl implements DisasterRecoveryConfigs { private readonly client: ServiceBusManagementClient; /** * Initialize a new instance of the class DisasterRecoveryConfigs class. * @param client Reference to the service client */ constructor(client: ServiceBusManagementClient) { this.client = client; } /** * Gets all Alias(Disaster Recovery configurations) * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param options The options parameters. */ public list( resourceGroupName: string, namespaceName: string, options?: DisasterRecoveryConfigsListOptionalParams ): PagedAsyncIterableIterator<ArmDisasterRecovery> { const iter = this.listPagingAll(resourceGroupName, namespaceName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, namespaceName, options); } }; } private async *listPagingPage( resourceGroupName: string, namespaceName: string, options?: DisasterRecoveryConfigsListOptionalParams ): AsyncIterableIterator<ArmDisasterRecovery[]> { let result = await this._list(resourceGroupName, namespaceName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, namespaceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, namespaceName: string, options?: DisasterRecoveryConfigsListOptionalParams ): AsyncIterableIterator<ArmDisasterRecovery> { for await (const page of this.listPagingPage( resourceGroupName, namespaceName, options )) { yield* page; } } /** * Gets the authorization rules for a namespace. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param options The options parameters. */ public listAuthorizationRules( resourceGroupName: string, namespaceName: string, alias: string, options?: DisasterRecoveryConfigsListAuthorizationRulesOptionalParams ): PagedAsyncIterableIterator<SBAuthorizationRule> { const iter = this.listAuthorizationRulesPagingAll( resourceGroupName, namespaceName, alias, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, alias, options ); } }; } private async *listAuthorizationRulesPagingPage( resourceGroupName: string, namespaceName: string, alias: string, options?: DisasterRecoveryConfigsListAuthorizationRulesOptionalParams ): AsyncIterableIterator<SBAuthorizationRule[]> { let result = await this._listAuthorizationRules( resourceGroupName, namespaceName, alias, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAuthorizationRulesNext( resourceGroupName, namespaceName, alias, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAuthorizationRulesPagingAll( resourceGroupName: string, namespaceName: string, alias: string, options?: DisasterRecoveryConfigsListAuthorizationRulesOptionalParams ): AsyncIterableIterator<SBAuthorizationRule> { for await (const page of this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, alias, options )) { yield* page; } } /** * Check the give namespace name availability. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param parameters Parameters to check availability of the given namespace name * @param options The options parameters. */ checkNameAvailability( resourceGroupName: string, namespaceName: string, parameters: CheckNameAvailability, options?: DisasterRecoveryConfigsCheckNameAvailabilityOptionalParams ): Promise<DisasterRecoveryConfigsCheckNameAvailabilityResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, parameters, options }, checkNameAvailabilityOperationSpec ); } /** * Gets all Alias(Disaster Recovery configurations) * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param options The options parameters. */ private _list( resourceGroupName: string, namespaceName: string, options?: DisasterRecoveryConfigsListOptionalParams ): Promise<DisasterRecoveryConfigsListResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, options }, listOperationSpec ); } /** * Creates or updates a new Alias(Disaster Recovery configuration) * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param parameters Parameters required to create an Alias(Disaster Recovery configuration) * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, namespaceName: string, alias: string, parameters: ArmDisasterRecovery, options?: DisasterRecoveryConfigsCreateOrUpdateOptionalParams ): Promise<DisasterRecoveryConfigsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, parameters, options }, createOrUpdateOperationSpec ); } /** * Deletes an Alias(Disaster Recovery configuration) * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param options The options parameters. */ delete( resourceGroupName: string, namespaceName: string, alias: string, options?: DisasterRecoveryConfigsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, options }, deleteOperationSpec ); } /** * Retrieves Alias(Disaster Recovery configuration) for primary or secondary namespace * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param options The options parameters. */ get( resourceGroupName: string, namespaceName: string, alias: string, options?: DisasterRecoveryConfigsGetOptionalParams ): Promise<DisasterRecoveryConfigsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, options }, getOperationSpec ); } /** * This operation disables the Disaster Recovery and stops replicating changes from primary to * secondary namespaces * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param options The options parameters. */ breakPairing( resourceGroupName: string, namespaceName: string, alias: string, options?: DisasterRecoveryConfigsBreakPairingOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, options }, breakPairingOperationSpec ); } /** * Invokes GEO DR failover and reconfigure the alias to point to the secondary namespace * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param options The options parameters. */ failOver( resourceGroupName: string, namespaceName: string, alias: string, options?: DisasterRecoveryConfigsFailOverOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, options }, failOverOperationSpec ); } /** * Gets the authorization rules for a namespace. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param options The options parameters. */ private _listAuthorizationRules( resourceGroupName: string, namespaceName: string, alias: string, options?: DisasterRecoveryConfigsListAuthorizationRulesOptionalParams ): Promise<DisasterRecoveryConfigsListAuthorizationRulesResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, options }, listAuthorizationRulesOperationSpec ); } /** * Gets an authorization rule for a namespace by rule name. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param authorizationRuleName The authorization rule name. * @param options The options parameters. */ getAuthorizationRule( resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, options?: DisasterRecoveryConfigsGetAuthorizationRuleOptionalParams ): Promise<DisasterRecoveryConfigsGetAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, authorizationRuleName, options }, getAuthorizationRuleOperationSpec ); } /** * Gets the primary and secondary connection strings for the namespace. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param authorizationRuleName The authorization rule name. * @param options The options parameters. */ listKeys( resourceGroupName: string, namespaceName: string, alias: string, authorizationRuleName: string, options?: DisasterRecoveryConfigsListKeysOptionalParams ): Promise<DisasterRecoveryConfigsListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, authorizationRuleName, options }, listKeysOperationSpec ); } /** * ListNext * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, namespaceName: string, nextLink: string, options?: DisasterRecoveryConfigsListNextOptionalParams ): Promise<DisasterRecoveryConfigsListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, nextLink, options }, listNextOperationSpec ); } /** * ListAuthorizationRulesNext * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param alias The Disaster Recovery configuration name * @param nextLink The nextLink from the previous successful call to the ListAuthorizationRules method. * @param options The options parameters. */ private _listAuthorizationRulesNext( resourceGroupName: string, namespaceName: string, alias: string, nextLink: string, options?: DisasterRecoveryConfigsListAuthorizationRulesNextOptionalParams ): Promise<DisasterRecoveryConfigsListAuthorizationRulesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, alias, nextLink, options }, listAuthorizationRulesNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const checkNameAvailabilityOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/CheckNameAvailability", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.CheckNameAvailabilityResult }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters5, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1 ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ArmDisasterRecoveryListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1 ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ArmDisasterRecovery }, 201: {}, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters7, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.alias ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}", httpMethod: "DELETE", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.alias ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ArmDisasterRecovery }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.alias ], headerParameters: [Parameters.accept], serializer }; const breakPairingOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/breakPairing", httpMethod: "POST", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.alias ], headerParameters: [Parameters.accept], serializer }; const failOverOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/failover", httpMethod: "POST", responses: { 200: {}, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters8, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.alias ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listAuthorizationRulesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/authorizationRules", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBAuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.alias ], headerParameters: [Parameters.accept], serializer }; const getAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/authorizationRules/{authorizationRuleName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBAuthorizationRule }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.authorizationRuleName, Parameters.alias ], headerParameters: [Parameters.accept], serializer }; const listKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/disasterRecoveryConfigs/{alias}/authorizationRules/{authorizationRuleName}/listKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AccessKeys }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.authorizationRuleName, Parameters.alias ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ArmDisasterRecoveryListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listAuthorizationRulesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SBAuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName1, Parameters.nextLink, Parameters.alias ], headerParameters: [Parameters.accept], serializer };
the_stack
import qs from 'qs'; import { createSearchClient } from '../../../test/mock/createSearchClient'; import { createWidget } from '../../../test/mock/createWidget'; import { wait } from '../../../test/utils/wait'; import type { Router, Widget, UiState, StateMapping, IndexUiState, } from '../../types'; import historyRouter from '../routers/history'; import instantsearch from '../..'; import type { JSDOM } from 'jsdom'; declare const jsdom: JSDOM; const createFakeRouter = (args: Partial<Router> = {}): Router => ({ onUpdate(..._args) {}, write(..._args) {}, read() { return {}; }, createURL(..._args) { return ''; }, dispose() { return undefined; }, ...args, }); const createFakeStateMapping = ( args: Partial<StateMapping> = {} ): StateMapping => ({ stateToRoute(uiState) { return uiState; }, routeToState(routeState) { return routeState; }, ...args, }); type HistoryState<TEntry> = { index: number; entries: TEntry[]; listeners: Array<(value: TEntry) => void>; }; const createFakeHistory = <TEntry = Record<string, unknown>>( { index = -1, entries = [], listeners = [], }: HistoryState<TEntry> = {} as HistoryState<TEntry> ) => { const state: HistoryState<TEntry> = { index, entries, listeners, }; return { subscribe(listener: (entry: TEntry) => void) { state.listeners.push(listener); }, push(value: TEntry) { state.entries.push(value); state.index++; }, back() { state.index--; listeners.forEach((listener) => { listener(state.entries[state.index]); }); }, }; }; const createFakeSearchBox = (): Widget => createWidget({ render({ helper }) { (this as any).refine = (value: string) => { helper.setQuery(value).search(); }; }, dispose({ state }) { return state.setQuery(''); }, getWidgetSearchParameters(searchParameters, { uiState }) { return searchParameters.setQuery(uiState.query || ''); }, getWidgetUiState(uiState, { searchParameters }) { return { ...uiState, query: searchParameters.query, }; }, }); const createFakeHitsPerPage = (): Widget => createWidget({ dispose({ state }) { return state; }, getWidgetSearchParameters(parameters) { return parameters; }, getWidgetUiState(uiState) { return uiState; }, }); describe('RoutingManager', () => { describe('within instantsearch', () => { // eslint-disable-next-line jest/no-done-callback test('should write in the router on searchParameters change', (done) => { const searchClient = createSearchClient(); const router = createFakeRouter({ write: jest.fn(), }); const search = instantsearch({ indexName: 'indexName', searchClient, routing: { router, }, }); const widget = createWidget({ render: jest.fn(), getWidgetUiState: jest.fn((uiState, { searchParameters }) => ({ ...uiState, q: searchParameters.query, })), getWidgetSearchParameters: jest.fn( (searchParameters) => searchParameters ), }); search.addWidgets([widget]); search.start(); search.once('render', async () => { // initialization is done at this point expect(widget.render).toHaveBeenCalledTimes(1); expect(widget.getWidgetSearchParameters).toHaveBeenCalledTimes(1); await wait(0); expect(router.write).toHaveBeenCalledTimes(0); search.mainIndex.getHelper()!.setQuery('q'); // routing write updates on change await wait(0); expect(router.write).toHaveBeenCalledTimes(1); expect(router.write).toHaveBeenCalledWith({ indexName: { q: 'q', }, }); done(); }); }); // eslint-disable-next-line jest/no-done-callback test('should update the searchParameters on router state update', (done) => { const searchClient = createSearchClient(); let onRouterUpdateCallback: (args: UiState) => void; const router = createFakeRouter({ onUpdate: (fn) => { onRouterUpdateCallback = fn; }, }); const search = instantsearch({ indexName: 'indexName', searchClient, routing: { router, }, }); const widget = createWidget({ render: jest.fn(), getWidgetSearchParameters: jest.fn((searchParameters, { uiState }) => searchParameters.setQuery(uiState.query) ), }); search.addWidgets([widget]); search.start(); search.once('render', () => { // initialization is done at this point expect(search.mainIndex.getHelper()!.state.query).toBeUndefined(); // this simulates a router update with a uiState of {query: 'a'} onRouterUpdateCallback({ indexName: { query: 'a', }, }); search.once('render', () => { // the router update triggers a new search // and given that the widget reads q as a query parameter expect(search.mainIndex.getHelper()!.state.query).toEqual('a'); done(); }); }); }); // eslint-disable-next-line jest/no-done-callback test('should apply state mapping on differences after searchFunction', (done) => { const searchClient = createSearchClient(); const router = createFakeRouter({ write: jest.fn(), }); const stateMapping = createFakeStateMapping({ stateToRoute(uiState) { return Object.keys(uiState).reduce((state, indexId) => { const indexState = uiState[indexId]; return { ...state, [indexId]: { query: indexState.query && indexState.query.toUpperCase(), }, }; }, {}); }, }); const search = instantsearch({ indexName: 'indexName', searchFunction: (helper) => { helper.setQuery('test').search(); }, searchClient, routing: { stateMapping, router, }, }); search.addWidgets([ createWidget({ getWidgetUiState(uiState, { searchParameters }) { return { ...uiState, query: searchParameters.query, }; }, getWidgetSearchParameters: jest.fn( (searchParameters) => searchParameters ), }), ]); search.start(); search.once('render', () => { // initialization is done at this point expect(search.mainIndex.getHelper()!.state.query).toEqual('test'); expect(router.write).toHaveBeenLastCalledWith({ indexName: { query: 'TEST', }, }); done(); }); }); test('should keep the UI state up to date on state changes', async () => { const searchClient = createSearchClient(); const stateMapping = createFakeStateMapping({}); const router = createFakeRouter({ write: jest.fn(), }); const search = instantsearch({ indexName: 'indexName', searchClient, routing: { stateMapping, router, }, }); const fakeSearchBox: any = createFakeSearchBox(); const fakeHitsPerPage = createFakeHitsPerPage(); search.addWidgets([fakeSearchBox, fakeHitsPerPage]); search.start(); await wait(0); // Trigger an update - push a change fakeSearchBox.refine('Apple'); await wait(0); expect(router.write).toHaveBeenCalledTimes(1); expect(router.write).toHaveBeenLastCalledWith({ indexName: { query: 'Apple', }, }); await wait(0); // Trigger change search.removeWidgets([fakeHitsPerPage]); await wait(0); // The UI state hasn't changed so `router.write` wasn't called a second // time expect(router.write).toHaveBeenCalledTimes(1); }); test('should keep the UI state up to date on first render', async () => { const searchClient = createSearchClient(); const stateMapping = createFakeStateMapping({}); const router = createFakeRouter({ write: jest.fn(), }); const search = instantsearch({ indexName: 'indexName', searchFunction(helper) { // Force the value of the query helper.setQuery('Apple iPhone').search(); }, searchClient, routing: { router, stateMapping, }, }); const fakeSearchBox = createFakeSearchBox(); const fakeHitsPerPage = createFakeHitsPerPage(); search.addWidgets([fakeSearchBox, fakeHitsPerPage]); // Trigger the call to `searchFunction` -> Apple iPhone search.start(); await wait(0); expect(router.write).toHaveBeenCalledTimes(1); expect(router.write).toHaveBeenLastCalledWith({ indexName: { query: 'Apple iPhone', }, }); // Trigger change search.removeWidgets([fakeHitsPerPage]); await wait(0); // The UI state hasn't changed so `router.write` wasn't called a second // time expect(router.write).toHaveBeenCalledTimes(1); }); test('should keep the UI state up to date on router.update', async () => { const searchClient = createSearchClient(); const stateMapping = createFakeStateMapping({}); const history = createFakeHistory<UiState>(); const router = createFakeRouter({ onUpdate(fn) { history.subscribe((state) => { fn(state); }); }, write: jest.fn((state) => { history.push(state); }), }); const search = instantsearch({ indexName: 'indexName', searchClient, routing: { router, stateMapping, }, }); const fakeSearchBox: any = createFakeSearchBox(); const fakeHitsPerPage = createFakeHitsPerPage(); search.addWidgets([fakeSearchBox, fakeHitsPerPage]); search.start(); await wait(0); // Trigger an update - push a change fakeSearchBox.refine('Apple'); await wait(0); expect(router.write).toHaveBeenCalledTimes(1); expect(router.write).toHaveBeenLastCalledWith({ indexName: { query: 'Apple', }, }); // Trigger an update - push a change fakeSearchBox.refine('Apple iPhone'); await wait(0); expect(router.write).toHaveBeenCalledTimes(2); expect(router.write).toHaveBeenLastCalledWith({ indexName: { query: 'Apple iPhone', }, }); await wait(0); // Trigger an update - Apple iPhone → Apple history.back(); await wait(0); // Trigger change search.removeWidgets([fakeHitsPerPage]); await wait(0); expect(router.write).toHaveBeenCalledTimes(3); expect(router.write).toHaveBeenLastCalledWith({ indexName: { query: 'Apple', }, }); }); test('skips duplicate route state entries', async () => { let triggerChange = false; const searchClient = createSearchClient(); const stateMapping = createFakeStateMapping({ stateToRoute(uiState) { if (triggerChange) { return { ...uiState, indexName: { ...uiState.indexName, triggerChange, }, }; } return uiState; }, }); const history = createFakeHistory<UiState>(); const router = createFakeRouter({ onUpdate(fn) { history.subscribe((state) => { fn(state); }); }, write: jest.fn((state) => { history.push(state); }), }); const search = instantsearch({ indexName: 'indexName', searchClient, routing: { router, stateMapping, }, }); const fakeSearchBox: any = createFakeSearchBox(); const fakeHitsPerPage1 = createFakeHitsPerPage(); const fakeHitsPerPage2 = createFakeHitsPerPage(); search.addWidgets([fakeSearchBox, fakeHitsPerPage1, fakeHitsPerPage2]); search.start(); await wait(0); // Trigger an update - push a change fakeSearchBox.refine('Apple'); await wait(0); expect(router.write).toHaveBeenCalledTimes(1); expect(router.write).toHaveBeenLastCalledWith({ indexName: { query: 'Apple', }, }); // Trigger change without UI state change search.removeWidgets([fakeHitsPerPage1]); await wait(0); expect(router.write).toHaveBeenCalledTimes(1); await wait(0); triggerChange = true; // Trigger change without UI state change but with a route change search.removeWidgets([fakeHitsPerPage2]); await wait(0); expect(router.write).toHaveBeenCalledTimes(2); expect(router.write).toHaveBeenLastCalledWith({ indexName: { query: 'Apple', triggerChange: true, }, }); }); }); describe('windowTitle', () => { test('should update the window title with URL query params on first render', async () => { jsdom.reconfigure({ url: 'https://website.com/?query=query', }); const setWindowTitle = jest.spyOn(window.document, 'title', 'set'); const searchClient = createSearchClient(); const stateMapping = createFakeStateMapping({}); const router = historyRouter({ windowTitle(routeState) { return `Searching for "${routeState.query}"`; }, }); const search = instantsearch({ indexName: 'instant_search', searchClient, routing: { router, stateMapping, }, }); const fakeSearchBox = createFakeSearchBox(); search.addWidgets([fakeSearchBox]); search.start(); await wait(0); expect(setWindowTitle).toHaveBeenCalledTimes(1); expect(setWindowTitle).toHaveBeenLastCalledWith('Searching for "query"'); setWindowTitle.mockRestore(); }); }); describe('parseURL', () => { const createFakeUrlWithRefinements: ({ length, }: { length: number; }) => string = ({ length }) => [ 'https://website.com/', Array.from( { length }, (_v, i) => `refinementList[brand][${i}]=brand-${i}` ).join('&'), ].join('?'); test('should parse refinements with more than 20 filters per category as array', () => { jsdom.reconfigure({ url: createFakeUrlWithRefinements({ length: 22 }), }); const router = historyRouter<IndexUiState>(); // @ts-expect-error: This method is considered private but we still use it // in the test after the TypeScript migration. // In a next refactor, we can consider changing this test implementation. const parsedUrl = router.parseURL({ qsModule: qs, location: window.location, }); expect(parsedUrl.refinementList!.brand).toBeInstanceOf(Array); expect(parsedUrl).toMatchInlineSnapshot(` { "refinementList": { "brand": [ "brand-0", "brand-1", "brand-2", "brand-3", "brand-4", "brand-5", "brand-6", "brand-7", "brand-8", "brand-9", "brand-10", "brand-11", "brand-12", "brand-13", "brand-14", "brand-15", "brand-16", "brand-17", "brand-18", "brand-19", "brand-20", "brand-21", ], }, } `); }); test('should support returning 100 refinements as array', () => { jsdom.reconfigure({ url: createFakeUrlWithRefinements({ length: 100 }), }); const router = historyRouter<IndexUiState>(); // @ts-expect-error: This method is considered private but we still use it // in the test after the TypeScript migration. // In a next refactor, we can consider changing this test implementation. const parsedUrl = router.parseURL({ qsModule: qs, location: window.location, }); expect(parsedUrl.refinementList!.brand).toBeInstanceOf(Array); }); }); describe('createURL', () => { it('returns an URL for a `routeState` with refinements', () => { const router = historyRouter<IndexUiState>(); const actual = router.createURL({ query: 'iPhone', page: 5, }); expect(actual).toBe('https://website.com/?query=iPhone&page=5'); }); it('returns an URL for an empty `routeState` with index', () => { const router = historyRouter(); const actual = router.createURL({ indexName: {}, }); expect(actual).toBe('https://website.com/'); }); it('returns an URL for an empty `routeState`', () => { const router = historyRouter(); const actual = router.createURL({}); expect(actual).toBe('https://website.com/'); }); }); });
the_stack
import React, { useState, useRef } from 'react'; import { useQueryClient } from 'react-query'; import { T } from '@tolgee/react'; import ReactList from 'react-list'; import { createProvider } from 'tg.fixtures/createProvider'; import { components, operations } from 'tg.service/apiSchema.generated'; import { invalidateUrlPrefix, useApiQuery } from 'tg.service/http/useQueryApi'; import { container } from 'tsyringe'; import { MessageService } from 'tg.service/MessageService'; import { ProjectPreferencesService } from 'tg.service/ProjectPreferencesService'; import { parseErrorResponse } from 'tg.fixtures/errorFIxtures'; import { confirmation } from 'tg.hooks/confirmation'; import { useTranslationsInfinite } from './useTranslationsInfinite'; import { useEdit, EditType } from './useEdit'; import { StateType } from 'tg.constants/translationStates'; import { useUrlSearchState } from 'tg.hooks/useUrlSearchState'; import { usePostKey, useDeleteKeys, usePutTag, useDeleteTag, usePutTranslationState, } from 'tg.service/TranslationHooks'; export type AfterCommand = 'EDIT_NEXT'; type LanguagesType = components['schemas']['LanguageModel']; type TranslationViewModel = components['schemas']['TranslationViewModel']; type KeyWithTranslationsModelType = components['schemas']['KeyWithTranslationsModel']; type TranslationsQueryType = operations['getTranslations']['parameters']['query']; type ActionType = | { type: 'SET_SEARCH'; payload: string } | { type: 'SET_SEARCH_IMMEDIATE'; payload: string } | { type: 'SET_FILTERS'; payload: FiltersType } | { type: 'SET_EDIT'; payload: EditType | undefined } | { type: 'SET_EDIT_FORCE'; payload: EditType | undefined } | { type: 'UPDATE_EDIT'; payload: Partial<EditType> } | { type: 'TOGGLE_SELECT'; payload: number } | { type: 'CHANGE_FIELD'; payload: ChangeValueType } | { type: 'FETCH_MORE' } | { type: 'SELECT_LANGUAGES'; payload: string[] | undefined } | { type: 'UPDATE_SCREENSHOT_COUNT'; payload: ChangeScreenshotNum } | { type: 'CHANGE_VIEW'; payload: ViewType } | { type: 'UPDATE_LANGUAGES' } | { type: 'DELETE_TRANSLATIONS'; payload: number[] } | { type: 'SET_TRANSLATION_STATE'; payload: SetTranslationStatePayload } | { type: 'ADD_TAG'; payload: AddTagPayload; onSuccess?: () => void } | { type: 'REMOVE_TAG'; payload: RemoveTagPayload } | { type: 'UPDATE_TRANSLATION'; payload: UpdateTranslationPayolad } | { type: 'INSERT_TRANSLATION'; payload: AddTranslationPayload } | { type: 'REGISTER_ELEMENT'; payload: KeyElement } | { type: 'UNREGISTER_ELEMENT'; payload: KeyElement } | { type: 'REGISTER_LIST'; payload: ReactList } | { type: 'UNREGISTER_LIST'; payload: ReactList }; type CellPosition = { keyId: number; language: string | undefined; }; type KeyElement = CellPosition & { ref: HTMLElement; }; export type ViewType = 'LIST' | 'TABLE'; type AddTranslationPayload = KeyWithTranslationsModelType; type UpdateTranslationPayolad = { keyId: number; lang: string; data: Partial<TranslationViewModel>; }; type RemoveTagPayload = { keyId: number; tagId: number; }; type AddTagPayload = { keyId: number; name: string; }; type ChangeValueType = { after?: AfterCommand; onSuccess?: () => void; }; export type FiltersType = Pick< TranslationsQueryType, | 'filterHasNoScreenshot' | 'filterHasScreenshot' | 'filterTranslatedAny' | 'filterUntranslatedAny' | 'filterTranslatedInLang' | 'filterUntranslatedInLang' | 'filterState' | 'filterTag' >; type SetTranslationStatePayload = { keyId: number; translationId: number; language: string; state: StateType; }; type ChangeScreenshotNum = { keyId: number; screenshotCount: number | undefined; }; export type TranslationsContextType = { dataReady: boolean; translations?: KeyWithTranslationsModelType[]; translationsLanguages?: string[]; translationsTotal?: number; languages?: LanguagesType[]; isLoading?: boolean; isFetching?: boolean; isFetchingMore?: boolean; isEditLoading?: boolean; hasMoreToFetch?: boolean; search?: string; urlSearch: string | undefined; selection: number[]; cursor?: EditType; selectedLanguages?: string[]; view: ViewType; filters: FiltersType; elementsRef: React.RefObject<Map<string, HTMLElement>>; reactList: ReactList | undefined; }; const messaging = container.resolve(MessageService); const projectPreferences = container.resolve(ProjectPreferencesService); export const [ TranslationsContextProvider, useTranslationsDispatch, useTranslationsSelector, ] = createProvider( (props: { projectId: number; keyName?: string; languages?: string[]; updateLocalStorageLanguages?: boolean; pageSize?: number; }) => { const queryClient = useQueryClient(); const [selection, setSelection] = useState<number[]>([]); const [view, setView] = useUrlSearchState('view', { defaultVal: 'LIST' }); const [initialLangs, setInitialLangs] = useState< string[] | null | undefined >(null); const elementsRef = useRef<Map<string, HTMLElement>>(new Map()); const [reactList, setReactList] = useState<ReactList>(); const languages = useApiQuery({ url: '/v2/projects/{projectId}/languages', method: 'get', path: { projectId: props.projectId }, query: { size: 1000, sort: ['tag'] }, options: { onSuccess(data) { const languages = projectPreferences .getForProject(props.projectId) ?.filter((l) => data._embedded?.languages?.find((lang) => lang.tag === l) ); // manually set initial langs setInitialLangs(languages.length ? languages : undefined); }, cacheTime: 0, }, }); const translations = useTranslationsInfinite({ projectId: props.projectId, keyName: props.keyName, pageSize: props.pageSize, updateLocalStorageLanguages: props.updateLocalStorageLanguages, // when initial langs are null, fetching is postponed initialLangs: props.languages || initialLangs, }); const edit = useEdit({ projectId: props.projectId, translations: translations.fixedTranslations, }); const handleTranslationsReset = () => { edit.setPosition(undefined); setSelection([]); }; const focusCell = (cell: CellPosition) => { const element = elementsRef.current?.get( JSON.stringify({ keyId: cell.keyId, language: cell.language }) ); element?.focus(); }; const setFocusPosition = (pos: EditType | undefined) => { // make it async if someone is stealing focus setTimeout(() => { // focus cell when closing editor if (pos === undefined && edit.position) { const position = { keyId: edit.position.keyId, language: edit.position.language, }; focusCell(position); } edit.setPosition(pos); }); }; const postKey = usePostKey(); const deleteKeys = useDeleteKeys(); const putTag = usePutTag(); const deleteTag = useDeleteTag(); const putTranslationState = usePutTranslationState(); const dispatch = async (action: ActionType) => { switch (action.type) { case 'SET_SEARCH': translations.setSearch(action.payload); handleTranslationsReset(); return; case 'SET_SEARCH_IMMEDIATE': translations.setUrlSearch(action.payload); handleTranslationsReset(); return; case 'SET_FILTERS': translations.setFilters(action.payload); handleTranslationsReset(); return; case 'SET_EDIT': if (edit.position?.changed) { setFocusPosition({ ...edit.position, mode: 'editor' }); confirmation({ title: <T>translations_unsaved_changes_confirmation_title</T>, message: <T>translations_unsaved_changes_confirmation</T>, cancelButtonText: <T>back_to_editing</T>, confirmButtonText: <T>translations_cell_save</T>, onConfirm: () => { dispatch({ type: 'CHANGE_FIELD', payload: { onSuccess() { setFocusPosition(action.payload); }, }, }); }, }); } else { setFocusPosition(action.payload); } return; case 'SET_EDIT_FORCE': setFocusPosition(action.payload); return; case 'UPDATE_EDIT': edit.setPosition((pos) => pos ? { ...pos, ...action.payload } : pos ); return; case 'TOGGLE_SELECT': { const newSelection = selection.includes(action.payload) ? selection.filter((s) => s !== action.payload) : [...selection, action.payload]; setSelection(newSelection); return; } case 'FETCH_MORE': translations.fetchNextPage(); return; case 'CHANGE_FIELD': { if (!edit.position) { return; } const { keyId, language, value } = edit.position; if (!language && !value) { // key can't be empty messaging.error(<T>global_empty_value</T>); return; } try { if (language) { // update translation await edit .mutateTranslation({ ...action.payload, value: value as string, keyId, language, }) .then((data) => { if (data) { return translations.updateTranslation( keyId, language, data?.translations[language] ); } }); } else { // update key await edit .mutateTranslationKey({ ...action.payload, value: value as string, keyId, language, }) .then(() => translations.updateTranslationKey(keyId, { keyName: value }) ); } doAfterCommand(action.payload.after); action.payload.onSuccess?.(); } catch (e) { const parsed = parseErrorResponse(e); parsed.forEach((error) => messaging.error(<T>{error}</T>)); } return; } case 'SELECT_LANGUAGES': translations.updateQuery({ languages: action.payload }); handleTranslationsReset(); return; case 'UPDATE_LANGUAGES': translations.updateQuery({}); handleTranslationsReset(); return; case 'UPDATE_SCREENSHOT_COUNT': translations.updateTranslationKey(action.payload.keyId, { screenshotCount: action.payload.screenshotCount, }); return; case 'CHANGE_VIEW': setView(action.payload); return; case 'DELETE_TRANSLATIONS': confirmation({ title: <T>translations_delete_selected</T>, message: ( <T parameters={{ count: String(action.payload.length) }}> translations_key_delete_confirmation_text </T> ), onConfirm() { deleteKeys.mutate( { path: { projectId: props.projectId, ids: action.payload }, }, { onSuccess() { translations.refetchTranslations(); handleTranslationsReset(); messaging.success( <T>Translation grid - Successfully deleted!</T> ); }, onError(e) { const parsed = parseErrorResponse(e); parsed.forEach((error) => messaging.error(<T>{error}</T>)); }, } ); }, }); return; case 'SET_TRANSLATION_STATE': putTranslationState.mutate( { path: { projectId: props.projectId, translationId: action.payload.translationId, state: action.payload.state, }, }, { onSuccess(data) { translations.updateTranslation( action.payload.keyId, action.payload.language, data ); }, onError(e) { const parsed = parseErrorResponse(e); parsed.forEach((error) => messaging.error(<T>{error}</T>)); }, } ); return; case 'ADD_TAG': return putTag .mutateAsync({ path: { projectId: props.projectId, keyId: action.payload.keyId }, content: { 'application/json': { name: action.payload.name } }, }) .then((data) => { const previousTags = translations.fixedTranslations ?.find((key) => key.keyId === action.payload.keyId) ?.keyTags.filter((t) => t.id !== data.id) || []; translations.updateTranslationKey(action.payload.keyId, { keyTags: [...previousTags, data!], }); invalidateUrlPrefix(queryClient, '/v2/projects/{projectId}/tags'); action.onSuccess?.(); }) .catch((e) => { const parsed = parseErrorResponse(e); parsed.forEach((error) => messaging.error(<T>{error}</T>)); // return never fullfilling promise to prevent after action return new Promise(() => {}); }); case 'REMOVE_TAG': return deleteTag .mutateAsync({ path: { keyId: action.payload.keyId, tagId: action.payload.tagId, projectId: props.projectId, }, }) .then(() => { const previousTags = translations.fixedTranslations?.find( (key) => key.keyId === action.payload.keyId )?.keyTags; invalidateUrlPrefix(queryClient, '/v2/projects/{projectId}/tags'); translations.updateTranslationKey(action.payload.keyId, { keyTags: previousTags?.filter( (t) => t.id !== action.payload.tagId ), }); }) .catch((e) => { const parsed = parseErrorResponse(e); parsed.forEach((error) => messaging.error(<T>{error}</T>)); }); case 'UPDATE_TRANSLATION': return translations.updateTranslation( action.payload.keyId, action.payload.lang, action.payload.data ); case 'INSERT_TRANSLATION': translations.insertAsFirst(action.payload); return; case 'REGISTER_ELEMENT': return elementsRef.current.set( JSON.stringify({ keyId: action.payload.keyId, language: action.payload.language, }), action.payload.ref ); case 'UNREGISTER_ELEMENT': return elementsRef.current.delete( JSON.stringify({ keyId: action.payload.keyId, language: action.payload.language, }) ); case 'REGISTER_LIST': setReactList(action.payload); return; case 'UNREGISTER_LIST': if (reactList === action.payload) { setReactList(undefined); } return; } }; const doAfterCommand = (command?: AfterCommand) => { switch (command) { case 'EDIT_NEXT': edit.moveEditToDirection('DOWN'); return; default: setFocusPosition(undefined); } }; const dataReady = Boolean(languages.data && translations.fixedTranslations); const state = { dataReady, translations: dataReady ? translations.fixedTranslations : undefined, translationsLanguages: translations.selectedLanguages, translationsTotal: translations.totalCount !== undefined ? translations.totalCount : undefined, languages: dataReady ? languages.data?._embedded?.languages : undefined, isLoading: translations.isLoading || languages.isLoading, isFetching: translations.isFetching || languages.isFetching || deleteKeys.isLoading || putTranslationState.isLoading || putTag.isLoading || deleteTag.isLoading || postKey.isLoading, isEditLoading: edit.isLoading, isFetchingMore: translations.isFetchingNextPage, hasMoreToFetch: translations.hasNextPage, search: translations.search as string, urlSearch: translations.urlSearch, filters: translations.filters, cursor: edit.position, selection, selectedLanguages: translations.query?.languages || translations.selectedLanguages, view: view as ViewType, elementsRef, reactList, }; return [state, dispatch]; } );
the_stack
import { Lexer, OPERATOR_CHARS, OPERATORS, OperatorTree, TemplateLexer, Token, TokenType } from './lexer' describe('Lexer', () => { const lexer = new Lexer() test('scans an expression', () => { lexer.reset('ab * 2') expect(lexer.peek()).toEqual({ type: TokenType.Identifier, value: 'ab' } as Token) const token = lexer.next() expect(token).toEqual({ type: TokenType.Identifier, value: 'ab', start: 0, end: 2 } as Token) expect(lexer.next()).toBeTruthy() expect(lexer.next()).toBeTruthy() expect(lexer.peek()).toBe(undefined) expect(lexer.next()).toBe(undefined) lexer.reset('a') expect(lexer.next()).toEqual({ type: TokenType.Identifier, value: 'a', start: 0, end: 1 } as Token) }) test('scans identifier with dots', () => expect(scanAll(lexer, 'a.b')).toEqual([ { type: TokenType.Identifier, value: 'a.b', start: 0, end: 3 }, ] as Token[])) test('scans string', () => expect(scanAll(lexer, '"a\\nb\\"c\'d"')).toEqual([ { type: TokenType.String, value: 'a\nb"c\'d', start: 0, end: 11 }, ] as Token[])) /* eslint-disable no-template-curly-in-string */ describe('templates', () => { test('scans no-substitution template', () => expect(scanAll(lexer, '`a`')).toEqual([ { type: TokenType.NoSubstitutionTemplate, value: 'a', start: 0, end: 3 }, ] as Token[])) test('scans template with empty head/tail', () => expect(scanAll(lexer, '`${x}`')).toEqual([ { type: TokenType.TemplateHead, value: '', start: 0, end: 3 }, { type: TokenType.Identifier, value: 'x', start: 3, end: 4 }, { type: TokenType.TemplateTail, value: '', start: 4, end: 6 }, ] as Token[])) test('scans template with empty head/tail and multiple tokens', () => expect(scanAll(lexer, '`${x+y}`')).toEqual([ { type: TokenType.TemplateHead, value: '', start: 0, end: 3 }, { type: TokenType.Identifier, value: 'x', start: 3, end: 4 }, { type: TokenType.Operator, value: '+', start: 4, end: 5 }, { type: TokenType.Identifier, value: 'y', start: 5, end: 6 }, { type: TokenType.TemplateTail, value: '', start: 6, end: 8 }, ] as Token[])) test('scans template with non-empty head, empty tail', () => expect(scanAll(lexer, '`a${x}`')).toEqual([ { type: TokenType.TemplateHead, value: 'a', start: 0, end: 4 }, { type: TokenType.Identifier, value: 'x', start: 4, end: 5 }, { type: TokenType.TemplateTail, value: '', start: 5, end: 7 }, ] as Token[])) test('scans template with empty head, non-empty tail', () => expect(scanAll(lexer, '`${x}b`')).toEqual([ { type: TokenType.TemplateHead, value: '', start: 0, end: 3 }, { type: TokenType.Identifier, value: 'x', start: 3, end: 4 }, { type: TokenType.TemplateTail, value: 'b', start: 4, end: 7 }, ] as Token[])) test('scans template with non-empty head/tail', () => expect(scanAll(lexer, '`a${x}b`')).toEqual([ { type: TokenType.TemplateHead, value: 'a', start: 0, end: 4 }, { type: TokenType.Identifier, value: 'x', start: 4, end: 5 }, { type: TokenType.TemplateTail, value: 'b', start: 5, end: 8 }, ] as Token[])) test('scans template with middle and empty values', () => expect(scanAll(lexer, '`${x}${y}`')).toEqual([ { type: TokenType.TemplateHead, value: '', start: 0, end: 3 }, { type: TokenType.Identifier, value: 'x', start: 3, end: 4 }, { type: TokenType.TemplateMiddle, value: '', start: 4, end: 7 }, { type: TokenType.Identifier, value: 'y', start: 7, end: 8 }, { type: TokenType.TemplateTail, value: '', start: 8, end: 10 }, ] as Token[])) test('scans template with middle', () => expect(scanAll(lexer, '`a${x}b${y}c`')).toEqual([ { type: TokenType.TemplateHead, value: 'a', start: 0, end: 4 }, { type: TokenType.Identifier, value: 'x', start: 4, end: 5 }, { type: TokenType.TemplateMiddle, value: 'b', start: 5, end: 9 }, { type: TokenType.Identifier, value: 'y', start: 9, end: 10 }, { type: TokenType.TemplateTail, value: 'c', start: 10, end: 13 }, ] as Token[])) test('scans nested no-substitution template', () => expect(scanAll(lexer, '`a${`x`}b`')).toEqual([ { type: TokenType.TemplateHead, value: 'a', start: 0, end: 4 }, { type: TokenType.NoSubstitutionTemplate, value: 'x', start: 4, end: 7 }, { type: TokenType.TemplateTail, value: 'b', start: 7, end: 10 }, ] as Token[])) test('scans nested template', () => expect(scanAll(lexer, '`a${`x${y}z`}b`')).toEqual([ { type: TokenType.TemplateHead, value: 'a', start: 0, end: 4 }, { type: TokenType.TemplateHead, value: 'x', start: 4, end: 8 }, { type: TokenType.Identifier, value: 'y', start: 8, end: 9 }, { type: TokenType.TemplateTail, value: 'z', start: 9, end: 12 }, { type: TokenType.TemplateTail, value: 'b', start: 12, end: 15 }, ] as Token[])) test('throws on unclosed expression', () => expect(() => scanAll(lexer, 'x${')).toThrow()) }) /* eslint-enable no-template-curly-in-string */ test('throws on unclosed string', () => { lexer.reset('"a') expect(() => lexer.next()).toThrow() }) test('scans single-char binary operators', () => expect(scanAll(lexer, 'a = b')).toEqual([ { type: TokenType.Identifier, value: 'a', start: 0, end: 1 }, { type: TokenType.Operator, value: '=', start: 2, end: 3 }, { type: TokenType.Identifier, value: 'b', start: 4, end: 5 }, ] as Token[])) test('scans 2-char binary operators', () => expect(scanAll(lexer, 'a == b')).toEqual([ { type: TokenType.Identifier, value: 'a', start: 0, end: 1 }, { type: TokenType.Operator, value: '==', start: 2, end: 4 }, { type: TokenType.Identifier, value: 'b', start: 5, end: 6 }, ] as Token[])) test('scans 3-char binary operators', () => expect(scanAll(lexer, 'a !== b')).toEqual([ { type: TokenType.Identifier, value: 'a', start: 0, end: 1 }, { type: TokenType.Operator, value: '!==', start: 2, end: 5 }, { type: TokenType.Identifier, value: 'b', start: 6, end: 7 }, ] as Token[])) test('scans adjacent operators', () => { expect(scanAll(lexer, 'a==!b')).toEqual([ { type: TokenType.Identifier, value: 'a', start: 0, end: 1 }, { type: TokenType.Operator, value: '==', start: 1, end: 3 }, { type: TokenType.Operator, value: '!', start: 3, end: 4 }, { type: TokenType.Identifier, value: 'b', start: 4, end: 5 }, ] as Token[]) }) describe('constants', () => { test('OPERATOR_CHARS', () => { const maxOpLength = Math.max(...Object.keys(OPERATORS).map(operator => operator.length)) for (const operator of Object.keys(OPERATORS)) { if (operator.length === 1) { expect( OPERATOR_CHARS[operator] === true || (OPERATOR_CHARS[operator] as { [ch: string]: OperatorTree })['\u0000'] === true ).toBeTruthy() } else if (operator.length === 2) { expect( (OPERATOR_CHARS[operator.charAt(0)] as { [ch: string]: OperatorTree })[operator.charAt(1)] === true || ((OPERATOR_CHARS[operator.charAt(0)] as { [ch: string]: OperatorTree })[ operator.charAt(1) ] as { [ch: string]: OperatorTree })['\u0000'] === true ).toBeTruthy() } else if (operator.length === 3) { expect( ((OPERATOR_CHARS[operator.charAt(0)] as { [ch: string]: OperatorTree })[operator.charAt(1)] as { [ch: string]: OperatorTree })[operator.charAt(2)] === true || (((OPERATOR_CHARS[operator.charAt(0)] as { [ch: string]: OperatorTree })[ operator.charAt(1) ] as { [ch: string]: OperatorTree })[operator.charAt(2)] as { [ch: string]: OperatorTree })['\u0000'] === true ).toBeTruthy() } else if (operator.length > maxOpLength) { throw new Error(`operators of length ${operator.length} are not yet supported`) } } }) }) }) describe('TemplateLexer', () => { const lexer = new TemplateLexer() test('scans template with middle', () => // eslint-disable-next-line no-template-curly-in-string expect(scanAll(lexer, 'a${x}b${y}c')).toEqual([ { type: TokenType.TemplateHead, value: 'a', start: 0, end: 3 }, { type: TokenType.Identifier, value: 'x', start: 3, end: 4 }, { type: TokenType.TemplateMiddle, value: 'b', start: 4, end: 8 }, { type: TokenType.Identifier, value: 'y', start: 8, end: 9 }, { type: TokenType.TemplateTail, value: 'c', start: 9, end: 11 }, ] as Token[])) }) function scanAll(lexer: Lexer, expressionString: string): Token[] { const tokens: Token[] = [] lexer.reset(expressionString) while (true) { const token = lexer.next() if (token) { tokens.push(token) } else { break } } return tokens }
the_stack
import uid2 = require("uid2"); import msgpack = require("notepack.io"); import { Adapter, BroadcastOptions, Room, SocketId } from "socket.io-adapter"; const debug = require("debug")("socket.io-redis"); module.exports = exports = createAdapter; /** * Request types, for messages between nodes */ enum RequestType { SOCKETS = 0, ALL_ROOMS = 1, REMOTE_JOIN = 2, REMOTE_LEAVE = 3, REMOTE_DISCONNECT = 4, REMOTE_FETCH = 5, SERVER_SIDE_EMIT = 6, } interface Request { type: RequestType; resolve: Function; timeout: NodeJS.Timeout; numSub?: number; msgCount?: number; [other: string]: any; } export interface RedisAdapterOptions { /** * the name of the key to pub/sub events on as prefix * @default socket.io */ key: string; /** * after this timeout the adapter will stop waiting from responses to request * @default 5000 */ requestsTimeout: number; } /** * Returns a function that will create a RedisAdapter instance. * * @param pubClient - a Redis client that will be used to publish messages * @param subClient - a Redis client that will be used to receive messages (put in subscribed state) * @param opts - additional options * * @public */ export function createAdapter( pubClient: any, subClient: any, opts?: Partial<RedisAdapterOptions> ) { return function (nsp) { return new RedisAdapter(nsp, pubClient, subClient, opts); }; } export class RedisAdapter extends Adapter { public readonly uid; public readonly requestsTimeout: number; private readonly channel: string; private readonly requestChannel: string; private readonly responseChannel: string; private requests: Map<string, Request> = new Map(); /** * Adapter constructor. * * @param nsp - the namespace * @param pubClient - a Redis client that will be used to publish messages * @param subClient - a Redis client that will be used to receive messages (put in subscribed state) * @param opts - additional options * * @public */ constructor( nsp: any, readonly pubClient: any, readonly subClient: any, opts: Partial<RedisAdapterOptions> = {} ) { super(nsp); this.uid = uid2(6); this.requestsTimeout = opts.requestsTimeout || 5000; const prefix = opts.key || "socket.io"; this.channel = prefix + "#" + nsp.name + "#"; this.requestChannel = prefix + "-request#" + this.nsp.name + "#"; this.responseChannel = prefix + "-response#" + this.nsp.name + "#"; const onError = (err) => { if (err) { this.emit("error", err); } }; this.subClient.psubscribe(this.channel + "*", onError); this.subClient.on("pmessageBuffer", this.onmessage.bind(this)); this.subClient.subscribe( [this.requestChannel, this.responseChannel], onError ); this.subClient.on("messageBuffer", this.onrequest.bind(this)); this.pubClient.on("error", onError); this.subClient.on("error", onError); } /** * Called with a subscription message * * @private */ private onmessage(pattern, channel, msg) { channel = channel.toString(); const channelMatches = channel.startsWith(this.channel); if (!channelMatches) { return debug("ignore different channel"); } const room = channel.slice(this.channel.length, -1); if (room !== "" && !this.rooms.has(room)) { return debug("ignore unknown room %s", room); } const args = msgpack.decode(msg); const [uid, packet, opts] = args; if (this.uid === uid) return debug("ignore same uid"); if (packet && packet.nsp === undefined) { packet.nsp = "/"; } if (!packet || packet.nsp !== this.nsp.name) { return debug("ignore different namespace"); } opts.rooms = new Set(opts.rooms); opts.except = new Set(opts.except); super.broadcast(packet, opts); } /** * Called on request from another node * * @private */ private async onrequest(channel, msg) { channel = channel.toString(); if (channel.startsWith(this.responseChannel)) { return this.onresponse(channel, msg); } else if (!channel.startsWith(this.requestChannel)) { return debug("ignore different channel"); } let request; try { request = JSON.parse(msg); } catch (err) { this.emit("error", err); return; } debug("received request %j", request); let response, socket; switch (request.type) { case RequestType.SOCKETS: if (this.requests.has(request.requestId)) { return; } const sockets = await super.sockets(new Set(request.rooms)); response = JSON.stringify({ requestId: request.requestId, sockets: [...sockets], }); this.pubClient.publish(this.responseChannel, response); break; case RequestType.ALL_ROOMS: if (this.requests.has(request.requestId)) { return; } response = JSON.stringify({ requestId: request.requestId, rooms: [...this.rooms.keys()], }); this.pubClient.publish(this.responseChannel, response); break; case RequestType.REMOTE_JOIN: if (request.opts) { const opts = { rooms: new Set<Room>(request.opts.rooms), except: new Set<Room>(request.opts.except), }; return super.addSockets(opts, request.rooms); } socket = this.nsp.sockets.get(request.sid); if (!socket) { return; } socket.join(request.room); response = JSON.stringify({ requestId: request.requestId, }); this.pubClient.publish(this.responseChannel, response); break; case RequestType.REMOTE_LEAVE: if (request.opts) { const opts = { rooms: new Set<Room>(request.opts.rooms), except: new Set<Room>(request.opts.except), }; return super.delSockets(opts, request.rooms); } socket = this.nsp.sockets.get(request.sid); if (!socket) { return; } socket.leave(request.room); response = JSON.stringify({ requestId: request.requestId, }); this.pubClient.publish(this.responseChannel, response); break; case RequestType.REMOTE_DISCONNECT: if (request.opts) { const opts = { rooms: new Set<Room>(request.opts.rooms), except: new Set<Room>(request.opts.except), }; return super.disconnectSockets(opts, request.close); } socket = this.nsp.sockets.get(request.sid); if (!socket) { return; } socket.disconnect(request.close); response = JSON.stringify({ requestId: request.requestId, }); this.pubClient.publish(this.responseChannel, response); break; case RequestType.REMOTE_FETCH: if (this.requests.has(request.requestId)) { return; } const opts = { rooms: new Set<Room>(request.opts.rooms), except: new Set<Room>(request.opts.except), }; const localSockets = await super.fetchSockets(opts); response = JSON.stringify({ requestId: request.requestId, sockets: localSockets.map((socket) => ({ id: socket.id, handshake: socket.handshake, rooms: [...socket.rooms], data: socket.data, })), }); this.pubClient.publish(this.responseChannel, response); break; case RequestType.SERVER_SIDE_EMIT: if (request.uid === this.uid) { debug("ignore same uid"); return; } const withAck = request.requestId !== undefined; if (!withAck) { this.nsp._onServerSideEmit(request.data); return; } let called = false; const callback = (arg) => { // only one argument is expected if (called) { return; } called = true; debug("calling acknowledgement with %j", arg); this.pubClient.publish( this.responseChannel, JSON.stringify({ type: RequestType.SERVER_SIDE_EMIT, requestId: request.requestId, data: arg, }) ); }; request.data.push(callback); this.nsp._onServerSideEmit(request.data); break; default: debug("ignoring unknown request type: %s", request.type); } } /** * Called on response from another node * * @private */ private onresponse(channel, msg) { let response; try { response = JSON.parse(msg); } catch (err) { this.emit("error", err); return; } const requestId = response.requestId; if (!requestId || !this.requests.has(requestId)) { debug("ignoring unknown request"); return; } debug("received response %j", response); const request = this.requests.get(requestId); switch (request.type) { case RequestType.SOCKETS: case RequestType.REMOTE_FETCH: request.msgCount++; // ignore if response does not contain 'sockets' key if (!response.sockets || !Array.isArray(response.sockets)) return; if (request.type === RequestType.SOCKETS) { response.sockets.forEach((s) => request.sockets.add(s)); } else { response.sockets.forEach((s) => request.sockets.push(s)); } if (request.msgCount === request.numSub) { clearTimeout(request.timeout); if (request.resolve) { request.resolve(request.sockets); } this.requests.delete(requestId); } break; case RequestType.ALL_ROOMS: request.msgCount++; // ignore if response does not contain 'rooms' key if (!response.rooms || !Array.isArray(response.rooms)) return; response.rooms.forEach((s) => request.rooms.add(s)); if (request.msgCount === request.numSub) { clearTimeout(request.timeout); if (request.resolve) { request.resolve(request.rooms); } this.requests.delete(requestId); } break; case RequestType.REMOTE_JOIN: case RequestType.REMOTE_LEAVE: case RequestType.REMOTE_DISCONNECT: clearTimeout(request.timeout); if (request.resolve) { request.resolve(); } this.requests.delete(requestId); break; case RequestType.SERVER_SIDE_EMIT: request.responses.push(response.data); debug( "serverSideEmit: got %d responses out of %d", request.responses.length, request.numSub ); if (request.responses.length === request.numSub) { clearTimeout(request.timeout); if (request.resolve) { request.resolve(null, request.responses); } this.requests.delete(requestId); } break; default: debug("ignoring unknown request type: %s", request.type); } } /** * Broadcasts a packet. * * @param {Object} packet - packet to emit * @param {Object} opts - options * * @public */ public broadcast(packet: any, opts: BroadcastOptions) { packet.nsp = this.nsp.name; const onlyLocal = opts && opts.flags && opts.flags.local; if (!onlyLocal) { const rawOpts = { rooms: [...opts.rooms], except: [...new Set(opts.except)], flags: opts.flags, }; const msg = msgpack.encode([this.uid, packet, rawOpts]); let channel = this.channel; if (opts.rooms && opts.rooms.size === 1) { channel += opts.rooms.keys().next().value + "#"; } debug("publishing message to channel %s", channel); this.pubClient.publish(channel, msg); } super.broadcast(packet, opts); } /** * Gets a list of sockets by sid. * * @param {Set<Room>} rooms the explicit set of rooms to check. */ public async sockets(rooms: Set<Room>): Promise<Set<SocketId>> { const localSockets = await super.sockets(rooms); const numSub = await this.getNumSub(); debug('waiting for %d responses to "sockets" request', numSub); if (numSub <= 1) { return Promise.resolve(localSockets); } const requestId = uid2(6); const request = JSON.stringify({ requestId, type: RequestType.SOCKETS, rooms: [...rooms], }); return new Promise((resolve, reject) => { const timeout = setTimeout(() => { if (this.requests.has(requestId)) { reject( new Error("timeout reached while waiting for sockets response") ); this.requests.delete(requestId); } }, this.requestsTimeout); this.requests.set(requestId, { type: RequestType.SOCKETS, numSub, resolve, timeout, msgCount: 1, sockets: localSockets, }); this.pubClient.publish(this.requestChannel, request); }); } /** * Gets the list of all rooms (across every node) * * @public */ public async allRooms(): Promise<Set<Room>> { const localRooms = new Set(this.rooms.keys()); const numSub = await this.getNumSub(); debug('waiting for %d responses to "allRooms" request', numSub); if (numSub <= 1) { return localRooms; } const requestId = uid2(6); const request = JSON.stringify({ requestId, type: RequestType.ALL_ROOMS, }); return new Promise((resolve, reject) => { const timeout = setTimeout(() => { if (this.requests.has(requestId)) { reject( new Error("timeout reached while waiting for allRooms response") ); this.requests.delete(requestId); } }, this.requestsTimeout); this.requests.set(requestId, { type: RequestType.ALL_ROOMS, numSub, resolve, timeout, msgCount: 1, rooms: localRooms, }); this.pubClient.publish(this.requestChannel, request); }); } /** * Makes the socket with the given id join the room * * @param {String} id - socket id * @param {String} room - room name * @public */ public remoteJoin(id: SocketId, room: Room): Promise<void> { const requestId = uid2(6); const socket = this.nsp.sockets.get(id); if (socket) { socket.join(room); return Promise.resolve(); } const request = JSON.stringify({ requestId, type: RequestType.REMOTE_JOIN, sid: id, room, }); return new Promise((resolve, reject) => { const timeout = setTimeout(() => { if (this.requests.has(requestId)) { reject( new Error("timeout reached while waiting for remoteJoin response") ); this.requests.delete(requestId); } }, this.requestsTimeout); this.requests.set(requestId, { type: RequestType.REMOTE_JOIN, resolve, timeout, }); this.pubClient.publish(this.requestChannel, request); }); } /** * Makes the socket with the given id leave the room * * @param {String} id - socket id * @param {String} room - room name * @public */ public remoteLeave(id: SocketId, room: Room): Promise<void> { const requestId = uid2(6); const socket = this.nsp.sockets.get(id); if (socket) { socket.leave(room); return Promise.resolve(); } const request = JSON.stringify({ requestId, type: RequestType.REMOTE_LEAVE, sid: id, room, }); return new Promise((resolve, reject) => { const timeout = setTimeout(() => { if (this.requests.has(requestId)) { reject( new Error("timeout reached while waiting for remoteLeave response") ); this.requests.delete(requestId); } }, this.requestsTimeout); this.requests.set(requestId, { type: RequestType.REMOTE_LEAVE, resolve, timeout, }); this.pubClient.publish(this.requestChannel, request); }); } /** * Makes the socket with the given id to be forcefully disconnected * @param {String} id - socket id * @param {Boolean} close - if `true`, closes the underlying connection * * @public */ public remoteDisconnect(id: SocketId, close?: boolean): Promise<void> { const requestId = uid2(6); const socket = this.nsp.sockets.get(id); if (socket) { socket.disconnect(close); return Promise.resolve(); } const request = JSON.stringify({ requestId, type: RequestType.REMOTE_DISCONNECT, sid: id, close, }); return new Promise((resolve, reject) => { const timeout = setTimeout(() => { if (this.requests.has(requestId)) { reject( new Error( "timeout reached while waiting for remoteDisconnect response" ) ); this.requests.delete(requestId); } }, this.requestsTimeout); this.requests.set(requestId, { type: RequestType.REMOTE_DISCONNECT, resolve, timeout, }); this.pubClient.publish(this.requestChannel, request); }); } public async fetchSockets(opts: BroadcastOptions): Promise<any[]> { const localSockets = await super.fetchSockets(opts); if (opts.flags?.local) { return localSockets; } const numSub = await this.getNumSub(); debug('waiting for %d responses to "fetchSockets" request', numSub); if (numSub <= 1) { return localSockets; } const requestId = uid2(6); const request = JSON.stringify({ requestId, type: RequestType.REMOTE_FETCH, opts: { rooms: [...opts.rooms], except: [...opts.except], }, }); return new Promise((resolve, reject) => { const timeout = setTimeout(() => { if (this.requests.has(requestId)) { reject( new Error("timeout reached while waiting for fetchSockets response") ); this.requests.delete(requestId); } }, this.requestsTimeout); this.requests.set(requestId, { type: RequestType.REMOTE_FETCH, numSub, resolve, timeout, msgCount: 1, sockets: localSockets, }); this.pubClient.publish(this.requestChannel, request); }); } public addSockets(opts: BroadcastOptions, rooms: Room[]) { if (opts.flags?.local) { return super.addSockets(opts, rooms); } const request = JSON.stringify({ type: RequestType.REMOTE_JOIN, opts: { rooms: [...opts.rooms], except: [...opts.except], }, rooms: [...rooms], }); this.pubClient.publish(this.requestChannel, request); } public delSockets(opts: BroadcastOptions, rooms: Room[]) { if (opts.flags?.local) { return super.delSockets(opts, rooms); } const request = JSON.stringify({ type: RequestType.REMOTE_LEAVE, opts: { rooms: [...opts.rooms], except: [...opts.except], }, rooms: [...rooms], }); this.pubClient.publish(this.requestChannel, request); } public disconnectSockets(opts: BroadcastOptions, close: boolean) { if (opts.flags?.local) { return super.disconnectSockets(opts, close); } const request = JSON.stringify({ type: RequestType.REMOTE_DISCONNECT, opts: { rooms: [...opts.rooms], except: [...opts.except], }, close, }); this.pubClient.publish(this.requestChannel, request); } public serverSideEmit(packet: any[]): void { const withAck = typeof packet[packet.length - 1] === "function"; if (withAck) { this.serverSideEmitWithAck(packet).catch(() => { // ignore errors }); return; } const request = JSON.stringify({ uid: this.uid, type: RequestType.SERVER_SIDE_EMIT, data: packet, }); this.pubClient.publish(this.requestChannel, request); } private async serverSideEmitWithAck(packet: any[]) { const ack = packet.pop(); const numSub = (await this.getNumSub()) - 1; // ignore self debug('waiting for %d responses to "serverSideEmit" request', numSub); if (numSub <= 0) { return ack(null, []); } const requestId = uid2(6); const request = JSON.stringify({ uid: this.uid, requestId, // the presence of this attribute defines whether an acknowledgement is needed type: RequestType.SERVER_SIDE_EMIT, data: packet, }); const timeout = setTimeout(() => { const storedRequest = this.requests.get(requestId); if (storedRequest) { ack( new Error( `timeout reached: only ${storedRequest.responses.length} responses received out of ${storedRequest.numSub}` ), storedRequest.responses ); this.requests.delete(requestId); } }, this.requestsTimeout); this.requests.set(requestId, { type: RequestType.SERVER_SIDE_EMIT, numSub, timeout, resolve: ack, responses: [], }); this.pubClient.publish(this.requestChannel, request); } /** * Get the number of subscribers of the request channel * * @private */ private getNumSub(): Promise<number> { if (this.pubClient.constructor.name === "Cluster") { // Cluster const nodes = this.pubClient.nodes(); return Promise.all( nodes.map((node) => node.send_command("pubsub", ["numsub", this.requestChannel]) ) ).then((values) => { let numSub = 0; values.map((value) => { numSub += parseInt(value[1], 10); }); return numSub; }); } else { // RedisClient or Redis return new Promise((resolve, reject) => { this.pubClient.send_command( "pubsub", ["numsub", this.requestChannel], (err, numSub) => { if (err) return reject(err); resolve(parseInt(numSub[1], 10)); } ); }); } } }
the_stack
import { h, render } from 'preact'; import cx from 'classnames'; import type { RefinementListComponentCSSClasses } from '../../components/RefinementList/RefinementList'; import RefinementList from '../../components/RefinementList/RefinementList'; import type { RefinementListRenderState, RefinementListConnectorParams, RefinementListWidgetDescription, } from '../../connectors/refinement-list/connectRefinementList'; import connectRefinementList from '../../connectors/refinement-list/connectRefinementList'; import { prepareTemplateProps, getContainerNode, createDocumentationMessageGenerator, } from '../../lib/utils'; import { component } from '../../lib/suit'; import type { Template, WidgetFactory, Renderer } from '../../types'; import type { PreparedTemplateProps } from '../../lib/utils/prepareTemplateProps'; import searchBoxDefaultTemplates from '../search-box/defaultTemplates'; import type { SearchBoxTemplates } from '../search-box/search-box'; import type { SearchBoxComponentTemplates } from '../../components/SearchBox/SearchBox'; import defaultTemplates from './defaultTemplates'; const withUsage = createDocumentationMessageGenerator({ name: 'refinement-list', }); const suit = component('RefinementList'); const searchBoxSuit = component('SearchBox'); export type RefinementListOwnCSSClasses = Partial<{ /** * CSS class to add to the root element. */ root: string | string[]; /** * CSS class to add to the root element when no refinements. */ noRefinementRoot: string | string[]; /** * CSS class to add to the root element with no results. */ noResults: string | string[]; /** * CSS class to add to the list element. */ list: string | string[]; /** * CSS class to add to each item element. */ item: string | string[]; /** * CSS class to add to each selected element. */ selectedItem: string | string[]; /** * CSS class to add to each label element (when using the default template). */ label: string | string[]; /** * CSS class to add to each checkbox element (when using the default template). */ checkbox: string | string[]; /** * CSS class to add to each label text element. */ labelText: string | string[]; /** * CSS class to add to the show more element */ showMore: string | string[]; /** * CSS class to add to the disabled show more element */ disabledShowMore: string | string[]; /** * CSS class to add to each count element (when using the default template). */ count: string | string[]; /** * CSS class to add to the searchable container. */ searchBox: string | string[]; }>; type RefinementListSearchableCSSClasses = Partial<{ searchableRoot: string | string[]; searchableForm: string | string[]; searchableInput: string | string[]; searchableSubmit: string | string[]; searchableSubmitIcon: string | string[]; searchableReset: string | string[]; searchableResetIcon: string | string[]; searchableLoadingIndicator: string | string[]; searchableLoadingIcon: string | string[]; }>; export type RefinementListCSSClasses = RefinementListOwnCSSClasses & RefinementListSearchableCSSClasses; export type RefinementListItemData = { /** * The number of occurrences of the facet in the result set. */ count: number; /** * True if the value is selected. */ isRefined: boolean; /** * The label to display. */ label: string; /** * The value used for refining. */ value: string; /** * The label highlighted (when using search for facet values). This value is displayed in the default template. */ highlighted: string; /** * The url with this refinement selected. */ url: string; /** * Object containing all the classes computed for the item. */ cssClasses: RefinementListCSSClasses; }; export type RefinementListOwnTemplates = Partial<{ /** * Item template, provided with `label`, `highlighted`, `value`, `count`, `isRefined`, `url` data properties. */ item: Template<RefinementListItemData>; /** * Template used for the show more text, provided with `isShowingMore` data property. */ showMoreText: Template; /** * Templates to use for search for facet values when there are no results. */ searchableNoResults: Template; }>; type RefinementListSearchableTemplates = Partial<{ /** * Templates to use for search for facet values submit button. */ searchableSubmit: SearchBoxTemplates['submit']; /** * Templates to use for search for facet values reset button. */ searchableReset: SearchBoxTemplates['reset']; /** * Templates to use for the search for facet values loading indicator. */ searchableLoadingIndicator: SearchBoxTemplates['loadingIndicator']; }>; export type RefinementListTemplates = RefinementListOwnTemplates & RefinementListSearchableTemplates; export type RefinementListComponentTemplates = Required<RefinementListOwnTemplates>; export type RefinementListWidgetParams = { /** * CSS Selector or HTMLElement to insert the widget. */ container: string | HTMLElement; /** * Add a search input to let the user search for more facet values. In order * to make this feature work, you need to make the attribute searchable * [using the API](https://www.algolia.com/doc/guides/searching/faceting/?language=js#declaring-a-searchable-attribute-for-faceting) * or [the dashboard](https://www.algolia.com/explorer/display/) */ searchable?: boolean; /** * Value of the search field placeholder. */ searchablePlaceholder?: string; /** * When `false` the search field will become disabled if there are less items * to display than the `options.limit`, otherwise the search field is always usable. */ searchableIsAlwaysActive?: boolean; /** * When activated, it will escape the facet values that are returned from Algolia. * In this case, the surrounding tags will always be `<mark></mark>`. */ searchableEscapeFacetValues?: boolean; /** * Templates to use for the widget. */ templates?: RefinementListTemplates; /** * CSS classes to add to the wrapping elements. */ cssClasses?: RefinementListCSSClasses; }; const renderer = ({ containerNode, cssClasses, templates, searchBoxTemplates, renderState, showMore, searchable, searchablePlaceholder, searchableIsAlwaysActive, }: { containerNode: HTMLElement; cssClasses: RefinementListComponentCSSClasses; renderState: { templateProps?: PreparedTemplateProps<RefinementListComponentTemplates>; searchBoxTemplateProps?: PreparedTemplateProps<SearchBoxComponentTemplates>; }; templates: RefinementListOwnTemplates; searchBoxTemplates: SearchBoxTemplates; showMore?: boolean; searchable?: boolean; searchablePlaceholder?: string; searchableIsAlwaysActive?: boolean; }): Renderer<RefinementListRenderState, RefinementListConnectorParams> => ( { refine, items, createURL, searchForItems, isFromSearch, instantSearchInstance, toggleShowMore, isShowingMore, hasExhaustiveItems, canToggleShowMore, }, isFirstRendering ) => { if (isFirstRendering) { renderState.templateProps = prepareTemplateProps({ defaultTemplates, templatesConfig: instantSearchInstance.templatesConfig, templates, }); renderState.searchBoxTemplateProps = prepareTemplateProps({ defaultTemplates: searchBoxDefaultTemplates, templatesConfig: instantSearchInstance.templatesConfig, templates: searchBoxTemplates, }); return; } render( <RefinementList createURL={createURL} cssClasses={cssClasses} facetValues={items} templateProps={renderState.templateProps!} searchBoxTemplateProps={renderState.searchBoxTemplateProps} toggleRefinement={refine} searchFacetValues={searchable ? searchForItems : undefined} searchPlaceholder={searchablePlaceholder} searchIsAlwaysActive={searchableIsAlwaysActive} isFromSearch={isFromSearch} showMore={showMore && !isFromSearch && items.length > 0} toggleShowMore={toggleShowMore} isShowingMore={isShowingMore} hasExhaustiveItems={hasExhaustiveItems} canToggleShowMore={canToggleShowMore} />, containerNode ); }; export type RefinementListWidget = WidgetFactory< RefinementListWidgetDescription & { $$widgetType: 'ais.refinementList' }, RefinementListConnectorParams, RefinementListWidgetParams >; /** * The refinement list widget is one of the most common widget that you can find * in a search UI. With this widget, the user can filter the dataset based on facets. * * The refinement list displays only the most relevant facets for the current search * context. The sort option only affects the facet that are returned by the engine, * not which facets are returned. * * This widget also implements search for facet values, which is a mini search inside the * values of the facets. This makes easy to deal with uncommon facet values. * * @requirements * * The attribute passed to `attribute` must be declared as an * [attribute for faceting](https://www.algolia.com/doc/guides/searching/faceting/#declaring-attributes-for-faceting) * in your Algolia settings. * * If you also want to use search for facet values on this attribute, you need to make it searchable using the [dashboard](https://www.algolia.com/explorer/display/) or using the [API](https://www.algolia.com/doc/guides/searching/faceting/#search-for-facet-values). */ const refinementList: RefinementListWidget = function refinementList( widgetParams ) { const { container, attribute, operator, sortBy, limit, showMore, showMoreLimit, searchable = false, searchablePlaceholder = 'Search...', searchableEscapeFacetValues = true, searchableIsAlwaysActive = true, cssClasses: userCssClasses = {}, templates = {}, transformItems, } = widgetParams || {}; if (!container) { throw new Error(withUsage('The `container` option is required.')); } const escapeFacetValues = searchable ? Boolean(searchableEscapeFacetValues) : false; const containerNode = getContainerNode(container); const cssClasses = { root: cx(suit(), userCssClasses.root), noRefinementRoot: cx( suit({ modifierName: 'noRefinement' }), userCssClasses.noRefinementRoot ), list: cx(suit({ descendantName: 'list' }), userCssClasses.list), item: cx(suit({ descendantName: 'item' }), userCssClasses.item), selectedItem: cx( suit({ descendantName: 'item', modifierName: 'selected' }), userCssClasses.selectedItem ), searchBox: cx( suit({ descendantName: 'searchBox' }), userCssClasses.searchBox ), label: cx(suit({ descendantName: 'label' }), userCssClasses.label), checkbox: cx(suit({ descendantName: 'checkbox' }), userCssClasses.checkbox), labelText: cx( suit({ descendantName: 'labelText' }), userCssClasses.labelText ), count: cx(suit({ descendantName: 'count' }), userCssClasses.count), noResults: cx( suit({ descendantName: 'noResults' }), userCssClasses.noResults ), showMore: cx(suit({ descendantName: 'showMore' }), userCssClasses.showMore), disabledShowMore: cx( suit({ descendantName: 'showMore', modifierName: 'disabled' }), userCssClasses.disabledShowMore ), searchable: { root: cx(searchBoxSuit(), userCssClasses.searchableRoot), form: cx( searchBoxSuit({ descendantName: 'form' }), userCssClasses.searchableForm ), input: cx( searchBoxSuit({ descendantName: 'input' }), userCssClasses.searchableInput ), submit: cx( searchBoxSuit({ descendantName: 'submit' }), userCssClasses.searchableSubmit ), submitIcon: cx( searchBoxSuit({ descendantName: 'submitIcon' }), userCssClasses.searchableSubmitIcon ), reset: cx( searchBoxSuit({ descendantName: 'reset' }), userCssClasses.searchableReset ), resetIcon: cx( searchBoxSuit({ descendantName: 'resetIcon' }), userCssClasses.searchableResetIcon ), loadingIndicator: cx( searchBoxSuit({ descendantName: 'loadingIndicator' }), userCssClasses.searchableLoadingIndicator ), loadingIcon: cx( searchBoxSuit({ descendantName: 'loadingIcon' }), userCssClasses.searchableLoadingIcon ), }, }; const specializedRenderer = renderer({ containerNode, cssClasses, templates, searchBoxTemplates: { submit: templates.searchableSubmit, reset: templates.searchableReset, loadingIndicator: templates.searchableLoadingIndicator, }, renderState: {}, searchable, searchablePlaceholder, searchableIsAlwaysActive, showMore, }); const makeWidget = connectRefinementList(specializedRenderer, () => render(null, containerNode) ); return { ...makeWidget({ attribute, operator, limit, showMore, showMoreLimit, sortBy, escapeFacetValues, transformItems, }), $$widgetType: 'ais.refinementList', }; }; export default refinementList;
the_stack
import * as assert from "assert"; import { testContext, disposeTestDocumentStore } from "../../Utils/TestUtil"; import { RavenErrorType, IDocumentStore, GetCountersOperation, CreateDatabaseOperation, DeleteDatabasesOperation, IDocumentSession, DocumentCountersOperation, CounterOperation, CounterBatch, CounterBatchOperation, } from "../../../src"; import { User, Company, Order, Employee } from "../../Assets/Entities"; import { assertThat } from "../../Utils/AssertExtensions"; describe("SessionCountersTest", function () { let store: IDocumentStore; beforeEach(async function () { store = await testContext.getDocumentStore(); }); afterEach(async () => await disposeTestDocumentStore(store)); it("sessionIncrementCounter", async () => { { const session = store.openSession(); await session.store(Object.assign(new User(), { name: "Aviv1" }), "users/1-A"); await session.store(Object.assign(new User(), { name: "Aviv2" }), "users/2-A"); await session.saveChanges(); } { const session = store.openSession(); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("downloads", 500); session.countersFor("users/2-A").increment("votes", 1000); await session.saveChanges(); } { let counters = (await store.operations.send( new GetCountersOperation("users/1-A", ["likes", "downloads"]))).counters; assert.strictEqual(counters.length, 2); assert.strictEqual( counters.filter(x => x.counterName === "likes")[0].totalValue, 100); assert.strictEqual( counters.filter(x => x.counterName === "downloads")[0].totalValue, 500); counters = (await store.operations.send(new GetCountersOperation("users/2-A", ["votes"]))).counters; assert.strictEqual(counters.length, 1); assert.strictEqual( counters.filter(x => x.counterName === "votes")[0].totalValue, 1000); } }); it("sessionDeleteCounter", async function () { { const session = store.openSession(); await session.store(Object.assign(new User(), { name: "Aviv1" }), "users/1-A"); await session.store(Object.assign(new User(), { name: "Aviv2" }), "users/2-A"); await session.saveChanges(); } { const session = store.openSession(); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("downloads", 500); session.countersFor("users/2-A").increment("votes", 1000); await session.saveChanges(); } let { counters } = (await store.operations .send(new GetCountersOperation("users/1-A", ["likes", "downloads"]))); assert.strictEqual(counters.length, 2); { const session = store.openSession(); session.countersFor("users/1-A").delete("likes"); session.countersFor("users/1-A").delete("downloads"); session.countersFor("users/2-A").delete("votes"); await session.saveChanges(); } counters = (await store.operations .send(new GetCountersOperation("users/1-A", ["likes", "downloads"]))) .counters; assertThat(counters) .hasSize(2); assertThat(counters[0]) .isNull(); assertThat(counters[1]) .isNull(); counters = (await store.operations.send(new GetCountersOperation("users/2-A", "votes"))) .counters; assertThat(counters) .hasSize(1); assertThat(counters[0]) .isNull(); }); it("sessionGetCounters", async function () { { const session = store.openSession(); await session.store(Object.assign(new User(), { name: "Aviv1" }), "users/1-A"); await session.store(Object.assign(new User(), { name: "Aviv2" }), "users/2-A"); await session.saveChanges(); } { const session = store.openSession(); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("downloads", 500); session.countersFor("users/2-A").increment("votes", 1000); await session.saveChanges(); } { const session = store.openSession(); const dic = await session.countersFor("users/1-A").getAll(); assert.strictEqual(Object.keys(dic).length, 2); assert.strictEqual(dic["likes"], 100); assert.strictEqual(dic["downloads"], 500); const c = await session.countersFor("users/2-A").get("votes"); assert.strictEqual(c, 1000); } { const session = store.openSession(); const dic = await session.countersFor("users/1-A").get(["likes", "downloads"]); assert.strictEqual(Object.keys(dic).length, 2); assert.strictEqual(dic["likes"], 100); assert.strictEqual(dic["downloads"], 500); } { const session = store.openSession(); const dic = await session.countersFor("users/1-A").get(["likes"]); assert.strictEqual(Object.keys(dic).length, 1); assert.strictEqual(dic["likes"], 100); } }); it("sessionGetCountersWithNonDefaultDatabase", async function () { const dbName = "db-" + (Math.random() * 1000 + 1).toFixed(2); await store.maintenance.server.send( new CreateDatabaseOperation({ databaseName: dbName })); try { { const session = store.openSession(dbName); await session.store(Object.assign(new User(), { name: "Aviv1" }), "users/1-A"); await session.store(Object.assign(new User(), { name: "Aviv2" }), "users/2-A"); await session.saveChanges(); } { const session = store.openSession(dbName); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("downloads", 500); session.countersFor("users/2-A").increment("votes", 1000); await session.saveChanges(); } { const session = store.openSession(dbName); const dic = await session.countersFor("users/1-A").getAll(); assert.strictEqual(Object.keys(dic).length, 2); assert.strictEqual(dic["likes"], 100); assert.strictEqual(dic["downloads"], 500); const c = await session.countersFor("users/2-A").get("votes"); assert.strictEqual(c, 1000); } } finally { await store.maintenance.server.send( new DeleteDatabasesOperation({ databaseNames: [ dbName], hardDelete: true })); } }); it("getCountersFor", async function() { { const session = store.openSession(); for (const n of [1, 2, 3]) { await storeDoc(session, `users/${n}-A`, { name: `Aviv${n}` }, User); } await session.saveChanges(); } { const session = store.openSession(); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("downloads", 100); session.countersFor("users/2-A").increment("votes", 100); await session.saveChanges(); } { const session = store.openSession(); let user = await session.load<User>("users/1-A"); let counters = session.advanced.getCountersFor(user); assert.strictEqual(counters.length, 2); assert.ok(counters.includes("downloads")); assert.ok(counters.includes("likes")); user = await session.load<User>("users/2-A"); counters = session.advanced.getCountersFor(user); assert.strictEqual(counters.length, 1); assert.ok(counters.includes("votes")); user = await session.load<User>("users/3-A"); counters = session.advanced.getCountersFor(user); assert.strictEqual(counters, null); } }); it("differentTypesOfCountersOperationsInOneSession", async function () { { const session = store.openSession(); for (const n of [ 1, 2 ]) { await storeDoc(session, `users/${n}-A`, { name: `Aviv${n}` }, User); } await session.saveChanges(); } { const session = store.openSession(); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("downloads", 100); session.countersFor("users/2-A").increment("votes", 1000); await session.saveChanges(); } { const session = store.openSession(); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").delete("downloads"); session.countersFor("users/2-A").increment("votes", -600); await session.saveChanges(); } { const session = store.openSession(); let val = await session.countersFor("users/1-A").get("likes"); assertThat(val) .isEqualTo(200); val = await session.countersFor("users/1-A").get("downloads"); assertThat(val) .isNull(); val = await session.countersFor("users/2-A").get("votes"); assertThat(val) .isEqualTo(400); } }); it("shouldThrow", async function () { { const session = store.openSession(); for (const n of [ 1 ]) { await storeDoc(session, `users/${n}-A`, { name: `Aviv${n}` }, User); } await session.saveChanges(); } { const session = store.openSession(); const user = await session.load("users/1-A"); session.countersFor(user).increment("likes", 100); await session.saveChanges(); assertThat(await session.countersFor(user).get("likes")) .isEqualTo(100); } }); it("sessionShouldTrackCounters", async function () { { const session = store.openSession(); for (const n of [ 1 ]) { await storeDoc(session, `users/${n}-A`, { name: `Aviv${n}` }, User); } session.countersFor("users/1-A").increment("likes", 100); await session.saveChanges(); } { const session = store.openSession(); assertThat(session.advanced.numberOfRequests) .isZero(); const val = await session.countersFor("users/1-A").get("likes"); assertThat(val) .isEqualTo(100); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); session.countersFor("users/1-A").get("likes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); } }); it("sessionShouldKeepNullsInCountersCache", async function () { { const session = store.openSession(); for (const n of [1]) { await storeDoc(session, `users/${n}-A`, { name: `Aviv${n}` }, User); } session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); session.countersFor("users/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); let val = await session.countersFor("users/1-A").get("score"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); assertThat(val) .isNull(); val = await session.countersFor("users/1-A").get("score"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); assertThat(val) .isNull(); const dic = await session.countersFor("users/1-A").getAll(); // should not contain null value for "score" assertThat(session.advanced.numberOfRequests).isEqualTo(2); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); } }); it("sessionShouldKnowWhenItHasAllCountersInCacheAndAvoidTripToServer_WhenUsingEntity", async function () { { const session = store.openSession(); for (const n of [1]) { await storeDoc(session, `users/${n}-A`, { name: `Aviv${n}` }, User); } session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); session.countersFor("users/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const user = await session.load("users/1-A"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); const userCounters = session.countersFor(user); let val = await userCounters.get("likes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); assertThat(val) .isEqualTo(100); val = await userCounters.get("dislikes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); assertThat(val) .isEqualTo(200); val = await userCounters.get("downloads"); // session should know at this point that it has all counters assertThat(session.advanced.numberOfRequests) .isEqualTo(4); assertThat(val) .isEqualTo(300); const dic = await userCounters.getAll(); // should not go to server assertThat(session.advanced.numberOfRequests) .isEqualTo(4); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); val = await userCounters.get("score"); //should not go to server assertThat(session.advanced.numberOfRequests) .isEqualTo(4); assertThat(val) .isNull(); } }); it("sessionShouldUpdateMissingCountersInCacheAndRemoveDeletedCounters_AfterRefresh", async function () { { const session = store.openSession(); for (const n of [1]) { await storeDoc(session, `users/${n}-A`, { name: `Aviv${n}` }, User); } session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); session.countersFor("users/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const user = await session.load("users/1-A"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); const userCounters = session.countersFor(user); let dic = await userCounters.getAll(); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); { const session2 = store.openSession(); session2.countersFor("users/1-A").increment("likes"); session2.countersFor("users/1-A").delete("dislikes"); session2.countersFor("users/1-A").increment("score", 1000); // new counter await session2.saveChanges(); } await session.advanced.refresh(user); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); // Refresh updated the document in session, // cache should know that it's missing 'score' by looking // at the document's metadata and go to server again to get all. // this should override the cache entirely and therefor // 'dislikes' won't be in cache anymore dic = await userCounters.getAll(); assertThat(session.advanced.numberOfRequests) .isEqualTo(4); assertThat(dic) .hasSize(3) .containsEntry("likes", 101) .containsEntry("downloads", 300) .containsEntry("score", 1000); // cache should know that it got all and not go to server, // and it shouldn't have 'dislikes' entry anymore const val = await userCounters.get("dislikes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(4); assertThat(val) .isNull(); } }); it("sessionShouldUpdateMissingCountersInCacheAndRemoveDeletedCounters_AfterLoadFromServer", async function () { { const session = store.openSession(); await storeDoc(session, `users/${1}-A`, { name: `Aviv${1}` }, User); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); session.countersFor("users/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const userCounters = session.countersFor("users/1-A"); let dic = await userCounters.getAll(); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); { const session2 = store.openSession(); session2.countersFor("users/1-A").increment("likes"); session2.countersFor("users/1-A").delete("dislikes"); session2.countersFor("users/1-A").increment("score", 1000); // new counter await session2.saveChanges(); } const user = await session.load("users/1-A"); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); // Refresh updated the document in session, // cache should know that it's missing 'score' by looking // at the document's metadata and go to server again to get all. // this should override the cache entirely and therefor // 'dislikes' won't be in cache anymore dic = await userCounters.getAll(); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); assertThat(dic) .hasSize(3) .containsEntry("likes", 101) .containsEntry("downloads", 300) .containsEntry("score", 1000); // cache should know that it got all and not go to server, // and it shouldn't have 'dislikes' entry anymore const val = await userCounters.get("dislikes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); assertThat(val) .isNull(); } }); it("sessionClearShouldClearCountersCache", async function () { { const session = store.openSession(); await storeDoc(session, `users/${1}-A`, { name: `Aviv${1}` }, User); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); session.countersFor("users/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const userCounters = session.countersFor("users/1-A"); let dic = await userCounters.getAll(); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); { const session2 = store.openSession(); session2.countersFor("users/1-A").increment("likes"); session2.countersFor("users/1-A").delete("dislikes"); session2.countersFor("users/1-A").increment("score", 1000); // new counter await session2.saveChanges(); } session.advanced.clear(); // should clear countersCache dic = await userCounters.getAll(); // should go to server again assertThat(session.advanced.numberOfRequests) .isEqualTo(2); assertThat(dic) .hasSize(3) .containsEntry("likes", 101) .containsEntry("downloads", 300) .containsEntry("score", 1000); } }); it("sessionEvictShouldRemoveEntryFromCountersCache", async function () { { const session = store.openSession(); await storeDoc(session, `users/${1}-A`, { name: `Aviv${1}` }, User); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); session.countersFor("users/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const user = await session.load("users/1-A"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); const userCounters = session.countersFor("users/1-A"); let dic = await userCounters.getAll(); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); { const session2 = store.openSession(); session2.countersFor("users/1-A").increment("likes"); session2.countersFor("users/1-A").delete("dislikes"); session2.countersFor("users/1-A").increment("score", 1000); // new counter await session2.saveChanges(); } session.advanced.evict(user); // should remove 'users/1-A' entry from CountersByDocId dic = await userCounters.getAll(); // should go to server again assertThat(session.advanced.numberOfRequests) .isEqualTo(3); assertThat(dic) .hasSize(3) .containsEntry("likes", 101) .containsEntry("downloads", 300) .containsEntry("score", 1000); } }); it("sessionShouldAlwaysLoadCountersFromCacheAfterGetAll", async function () { { const session = store.openSession(); await storeDoc(session, `users/${1}-A`, { name: `Aviv${1}` }, User); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); session.countersFor("users/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const dic = await session.countersFor("users/1-A").getAll(); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); //should not go to server after GetAll() request let val = await session.countersFor("users/1-A").get("likes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); assertThat(val) .isEqualTo(100); val = await session.countersFor("users/1-A").get("votes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); assertThat(val) .isNull(); } }); it("sessionShouldOverrideExistingCounterValuesInCacheAfterGetAll", async function () { { const session = store.openSession(); await storeDoc(session, `users/${1}-A`, { name: `Aviv${1}` }, User); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); session.countersFor("users/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); let val = await session.countersFor("users/1-A").get("likes"); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); assertThat(val) .isEqualTo(100); val = await session.countersFor("users/1-A").get("score"); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); assertThat(val) .isNull(); const operation = new DocumentCountersOperation(); operation.documentId = "users/1-A"; operation.operations = [CounterOperation.create("likes", "Increment", 400)]; const counterBatch = new CounterBatch(); counterBatch.documents = [operation]; await store.operations.send(new CounterBatchOperation(counterBatch)); const dic = await session.countersFor("users/1-A").getAll(); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); assertThat(dic) .hasSize(3) .containsEntry("dislikes", 200) .containsEntry("downloads", 300) .containsEntry("likes", 500); val = await session.countersFor("users/1-A").get("score"); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); // null values should still be in cache assertThat(val) .isNull(); } }); it("sessionIncrementCounterShouldUpdateCounterValueAfterSaveChanges", async function () { { const session = store.openSession(); await storeDoc(session, `users/1-A`, { name: `Aviv1` }, User); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 300); await session.saveChanges(); } { const session = store.openSession(); let val = await session.countersFor("users/1-A").get("likes"); assertThat(val) .isEqualTo(100); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); session.countersFor("users/1-A").increment("likes", 50); // should not increment the counter value in cache val = await session.countersFor("users/1-A").get("likes"); assertThat(val) .isEqualTo(100); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); session.countersFor("users/1-A").increment("dislikes", 200); // should not add the counter to cache val = await session.countersFor("users/1-A").get("dislikes"); // should go to server assertThat(val) .isEqualTo(300); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); session.countersFor("users/1-A").increment("score", 1000); // should not add the counter to cache assertThat(session.advanced.numberOfRequests) .isEqualTo(2); // SaveChanges should updated counters values in cache // according to increment result await session.saveChanges(); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); // should not go to server for these val = await session.countersFor("users/1-A").get("likes"); assertThat(val) .isEqualTo(150); val = await session.countersFor("users/1-A").get("dislikes"); assertThat(val) .isEqualTo(500); val = await session.countersFor("users/1-A").get("score"); assertThat(val) .isEqualTo(1000); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); } }); it("sessionShouldRemoveCounterFromCacheAfterCounterDeletion", async function () { { const session = store.openSession(); await storeDoc(session, `users/1-A`, { name: `Aviv1` }, User); session.countersFor("users/1-A").increment("likes", 100); await session.saveChanges(); } { const session = store.openSession(); let val = await session.countersFor("users/1-A").get("likes"); assertThat(val) .isEqualTo(100); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); session.countersFor("users/1-A").delete("likes"); await session.saveChanges(); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); val = await session.countersFor("users/1-A").get("likes"); assertThat(val) .isNull(); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); } }); it("sessionShouldRemoveCountersFromCacheAfterDocumentDeletion", async function () { { const session = store.openSession(); await storeDoc(session, `users/1-A`, { name: `Aviv1` }, User); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); await session.saveChanges(); } { const session = store.openSession(); const dic = await session.countersFor("users/1-A").get(["likes", "dislikes"]); assertThat(dic) .hasSize(2) .containsEntry("likes", 100) .containsEntry("dislikes", 200); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); session.delete("users/1-A"); await session.saveChanges(); assertThat(session.advanced.numberOfRequests) .isEqualTo(2); const val = await session.countersFor("users/1-A").get("likes"); assertThat(val) .isNull(); assertThat(session.advanced.numberOfRequests) .isEqualTo(3); } }); it("sessionIncludeSingleCounter", async function () { { const session = store.openSession(); await storeDoc(session, `users/1-A`, { name: `Aviv1` }, User); session.countersFor("users/1-A").increment("likes", 100); session.countersFor("users/1-A").increment("dislikes", 200); await session.saveChanges(); } { const session = store.openSession(); const user = await session.load("users/1-A", { includes: i => i.includeCounter("likes") }); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); const counter = await session.countersFor(user).get("likes"); assertThat(counter) .isEqualTo(100); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); } }); it("sessionChainedIncludeCounter", async function () { { const session = store.openSession(); await storeDoc(session, `companies/1-A`, { name: `HR` }, Company); await storeDoc(session, `orders/1-A`, { company: "companies/1-A" }, Order); session.countersFor("orders/1-A").increment("likes", 100); session.countersFor("orders/1-A").increment("dislikes", 200); await session.saveChanges(); } { const session = store.openSession(); const order = await session.load( "orders/1-A", { includes: i => i.includeCounter("likes") .includeCounter("dislikes") }); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); let counter = await session.countersFor(order).get("likes"); assertThat(counter) .isEqualTo(100); counter = await session.countersFor(order).get("dislikes"); assertThat(counter) .isEqualTo(200); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); } }); it("sessionChainedIncludeAndIncludeCounter", async function () { { const session = store.openSession(); await storeDoc(session, "companies/1-A", { name: "HR" }, Company); await storeDoc(session, "employees/1-A", { firstName: "Aviv" }, Employee); await storeDoc(session, "orders/1-A", { company: "companies/1-A", employee: "employees/1-A" }, Order); session.countersFor("orders/1-A").increment("likes", 100); session.countersFor("orders/1-A").increment("dislikes", 200); session.countersFor("orders/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const order = await session.load<Order>("orders/1-A", { includes: i => i.includeCounter("likes") .includeDocuments("company") .includeCounter("dislikes") .includeCounter("downloads") .includeDocuments("employee") }); const company = await session.load(order.company); assertThat(company["name"]) .isEqualTo("HR"); const employee = await session.load(order.employee); assertThat(employee["firstName"]) .isEqualTo("Aviv"); const dic = await session.countersFor(order).getAll(); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); } }); it("sessionIncludeCounters", async function () { { const session = store.openSession(); await storeDoc(session, "companies/1-A", { name: "HR" }, Company); await storeDoc(session, "orders/1-A", { company: "companies/1-A" }, Order); session.countersFor("orders/1-A").increment("likes", 100); session.countersFor("orders/1-A").increment("dislikes", 200); await session.saveChanges(); } { const session = store.openSession(); const order = await session.load<Order>( "orders/1-A", { includes: i => i .includeDocuments("company") .includeCounters([ "likes", "dislikes"]) }); const company = await session.load<Company>(order.company); assertThat(company.name) .isEqualTo("HR"); const dic = await session.countersFor(order).getAll(); assertThat(dic) .hasSize(2) .containsEntry("likes", 100) .containsEntry("dislikes", 200); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); } }); it("sessionIncludeAllCounters", async function () { { const session = store.openSession(); await storeDoc(session, "companies/1-A", { name: "HR" }, Company); await storeDoc(session, "orders/1-A", { company: "companies/1-A", }, Order); session.countersFor("orders/1-A").increment("likes", 100); session.countersFor("orders/1-A").increment("dislikes", 200); session.countersFor("orders/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const order = await session.load<Order>("orders/1-A", { includes: i => i .includeDocuments("company") .includeAllCounters() }); const company = await session.load<Company>(order.company); assertThat(company.name) .isEqualTo("HR"); const dic = await session.countersFor(order).getAll(); assertThat(dic) .hasSize(3) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); } }); it("sessionIncludeSingleCounterAfterIncludeAllCountersShouldThrow", async function () { { const session = store.openSession(); await storeDoc(session, "companies/1-A", { name: "HR" }, Company); await storeDoc(session, "orders/1-A", { company: "companies/1-A", }, Order); session.countersFor("orders/1-A").increment("likes", 100); session.countersFor("orders/1-A").increment("dislikes", 200); session.countersFor("orders/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); try { await session.load("orders/1-A", { includes: i => i .includeDocuments("company") .includeAllCounters() .includeCounter("likes") }); assert.fail("should have thrown"); } catch (err) { assert.strictEqual(err.name, "InvalidOperationException" as RavenErrorType); } } }); it("sessionIncludeAllCountersAfterIncludeSingleCounterShouldThrow", async function () { { const session = store.openSession(); await storeDoc(session, "companies/1-A", { name: "HR" }, Company); await storeDoc(session, "orders/1-A", { company: "companies/1-A", }, Order); session.countersFor("orders/1-A").increment("likes", 100); session.countersFor("orders/1-A").increment("dislikes", 200); session.countersFor("orders/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); try { await session.load("orders/1-A", { includes: i => i .includeDocuments("company") .includeCounter("likes") .includeAllCounters() }); assert.fail("should have thrown"); } catch (err) { assert.strictEqual(err.name, "InvalidOperationException" as RavenErrorType); } } }); it("sessionIncludeCountersShouldRegisterMissingCounters", async function () { { const session = store.openSession(); await storeDoc(session, "companies/1-A", { name: "HR" }, Company); await storeDoc(session, "orders/1-A", { company: "companies/1-A", }, Order); session.countersFor("orders/1-A").increment("likes", 100); session.countersFor("orders/1-A").increment("dislikes", 200); session.countersFor("orders/1-A").increment("downloads", 300); await session.saveChanges(); } { const session = store.openSession(); const order = await session.load<Order>("orders/1-A", { includes: i => i.includeDocuments("company") .includeCounters([ "likes", "downloads", "dances"]) .includeCounter("dislikes") .includeCounter("cats") }); const company = await session.load<Company>(order.company); assertThat(company.name) .isEqualTo("HR"); // should not go to server const dic = await session.countersFor(order).getAll(); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); assertThat(dic) .hasSize(5) .containsEntry("likes", 100) .containsEntry("dislikes", 200) .containsEntry("downloads", 300); //missing counters should be in cache assertThat(dic["dances"]) .isNull(); assertThat(dic["cats"]) .isNull(); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); } }); it("sessionIncludeCountersMultipleLoads", async function () { { const session = store.openSession(); await storeDoc(session, "companies/1-A", { name: "HR" }, Company); await storeDoc(session, "orders/1-A", { company: "companies/1-A", }, Order); await storeDoc(session, "companies/2-A", { name: "HP" }, Company); await storeDoc(session, "orders/2-A", { company: "companies/2-A", }, Order); session.countersFor("orders/1-A").increment("likes", 100); session.countersFor("orders/1-A").increment("dislikes", 200); session.countersFor("orders/2-A").increment("score", 300); session.countersFor("orders/2-A").increment("downloads", 400); await session.saveChanges(); } { const session = store.openSession(); const orders = await session.load<Order>( ["orders/1-A", "orders/2-A"], { includes: i => i .includeDocuments("company") .includeAllCounters() }); let order = orders["orders/1-A"]; let company = await session.load<Company>(order.company); assertThat(company.name) .isEqualTo("HR"); let dic = await session.countersFor(order).getAll(); assertThat(dic) .hasSize(2) .containsEntry("likes", 100) .containsEntry("dislikes", 200); order = orders["orders/2-A"]; company = await session.load<Company>(order.company); assertThat(company.name) .isEqualTo("HP"); dic = await session.countersFor(order).getAll(); assertThat(dic) .hasSize(2) .containsEntry("score", 300) .containsEntry("downloads", 400); assertThat(session.advanced.numberOfRequests) .isEqualTo(1); } }); }); async function storeDoc(session: IDocumentSession, id: string, data: any, clazz: any) { await session.store( Object.assign(new clazz(), data), id); }
the_stack
import { Events, Segment, LoaderInterface, XhrSetupCallback } from "p2p-media-loader-core"; import { Manifest, Parser } from "m3u8-parser"; import { AssetsStorage } from "./engine"; const defaultSettings: SegmentManagerSettings = { forwardSegmentCount: 20, swarmId: undefined, assetsStorage: undefined, }; export type ByteRange = { length: number; offset: number } | undefined; export class SegmentManager { private readonly loader: LoaderInterface; private masterPlaylist: Playlist | null = null; private readonly variantPlaylists = new Map<string, Playlist>(); private segmentRequest: SegmentRequest | null = null; private playQueue: { segmentSequence: number; segmentUrl: string; segmentByteRange: ByteRange; playPosition?: { start: number; duration: number; }; }[] = []; private readonly settings: SegmentManagerSettings; public constructor(loader: LoaderInterface, settings: Partial<SegmentManagerSettings> = {}) { this.settings = { ...defaultSettings, ...settings }; this.loader = loader; this.loader.on(Events.SegmentLoaded, this.onSegmentLoaded); this.loader.on(Events.SegmentError, this.onSegmentError); this.loader.on(Events.SegmentAbort, this.onSegmentAbort); } public getSettings(): SegmentManagerSettings { return this.settings; } public processPlaylist(requestUrl: string, content: string, responseUrl: string): void { const parser = new Parser(); parser.push(content); parser.end(); const playlist = new Playlist(requestUrl, responseUrl, parser.manifest); if (playlist.manifest.playlists) { this.masterPlaylist = playlist; for (const [key, variantPlaylist] of this.variantPlaylists) { const { streamSwarmId, found, index } = this.getStreamSwarmId(variantPlaylist.requestUrl); if (!found) { this.variantPlaylists.delete(key); } else { variantPlaylist.streamSwarmId = streamSwarmId; variantPlaylist.streamId = "V" + index.toString(); } } } else { const { streamSwarmId, found, index } = this.getStreamSwarmId(requestUrl); if (found || this.masterPlaylist === null) { // do not add audio and subtitles to variants playlist.streamSwarmId = streamSwarmId; playlist.streamId = this.masterPlaylist === null ? undefined : "V" + index.toString(); this.variantPlaylists.set(requestUrl, playlist); this.updateSegments(); } } } public async loadPlaylist(url: string): Promise<{ response: string; responseURL: string }> { const assetsStorage = this.settings.assetsStorage; let xhr: { response: string; responseURL: string } | undefined; if (assetsStorage !== undefined) { let masterSwarmId: string | undefined; masterSwarmId = this.getMasterSwarmId(); if (masterSwarmId === undefined) { masterSwarmId = url.split("?")[0]; } const asset = await assetsStorage.getAsset(url, undefined, masterSwarmId); if (asset !== undefined) { xhr = { responseURL: asset.responseUri, response: asset.data as string, }; } else { xhr = await this.loadContent(url, "text"); void assetsStorage.storeAsset({ masterManifestUri: this.masterPlaylist !== null ? this.masterPlaylist.requestUrl : url, masterSwarmId: masterSwarmId, requestUri: url, responseUri: xhr.responseURL, data: xhr.response, }); } } else { xhr = await this.loadContent(url, "text"); } this.processPlaylist(url, xhr.response, xhr.responseURL); return xhr; } public async loadSegment( url: string, byteRange: ByteRange ): Promise<{ content: ArrayBuffer | undefined; downloadBandwidth?: number }> { const segmentLocation = this.getSegmentLocation(url, byteRange); const byteRangeString = byteRangeToString(byteRange); if (!segmentLocation) { let content: ArrayBuffer | undefined; // Not a segment from variants; usually can be: init, audio or subtitles segment, encription key etc. const assetsStorage = this.settings.assetsStorage; if (assetsStorage !== undefined) { let masterManifestUri = this.masterPlaylist?.requestUrl; let masterSwarmId: string | undefined; masterSwarmId = this.getMasterSwarmId(); if (masterSwarmId === undefined && this.variantPlaylists.size === 1) { const result = this.variantPlaylists.values().next(); if (!result.done) { // always true masterSwarmId = result.value.requestUrl.split("?")[0]; } } if (masterManifestUri === undefined && this.variantPlaylists.size === 1) { const result = this.variantPlaylists.values().next(); if (!result.done) { // always true masterManifestUri = result.value.requestUrl; } } if (masterSwarmId !== undefined && masterManifestUri !== undefined) { const asset = await assetsStorage.getAsset(url, byteRangeString, masterSwarmId); if (asset !== undefined) { content = asset.data as ArrayBuffer; } else { const xhr = await this.loadContent(url, "arraybuffer", byteRangeString); content = xhr.response as ArrayBuffer; void assetsStorage.storeAsset({ masterManifestUri: masterManifestUri, masterSwarmId: masterSwarmId, requestUri: url, requestRange: byteRangeString, responseUri: xhr.responseURL, data: content, }); } } } if (content === undefined) { const xhr = await this.loadContent(url, "arraybuffer", byteRangeString); content = xhr.response as ArrayBuffer; } return { content, downloadBandwidth: 0 }; } const segmentSequence = (segmentLocation.playlist.manifest.mediaSequence ? segmentLocation.playlist.manifest.mediaSequence : 0) + segmentLocation.segmentIndex; if (this.playQueue.length > 0) { const previousSegment = this.playQueue[this.playQueue.length - 1]; if (previousSegment.segmentSequence !== segmentSequence - 1) { // Reset play queue in case of segment loading out of sequence this.playQueue = []; } } if (this.segmentRequest) { this.segmentRequest.onError("Cancel segment request: simultaneous segment requests are not supported"); } const promise = new Promise<{ content: ArrayBuffer | undefined; downloadBandwidth?: number }>( (resolve, reject) => { this.segmentRequest = new SegmentRequest( url, byteRange, segmentSequence, segmentLocation.playlist.requestUrl, (content: ArrayBuffer | undefined, downloadBandwidth?: number) => resolve({ content, downloadBandwidth }), (error) => reject(error) ); } ); this.playQueue.push({ segmentUrl: url, segmentByteRange: byteRange, segmentSequence: segmentSequence }); void this.loadSegments(segmentLocation.playlist, segmentLocation.segmentIndex, true); return promise; } public setPlayingSegment(url: string, byteRange: ByteRange, start: number, duration: number): void { const urlIndex = this.playQueue.findIndex( (segment) => segment.segmentUrl === url && compareByteRanges(segment.segmentByteRange, byteRange) ); if (urlIndex >= 0) { this.playQueue = this.playQueue.slice(urlIndex); this.playQueue[0].playPosition = { start, duration }; this.updateSegments(); } } public setPlayingSegmentByCurrentTime(playheadPosition: number): void { if (this.playQueue.length === 0 || !this.playQueue[0].playPosition) { return; } const currentSegmentPosition = this.playQueue[0].playPosition; const segmentEndTime = currentSegmentPosition.start + currentSegmentPosition.duration; if (segmentEndTime - playheadPosition < 0.2) { // means that current segment is (almost) finished playing // remove it from queue this.playQueue = this.playQueue.slice(1); this.updateSegments(); } } public abortSegment(url: string, byteRange: ByteRange): void { if ( this.segmentRequest && this.segmentRequest.segmentUrl === url && compareByteRanges(this.segmentRequest.segmentByteRange, byteRange) ) { this.segmentRequest.onSuccess(undefined, 0); this.segmentRequest = null; } } public async destroy(): Promise<void> { if (this.segmentRequest) { this.segmentRequest.onError("Loading aborted: object destroyed"); this.segmentRequest = null; } this.masterPlaylist = null; this.variantPlaylists.clear(); this.playQueue = []; if (this.settings.assetsStorage !== undefined) { await this.settings.assetsStorage.destroy(); } await this.loader.destroy(); } private updateSegments(): void { if (!this.segmentRequest) { return; } const segmentLocation = this.getSegmentLocation( this.segmentRequest.segmentUrl, this.segmentRequest.segmentByteRange ); if (segmentLocation) { void this.loadSegments(segmentLocation.playlist, segmentLocation.segmentIndex, false); } } private onSegmentLoaded = (segment: Segment) => { if ( this.segmentRequest && this.segmentRequest.segmentUrl === segment.url && byteRangeToString(this.segmentRequest.segmentByteRange) === segment.range ) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.segmentRequest.onSuccess(segment.data!.slice(0), segment.downloadBandwidth); this.segmentRequest = null; } }; private onSegmentError = (segment: Segment, error: unknown) => { if ( this.segmentRequest && this.segmentRequest.segmentUrl === segment.url && byteRangeToString(this.segmentRequest.segmentByteRange) === segment.range ) { this.segmentRequest.onError(error); this.segmentRequest = null; } }; private onSegmentAbort = (segment: Segment) => { if ( this.segmentRequest && this.segmentRequest.segmentUrl === segment.url && byteRangeToString(this.segmentRequest.segmentByteRange) === segment.range ) { this.segmentRequest.onError("Loading aborted: internal abort"); this.segmentRequest = null; } }; private getSegmentLocation( url: string, byteRange: ByteRange ): { playlist: Playlist; segmentIndex: number } | undefined { for (const playlist of this.variantPlaylists.values()) { const segmentIndex = playlist.getSegmentIndex(url, byteRange); if (segmentIndex >= 0) { return { playlist: playlist, segmentIndex: segmentIndex }; } } return undefined; } private async loadSegments(playlist: Playlist, segmentIndex: number, requestFirstSegment: boolean) { const segments: Segment[] = []; const playlistSegments = playlist.manifest.segments; const initialSequence = playlist.manifest.mediaSequence ?? 0; let loadSegmentId: string | null = null; let priority = Math.max(0, this.playQueue.length - 1); const masterSwarmId = this.getMasterSwarmId(); for ( let i = segmentIndex; i < playlistSegments.length && segments.length < this.settings.forwardSegmentCount; ++i ) { const segment = playlist.manifest.segments[i]; const url = playlist.getSegmentAbsoluteUrl(segment.uri); const byteRange: ByteRange = segment.byteRange; const id = this.getSegmentId(playlist, initialSequence + i); segments.push({ id: id, url: url, masterSwarmId: masterSwarmId !== undefined ? masterSwarmId : playlist.streamSwarmId, masterManifestUri: this.masterPlaylist !== null ? this.masterPlaylist.requestUrl : playlist.requestUrl, streamId: playlist.streamId, sequence: (initialSequence + i).toString(), range: byteRangeToString(byteRange), priority: priority++, }); if (requestFirstSegment && !loadSegmentId) { loadSegmentId = id; } } this.loader.load(segments, playlist.streamSwarmId); if (loadSegmentId) { const segment = await this.loader.getSegment(loadSegmentId); if (segment) { // Segment already loaded by loader this.onSegmentLoaded(segment); } } } private getSegmentId(playlist: Playlist, segmentSequence: number): string { return `${playlist.streamSwarmId}+${segmentSequence}`; } private getMasterSwarmId() { const settingsSwarmId = this.settings.swarmId && this.settings.swarmId.length !== 0 ? this.settings.swarmId : undefined; if (settingsSwarmId !== undefined) { return settingsSwarmId; } return this.masterPlaylist !== null ? this.masterPlaylist.requestUrl.split("?")[0] : undefined; } private getStreamSwarmId(playlistUrl: string): { streamSwarmId: string; found: boolean; index: number } { const masterSwarmId = this.getMasterSwarmId(); if (this.masterPlaylist && this.masterPlaylist.manifest.playlists && masterSwarmId) { for (let i = 0; i < this.masterPlaylist.manifest.playlists.length; ++i) { const url = new URL( this.masterPlaylist.manifest.playlists[i].uri, this.masterPlaylist.responseUrl ).toString(); if (url === playlistUrl) { return { streamSwarmId: `${masterSwarmId}+V${i}`, found: true, index: i }; } } } return { streamSwarmId: masterSwarmId ?? playlistUrl.split("?")[0], found: false, index: -1, }; } private async loadContent( url: string, responseType: XMLHttpRequestResponseType, range?: string ): Promise<XMLHttpRequest> { return new Promise<XMLHttpRequest>((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = responseType; if (range) { xhr.setRequestHeader("Range", range); } xhr.addEventListener("readystatechange", () => { if (xhr.readyState !== 4) return; if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr); } else { reject(xhr.statusText); } }); const xhrSetup = (this.loader.getSettings() as { xhrSetup?: XhrSetupCallback }).xhrSetup; if (xhrSetup) { xhrSetup(xhr, url); } xhr.send(); }); } } class Playlist { public streamSwarmId = ""; public streamId?: string; public constructor(readonly requestUrl: string, readonly responseUrl: string, readonly manifest: Manifest) {} public getSegmentIndex(url: string, byteRange: ByteRange): number { for (let i = 0; i < this.manifest.segments.length; ++i) { const segment = this.manifest.segments[i]; const segmentUrl = this.getSegmentAbsoluteUrl(segment.uri); if (url === segmentUrl && compareByteRanges(segment.byteRange, byteRange)) { return i; } } return -1; } public getSegmentAbsoluteUrl(segmentUrl: string): string { return new URL(segmentUrl, this.responseUrl).toString(); } } class SegmentRequest { public constructor( readonly segmentUrl: string, readonly segmentByteRange: ByteRange, readonly segmentSequence: number, readonly playlistRequestUrl: string, readonly onSuccess: (content: ArrayBuffer | undefined, downloadBandwidth: number | undefined) => void, readonly onError: (error: unknown) => void ) {} } export interface SegmentManagerSettings { /** * Number of segments for building up predicted forward segments sequence; used to predownload and share via P2P */ forwardSegmentCount: number; /** * Override default swarm ID that is used to identify unique media stream with trackers (manifest URL without * query parameters is used as the swarm ID if the parameter is not specified) */ swarmId?: string; /** * A storage for the downloaded assets: manifests, subtitles, init segments, DRM assets etc. By default the assets are not stored. */ assetsStorage?: AssetsStorage; } function compareByteRanges(b1: ByteRange, b2: ByteRange) { return b1 === undefined ? b2 === undefined : b2 !== undefined && b1.length === b2.length && b1.offset === b2.offset; } function byteRangeToString(byteRange: ByteRange): string | undefined { if (byteRange === undefined) { return undefined; } const end = byteRange.offset + byteRange.length - 1; return `bytes=${byteRange.offset}-${end}`; }
the_stack
import { createTheme, createStyles, Grid, withStyles } from '@material-ui/core'; import * as React from 'react'; import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import AltinnColumnLayout from 'app-shared/components/AltinnColumnLayout'; import AltinnSpinner from 'app-shared/components/AltinnSpinner'; import altinnTheme from 'app-shared/theme/altinnStudioTheme'; import { getLanguageFromKey } from 'app-shared/utils/language'; import VersionControlHeader from 'app-shared/version-control/versionControlHeader'; import { ICommit, IRepository } from '../../../types/global'; import { HandleServiceInformationActions } from '../handleServiceInformationSlice'; import { fetchRepoStatus } from '../../handleMergeConflict/handleMergeConflictSlice'; import MainContent from './MainContent'; import SideMenuContent from './SideMenuContent'; import { repoStatusUrl } from '../../../utils/urlHelper'; export interface IAdministrationComponentProvidedProps { classes: any; dispatch?: Dispatch; } export interface IAdministrationComponentProps extends IAdministrationComponentProvidedProps { initialCommit: ICommit; language: any; service: IRepository; serviceDescription: string; serviceDescriptionIsSaving: boolean; serviceId: string; serviceIdIsSaving: boolean; serviceName: string; serviceNameIsSaving: boolean; } export interface IAdministrationComponentState { editServiceDescription: boolean; editServiceId: boolean; editServiceName: boolean; serviceDescription: string; serviceId: string; serviceName: string; serviceNameAnchorEl: any; } const theme = createTheme(altinnTheme); const styles = createStyles({ avatar: { maxHeight: '2em', }, sidebarHeader: { marginBottom: 20, fontSize: 20, fontWeight: 500, }, sidebarHeaderSecond: { marginTop: 36, }, sidebarInfoText: { fontSize: 16, marginBottom: 12, }, iconStyling: { fontSize: 35, textAlign: 'right' as 'right', }, sidebarServiceOwner: { marginTop: 10, }, sidebarCreatedBy: { fontSize: 16, marginTop: 10, }, spinnerLocation: { margin: 'auto', }, marginBottom_24: { marginBottom: 24, }, versionControlHeaderMargin: { marginLeft: 60, }, [theme.breakpoints.up('md')]: { versionControlHeaderMargin: { marginLeft: theme.sharedStyles.leftDrawerMenuClosedWidth + 60, }, }, }); export class AdministrationComponent extends React.Component<IAdministrationComponentProps, IAdministrationComponentState> { public static getDerivedStateFromProps(_props: IAdministrationComponentProps, _state: IAdministrationComponentState) { if (_state.editServiceName || _props.serviceNameIsSaving) { return { serviceDescription: _props.serviceDescription, serviceId: _props.serviceId, serviceName: _state.serviceName, }; } if (_state.editServiceDescription || _props.serviceDescriptionIsSaving) { return { serviceDescription: _state.serviceDescription, serviceId: _props.serviceId, serviceName: _props.serviceName, }; } if (_state.editServiceId || _props.serviceIdIsSaving) { return { serviceDescription: _props.serviceDescription, serviceId: _state.serviceId, serviceName: _props.serviceName, }; } return { serviceDescription: _props.serviceDescription, serviceId: _props.serviceId, serviceName: _props.serviceName, }; } // eslint-disable-next-line react/state-in-constructor public state: IAdministrationComponentState = { editServiceDescription: false, editServiceId: false, editServiceName: false, serviceDescription: '', serviceId: '', serviceName: this.props.serviceName, serviceNameAnchorEl: null, }; public componentDidMount() { const altinnWindow: any = window; const { org, app } = altinnWindow; this.props.dispatch(HandleServiceInformationActions.fetchService( { url: `${altinnWindow.location.origin}/designer/api/v1/repos/${org}/${app}` }, )); this.props.dispatch(HandleServiceInformationActions.fetchInitialCommit( { url: `${altinnWindow.location.origin}/designer/api/v1/repos/${org}/${app}/initialcommit` }, )); this.props.dispatch(HandleServiceInformationActions.fetchServiceConfig( { url: `${altinnWindow.location.origin}/designer/${org}/${app}/Config/GetServiceConfig` }, )); this.props.dispatch(fetchRepoStatus({ url: repoStatusUrl, org, repo: app, })); } public onServiceNameChanged = (event: any) => { this.setState({ serviceName: event.target.value, serviceNameAnchorEl: null }); } public handleEditServiceName = () => { this.setState({ editServiceName: true }); } public onBlurServiceName = () => { if (this.state.editServiceName && (!this.state.serviceName || this.state.serviceName === '')) { this.setState({ serviceNameAnchorEl: document.getElementById('administrationInputServicename'), }); } else { const { org, app } = window as Window as IAltinnWindow; // eslint-disable-next-line max-len this.props.dispatch(HandleServiceInformationActions.saveServiceName({ url: `${window.location.origin}/designer/${org}/${app}/Text/SetServiceName`, newServiceName: this.state.serviceName, })); this.props.dispatch(HandleServiceInformationActions.saveServiceConfig({ url: `${window.location.origin}/designer/${org}/${app}/Config/SetServiceConfig`, newServiceDescription: this.state.serviceDescription, newServiceId: this.state.serviceId, newServiceName: this.state.serviceName, })); this.setState({ editServiceName: false }); } } public onServiceDescriptionChanged = (event: any) => { this.setState({ serviceDescription: event.target.value, editServiceDescription: true }); } public onBlurServiceDescription = () => { if (this.state.editServiceDescription) { const { org, app } = window as Window as IAltinnWindow; // eslint-disable-next-line max-len this.props.dispatch(HandleServiceInformationActions.saveServiceConfig({ url: `${window.location.origin}/designer/${org}/${app}/Config/SetServiceConfig`, newServiceDescription: this.state.serviceDescription, newServiceId: this.state.serviceId, newServiceName: this.state.serviceName, })); this.setState({ editServiceDescription: false }); } } public onServiceIdChanged = (event: any) => { this.setState({ serviceId: event.target.value, editServiceId: true }); } public onBlurServiceId = () => { if (this.state.editServiceId) { const { org, app } = window as Window as IAltinnWindow; // eslint-disable-next-line max-len this.props.dispatch(HandleServiceInformationActions.saveServiceConfig({ url: `${window.location.origin}/designer/${org}/${app}/Config/SetServiceConfig`, newServiceDescription: this.state.serviceDescription, newServiceId: this.state.serviceId, newServiceName: this.state.serviceName, })); this.setState({ editServiceId: false }); } } public RenderMainContent = () => { return ( <MainContent editServiceName={this.state.editServiceName} handleEditServiceName={this.handleEditServiceName} language={this.props.language} onBlurServiceDescription={this.onBlurServiceDescription} onBlurServiceId={this.onBlurServiceId} onBlurServiceName={this.onBlurServiceName} onServiceDescriptionChanged={this.onServiceDescriptionChanged} onServiceIdChanged={this.onServiceIdChanged} onServiceNameChanged={this.onServiceNameChanged} service={this.props.service} serviceDescription={this.state.serviceDescription} serviceId={this.state.serviceId} serviceName={this.state.serviceName} serviceNameAnchorEl={this.state.serviceNameAnchorEl} /> ); } public render() { const { classes, service, serviceName, serviceDescription, serviceId, } = this.props; const render = service && serviceName !== null && serviceDescription !== null && serviceId !== null; const AboveColumnChildren = () => ( <div className={classes.versionControlHeaderMargin}> <VersionControlHeader language={this.props.language} /> </div> ); const SideMenuChildren = () => ( <SideMenuContent initialCommit={this.props.initialCommit} language={this.props.language} service={this.props.service} /> ); return ( <div data-testid='administration-container'> {render ? ( <AltinnColumnLayout aboveColumnChildren={<AboveColumnChildren />} sideMenuChildren={<SideMenuChildren />} header={getLanguageFromKey('administration.administration', this.props.language)} > <this.RenderMainContent /> </AltinnColumnLayout> ) : <Grid container={true}> <AltinnSpinner spinnerText='Laster siden' styleObj={classes.spinnerLocation} /> </Grid> } </div> ); } } const mapStateToProps = ( state: IServiceDevelopmentState, props: IAdministrationComponentProvidedProps, ): IAdministrationComponentProps => { return { classes: props.classes, dispatch: props.dispatch, initialCommit: state.serviceInformation.initialCommit, language: state.languageState.language, service: state.serviceInformation.repositoryInfo, serviceDescription: state.serviceInformation.serviceDescriptionObj ? state.serviceInformation.serviceDescriptionObj.description : '', serviceDescriptionIsSaving: state.serviceInformation.serviceDescriptionObj ? state.serviceInformation.serviceDescriptionObj.saving : false, serviceId: state.serviceInformation.serviceIdObj ? state.serviceInformation.serviceIdObj.serviceId : '', serviceIdIsSaving: state.serviceInformation.serviceIdObj ? state.serviceInformation.serviceIdObj.saving : false, serviceName: state.serviceInformation.serviceNameObj ? state.serviceInformation.serviceNameObj.name : '', serviceNameIsSaving: state.serviceInformation.serviceNameObj ? state.serviceInformation.serviceNameObj.saving : false, }; }; export const Administration = withStyles(styles)(connect(mapStateToProps)(AdministrationComponent));
the_stack
import Restful from '../../'; import {FilePurpose, GetReturnFieldGroupEnum} from '../../../../enums'; import { CheckEligibilityRequest, CloseReturnRequest, CreateReturnRequest, DecideReturnRequest, EscalateRequest, GetEstimateRequest, MarkAsReceivedRequest, MarkAsShippedRequest, MarkRefundSentRequest, PostOrderIssueRefundRequest, ProvideLabelRequest, ReturnRequestType, SearchReturnParams, SendMessageRequest, SetReturnCreationSessionRequest, UpdateTrackingRequest, UploadFileRequest, VoidLabelRequest } from '../../../../types'; /** * Post-Order Return API */ export default class Return extends Restful { static id = 'Return'; get basePath(): string { return '/post-order/v2'; } get useIaf() { return true; } /** * Create or update a shipping label provided by the seller. * * @param returnId The unique eBay-assigned ID of the return. * @param payload the ProvideLabelRequest */ public addShippingLabelInfo(returnId: string, payload: ProvideLabelRequest) { const id = encodeURIComponent(returnId); return this.post(`/return/${id}/add_shipping_label`, payload); } /** * Cancel a return request. * * @param returnId The unique eBay-assigned ID of the return request. * @param payload The CloseReturnRequest. */ public cancelReturnRequest(returnId: string, payload?: CloseReturnRequest) { const id = encodeURIComponent(returnId); if (payload && payload.buyerCloseReason) { payload.buyerCloseReason = payload.buyerCloseReason.trim(); } return this.post(`/return/${id}/cancel`, payload); } /** * Check to see if an item is eligible for a return. * * @param payload the CheckEligibilityRequest */ public checkReturnEligibility(payload: CheckEligibilityRequest) { return this.post(`/return/check_eligibility`, payload); } /** * Validate the eligibility of an existing shipping label. * * @param returnId The unique eBay-assigned ID of the return. */ public checkShippingLabelEligibility(returnId: string) { const id = encodeURIComponent(returnId); return this.get(`/return/${id}/check_label_print_eligibility`); } /** * Create a return draft. * * @param payload the SetReturnCreationSessionRequest */ public createReturnDraft(payload: SetReturnCreationSessionRequest) { return this.post(`/return/draft`, payload); } /** * Request a return for an item. * * @param payload the CreateReturnRequest * @param fieldGroups can be used in the call URI to control the detail level that is returned in response. */ public createReturnRequest(payload: CreateReturnRequest, fieldGroups?: GetReturnFieldGroupEnum) { return this.post(`/return`, payload, { params: { fieldgroups: fieldGroups } }); } /** * Create an eBay shipping label for the buyer. * * @param returnId The unique eBay-assigned ID of the return. */ public createReturnShippingLabel(returnId: string) { const id = encodeURIComponent(returnId); return this.post(`/return/${id}/initiate_shipping_label`); } /** * Delete a file associated with a return draft. * * @param draftId The unique eBay-assigned ID of the return draft. * @param fileId The unique eBay-assigned ID of the draft file. */ public deleteReturnDraftFile(draftId: string, fileId: string) { draftId = encodeURIComponent(draftId); fileId = encodeURIComponent(fileId); return this.delete(`/return/draft/${draftId}/file/${fileId}`); } /** * Escalate an existing return to eBay customer support. * * @param returnId The unique eBay-assigned ID of the return request. * @param payload the EscalateRequest */ public escalateReturn(returnId: string, payload?: EscalateRequest) { const id = encodeURIComponent(returnId); return this.post(`/return/${id}/escalate`, payload); } /** * Retrieve the details of a specific return. * * @param returnId The unique eBay-assigned ID of the return request. * @param fieldGroups can be used in the call URI to control the detail level that is returned in response. */ public getReturn(returnId: string, fieldGroups?: GetReturnFieldGroupEnum) { returnId = encodeURIComponent(returnId); return this.get(`/return/${returnId}`, { params: { fieldgroups: fieldGroups } }); } /** * Retrieve a return draft. * * @param returnId The unique eBay-assigned ID of the return request. */ public getReturnDraft(returnId: string) { const id = encodeURIComponent(returnId); return this.get(`/return/draft/${id}`); } /** * Retrieve the files associated with a return draft. * * @param returnId The unique eBay-assigned ID of the return draft. */ public getReturnDraftFiles(returnId: string) { const id = encodeURIComponent(returnId); return this.get(`/return/draft/${id}/files`); } /** * Retrieve the cost estimate of a refund with its shipping cost. * * @param payload the GetEstimateRequest */ public getReturnEstimate(payload: GetEstimateRequest) { return this.post(`/return/estimate`, payload); } /** * Retrieve the cost estimate of a refund with its shipping cost. * * @param returnId The unique eBay-assigned ID of the return. */ public getReturnFiles(returnId: string) { const id = encodeURIComponent(returnId); return this.get(`/return/${id}/files`); } /** * Retrieve seller's return preferences. */ public getReturnPreferences() { return this.get(`/return/preference`); } /** * Retrieve the data for an existing shipping label. * * @param returnId The unique eBay-assigned ID of the return. */ public getReturnShippingLabel(returnId: string) { returnId = encodeURIComponent(returnId); return this.get(`/return/${returnId}/get_shipping_label`); } /** * Retrieve shipment tracking activity for a return. * * @param returnId The unique eBay-assigned ID of the return. * @param carrierUsed The shipping carrier used to to ship the package. * @param trackingNumber The tracking number of the package. */ public getShipmentTrackingInfo(returnId: string, carrierUsed: string, trackingNumber: string) { returnId = encodeURIComponent(returnId); return this.get(`/return/${returnId}/tracking`, { params: { carrier_used: carrierUsed, tracking_number: trackingNumber } }); } /** * Issue a refund. * * @param returnId The unique eBay-assigned ID of the return. * @param payload The IssueRefundRequest. */ public issueReturnRefund(returnId: string, payload: PostOrderIssueRefundRequest) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/issue_refund`, payload); } /** * Mark a returned item as received. * * @param returnId The unique eBay-assigned ID of the return. * @param payload the MarkAsReceivedRequest */ public markReturnReceived(returnId: string, payload?: MarkAsReceivedRequest) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/mark_as_received`, payload); } /** * Mark a refund as received. * * @param returnId The unique eBay-assigned ID of the return. */ public markReturnRefundReceived(returnId: string) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/mark_refund_received`); } /** * Notify the buyer that a refund has been issued. * * @param returnId The unique eBay-assigned ID of the return. * @param payload the MarkRefundSentRequest */ public markReturnRefundSent(returnId: string, payload: MarkRefundSentRequest) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/mark_refund_sent`, payload); } /** * Mark a return as shipped. * * @param returnId The unique eBay-assigned ID of the return. * @param payload the MarkAsShippedRequest */ public markReturnShipped(returnId: string, payload?: MarkAsShippedRequest) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/mark_as_shipped`, payload); } /** * Perform an action on a return, such as APPROVE. * * @param returnId The unique eBay-assigned ID of the return. * @param payload the DecideReturnRequest */ public processReturnRequest(returnId: string, payload: DecideReturnRequest) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/decide`, payload); } /** * Retrieve details on items being returned. * * @param params the SearchReturnParams */ public search(params: SearchReturnParams) { return this.get(`/return/search`, { params }); } /** * Send a message to the buyer or seller regarding a return. * * @param returnId The unique eBay-assigned ID of the return. * @param payload the SendMessageRequest */ public sendReturnMessage(returnId: string, payload?: SendMessageRequest) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/send_message`, payload); } /** * Send a shipping label to an email address. * * @param returnId The unique eBay-assigned ID of the return. * @param toEmailAddress The recipient's email address is specified in this field. */ public sendReturnShippingLabel(returnId: string, toEmailAddress?: string) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/send_shipping_label`, {}, { params: { to_email_address: toEmailAddress } }); } /** * Send a shipping label to an email address. * * @param rmaRequired This field is included and set to true if the seller wishes to require that the buyer provide * a Return Merchandise Authorization (RMA) when returning an item. */ public setReturnPreferences(rmaRequired: boolean) { return this.post(`/return/preference`, { rmaRequired }); } /** * Activate the files associated with a return. * * @param returnId The unique eBay-assigned ID of the return. * @param filePurpose This value is used to indicate if the file(s) are being used to provide more information * about the condition of the item, or intended to provide more information about shipment tracking or about * the shipping label. */ public submitReturnFile(returnId: string, filePurpose?: FilePurpose) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/file/submit`, { filePurpose }); } /** * Update an existing return draft. * * @param draftId The unique eBay-assigned ID of the return draft. * @param returnRequest the ReturnRequestType */ public updateReturnDraft(draftId: string, returnRequest: ReturnRequestType) { draftId = encodeURIComponent(draftId); return this.put(`/return/draft/${draftId}`, { returnRequest }); } /** * Update shipment tracking information. * * @param returnId The unique eBay-assigned ID of the return request. * @param payload the UpdateTrackingRequest */ public updateShipmentTrackingInfo(returnId: string, payload: UpdateTrackingRequest) { returnId = encodeURIComponent(returnId); return this.put(`/return/${returnId}/update_tracking`, payload); } /** * Upload the files relating to a return draft. * * @param draftId The unique eBay-assigned ID of the return draft. * @param payload the UploadFileRequest */ public uploadReturnDraftFile(draftId: string, payload: UploadFileRequest) { draftId = encodeURIComponent(draftId); return this.post(`/return/draft/${draftId}/file/upload`, payload); } /** * Upload the files relating to a return. * * @param returnId The unique eBay-assigned ID of the return. * @param payload the UploadFileRequest */ public uploadReturnFile(returnId: string, payload: UploadFileRequest) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/file/upload`, payload); } /** * Void a shipping label. * * @param returnId The unique eBay-assigned ID of the return. * @param payload the VoidLabelRequest */ public voidShippingLabel(returnId: string, payload: VoidLabelRequest) { returnId = encodeURIComponent(returnId); return this.post(`/return/${returnId}/void_shipping_label`, payload); } }
the_stack
declare namespace JQueryRoundabout { /** * Specifier for an axis. * - `x`: The horizontal axis. * - `x`: The vertical axis. */ export type Axis = "x" | "y"; /** * The animation method used when animating the roundabout. */ export type AnimationMethod = "next" | "previous" | "nearest" /** * Callback for various different events triggered by roundabout, such as * {@link RoundaboutSettings.btnNextCallback}. */ export type RoundaboutCallback = () => void; /** * Roundabout comes with many settable configuration options that let you customize how it operates. */ export interface RoundaboutSettings { /** * When true, Roundabout will automatically advance the moving elements to the next child at a regular interval * (settable as autoplayDuration). * * Defaults to `false`. */ autoplay: boolean; /** * The length of time (in milliseconds) between animation triggers when a Roundabout's autoplay is playing. * * Defaults to `1000`. */ autoplayDuration: number; /** * The length of time (in milliseconds) to delay the start of Roundabout's configured autoplay option. This only * works with setting autoplay to true, and only on the first start of autoplay. * * Defaults to `0`. */ autoplayInitialDelay: number; /** * When true, Roundabout will pause autoplay when the user moves the cursor over the Roundabout container. * * Defaults to `false`. */ autoplayPauseOnHover: boolean; /** * The starting direction in which Roundabout should face relative to the focusBearing. * * Defaults to `0.0`. */ bearing: number; /** * A jQuery selector of page elements that, when clicked, will trigger the Roundabout to animate to the next * moving element. * * Defaults to `null`. */ btnNext: string; /** * A function that will be called once the animation triggered by a btnNext-related click has finished. * * Defaults to `function() {}`. */ btnNextCallback: RoundaboutCallback; /** * A jQuery selector of page elements that, when clicked, will trigger the Roundabout to animate to the previous * moving element. * * Defaults to `null`. */ btnPrev: string; /** * A function that will be called once the animation triggered by a btnPrev-related click has finished. * * Defaults to `function() {}`. */ btnPrevCallback: RoundaboutCallback; /** * A jQuery selector of page elements that, when clicked, will start the Roundabout's autoplay feature (if it's * currently stopped). * * Defaults to `null`. */ btnStartAutoplay: string; /** * A jQuery selector of page elements that, when clicked, will stop the Roundabout's autoplay feature (if it's * current playing). * * Defaults to `null`. */ btnStopAutoplay: string; /** * A jQuery selector of page elements that, when clicked, will toggle the Roundabout's autoplay state (either * starting or stopping). * * Defaults to `null`. */ btnToggleAutoplay: string; /** * A jQuery selector of child elements within the elements Roundabout is called upon that will become the moving * elements within Roundabout. By default, Roundabout works on unordered lists, but it can be changed to work * with any nested set of child elements. * * Defaults to `li`. */ childSelector: string; /** * When true, Roundabout will bring non-focused moving elements into focus when they're clicked. Otherwise, * click events won't be captured and will be passed through to the moving child elements. * * Defaults to `true`. */ clickToFocus: boolean; /** * A function that will be called once the clickToFocus animation has completed. * * Defaults to `function() {}`. */ clickToFocusCallback: RoundaboutCallback; /** * When true, Roundabout will replace the contents of moving elements with information about the moving elements * themselves. * * Defaults to `false`. */ debug: boolean; /** * The axis along which drag events are measured. * * Defaults to `x`. */ dragAxis: Axis; /** * Alters the rate at which dragging moves the Roundabout's moving elements. Higher numbers will cause the * moving elements to move less. * * Defaults to `4`. */ dragFactor: number; /** * The animation method to use when a dragged Roundabout is dropped. * * Defaults to `nearest`. */ dropAnimateTo: AnimationMethod; /** * A function that will be called once the dropped animation has completed. * * Defaults to `function() {}`. */ dropCallback: RoundaboutCallback /** * The length of time (in milliseconds) the animation will take to animate Roundabout to the appropriate child * when the Roundabout is “dropped.” * * Defaults to `600`. */ dropDuration: number; /** * The easing function to use when animating Roundabout after it has been “dropped.” With no other plugins, the * standard jQuery easing functions are available. When using the jQuery easing plugin all of its easing functions will also be available. * * Defaults to `swing`. */ dropEasing: string; /** * The length of time Roundabout will take to move from one child element being in focus to another (when an * animation is triggered). This value acts as the default for Roundabout, but each animation action can be given * a custom duration for that animation. * * Defaults to `600`. */ duration: number; /** * The easing function to use when animating Roundabout. With no other plugins, the standard jQuery easing * functions are available. When using the jQuery easing plugin, all of its easing functions will also be * available. * * Defaults to `swing`. */ easing: string; /** * Requires event.drag and event.drop plugins by ThreeDubMedia. Allows a user to rotate Roundabout be clicking * and dragging the Roundabout area itself. * * Defaults to `false`. */ enableDrag: boolean; /** * The maximum distance two values can be from one another to still be considered equal by Roundabout's * standards. This prevents JavaScript rounding errors. * * Defaults to `0.001`. */ floatComparisonThreshold: number; /** * The bearing that Roundabout will use as the focus point. All animations that move Roundabout between children * will animate the given child element to this bearing. * * Defaults to `0.0`. */ focusBearing: number; /** * The greatest opacity that will be assigned to a moving element. This occurs when the moving element is at the * same bearing as the focusBearing. * * Defaults to `1.0`. */ maxOpacity: number; /** * The greatest size (relative to its starting size) that will be assigned to a moving element. This occurs when * the moving element is at the same bearing as the focusBearing. * * Defaults to `1.0`. */ maxScale: number; /** * The greatest z-index that will be assigned to a moving element. This occurs when the moving element is at the * same bearing as the focusBearing. * * Defaults to `280`. */ maxZ: number; /** * The lowest opacity that will be assigned to a moving element. This occurs when the moving element is opposite * of (that is, 180° away from) the focusBearing. * * Defaults to `0.4`. */ minOpacity: number; /** * The lowest size (relative to its starting size) that will be assigned to a moving element. This occurs when * the moving element is opposite of (that is, 180° away from) the focusBearing. * * Defaults to `0.4`. */ minScale: number; /** * The lowest z-index that will be assigned to a moving element. This occurs when the moving element is opposite * of (that is, 180° away from) the focusBearing. * * Defaults to `100`. */ minZ: number; /** * When true, reverses the direction in which Roundabout will operate. By default, next animations will rotate * moving elements in a clockwise direction and previous animations will be counterclockwise. Using reflect will * flip the two. * * Defaults to `false`. */ reflect: boolean; /** * When true, attaches a resize event onto the window and will automatically relayout Roundabout's child * elements as the holder element changes size. * * Defaults to `false`. */ responsive: boolean; /** * The path that moving elements follow. By default, Roundabout comes with one shape, which is lazySusan. When * using Roundabout with the Roundabout Shapes plugin, there are many other shapes available. * * Defaults to `lazySusan`. */ shape: string; /** * The child element that will start at the Roundabout's focusBearing on load. This is a zero-based counter * based on the order of markup. * * Defaults to `0`. */ startingChild: number; /** * Slightly alters the calculations of moving elements. In the default shape, it adjusts the apparent tilt. * Other shapes will differ. * * Defaults to `0.0`. */ tilt: number; /** * When true, a blur event will be triggered on the child element that moves out of the focused position when * it does so. * * Defaults to `true`. */ triggerBlurEvents: boolean; /** * When true, a focus event will be triggered on the child element that moves into focus when it does so. * * Defaults to `true`. */ triggerFocusEvents: boolean; } } interface JQuery { /** * Initializes roundabout on the current element. * @param settings Optional settings for configuring Roundabout. * @param onReady A callback function that is invoked once the Roundabout is ready. * @return this jQuery instance for chaining. */ roundabout(settings?: Partial<JQueryRoundabout.RoundaboutSettings>, onReady?: JQueryRoundabout.RoundaboutCallback): this; /** * Initializes roundabout on the current element. * @param onReady A callback function that is invoked once the Roundabout is ready. * @return this jQuery instance for chaining. */ roundabout(onReady: JQueryRoundabout.RoundaboutCallback): this; /** * Changes the bearing of the Roundabout. * @param method The method to call on the Roundabout instance. * @param bearing The new bearing in degrees, a value between `0.0` and `359.9`. * @param onChangeComplete * @return this jQuery instance for chaining. */ roundabout(method: "setBearing", bearing: number, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Alters the bearing of the Roundabout by a given amount, either positive or negative degrees. * @param method The method to call on the Roundabout instance. * @param delta The amount in degrees by which the bearing will change, either positive or negative. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "adjustBearing", delta: number, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Changes the tilt of the Roundabout. * @param method The method to call on the Roundabout instance. * @param tilt The new tilt in degrees, typically between `-2.0` and `10.0`. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "setTilt", tilt: number, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Alters the tilt of the Roundabout by a given amount, either in positive or negative amounts. * @param method The method to call on the Roundabout instance. * @param delta The amount in degrees by which the tilt will change (either positive or negative). * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "adjustTilt", delta: number, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the nearest child. This animation will not move the Roundabout if any child is already * in focus. * @param method The method to call on the Roundabout instance. * @param duration The length of time (in milliseconds) that the animation will take to complete; uses Roundabout’s * configured duration if no value is set here * @param easing The name of the easing function to use for movement; uses Roundabout’s configured easing if no * value is set here. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToNearestChild", duration: number, easing: string, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the nearest child. This animation will not move the Roundabout if any child is already * in focus. * @param method The method to call on the Roundabout instance. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToNearestChild", onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the given childPosition, which is a zero-based counter of children based on the order * of markup. * @param method The method to call on the Roundabout instance. * @param childPosition The zero-based child to which Roundabout will animate. * @param duration The length of time (in milliseconds) that the animation will take to complete; uses Roundabout’s * configured duration if no value is set here * @param easing The name of the easing function to use for movement; uses Roundabout’s configured easing if no * value is set here. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToChild", childPosition: number, duration: number, easing: string, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the given childPosition, which is a zero-based counter of children based on the order * of markup. * @param method The method to call on the Roundabout instance. * @param childPosition The zero-based child to which Roundabout will animate. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToChild", childPosition: number, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the next child element. * @param method The method to call on the Roundabout instance. * @param duration The length of time (in milliseconds) that the animation will take to complete; uses Roundabout’s * configured duration if no value is set here * @param easing The name of the easing function to use for movement; uses Roundabout’s configured easing if no * value is set here. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToNextChild", duration: number, easing: string, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the next child element. * @param method The method to call on the Roundabout instance. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToNextChild", onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the previous child element. * @param method The method to call on the Roundabout instance. * @param duration The length of time (in milliseconds) that the animation will take to complete; uses Roundabout’s * configured duration if no value is set here * @param easing The name of the easing function to use for movement; uses Roundabout’s configured easing if no * value is set here. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToPreviousChild", duration: number, easing: string, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the previous child element. * @param method The method to call on the Roundabout instance. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToPreviousChild", onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the given amount of degrees away from its current bearing (either positive or negative * degrees). * @param method The method to call on the Roundabout instance. * @param degrees The amount by which the bearing will change (either positive or negative) * @param duration The length of time (in milliseconds) that the animation will take to complete; uses Roundabout’s * configured duration if no value is set here * @param easing The name of the easing function to use for movement; uses Roundabout’s configured easing if no * value is set here. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToDelta", degrees: number, duration: number, easing: string, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout to the given amount of degrees away from its current bearing (either positive or negative * degrees). * @param method The method to call on the Roundabout instance. * @param degrees The amount by which the bearing will change (either positive or negative) * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateToDelta", degrees: number, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout so that a given bearing ends at the configured focusBearing. * @param method The method to call on the Roundabout instance. * @param degrees A value between `0.0` and `359.9`. * @param duration The length of time (in milliseconds) that the animation will take to complete; uses Roundabout’s * configured duration if no value is set here * @param easing The name of the easing function to use for movement; uses Roundabout’s configured easing if no * value is set here. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateBearingToFocus", degrees: number, duration: number, easing: string, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Animates the Roundabout so that a given bearing ends at the configured focusBearing. * * @param method The method to call on the Roundabout instance. * @param degrees A value between `0.0` and `359.9`. * @param onChangeComplete Callback function that is invoked once the change completes. * @return this jQuery instance for chaining. */ roundabout(method: "animateBearingToFocus", degrees: number, onChangeComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Starts the Roundabout’s autoplay feature. * @param method The method to call on the Roundabout instance. * @param onAnimationComplete Callback function that is invoked after each autoplay animation completes. * @return this jQuery instance for chaining. */ roundabout(method: "startAutoplay", onAnimationComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Stops the Roundabout’s autoplay feature. * @param method The method to call on the Roundabout instance. * @param keepAutoplayBindings When `true` will not destroy any autoplay mouseenter and mouseleave event bindings * that were set by `autoplayPauseOnHover`. * @return this jQuery instance for chaining. */ roundabout(method: "stopAutoplay", keepAutoplayBindings?: boolean): this; /** * Starts or stops the Roundabout’s autoplay feature (based upon its current state). * @param method The method to call on the Roundabout instance. * @param onAnimationComplete Callback function that is invoked after each autoplay animation completes. * @return this jQuery instance for chaining. */ roundabout(method: "toggleAutoplay", onAnimationComplete?: JQueryRoundabout.RoundaboutCallback): this; /** * Checks to see if the Roundabout’s autoplay feature is currently playing or not. * @param method The method to call on the Roundabout instance. * @return `true` if autoplay is active, or `false` otherwise. */ roundabout(method: "isAutoplaying"): boolean; /** * Changes the length of time (in milliseconds) that the Roundabout’s autoplay feature waits between attempts to * animate to the next child. * @param method The method to call on the Roundabout instance. * @param duration Length of time (in milliseconds) between attempts to have autoplay animate to the next child * element. * @return this jQuery instance for chaining. */ roundabout(method: "changeAutoplayDuration", duration: number): this; /** * Repositions child elements based on new contextual information. This is most helpful when the Roundabout element * itself changes size and moving child elements within need readjusting. * @param method The method to call on the Roundabout instance. * @return this jQuery instance for chaining. */ roundabout(method: "relayoutChildren"): this; /** * Gets the nearest child element to the `focusBearing`. This number is a zero-based counter based on order of * markup. * @param method The method to call on the Roundabout instance. * @return Zero-based index of the nearest child. */ roundabout(method: "getNearestChild"): number; /** * Gets the child currently in focus. This number is a zero-based counter based on order of markup. * @param method The method to call on the Roundabout instance. * @return Zero-based index of the focused child. */ roundabout(method: "getChildInFocus", ): number; } // Extend available event types declare namespace JQuery { interface TypeToTriggeredEventMap< TDelegateTarget, TData, TCurrentTarget, TTarget > { /** * Triggered by the {@link JQuery.roundabout|jQuery Roundabout plugin}. * * This event fires on the Roundabout element when its child elements have been repositioned and are in place. */ childrenUpdated: JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>; /** * Triggered by the jQuery Roundabout plugin * * This event fires on child elements that have been repositioned and are in place. */ reposition: JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>; /** * Triggered by the {@link JQuery.roundabout|jQuery Roundabout plugin}. * * This event fires on the Roundabout element when its `bearing` has been set. */ bearingSet: JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>; /** * Triggered by the {@link JQuery.roundabout|jQuery Roundabout plugin}. * * This event fires on moving child elements when an animation causes them pass through the point that is * opposite (or 180°) from the `focusBearing` in a clockwise motion. */ moveClockwiseThroughBack: JQuery.EventBase<TDelegateTarget, TData, TCurrentTarget, TTarget>; /** * Triggered by the {@link JQuery.roundabout|jQuery Roundabout plugin}. * * This event fires on moving child elements when an animation causes them to pass through the point that is * opposite (or 180°) from the focusBearing in a counterclockwise motion. */ moveCounterclockwiseThroughBack: JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>; /** * Triggered by the {@link JQuery.roundabout|jQuery Roundabout plugin}. * * This event fires on the Roundabout element at the start of any animation. */ animationStart: JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>; /** * Triggered by the {@link JQuery.roundabout|jQuery Roundabout plugin}. * * This event fires on the Roundabout element at the end of any animation. */ animationEnd: JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>; /** * Triggered by the {@link JQuery.roundabout|jQuery Roundabout plugin}. * * This event fires on the Roundabout element when the `autoplay` feature starts. */ autoplayStart: JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>; /** * Triggered by the {@link JQuery.roundabout|jQuery Roundabout plugin}. * * This event fires on the Roundabout element when the `autoplay` feature stops. */ autoplayStop: JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>; } }
the_stack
import Title from 'view/title'; import TizenControlbar from 'view/controls/tizen/tizen-controlbar'; import TizenSeekbar from './tizen-seekbar'; import DisplayContainer from 'view/controls/display-container'; import PauseDisplayTemplate from 'view/controls/tizen/templates/pause-display'; import { TizenMenu } from 'view/controls/components/menu/tizen-menu.js'; import { addClass, removeClass, createElement } from 'utils/dom'; import { STATE_PLAYING, STATE_PAUSED, USER_ACTION } from 'events/events'; import Controls from 'view/controls/controls'; import type ViewModel from 'view/view-model'; import type { PlayerAPI } from 'types/generic.type'; require('css/tizen.less'); const ACTIVE_TIMEOUT = 5000; const reasonInteraction = () => { return { reason: 'interaction' }; }; function createBufferIcon(context: HTMLDocument, displayContainer: DisplayContainer, className: string): void { const circle = context.createElementNS('http://www.w3.org/2000/svg', 'circle'); circle.setAttribute('class', className); circle.setAttribute('cx', '50%'); circle.setAttribute('cy', '50%'); circle.setAttribute('r', '75'); const svgContainer = displayContainer.element().querySelector('.jw-svg-icon-buffer'); if (svgContainer) { svgContainer.appendChild(circle); } } class TizenControls extends Controls { context: HTMLDocument; playerContainer: HTMLElement; api: PlayerAPI | null; model: ViewModel | null; div: HTMLElement | null; backdrop: HTMLElement | null; pauseDisplay: HTMLElement | null; displayContainer: DisplayContainer | null; controlbar: TizenControlbar | null; seekbar: TizenSeekbar | null; seekState: boolean; settingsMenu: TizenMenu | null; showing: boolean; instreamState: boolean; keydownCallback: ((evt: KeyboardEvent) => void) | null; userInactive: any; wrapperElement: any; addBackdrop: any; trigger: any; constructor(context: HTMLDocument, playerContainer: HTMLElement) { super(context, playerContainer); this.context = context; this.playerContainer = playerContainer; this.api = null; this.model = null; this.div = null; this.backdrop = null; this.pauseDisplay = null; this.displayContainer = null; this.controlbar = null; this.seekbar = null; this.seekState = false; this.settingsMenu = null; this.showing = false; this.instreamState = false; this.keydownCallback = null; } get apiEnabled(): boolean { return !!this.api; } enable(api: PlayerAPI, model: ViewModel): void { addClass(this.playerContainer, 'jw-tizen-app jw-flag-fullscreen'); this.api = api; this.model = model; const element = this.context.createElement('div'); element.className = 'jw-tizen-controls jw-tizen-reset'; // Pause Display if (!this.pauseDisplay) { const pauseDisplay = createElement(PauseDisplayTemplate()); const title = new Title(model); title.setup(pauseDisplay.querySelector('.jw-pause-display-container')); element.appendChild(pauseDisplay); this.pauseDisplay = pauseDisplay; } // Display Buttons - Buffering if (!this.displayContainer) { const displayContainer = new DisplayContainer(model, api); createBufferIcon(this.context, displayContainer, 'jw-tizen-buffer-draw'); createBufferIcon(this.context, displayContainer, 'jw-tizen-buffer-erase'); element.appendChild(displayContainer.element()); this.displayContainer = displayContainer; } // Controlbar const controlbar = new TizenControlbar(api, model, this.playerContainer.querySelector('.jw-hidden-accessibility')); controlbar.on('backClick', this.onBackClick, this); element.appendChild(controlbar.element()); // Seekbar const seekbar = this.seekbar = new TizenSeekbar(model, api, controlbar.elements.time); element.appendChild(seekbar.element()); // Settings/Tracks Menu const localization = model.get('localization'); const settingsMenu = new TizenMenu(api, model.player, this.controlbar, localization); settingsMenu.on(USER_ACTION, () => this.userActive()); controlbar.on('settingsInteraction', () => { settingsMenu.toggle(); const activeButton = this.div && this.div.querySelector('.jw-active'); if (settingsMenu.visible && activeButton) { removeClass(activeButton, 'jw-active'); } }); element.insertBefore(settingsMenu.el, controlbar.element()); // Trigger backClick when all videos complete api.on('playlistComplete', this.onBackClick, this); // Remove event listener added in base controls if (this.keydownCallback) { this.playerContainer.removeEventListener('keydown', this.keydownCallback); this.keydownCallback = null; } // For the TV app to hear events this.keydownCallback = (evt) => this.handleKeydown(evt); document.addEventListener('keydown', this.keydownCallback); // To enable features like the ad skip button super.enable.call(this, api, model); // Next Up Tooltip const baseControlbar = this.controlbar; if (baseControlbar) { const nextUpToolTip = baseControlbar.nextUpToolTip; if (nextUpToolTip) { nextUpToolTip.off('all'); if (model.get('nextUp')) { nextUpToolTip.onNextUp(model, model.get('nextUp')); } baseControlbar.nextUpToolTip = null; controlbar.nextUpToolTip = nextUpToolTip; element.appendChild(nextUpToolTip.element()); } // Destroy the controlbar being overridden baseControlbar.destroy(); } // Destroy the settings menu being overridden if (this.settingsMenu) { this.settingsMenu.destroy(); } this.settingsMenu = settingsMenu; this.controlbar = controlbar; this.div = element; this.addBackdrop(); this.addControls(); this.playerContainer.focus({ preventScroll: true }); // Hide controls on the first frame this.userInactive(); model.set('controlsEnabled', true); } addControls(): void { const controls = this.wrapperElement.querySelector('.jw-controls'); if (controls) { this.wrapperElement.removeChild(controls); } super.addControls.call(this); } disable(model: ViewModel): void { this.model = null; if (this.apiEnabled) { this.api.off(null, null, this); this.api = null; } if (this.keydownCallback) { document.removeEventListener('keydown', this.keydownCallback); } if (this.seekbar) { this.seekbar.destroy(); } super.disable.call(this, model); } userActive(timeout: number = ACTIVE_TIMEOUT): void { super.userActive.call(this, timeout); } onBackClick(): void { this.api.trigger('backClick'); this.api.remove(); } private handleKeydown(evt: KeyboardEvent): void { if (!this.apiEnabled || !this.model) { return; } let playButtonActive = false; const settingsMenu = this.settingsMenu; if (settingsMenu && settingsMenu.visible && evt.keyCode !== 10253) { return; } if (this.controlbar) { this.controlbar.handleKeydown(evt, this.showing, this.instreamState); playButtonActive = this.controlbar.activeButton === this.controlbar.elements.play; } switch (evt.keyCode) { case 37: // left-arrow if (this.instreamState) { this.userActive(); return; } if (this.seekState) { this.updateSeek(-10); return; } if (!this.showing || playButtonActive) { this.enterSeekMode(); return; } this.userActive(); break; case 39: // right-arrow if (this.instreamState) { this.userActive(); return; } if (this.seekState) { this.updateSeek(10); return; } if (!this.showing || playButtonActive) { this.enterSeekMode(); return; } this.userActive(); break; case 38: // up-arrow if (this.seekState) { this.exitSeekMode(); this.userInactive(); this.api.play(); return; } this.userActive(); break; case 40: // down-arrow if (this.seekState) { this.exitSeekMode(); } this.userActive(); break; case 13: // center/enter evt.preventDefault(); if (this.seekState) { this.seek(); return; } if (!this.showing) { this.userActive(); this.api.playToggle(reasonInteraction()); } break; case 415: // play if (this.seekState) { this.seek(); return; } if (this.model.get('state') !== STATE_PLAYING) { this.api.play(); } break; case 19: // pause if (this.seekState) { this.exitSeekMode(); return; } if (this.model.get('state') !== STATE_PAUSED) { this.userActive(); this.api.pause(); } break; case 10252: // play/pause if (this.seekState) { this.seek(); return; } if (this.model.get('state') !== STATE_PAUSED) { this.userActive(); } this.api.playToggle(reasonInteraction()); break; case 412: // Rewind break; case 417: // FastForward break; case 10009: // Back if (this.seekState) { this.exitSeekMode(); this.userActive(); return; } this.onBackClick(); break; case 10253: // menu this.userActive(); if (settingsMenu) { settingsMenu.toggle(evt); } break; case 10182: // Exit/Home this.api.remove(); break; default: break; } } private seek(): void { if (!this.apiEnabled || !this.seekbar) { return; } this.seekbar.seek(); this.exitSeekMode(); this.api.play(); this.userInactive(); } private enterSeekMode(): void { if (!this.apiEnabled || !this.seekbar) { return; } addClass(this.playerContainer, 'jw-flag-seek'); this.seekState = true; this.seekbar.show(); this.api.pause(); this.userActive(); } private exitSeekMode(): void { if (!this.seekbar) { return; } removeClass(this.playerContainer, 'jw-flag-seek'); this.seekState = false; this.seekbar.hide(); } private updateSeek(increment: number): void { if (!this.seekbar) { return; } this.seekbar.update(increment); this.userActive(); } } export default TizenControls;
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 widget that displays exactly two elements with a splitter between them. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.splitterBorderWidth = VRS.globalOptions.splitterBorderWidth !== undefined ? VRS.globalOptions.splitterBorderWidth : 1; // The width in pixels of the borders around splitters. /** * Carries the state of a VRS splitter. */ class Splitter_State { /** * A single instance of a SplitterPaneDetail. */ bar: SplitterPaneDetail = null; /** * An array of 2 SplitterPaneDetail objects. */ panes: SplitterPaneDetail[] = []; /** * The pixel offset of the left/top edge of the splitter bar. */ posn: number = -1; /** * The collapse button jQuery element. */ collapseButton: JQuery = null; /** * 1 if the first pane has been collapsed, 2 if the second pane has been collapsed. 0 if neither are collapsed. */ collapsedPane: number = 0; /** * True if the position has been set by the user. */ userSetPosn: boolean = false; /** * The pixel position from which the splitter is dragged. -1 if the splitter is not being dragged. */ startMovePosn: number = -1; /** * The previous pixel position of the splitter bar. */ previousPosn: number = -1; /** * The previous pixel length of pane 0. */ previousPane0Length: number = -1; /** * The previous pixel length of pane 1. */ previousPane1Length: number = -1; /** * The namespace that all DOM events that use $.proxy are suffixed with to ensure that unbinds only unbind * our splitter and nothing else. */ eventNamespace: string = ''; } /** * Carries the state of a single pane within a VRS splitter. */ class SplitterPane_State { /** * The container element that wraps the content in a splitter pane. */ container: JQuery = null; /** * The direct-access Splitter jQuery UI object - only set if the content is itself a splitter. */ splitterContent: Splitter = null; /** * The CSS that needs to be applied to the content to bring it back to the state it was in before it was placed in a pane. */ originalContentCss: Object = null; } /** * Groups together things that a splitter knows about one of its panes, or about its bar. */ class SplitterPaneDetail { constructor(public element: JQuery) { } /** * The direct-access object to the splitterPane plugin for the pane. Note that the detail for the bar doesn't have one of these. */ splitterPane: SplitterPane = undefined; /** * The length, in pixels, of the pane in the relevant dimension (width for vertical splitters, height for horizontal splitters) */ length: number = 0; } /** * The details recorded in SplitterGroupPersistence for a splitter. */ export interface Splitter_Detail { splitter: Splitter; barMovedHookResult: IEventHandleJQueryUI; pane1Length?: number; pane2Length?: number; } /** * The state object saved by SplitterGroupPersistence for a group of (potentially) nested splitters. */ export interface SplitterGroupPersistence_SaveState { lengths: SplitterGroupPersistence_SplitterSaveState[]; } /** * The state object recording persisted state for a single splitter. */ export interface SplitterGroupPersistence_SplitterSaveState { name: string; pane: number; vertical: boolean; length: number; } /** * The object responsible for saving and loading the state of a group of nested splitters. */ export class SplitterGroupPersistence implements ISelfPersist<SplitterGroupPersistence_SaveState> { private _Name: string; private _SplitterDetails: { [index: string]: Splitter_Detail } = {}; // An associative array of splitter details indexed by splitter name. private _AutoSaveEnabled = false; constructor(name: string) { if(!name || name === '') throw 'You must supply the name that the group of splitters will be saved under'; this._Name = name; } getAutoSaveEnabled() : boolean { return this._AutoSaveEnabled; } setAutoSaveEnabled(value: boolean) { this._AutoSaveEnabled = value; } /** * Releases the resources attached to the splitter group persistence object. */ dispose() { $.each(this._SplitterDetails, function() { var details = this; if(details.splitter && details.barMovedHookResult) { details.splitter.unhook(details.barMovedHookResult); } }); this._SplitterDetails = {}; } /** * Saves the current state of the group of splitters. */ saveState() { VRS.configStorage.save(this.persistenceKey(), this.createSettings()); } /** * Returns the saved state for the group of splitters or the current state if no state has been saved. */ loadState() : SplitterGroupPersistence_SaveState { var savedSettings = VRS.configStorage.load(this.persistenceKey(), {}); return $.extend(this.createSettings(), savedSettings); } /** * Returns the saved state for a single splitter within the group. */ getSplitterSavedState(splitterName: string) { var result = null; var savedSettings = VRS.configStorage.load(this.persistenceKey(), null); if(savedSettings) { $.each(savedSettings.lengths, (idx, savedSplitter) => { if(savedSplitter.name === splitterName) { result = savedSplitter; } return result === null; }); } return result; } /** * Applies the saved state to the splitters held by the object. */ applyState(settings: SplitterGroupPersistence_SaveState) { var autoSaveState = this.getAutoSaveEnabled(); this.setAutoSaveEnabled(false); var length = settings.lengths ? settings.lengths.length : -1; for(var i = 0;i < length;++i) { var details = settings.lengths[i]; var splitterDetails = this._SplitterDetails[details.name]; if(splitterDetails) { splitterDetails.splitter.applySavedLength(details); } } this.setAutoSaveEnabled(autoSaveState); } /** * Loads and applies the saved state. */ loadAndApplyState() { this.applyState(this.loadState()); } /** * Returns the key to save the splitter positions against. */ private persistenceKey() : string { return 'vrsSplitterPosition-' + this._Name; } /** * Returns the current state. */ private createSettings() : SplitterGroupPersistence_SaveState { var lengths = []; for(var splitterName in this._SplitterDetails) { var splitterDetails = this._SplitterDetails[splitterName]; var splitter = splitterDetails.splitter; var pane = splitter.getSavePane(); lengths.push({ name: splitter.getName(), pane: pane, vertical: splitter.getIsVertical(), length: pane === 1 ? splitterDetails.pane1Length : splitterDetails.pane2Length }); } return { lengths: lengths }; } /** * Adds a splitter to the group of splitters whose positions will be saved. */ registerSplitter(splitterElement: JQuery) : Splitter_Detail { var splitter = VRS.jQueryUIHelper.getSplitterPlugin(splitterElement); var splitterName = splitter.getName(); var existingSplitter = this._SplitterDetails[splitterName]; if(existingSplitter) throw 'The ' + splitterName + ' splitter has already been registered'; this._SplitterDetails[splitterName] = { splitter: splitter, barMovedHookResult: splitter.hookBarMoved(this.onBarMoved, this) }; return this.getSplitterSavedState(splitterName); } /** * Called when the user moves a splitter that this object is saving state for. */ private onBarMoved(event: Event, data: Splitter_BarMovedEventArgs) { var splitter = VRS.jQueryUIHelper.getSplitterPlugin(data.splitterElement); var splitterDetails = splitter ? this._SplitterDetails[splitter.getName()] : null; if(splitterDetails) { splitterDetails.pane1Length = data.pane1Length; splitterDetails.pane2Length = data.pane2Length; if(this.getAutoSaveEnabled()) { this.saveState(); } } } } /* * JQueryUIHelper */ export var jQueryUIHelper: JQueryUIHelper = VRS.jQueryUIHelper || {}; jQueryUIHelper.getSplitterPlugin = (jQueryElement: JQuery) : Splitter => { return <Splitter>jQueryElement.data('vrsVrsSplitter'); } jQueryUIHelper.getSplitterPanePlugin = (jQueryElement: JQuery) : SplitterPane => { return <SplitterPane>jQueryElement.data('vrsVrsSplitterPane'); } /** * The options supported by a SplitterPane. */ export interface SplitterPane_Options { /** * True if the parent splitter is vertical. */ isVertical?: boolean; /** * The smallest allowable number of pixels. */ minPixels?: number; /** * Either a pixel value (can be a %age) or a method that takes the width of the splitter without the bar and returns a number of pixels. */ max?: PercentValue | ((splitterWidth: number) => number); /** * Either a pixel value (can be a %age) or a method that takes the width of the splitter without the bar and returns a number of pixels. */ startSize?: PercentValue | ((splitterWidth: number) => number); } /** * A jQuery UI widget that encapsulates a single pane within a splitter. */ export class SplitterPane extends JQueryUICustomWidget { options: SplitterPane_Options = { isVertical: false, minPixels: 1, }; private _getState() : SplitterPane_State { var result = this.element.data('splitterPaneState'); if(result === undefined) { result = new SplitterPane_State(); this.element.data('splitterPaneState', result); } return result; } _create() { var state = this._getState(); state.originalContentCss = this.element.css([ 'width', 'height' ]); this.element.css({ width: '100%', height: '100%' }); state.container = $('<div/>') .css({ position: 'absolute', left: '0', top: '0', 'z-index': '1', '-moz-outline-style': 'none', width: '100%', height: '100%' }) .addClass('splitterPane') .insertBefore(this.element) // Don't use wrap, it uses a copy .append(this.element); state.splitterContent = VRS.jQueryUIHelper.getSplitterPlugin(this.element); if(!state.splitterContent) { state.container .css({ overflow: 'auto' }) .addClass('border'); } if(VRS.refreshManager) { VRS.refreshManager.registerOwner(state.container); } } _destroy() { var state = this._getState(); if(state.container) { if(VRS.refreshManager) { VRS.refreshManager.unregisterOwner(state.container); } this.element.unwrap(); state.container = null; if(state.originalContentCss) { this.element.css(state.originalContentCss); } state.originalContentCss = null; } } /** * Returns the pane's container object. This object is at the top level of elements, it is the one that the splitter controls. */ getContainer() : JQuery { return this._getState().container; } /** * Returns the pane's content element. This object is below the container, it's the UI that the user sees within the splitter. */ getContent() : JQuery { return this.element; } /** * Returns true if the content of the pane is another splitter. */ getContentIsSplitter() : boolean { return !!this._getState().splitterContent; } /** * Returns the minimum number of pixels that this pane can be sized to. */ getMinPixels() : number { return this.options.minPixels; } /** * Returns the maximum number of pixels that this pane can be sized to. * @param {number} availableLengthWithoutBar The pixel width of the parent splitter after the splitter bar has been removed. * @returns {number=} */ getMaxPixels(availableLengthWithoutBar: number) : number { return this._getPixelsFromMaxOrStartSize(this.options.max, availableLengthWithoutBar); } /** * Returns the initial size of the splitter in pixels. * @param {number} availableLengthWithoutBar The pixel width of the parent splitter after the splitter bar has been removed. */ getStartSize(availableLengthWithoutBar: number) : number { return this._getPixelsFromMaxOrStartSize(this.options.startSize, availableLengthWithoutBar); } /** * Returns either the maxmimum number of pixels allowed or the starting size * @param {(VRS_VALUE_PERCENT|function(number):number)=} maxOrStartSize The max or startSize value to resolve. * @param {number} availableLengthWithoutBar The width of the parent splitter after the bar has been removed. * @returns {number=} The resolved pixel width or null if there is no maximum / start width. */ _getPixelsFromMaxOrStartSize(maxOrStartSize: PercentValue | ((size: number) => number), availableLengthWithoutBar: number) : number { var result: number = null; if(maxOrStartSize) { if(maxOrStartSize instanceof Function) { result = maxOrStartSize(availableLengthWithoutBar); } else { var valuePercent = <PercentValue>maxOrStartSize; result = valuePercent.value; if(valuePercent.isPercent) { result = Math.max(1, Math.ceil(availableLengthWithoutBar * result)); } } } return result; } } $.widget('vrs.vrsSplitterPane', new SplitterPane()); /** * The options that a Splitter supports. */ export interface Splitter_Options { /** * The mandatory name for the splitter. */ name: string; /** * True if the splitter is vertical, false if it is horizontal. */ vertical?: boolean; /** * 1 if the first pane's location should be preserved across page refreshes, 2 if the 2nd pane's location should be preserved. Not used with fixed splitters. */ savePane?: number; /** * 1 if the first pane should be collapsible, 2 if the second is collapsible. */ collapsePane?: number; /** * A two element array holding the minimum number of pixels for each pane. Use undefined / null if a particular pane has no minimum (in which case a minimum of 1 is applied). */ minPixels?: number[]; /** * 1 if the max value applies to the first pane, 2 if it applies to the second pane. */ maxPane?: number; /** * Either an integer number of pixels or a string ending in % for a percentage. Can also be a function that is passed the available length and returns the number of pixels. */ max?: number | string | PercentValue | ((availableLength: number) => number); /** * 1 if the start size applies to the first pane, 2 if it applies to the second pane. */ startSizePane?: number; /** * An integer pixels, %age of available length or function returning number of pixels when passed the available length. */ startSize?: number | string | PercentValue | ((availableLength: number) => number); /** * The persistence object that this splitter will have its bar positions saved through. */ splitterGroupPersistence?: SplitterGroupPersistence; /** * True if the splitter is not nested within another splitter. */ isTopLevelSplitter?: boolean; /** * The element to force the first pane to reattach to if the splitter is destroyed. */ leftTopParent?: JQuery; /** * The element to force the second pane to reattach to if the splitter is destroyed. */ rightBottomParent?: JQuery; } /** * The event args for the Splitter BarMoved event. */ export interface Splitter_BarMovedEventArgs { splitterElement: JQuery; pane1Length: number; pane2Length: number; barLength: number; } /** * A JQueryUI plugin that adds a splitter with two panes. Splitters can be nested within other splitters. */ export class Splitter extends JQueryUICustomWidget { options: Splitter_Options = { name: undefined, vertical: true, savePane: 1, collapsePane: undefined, minPixels: [ 10, 10 ], maxPane: 0, max: null, startSizePane: 0, startSize: null, splitterGroupPersistence: null, isTopLevelSplitter: false, }; private _getState() : Splitter_State { var result = this.element.data('splitterState'); if(result === undefined) { result = new Splitter_State(); this.element.data('splitterState', result); } return result; } _create() { var options = this.options; var state = this._getState(); var i; if(!options.name) throw 'You must supply a name for the splitter'; state.eventNamespace = 'vrsSplitter-' + options.name; options.max = this.convertMaxOrStartSize(options.maxPane, options.max, 'max'); options.startSize = this.convertMaxOrStartSize(options.startSizePane, options.startSize, 'start size'); if(options.minPixels.length !== 2) throw 'You must pass two integers for minPixels'; if(!options.minPixels[0] || options.minPixels[0] < 1) options.minPixels[0] = 1; if(!options.minPixels[1] || options.minPixels[1] < 1) options.minPixels[1] = 1; this.element .attr('id', 'vrsSplitter-' + options.name) .css({ position: 'absolute', width: '100%', height: '100%', overflow: 'hidden' }); this.element.addClass('vrsSplitter'); var children = this.element.children(); if(children.length !== 2) throw 'A splitter control must have two children'; for(i = 0;i < 2;++i) { var pane = $(children[i]).vrsSplitterPane(<SplitterPane_Options>{ isVertical: options.vertical, minPixels: options.minPixels[i], max: options.maxPane === i + 1 ? <PercentValue>options.max : undefined, startSize: options.startSizePane === i + 1 ? <PercentValue>options.startSize : undefined }); var splitterPane = VRS.jQueryUIHelper.getSplitterPanePlugin(pane); var detail = new SplitterPaneDetail(splitterPane.getContainer()); detail.splitterPane = splitterPane; state.panes.push(detail); } if(VRS.refreshManager) VRS.refreshManager.rebuildRelationships(); state.bar = new SplitterPaneDetail($('<div/>') .insertAfter(state.panes[0].element) .addClass('bar') .addClass(options.vertical ? 'vertical' : 'horizontal') .addClass('movable') .css({ 'z-index': '100', position: 'absolute', 'user-select': 'none', '-webkit-user-select': 'none', '-khtml-user-select': 'none', '-moz-user-select': 'none' }) ); state.bar.element.mousedown($.proxy(this._barMouseDown, this)); state.bar.element.on('touchstart', $.proxy(this._touchStart, this)); state.bar.length = options.vertical ? state.bar.element.outerWidth() : state.bar.element.outerHeight(); if(options.collapsePane) { state.collapseButton = $('<div/>') .addClass('collapse') .addClass(options.vertical ? 'vertical' : 'horizontal') .click($.proxy(this._collapseClicked, this)) .appendTo(state.bar.element); state.bar.element .dblclick($.proxy(this._collapseClicked, this)); this._syncCollapseButtonState(state); } var savedState = null; if(options.splitterGroupPersistence) { savedState = options.splitterGroupPersistence.registerSplitter(this.element); } var availableLength = this._determineAvailableLength(state); if(savedState) { this.applySavedLength(savedState); } else if(options.startSizePane) { var availableLengthWithoutBar = this._determineAvailableLengthWithoutBar(state, availableLength); var paneDetail = state.panes[options.startSizePane - 1]; paneDetail.length = paneDetail.splitterPane.getStartSize(availableLengthWithoutBar); this._moveSplitterToFitPaneLength(state, options.startSizePane - 1, availableLength); this._setPositions(state, availableLength); } else { state.posn = Math.floor(availableLength / 2); this._sizePanesToSplitter(state, availableLength); this._setPositions(state, availableLength); } this._raiseBarMoved(state); if(VRS.refreshManager && state.panes.length >= 2) { VRS.refreshManager.refreshTargets(state.panes[0].element); VRS.refreshManager.refreshTargets(state.panes[1].element); } $(window).on('resize.' + state.eventNamespace, $.proxy(this._windowResized, this)); } _destroy() { var options = this.options; var state = this._getState(); if(state.panes && state.panes.length === 2) { for(var i = 0;i < state.panes.length;++i) { var details = state.panes[i]; var element = details.splitterPane.getContent(); var originalParent = i === 0 ? options.leftTopParent : options.rightBottomParent; var elementIsSplitter = details.splitterPane.getContentIsSplitter(); details.splitterPane.destroy(); if(elementIsSplitter) { element.vrsSplitter('destroy'); } else if(originalParent) { element.appendTo(originalParent); } } state.panes = []; } if(state.bar !== null) { state.bar.element.off(); state.bar.element.remove(); state.bar = null; } $(window).off('resize.' + state.eventNamespace, this._windowResized); this.element.remove(); if(VRS.refreshManager) { VRS.refreshManager.rebuildRelationships(); } } /** * Converts a string / number / function into either a VRS_VALUE_PERCENT or a function that takes a width and returns a number of pixels. */ private convertMaxOrStartSize(paneNumber: number, maxOrStartSize: string | number | PercentValue | ((availableLength: number) => number), description: string) : PercentValue | ((availableLength: number) => number) { var result: PercentValue | ((availableLength: number) => number) = <any>maxOrStartSize; if(paneNumber) { if(!(maxOrStartSize instanceof Function) && (<PercentValue>maxOrStartSize).isPercent === undefined) { var valuePercent = VRS.unitConverter.getPixelsOrPercent(<string | number>maxOrStartSize); if(valuePercent.isPercent && (valuePercent.value < 0.01 || valuePercent.value > 0.99)) throw description + ' percent must be between 1% and 99% inclusive'; result = valuePercent; } } return result; } /** * Gets the name of the splitter. */ getName() : string { return this.options.name; } /** * Gets a value indicating whether the bar is vertical or horizontal. */ getIsVertical() : boolean { return this.options.vertical; } /** * Gets the number of the pane whose dimensions are to be saved. Only one pane is ever saved. */ getSavePane() : number { return this.options.savePane; } /** * Raised when the splitter bar is moved. */ hookBarMoved(callback: (event: Event, data: Splitter_BarMovedEventArgs) => void, forceThis?: Object) : IEventHandleJQueryUI { return VRS.globalDispatch.hookJQueryUIPluginEvent(this.element, 'vrsSplitter', 'barMoved', callback, forceThis); } private _raiseBarMoved(state: Splitter_State) { var panesCount = state.panes.length; this._trigger('barMoved', null, <Splitter_BarMovedEventArgs>{ splitterElement: this.element, pane1Length: panesCount > 0 ? state.panes[0].length : -1, pane2Length: panesCount > 1 ? state.panes[1].length : -1, barLength: state.bar ? state.bar.length : -1 }); } /** * Unhooks an event hooked on the object. */ unhook(hookResult: IEventHandleJQueryUI) { VRS.globalDispatch.unhookJQueryUIPluginEvent(this.element, hookResult); } /** * Returns the current length available to the splitter, within which the panes and bar have to fit. */ private _determineAvailableLength(state: Splitter_State) : number { var result = this.options.vertical ? this.element.width() : this.element.height(); // Each pane has a border applied to it unless that pane contains a splitter. We need to knock the widths // of the border off the available length. if(!state) state = this._getState(); for(var i = 0;i < 2;++i) { if(!state.panes[0].splitterPane.getContentIsSplitter()) result -= 2 * VRS.globalOptions.splitterBorderWidth; } return result; } /** * Returns the length available to the panes, i.e. the overall length minus the bar length. */ private _determineAvailableLengthWithoutBar(state: Splitter_State, availableLength: number) : number { if(!state) state = this._getState(); if(availableLength === undefined) availableLength = this._determineAvailableLength(state); return Math.max(0, availableLength - state.bar.length); } /** * Changes the size of both panes to make them fit flush with the current position of the splitter bar. */ private _sizePanesToSplitter(state: Splitter_State, availableLength: number) { if(availableLength === undefined) availableLength = this._determineAvailableLength(state); var bar = state.bar; var pane0 = state.panes[0]; var pane1 = state.panes[1]; pane0.length = state.posn; pane1.length = availableLength - (pane0.length + bar.length); } /** * Constrains the lengths of the panes to their minimums and maximums. */ private _applyMinMax(state: Splitter_State, availableLength: number) { if(!state) state = this._getState(); if(state.panes.length > 1) { if(availableLength === undefined) availableLength = this._determineAvailableLength(state); var availableWithoutBar = this._determineAvailableLengthWithoutBar(state, availableLength); var moveSplitter = (offsetPixels: number, subtract: boolean) => { offsetPixels = Math.max(0, offsetPixels); if(offsetPixels) { if(subtract) offsetPixels = -offsetPixels; state.posn += offsetPixels; this._sizePanesToSplitter(state, availableLength); } }; for(var i = 1;i >= 0;--i) { var paneDetail = state.panes[i]; var minPixels = paneDetail.splitterPane.getMinPixels(); var maxPixels = paneDetail.splitterPane.getMaxPixels(availableWithoutBar); if(maxPixels) moveSplitter(paneDetail.length - maxPixels, i === 0); if(minPixels) moveSplitter(minPixels - paneDetail.length, i === 1); } } } /** * Sizes the panes to match the saved state passed across. */ applySavedLength(savedState: SplitterGroupPersistence_SplitterSaveState) { var options = this.options; var pane = savedState.pane; var vertical = savedState.vertical; var length = savedState.length; if(options.savePane === pane && options.vertical === vertical) { var state = this._getState(); if(state.panes.length > 1) { state.userSetPosn = true; var paneIndex = pane - 1; state.panes[paneIndex].length = length; var availableLength = this._determineAvailableLength(state); this._moveSplitterToFitPaneLength(state, paneIndex, availableLength); this._setPositions(state, availableLength); } } } /** * Updates the CSS on the panes and bar to move them into position on screen and raises events to let observers * know that the panes have been resized or moved. Returns true if the panes had to be resized, false if there was * no work to do. */ private _setPositions(state: Splitter_State, availableLength: number) : boolean { if(!state) state = this._getState(); if(availableLength === undefined) availableLength = this._determineAvailableLength(state); var collapsed = !!state.collapsedPane; if(!collapsed) this._applyMinMax(state, availableLength); var options = this.options; var bar = state.bar; var pane0 = state.panes[0]; var pane1 = state.panes[1]; var pane0Length = pane0.length; var pane1Length = pane1.length; var barLength = bar.length; var posn = state.posn; if(collapsed) { switch(state.collapsedPane) { case 1: pane0Length = 0; posn = 0; pane1Length += pane0.length; break; case 2: pane0Length += pane1.length; posn = pane0Length; pane1Length = 0; break; } } var pane1Posn = posn + barLength; var result = state.previousPosn !== posn || state.previousPane0Length !== pane0Length || state.previousPane1Length !== pane1Length; if(result) { state.previousPosn = posn; state.previousPane0Length = pane0Length; state.previousPane1Length = pane1Length; var barOffset = pane0Length === 0 ? 0 : pane0.splitterPane.getContentIsSplitter() ? 0 : 2 * VRS.globalOptions.splitterBorderWidth; pane1Posn += barOffset; if(options.vertical) { pane1.element.css({ left: pane1Posn, width: pane1Length }); bar.element.css({ left: posn + barOffset }); pane0.element.css({ width: pane0Length }); } else { pane1.element.css({ top: pane1Posn, height: pane1Length }); bar.element.css({ top: posn + barOffset }); pane0.element.css({ height: pane0Length }); } if(VRS.refreshManager) { if(pane0Length) VRS.refreshManager.refreshTargets(pane0.element); if(pane1Length) VRS.refreshManager.refreshTargets(pane1.element); } this._raiseBarMoved(state); } return result; } /** * Assuming that one pane has the correct length this method adjusts the length of the other pane and the position * of the splitter bar to fill all available room. */ private _moveSplitterToFitPaneLength(state: Splitter_State, fitPaneIndex: number, availableLength?: number) { var pane0 = state.panes[0]; var pane1 = state.panes[1]; var bar = state.bar; if(availableLength === undefined) { availableLength = this._determineAvailableLength(state); } switch(fitPaneIndex) { case 0: state.posn = pane0.length; pane1.length = availableLength - (pane0.length + bar.length); break; case 1: state.posn = availableLength - (bar.length + pane1.length); pane0.length = state.posn; break; default: throw 'Not implemented'; } } /** * Assuming that the elements are in the correct position but the available room has changed, this changes the * lengths of the panes and the splitter position to try to keep both panes occupying the same proportion of * the new available length. */ private _moveSplitterToKeepPaneProportions(state: Splitter_State, availableLength: number) { var options = this.options; var pane0 = state.panes[0]; var pane1 = state.panes[1]; var bar = state.bar; if(availableLength === undefined) availableLength = this._determineAvailableLength(state); var oldAvailableLength = pane0.length + pane1.length + bar.length; if(oldAvailableLength !== availableLength) { var sized = false; if(options.maxPane) { var maxPane = state.panes[options.maxPane - 1]; var availableLengthWithoutBar = this._determineAvailableLengthWithoutBar(state, availableLength); var maxPaneLimit = maxPane.splitterPane.getMaxPixels(availableLengthWithoutBar); if(maxPaneLimit <= maxPane.length) { var otherPane = state.panes[options.maxPane === 1 ? 1 : 0]; maxPane.length = maxPaneLimit; otherPane.length = availableLengthWithoutBar - maxPaneLimit; state.posn = pane0.length; sized = true; } } if(!sized) { var pane0Proportion = pane0.length / oldAvailableLength; pane0.length = oldAvailableLength === 0 ? 1 : Math.floor(0.5 + (availableLength * pane0Proportion)); this._moveSplitterToFitPaneLength(state, 0, availableLength); } } } /** * Modifies the size and positions of the panes to fit into the available length. Returns true if panes * had to be moved as a result. */ private adjustToNewSize(state: Splitter_State) : boolean { if(state === undefined) state = this._getState(); var options = this.options; var availableLength = this._determineAvailableLength(state); var lockedPane = state.userSetPosn ? options.savePane : 0; if(lockedPane) this._moveSplitterToFitPaneLength(state, lockedPane - 1, availableLength); else this._moveSplitterToKeepPaneProportions(state, availableLength); return this._setPositions(state, availableLength); } /** * Updates the collapse button to reflect the collapsed state. */ private _syncCollapseButtonState(state: Splitter_State) { if(!state) state = this._getState(); var options = this.options; var button = state.collapseButton; var collapsed = !!state.collapsedPane; button.removeClass('left right up down'); switch(options.collapsePane) { case 1: if(options.vertical) button.addClass(collapsed ? 'right' : 'left'); else button.addClass(collapsed ? 'down' : 'up'); break; case 2: if(options.vertical) button.addClass(collapsed ? 'left' : 'right'); else button.addClass(collapsed ? 'up' : 'down'); break; } } /** * Called when the user clicks on the splitter bar. */ private _barMouseDown(event: JQueryEventObject) : boolean { return this._startMove(event, true, event.pageX, event.pageY, (state: Splitter_State) => { $(document) .on('mousemove.' + state.eventNamespace, $.proxy(this._documentMouseMove, this)) .on('mouseup.' + state.eventNamespace, $.proxy(this._documentMouseUp, this)); }); } /** * Called when the user touches the splitter bar */ private _touchStart(event: JQueryEventObject) : boolean { event.preventDefault(); var touch = (<TouchEvent>event.originalEvent).touches[0]; return this._startMove(event, false, touch.pageX, touch.pageY, (state: Splitter_State) => { state.bar.element .on('touchmove.' + state.eventNamespace, $.proxy(this._touchMove, this)) .on('touchend.' + state.eventNamespace, $.proxy(this._touchEnd, this)); }); } /** * Does the work for the start move event handlers. */ private _startMove(event: JQueryEventObject, testForLeftButton: boolean, pageX: number, pageY: number, hookMoveAndUp: (state: Splitter_State) => void) : boolean { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var isLeftButton = !testForLeftButton || event.which === 1; var result = !isLeftButton; if(!result) { var options = this.options; var state = this._getState(); state.bar.element.addClass('moving'); state.startMovePosn = state.posn - (options.vertical ? pageX : pageY); hookMoveAndUp.call(this, state); event.stopPropagation(); } return result; } /** * Called when the user moves the mouse after having clicked on the splitter bar. */ private _documentMouseMove(event: JQueryEventObject) : boolean { return this._continueMove(event, event.pageX, event.pageY); } /** * Called when the user moves the mouse after having touched on the splitter bar. */ private _touchMove(event: JQueryEventObject) : boolean { var touch = (<TouchEvent>event.originalEvent).touches[0]; return this._continueMove(event, touch.pageX, touch.pageY); } /** * Does the work for the move events. */ private _continueMove(event: JQueryEventObject, pageX: number, pageY: number) : boolean { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var options = this.options; var state = this._getState(); var availableLength = this._determineAvailableLength(state); state.posn = Math.max(0, Math.min(availableLength, state.startMovePosn + (options.vertical ? pageX : pageY))); this._sizePanesToSplitter(state, availableLength); state.userSetPosn = true; this._setPositions(state, availableLength); event.stopPropagation(); return false; } /** * Called when the user releases the mouse after having clicked on the splitter bar. */ private _documentMouseUp(event: JQueryEventObject) : boolean { return this._stopMove(event, (state: Splitter_State) => { $(document) .off('mousemove.' + state.eventNamespace, this._documentMouseMove) .off('mouseup.' + state.eventNamespace, this._documentMouseUp); }); } /** * Called when the user lifts their finger off a splitter bar. */ private _touchEnd(event: JQueryEventObject) : boolean { return this._stopMove(event, (state: Splitter_State) => { state.bar.element .off('touchmove.' + state.eventNamespace, this._touchMove) .off('touchend.' + state.eventNamespace, this._touchEnd); }); } /** * Does the work for the stop move event handlers. */ private _stopMove(event: JQueryEventObject, unhookMoveAndUp: (state: Splitter_State) => void) : boolean { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var state = this._getState(); state.bar.element.removeClass('moving'); unhookMoveAndUp.call(this, state); event.stopPropagation(); return false; } /** * Called when the browser window is resized. */ private _windowResized() { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var state = this._getState(); this.adjustToNewSize(state); } /** * Called when the collapse button on the bar is clicked. */ private _collapseClicked(event: Event) { if(VRS.timeoutManager) { VRS.timeoutManager.resetTimer(); } var state = this._getState(); state.collapsedPane = state.collapsedPane ? 0 : this.options.collapsePane; this._syncCollapseButtonState(state); this._setPositions(state, this._determineAvailableLength(state)); event.stopPropagation(); return false; } } $.widget('vrs.vrsSplitter', new Splitter()); } declare interface JQuery { vrsSplitterPane(); vrsSplitterPane(options: VRS.SplitterPane_Options); vrsSplitterPane(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); vrsSplitter(); vrsSplitter(options: VRS.Splitter_Options); vrsSplitter(methodName: string, param1?: any, param2?: any, param3?: any, param4?: any); }
the_stack
import { addListeners } from '../../../../../client/addListener' import { ANIMATION_C } from '../../../../../client/animation/ANIMATION_C' import applyStyle from '../../../../../client/applyStyle' import namespaceURI from '../../../../../client/component/namespaceURI' import { Context } from '../../../../../client/context' import { Element } from '../../../../../client/element' import { makeCustomListener } from '../../../../../client/event/custom' import { IOPointerEvent } from '../../../../../client/event/pointer' import { makePointerCancelListener } from '../../../../../client/event/pointer/pointercancel' import { makePointerDownListener } from '../../../../../client/event/pointer/pointerdown' import { makePointerEnterListener } from '../../../../../client/event/pointer/pointerenter' import { makePointerLeaveListener } from '../../../../../client/event/pointer/pointerleave' import { makePointerMoveListener } from '../../../../../client/event/pointer/pointermove' import { makePointerUpListener } from '../../../../../client/event/pointer/pointerup' import { makeResizeListener } from '../../../../../client/event/resize' import { harmonicArray } from '../../../../../client/id' import { randomBetween } from '../../../../../client/math' import { Mode } from '../../../../../client/mode' import { PositionObserver } from '../../../../../client/PositionObserver' import { getThemeModeColor } from '../../../../../client/theme' import { describeEllipseArc, norm, Point, pointDistance, Position, unitVector, } from '../../../../../client/util/geometry' import { Pod } from '../../../../../pod' import { System } from '../../../../../system' import { Dict } from '../../../../../types/Dict' import { IHTMLDivElement } from '../../../../../types/global/dom' import { Unlisten } from '../../../../../types/Unlisten' import { clamp } from '../../../../core/relation/Clamp/f' const HARMONIC = harmonicArray(20) export const DEFAULT_N = 4 export const DEFAULT_K = 4 export const DEFAULT_R = 42 export const DEFAULT_M = 'none' const MOVE_TIMEOUT_MAX = 12 // sec export interface Props { style?: Dict<string> className?: string disabled?: boolean r?: number mode?: Mode x?: number y?: number context?: Context } export const DEFAULT_STYLE = { width: '100%', height: '100%', color: 'current-color', } export default class Bot extends Element<IHTMLDivElement, Props> { private _r: number = 0 private _x: number = 0 private _y: number = 0 private _tx: number = 0 // target x private _ty: number = 0 // target y private _svg: SVGSVGElement private _pointer_position: Dict<Position> = {} private _pointer_down: Dict<boolean> = {} private _pointer_occluded: Dict<boolean> = {} private _pointer_down_count: number = 0 private _pointer_enter_count: number = 0 private _pointer_inside: Dict<boolean> = {} private _pointer_visible: boolean = false private _bot: SVGGElement private _eye_ellipse: SVGEllipseElement[] = [] private _eye_ball: SVGEllipseElement private _eye_brow: SVGPathElement private _laser: Dict<SVGGElement> = {} private _laser_ray: Dict<SVGLineElement> = {} private _laser_focus: Dict<SVGEllipseElement> = {} private _removed: boolean = false private _move_timeout: NodeJS.Timer private _container: IHTMLDivElement private _container_x: number = 0 private _container_y: number = 0 private _container_rx: number = 0 private _container_ry: number = 0 private _container_rz: number = 0 private _container_sx: number = 1 private _container_sy: number = 1 private _move_animation_frame: number | undefined = undefined private _sync_animation_frame: number | undefined = undefined constructor($props: Props, $system: System, $pod: Pod) { super($props, $system, $pod) const { className, style = {}, r = DEFAULT_R, disabled, x = 0, y = 0, } = this.$props const n = DEFAULT_N this._x = x - r - 2 this._y = y - r - 2 const container = this.$system.api.document.createElement('div') applyStyle(container, { ...DEFAULT_STYLE, ...style }) this._container = container const svg = this.$system.api.document.createElementNS(namespaceURI, 'svg') svg.classList.add('bot-svg') if (className) { svg.classList.add(className) } applyStyle(svg, { ...{ position: 'absolute', top: '0', left: '0', stroke: 'currentColor' }, }) this._svg = svg this._bot = this.$system.api.document.createElementNS(namespaceURI, 'g') this._bot.classList.add('eye') for (let i = 0; i < n; i++) { const ellipse = this.$system.api.document.createElementNS( namespaceURI, 'ellipse' ) ellipse.classList.add('eye-ellipse') ellipse.style.fill = `none` ellipse.style.strokeWidth = `1px` this._eye_ellipse.push(ellipse) this._bot.appendChild(ellipse) } this._eye_ball = this.$system.api.document.createElementNS( namespaceURI, 'ellipse' ) this._eye_ball.classList.add('eye-ball') this._bot.appendChild(this._eye_ball) this._eye_brow = this.$system.api.document.createElementNS( namespaceURI, 'path' ) this._eye_brow.classList.add('eye-brow') this._eye_brow.setAttribute('fill', 'none') this._eye_brow.setAttribute('stroke-width', '3') this._bot.appendChild(this._eye_brow) svg.appendChild(this._bot) container.appendChild(svg) this.$element = container this.addEventListener(makePointerEnterListener(this._onPointerEnter)) this.addEventListener(makePointerLeaveListener(this._onPointerLeave)) const position_observer = new PositionObserver( this.$system, ({ x, y, sx, sy, rx, ry, rz }) => { this._container_x = x this._container_y = y this._container_sx = sx this._container_sy = sy this._container_rx = rx this._container_ry = ry this._container_rz = rz } ) // this._tick_body() this._position_observer = position_observer } private _enabled = (): boolean => { const { disabled } = this.$props if (document.visibilityState === 'visible') { if (disabled === undefined) { const { $disabled } = this.$context return !$disabled } else { return !disabled } } else { return false } } private _disabled: boolean = true private _refresh_enabled = (): void => { if (this._enabled()) { this._enable() } else { this._disable() } } private _reset_move_timeout = (offset: number = 0) => { // console.log('Bot', '_reset_move_timeout') if (this._move_timeout) { clearTimeout(this._move_timeout) } const moveTimeoutHandler = () => { this._start_move() this._reset_move_timeout() } this._move_timeout = setTimeout( moveTimeoutHandler, offset + randomBetween(0, MOVE_TIMEOUT_MAX) * 1000 ) } private _enable = () => { if (this._disabled) { // console.log('Bot', '_enable') this._disabled = false this._follow() this._reset_move_timeout(1000) } } private _disable = () => { if (!this._disabled) { // console.log('Bot', '_disable') this._disabled = true if (this._move_timeout) { clearTimeout(this._move_timeout) } this._unfollow() } } private _pointing_self: Dict<boolean> = {} private _pointing_self_count: number = 0 private _synced: boolean = true private _get_pointer_xyz = (): [number, number, number] => { const { $width, $height } = this.$context let x: number = 1 let y: number = 1 let z: number = 0 const center = this._center() as Point let pointer_center = center let pointer_sum_x = 0 let pointer_sum_y = 0 let pointer_count = 0 for (let pointerId in this._pointer_position) { pointer_count++ const p = this._pointer_position[pointerId] const { x, y } = p pointer_sum_x += x pointer_sum_y += y } if (pointer_count > 0 && !this._disabled) { pointer_center = { x: pointer_sum_x / pointer_count, y: pointer_sum_y / pointer_count, } const center = this._center() const d = pointDistance(center, pointer_center) const D = norm($width, $height) const u = unitVector( center.x, center.y, pointer_center.x, pointer_center.y ) x = u.x y = u.y z = Math.min(d, D) / D } return [x, y, z] } private _get_target_xyz = (): [number, number, number] => { if (this._synced) { return this._get_pointer_xyz() } else { return [this._temp_x, this._temp_y, this._temp_z] } } private _temp_x: number = 0 private _temp_y: number = 0 private _temp_z: number = 0 private _tick_body() { const { r = DEFAULT_R } = this.$props const n = DEFAULT_N const k = DEFAULT_K const cX = r + 3 // BORDER const cY = r + 3 let angle: number = 0 const center = this._center() as Point for (let pointerId in this._pointer_position) { const p = this._pointer_position[pointerId] const d = pointDistance({ x: center.x + 3, y: center.y + 3 }, p) if (d > r + 1) { if (this._pointing_self[pointerId]) { this.__onPointerLeave(Number.parseInt(pointerId)) } } else { if (!this._pointing_self[pointerId]) { this.__onPointerEnter(Number.parseInt(pointerId)) } } } const [x, y, z] = this._get_target_xyz() this._temp_x = x this._temp_y = y this._temp_z = z angle = (Math.atan2(y, x) * 180) / Math.PI + 90 if (angle < 0) { angle += 360 } const kx = x * z * (r - 9) const ky = y * z * (r - 9) this._bot.style.transform = `translate(${this._x}px, ${this._y}px)` for (let i = 0; i < n; i++) { const h = HARMONIC[i] const rx = r / (i + 1) const ry = rx * (1 - z / k) const kcx = (h * kx) / k const kcy = (h * ky) / k const cx = cX + (k * kcx) / 2 const cy = cY + (k * kcy) / 2 let ellipse = this._eye_ellipse[i] ellipse.setAttribute('rx', rx.toString()) ellipse.setAttribute('ry', ry.toString()) ellipse.setAttribute('cx', cx.toString()) ellipse.setAttribute('cy', cy.toString()) ellipse.style.transformOrigin = `${cx}px ${cy}px` ellipse.style.transform = `rotate(${angle}deg)` } const hn = HARMONIC[n - 1] const w = this._pointing_self_count > 0 ? 7 : 8 const rx = r / (n + 1) / w const ry = Math.max(rx * (1 - z / k), 1) const kcx = (hn * kx) / k const kcy = (hn * ky) / k const cx = cX + (k * kcx) / 2 const cy = cY + (k * kcy) / 2 this._eye_ball.setAttribute('rx', rx.toString()) this._eye_ball.setAttribute('ry', ry.toString()) this._eye_ball.setAttribute('cx', cx.toString()) this._eye_ball.setAttribute('cy', cy.toString()) this._eye_ball.style.transformOrigin = `${cx}px ${cy}px` this._eye_ball.style.transform = `rotate(${angle}deg)` this._bot.appendChild(this._eye_ball) const startAngle = 300 const stopAngle = 330 this._eye_brow.style.transformOrigin = `${cX}px ${cY}px` this._eye_brow.style.transform = `rotate(${angle}deg)` this._eye_brow.setAttribute( 'd', describeEllipseArc( cX, cY, r + 6, (r + 6) * (1 - z / 2.5), startAngle - (stopAngle - startAngle) / 5, startAngle + (stopAngle - startAngle) / 5 ) ) for (let pointerId in this._laser_position) { const p = this._laser_position[pointerId] let laser = this._laser[pointerId] let laser_ray = this._laser_ray[pointerId] let laser_focus = this._laser_focus[pointerId] if (!laser) { const { mode_color } = this._get_color() laser = this.$system.api.document.createElementNS(namespaceURI, 'g') laser.classList.add('laser') laser_ray = this.$system.api.document.createElementNS( namespaceURI, 'line' ) laser_ray.classList.add('laser-ray') laser_ray.style.stroke = mode_color laser_ray.style.strokeDasharray = '2' laser_ray.style.strokeWidth = '2' laser.appendChild(laser_ray) laser_focus = this.$system.api.document.createElementNS( namespaceURI, 'ellipse' ) laser_focus.classList.add('laser-focus') laser_focus.style.fill = mode_color laser_focus.style.stroke = mode_color laser_focus.style.transformOrigin = '50% 50%' laser_focus.setAttribute('rx', '1') laser_focus.setAttribute('ry', '1') laser.appendChild(laser_focus) this._laser[pointerId] = laser this._laser_focus[pointerId] = laser_focus this._laser_ray[pointerId] = laser_ray this._svg.appendChild(laser) } const lx = p.x const ly = p.y const lxs = lx.toString() const lys = ly.toString() laser_ray.setAttribute('x1', (this._x + cx).toString()) laser_ray.setAttribute('y1', (this._y + cy).toString()) laser_ray.setAttribute('x2', lxs) laser_ray.setAttribute('y2', lys) laser_focus.setAttribute('cx', lxs) laser_focus.setAttribute('cy', lys) } } private _center = (): { x: number; y: number } => { const { r = DEFAULT_R } = this.$props const center = { x: this._x + r, y: this._y + r } return center } public getPosition = (): Position => { return { x: this._x, y: this._y, } } public setPosition = ({ x, y }: Position): void => { this._x = x this._y = y } public setOccluded = (pointerId: number, occluded: boolean): void => { // console.log('Bot', 'setOccluded', pointerId, occluded) if (occluded) { this._pointer_occluded[pointerId] = true } else { delete this._pointer_occluded[pointerId] } } private _start_move = (): void => { if (this._pointing_self_count > 0) { return } const { r = DEFAULT_R } = this.$props const { $width, $height } = this.$context const D = 2 * r + 3 this._tx = randomBetween(3, $width - D) this._ty = randomBetween(3, $height - D) this._move_animation_frame = requestAnimationFrame(this._move_tick) } public _move_tick = (): void => { if (Math.abs(this._x - this._tx) > 1 || Math.abs(this._y - this._ty) > 1) { this._x += (this._tx - this._x) * ANIMATION_C this._y += (this._ty - this._y) * ANIMATION_C this._tick_body() this._move_animation_frame = requestAnimationFrame(this._move_tick) } else { this._move_animation_frame = undefined } } private _start_sync = (): void => { // console.log('Bot', '_start_sync') this._sync_animation_frame = requestAnimationFrame(this._sync_tick) } private _sync_tick = (): void => { if (this._synced) { return } const [tx, ty, tz] = this._get_pointer_xyz() const dx = tx - this._temp_x const dy = ty - this._temp_y const dz = tz - this._temp_z const k = 1 / 100 if (Math.abs(dx) > k || Math.abs(dy) > k || Math.abs(dz) > k) { this._temp_x += dx * ANIMATION_C this._temp_y += dy * ANIMATION_C this._temp_z += dz * ANIMATION_C this._tick_body() this._start_sync() } else { this._synced = true } } private _onPointerEnter = (event: IOPointerEvent) => { // console.log('Bot', '_onPointerEnter') const { pointerId } = event this.__onPointerEnter(pointerId) } private __onPointerEnter = (pointerId: number) => { // console.log('Bot', '__onPointerEnter') this._pointing_self[pointerId] = true this._pointing_self_count++ this._tick_color() } private _onPointerLeave = (event: IOPointerEvent) => { // console.log('Bot', '_onPointerLeave') const { pointerId } = event this.__onPointerLeave(pointerId) } private __onPointerLeave = (pointerId: number): void => { // console.log('Bot', '__onPointerLeave') delete this._pointing_self[pointerId] this._pointing_self_count-- this._tick_color() } private _onContextPointerEnter = (event: IOPointerEvent) => { const { x, y } = this._getXY(event) const { pointerId } = event if (!this._pointer_inside[pointerId]) { // log('Bot', '_onContextPointerEnter', pointerId) this._pointer_inside[pointerId] = true this._pointer_enter_count++ this._pointer_position[pointerId] = { x, y } this._pointer_visible = this._pointer_enter_count > 0 if (this._synced) { this._synced = false this._start_sync() } this._tick_body() } } private _onContextPointerLeave = (event: IOPointerEvent) => { const { pointerId } = event // log('Bot', '_onContextPointerLeave', pointerId) this.__onContextPointerLeave(event) } private __onContextPointerLeave = (event: IOPointerEvent) => { const { $width, $height } = this.$context const { pointerId } = event if (this._pointer_inside[pointerId]) { // log('Bot', '__onContextPointerLeave', pointerId) this._pointer_enter_count-- if (this._pointer_down[pointerId]) { this._remove_pointer_down(event) } const position = this._pointer_position[pointerId] delete this._pointer_inside[pointerId] delete this._pointer_position[pointerId] this._removePointerLaser(pointerId) this._pointer_visible = this._pointer_enter_count > 0 if (this._synced) { if (!this._pointer_visible) { this._synced = false this._start_sync() } } this._tick_body() } } private _onContextPointerCancel = (event: IOPointerEvent) => { const { pointerId } = event // console.log('Bot', '_onContextPointerCancel', pointerId) this.__onContextPointerLeave(event) } private _onContextPointerMove = (event: IOPointerEvent) => { // console.log('Bot', '_onContextPointerMove') const position = this._getXY(event) const { pointerId } = event // if (this._pointer_inside[pointerId]) { this._pointer_position[pointerId] = position if (this._pointer_down[pointerId]) { this._laser_position[pointerId] = position } this._pointer_visible = this._pointer_enter_count > 0 this._tick_body() // } } private _getXY = (event: IOPointerEvent): Position => { // const { $x, $y, $sx, $sy, $rx, $ry, $rz } = this.$context const { screenX, screenY } = event const rz_cos = Math.cos(-this._container_rz) const rz_sin = Math.sin(-this._container_rz) const sx = (screenX - this._container_x) / this._container_sx const sy = (screenY - this._container_y) / this._container_sy const x = sx * rz_cos - sy * rz_sin const y = sx * rz_sin + sy * rz_cos return { x, y } } private _onContextPointerDown = (event: IOPointerEvent) => { const { pointerId } = event if (!this._pointer_down[pointerId]) { // log('Bot', '_onContextPointerDown', pointerId) const position = this._getXY(event) this._pointer_down_count++ this._pointer_down[pointerId] = true this._pointer_inside[pointerId] = true this._pointer_position[pointerId] = position this._laser_position[pointerId] = position this._tick_body() } } private _laser_position: Position[] = [] private _remove_pointer_down = (event: IOPointerEvent): void => { // log('Bot', '_remove_pointer_down') const { mode } = this.$props const { pointerId, pointerType } = event this._pointer_down_count-- delete this._pointer_down[pointerId] // AD HOC // https://bugs.chromium.org/p/chromium/issues/detail?id=1147674 if (pointerType === 'touch' || pointerType === 'pen') { delete this._pointer_position[pointerId] } const remove_laser = () => { if (!this._pointer_down[pointerId]) { this._removePointerLaser(pointerId) this._tick_body() } } setTimeout(() => { remove_laser() }, 90) } private _onContextPointerUp = (event: IOPointerEvent) => { const { pointerId } = event if (this._pointer_down[pointerId]) { // log('Bot', '_onContextPointerUp', pointerId) this._remove_pointer_down(event) } } private _removePointerLaser = (pointerId: number): void => { const laser = this._laser[pointerId] if (laser) { // log('Bot', '_removePointerLaser', pointerId) this._svg.removeChild(laser) delete this._laser_position[pointerId] delete this._laser[pointerId] delete this._laser_focus[pointerId] delete this._laser_ray[pointerId] } } private _width: number = 0 private _height: number = 0 private _onContextResize = () => { // console.log('Bot', '_onContextResize') const { $width, $height } = this.$context this._resizeSVG() this._translate() this._width = $width this._height = $height if (this._enabled()) { this._reset_move_timeout() } } private _resizeSVG = () => { const { $width, $height } = this.$context this._svg.setAttribute('width', `${$width}`) this._svg.setAttribute('height', `${$height}`) } private _translate = () => { // console.count('_translate') const { $width, $height } = this.$context const { r = DEFAULT_R } = this.$props const dw = $width - this._width const dh = $height - this._height const dx = dw / 2 const dy = dh / 2 this._x += dx this._y += dy // console.log(dx, dy) const P = 3 const D = 2 * r + P this._x = clamp(this._x, P, $width - D) this._y = clamp(this._y, P, $height - D) this._tick_body() } private _onContextEnabled = (): void => { // console.log('Bot', '_onContextEnabled') this._refresh_enabled() } private _onContextDisabled = (): void => { // console.log('Bot', '_onContextDisabled') this._refresh_enabled() } private _unlisten_context: Unlisten private _following = false public _follow = (): void => { // console.log('Bot', '_follow') if (this._following) { return } this._following = true const pointerDownListener = makePointerDownListener( this._onContextPointerDown, true ) const pointerUpListener = makePointerUpListener( this._onContextPointerUp, true ) const pointerMoveListener = makePointerMoveListener( this._onContextPointerMove, true ) const pointerEnterListener = makePointerEnterListener( this._onContextPointerEnter, true ) const pointerLeaveListener = makePointerLeaveListener( this._onContextPointerLeave, true ) const pointerCancelListener = makePointerCancelListener( this._onContextPointerCancel, true ) // const enterModeListener = makeCustomListener( // 'entermode', // ({ mode }) => { // console.log('Bot', '_on_enter_mode') // this.setProp('mode', mode) // }, // true // ) const graphEnterModeListener = makeCustomListener( '_graph_mode', ({ mode }) => { // console.log('Bot', '_on_graph_enter_mode') this.setProp('mode', mode) }, true ) this._unlisten_context = addListeners(this.$context, [ pointerDownListener, pointerUpListener, pointerMoveListener, pointerEnterListener, pointerLeaveListener, pointerCancelListener, // enterModeListener, graphEnterModeListener, ]) } private _get_color = (): { color: string; mode_color: string } => { const { $theme, $color } = this.$context const { style = {}, mode = DEFAULT_M } = this.$props const { color = $color } = style const mode_color = getThemeModeColor($theme, mode, color) return { color, mode_color } } private _tick_color = (): void => { // console.log('Bot', '_tick_color') const { mode = DEFAULT_M } = this.$props const { color, mode_color } = this._get_color() for (let i = 0; i < this._eye_ellipse.length; i++) { const eye_ellipse = this._eye_ellipse[i] if ( // this._pointing_self_count > 0 false ) { eye_ellipse.style.stroke = mode_color } else { eye_ellipse.style.stroke = color } } this._eye_brow.style.stroke = mode_color this._eye_ball.style.fill = mode_color this._eye_ball.style.stroke = mode_color for (const pointerId in this._laser_focus) { const laser_focus = this._laser_focus[pointerId] const laser_ray = this._laser_ray[pointerId] laser_focus.style.fill = mode_color laser_focus.style.stroke = mode_color laser_ray.style.stroke = mode_color } } public _unfollow = (): void => { if (!this._following) { return } // console.log('Bot', '_unfollow') this._following = false const unlisten = this._unlisten_context unlisten() } private _context_unlisten: Unlisten private _document_listener: Unlisten private _position_observer: PositionObserver onMount() { // console.log('Bot', 'onMount') const { $width, $height } = this.$context const { r = DEFAULT_R, x, y } = this.$props if (x === undefined) { this._x = $width / 2 - r - 2 } if (y === undefined) { this._y = $height / 2 - r - 2 } this._width = $width this._height = $height this._tick_color() this._tick_body() this._refresh_enabled() this._document_listener = () => { this._refresh_enabled() } document.addEventListener( 'visibilitychange', this._document_listener, false ) this._context_unlisten = addListeners(this.$context, [ makeResizeListener(this._onContextResize), makeCustomListener('enabled', this._onContextEnabled), makeCustomListener('themechanged', () => { // console.log('Bot', '_on_context_theme_changed') this._tick_color() }), makeCustomListener('colorchanged', () => { // console.log('Bot', '_on_context_theme_changed') this._tick_color() }), ]) this._resizeSVG() this._position_observer.observe(this._container) } onUnmount($context: Context): void { // console.log('Bot', 'onUnmount') const {} = $context this._disable() this._context_unlisten() if (this._move_animation_frame !== undefined) { cancelAnimationFrame(this._move_animation_frame) this._move_animation_frame = undefined } for (const pointerId in this._pointer_down) { this._removePointerLaser(Number.parseInt(pointerId)) } this._pointer_position = {} this._pointer_down = {} this._pointer_occluded = {} this._pointer_down_count = 0 this._pointer_enter_count = 0 this._pointer_inside = {} this._pointer_visible = false document.removeEventListener('visibilitychange', this._document_listener) this._position_observer.disconnect() } onPropChanged(prop: string, current: any) { // console.log('Bot', prop, current) if (prop === 'style') { applyStyle(this._container, { ...DEFAULT_STYLE, ...current }) this._tick_color() } if (prop === 'disabled') { this._refresh_enabled() } else if (prop === 'mode') { // this._tick_body() this._tick_color() } else if (prop === 'n') { this._tick_body() } else if (prop === 'r') { const prev = this._r || DEFAULT_R current = current || DEFAULT_R this._x += prev - current this._y += prev - current this._tick_body() } else if (prop === 'x') { const { r = DEFAULT_R } = this.$props this._x = current - r - 2 this._tick_body() } else if (prop === 'y') { const { r = DEFAULT_R } = this.$props this._y = current - r - 2 this._tick_body() } } }
the_stack
import { Smithchart, ISmithchartLoadedEventArgs } from '../../../src/smithchart/index'; import { createElement, remove } from '@syncfusion/ej2-base'; import {profile , inMB, getMemoryProfile} from '../../common.spec'; /** * Title spec */ describe('Smithchart title properties tesing', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); describe('Title testing', () => { let id: string = 'title'; let smithchart: Smithchart; let ele: HTMLDivElement; let spec: Element; beforeAll(() => { ele = <HTMLDivElement>createElement('div', { id: id, styles: 'height: 512px; width: 512px;' }); document.body.appendChild(ele); smithchart = new Smithchart({ title: { visible: true, text : 'Transmission lines applied for both impedance and impedance', subtitle: { visible: true } } }, '#' + id); }); afterAll(() => { remove(ele); smithchart.destroy(); }); it('Checking size as null', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_svg'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.width = null; smithchart.height = null; smithchart.refresh(); }); it('Checking size in percentage', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_svg'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.width = '50%'; smithchart.height = '100%'; smithchart.refresh(); }); it('Checking size with onPropertyChanged', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_svg'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.width = '500'; smithchart.height = '500'; smithchart.dataBind(); }); it('Checking border with onPropertyChanged', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_svg'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.border.width = 2; smithchart.dataBind(); }); it('Checking background with onPropertyChanged', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_svg'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.background = ''; smithchart.dataBind(); }); it('Checking title element', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.text = 'Transmission lines applied for both impedance and impedance'; smithchart.title.visible = true; smithchart.refresh(); }); it('Checking title element with description', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.text = 'Transmission lines applied for both impedance and impedance'; smithchart.title.description = 'It represents the smithchart title'; smithchart.title.visible = true; smithchart.refresh(); }); it('Checking sub-title element', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(2); }; smithchart.title.subtitle.text = 'Smithchart subtitle'; smithchart.title.subtitle.visible = true; smithchart.refresh(); }); it('Checking sub-title element with description', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(2); }; smithchart.title.subtitle.text = 'Smithchart subtitle'; smithchart.title.subtitle.description = 'It represents the smithchart subtitle'; smithchart.title.subtitle.visible = true; smithchart.refresh(); }); it('Title alignment as Near', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.textAlignment = 'Near'; smithchart.refresh(); }); it('Title alignment as Center', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.textAlignment = 'Center'; smithchart.refresh(); }); it('Title alignment as Far', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.textAlignment = 'Far'; smithchart.refresh(); }); it('Title alignment as Near - set enableTrim as True - set maximumWidth', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.textAlignment = 'Near'; smithchart.title.enableTrim = true; smithchart.title.maximumWidth = 100; smithchart.refresh(); }); it('Title alignment as Center - set enableTrim as True - set maximumWidth', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.textAlignment = 'Center'; smithchart.title.enableTrim = true; smithchart.title.maximumWidth = 100; smithchart.refresh(); }); it('Title alignment as Center - set enableTrim as True - set maximum width as 250', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.textAlignment = 'Center'; smithchart.title.enableTrim = true; smithchart.title.text = 'SmithchartTitle'; smithchart.title.maximumWidth = 200; smithchart.refresh(); }); it('Title alignment as Far - set enableTrim as True - set maximumWidth', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.textAlignment = 'Far'; smithchart.title.enableTrim = true; smithchart.title.maximumWidth = 100; smithchart.refresh(); }); it('SubTitle alignment as Near', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.subtitle.textAlignment = 'Near'; smithchart.refresh(); }); it('SubTitle alignment as Far', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.subtitle.textAlignment = 'Far'; smithchart.refresh(); }); it('SubTitle alignment as Center', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.subtitle.textAlignment = 'Center'; smithchart.refresh(); }); it('SubTitle alignment as Near - set enableTrim as True - set maximumWidth', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.subtitle.textAlignment = 'Near'; smithchart.title.subtitle.enableTrim = true; smithchart.title.subtitle.maximumWidth = 50; smithchart.refresh(); }); it('SubTitle alignment as Far - set enableTrim as True - set maximumWidth', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.subtitle.textAlignment = 'Far'; smithchart.title.subtitle.enableTrim = true; smithchart.title.subtitle.maximumWidth = 50; smithchart.refresh(); }); it('SubTitle alignment as Center - set enableTrim as True - set maximumWidth', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.title.subtitle.textAlignment = 'Center'; smithchart.title.subtitle.enableTrim = true; smithchart.title.subtitle.maximumWidth = 50; smithchart.refresh(); }); it('Checking border width for smithchart', () => { smithchart.loaded = (args: ISmithchartLoadedEventArgs) => { let element: Element = document.getElementById(smithchart.element.id + '_Title_Group'); expect(element.childElementCount).toBeGreaterThanOrEqual(1); }; smithchart.border.width = 2; smithchart.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); });
the_stack
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { Type } from '@angular/core'; import { discardPeriodicTasks, fakeAsync, flush, TestBed, tick, waitForAsync, } from '@angular/core/testing'; import { AuthService } from '@spartacus/core'; import { cold } from 'jasmine-marbles'; import { BehaviorSubject, Observable, of, Subject } from 'rxjs'; import { take } from 'rxjs/operators'; import { CpqAccessData } from './cpq-access-data.models'; import { CpqAccessLoaderService } from './cpq-access-loader.service'; import { CpqAccessStorageService } from './cpq-access-storage.service'; import { CpqConfiguratorAuthConfig } from './cpq-configurator-auth.config'; import { defaultCpqConfiguratorAuthConfig } from './default-cpq-configurator-auth.config'; import createSpy = jasmine.createSpy; const oneHour: number = 1000 * 60; const accessData: CpqAccessData = { accessToken: 'validToken', endpoint: 'https://cpq', accessTokenExpirationTime: Date.now() + oneHour, }; const anotherAccessData: CpqAccessData = { accessToken: 'anotherValidToken', endpoint: 'https://cpq', accessTokenExpirationTime: Date.now() + oneHour, }; const expiredAccessData: CpqAccessData = { accessToken: 'expiredToken', endpoint: 'https://cpq', accessTokenExpirationTime: Date.now() - oneHour, }; const accessDataSoonExpiring: CpqAccessData = { accessToken: 'validTokenSoonExpiring', endpoint: 'https://cpq', accessTokenExpirationTime: 0, }; let accessDataObs: Observable<CpqAccessData>; let authDataObs: Observable<Boolean>; let accessDataSubject: Subject<CpqAccessData>; let authDataSubject: Subject<Boolean>; let httpBehaviour = true; class CpqAccessLoaderServiceMock { getCpqAccessData = createSpy().and.callFake(() => { return httpBehaviour ? accessDataObs.pipe(take(1)) : accessDataObs; }); } class AuthServiceMock { isUserLoggedIn = createSpy().and.callFake(() => authDataObs); } const TIME_UNTIL_TOKEN_EXPIRES = 60000; // one minute describe('CpqAccessStorageService', () => { let serviceUnderTest: CpqAccessStorageService; let cpqAccessLoaderService: CpqAccessLoaderService; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ { provide: CpqAccessLoaderService, useClass: CpqAccessLoaderServiceMock, }, { provide: CpqConfiguratorAuthConfig, useValue: defaultCpqConfiguratorAuthConfig, }, { provide: AuthService, useClass: AuthServiceMock, }, ], }); serviceUnderTest = TestBed.inject( CpqAccessStorageService as Type<CpqAccessStorageService> ); cpqAccessLoaderService = TestBed.inject( CpqAccessLoaderService as Type<CpqAccessLoaderService> ); accessDataSoonExpiring.accessTokenExpirationTime = Date.now() + TIME_UNTIL_TOKEN_EXPIRES; accessDataObs = accessDataSubject = new Subject<CpqAccessData>(); authDataObs = authDataSubject = new BehaviorSubject<Boolean>(true); httpBehaviour = true; }) ); afterEach(() => { authDataSubject.next(false); // stops the auto pulling of access data }); it('should create service', () => { expect(serviceUnderTest).toBeDefined(); }); it('should return access data', () => { accessDataObs = of(accessData); takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBeDefined(); expect(returnedData.accessToken).toEqual(accessData.accessToken); expect(returnedData.accessTokenExpirationTime).toEqual( accessData.accessTokenExpirationTime ); expect(returnedData.endpoint).toEqual(accessData.endpoint); }); }); it('should cache access data', () => { let counter = 0; // first request takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBeDefined(); counter++; }); // second request, while first is in progress () takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBeDefined(); counter++; }); // fulfill first request accessDataSubject.next(accessData); // third request takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBeDefined(); counter++; }); expect(counter).toBe(3); }); it('should not return access data if token is expired', fakeAsync(() => { accessDataObs = accessDataSubject = new BehaviorSubject<CpqAccessData>( expiredAccessData ); let hasCpqAccessDataEmitted = false; serviceUnderTest.getCpqAccessData().subscribe(() => { hasCpqAccessDataEmitted = true; }); discardPeriodicTasks(); expect(hasCpqAccessDataEmitted).toBe(false); })); it('should do only one additional call when expired token is emitted followed by valid one', fakeAsync(() => { const subscription = serviceUnderTest.getCpqAccessData().subscribe(); subscription.add(serviceUnderTest.getCpqAccessData().subscribe()); subscription.add(serviceUnderTest.getCpqAccessData().subscribe()); subscription.add(serviceUnderTest.getCpqAccessData().subscribe()); accessDataSubject.next(expiredAccessData); accessDataSubject.next(accessData); tick(TIME_UNTIL_TOKEN_EXPIRES); expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes(2); subscription.unsubscribe(); discardPeriodicTasks(); })); it('should accept token that soon expires', (done) => { takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessDataSoonExpiring); done(); }); accessDataSubject.next(accessDataSoonExpiring); }); it('should not return emissions with tokens that are not valid at all', () => { httpBehaviour = false; accessDataObs = cold('--yxx', { x: accessData, y: expiredAccessData }); const expectedObs = cold('---xx', { x: accessData }); expect(serviceUnderTest.getCpqAccessData()).toBeObservable(expectedObs); }); it('should trigger new call if token expires over time', fakeAsync(() => { takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessDataSoonExpiring); }); accessDataSubject.next(accessDataSoonExpiring); tick(TIME_UNTIL_TOKEN_EXPIRES); takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessData); }); accessDataSubject.next(accessData); discardPeriodicTasks(); })); it('should use only one publication for multiple observables after cache refresh', fakeAsync(() => { takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessDataSoonExpiring); }); const existingObs = takeOneCpqAccessData(); existingObs.subscribe((returnedData) => { expect(returnedData).toBe(accessDataSoonExpiring); expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes(1); }); accessDataSubject.next(accessDataSoonExpiring); tick(TIME_UNTIL_TOKEN_EXPIRES); takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessData); existingObs.subscribe((data) => { expect(data).toBe(accessData); //We expect one more call to the backend as token expired expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes( 2 ); }); }); accessDataSubject.next(accessData); discardPeriodicTasks(); })); it('should cancel refresh of expired token on user log out', fakeAsync(() => { takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessDataSoonExpiring); }); accessDataSubject.next(accessDataSoonExpiring); authDataSubject.next(false); tick(TIME_UNTIL_TOKEN_EXPIRES); accessDataSubject.next(anotherAccessData); expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes(1); discardPeriodicTasks(); })); it('should fetch new token after logoff/login cycle', fakeAsync(() => { takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessDataSoonExpiring); }); accessDataSubject.next(accessDataSoonExpiring); authDataSubject.next(false); tick(TIME_UNTIL_TOKEN_EXPIRES); serviceUnderTest.getCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(anotherAccessData); //We expect one more call to the backend as token expired expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes(2); }); accessDataSubject.next(accessData); // nobody should receive this, as user is logged off flush(); authDataSubject.next(true); accessDataSubject.next(anotherAccessData); discardPeriodicTasks(); })); it('should get new token after refresh', (done) => { const obs = takeOneCpqAccessData(); accessDataSubject.next(accessData); serviceUnderTest.renewCpqAccessData(); accessDataSubject.next(anotherAccessData); obs.subscribe((returnedData) => { expect(returnedData).toBe(anotherAccessData); expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes(2); done(); }); }); it('should not emit old token after refresh anymore', fakeAsync(() => { const obs = takeOneCpqAccessData(); accessDataSubject.next(accessData); serviceUnderTest.renewCpqAccessData(); obs.subscribe((returnedData) => { expect(returnedData).toBe(anotherAccessData); expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes(2); }); flush(); accessDataSubject.next(anotherAccessData); discardPeriodicTasks(); })); it('should not fail on refresh when not initialized', (done) => { serviceUnderTest.renewCpqAccessData(); takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessData); expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes(1); done(); }); accessDataSubject.next(accessData); }); it('should only refresh when user is logged in', (done) => { //make sure obs is initiated (in contrast to previous test) const obs = serviceUnderTest.getCpqAccessData(); accessDataSubject.next(accessData); authDataSubject.next(false); serviceUnderTest.renewCpqAccessData(); accessDataSubject.next(anotherAccessData); obs.subscribe((returnedData) => { expect(returnedData).toBe(accessData); expect(cpqAccessLoaderService.getCpqAccessData).toHaveBeenCalledTimes(2); done(); }); authDataSubject.next(true); accessDataSubject.next(accessData); }); it('should be able to still fetch new access data after error', () => { takeOneCpqAccessData().subscribe( () => { fail('should throw an error'); }, (error) => { expect(error).toBeDefined(); accessDataObs = of(accessData); takeOneCpqAccessData().subscribe((returnedData) => { expect(returnedData).toBe(accessData); }); } ); accessDataSubject.error('fail'); }); describe('fetchNextTokenIn', () => { it('should throw error in case auth configuration is incomplete', () => { serviceUnderTest['config'].productConfigurator.cpq = undefined; expect(() => serviceUnderTest['fetchNextTokenIn'](accessData) ).toThrowError(); }); }); describe('isTokenExpired', () => { it('should throw error in case auth configuration is incomplete', () => { serviceUnderTest['config'].productConfigurator.cpq = undefined; expect(() => serviceUnderTest['isTokenExpired'](accessData) ).toThrowError(); }); }); function takeOneCpqAccessData(): Observable<CpqAccessData> { return serviceUnderTest.getCpqAccessData().pipe(take(1)); } });
the_stack
import 'reflect-metadata'; import {Rule, RuleResult, RuleTarget} from '../../../src/types'; import path = require('path'); import {expect} from 'chai'; import {RetireJsEngine, RetireJsInvocation} from '../../../src/lib/retire-js/RetireJsEngine' import * as TestOverrides from '../../test-related-lib/TestOverrides'; import { CUSTOM_CONFIG } from '../../../src/Constants'; TestOverrides.initializeTestSetup(); function getInvertedAliasMap(engine: RetireJsEngine): Map<string,string> { const invertedMap: Map<string,string> = new Map(); const originalMap: Map<string,string> = (engine as any).originalFilesByAlias; for (const [key, value] of originalMap.entries()) { invertedMap.set(value, key); } return invertedMap; } describe('RetireJsEngine', () => { let testEngine: RetireJsEngine; beforeEach(async () => { testEngine = new RetireJsEngine(); await testEngine.init(); }); describe('createTmpDirWithDuplicatedTargets()', () => { describe('Text files', () => { // ============= TEST SETUP ============== // Create a target that simulates a glob matching two JS files. const globPaths = [ path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-a', 'jquery-3.1.0.js'), path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-b', 'jquery-3.5.1.js') ]; const globTarget: RuleTarget = { target: path.join('.', 'test', 'code-fixtures', 'projects', 'dep-test-app', '**', 'jquery*.js'), paths: globPaths }; // Create a target that simulates matching an entire directory containing some JS files. const dirPaths = [ path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-c', 'Burrito.js'), path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-c', 'Taco.js') ]; const dirTarget: RuleTarget = { target: path.join('.', 'test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-c'), isDirectory: true, paths: dirPaths }; // Create a target that simulates matching a single JS file directly. const filePaths = [ path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-d', 'OrangeChicken.js') ]; const fileTarget: RuleTarget = { target: path.join('.', 'test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-d', 'OrangeChicken.js'), paths: filePaths }; // Create a target that simulates matching a directory full of .resource files. const resourcePaths = [ path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-e', 'JsStaticResource1.resource'), path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-e', 'JsStaticResource2.resource'), // Even though this resource is an HTML file instead of a JS file, we still expect it to be duplicated // because it's still a text file. path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-e', 'HtmlStaticResource1.resource'), ]; const resourceTarget: RuleTarget = { target: path.join('.', 'test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-e'), isDirectory: true, paths: resourcePaths }; // Create a target that simulates matching a directory containing a bunch of files with weird/absent extensions, // but corresponding .resource-meta.xml files denoting them as static resources. const implicitResourcePaths = [ path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-g', 'JsResWithOddExt.foo'), path.resolve('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-g', 'JsResWithoutExt') ]; const implicitResourceTarget: RuleTarget = { target: path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-g'), isDirectory: true, paths: implicitResourcePaths }; // Put all of our targets into an array. const targets: RuleTarget[] = [globTarget, dirTarget, fileTarget, resourceTarget, implicitResourceTarget]; it('Files with a .js extension are duplicated', async () => { // ================= INVOCATION OF TEST METHOD ============ await (testEngine as any).createTmpDirWithDuplicatedTargets(targets); // ================ ASSERTIONS ================ // Create an array of the files we're looking for, and a set of all the files that were aliased. const expectedDupedFiles: string[] = [...globPaths, ...dirPaths, ...filePaths]; const actualDupedFiles: Set<string> = new Set([...(testEngine as any).originalFilesByAlias.values() as string[]]); expectedDupedFiles.forEach((expectedFile) => { expect(actualDupedFiles.has(expectedFile)).to.equal(true, `JS file ${expectedFile} was not duplicated`); expect(getInvertedAliasMap(testEngine).get(expectedFile).endsWith('.js')).to.equal(true, 'Alias should end in .js'); }); }); it('Files with a .resource extension are duplicated and given a .js alias', async () => { // ================= INVOCATION OF TEST METHOD ============ await (testEngine as any).createTmpDirWithDuplicatedTargets(targets); // ================ ASSERTIONS ================ // Create an array of the files we're looking for, and a set of all the files that were aliased. const expectedDupedFiles: string[] = resourcePaths; const actualDupedFiles: Set<string> = new Set([...(testEngine as any).originalFilesByAlias.values() as string[]]); expectedDupedFiles.forEach((expectedFile) => { expect(actualDupedFiles.has(expectedFile)).to.equal(true, `Explicit resource file ${expectedFile} was not duplicated`); expect(getInvertedAliasMap(testEngine).get(expectedFile).endsWith('.js')).to.equal(true, 'Alias should end in .js'); }); }); it('Files accompanied by a .resource-meta.xml file are duplicated and given a .js alias', async () => { // ================= INVOCATION OF TEST METHOD ============ await (testEngine as any).createTmpDirWithDuplicatedTargets(targets); // ================ ASSERTIONS ================ // Create an array of the files we're looking for, and a set of all the files that were aliased. const expectedDupedFiles: string[] = implicitResourcePaths; const actualDupedFiles: Set<string> = new Set([...(testEngine as any).originalFilesByAlias.values() as string[]]); expectedDupedFiles.forEach((expectedFile) => { expect(actualDupedFiles.has(expectedFile)).to.equal(true, `Implicit resource file ${expectedFile} was not duplicated`); expect(getInvertedAliasMap(testEngine).get(expectedFile).endsWith('.js')).to.equal(true, 'Alias should end in .js'); }); }); }); describe('Binary files', () => { // ===================== TEST SETUP ========= // Create a target that simulates a glob matching a bunch of different ZIPs, all of which were generated // from the same contents. Crucially, this ZIP has no directories within it; its structure is totally flat. const flatZipPaths = [ path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-f', 'ZipFile.zip'), path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-f', 'ZipFileAsResource.resource'), path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-f', 'ZipFileWithNoExt'), path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-f', 'ZipFileWithOddExt.foo') ]; const flatZipTarget: RuleTarget = { target: path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-f', 'ZipFile*'), paths: flatZipPaths }; // Create a target that simulates directly matching a ZIP. Crucially, this ZIP has directories, some of which // are empty, and others are not. const verticalZipPaths = [ path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-h', 'ZipWithDirectories.zip') ]; const verticalZipTarget: RuleTarget = { target: path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-h', '*.zip'), paths: verticalZipPaths }; // Create a target that simulates a glob matching a bunch of image files. const imgPaths = [ path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-f', 'ImageFileAsResource.resource'), path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-f', 'ImageFileWithNoExt'), path.join('test', 'code-fixtures', 'projects', 'dep-test-app', 'folder-f', 'ImageFileWithOddExt.foo') ]; const imgTarget: RuleTarget = { target: path.join('test', 'code-fixtures', 'project', 'dep-test-app', 'folder-f', 'ImageFile*'), paths: imgPaths }; const targets: RuleTarget[] = [flatZipTarget, verticalZipTarget, imgTarget]; it('ZIPs are extracted, and text files within are aliased', async () => { // ================= INVOCATION OF TEST METHOD ============ await (testEngine as any).createTmpDirWithDuplicatedTargets(targets); // ================ ASSERTIONS ================ const flatZipContents = [ 'HtmlFile.html', 'HtmlFileWithOddExt.foo', 'HtmlFileWithoutExt', 'JsFile.js', 'JsFileWithOddExt.foo', 'JsFileWithoutExt' ]; // Paths within a ZIP are normalized to UNIX. const verticalZipContents = [ 'FilledParentFolder/ChildFolderWithText/JsFile.js', 'FilledParentFolder/ChildFolderWithText/JsFileWithOddExt.foo', 'FilledParentFolder/ChildFolderWithText/JsFileWithoutExt' ]; const actualDupedFiles = new Set([...(testEngine as any).originalFilesByAlias.values() as string[]]); // For each of the flat ZIPs... for (const zipPath of flatZipPaths) { // Verify that the ZIP was extracted. expect((testEngine as any).zipDstByZipSrc.has(zipPath)).to.equal(true, `Zip file ${zipPath} should have been extracted`); // Verify that all of the expected files in the zip were aliased. for (const expectedFile of flatZipContents) { const fullPath = `${zipPath}:${expectedFile}`; expect(actualDupedFiles.has(fullPath)).to.equal(true, `Zip contents ${fullPath} should be aliased`); } } // For the vertical ZIPs... for (const zipPath of verticalZipPaths) { // Verify that the ZIP was extracted. expect((testEngine as any).zipDstByZipSrc.has(zipPath)).to.equal(true, `Zip file ${zipPath} should have been extracted`); // Verify that all of the expected files in the zip were aliased. for (const expectedFile of verticalZipContents) { const fullPath = `${zipPath}:${expectedFile}`; expect(actualDupedFiles.has(fullPath)).to.equal(true, `Zip contents ${fullPath} should be aliased`); } } }); it('Non-ZIP binary files are ignored', async () => { // ================= INVOCATION OF TEST METHOD ============ await (testEngine as any).createTmpDirWithDuplicatedTargets(targets); // ================ ASSERTIONS ================ // Verify that none of the images were treated as zips. for (const imgPath of imgPaths) { expect((testEngine as any).zipDstByZipSrc.has(imgPath)).to.equal(false, `Extraction should not be attempted on image file ${imgPath}`); } }); }); }); describe('processOutput()', () => { it('Properly dealiases and processes results from files', async () => { // First, we need to seed the test engine with some fake aliases. const firstOriginal = path.join('first', 'unimportant', 'path', 'jquery-3.1.0.js'); const firstAlias = path.join('first', 'unimportant', 'alias', 'jquery-3.1.0.js'); const secondOriginal = path.join('first', 'unimportant', 'path', 'angular-scenario.js'); const secondAlias = path.join('first', 'unimportant', 'alias', 'angular-scenario.js'); (testEngine as any).originalFilesByAlias.set(firstAlias, firstOriginal); (testEngine as any).originalFilesByAlias.set(secondAlias, secondOriginal); // Next, we want to spoof some output that looks like it came from RetireJS. const fakeRetireOutput = { "version": "2.2.2", "data": [{ "file": firstAlias, "results": [{ "version": "3.1.0", "component": "jquery", "vulnerabilities": [{ "severity": "low" }, { "severity": "medium" }, { "severity": "medium" }] }] }, { "file": secondAlias, "results": [{ "version": "1.10.2", "component": "jquery", "vulnerabilities": [{ "severity": "high" }, { "severity": "medium" }, { "severity": "low" }, { "severity": "medium" }, { "severity": "medium" }] }, { "version": "1.2.13", "component": "angularjs", "vulnerabilities": [{ "severity": "low" }, { "severity": "low" }, { "severity": "low" }, { "severity": "low" }, { "severity": "low" }, { "severity": "low" }] }] }] }; // THIS IS THE ACTUAL METHOD BEING TESTED: Now we feed that fake result into the engine and see what we get back. const results: RuleResult[] = (testEngine as any).processOutput(JSON.stringify(fakeRetireOutput), 'insecure-bundled-dependencies'); // Now we run our assertions. expect(results.length).to.equal(2, 'Should be two result objects because of the two spoofed files.'); expect(results[0].fileName).to.equal(firstOriginal, 'First path should have been de-aliased properly'); expect(results[0].violations.length).to.equal(1, 'Should be a single violation in the first result'); expect(results[0].violations[0].severity).to.equal(2, 'Severity should be translated to 2'); expect(results[1].fileName).to.equal(secondOriginal, 'Second path should have been de-aliased properly'); expect(results[1].violations.length).to.equal(2, 'Should be two violations in the second file'); expect(results[1].violations[0].severity).to.equal(1, 'Sev should be translated to 1'); expect(results[1].violations[1].severity).to.equal(3, 'Sev should be translated to 3'); }); // Changes to the codebase make it unclear how this corner case would occur, but it's worth having the automation // so we avoid introducing any weird bugs in the future. it('Corner Case: When file has multiple aliases, results are consolidated', async () => { // First, we need to seed the engine with some fake data. const originalFile = path.join('unimportant', 'path', 'to', 'SomeFile.js'); const firstAlias = path.join('unimportant', 'alias', 'for', 'Alias1.js'); const secondAlias = path.join('unimportant', 'alias', 'for', 'Alias2.js'); (testEngine as any).originalFilesByAlias.set(firstAlias, originalFile); (testEngine as any).originalFilesByAlias.set(secondAlias, originalFile); // Next, we want to spoof some output that looks like it came from RetireJS. const fakeRetireOutput = { "version": "2.2.2", "data": [{ "file": firstAlias, "results": [{ "version": "3.1.0", "component": "jquery", "vulnerabilities": [{ "severity": "low" }, { "severity": "medium" }, { "severity": "medium" }] }] }, { "file": secondAlias, "results": [{ "version": "1.10.2", "component": "jquery", "vulnerabilities": [{ "severity": "high" }, { "severity": "medium" }, { "severity": "low" }, { "severity": "medium" }, { "severity": "medium" }] }, { "version": "1.2.13", "component": "angularjs", "vulnerabilities": [{ "severity": "low" }, { "severity": "low" }, { "severity": "low" }, { "severity": "low" }, { "severity": "low" }, { "severity": "low" }] }] }] }; // THIS IS THE ACTUAL METHOD BEING TESTED: Now we feed that fake result into the engine and see what we get back. const results: RuleResult[] = (testEngine as any).processOutput(JSON.stringify(fakeRetireOutput), 'insecure-bundled-dependencies'); // Now we run our assertions. expect(results.length).to.equal(1, 'Should be one result object, since both aliases correspond to the same original file'); expect(results[0].fileName).to.equal(originalFile, 'Path should properly de-alias back to the ZIP'); expect(results[0].violations.length).to.equal(3, 'All violations should be consolidated properly'); expect(results[0].violations[0].severity).to.equal(2, 'Severity should be translated to 2'); expect(results[0].violations[1].severity).to.equal(1, 'Sev should be translated to 1'); expect(results[0].violations[2].severity).to.equal(3, 'Sev should be translated to 3'); }); describe('Error handling', () => { it('Throws user-friendly error for un-parsable JSON', async () => { const invalidJson = '{"beep": ['; try { const results: RuleResult[] = (testEngine as any).processOutput(invalidJson, 'insecure-bundled-dependencies'); expect(true).to.equal(false, 'Exception should be thrown'); expect(results).to.equal(null, 'This assertion should never fire. It is needed to make the TS compiler stop complaining'); } catch (e) { expect(e.message.toLowerCase()).to.include('could not parse retirejs output', 'Error message should be user-friendly'); } }); it('Throws user-friendly error for improperly formed JSON', async () => { const malformedJson = { // The top-level will not have the `data` property. "version": "2.2.2" }; try { const results: RuleResult[] = (testEngine as any).processOutput(JSON.stringify(malformedJson), 'insecure-bundled-dependencies'); expect(true).to.equal(false, 'Exception should be thrown'); expect(results).to.equal(null, 'This assertion should never fire. It is needed to make the TS compiler stop complaining'); } catch (e) { expect(e.message.toLowerCase()).to.include('retire-js output did not match expected structure'); } }); }); }); describe('shouldEngineRun()', () => { it('should always return true if the engine was not filtered out', () => { expect((testEngine as any).shouldEngineRun([],[],[],new Map<string,string>())).to.be.true; }); }); describe('isEngineRequested()', () => { const emptyEngineOptions = new Map<string, string>(); const configFilePath = '/some/file/path/config.json'; const engineOptionsWithEslintCustom = new Map<string, string>([ [CUSTOM_CONFIG.EslintConfig, configFilePath] ]); const engineOptionsWithPmdCustom = new Map<string, string>([ [CUSTOM_CONFIG.PmdConfig, configFilePath] ]); it('should return true if filter contains "retire-js" and engineOptions map is empty', () => { const filterValues = ['retire-js', 'pmd']; const isEngineRequested = (testEngine as any).isEngineRequested(filterValues, emptyEngineOptions); expect(isEngineRequested).to.be.true; }); it('should return true if filter contains "retire-js" and engineOptions map contains eslint config', () => { const filterValues = ['retire-js', 'pmd']; const isEngineRequested = (testEngine as any).isEngineRequested(filterValues, engineOptionsWithEslintCustom); expect(isEngineRequested).to.be.true; }); it('should return true if filter contains "retire-js" and engineOptions map contains pmd config', () => { const filterValues = ['retire-js', 'pmd']; const isEngineRequested = (testEngine as any).isEngineRequested(filterValues, engineOptionsWithPmdCustom); expect(isEngineRequested).to.be.true; }); it('should return false if filter does not contain "retire-js" irrespective of engineOptions', () => { const filterValues = ['eslint-lwc', 'pmd']; const isEngineRequested = (testEngine as any).isEngineRequested(filterValues, emptyEngineOptions); expect(isEngineRequested).to.be.false; }); }); describe('buildCliInvocations()', () => { it('Properly invokes Insecure Bundled Dependencies rule', async () => { // Get the bundled dependency rule from the catalog. const bundledDepRule: Rule = (await (testEngine as any).getCatalog()).rules.find(r => r.name === 'insecure-bundled-dependencies'); // If we don't have a rule, we can't do any tests. expect(bundledDepRule).to.not.equal(null, 'Rule must exist'); // Invocation of tested method: Build an object describing the RetireJS invocations. const target: string = path.join('target', 'does', 'not', 'matter', 'here'); const invocations: RetireJsInvocation[] = (testEngine as any).buildCliInvocations([bundledDepRule], target); // Assertions: // There should be exactly one invocation, since there was exactly one rule. expect(invocations.length).to.equal(1, 'Should be one invocation'); const invocation = invocations[0]; expect(invocation.rule).to.equal('insecure-bundled-dependencies', 'Invocation is for incorrect rule'); expect(invocation.args[0]).to.equal('--js'); expect(invocation.args[1]).to.equal('--jspath'); expect(invocation.args[2]).to.equal(target); expect(invocation.args[3]).to.equal('--outputformat'); expect(invocation.args[4]).to.equal('json'); expect(invocation.args[5]).to.equal('--jsrepo'); expect(invocation.args[6]).to.equal((RetireJsEngine as any).VULN_JSON_PATH); }); }); });
the_stack
// IMPORTANT // This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually. // In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator // Generated from: https://ml.googleapis.com/$discovery/rest?version=v1 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Google Cloud Machine Learning Engine v1 */ function load(name: "ml", version: "v1"): PromiseLike<void>; function load(name: "ml", version: "v1", callback: () => any): void; const projects: ml.ProjectsResource; namespace ml { interface GoogleApi__HttpBody { /** The HTTP Content-Type string representing the content type of the body. */ contentType?: string; /** HTTP body binary data. */ data?: string; /** * Application specific response metadata. Must be set in the first response * for streaming APIs. */ extensions?: Array<Record<string, any>>; } interface GoogleCloudMlV1_HyperparameterOutput_HyperparameterMetric { /** The objective value at this training step. */ objectiveValue?: number; /** The global training step for this metric. */ trainingStep?: string; } interface GoogleCloudMlV1__AutoScaling { /** * Optional. The minimum number of nodes to allocate for this model. These * nodes are always up, starting from the time the model is deployed, so the * cost of operating this model will be at least * `rate` &#42; `min_nodes` &#42; number of hours since last billing cycle, * where `rate` is the cost per node-hour as documented in * [pricing](https://cloud.google.com/ml-engine/pricing#prediction_pricing), * even if no predictions are performed. There is additional cost for each * prediction performed. * * Unlike manual scaling, if the load gets too heavy for the nodes * that are up, the service will automatically add nodes to handle the * increased load as well as scale back as traffic drops, always maintaining * at least `min_nodes`. You will be charged for the time in which additional * nodes are used. * * If not specified, `min_nodes` defaults to 0, in which case, when traffic * to a model stops (and after a cool-down period), nodes will be shut down * and no charges will be incurred until traffic to the model resumes. */ minNodes?: number; } interface GoogleCloudMlV1__GetConfigResponse { /** The service account Cloud ML uses to access resources in the project. */ serviceAccount?: string; /** The project number for `service_account`. */ serviceAccountProject?: string; } interface GoogleCloudMlV1__HyperparameterOutput { /** * All recorded object metrics for this trial. This field is not currently * populated. */ allMetrics?: GoogleCloudMlV1_HyperparameterOutput_HyperparameterMetric[]; /** The final objective metric seen for this trial. */ finalMetric?: GoogleCloudMlV1_HyperparameterOutput_HyperparameterMetric; /** The hyperparameters given to this trial. */ hyperparameters?: Record<string, string>; /** The trial id for these results. */ trialId?: string; } interface GoogleCloudMlV1__HyperparameterSpec { /** * Required. The type of goal to use for tuning. Available types are * `MAXIMIZE` and `MINIMIZE`. * * Defaults to `MAXIMIZE`. */ goal?: string; /** * Optional. The Tensorflow summary tag name to use for optimizing trials. For * current versions of Tensorflow, this tag name should exactly match what is * shown in Tensorboard, including all scopes. For versions of Tensorflow * prior to 0.12, this should be only the tag passed to tf.Summary. * By default, "training/hptuning/metric" will be used. */ hyperparameterMetricTag?: string; /** * Optional. The number of training trials to run concurrently. * You can reduce the time it takes to perform hyperparameter tuning by adding * trials in parallel. However, each trail only benefits from the information * gained in completed trials. That means that a trial does not get access to * the results of trials running at the same time, which could reduce the * quality of the overall optimization. * * Each trial will use the same scale tier and machine types. * * Defaults to one. */ maxParallelTrials?: number; /** * Optional. How many training trials should be attempted to optimize * the specified hyperparameters. * * Defaults to one. */ maxTrials?: number; /** Required. The set of parameters to tune. */ params?: GoogleCloudMlV1__ParameterSpec[]; } interface GoogleCloudMlV1__Job { /** Output only. When the job was created. */ createTime?: string; /** Output only. When the job processing was completed. */ endTime?: string; /** Output only. The details of a failure or a cancellation. */ errorMessage?: string; /** Required. The user-specified id of the job. */ jobId?: string; /** Input parameters to create a prediction job. */ predictionInput?: GoogleCloudMlV1__PredictionInput; /** The current prediction job result. */ predictionOutput?: GoogleCloudMlV1__PredictionOutput; /** Output only. When the job processing was started. */ startTime?: string; /** Output only. The detailed state of a job. */ state?: string; /** Input parameters to create a training job. */ trainingInput?: GoogleCloudMlV1__TrainingInput; /** The current training job result. */ trainingOutput?: GoogleCloudMlV1__TrainingOutput; } interface GoogleCloudMlV1__ListJobsResponse { /** The list of jobs. */ jobs?: GoogleCloudMlV1__Job[]; /** * Optional. Pass this token as the `page_token` field of the request for a * subsequent call. */ nextPageToken?: string; } interface GoogleCloudMlV1__ListModelsResponse { /** The list of models. */ models?: GoogleCloudMlV1__Model[]; /** * Optional. Pass this token as the `page_token` field of the request for a * subsequent call. */ nextPageToken?: string; } interface GoogleCloudMlV1__ListVersionsResponse { /** * Optional. Pass this token as the `page_token` field of the request for a * subsequent call. */ nextPageToken?: string; /** The list of versions. */ versions?: GoogleCloudMlV1__Version[]; } interface GoogleCloudMlV1__ManualScaling { /** * The number of nodes to allocate for this model. These nodes are always up, * starting from the time the model is deployed, so the cost of operating * this model will be proportional to `nodes` &#42; number of hours since * last billing cycle plus the cost for each prediction performed. */ nodes?: number; } interface GoogleCloudMlV1__Model { /** * Output only. The default version of the model. This version will be used to * handle prediction requests that do not specify a version. * * You can change the default version by calling * [projects.methods.versions.setDefault](/ml-engine/reference/rest/v1/projects.models.versions/setDefault). */ defaultVersion?: GoogleCloudMlV1__Version; /** Optional. The description specified for the model when it was created. */ description?: string; /** * Required. The name specified for the model when it was created. * * The model name must be unique within the project it is created in. */ name?: string; /** * Optional. If true, enables StackDriver Logging for online prediction. * Default is false. */ onlinePredictionLogging?: boolean; /** * Optional. The list of regions where the model is going to be deployed. * Currently only one region per model is supported. * Defaults to 'us-central1' if nothing is set. * Note: * &#42; No matter where a model is deployed, it can always be accessed by * users from anywhere, both for online and batch prediction. * &#42; The region for a batch prediction job is set by the region field when * submitting the batch prediction job and does not take its value from * this field. */ regions?: string[]; } interface GoogleCloudMlV1__OperationMetadata { /** The time the operation was submitted. */ createTime?: string; /** The time operation processing completed. */ endTime?: string; /** Indicates whether a request to cancel this operation has been made. */ isCancellationRequested?: boolean; /** Contains the name of the model associated with the operation. */ modelName?: string; /** The operation type. */ operationType?: string; /** The time operation processing started. */ startTime?: string; /** Contains the version associated with the operation. */ version?: GoogleCloudMlV1__Version; } interface GoogleCloudMlV1__ParameterSpec { /** Required if type is `CATEGORICAL`. The list of possible categories. */ categoricalValues?: string[]; /** * Required if type is `DISCRETE`. * A list of feasible points. * The list should be in strictly increasing order. For instance, this * parameter might have possible settings of 1.5, 2.5, and 4.0. This list * should not contain more than 1,000 values. */ discreteValues?: number[]; /** * Required if typeis `DOUBLE` or `INTEGER`. This field * should be unset if type is `CATEGORICAL`. This value should be integers if * type is `INTEGER`. */ maxValue?: number; /** * Required if type is `DOUBLE` or `INTEGER`. This field * should be unset if type is `CATEGORICAL`. This value should be integers if * type is INTEGER. */ minValue?: number; /** * Required. The parameter name must be unique amongst all ParameterConfigs in * a HyperparameterSpec message. E.g., "learning_rate". */ parameterName?: string; /** * Optional. How the parameter should be scaled to the hypercube. * Leave unset for categorical parameters. * Some kind of scaling is strongly recommended for real or integral * parameters (e.g., `UNIT_LINEAR_SCALE`). */ scaleType?: string; /** Required. The type of the parameter. */ type?: string; } interface GoogleCloudMlV1__PredictRequest { /** Required. The prediction request body. */ httpBody?: GoogleApi__HttpBody; } interface GoogleCloudMlV1__PredictionInput { /** * Optional. Number of records per batch, defaults to 64. * The service will buffer batch_size number of records in memory before * invoking one Tensorflow prediction call internally. So take the record * size and memory available into consideration when setting this parameter. */ batchSize?: string; /** Required. The format of the input data files. */ dataFormat?: string; /** * Required. The Google Cloud Storage location of the input data files. * May contain wildcards. */ inputPaths?: string[]; /** * Optional. The maximum number of workers to be used for parallel processing. * Defaults to 10 if not specified. */ maxWorkerCount?: string; /** * Use this field if you want to use the default version for the specified * model. The string must use the following format: * * `"projects/<var>[YOUR_PROJECT]</var>/models/<var>[YOUR_MODEL]</var>"` */ modelName?: string; /** Required. The output Google Cloud Storage location. */ outputPath?: string; /** Required. The Google Compute Engine region to run the prediction job in. */ region?: string; /** * Optional. The Google Cloud ML runtime version to use for this batch * prediction. If not set, Google Cloud ML will pick the runtime version used * during the CreateVersion request for this model version, or choose the * latest stable version when model version information is not available * such as when the model is specified by uri. */ runtimeVersion?: string; /** * Use this field if you want to specify a Google Cloud Storage path for * the model to use. */ uri?: string; /** * Use this field if you want to specify a version of the model to use. The * string is formatted the same way as `model_version`, with the addition * of the version information: * * `"projects/<var>[YOUR_PROJECT]</var>/models/<var>YOUR_MODEL/versions/<var>[YOUR_VERSION]</var>"` */ versionName?: string; } interface GoogleCloudMlV1__PredictionOutput { /** The number of data instances which resulted in errors. */ errorCount?: string; /** Node hours used by the batch prediction job. */ nodeHours?: number; /** The output Google Cloud Storage location provided at the job creation time. */ outputPath?: string; /** The number of generated predictions. */ predictionCount?: string; } interface GoogleCloudMlV1__TrainingInput { /** Optional. Command line arguments to pass to the program. */ args?: string[]; /** Optional. The set of Hyperparameters to tune. */ hyperparameters?: GoogleCloudMlV1__HyperparameterSpec; /** * Optional. A Google Cloud Storage path in which to store training outputs * and other data needed for training. This path is passed to your TensorFlow * program as the 'job_dir' command-line argument. The benefit of specifying * this field is that Cloud ML validates the path for use in training. */ jobDir?: string; /** * Optional. Specifies the type of virtual machine to use for your training * job's master worker. * * The following types are supported: * * <dl> * <dt>standard</dt> * <dd> * A basic machine configuration suitable for training simple models with * small to moderate datasets. * </dd> * <dt>large_model</dt> * <dd> * A machine with a lot of memory, specially suited for parameter servers * when your model is large (having many hidden layers or layers with very * large numbers of nodes). * </dd> * <dt>complex_model_s</dt> * <dd> * A machine suitable for the master and workers of the cluster when your * model requires more computation than the standard machine can handle * satisfactorily. * </dd> * <dt>complex_model_m</dt> * <dd> * A machine with roughly twice the number of cores and roughly double the * memory of <code suppresswarning="true">complex_model_s</code>. * </dd> * <dt>complex_model_l</dt> * <dd> * A machine with roughly twice the number of cores and roughly double the * memory of <code suppresswarning="true">complex_model_m</code>. * </dd> * <dt>standard_gpu</dt> * <dd> * A machine equivalent to <code suppresswarning="true">standard</code> that * also includes a * <a href="/ml-engine/docs/how-tos/using-gpus"> * GPU that you can use in your trainer</a>. * </dd> * <dt>complex_model_m_gpu</dt> * <dd> * A machine equivalent to * <code suppresswarning="true">complex_model_m</code> that also includes * four GPUs. * </dd> * </dl> * * You must set this value when `scaleTier` is set to `CUSTOM`. */ masterType?: string; /** * Required. The Google Cloud Storage location of the packages with * the training program and any additional dependencies. * The maximum number of package URIs is 100. */ packageUris?: string[]; /** * Optional. The number of parameter server replicas to use for the training * job. Each replica in the cluster will be of the type specified in * `parameter_server_type`. * * This value can only be used when `scale_tier` is set to `CUSTOM`.If you * set this value, you must also set `parameter_server_type`. */ parameterServerCount?: string; /** * Optional. Specifies the type of virtual machine to use for your training * job's parameter server. * * The supported values are the same as those described in the entry for * `master_type`. * * This value must be present when `scaleTier` is set to `CUSTOM` and * `parameter_server_count` is greater than zero. */ parameterServerType?: string; /** Required. The Python module name to run after installing the packages. */ pythonModule?: string; /** Required. The Google Compute Engine region to run the training job in. */ region?: string; /** * Optional. The Google Cloud ML runtime version to use for training. If not * set, Google Cloud ML will choose the latest stable version. */ runtimeVersion?: string; /** * Required. Specifies the machine types, the number of replicas for workers * and parameter servers. */ scaleTier?: string; /** * Optional. The number of worker replicas to use for the training job. Each * replica in the cluster will be of the type specified in `worker_type`. * * This value can only be used when `scale_tier` is set to `CUSTOM`. If you * set this value, you must also set `worker_type`. */ workerCount?: string; /** * Optional. Specifies the type of virtual machine to use for your training * job's worker nodes. * * The supported values are the same as those described in the entry for * `masterType`. * * This value must be present when `scaleTier` is set to `CUSTOM` and * `workerCount` is greater than zero. */ workerType?: string; } interface GoogleCloudMlV1__TrainingOutput { /** * The number of hyperparameter tuning trials that completed successfully. * Only set for hyperparameter tuning jobs. */ completedTrialCount?: string; /** The amount of ML units consumed by the job. */ consumedMLUnits?: number; /** Whether this job is a hyperparameter tuning job. */ isHyperparameterTuningJob?: boolean; /** * Results for individual Hyperparameter trials. * Only set for hyperparameter tuning jobs. */ trials?: GoogleCloudMlV1__HyperparameterOutput[]; } interface GoogleCloudMlV1__Version { /** * Automatically scale the number of nodes used to serve the model in * response to increases and decreases in traffic. Care should be * taken to ramp up traffic according to the model's ability to scale * or you will start seeing increases in latency and 429 response codes. */ autoScaling?: GoogleCloudMlV1__AutoScaling; /** Output only. The time the version was created. */ createTime?: string; /** * Required. The Google Cloud Storage location of the trained model used to * create the version. See the * [overview of model * deployment](/ml-engine/docs/concepts/deployment-overview) for more * information. * * When passing Version to * [projects.models.versions.create](/ml-engine/reference/rest/v1/projects.models.versions/create) * the model service uses the specified location as the source of the model. * Once deployed, the model version is hosted by the prediction service, so * this location is useful only as a historical record. * The total number of model files can't exceed 1000. */ deploymentUri?: string; /** Optional. The description specified for the version when it was created. */ description?: string; /** Output only. The details of a failure or a cancellation. */ errorMessage?: string; /** * Output only. If true, this version will be used to handle prediction * requests that do not specify a version. * * You can change the default version by calling * [projects.methods.versions.setDefault](/ml-engine/reference/rest/v1/projects.models.versions/setDefault). */ isDefault?: boolean; /** Output only. The time the version was last used for prediction. */ lastUseTime?: string; /** * Manually select the number of nodes to use for serving the * model. You should generally use `auto_scaling` with an appropriate * `min_nodes` instead, but this option is available if you want more * predictable billing. Beware that latency and error rates will increase * if the traffic exceeds that capability of the system to serve it based * on the selected number of nodes. */ manualScaling?: GoogleCloudMlV1__ManualScaling; /** * Required.The name specified for the version when it was created. * * The version name must be unique within the model it is created in. */ name?: string; /** * Optional. The Google Cloud ML runtime version to use for this deployment. * If not set, Google Cloud ML will choose a version. */ runtimeVersion?: string; /** Output only. The state of a version. */ state?: string; } interface GoogleIamV1__AuditConfig { /** * The configuration for logging of each type of permission. * Next ID: 4 */ auditLogConfigs?: GoogleIamV1__AuditLogConfig[]; exemptedMembers?: string[]; /** * Specifies a service that will be enabled for audit logging. * For example, `storage.googleapis.com`, `cloudsql.googleapis.com`. * `allServices` is a special value that covers all services. */ service?: string; } interface GoogleIamV1__AuditLogConfig { /** * Specifies the identities that do not cause logging for this type of * permission. * Follows the same format of Binding.members. */ exemptedMembers?: string[]; /** The log type that this config enables. */ logType?: string; } interface GoogleIamV1__Binding { /** * The condition that is associated with this binding. * NOTE: an unsatisfied condition will not allow user access via current * binding. Different bindings, including their conditions, are examined * independently. * This field is GOOGLE_INTERNAL. */ condition?: GoogleType__Expr; /** * Specifies the identities requesting access for a Cloud Platform resource. * `members` can have the following values: * * &#42; `allUsers`: A special identifier that represents anyone who is * on the internet; with or without a Google account. * * &#42; `allAuthenticatedUsers`: A special identifier that represents anyone * who is authenticated with a Google account or a service account. * * &#42; `user:{emailid}`: An email address that represents a specific Google * account. For example, `alice@gmail.com` or `joe@example.com`. * * * &#42; `serviceAccount:{emailid}`: An email address that represents a service * account. For example, `my-other-app@appspot.gserviceaccount.com`. * * &#42; `group:{emailid}`: An email address that represents a Google group. * For example, `admins@example.com`. * * * &#42; `domain:{domain}`: A Google Apps domain name that represents all the * users of that domain. For example, `google.com` or `example.com`. */ members?: string[]; /** * Role that is assigned to `members`. * For example, `roles/viewer`, `roles/editor`, or `roles/owner`. * Required */ role?: string; } interface GoogleIamV1__Policy { /** Specifies cloud audit logging configuration for this policy. */ auditConfigs?: GoogleIamV1__AuditConfig[]; /** * Associates a list of `members` to a `role`. * `bindings` with no members will result in an error. */ bindings?: GoogleIamV1__Binding[]; /** * `etag` is used for optimistic concurrency control as a way to help * prevent simultaneous updates of a policy from overwriting each other. * It is strongly suggested that systems make use of the `etag` in the * read-modify-write cycle to perform policy updates in order to avoid race * conditions: An `etag` is returned in the response to `getIamPolicy`, and * systems are expected to put that etag in the request to `setIamPolicy` to * ensure that their change will be applied to the same version of the policy. * * If no `etag` is provided in the call to `setIamPolicy`, then the existing * policy is overwritten blindly. */ etag?: string; iamOwned?: boolean; /** Version of the `Policy`. The default version is 0. */ version?: number; } interface GoogleIamV1__SetIamPolicyRequest { /** * REQUIRED: The complete policy to be applied to the `resource`. The size of * the policy is limited to a few 10s of KB. An empty policy is a * valid policy but certain Cloud Platform services (such as Projects) * might reject them. */ policy?: GoogleIamV1__Policy; /** * OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only * the fields in the mask will be modified. If no mask is provided, the * following default mask is used: * paths: "bindings, etag" * This field is only used by Cloud IAM. */ updateMask?: string; } interface GoogleIamV1__TestIamPermissionsRequest { /** * The set of permissions to check for the `resource`. Permissions with * wildcards (such as '&#42;' or 'storage.&#42;') are not allowed. For more * information see * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). */ permissions?: string[]; } interface GoogleIamV1__TestIamPermissionsResponse { /** * A subset of `TestPermissionsRequest.permissions` that the caller is * allowed. */ permissions?: string[]; } interface GoogleLongrunning__ListOperationsResponse { /** The standard List next-page token. */ nextPageToken?: string; /** A list of operations that matches the specified filter in the request. */ operations?: GoogleLongrunning__Operation[]; } interface GoogleLongrunning__Operation { /** * If the value is `false`, it means the operation is still in progress. * If `true`, the operation is completed, and either `error` or `response` is * available. */ done?: boolean; /** The error result of the operation in case of failure or cancellation. */ error?: GoogleRpc__Status; /** * Service-specific metadata associated with the operation. It typically * contains progress information and common metadata such as create time. * Some services might not provide such metadata. Any method that returns a * long-running operation should document the metadata type, if any. */ metadata?: Record<string, any>; /** * The server-assigned name, which is only unique within the same service that * originally returns it. If you use the default HTTP mapping, the * `name` should have the format of `operations/some/unique/name`. */ name?: string; /** * The normal response of the operation in case of success. If the original * method returns no data on success, such as `Delete`, the response is * `google.protobuf.Empty`. If the original method is standard * `Get`/`Create`/`Update`, the response should be the resource. For other * methods, the response should have the type `XxxResponse`, where `Xxx` * is the original method name. For example, if the original method name * is `TakeSnapshot()`, the inferred response type is * `TakeSnapshotResponse`. */ response?: Record<string, any>; } interface GoogleRpc__Status { /** The status code, which should be an enum value of google.rpc.Code. */ code?: number; /** * A list of messages that carry the error details. There is a common set of * message types for APIs to use. */ details?: Array<Record<string, any>>; /** * A developer-facing error message, which should be in English. Any * user-facing error message should be localized and sent in the * google.rpc.Status.details field, or localized by the client. */ message?: string; } interface GoogleType__Expr { /** * An optional description of the expression. This is a longer text which * describes the expression, e.g. when hovered over it in a UI. */ description?: string; /** * Textual representation of an expression in * Common Expression Language syntax. * * The application context of the containing message determines which * well-known feature set of CEL is supported. */ expression?: string; /** * An optional string indicating the location of the expression for error * reporting, e.g. a file name and a position in the file. */ location?: string; /** * An optional title for the expression, i.e. a short string describing * its purpose. This can be used e.g. in UIs which allow to enter the * expression. */ title?: string; } interface JobsResource { /** Cancels a running job. */ cancel(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the job to cancel. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** Creates a training or a batch prediction job. */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Required. The project name. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Job>; /** Describes a job. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the job to get the description of. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Job>; /** * Gets the access control policy for a resource. * Returns an empty policy if the resource exists and does not have a policy * set. */ getIamPolicy(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy is being requested. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__Policy>; /** Lists the jobs in the project. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** Optional. Specifies the subset of jobs to retrieve. */ filter?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Optional. The number of jobs to retrieve per "page" of results. If there * are more remaining results than this number, the response message will * contain a valid value in the `next_page_token` field. * * The default value is 20, and the maximum page size is 100. */ pageSize?: number; /** * Optional. A page token to request the next page of results. * * You get the token from the `next_page_token` field of the response from * the previous call. */ pageToken?: string; /** Required. The name of the project for which to list jobs. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__ListJobsResponse>; /** * Sets the access control policy on the specified resource. Replaces any * existing policy. */ setIamPolicy(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy is being specified. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__Policy>; /** * Returns permissions that a caller has on the specified resource. * If the resource does not exist, this will return an empty set of * permissions, not a NOT_FOUND error. * * Note: This operation is designed to be used for building permission-aware * UIs and command-line tools, not for authorization checking. This operation * may "fail open" without warning. */ testIamPermissions(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy detail is being requested. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__TestIamPermissionsResponse>; } interface VersionsResource { /** * Creates a new version of a model from a trained TensorFlow model. * * If the version created in the cloud by this call is the first deployed * version of the specified model, it will be made the default version of the * model. When you add a version to a model that already has one or more * versions, the default version does not automatically change. If you want a * new version to be the default, you must call * [projects.models.versions.setDefault](/ml-engine/reference/rest/v1/projects.models.versions/setDefault). */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Required. The name of the model. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Deletes a model version. * * Each model can have multiple versions deployed and in use at any given * time. Use this method to remove a single version. * * Note: You cannot delete the version that is set as the default version * of the model unless it is the only remaining version. */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Required. The name of the version. You can get the names of all the * versions of a model by calling * [projects.models.versions.list](/ml-engine/reference/rest/v1/projects.models.versions/list). */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Gets information about a model version. * * Models can have multiple versions. You can call * [projects.models.versions.list](/ml-engine/reference/rest/v1/projects.models.versions/list) * to get the same information that this method returns for all of the * versions of a model. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the version. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Version>; /** * Gets basic information about all the versions of a model. * * If you expect that a model has a lot of versions, or if you need to handle * only a limited number of results at a time, you can request that the list * be retrieved in batches (called pages): */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Optional. The number of versions to retrieve per "page" of results. If * there are more remaining results than this number, the response message * will contain a valid value in the `next_page_token` field. * * The default value is 20, and the maximum page size is 100. */ pageSize?: number; /** * Optional. A page token to request the next page of results. * * You get the token from the `next_page_token` field of the response from * the previous call. */ pageToken?: string; /** Required. The name of the model for which to list the version. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__ListVersionsResponse>; /** * Updates the specified Version resource. * * Currently the only supported field to update is `description`. */ patch(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the model. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Required. Specifies the path, relative to `Version`, of the field to * update. Must be present and non-empty. * * For example, to change the description of a version to "foo", the * `update_mask` parameter would be specified as `description`, and the * `PATCH` request body would specify the new value, as follows: * { * "description": "foo" * } * In this example, the version is blindly overwritten since no etag is given. * * To adopt etag mechanism, include `etag` field in the mask, and include the * `etag` value in your version resource. * * Currently the only supported update masks are `description`, `labels`, and * `etag`. */ updateMask?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Designates a version to be the default for the model. * * The default version is used for prediction requests made against the model * that don't specify a version. * * The first version to be created for a model is automatically set as the * default. You must make any subsequent changes to the default version * setting manually using this method. */ setDefault(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Required. The name of the version to make the default for the model. You * can get the names of all the versions of a model by calling * [projects.models.versions.list](/ml-engine/reference/rest/v1/projects.models.versions/list). */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Version>; } interface ModelsResource { /** * Creates a model which will later contain one or more versions. * * You must add at least one version before you can request predictions from * the model. Add versions by calling * [projects.models.versions.create](/ml-engine/reference/rest/v1/projects.models.versions/create). */ create(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Required. The project name. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Model>; /** * Deletes a model. * * You can only delete a model if there are no versions in it. You can delete * versions by calling * [projects.models.versions.delete](/ml-engine/reference/rest/v1/projects.models.versions/delete). */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the model. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Gets information about a model, including its name, the description (if * set), and the default version (if at least one version of the model has * been deployed). */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The name of the model. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__Model>; /** * Gets the access control policy for a resource. * Returns an empty policy if the resource exists and does not have a policy * set. */ getIamPolicy(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy is being requested. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__Policy>; /** * Lists the models in a project. * * Each project can contain multiple models, and each model can have multiple * versions. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Optional. The number of models to retrieve per "page" of results. If there * are more remaining results than this number, the response message will * contain a valid value in the `next_page_token` field. * * The default value is 20, and the maximum page size is 100. */ pageSize?: number; /** * Optional. A page token to request the next page of results. * * You get the token from the `next_page_token` field of the response from * the previous call. */ pageToken?: string; /** Required. The name of the project whose models are to be listed. */ parent: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__ListModelsResponse>; /** * Updates a specific model resource. * * Currently the only supported fields to update are `description` and * `default_version.name`. */ patch(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The project name. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Required. Specifies the path, relative to `Model`, of the field to update. * * For example, to change the description of a model to "foo" and set its * default version to "version_1", the `update_mask` parameter would be * specified as `description`, `default_version.name`, and the `PATCH` * request body would specify the new value, as follows: * { * "description": "foo", * "defaultVersion": { * "name":"version_1" * } * } * In this example, the model is blindly overwritten since no etag is given. * * To adopt etag mechanism, include `etag` field in the mask, and include the * `etag` value in your model resource. * * Currently the supported update masks are `description`, * `default_version.name`, `labels`, and `etag`. */ updateMask?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Sets the access control policy on the specified resource. Replaces any * existing policy. */ setIamPolicy(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy is being specified. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__Policy>; /** * Returns permissions that a caller has on the specified resource. * If the resource does not exist, this will return an empty set of * permissions, not a NOT_FOUND error. * * Note: This operation is designed to be used for building permission-aware * UIs and command-line tools, not for authorization checking. This operation * may "fail open" without warning. */ testIamPermissions(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * REQUIRED: The resource for which the policy detail is being requested. * See the operation documentation for the appropriate value for this field. */ resource: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleIamV1__TestIamPermissionsResponse>; versions: VersionsResource; } interface OperationsResource { /** * Starts asynchronous cancellation on a long-running operation. The server * makes a best effort to cancel the operation, but success is not * guaranteed. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. Clients can use * Operations.GetOperation or * other methods to check whether the cancellation succeeded or whether the * operation completed despite cancellation. On successful cancellation, * the operation is not deleted; instead, it becomes an operation with * an Operation.error value with a google.rpc.Status.code of 1, * corresponding to `Code.CANCELLED`. */ cancel(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name of the operation resource to be cancelled. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** * Deletes a long-running operation. This method indicates that the client is * no longer interested in the operation result. It does not cancel the * operation. If the server doesn't support this method, it returns * `google.rpc.Code.UNIMPLEMENTED`. */ delete(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name of the operation resource to be deleted. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<{}>; /** * Gets the latest state of a long-running operation. Clients can use this * method to poll the operation result at intervals as recommended by the API * service. */ get(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name of the operation resource. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__Operation>; /** * Lists operations that match the specified filter in the request. If the * server doesn't support this method, it returns `UNIMPLEMENTED`. * * NOTE: the `name` binding allows API services to override the binding * to use different resource name schemes, such as `users/&#42;/operations`. To * override the binding, API services can add a binding such as * `"/v1/{name=users/&#42;}/operations"` to their service configuration. * For backwards compatibility, the default name includes the operations * collection id, however overriding users must ensure the name binding * is the parent resource, without the operations collection id. */ list(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** The standard list filter. */ filter?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** The name of the operation's parent resource. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** The standard list page size. */ pageSize?: number; /** The standard list page token. */ pageToken?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleLongrunning__ListOperationsResponse>; } interface ProjectsResource { /** * Get the service account information associated with your project. You need * this information in order to grant the service account persmissions for * the Google Cloud Storage location where you put your model training code * for training the model with Google Cloud Machine Learning. */ getConfig(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** Required. The project name. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleCloudMlV1__GetConfigResponse>; /** * Performs prediction on the data in the request. * * &#42;&#42;&#42;&#42; REMOVE FROM GENERATED DOCUMENTATION */ predict(request: { /** V1 error format. */ "$.xgafv"?: string; /** OAuth access token. */ access_token?: string; /** Data format for response. */ alt?: string; /** OAuth bearer token. */ bearer_token?: string; /** JSONP */ callback?: string; /** Selector specifying which fields to include in a partial response. */ fields?: string; /** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * Required. The resource name of a model or a version. * * Authorization: requires the `predict` permission on the specified resource. */ name: string; /** OAuth 2.0 token for the current user. */ oauth_token?: string; /** Pretty-print response. */ pp?: boolean; /** Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; }): Request<GoogleApi__HttpBody>; jobs: JobsResource; models: ModelsResource; operations: OperationsResource; } } }
the_stack
import { isString, isUndefined, isNumber, includes, isNull, range, getFirstValidValue, } from '@src/helpers/utils'; import { DataToExport } from '@src/component/exportMenu'; import { HeatmapCategoriesType, TreemapSeriesType, AreaSeriesDataType, CoordinateDataType, LineSeriesDataType, RangeDataType, PieSeriesType, NestedPieSeriesType, } from '@t/options'; import { getCoordinateXValue, getCoordinateYValue } from './coordinate'; type ExportData2DArray = (string | number)[][]; export type SpreadSheetExtension = 'csv' | 'xls'; type ImageExtension = 'png' | 'jpeg'; type Extension = SpreadSheetExtension | ImageExtension; const DATA_URI_HEADERS = { xls: 'data:application/vnd.ms-excel;base64,', csv: 'data:text/csv;charset=utf-8,%EF%BB%BF' /* BOM for utf-8 */, }; function getDownloadMethod() { let method; const isDownloadAttributeSupported = !isUndefined(document.createElement('a').download); const isMSSaveOrOpenBlobSupported = !isUndefined( window.Blob && window.navigator.msSaveOrOpenBlob ); if (isMSSaveOrOpenBlobSupported) { method = downloadWithMSSaveOrOpenBlob; } else if (isDownloadAttributeSupported) { method = downloadWithAnchorElementDownloadAttribute; } return method; } /** * Base64 string to blob * original source ref: https://github.com/miguelmota/base64toblob/blob/master/base64toblob.js * Licence: MIT Licence */ function base64toBlob(base64String: string) { const contentType = base64String .substr(0, base64String.indexOf(';base64,')) .substr(base64String.indexOf(':') + 1); const sliceSize = 1024; const byteCharacters = atob(base64String.substr(base64String.indexOf(',') + 1)); const byteArrays: Uint8Array[] = []; for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i += 1) { byteNumbers[i] = slice.charCodeAt(i); } byteArrays.push(new window.Uint8Array(byteNumbers)); } try { // for IE 11 return new Blob(byteArrays, { type: contentType }); } catch (e) { // for IE 10 return new Blob( byteArrays.map((byteArr) => byteArr.buffer), { type: contentType } ); } } function isImageExtension(extension: Extension) { return extension === 'jpeg' || extension === 'png'; } function downloadWithMSSaveOrOpenBlob( fileName: string, extension: Extension, content: string, contentType?: string ) { const blobObject = isImageExtension(extension) ? base64toBlob(content) : new Blob([content], { type: contentType }); window.navigator.msSaveOrOpenBlob(blobObject, `${fileName}.${extension}`); } function downloadWithAnchorElementDownloadAttribute( fileName: string, extension: Extension, content?: string ) { if (content) { const anchorElement = document.createElement('a'); anchorElement.href = content; anchorElement.target = '_blank'; anchorElement.download = `${fileName}.${extension}`; document.body.appendChild(anchorElement); anchorElement.click(); anchorElement.remove(); } } function oneLineTrim(...args: [TemplateStringsArray, string]) { const normalTag = (template, ...expressions) => template.reduce((accumulator, part, i) => accumulator + expressions[i - 1] + part); return normalTag(...args).replace(/\n\s*/g, ''); } function isNeedDataEncoding() { const isDownloadAttributeSupported = !isUndefined(document.createElement('a').download); const isMSSaveOrOpenBlobSupported = !isUndefined( window.Blob && window.navigator.msSaveOrOpenBlob ); return !isMSSaveOrOpenBlobSupported && isDownloadAttributeSupported; } function getBulletLongestArrayLength(arr: any[], field: string): number { return arr.reduce( (acc, cur, idx) => (!idx || acc < cur?.[field]?.length ? cur[field].length : acc), 0 ); } function makeBulletExportData({ series }: DataToExport): ExportData2DArray { const seriesData = series.bullet!.data; const markerCount = getBulletLongestArrayLength(seriesData, 'markers'); const rangeCount = getBulletLongestArrayLength(seriesData, 'ranges'); const rangesHeaders = range(0, rangeCount).map((idx) => `Range ${idx + 1}`); const markerHeaders = range(0, markerCount).map((idx) => `Marker ${idx + 1}`); return seriesData.reduce<ExportData2DArray>( (acc, { data, markers, name, ranges }) => { const rangeDatum = rangesHeaders.map((_, index) => { const rangeData = ranges?.[index]; return rangeData ? `${rangeData[0]} ~ ${rangeData[1]}` : ''; }); const markerDatum = markerHeaders.map((_, index) => markers?.[index] ?? ''); return [...acc, [name, data ?? '', ...rangeDatum, ...markerDatum]]; }, [['', 'Actual', ...rangesHeaders, ...markerHeaders]] ); } function makeHeatmapExportData({ categories, series }: DataToExport): ExportData2DArray { const xCategories = (categories as HeatmapCategoriesType).x; return series.heatmap!.data.reduce<ExportData2DArray>( (acc, { data, yCategory }) => [ ...acc, [yCategory, ...data.map((datum) => (isNull(datum) ? '' : datum))], ], [['', ...xCategories]] ); } function recursiveTreemapData( { label, data, children = [] }: TreemapSeriesType, result: ExportData2DArray ) { if (data) { result.push([label, data]); } children.forEach((childrenData) => recursiveTreemapData(childrenData, result)); return result; } function makeTreemapExportData(exportData: DataToExport) { const { series } = exportData; const result: ExportData2DArray = [['Label', 'Data']]; series.treemap!.data.forEach((datum) => { recursiveTreemapData(datum, result); }); return result; } function makeBubbleExportData(exportData: DataToExport): ExportData2DArray { const { series } = exportData; return series.bubble!.data.reduce<ExportData2DArray>( (acc, { name, data }) => [ ...acc, ...data.map((datum) => isNull(datum) ? [] : [name, datum.label, String(datum.x), datum.y, datum.r] ), ], [['Name', 'Label', 'X', 'Y', 'Radius']] ); } function makeBoxPlotExportData(exportData: DataToExport): ExportData2DArray { const { series } = exportData; const categories = (exportData.categories ?? []) as string[]; return series.boxPlot!.data.reduce<ExportData2DArray>( (acc, { name, data, outliers }) => { const values = (data ?? []).map((rawData, index) => { const outlierValue = (outliers ?? []).find((outlier) => outlier[0] === index)?.[1]; const value = outlierValue ? [...rawData, outlierValue] : [...rawData]; return value.join(); }); return [...acc, [name, ...values]]; }, [['', ...categories]] ); } function makePieExportData(exportData: DataToExport): ExportData2DArray { const { series } = exportData; const categories = (exportData.categories ?? []) as string[]; return (series.pie!.data as Array<PieSeriesType | NestedPieSeriesType>).reduce<ExportData2DArray>( (acc, { name, data }) => { const values = Array.isArray(data) ? (data ?? []).reduce<ExportData2DArray>((accNestedPieValue, value) => { return [...accNestedPieValue, [value.name, value.data ?? '']]; }, []) : [[name, data ?? '']]; return [...acc, ...values]; }, (categories as string[]).length ? [['', ...categories]] : [] ); } function makeCoordinateExportDataValues( type: string, categories: string[], data: Array<LineSeriesDataType | CoordinateDataType | AreaSeriesDataType> ) { return categories.map((category, index) => { if (type === 'area' && Array.isArray(data[index])) { return (data[index] as RangeDataType<number>).join(); } const foundItem = data.find( (value) => category === String(getCoordinateXValue(value as CoordinateDataType)) ); return foundItem ? getCoordinateYValue(foundItem) : ''; }); } function makeExportData(exportData: DataToExport): ExportData2DArray { const { series } = exportData; const categories = exportData.categories as string[]; return Object.keys(series).reduce<ExportData2DArray>( (acc, type) => { const result = series[type].data.map(({ name, data }) => { const values = !isNumber(getFirstValidValue(data)) && includes(['line', 'area', 'scatter'], type) ? makeCoordinateExportDataValues(type, categories, data) : data.map((value) => (Array.isArray(value) ? value.join() : value)); return [name, ...values]; }); return [...acc, ...result]; }, series.gauge ? [] : [['', ...categories]] ); } function get2DArrayFromRawData(exportData: DataToExport) { let result: ExportData2DArray; const { series } = exportData; if (series.bullet) { result = makeBulletExportData(exportData); } else if (series.heatmap) { result = makeHeatmapExportData(exportData); } else if (series.bubble) { result = makeBubbleExportData(exportData); } else if (series.boxPlot) { result = makeBoxPlotExportData(exportData); } else if (series.pie) { result = makePieExportData(exportData); } else if (series.treemap) { result = makeTreemapExportData(exportData); } else { result = makeExportData(exportData); } return result; } function getTableElementStringForXLS(chartData2DArray: ExportData2DArray) { let tableElementString = '<table>'; chartData2DArray.forEach((row, rowIndex) => { const cellTagName = rowIndex === 0 ? 'th' : 'td'; tableElementString += '<tr>'; row.forEach((cell, cellIndex) => { const cellNumberClass = rowIndex !== 0 || cellIndex === 0 ? ' class="number"' : ''; const cellString = `<${cellTagName}${cellNumberClass}>${cell}</${cellTagName}>`; tableElementString += cellString; }); tableElementString += '</tr>'; }); tableElementString += '</table>'; return tableElementString; } function makeXLSBodyWithRawData(chartData2DArray: ExportData2DArray) { return oneLineTrim`<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"> <head> <!--[if gte mso 9]> <xml> <x:ExcelWorkbook> <x:ExcelWorksheets> <x:ExcelWorksheet> <x:Name>Ark1</x:Name> <x:WorksheetOptions> <x:DisplayGridlines/> </x:WorksheetOptions> </x:ExcelWorksheet> </x:ExcelWorksheets> </x:ExcelWorkbook> </xml> <![endif]--> <meta name=ProgId content=Excel.Sheet> <meta charset=UTF-8> </head> <body> ${getTableElementStringForXLS(chartData2DArray)} </body> </html>`; } function makeCSVBodyWithRawData( chartData2DArray: ExportData2DArray, option: { lineDelimiter?: string; itemDelimiter?: string } = {} ) { const { lineDelimiter = '\u000a', itemDelimiter = ',' } = option; const lastRowIndex = chartData2DArray.length - 1; let csvText = ''; chartData2DArray.forEach((row, rowIndex) => { const lastCellIndex = row.length - 1; row.forEach((cell, cellIndex) => { const cellContent = isNumber(cell) ? cell : `"${cell}"`; csvText += cellContent; if (cellIndex < lastCellIndex) { csvText += itemDelimiter; } }); if (rowIndex < lastRowIndex) { csvText += lineDelimiter; } }); return csvText; } export function execDownload( fileName: string, extension: Extension, content: string, contentType?: string ) { const downloadMethod = getDownloadMethod(); if (!isString(content) || !downloadMethod) { return; } downloadMethod(fileName, extension, content, contentType); } export function downloadSpreadSheet( fileName: string, extension: SpreadSheetExtension, data: DataToExport ) { const chartData2DArray = get2DArrayFromRawData(data); const contentType = DATA_URI_HEADERS[extension].replace(/(data:|;base64,|,%EF%BB%BF)/g, ''); let content = ''; if (extension === 'csv') { content = makeCSVBodyWithRawData(chartData2DArray); } else { content = makeXLSBodyWithRawData(chartData2DArray); } if (isNeedDataEncoding()) { if (extension !== 'csv') { // base64 encoding for data URI scheme. content = window.btoa(unescape(encodeURIComponent(content))); } content = DATA_URI_HEADERS[extension] + content; } execDownload(fileName, extension, content, contentType); }
the_stack
import nj from 'numjs' import { FaceEmbedding, log, Point, Rectangle, } from './config' import { createImageData, cropImage, distance, imageMd5, imageToData, loadImage, saveImage, toBuffer, toDataURL, } from './misc' export interface FacialLandmark { [idx: string]: Point, leftEye: Point, rightEye: Point, nose: Point, leftMouthCorner: Point, rightMouthCorner: Point, } export interface FaceJsonObject { confidence? : number, embedding : number[], imageData : string, // Base64 of Buffer landmark? : FacialLandmark, location : Rectangle, md5 : string, } export interface FaceOptions { boundingBox? : number[], // [x0, y0, x1, y1] confidence? : number, file? : string, landmarks? : number[][], // Facial Landmark md5? : string, // for fromJSON fast init } export class Face { public static id = 0 public id: number /** * * Get Face md5 * @type {string} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face md5: ', faceList[0].md5) * // Output md5: 003c926dd9d2368a86e41a2938aacc98 */ /** * * Get Face md5 * @type {string} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face md5: ', faceList[0].md5) * // Output md5: 003c926dd9d2368a86e41a2938aacc98 */ public md5!: string /** * * Get Face imageData * @type {ImageData} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face imageData: ', faceList[0].imageData) * // Output, Base64 of Buffer * // imageData: ImageData { * // data: * // Uint8ClampedArray [ * // 81, * // ... 211500 more items ] } */ /** * * Get Face imageData * @type {ImageData} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face imageData: ', faceList[0].imageData) * // Output, Base64 of Buffer * // imageData: ImageData { * // data: * // Uint8ClampedArray [ * // 81, * // ... 211500 more items ] } */ public imageData!: ImageData /** * * Get Face location * @type {(Rectangle | undefined)} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face location : ', faceList[0].location) * // Output location: { x: 360, y: 94, w: 230, h: 230 } */ public location: Rectangle | undefined /** * * Get Face confidence * @type {(number | undefined)} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face confidence : ', faceList[0].confidence) * // Output confidence: 0.9999634027481079 */ public confidence: number | undefined /** * @desc FacialLandmark Type * @typedef FacialLandmark * @property { Point } leftEye * @property { Point } rightEye * @property { Point } nose * @property { Point } leftMouthCorner * @property { Point } rightMouthCorner */ /** * * Get Face landmark, containing rightEye, leftEye, nose, leftMouthCorner and rightMouthCorner * @type {(FacialLandmark | undefined)} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face landmark : ', faceList[0].landmark) * // Output * // landmark: { leftEye: { x: 441, y: 180 }, * // rightEye: { x: 515, y: 208 }, * // nose: { x: 459, y: 239 }, * // leftMouthCorner: { x: 417, y: 262 }, * // rightMouthCorner: { x: 482, y: 286 } } */ public landmark: FacialLandmark | undefined private _embedding!: FaceEmbedding /** * Creates an instance of Face. * @param {ImageData} [imageData] */ constructor ( imageData?: ImageData, ) { this.id = Face.id++ log.verbose('Face', 'constructor(%dx%d) #%d', imageData ? imageData.width : 0, imageData ? imageData.height : 0, this.id, ) if (imageData) { this.imageData = imageData } } /** * Init a face * @param {FaceOptions} [options={}] * @returns {Promise<this>} */ public async init (options: FaceOptions = {}): Promise<this> { if (options.file) { if (this.imageData) { throw new Error('constructor(imageData) or init({file}) can not be both specified at same time!') } this.imageData = await this.initFile(options.file) } return this.initSync(options) } /** * @private */ public initSync (options: FaceOptions = {}): this { log.verbose('Face', 'init()') if (!this.imageData) { throw new Error('initSync() must be called after imageData set') } if (options.confidence) { this.confidence = options.confidence } if (options.landmarks) { this.landmark = this.initLandmarks(options.landmarks) } if (!this.imageData) { throw new Error('no image data!') } if (options.boundingBox) { this.location = this.initBoundingBox(options.boundingBox) this.imageData = this.updateImageData(this.imageData) } else { this.location = this.initBoundingBox([0, 0, this.imageData.width, this.imageData.height]) } if (options.md5) { this.md5 = options.md5 } else { // update md5 this.md5 = imageMd5(this.imageData) } return this } /** * @private */ private initLandmarks (marks: number[][]): FacialLandmark { log.verbose('Face', 'initLandmarks([%s]) #%d', marks, this.id, ) const leftEye: Point = { x: Math.round(marks[0][0]), y: Math.round(marks[0][1]), } const rightEye: Point = { x: Math.round(marks[1][0]), y: Math.round(marks[1][1]), } const nose: Point = { x: Math.round(marks[2][0]), y: Math.round(marks[2][1]), } const leftMouthCorner: Point = { x: Math.round(marks[3][0]), y: Math.round(marks[3][1]), } const rightMouthCorner: Point = { x: Math.round(marks[4][0]), y: Math.round(marks[4][1]), } return { leftEye, rightEye, nose, leftMouthCorner, rightMouthCorner, } } /** * @private */ private async initFile (file: string): Promise<ImageData> { log.verbose('Face', 'initFilename(%s) #%d', file, this.id, ) const image = await loadImage(file) const imageData = imageToData(image) return imageData } /** * @private */ private initBoundingBox (boundingBox: number[]): Rectangle { log.verbose('Face', 'initBoundingBox([%s]) #%d', boundingBox, this.id, ) if (!this.imageData) { throw new Error('no imageData!') } return { x: boundingBox[0], y: boundingBox[1], w: boundingBox[2] - boundingBox[0], h: boundingBox[3] - boundingBox[1], } } /** * @private */ private updateImageData (imageData: ImageData): ImageData { if (!this.location) { throw new Error('no location!') } if (this.location.w === imageData.width && this.location.h === imageData.height ) { return imageData } // need to corp and reset this.data log.verbose('Face', 'initBoundingBox() box.w=%d, box.h=%d; image.w=%d, image.h=%d', this.location.w, this.location.h, imageData.width, imageData.height, ) const croppedImage = cropImage( imageData, this.location.x, this.location.y, this.location.w, this.location.h, ) return croppedImage } /** * @private */ public toString (): string { return `Face<${this.md5}>` } /** * @desc FaceJsonObject Type * @typedef FaceJsonObject * @property { number } confidence - The confidence to confirm is face * @property { number[] } embedding * @property { string } imageData - Base64 of Buffer * @property { FacialLandmark } landmark - Face landmark * @property { Rectangle } location - Face location * @property { string } md5 - Face md5 */ /** * Get Face Json format data * * @returns {FaceJsonObject} */ public toJSON (): FaceJsonObject { const imageData = this.imageData const location = this.location if (!imageData) { throw new Error('no image data') } if (!location) { throw new Error('no location') } const { confidence, embedding, landmark, md5, } = this const embeddingArray = embedding ? embedding.tolist() : [] const imageDataBase64 = Buffer.from(imageData.data.buffer as ArrayBuffer) .toString('base64') const obj = { confidence, embedding: embeddingArray, // turn nj.NdArray to javascript array imageData: imageDataBase64, landmark, location, md5, } return obj } /** * * @static * @param {(FaceJsonObject | string)} obj * @returns {Face} */ public static fromJSON (obj: FaceJsonObject | string): Face { log.verbose('Face', 'fromJSON(%s)', typeof obj) if (typeof obj === 'string') { log.silly('Face', 'fromJSON() JSON.parse(obj)') obj = JSON.parse(obj) as FaceJsonObject } const buffer = Buffer.from(obj.imageData, 'base64') const array = new Uint8ClampedArray(buffer) const location = obj.location const imageData = createImageData(array, location.w, location.h) const face = new Face(imageData) const options = {} as FaceOptions options.boundingBox = [ obj.location.x, obj.location.y, obj.location.x + obj.location.w, obj.location.y + obj.location.h, ] options.confidence = obj.confidence options.md5 = obj.md5 if (obj.landmark) { const m = obj.landmark options.landmarks = [ [m.leftEye.x, m.leftEye.y], [m.rightEye.x, m.rightEye.y], [m.nose.x, m.nose.y], [m.leftMouthCorner.x, m.leftMouthCorner.y], [m.rightMouthCorner.x, m.rightMouthCorner.y], ] } face.initSync(options) if (obj.embedding && obj.embedding.length) { face.embedding = nj.array(obj.embedding) } else { log.verbose('Face', 'fromJSON() no embedding found for face %s#%s', face.id, face.md5) } return face } /** * * Embedding the face, FaceEmbedding is 128 dim * @type {(FaceEmbedding | undefined)} * @memberof Face */ public get embedding (): FaceEmbedding | undefined { // if (!this._embedding) { // throw new Error('no embedding yet!') // } return this._embedding } /** * * Set embedding for a face */ public set embedding (embedding: FaceEmbedding | undefined) { if (!embedding) { throw new Error(`Face<${this.md5}> embedding must defined!`) } else if (!(embedding instanceof (nj as any).NdArray) && embedding.constructor.name !== 'NdArray' ) { console.error(embedding.constructor.name, embedding) throw new Error(`Face<${this.md5}> embedding is not instanceof nj.NdArray!(${typeof embedding} instead)`) } else if (this._embedding) { throw new Error(`Face<${this.md5}> already had embedding!`) } else if (!embedding.shape) { throw new Error(`Face<${this.md5}> embedding has no shape property!`) } else if (embedding.shape[0] !== 128) { throw new Error(`Face<${this.md5}> embedding dim is not 128! got: ${embedding.shape[0]}`) } this._embedding = embedding } /** * @desc Point Type * @typedef Point * @property { number } x * @property { number } y */ /** * * Get center point for the location * @type {Point} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face center : ', faceList[0].center) * // Output: center: { x: 475, y: 209 } */ public get center (): Point { if (!this.location) { throw new Error('no location') } if (!this.imageData) { throw new Error('no imageData') } const x = Math.round(this.location.x + this.imageData.width / 2) const y = Math.round(this.location.y + this.imageData.height / 2) return { x, y } } /** * * Get width for the imageData * @type {number} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face width : ', faceList[0].width) * // Output: width: 230 */ public get width (): number { if (!this.imageData) { throw new Error('no imageData') } return this.imageData.width } /** * * Get height for the imageData * @type {number} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face height : ', faceList[0].height) * // Output: height: 230 */ public get height (): number { if (!this.imageData) { throw new Error('no imageData') } return this.imageData.height } /** * * Get depth for the imageData: length/width/height * @type {number} * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * console.info('face depth : ', faceList[0].depth) * // Output: depth: 4 */ public get depth (): number { if (!this.imageData) { throw new Error('no imageData') } return this.imageData.data.length / this.imageData.width / this.imageData.height } /** * * Get the two face's distance, the smaller the number is, the similar of the two face * @param {Face} face * @returns {number} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * faceList[0].embedding = await facenet.embedding(faceList[0]) * faceList[1].embedding = await facenet.embedding(faceList[1]) * console.info('distance between the different face: ', faceList[0].distance(faceList[1])) * console.info('distance between the same face: ', faceList[0].distance(faceList[0])) * // Output * // distance between the different face: 1.2971515811057608 * // distance between the same face: 0 * // faceList[0] is totally the same with faceList[0], so the number is 0 * // faceList[1] is different with faceList[1], so the number is big. * // If the number is smaller than 0.75, maybe they are the same person. */ public distance (face: Face): number { if (!this.embedding) { throw new Error(`sourceFace(${this.md5}).distance() source face no embedding!`) } if (!face.embedding) { throw new Error(`Face.distance(${face.md5}) target face no embedding!`) } const faceEmbeddingNdArray = face.embedding.reshape(1, -1) as nj.NdArray return distance(this.embedding, faceEmbeddingNdArray)[0] } /** * @private */ public dataUrl (): string { if (!this.imageData) { throw new Error('no imageData') } return toDataURL(this.imageData) } /** * @private */ public buffer (): Buffer { if (!this.imageData) { throw new Error('no imageData') } return toBuffer(this.imageData) } /** * * Save the face to the file * @param {string} file * @returns {Promise<void>} * @example * const imageFile = `${__dirname}/../tests/fixtures/two-faces.jpg` * const faceList = await facenet.align(imageFile) * faceList[0].save('womenFace.jpg') * // You can see it save the women face from `two-faces` pic to `womenFace.jpg` */ public async save (file: string): Promise<void> { if (!this.imageData) { throw new Error('no imageData') } await saveImage(this.imageData, file) } }
the_stack
import { SpawnSyncReturns } from "child_process"; import { join } from "path"; import { writeToFileSync } from "./utils"; import { readFileSync, existsSync } from "fs"; import { CompanionConfig } from "./companion"; export const ATTIC = "attic"; export const TESTCASES = "testcases"; export const LANGUAGES = "languages"; // TODO(#68): Allow checker to compile without time limit (this should be added after cancel is available). export const FRIEND_TIMEOUT = 50_000; export const MAIN_SOLUTION_BINARY = "sol"; export const CHECKER_BINARY = "checker"; export const BRUTE_BINARY = "brute"; export const GENERATOR_BINARY = "generator"; export const GENERATED_TEST_CASE = "gen"; export enum Verdict { OK, // Accepted WA, // Wrong Answer TLE, // Time Limit Exceeded RTE, // Runtime Error CE, // Compilation Error FAIL, // Failed. This verdict is emitted when there is a problem with checker or brute solution. NO_TESTCASES, } export class TestCaseResult { status: Verdict; spanTime?: number; constructor(status: Verdict, spanTime?: number) { this.status = status; this.spanTime = spanTime; } isOk() { return this.status === Verdict.OK; } } export class SolutionResult { status: Verdict; private failTestCaseId: Option<string>; private maxTime: Option<number>; constructor(status: Verdict, failTestCaseId?: string, maxTime?: number) { this.status = status; this.failTestCaseId = new Option(failTestCaseId); this.maxTime = new Option(maxTime); } isOk() { return this.status === Verdict.OK; } /** * Return id from failing test case. Will throw error if isOk() */ getFailTestCaseId() { return this.failTestCaseId.unwrap(); } /** * Return max time among all test cases. Will throw error if !isOk() */ getMaxTime() { return this.maxTime.unwrap(); } } export class Problem { identifier?: string; name?: string; inputs?: string[]; outputs?: string[]; constructor( identifier?: string, name?: string, inputs?: string[], outputs?: string[] ) { this.identifier = identifier; this.name = name; this.inputs = inputs; this.outputs = outputs; } } export class Contest { name: string; problems: Problem[]; constructor(name: string, problems: Problem[]) { this.name = name; this.problems = problems; } } export class SiteDescription { name: string; description: string; contestIdPlaceholder: string; problemIdPlaceholder: string; contestParser: (contestId: string) => Contest; problemParser: (problemId: string) => Problem; constructor( name: string, description: string, contestIdPlaceholder: string, problemIdPlaceholder: string, contestParser: (contestId: string) => Contest, problemParser: (problemId: string) => Problem ) { this.name = name; this.description = description; this.contestIdPlaceholder = contestIdPlaceholder; this.problemIdPlaceholder = problemIdPlaceholder; this.contestParser = contestParser; this.problemParser = problemParser; } } export class Execution { private cached: boolean; private result: Option<SpawnSyncReturns<Buffer>>; timeSpan: Option<number>; timeout: Option<number>; constructor( result?: SpawnSyncReturns<Buffer>, timeSpan?: number, timeout?: number, cached?: boolean ) { this.result = new Option(result); this.timeSpan = new Option(timeSpan); this.timeout = new Option(timeout); this.cached = cached || false; } static cached() { return new Execution(undefined, undefined, undefined, true); } getCached() { return this.cached; } isTLE() { return ( !this.getCached() && this.timeSpan.unwrap() >= this.timeout.unwrap() ); } failed() { return !this.getCached() && this.result.unwrap().status !== 0; } status() { return this.result.mapOr(0, (result) => { return result.status; }); } /** * This method will raise an error if is called on a cached execution. */ stdout() { return this.result.unwrap().stdout; } /** * This method will raise an error if is called on a cached execution. */ stderr() { return this.result.unwrap().stderr; } } export class LanguageCommand { run: string[]; preRun: string[]; constructor(run: string[], preRun: string[]) { this.run = run; this.preRun = preRun; } } export class Option<T> { value?: T; constructor(value?: T) { this.value = value; } static none<T>() { return new Option<T>(undefined); } static some<T>(value: T) { return new Option<T>(value); } isSome() { return this.value !== undefined; } isNone() { return !this.isSome(); } unwrap(): T { if (this.value === undefined) { throw new Error("Expected value found undefined"); } else { return this.value; } } unwrapOr(value: T): T { if (this.isSome()) { return this.unwrap(); } else { return value; } } map<R>(predicate: (arg: T) => R): Option<R> { if (this.isSome()) { return Option.some(predicate(this.unwrap())); } else { return Option.none(); } } mapOr<R>(value: R, predicate: (arg: T) => R): R { if (this.isSome()) { return predicate(this.unwrap()); } else { return value; } } } /** * Result of compiling code file. * Path to code file, and output file. * If no compilation was performed `output` is Option.none */ export class CompileResult { code: string; private output: Option<string>; constructor(code: string, output?: string) { this.code = code; this.output = new Option(output); } getOutput() { return this.output.unwrapOr(""); } } export class ConfigFile { mainSolution: Option<string>; bruteSolution: Option<string>; generator: Option<string>; checker: Option<string>; companionConfig: Option<CompanionConfig>; constructor( mainSolution?: string, bruteSolution?: string, generator?: string, checker?: string ) { this.mainSolution = new Option(mainSolution); this.bruteSolution = new Option(bruteSolution); this.generator = new Option(generator); this.checker = new Option(checker); this.companionConfig = Option.none(); } setCompanionConfig(companionConfig: CompanionConfig) { this.companionConfig = Option.some(companionConfig); } /** * Check configuration file already exist, and create it otherwise with * default solution problem. */ static checkExist(path: string) { if (!existsSync(join(path, ATTIC, "config.json"))) { let config = ConfigFile.empty(); let mainSolution = join(path, "sol.cpp"); if (existsSync(mainSolution)) { config.mainSolution = Option.some(mainSolution); } config.dump(path); } } dump(path: string) { let configFile = JSON.stringify(this, null, 2); writeToFileSync(join(path, ATTIC, "config.json"), configFile); } /** * Check that all files specified in configurations exist and remove it otherwise. */ private verify() { let changed = false; if (!this.mainSolution.mapOr(true, existsSync)) { this.mainSolution = Option.none(); changed = true; } if (!this.bruteSolution.mapOr(true, existsSync)) { this.bruteSolution = Option.none(); changed = true; } if (!this.generator.mapOr(true, existsSync)) { this.generator = Option.none(); changed = true; } if (!this.checker.mapOr(true, existsSync)) { this.checker = Option.none(); changed = true; } return changed; } static loadConfig( path: string, checkExist: boolean = false ): Option<ConfigFile> { if (checkExist) { ConfigFile.checkExist(path); } let configPath = join(path, ATTIC, "config.json"); if (existsSync(configPath)) { let configData = readFileSync( join(path, ATTIC, "config.json"), "utf8" ); let parsed = JSON.parse(configData); let config = new ConfigFile( parsed.mainSolution?.value, parsed.bruteSolution?.value, parsed.generator?.value, parsed.checker?.value ); config.setCompanionConfig(parsed.companionConfig?.value); if (config.verify()) { config.dump(path); } return Option.some(config); } else { return Option.none(); } } static empty(): ConfigFile { return new ConfigFile(); } timeLimit(): Option<number> { return this.companionConfig.map((config) => config.timeLimit); } url(): Option<string> { return this.companionConfig.map((config) => config.url); } } export class ProblemInContest { problemConfig: ConfigFile; contestPath: string; constructor(problemConfig: ConfigFile, contestPath: string) { this.problemConfig = problemConfig; this.contestPath = contestPath; } } export function verdictName(verdict: Verdict) { switch (verdict) { case Verdict.OK: return "OK"; case Verdict.WA: return "WA"; case Verdict.TLE: return "TLE"; case Verdict.RTE: return "RTE"; case Verdict.CE: return "CE"; case Verdict.FAIL: return "FAIL"; default: throw new Error("Invalid Verdict"); } }
the_stack
import type { LDClient as TLDClient, LDOptions as TLDOptions, } from 'launchdarkly-js-client-sdk'; import type { LDUser as TLDUser } from 'launchdarkly-js-sdk-common'; export type TFlagName = string; export type TFlagVariation = | boolean | string | number | Record<string, unknown> | unknown[]; export type TFlag = [flagName: TFlagName, flagVariation: TFlagVariation]; export type TFlags = Record<string, TFlagVariation>; export type TUser<TAdditionalUserProperties = Record<string, unknown>> = { key?: string; } & TAdditionalUserProperties; export enum AdapterSubscriptionStatus { Subscribed, Unsubscribed, } export enum AdapterConfigurationStatus { Unconfigured, Configuring, Configured, } export enum AdapterInitializationStatus { Succeeded, Failed, } export type TAdapterConfiguration = { initializationStatus?: AdapterInitializationStatus; }; export type TAdapterStatus = { configurationStatus: AdapterConfigurationStatus; subscriptionStatus: AdapterSubscriptionStatus; }; export type TAdapterStatusChange = { id?: TAdapterIdentifiers; status: Partial<TAdapterStatus>; }; export type TFlagsChange = { id?: TAdapterIdentifiers; flags: TFlags }; export type TAdapterEventHandlers = { onFlagsStateChange: (flagsChange: TFlagsChange) => void; onStatusStateChange: (statusChange: TAdapterStatusChange) => void; }; type TDefaultAdditionalUserProperties = Record<string, unknown>; export type TBaseAdapterArgs< TAdditionalUserProperties = TDefaultAdditionalUserProperties > = { user: TUser<TAdditionalUserProperties>; }; export type TLaunchDarklyAdapterArgs = TBaseAdapterArgs<TLDUser> & { sdk: { clientSideId: string; clientOptions?: TLDOptions; }; flags: TFlags; subscribeToFlagChanges?: boolean; throwOnInitializationFailure?: boolean; flagsUpdateDelayMs?: number; }; export type TGraphQlAdapterArgs< TAdditionalUserProperties = TDefaultAdditionalUserProperties > = TBaseAdapterArgs<TAdditionalUserProperties> & { fetcher?: typeof fetch; uri: string; query: string; pollingInteralMs?: number; getQueryVariables?: (adapterArgs: TGraphQlAdapterArgs) => unknown; getRequestHeaders?: ( adapterArgs: TGraphQlAdapterArgs ) => Record<string, string>; parseFlags?: <TFetchedFlags = unknown, TParsedFlags = TFlags>( fetchedFlags: TFetchedFlags ) => TParsedFlags; cacheIdentifier?: TCacheIdentifiers; }; export type THttpAdapterArgs< TAdditionalUserProperties = TDefaultAdditionalUserProperties > = TBaseAdapterArgs<TAdditionalUserProperties> & { execute: () => Promise<any>; pollingInteralMs?: number; cacheIdentifier?: TCacheIdentifiers; }; export type TLocalStorageAdapterArgs< TAdditionalUserProperties = TDefaultAdditionalUserProperties > = TBaseAdapterArgs<TAdditionalUserProperties> & { pollingInteralMs?: number; }; export type TMemoryAdapterArgs< TAdditionalUserProperties = TDefaultAdditionalUserProperties > = TBaseAdapterArgs<TAdditionalUserProperties>; export type TSplitioAdapterArgs = TBaseAdapterArgs & { sdk: { authorizationKey: string; options?: Record<string, unknown> & { core?: Record<string, string> }; // Matches the signature of SplitIO.Attributes treatmentAttributes?: Record< string, string | number | boolean | Array<string | number> >; }; }; export type TCombinedAdapterArgs< TAdditionalUserProperties = TDefaultAdditionalUserProperties, TAdditionalHttpUserProperties = TDefaultAdditionalUserProperties, TAdditionalGraphQlUserProperties = TDefaultAdditionalUserProperties, TAdditionalLocalStorageUserProperties = TDefaultAdditionalUserProperties, TAdditionalMemoryUserProperties = TDefaultAdditionalUserProperties > = TBaseAdapterArgs<TAdditionalUserProperties> & { launchdarkly?: TLaunchDarklyAdapterArgs; localstorage?: TLocalStorageAdapterArgs<TAdditionalLocalStorageUserProperties>; memory?: TMemoryAdapterArgs<TAdditionalMemoryUserProperties>; splitio?: TSplitioAdapterArgs; graphql?: TGraphQlAdapterArgs<TAdditionalGraphQlUserProperties>; http?: THttpAdapterArgs<TAdditionalHttpUserProperties>; }; export type TAdapterArgs = | TLaunchDarklyAdapterArgs | TLocalStorageAdapterArgs | TMemoryAdapterArgs | TSplitioAdapterArgs | TGraphQlAdapterArgs | THttpAdapterArgs | TCombinedAdapterArgs; export const adapterIdentifiers = { launchdarkly: 'launchdarkly', localstorage: 'localstorage', memory: 'memory', splitio: 'splitio', graphql: 'graphql', http: 'http', combined: 'combined', } as const; export type TAdapterIdentifiers = | typeof adapterIdentifiers[keyof typeof adapterIdentifiers] | string; export type TFlagsContext = Record<TAdapterIdentifiers, TFlags>; export const cacheIdentifiers = { local: 'local', session: 'session', } as const; export type TCacheIdentifiers = typeof cacheIdentifiers[keyof typeof cacheIdentifiers]; export type TUpdateFlagsOptions = { lockFlags?: boolean; unsubscribeFlags?: boolean; }; export type TFlagsUpdateFunction = ( flags: TFlags, options?: TUpdateFlagsOptions ) => void; export interface TAdapterInterface<Args extends TAdapterArgs> { // Identifiers are used to uniquely identify an interface when performing a condition check. id: TAdapterIdentifiers; // Used if a combined adapter intends to affect variaus other adapter's feature states effectIds?: TAdapterIdentifiers[]; configure: ( adapterArgs: Args, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; reconfigure: ( adapterArgs: Args, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; getIsConfigurationStatus: ( configurationStatus: AdapterConfigurationStatus ) => boolean; setConfigurationStatus?: ( nextConfigurationStatus: AdapterConfigurationStatus ) => void; waitUntilConfigured?: () => Promise<unknown>; reset?: () => void; getFlag?: (flagName: TFlagName) => TFlagVariation | undefined; unsubscribe: () => void; subscribe: () => void; updateFlags: TFlagsUpdateFunction; getUser?: () => TUser | undefined; } export interface TLaunchDarklyAdapterInterface extends TAdapterInterface<TLaunchDarklyAdapterArgs> { id: typeof adapterIdentifiers.launchdarkly; configure: ( adapterArgs: TLaunchDarklyAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; reconfigure: ( adapterArgs: TLaunchDarklyAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; getIsConfigurationStatus: ( adapterConfigurationStatus: AdapterConfigurationStatus ) => boolean; getClient: () => TLDClient | undefined; getFlag: (flagName: TFlagName) => TFlagVariation | undefined; updateUserContext: ( updatedUserProps: TLaunchDarklyAdapterArgs['user'] ) => Promise<unknown>; unsubscribe: () => void; subscribe: () => void; } export interface TLocalStorageAdapterInterface extends TAdapterInterface<TLocalStorageAdapterArgs> { id: typeof adapterIdentifiers.localstorage; configure: ( adapterArgs: TLocalStorageAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; reconfigure: ( adapterArgs: TLocalStorageAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; getIsConfigurationStatus: ( adapterConfigurationStatus: AdapterConfigurationStatus ) => boolean; waitUntilConfigured: () => Promise<unknown>; unsubscribe: () => void; subscribe: () => void; } export interface TGraphQlAdapterInterface extends TAdapterInterface<TGraphQlAdapterArgs> { id: typeof adapterIdentifiers.graphql; configure: ( adapterArgs: TGraphQlAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; reconfigure: ( adapterArgs: TGraphQlAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; getIsConfigurationStatus: ( adapterConfigurationStatus: AdapterConfigurationStatus ) => boolean; waitUntilConfigured: () => Promise<unknown>; unsubscribe: () => void; subscribe: () => void; } export interface THttpAdapterInterface extends TAdapterInterface<THttpAdapterArgs> { id: typeof adapterIdentifiers.http; configure: ( adapterArgs: THttpAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; reconfigure: ( adapterArgs: THttpAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; getIsConfigurationStatus: ( adapterConfigurationStatus: AdapterConfigurationStatus ) => boolean; waitUntilConfigured: () => Promise<unknown>; unsubscribe: () => void; subscribe: () => void; } export interface TMemoryAdapterInterface extends TAdapterInterface<TMemoryAdapterArgs> { id: typeof adapterIdentifiers.memory; configure: ( adapterArgs: TMemoryAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; reconfigure: ( adapterArgs: TMemoryAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; getIsConfigurationStatus: ( adapterConfigurationStatus: AdapterConfigurationStatus ) => boolean; waitUntilConfigured: () => Promise<unknown>; reset: () => void; updateFlags: TFlagsUpdateFunction; unsubscribe: () => void; subscribe: () => void; } export interface TCombinedAdapterInterface extends TAdapterInterface<TCombinedAdapterArgs> { id: typeof adapterIdentifiers.combined; effectIds?: TAdapterIdentifiers[]; combine: <TAdapterInstance extends TAdapter>( adapters: TAdapterInstance[] ) => void; configure: ( adapterArgs: TCombinedAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; reconfigure: ( adapterArgs: TCombinedAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; getIsConfigurationStatus: ( adapterConfigurationStatus: AdapterConfigurationStatus ) => boolean; waitUntilConfigured: () => Promise<unknown>; reset: () => void; updateFlags: TFlagsUpdateFunction; unsubscribe: () => void; subscribe: () => void; } export interface TSplitioAdapterInterface extends TAdapterInterface<TSplitioAdapterArgs> { id: typeof adapterIdentifiers.splitio; configure: ( adapterArgs: TSplitioAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; reconfigure: ( adapterArgs: TSplitioAdapterArgs, adapterEventHandlers: TAdapterEventHandlers ) => Promise<TAdapterConfiguration>; getIsConfigurationStatus: ( adapterConfigurationStatus: AdapterConfigurationStatus ) => boolean; unsubscribe: () => void; subscribe: () => void; } export type TAdapter = | TLaunchDarklyAdapterInterface | TLocalStorageAdapterInterface | TMemoryAdapterInterface | TSplitioAdapterInterface | TGraphQlAdapterInterface | THttpAdapterInterface | TCombinedAdapterInterface; export type TConfigureAdapterArgs< TAdapterInstance extends TAdapter > = TAdapterInstance extends TLaunchDarklyAdapterInterface ? TLaunchDarklyAdapterArgs : TAdapterInstance extends TLocalStorageAdapterInterface ? TLocalStorageAdapterArgs : TAdapterInstance extends TMemoryAdapterInterface ? TMemoryAdapterArgs : TAdapterInstance extends TSplitioAdapterInterface ? TSplitioAdapterArgs : TAdapterInstance extends TGraphQlAdapterInterface ? TGraphQlAdapterArgs : TAdapterInstance extends THttpAdapterInterface ? THttpAdapterArgs : TAdapterInstance extends TCombinedAdapterInterface ? TCombinedAdapterArgs : never; export type TConfigureAdapterProps<TAdapterInstance extends TAdapter> = { adapter: TAdapterInstance extends TLaunchDarklyAdapterInterface ? TLaunchDarklyAdapterInterface : TAdapterInstance extends TLocalStorageAdapterInterface ? TLocalStorageAdapterInterface : TAdapterInstance extends TMemoryAdapterInterface ? TMemoryAdapterInterface : TAdapterInstance extends TSplitioAdapterInterface ? TSplitioAdapterInterface : TAdapterInstance extends TGraphQlAdapterInterface ? TGraphQlAdapterInterface : TAdapterInstance extends THttpAdapterInterface ? THttpAdapterInterface : TAdapterInstance extends TCombinedAdapterInterface ? TCombinedAdapterInterface : never; adapterArgs: TConfigureAdapterArgs<TAdapterInstance>; }; export type TAdapterReconfigurationOptions = { shouldOverwrite?: boolean; }; export type TAdapterReconfiguration = { adapterArgs: TAdapterArgs; options: TAdapterReconfigurationOptions; }; export type TConfigureAdapterChildrenAsFunctionArgs = { isAdapterConfigured: boolean; }; export type TConfigureAdapterChildrenAsFunction = ( args: TConfigureAdapterChildrenAsFunctionArgs ) => React.ReactNode; export type TConfigureAdapterChildren = | TConfigureAdapterChildrenAsFunction | React.ReactNode; export type TReconfigureAdapter = ( adapterArgs: TAdapterArgs, options: TAdapterReconfigurationOptions ) => void; export type TAdapterContext = { adapterEffectIdentifiers: TAdapterIdentifiers[]; reconfigure: TReconfigureAdapter; status: TAdapterStatus; }; type TLaunchDarklyFlopflipGlobal = { adapter: TLaunchDarklyAdapterInterface; updateFlags: TFlagsUpdateFunction; }; type TSplitioAdapterGlobal = { adapter: TSplitioAdapterInterface; updateFlags: TFlagsUpdateFunction; }; type TMemoryAdapterGlobal = { adapter: TMemoryAdapterInterface; updateFlags: TFlagsUpdateFunction; }; type TLocalStorageAdapterGlobal = { adapter: TLocalStorageAdapterInterface; updateFlags: TFlagsUpdateFunction; }; type TGraphQlAdapterGlobal = { adapter: TLocalStorageAdapterInterface; updateFlags: TFlagsUpdateFunction; }; type THttpAdapterGlobal = { adapter: TLocalStorageAdapterInterface; updateFlags: TFlagsUpdateFunction; }; type TCombinedAdapterGlobal = { adapter: TCombinedAdapterInterface; updateFlags: TFlagsUpdateFunction; }; export type TFlopflipGlobal = { [adapterIdentifiers.launchdarkly]?: TLaunchDarklyFlopflipGlobal; [adapterIdentifiers.splitio]?: TSplitioAdapterGlobal; [adapterIdentifiers.memory]?: TMemoryAdapterGlobal; [adapterIdentifiers.localstorage]?: TLocalStorageAdapterGlobal; [adapterIdentifiers.graphql]?: TGraphQlAdapterGlobal; [adapterIdentifiers.http]?: THttpAdapterGlobal; [adapterIdentifiers.combined]?: TCombinedAdapterGlobal; }; declare global { interface Window { __flopflip__: TFlopflipGlobal; } } export type TDiff<ExcludedFrom, ToExclude> = Pick< ExcludedFrom, Exclude<keyof ExcludedFrom, keyof ToExclude> >; export type TCache = { get: <T = any>(key: string) => T; set: (key: string, value: any) => boolean; unset: (key: string) => void; }; export type TCacheOptions = { prefix: string; };
the_stack
import { ClassType } from '@deepkit/core'; import { expect, test } from '@jest/globals'; import { entity, t } from '../src/decorator'; import { propertiesOf, reflect, ReflectionClass, ReflectionFunction, ReflectionMethod, typeOf, valuesOf } from '../src/reflection/reflection'; import { annotateClass, assertType, AutoIncrement, autoIncrementAnnotation, BackReference, Data, databaseAnnotation, DatabaseField, defaultAnnotation, Embedded, Entity, entityAnnotation, Excluded, Group, groupAnnotation, Index, integer, isPrimaryKeyType, MapName, metaAnnotation, MySQL, Postgres, PrimaryKey, primaryKeyAnnotation, Reference, referenceAnnotation, ReflectionKind, ReflectionVisibility, SQLite, stringifyResolvedType, Type, TypeClass, TypeFunction, TypeIndexSignature, TypeMethod, TypeNumber, TypeObjectLiteral, TypeTuple, Unique } from '../src/reflection/type'; import { TypeNumberBrand } from '@deepkit/type-spec'; import { MinLength, validate, ValidatorError } from '../src/validator'; import { expectEqualType } from './utils'; import { MyAlias } from './types'; import { resolveRuntimeType } from '../src/reflection/processor'; import { uuid } from '../src/utils'; import { deserialize } from '../src/serializer-facade'; test('class', () => { class Entity { tags!: string[]; } const type = reflect(Entity); expectEqualType(type, { kind: ReflectionKind.class, classType: Entity, types: [ { kind: ReflectionKind.property, visibility: ReflectionVisibility.public, name: 'tags', type: { kind: ReflectionKind.array, type: { kind: ReflectionKind.string } } } ] }); }); test('class optional question mark', () => { class Entity { title?: string; } const type = reflect(Entity); expectEqualType(type, { kind: ReflectionKind.class, classType: Entity, types: [ { kind: ReflectionKind.property, visibility: ReflectionVisibility.public, name: 'title', optional: true, type: { kind: ReflectionKind.string } } ] }); }); test('class optional union', () => { class Entity { title: string | undefined; } const type = reflect(Entity); expectEqualType(type, { kind: ReflectionKind.class, classType: Entity, types: [ { kind: ReflectionKind.property, visibility: ReflectionVisibility.public, name: 'title', optional: true, type: { kind: ReflectionKind.string } } ] }); }); test('class constructor', () => { class Entity1 { constructor(title: string) { } } class Entity2 { constructor(public title: string) { } } expectEqualType(reflect(Entity1), { kind: ReflectionKind.class, classType: Entity1, types: [ { kind: ReflectionKind.method, visibility: ReflectionVisibility.public, name: 'constructor', parameters: [ { kind: ReflectionKind.parameter, name: 'title', type: { kind: ReflectionKind.string } } ], return: { kind: ReflectionKind.any } } ] } as Type); expectEqualType(reflect(Entity2), { kind: ReflectionKind.class, classType: Entity2, types: [ { kind: ReflectionKind.method, visibility: ReflectionVisibility.public, name: 'constructor', parameters: [ { kind: ReflectionKind.parameter, name: 'title', visibility: ReflectionVisibility.public, type: { kind: ReflectionKind.string } } ], return: { kind: ReflectionKind.any } }, { kind: ReflectionKind.property, visibility: ReflectionVisibility.public, name: 'title', type: { kind: ReflectionKind.string } }, ] } as Type); }); test('class extends another', () => { class Class1 { constructor(title: string) { } } class Class2 extends Class1 { constructor() { super('asd'); } } const reflection = ReflectionClass.from(Class2); const constructor = reflection.getMethodOrUndefined('constructor'); expect(constructor).toBeInstanceOf(ReflectionMethod); expect(constructor!.getParameters().length).toBe(0); }); test('class expression extends another', () => { class Class1 { constructor(title: string) { } } const class2 = class extends Class1 { constructor() { super('asd'); } } const reflection = ReflectionClass.from(class2); const constructor = reflection.getMethodOrUndefined('constructor'); expect(constructor).toBeInstanceOf(ReflectionMethod); expect(constructor!.getParameters().length).toBe(0); }); test('constructor type abstract', () => { type constructor = abstract new (...args: any) => any; expectEqualType(typeOf<constructor>(), { kind: ReflectionKind.function, name: 'new', parameters: [ { kind: ReflectionKind.parameter, name: 'args', type: { kind: ReflectionKind.rest, type: { kind: ReflectionKind.any } } } ], return: { kind: ReflectionKind.any } }); }); test('constructor type normal', () => { type constructor = new (a: string, b: number) => void; expectEqualType(typeOf<constructor>(), { kind: ReflectionKind.function, name: 'new', parameters: [ { kind: ReflectionKind.parameter, name: 'a', type: { kind: ReflectionKind.string } }, { kind: ReflectionKind.parameter, name: 'b', type: { kind: ReflectionKind.number } }, ], return: { kind: ReflectionKind.void } } as TypeFunction); }); test('interface', () => { interface Entity { tags: string[]; } const type = typeOf<Entity>(); expectEqualType(type, { kind: ReflectionKind.objectLiteral, typeName: 'Entity', types: [ { kind: ReflectionKind.propertySignature, name: 'tags', type: { kind: ReflectionKind.array, type: { kind: ReflectionKind.string } } } ] }); }); test('tuple', () => { { const type = typeOf<[string]>(); expectEqualType(type, { kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.string } } ] } as TypeTuple); } { const type = typeOf<[string, number]>(); expectEqualType(type, { kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.string } }, { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.number } } ] } as TypeTuple); } }); test('any of type alias', () => { { const type = typeOf<MyAlias<any>>(); expectEqualType(type, { kind: ReflectionKind.any }); } { class MyClass { private c: MyAlias<any>; } const reflection = ReflectionClass.from(MyClass); const property = reflection.getProperty('c'); expectEqualType(property.type, { kind: ReflectionKind.any }); } }); test('named tuple', () => { { const type = typeOf<[title: string]>(); expectEqualType(type, { kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.string }, name: 'title' } ] } as TypeTuple); } { const type = typeOf<[title: string, prio: number]>(); expectEqualType(type, { kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.string }, name: 'title' }, { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.number }, name: 'prio' } ] } as TypeTuple); } }); test('rest tuple', () => { { const type = typeOf<[...string[]]>(); expectEqualType(type, { kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.rest, type: { kind: ReflectionKind.string } } } ] } as TypeTuple); } { const type = typeOf<[...string[], number]>(); expectEqualType(type, { kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.rest, type: { kind: ReflectionKind.string } } }, { kind: ReflectionKind.tupleMember, type: { kind: ReflectionKind.number } } ] } as TypeTuple); } }); test('rest named tuple', () => { { const type = typeOf<[...title: string[]]>(); expectEqualType(type, { kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, name: 'title', type: { kind: ReflectionKind.rest, type: { kind: ReflectionKind.string } } } ] } as TypeTuple); } { const type = typeOf<[...title: string[], prio: number]>(); expectEqualType(type, { kind: ReflectionKind.tuple, types: [ { kind: ReflectionKind.tupleMember, name: 'title', type: { kind: ReflectionKind.rest, type: { kind: ReflectionKind.string } } }, { kind: ReflectionKind.tupleMember, name: 'prio', type: { kind: ReflectionKind.number } }, ] } as TypeTuple); } }); test('typeof primitives', () => { expectEqualType(typeOf<string>(), { kind: ReflectionKind.string }); expectEqualType(typeOf<number>(), { kind: ReflectionKind.number }); expectEqualType(typeOf<boolean>(), { kind: ReflectionKind.boolean }); expectEqualType(typeOf<bigint>(), { kind: ReflectionKind.bigint }); expectEqualType(typeOf<null>(), { kind: ReflectionKind.null }); expectEqualType(typeOf<undefined>(), { kind: ReflectionKind.undefined }); expectEqualType(typeOf<any>(), { kind: ReflectionKind.any }); expectEqualType(typeOf<never>(), { kind: ReflectionKind.never }); expectEqualType(typeOf<void>(), { kind: ReflectionKind.void }); }); test('typeof union', () => { type t = 'a' | 'b'; expectEqualType(typeOf<t>(), { kind: ReflectionKind.union, types: [{ kind: ReflectionKind.literal, literal: 'a' }, { kind: ReflectionKind.literal, literal: 'b' }] }); }); test('valuesOf union', () => { type t = 'a' | 'b'; expectEqualType(valuesOf<t>(), ['a', 'b']); expectEqualType(valuesOf<string | number>(), [{ kind: ReflectionKind.string }, { kind: ReflectionKind.number }]); }); test('valuesOf object literal', () => { type t = { a: string, b: number }; expectEqualType(valuesOf<t>(), [{ kind: ReflectionKind.string }, { kind: ReflectionKind.number }]); }); test('propertiesOf inline', () => { expect(propertiesOf<{ a: string, b: number }>()).toEqual(['a', 'b']); }); test('object literal index signature', () => { type t = { [name: string]: string | number, a: string, }; expect(typeOf<t>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.indexSignature, index: { kind: ReflectionKind.string }, type: { kind: ReflectionKind.union, types: [{ kind: ReflectionKind.string }, { kind: ReflectionKind.number }] } } as TypeIndexSignature, { kind: ReflectionKind.propertySignature, name: 'a', type: { kind: ReflectionKind.string } } ] }); }); test('propertiesOf external', () => { type o = { a: string, b: number }; expect(propertiesOf<o>()).toEqual(['a', 'b']); }); test('propertiesOf class', () => { class User { a!: string; b!: string; } expect(propertiesOf<User>()).toEqual(['a', 'b']); }); test('typeof object literal', () => { expectEqualType(typeOf<{ a: string }>(), { kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'a', type: { kind: ReflectionKind.string } }] } as TypeObjectLiteral); }); test('typeof object literal with function', () => { expectEqualType(typeOf<{ add(item: string): any }>(), { kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.methodSignature, name: 'add', parameters: [{ kind: ReflectionKind.parameter, name: 'item', type: { kind: ReflectionKind.string } }], return: { kind: ReflectionKind.any } }] } as TypeObjectLiteral); }); test('typeof class', () => { class Entity { a!: string; } expectEqualType(typeOf<Entity>(), { kind: ReflectionKind.class, classType: Entity, types: [{ kind: ReflectionKind.property, name: 'a', visibility: ReflectionVisibility.public, type: { kind: ReflectionKind.string } }] } as TypeClass); expectEqualType(reflect(Entity), { kind: ReflectionKind.class, classType: Entity, types: [{ kind: ReflectionKind.property, name: 'a', visibility: ReflectionVisibility.public, type: { kind: ReflectionKind.string } }] } as TypeClass); }); test('typeof generic class', () => { class Entity<T> { a!: T; } expectEqualType(typeOf<Entity<string>>(), { kind: ReflectionKind.class, classType: Entity, arguments: [typeOf<string>()], types: [{ kind: ReflectionKind.property, name: 'a', visibility: ReflectionVisibility.public, type: { kind: ReflectionKind.string } }] } as TypeClass); expectEqualType(reflect(Entity, typeOf<string>()), { kind: ReflectionKind.class, arguments: [typeOf<string>()], classType: Entity, types: [{ kind: ReflectionKind.property, name: 'a', visibility: ReflectionVisibility.public, type: { kind: ReflectionKind.string } }] } as TypeClass); }); test('function', () => { function pad(text: string, size: number): string { return text; } const type = reflect(pad); expectEqualType(type, { kind: ReflectionKind.function, name: 'pad', function: pad, parameters: [ { kind: ReflectionKind.parameter, name: 'text', type: { kind: ReflectionKind.string } }, { kind: ReflectionKind.parameter, name: 'size', type: { kind: ReflectionKind.number } }, ], return: { kind: ReflectionKind.string } }); }); test('type function', () => { type pad = (text: string, size: number) => string; expectEqualType(typeOf<pad>(), { kind: ReflectionKind.function, parameters: [ { kind: ReflectionKind.parameter, name: 'text', type: { kind: ReflectionKind.string } }, { kind: ReflectionKind.parameter, name: 'size', type: { kind: ReflectionKind.number } }, ], return: { kind: ReflectionKind.string } }); }); test('query literal', () => { type o = { a: string | number }; expectEqualType(typeOf<o['a']>(), { kind: ReflectionKind.union, types: [ { kind: ReflectionKind.string }, { kind: ReflectionKind.number }, ] }); }); test('template literal', () => { type l = `_${'a' | 'b'}Changed`; type l2 = `_${string}Changed${'a' | 'b'}`; type l3 = `_${string}Changed${2 | 'b'}`; type l33 = `_${string}Changed${number | 'b'}`; type l4 = `_${string}Changed${true | 'b'}`; type l5 = `_${string}Changed${boolean | 'b'}`; type l6 = `_${string}Changed${bigint | 'b'}`; type l7 = `${string}`; type l77 = `${number}`; type l771 = `${boolean}`; type l8 = `helloworld`; type hw = 'hello' | 'world'; type l9 = `${hw | 'b'}_` type l10 = `${`(${hw})`}_` const type0 = typeOf<l>(); expectEqualType(type0, { kind: ReflectionKind.union, types: [{ kind: ReflectionKind.literal, literal: '_aChanged' }, { kind: ReflectionKind.literal, literal: '_bChanged' }] } as Type); const type1 = typeOf<l2>(); expectEqualType(type1, { kind: ReflectionKind.union, types: [ { kind: ReflectionKind.templateLiteral, types: [ { kind: ReflectionKind.literal, literal: '_' }, { kind: ReflectionKind.string }, { kind: ReflectionKind.literal, literal: 'Changeda' }, ] }, { kind: ReflectionKind.templateLiteral, types: [ { kind: ReflectionKind.literal, literal: '_' }, { kind: ReflectionKind.string }, { kind: ReflectionKind.literal, literal: 'Changedb' }, ] }, ] } as Type); expect(stringifyResolvedType(typeOf<l3>())).toBe('`_${string}Changed2` | `_${string}Changedb`'); expect(stringifyResolvedType(typeOf<l33>())).toBe('`_${string}Changed${number}` | `_${string}Changedb`'); expect(stringifyResolvedType(typeOf<l4>())).toBe('`_${string}Changedtrue` | `_${string}Changedb`'); expect(stringifyResolvedType(typeOf<l5>())).toBe('`_${string}Changedfalse` | `_${string}Changedtrue` | `_${string}Changedb`'); expect(stringifyResolvedType(typeOf<l6>())).toBe('`_${string}Changed${bigint}` | `_${string}Changedb`'); expect(stringifyResolvedType(typeOf<l7>())).toBe('string'); expect(stringifyResolvedType(typeOf<l77>())).toBe('`${number}`'); expect(stringifyResolvedType(typeOf<l771>())).toBe(`'false' | 'true'`); expect(stringifyResolvedType(typeOf<l8>())).toBe(`'helloworld'`); expect(stringifyResolvedType(typeOf<l9>())).toBe(`'hello_' | 'world_' | 'b_'`); expect(stringifyResolvedType(typeOf<l10>())).toBe(`'(hello)_' | '(world)_'`); }); test('mapped type key literal', () => { type o = { a: string, b: number, c: boolean, [2]: any }; type Prefix<T> = { [P in keyof T as P extends string ? `v${P}` : never]: T[P] }; type o2 = Prefix<o>; }); test('pick', () => { class Config { debug: boolean = false; title: string = ''; } type t = Pick<Config, 'debug'>; expectEqualType(typeOf<t>(), { kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'debug', type: { kind: ReflectionKind.boolean } }, ] }); class MyService { constructor(public config: Pick<Config, 'debug'>) { } } const reflection = ReflectionClass.from(MyService); const parameters = reflection.getMethodParameters('constructor'); expect(parameters[0].getType()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'debug', type: { kind: ReflectionKind.boolean } }, ] }); }); test('query union from keyof', () => { type o = { a: string, b: string, c: number }; expectEqualType(typeOf<o[keyof o]>(), { kind: ReflectionKind.union, types: [ { kind: ReflectionKind.string }, { kind: ReflectionKind.number }, ] }); }); test('query union manual', () => { type o = { a: string, b: string, c: number }; expectEqualType(typeOf<o['a' | 'b' | 'c']>(), { kind: ReflectionKind.union, types: [ { kind: ReflectionKind.string }, { kind: ReflectionKind.number }, ] }); }); test('query number index', () => { type o = [string, string, number]; expectEqualType(typeOf<o[number]>(), { kind: ReflectionKind.union, types: [ { kind: ReflectionKind.string }, { kind: ReflectionKind.number }, ] }); expectEqualType(typeOf<o[0]>(), { kind: ReflectionKind.string }); expectEqualType(typeOf<o[1]>(), { kind: ReflectionKind.string }); expectEqualType(typeOf<o[2]>(), { kind: ReflectionKind.number }); }); test('mapped type partial', () => { type Partial2<T> = { [P in keyof T]?: T[P]; } type o = { a: string }; type p = Partial2<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'a', optional: true, type: { kind: ReflectionKind.string } }] }); }); test('mapped type required', () => { type Required2<T> = { [P in keyof T]-?: T[P]; } type o = { a?: string }; type p = Required2<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'a', type: { kind: ReflectionKind.string } }] }); }); test('mapped type partial readonly', () => { type Partial2<T> = { readonly [P in keyof T]?: T[P]; } type o = { a: string }; type p = Partial2<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'a', readonly: true, optional: true, type: { kind: ReflectionKind.string } }] }); }); test('mapped type filter never', () => { type FilterB<T> = { [P in keyof T]?: P extends 'b' ? never : T[P]; } type o = { a?: string, b: string }; type p = FilterB<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, optional: true, name: 'a', type: { kind: ReflectionKind.string } }] }); }); test('object literal optional', () => { expectEqualType(typeOf<{ a?: string }>(), { kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'a', optional: true, type: { kind: ReflectionKind.string } }] }); }); test('object literal readonly', () => { expectEqualType(typeOf<{ readonly a: string }>(), { kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'a', readonly: true, type: { kind: ReflectionKind.string } }] }); }); test('type alias partial remove readonly', () => { type Partial2<T> = { -readonly [P in keyof T]?: T[P]; } type o = { readonly a: string }; type p = Partial2<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'a', optional: true, type: { kind: ReflectionKind.string } }] }); }); test('global partial', () => { type o = { a: string }; type p = Partial<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.propertySignature, name: 'a', optional: true, type: { kind: ReflectionKind.string } }] }); }); test('global record', () => { type p = Record<string, number>; //equivalent to type a = { [K in string]: number }; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.indexSignature, type: { kind: ReflectionKind.number }, index: { kind: ReflectionKind.string } }] } as Type as any); expect(typeOf<a>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [{ kind: ReflectionKind.indexSignature, type: { kind: ReflectionKind.number }, index: { kind: ReflectionKind.string } }] }); }); test('global InstanceType', () => { // type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : true; type a = InstanceType<any>; // expect(typeOf<a>()).toMatchObject({kind: ReflectionKind.any} as Type as any); }); test('type alias all string', () => { type AllString<T> = { [P in keyof T]: string; } type o = { a: string, b: number }; type p = AllString<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'a', type: { kind: ReflectionKind.string } }, { kind: ReflectionKind.propertySignature, name: 'b', type: { kind: ReflectionKind.string } } ] }); }); test('type alias conditional type', () => { type IsString<T> = { [P in keyof T]: T[P] extends string ? true : false; } type o = { a: string, b: number }; type p = IsString<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'a', type: { kind: ReflectionKind.literal, literal: true, } }, { kind: ReflectionKind.propertySignature, name: 'b', type: { kind: ReflectionKind.literal, literal: false, } }, ] }); }); test('type alias infer', () => { type InferTypeOfT<T> = { [P in keyof T]: T[P] extends { t: infer OT } ? OT : never } type o = { a: { t: string }, b: { t: number } }; type p = InferTypeOfT<o>; expect(typeOf<p>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'a', type: { kind: ReflectionKind.string } }, { kind: ReflectionKind.propertySignature, name: 'b', type: { kind: ReflectionKind.number } }, ] }); }); test('user interface', () => { interface User { username: string; created: Date; } const type = typeOf<User>(); expect(type).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'username', type: { kind: ReflectionKind.string } }, { kind: ReflectionKind.propertySignature, name: 'created', type: { kind: ReflectionKind.class, classType: Date, types: [] } }, ] }); }); test('generic static', () => { interface Request<T> { body: T; } interface Body { title: string; } const type = typeOf<Request<Body>>(); expect(type).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'body', type: { kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'title', type: { kind: ReflectionKind.string } } ] } }, ] }); expect(typeOf<Request<string>>()).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'body', type: { kind: ReflectionKind.string } }, ] }); }); //this does not work yet // test('function generic static', () => { // function infer<T extends string | number>(): Type { // return typeOf<T>(); // } // // expect(infer<'abc'>()).toMatchObject({ kind: ReflectionKind.string }); // expect(infer<123>()).toMatchObject({ kind: ReflectionKind.number }); // }); test('generic dynamic', () => { interface Request<T extends object> { body: T; } interface Body { title: string; } const type = typeOf<Request<never>>([typeOf<Body>()]); expect(type).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'body', type: { kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'title', type: { kind: ReflectionKind.string } } ] } }, ] }); expect(typeOf<Request<never>>([typeOf<string>()])).toMatchObject({ kind: ReflectionKind.objectLiteral, types: [ { kind: ReflectionKind.propertySignature, name: 'body', type: { kind: ReflectionKind.string } }, ] }); }); test('reflection class', () => { class User { created: Date = new Date; constructor(public username: string) { } say(text: string): void { console.log(`${this.username}: ${text}`); } } const reflection = ReflectionClass.from(User); expect(reflection.getMethodNames()).toEqual(['constructor', 'say']); const sayMethod = reflection.getMethod('say')!; expect(sayMethod.getParameterNames()).toEqual(['text']); expect(sayMethod.getParameterType('text')!.kind).toBe(ReflectionKind.string); expect(sayMethod.getReturnType().kind).toEqual(ReflectionKind.void); expect(reflection.getPropertyNames()).toEqual(['created', 'username']); expectEqualType(reflection.getProperty('username')!.type, { kind: ReflectionKind.string }); //string expect(reflection.getProperty('username')!.isPublic()).toBe(true); //true }); test('reflection function', () => { function say(text: string): void { console.log(`Text: ${text}`); } const reflection = ReflectionFunction.from(say); reflection.getParameters(); //[text: string] reflection.getReturnType(); //[void] expect(reflection.getParameterNames()).toEqual(['text']); expect(reflection.getParameter('text')!.getType().kind).toBe(ReflectionKind.string); expect(reflection.getParameterType('text')!.kind).toBe(ReflectionKind.string); expect(reflection.getReturnType().kind).toBe(ReflectionKind.void); }); test('destructing params', () => { interface Param { title: string; } function say(first: string, { title }: Param, last: number): void { } const reflection = ReflectionFunction.from(say); expect(reflection.getParameterNames()).toEqual(['first', 'param1', 'last']); }); test('interface extends basic', () => { interface Base { base: boolean; } interface User extends Base { id: number & PrimaryKey; } const reflection = ReflectionClass.from(typeOf<User>()); console.log('reflection', reflection.type); expect(reflection.getProperty('base').getKind()).toBe(ReflectionKind.boolean); expect(reflection.getProperty('id').getKind()).toBe(ReflectionKind.number); expect(reflection.getProperty('id').isPrimaryKey()).toBe(true); }); test('interface extends generic', () => { interface Base<T> { base: T; } interface User extends Base<boolean> { id: number & PrimaryKey; } const reflection = ReflectionClass.from(typeOf<User>()); console.log('reflection', reflection.type); expect(reflection.getProperty('base').getKind()).toBe(ReflectionKind.boolean); expect(reflection.getProperty('id').getKind()).toBe(ReflectionKind.number); expect(reflection.getProperty('id').isPrimaryKey()).toBe(true); }); test('interface entity', () => { interface User extends Entity<{ name: 'user', collection: 'users' }> { id: number & PrimaryKey; } const reflection = ReflectionClass.from(typeOf<User>()); const entityOptions = entityAnnotation.getFirst(reflection.type); expect(entityOptions).toEqual({ name: 'user', collection: 'users' }); expect(reflection.name).toBe('user'); expect(reflection.collectionName).toBe('users'); }); test('primaryKey', () => { type a = number & PrimaryKey; console.log((typeOf<a>() as any).decorators[0].types); class User { id: number & PrimaryKey = 0; } const reflection = ReflectionClass.from(User); const property = reflection.getProperty('id')!; expect(property.getType().kind).toBe(ReflectionKind.number); const annotations = primaryKeyAnnotation.getAnnotations(property.getType()); expect(annotations![0]).toEqual(true); expect(property.isPrimaryKey()).toEqual(true); }); test('Reference', () => { interface User { id: number & PrimaryKey; pages: Page[] & BackReference; } interface Page { owner: User & Reference; } const reflection = ReflectionClass.from(typeOf<Page>() as TypeClass); const property = reflection.getProperty('owner')!; const owner = property.getType(); assertType(owner, ReflectionKind.objectLiteral); expect(owner.typeName).toBe('User'); assertType(owner.types[0], ReflectionKind.propertySignature); expect(owner.types[0].name).toBe('id'); assertType(owner.types[0].type, ReflectionKind.number); const annotations = referenceAnnotation.getAnnotations(owner); expect(annotations![0]).toEqual({}); }); test('cache with annotations array', () => { type MyString = string; type MyPrimaryKeys = MyString[] & PrimaryKey; const string = typeOf<MyString>(); assertType(string, ReflectionKind.string); expect(primaryKeyAnnotation.isPrimaryKey(string)).toEqual(false); const primaryKeys = typeOf<MyPrimaryKeys>(); assertType(primaryKeys, ReflectionKind.array); assertType(primaryKeys.type, ReflectionKind.string); expect(primaryKeyAnnotation.isPrimaryKey(primaryKeys)).toEqual(true); expect(primaryKeyAnnotation.isPrimaryKey(primaryKeys.type)).toEqual(false); assertType(primaryKeys.type.parent!, ReflectionKind.array); expect(primaryKeys.type.parent!.type === primaryKeys.type).toBe(true); //intersection with decorators shallow copy the MyString[], which makes the subchild parent "invalid" // expect(primaryKeys.type.parent === primaryKeys).toBe(true); }); test('cache with annotations type alias', () => { type MyString = string; type MyPrimaryKey = MyString & PrimaryKey; const str = typeOf<MyString>(); assertType(str, ReflectionKind.string); expect(primaryKeyAnnotation.isPrimaryKey(str)).toEqual(false); const primaryKey = typeOf<MyPrimaryKey>(); assertType(primaryKey, ReflectionKind.string); expect(primaryKeyAnnotation.isPrimaryKey(primaryKey)).toEqual(true); const str2 = typeOf<MyString>(); assertType(str2, ReflectionKind.string); expect(primaryKeyAnnotation.isPrimaryKey(str2)).toEqual(false); interface User { id: MyPrimaryKey & AutoIncrement; id2: MyPrimaryKey; } const user = typeOf<User>(); assertType(user, ReflectionKind.objectLiteral); assertType(user.types[0], ReflectionKind.propertySignature); expect(primaryKeyAnnotation.getAnnotations(user.types[0].type)).toEqual([true]); expect(autoIncrementAnnotation.getAnnotations(user.types[0].type)).toEqual([true]); assertType(user.types[1], ReflectionKind.propertySignature); expect(primaryKeyAnnotation.getAnnotations(user.types[1].type)).toEqual([true]); expect(autoIncrementAnnotation.getAnnotations(user.types[1].type)).toEqual([]); }); test('cache with annotations class', () => { interface User extends Entity<{ name: 'user', collection: 'users' }> { username: string; } interface Page { owner: User & Reference; admin: User; } const page = typeOf<Page>(); assertType(page, ReflectionKind.objectLiteral); assertType(page.types[0], ReflectionKind.propertySignature); expect(page.types[0].name).toBe('owner'); assertType(page.types[0].type, ReflectionKind.objectLiteral); const user = typeOf<User>(); const user2 = typeOf<User>(); expect(user === user2).toBe(true); assertType(user, ReflectionKind.objectLiteral); expect(referenceAnnotation.getAnnotations(user)).toEqual([]); expect(entityAnnotation.getFirst(user)).toEqual({ name: 'user', collection: 'users' }); expect(referenceAnnotation.getAnnotations(page.types[0].type)).toEqual([{}]); expect(entityAnnotation.getFirst(page.types[0].type)).toEqual({ name: 'user', collection: 'users' }); assertType(page.types[1], ReflectionKind.propertySignature); assertType(page.types[1].type, ReflectionKind.objectLiteral); expect(referenceAnnotation.getAnnotations(page.types[1].type)).toEqual([]); expect(entityAnnotation.getFirst(page.types[1].type)).toEqual({ name: 'user', collection: 'users' }); }); test('cache different types', () => { interface Post { slug: string & SQLite<{ type: 'text' }>; size: number & SQLite<{ type: 'integer(4)' }>; } const post = typeOf<Post>(); assertType(post, ReflectionKind.objectLiteral); assertType(post.types[0], ReflectionKind.propertySignature); const slugDatabase = databaseAnnotation.getDatabase(post.types[0].type, 'sqlite'); expect(slugDatabase!.type).toBe('text'); assertType(post.types[1], ReflectionKind.propertySignature); const sizeDatabase = databaseAnnotation.getDatabase(post.types[1].type, 'sqlite'); expect(sizeDatabase!.type).toBe('integer(4)'); }); test('cache parent unset', () => { type MyString = string; type Union = MyString | number; const union = typeOf<Union>(); const string = typeOf<MyString>(); expect(string.parent).toBeUndefined(); assertType(string, ReflectionKind.string); assertType(union, ReflectionKind.union); assertType(union.types[0], ReflectionKind.string); expect(union.types[0].parent === union).toBe(true); }); test('cache parent unset circular', () => { interface User { groups: Group[] & BackReference<{ via: UserGroup }>; } interface Group { } interface UserGroup { user: User; } const user = typeOf<User>(); const group = typeOf<Group>(); const userGroup = typeOf<UserGroup>(); expect(userGroup.parent).toBeUndefined(); expect(group.parent).toBeUndefined(); expect(user.parent).toBeUndefined(); assertType(user, ReflectionKind.objectLiteral); assertType(user.types[0], ReflectionKind.propertySignature); assertType(user.types[0].type, ReflectionKind.array); assertType(user.types[0].type.type, ReflectionKind.objectLiteral); expect(user.types[0].type.parent === user.types[0]).toBe(true); //intersection with decorators shallow copy the Group[], which makes the subchild parent "invalid" // expect(user.types[0].type.type.parent === user.types[0].type).toBe(true); }); test('circular interface', () => { interface User extends Entity<{ name: 'user', collection: 'users' }> { pages: Page[] & BackReference; page: Page & BackReference; } interface Page { owner: User & Reference; admin: User; } const user = typeOf<User>(); const user2 = typeOf<User>(); expect(user === user2).toBe(true); assertType(user, ReflectionKind.objectLiteral); expect(referenceAnnotation.getAnnotations(user)).toEqual([]); expect(entityAnnotation.getFirst(user)).toEqual({ name: 'user', collection: 'users' }); const page = typeOf<Page>(); assertType(page, ReflectionKind.objectLiteral); assertType(page.types[0], ReflectionKind.propertySignature); expect(page.types[0].name).toBe('owner'); assertType(page.types[0].type, ReflectionKind.objectLiteral); expect(referenceAnnotation.getAnnotations(page.types[0].type)).toEqual([{}]); expect(entityAnnotation.getFirst(page.types[0].type)).toEqual({ name: 'user', collection: 'users' }); assertType(page.types[1], ReflectionKind.propertySignature); assertType(page.types[1].type, ReflectionKind.objectLiteral); expect(referenceAnnotation.getAnnotations(page.types[1].type)).toEqual([]); expect(entityAnnotation.getFirst(page.types[1].type)).toEqual({ name: 'user', collection: 'users' }); }); test('built in numeric type', () => { class User { id: integer = 0; } const reflection = ReflectionClass.from(User); const property = reflection.getProperty('id')!; expect(property.getType().kind).toBe(ReflectionKind.number); expect((property.getType() as TypeNumber).brand).toBe(TypeNumberBrand.integer); }); test('class validator', () => { class Email { constructor(public email: string) { } @t.validator validator(): ValidatorError | void { if (this.email === '') return new ValidatorError('email', 'Invalid email'); } } const reflection = ReflectionClass.from(Email); expect(reflection.validationMethod).toBe('validator'); expect(validate<Email>(new Email(''))).toEqual([{ path: '', code: 'email', message: 'Invalid email' }]); expect(validate<Email>(new Email('asd'))).toEqual([]); }); test('value object single field', () => { class Price { constructor(public amount: integer) { } isFree() { return this.amount === 0; } } class Product { price2?: Price; constructor(public title: string, public price: Embedded<Price>) { } } const reflection = ReflectionClass.from(Product); const title = reflection.getProperty('title')!; expect(title.isEmbedded()).toBe(false); const price = reflection.getProperty('price')!; expect(price.isEmbedded()).toBe(true); expect(price.getEmbedded()).toEqual({}); assertType(price.type, ReflectionKind.class); expect(price.type.classType).toBe(Price); const price2 = reflection.getProperty('price2')!; expect(price2.isEmbedded()).toBe(false); assertType(price2.type, ReflectionKind.class); expect(price2.type.classType).toBe(Price); }); test('type decorator with union', () => { type HttpQuery<T> = T & { __meta?: ['httpQuery'] }; type a = HttpQuery<number | string>; const type = typeOf<a>(); assertType(type, ReflectionKind.union); expect(metaAnnotation.getAnnotations(type)).toEqual([{ name: 'httpQuery', options: [] }]); }); test('simple brands', () => { type Username = string & { __brand: 'username' }; class User { username: Username = '' as Username; } const reflection = ReflectionClass.from(User); const property = reflection.getProperty('username')!; expect(property.getType().kind).toBe(ReflectionKind.string); expect(defaultAnnotation.getAnnotations(property.getType())).toEqual([typeOf<{ __brand: 'username' }>()]); }); // test('ts-brand', () => { // type Brand<Base, // Branding, // ReservedName extends string = '__type__'> = Base & { [K in ReservedName]: Branding } & { __witness__: Base }; // // const type = typeOf<Brand<string, 'uuid'>>(); // const expected: TypeString = { // kind: ReflectionKind.string, // brands: [ // { // kind: ReflectionKind.objectLiteral, types: [ // { kind: ReflectionKind.propertySignature, name: '__type__', type: { kind: ReflectionKind.literal, literal: 'uuid' } }, // ] // }, // { // kind: ReflectionKind.objectLiteral, types: [] // } // ] // }; // (expected.brands![1] as TypeObjectLiteral).types.push({ kind: ReflectionKind.propertySignature, name: '__witness__', type: expected }); // expect(type).toEqual(expected); // }); // test('decorate class', () => { // @t.group('a') // class User { // username: string = ''; // } // // const reflection = ReflectionClass.from(User); // expect(reflection.groups).toEqual(['a']); // }); test('group decorator', () => { class User { username: string & Group<'a'> = ''; } const reflection = ReflectionClass.from(User); const username = reflection.getProperty('username'); expect(username!.getGroups()).toEqual(['a']); }); test('exclude decorator', () => { class User { username: string & Excluded<'json'> = ''; } const reflection = ReflectionClass.from(User); const username = reflection.getProperty('username'); expect(username!.getExcluded()).toEqual(['json']); }); test('data decorator', () => { class User { username: string & Data<'key', 3> = ''; config: number & Data<'key', true> = 3; } const reflection = ReflectionClass.from(User); const username = reflection.getProperty('username'); expect(username!.getData()).toEqual({ key: 3 }); expect(reflection.getProperty('config')!.getData()).toEqual({ key: true }); }); test('reference decorator', () => { class Group { } class User { group?: Group & Reference; group2?: Group & Reference<{ onDelete: 'SET NULL' }>; } const reflection = ReflectionClass.from(User); expect(reflection.getProperty('group')!.getReference()).toEqual({}); expect(reflection.getProperty('group2')!.getReference()).toEqual({ onDelete: 'SET NULL' }); }); test('index decorator', () => { class User { username: string & Index<{ name: 'username', unique: true }> = ''; email?: string & Unique; config: number & Index = 2; } const reflection = ReflectionClass.from(User); const username = reflection.getProperty('username'); expect(username!.getIndex()).toEqual({ name: 'username', unique: true }); expect(reflection.getProperty('email')!.getIndex()).toEqual({ unique: true }); expect(reflection.getProperty('config')!.getIndex()).toEqual({}); }); test('database decorator', () => { class User { username: string & MySQL<{ type: 'varchar(255)' }> = ''; email?: string & SQLite<{ type: 'varchar(128)' }>; config: number & Postgres<{ type: 'smallint' }> = 5; nope?: number; } const reflection = ReflectionClass.from(User); const username = reflection.getProperty('username'); expect(username!.getDatabase('mysql')).toEqual({ type: 'varchar(255)' }); expect(reflection.getProperty('email')!.getDatabase('sqlite')).toEqual({ type: 'varchar(128)' }); expect(reflection.getProperty('config')!.getDatabase('postgres')).toEqual({ type: 'smallint' }); expect(reflection.getProperty('nope')!.getDatabase('postgres')).toEqual(undefined); }); test('enum const', () => { const enum MyEnum { a, b, c } const type = typeOf<MyEnum>(); expectEqualType(type, { kind: ReflectionKind.enum, enum: { a: 0, b: 1, c: 2 }, values: [0, 1, 2] }); }); test('enum default', () => { enum MyEnum { a, b, c } const type = typeOf<MyEnum>(); expectEqualType(type, { kind: ReflectionKind.enum, enum: { a: 0, b: 1, c: 2 }, values: [0, 1, 2] }); }); test('enum initializer 1', () => { enum MyEnum { a = 3, b, c } const type = typeOf<MyEnum>(); expectEqualType(type, { kind: ReflectionKind.enum, enum: { a: 3, b: 4, c: 5 }, values: [3, 4, 5] }); }); test('enum initializer 2', () => { enum MyEnum { a = 0, b = 1 << 0, c = 1 << 1, d = 1 << 2, } const type = typeOf<MyEnum>(); expectEqualType(type, { kind: ReflectionKind.enum, enum: { a: 0, b: 1, c: 2, d: 4 }, values: [0, 1, 2, 4] }); }); test('decorate class inheritance', () => { class Timestamp { created: Date & Group<'base'> = new Date; } class User extends Timestamp { username: string & Group<'a'> & Group<'b'> = ''; } const reflection = ReflectionClass.from(User); const username = reflection.getProperty('username'); expect(username!.getGroups()).toEqual(['a', 'b']); const created = reflection.getProperty('created'); expect(created!.getGroups()).toEqual(['base']); }); test('decorate class inheritance override decorator data', () => { class Timestamp { created: Date & Group<'base'> = new Date; } class User extends Timestamp { created: Date & Group<'a'> = new Date; } const reflection = ReflectionClass.from(User); const created = reflection.getProperty('created'); expect(created!.getGroups()).toEqual(['a']); }); // test('decorate interface', () => { // interface User { // /** // * @description test // */ // username: string; // } // // const reflection = decorate<User>({ // username: t.group('a') // }); // // const username = reflection.getProperty('username')!; // expect(username.getKind()).toBe(ReflectionKind.string); // expect(username.groups).toEqual(['a']); // expect(username.getDescription()).toEqual('test'); // }); test('set constructor parameter manually', () => { class Response { constructor(public success: boolean) { } } class StreamApiResponseClass<T> { constructor(public response: T) { } } // { // const reflection = reflect(StreamApiResponseClass); // assertType(reflection, ReflectionKind.class); // // // type T = StreamApiResponseClass; // // type a = T['response']; // //if there is no type passed to T it resolved to any // expect(reflection.typeArguments).toEqual([{ kind: ReflectionKind.any }]); // } // // { // class StreamApiResponseClassWithDefault<T = string> { // constructor(public response: T) { // } // } // // const reflection = reflect(StreamApiResponseClassWithDefault); // assertType(reflection, ReflectionKind.class); // // // type T = StreamApiResponseClassWithDefault; // // type a = T['response']; // expect(reflection.typeArguments).toMatchObject([{ kind: ReflectionKind.string }]); // } // // expectEqualType(typeOf<Response>(), { // kind: ReflectionKind.class, // classType: Response, // types: [ // { // kind: ReflectionKind.method, name: 'constructor', visibility: ReflectionVisibility.public, parameters: [ // { kind: ReflectionKind.parameter, name: 'success', visibility: ReflectionVisibility.public, type: { kind: ReflectionKind.boolean } } // ], return: { kind: ReflectionKind.any } // }, // { // kind: ReflectionKind.property, visibility: ReflectionVisibility.public, name: 'success', type: { kind: ReflectionKind.boolean } // } // ] // } as Type); function StreamApiResponse<T>(responseBodyClass: ClassType<T>) { class A extends StreamApiResponseClass<T> { constructor(@t.type(responseBodyClass) public response: T) { super(response); } } return A; } { const classType = StreamApiResponse(Response); const reflection = ReflectionClass.from(classType); expect(reflection.getMethods().length).toBe(1); expect(reflection.getProperties().length).toBe(1); expect(reflection.getMethod('constructor')!.getParameters().length).toBe(1); //if this fails, ClassType can probably not be resolved expect(reflection.getMethod('constructor')!.getParameter('response')!.getType().kind).toBe(ReflectionKind.class); expect(reflection.getMethods()[0].getName()).toBe('constructor'); const responseType = reflection.getProperty('response')!.getType(); expect(responseType.kind).toBe(ReflectionKind.class); if (responseType.kind === ReflectionKind.class) { expect(responseType.classType).toBe(Response); } } function StreamApiResponse2<T>(responseBodyClass: ClassType<T>) { if (!responseBodyClass) throw new Error(); class A extends StreamApiResponseClass<T> { constructor(public response: T) { super(response); } } return A; } { const classType = StreamApiResponse2(Response); const type = resolveRuntimeType(classType) as TypeClass; expect((type.types[0] as TypeMethod).parameters[0].type.kind).toBe(ReflectionKind.class); const reflection = ReflectionClass.from(classType); expect(reflection.getMethods().length).toBe(1); expect(reflection.getProperties().length).toBe(1); expect(reflection.getMethod('constructor').getParameters().length).toBe(1); expect(reflection.getMethod('constructor').getParameter('response').getType().kind).toBe(ReflectionKind.class); expect(reflection.getMethods()[0].getName()).toBe('constructor'); //make sure parent's T is correctly set expect(reflection.getSuperReflectionClass()!.type.typeArguments![0].kind).toBe(ReflectionKind.class); const responseType = reflection.getProperty('response')!.getType(); expect(responseType.kind).toBe(ReflectionKind.class); if (responseType.kind === ReflectionKind.class) { expect(responseType.classType).toBe(Response); } } { const type = typeOf<StreamApiResponseClass<Response>>() as TypeClass; const reflection = ReflectionClass.from(type); if (type.kind === ReflectionKind.class) { const t1 = type.arguments![0] as TypeClass; expect(t1.kind).toBe(ReflectionKind.class); expect(t1.classType).toBe(Response); } expect(reflection.getMethods().length).toBe(1); expect(reflection.getProperties().length).toBe(1); expect(reflection.getMethod('constructor').getParameters().length).toBe(1); expect(reflection.getMethod('constructor').getParameter('response').getType().kind).toBe(ReflectionKind.class); const responseType = reflection.getProperty('response')!.getType(); expect(responseType.kind).toBe(ReflectionKind.class); if (responseType.kind === ReflectionKind.class) { expect(responseType.classType).toBe(Response); } expect(reflection.getMethods()[0].getName()).toBe('constructor'); } }); test('circular type 1', () => { type Page = { title: string; children: Page[] } const type = typeOf<Page>(); expect(type.kind).toBe(ReflectionKind.objectLiteral); if (type.kind === ReflectionKind.objectLiteral) { const c = type.types[1]; expect(c.kind).toBe(ReflectionKind.propertySignature); if (c.kind === ReflectionKind.propertySignature) { const cType = c.type; expect(cType.kind).toBe(ReflectionKind.array); if (cType.kind === ReflectionKind.array) { expect(cType.type.kind).toBe(ReflectionKind.objectLiteral); expect(cType.type === type).toBe(true); } } } }); test('circular type 2', () => { type Document = { title: string; root: Node; } type Node = { children: Node[] } const type = typeOf<Document>(); expect(type.kind).toBe(ReflectionKind.objectLiteral); if (type.kind === ReflectionKind.objectLiteral) { const rootProperty = type.types[1]; expect(rootProperty.kind).toBe(ReflectionKind.propertySignature); if (rootProperty.kind === ReflectionKind.propertySignature) { const rootType = rootProperty.type; expect(rootType.kind).toBe(ReflectionKind.objectLiteral); if (rootType.kind === ReflectionKind.objectLiteral) { const childrenProperty = rootType.types[0]; expect(childrenProperty.kind).toBe(ReflectionKind.propertySignature); if (childrenProperty.kind === ReflectionKind.propertySignature) { expect(childrenProperty.type.kind).toBe(ReflectionKind.array); if (childrenProperty.type.kind === ReflectionKind.array) { expect(childrenProperty.type.type).toBe(rootType); } } } } } }); test('circular interface 2', () => { interface Document { title: string; root: Node; } interface Node { children: Node[]; } const type = typeOf<Document>(); expect(type.kind).toBe(ReflectionKind.objectLiteral); if (type.kind === ReflectionKind.objectLiteral) { const rootProperty = type.types[1]; expect(rootProperty.kind).toBe(ReflectionKind.propertySignature); if (rootProperty.kind === ReflectionKind.propertySignature) { const rootType = rootProperty.type; expect(rootType.kind).toBe(ReflectionKind.objectLiteral); if (rootType.kind === ReflectionKind.objectLiteral) { const childrenProperty = rootType.types[0]; expect(childrenProperty.kind).toBe(ReflectionKind.propertySignature); if (childrenProperty.kind === ReflectionKind.propertySignature) { expect(childrenProperty.type.kind).toBe(ReflectionKind.array); if (childrenProperty.type.kind === ReflectionKind.array) { expect(childrenProperty.type.type).toBe(rootType); } } } } } }); test('circular class 2', () => { class Document { title!: string; root!: Node; } class Node { children!: Node[]; } const type = typeOf<Document>(); assertType(type, ReflectionKind.class); const rootProperty = type.types[1]; assertType(rootProperty, ReflectionKind.property); assertType(rootProperty.type, ReflectionKind.class); assertType(rootProperty.type.types[0], ReflectionKind.property); assertType(rootProperty.type.types[0].type, ReflectionKind.array); assertType(rootProperty.type.types[0].type.type, ReflectionKind.class); assertType(rootProperty.type.types[0].type.type.types[0], ReflectionKind.property); expect(rootProperty.type.types[0].type.type.types[0].name).toBe('children'); }); test('circular class 3', () => { class Document { title!: string; root!: Node; } class Node { document!: Document; children!: Node[]; } const type = typeOf<Document>(); assertType(type, ReflectionKind.class); const rootProperty = type.types[1]; assertType(rootProperty, ReflectionKind.property); const rootType = rootProperty.type; assertType(rootType, ReflectionKind.class); const documentProperty = rootType.types[0]; assertType(documentProperty, ReflectionKind.property); assertType(documentProperty.type, ReflectionKind.class); const childrenProperty = rootType.types[1]; assertType(childrenProperty, ReflectionKind.property); assertType(childrenProperty.type, ReflectionKind.array); assertType(childrenProperty.type.type, ReflectionKind.class); }); test('typeOf returns same instance, and new one for generics', () => { class Clazz { } class GenericClazz<T> { item!: T; } { const clazz1 = typeOf<Clazz>(); const clazz2 = typeOf<Clazz>(); //this has to be equal otherwise JitContainer is always empty, and we would basically have no place to store cache data expect(clazz1 === clazz2).toBe(true); } //but types used in other types get their own instance { const clazz1 = typeOf<Clazz>(); const clazz2 = typeOf<Clazz>(); //this has to be equal otherwise JitContainer is always empty, and we would basically have no place to store cache data expect(clazz1 === clazz2).toBe(true); } { const clazz1 = typeOf<GenericClazz<string>>(); const clazz2 = typeOf<GenericClazz<string>>(); const clazz3 = typeOf<GenericClazz<number>>(); //generics produce always a new type, no matter what. otherwise, it would be a memory leak. expect(clazz1 === clazz2).toBe(false); expect(clazz2 === clazz3).toBe(false); //to get a cached result, a type alias can be used type GenericClassString = GenericClazz<string>; const clazz4 = typeOf<GenericClassString>(); const clazz5 = typeOf<GenericClassString>(); expect(clazz4 === clazz5).toBe(true); } { class Composition { clazz1!: Clazz; clazz2!: Clazz; } const clazz1 = typeOf<Clazz>(); const t = typeOf<Composition>(); assertType(t, ReflectionKind.class); assertType(t.types[0], ReflectionKind.property); assertType(t.types[1], ReflectionKind.property); assertType(t.types[0].type, ReflectionKind.class); assertType(t.types[1].type, ReflectionKind.class); expect(t.types[0].type.classType === Clazz).toBe(true); //properties clazz1 and clazz2 get each their own type instance expect(t.types[0].type === t.types[1].type).toBe(false); //properties get their own instance, so it's not equal to clazz1 (as annotations would otherwise be redirected to the actual class) expect(t.types[0].type === clazz1).toBe(false); } }); test('reference types decorators correct', () => { @entity.name('user') class User { id!: number & PrimaryKey & AutoIncrement; } @entity.name('post') class Post { id!: number & PrimaryKey & AutoIncrement; user?: User & Reference; } const user = ReflectionClass.from(User); expect(user.getProperty('id').isPrimaryKey()).toBe(true); expect(user.getProperty('id').isAutoIncrement()).toBe(true); expect(user.getPrimary() === user.getProperty('id')).toBe(true); expect(user.getAutoIncrement() === user.getProperty('id')).toBe(true); }); test('singleTableInheritance', () => { @entity.collection('persons') abstract class Person { id: number & PrimaryKey & AutoIncrement = 0; firstName?: string; lastName?: string; abstract type: string; } @entity.singleTableInheritance() class Employee extends Person { email?: string; type: 'employee' = 'employee'; } @entity.singleTableInheritance() class Freelancer extends Person { @t budget: number = 10_000; type: 'freelancer' = 'freelancer'; } const person = ReflectionClass.from(Person); const employee = ReflectionClass.from(Employee); const freelancer = ReflectionClass.from(Freelancer); expect(person.singleTableInheritance).toBe(false); expect(person.collectionName).toBe('persons'); expect(employee.singleTableInheritance).toBe(true); expect(employee.collectionName).toBe('persons'); //todo: this should be inherited? expect(freelancer.singleTableInheritance).toBe(true); const discriminant = person.getSingleTableInheritanceDiscriminantName(); expect(discriminant).toBe('type'); }); test('Array<T>', () => { expect(typeOf<string[]>()).toMatchObject({ kind: ReflectionKind.array, type: { kind: ReflectionKind.string } }); expect(typeOf<Array<string>>()).toMatchObject({ kind: ReflectionKind.array, type: { kind: ReflectionKind.string } }); }); test('default function expression', () => { class post { uuid: string = uuid(); id: integer & AutoIncrement & PrimaryKey = 0; created: Date = new Date; type: string = 'asd'; } const reflection = ReflectionClass.from(post); expect(reflection.getProperty('uuid').hasDefaultFunctionExpression()).toBe(true); expect(reflection.getProperty('id').hasDefaultFunctionExpression()).toBe(false); expect(reflection.getProperty('created').hasDefaultFunctionExpression()).toBe(false); expect(reflection.getProperty('type').hasDefaultFunctionExpression()).toBe(false); }); test('type decorator first position', () => { class author { } class post { id: PrimaryKey & number = 0; author?: Reference & MapName<'_author'> & author; } type a = Omit<post, 'author'>; const reflection = ReflectionClass.from(post); expect(reflection.getProperty('id').type.kind).toBe(ReflectionKind.number); expect(reflection.getProperty('id').isPrimaryKey()).toBe(true); expect(reflection.getProperty('author').type.kind).toBe(ReflectionKind.class); expect(reflection.getProperty('author').isPrimaryKey()).toBe(false); expect(reflection.getProperty('author').isReference()).toBe(true); }); test('annotateClass static', () => { class ExternalClass { } interface AnnotatedClass { id: number; } annotateClass<AnnotatedClass>(ExternalClass); expect(stringifyResolvedType(reflect(ExternalClass))).toBe('ExternalClass {id: number}'); }); test('annotateClass generic', () => { class ExternalClass { } class AnnotatedClass<T> { id!: T; } annotateClass(ExternalClass, AnnotatedClass); expect(stringifyResolvedType(reflect(ExternalClass))).toBe('ExternalClass {id: T}'); expect(stringifyResolvedType(reflect(ExternalClass, typeOf<number>()))).toBe('ExternalClass {id: number}'); }); test('test', () => { interface Article { id: number; title?: string; } validate<Article>({ id: 1 }).length; //0, means it validated successfully validate<Article>({}).length; //1, means there are validation errors console.log(validate<Article>({})); });
the_stack
import {HttpErrorResponse} from '@angular/common/http'; import {ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing'; import {FormsModule} from '@angular/forms'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatIconModule} from '@angular/material/icon'; import {MatInputModule} from '@angular/material/input'; import {MatSnackBar} from '@angular/material/snack-bar'; import {Sort} from '@angular/material/sort'; import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing'; import {BehaviorSubject, throwError} from 'rxjs'; import {CollectionParameters, Interval, Layer} from '../models'; import {LocalMetricsService, MetricsService} from '../services/metrics_service'; import {LocalRenderDataService, RenderDataService} from '../services/render_data_service'; import {SystemTopology, Viewport} from '../util'; import {Sidebar} from './sidebar'; import {SidebarModule} from './sidebar_module'; import {mockThreads} from './thread_table/table_helpers_test'; try { TestBed.initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting()); } catch { // Ignore exceptions when calling it multiple times. } // Delay time which will guarantee flush of viewport update const VIEWPORT_UPDATE_DEBOUNCE_MS = 1000; function setupSidebar(component: Sidebar) { component.parameters = new BehaviorSubject<CollectionParameters|undefined>( new CollectionParameters('collection_params', [], 0, 100)); component.expandedThread = new BehaviorSubject<string|undefined>(undefined); component.systemTopology = new SystemTopology([]); component.preview = new BehaviorSubject<Interval|undefined>(undefined); component.layers = new BehaviorSubject<Array<BehaviorSubject<Layer>>>([]); component.viewport = new BehaviorSubject<Viewport>(new Viewport()); component.viewport.value.updateSize(50, 50); component.tab = new BehaviorSubject<number>(0); component.threadSort = new BehaviorSubject<Sort>({active: '', direction: ''}); component.filter = new BehaviorSubject<string>(''); component.showMigrations = new BehaviorSubject<boolean>(true); component.showSleeping = new BehaviorSubject<boolean>(true); component.maxIntervalCount = new BehaviorSubject<number>(0); component.cpuFilter = new BehaviorSubject<string>(''); } function createSidebarWithMockData(): ComponentFixture<Sidebar> { const fixture = TestBed.createComponent(Sidebar); const component = fixture.componentInstance; setupSidebar(component); fixture.detectChanges(); return fixture; } function mockMetricServiceHttpError(functionToMock: keyof MetricsService): jasmine.Spy { // Set up failing request const metricsService = TestBed.get('MetricsService') as MetricsService; return spyOn(metricsService, functionToMock) .and.returnValue( throwError(new HttpErrorResponse({error: 'lorem ipsum'}))); } function mockRenderDataServiceHttpError( functionToMock: keyof RenderDataService): jasmine.Spy { // Set up failing request // Not deprecated until Angular 9.0.0, which isn't GA yet. // tslint:disable:deprecation const renderDataService = TestBed.get('RenderDataService') as RenderDataService; // tslint:enable:deprecation return spyOn(renderDataService, functionToMock) .and.returnValue( throwError(new HttpErrorResponse({error: 'lorem ipsum'}))); } describe('Sidebar', () => { beforeEach(async () => { document.body.style.width = '500px'; document.body.style.height = '500px'; await TestBed .configureTestingModule({ imports: [ FormsModule, MatFormFieldModule, MatInputModule, MatIconModule, SidebarModule ], providers: [ {provide: 'MetricsService', useClass: LocalMetricsService}, {provide: 'RenderDataService', useClass: LocalRenderDataService}, ], }) .compileComponents(); }); it('should create', () => { const fixture = createSidebarWithMockData(); expect(fixture.componentInstance).toBeTruthy(); }); it('should update threads on viewport change', fakeAsync(() => { const fixture = createSidebarWithMockData(); const component = fixture.componentInstance; const metricsService = TestBed.get('MetricsService') as MetricsService; const expectedThreads = mockThreads().slice(0, 10); spyOn(metricsService, 'getThreadSummaries') .and.returnValue(new BehaviorSubject(expectedThreads)); const threadSpy = jasmine.createSpy('threadSpy'); component.threads.subscribe(threadSpy); expect(threadSpy).toHaveBeenCalledTimes(1); // Trigger viewport update. Calls should be debounced const updatedViewport = new Viewport(component.viewport.value); updatedViewport.updateSize(50, 50); component.viewport.next(updatedViewport); component.viewport.next(updatedViewport); component.viewport.next(updatedViewport); component.viewport.next(updatedViewport); expect(threadSpy).toHaveBeenCalledTimes(1); tick(VIEWPORT_UPDATE_DEBOUNCE_MS); // Verify thread data was properly updated expect(threadSpy).toHaveBeenCalledTimes(2); expect(threadSpy).toHaveBeenCalledWith( jasmine.arrayContaining(expectedThreads)); })); it('should update expanded thread', async () => { const fixture = createSidebarWithMockData(); const component = fixture.componentInstance; await fixture.whenStable(); const expandedFtraceIntervalsSpy = jasmine.createSpy('expandedFtraceIntervalsSpy'); component.expandedFtraceIntervals.subscribe(expandedFtraceIntervalsSpy); const expandedThreadIntervalsSpy = jasmine.createSpy('expandedThreadIntervalsSpy'); component.expandedThreadIntervals.subscribe(expandedThreadIntervalsSpy); const expandedThreadAntagonistsSpy = jasmine.createSpy('expandedThreadAntagonistsSpy'); component.expandedThreadAntagonists.subscribe(expandedThreadAntagonistsSpy); // Simulate thread expansion const threadToExpand = component.threads.value[3]; component.expandedThread.next(threadToExpand.label); expect(expandedFtraceIntervalsSpy).toHaveBeenCalled(); expect(expandedFtraceIntervalsSpy) .toHaveBeenCalledWith(jasmine.arrayContaining(threadToExpand.events)); expect(expandedThreadIntervalsSpy).toHaveBeenCalled(); expect(expandedThreadIntervalsSpy) .toHaveBeenCalledWith( jasmine.arrayContaining(threadToExpand.intervals)); expect(expandedThreadAntagonistsSpy).toHaveBeenCalled(); expect(expandedThreadAntagonistsSpy) .toHaveBeenCalledWith( jasmine.arrayContaining(threadToExpand.antagonists)); }); it('should surface error message upon failure of thread summary request', fakeAsync(() => { const fixture = createSidebarWithMockData(); const component = fixture.componentInstance; mockMetricServiceHttpError('getThreadSummaries'); const snackBar = TestBed.get(MatSnackBar) as MatSnackBar; const snackBarSpy = spyOn(snackBar, 'openFromComponent'); // Failed request should occur during viewport update const updatedViewport = new Viewport(component.viewport.value); updatedViewport.updateSize(0, 50); component.viewport.next(updatedViewport); tick(VIEWPORT_UPDATE_DEBOUNCE_MS); expect(snackBarSpy).toHaveBeenCalledTimes(1); const componentParameters = component.parameters.value; expect(componentParameters).toBeTruthy(); const actualError = snackBarSpy.calls.mostRecent().args[1].data.summary; expect(actualError) .toContain(`Failed to get thread summaries for ${ componentParameters!.name}`); })); it('should surface error message upon failure of thread event request', async () => { const fixture = createSidebarWithMockData(); const component = fixture.componentInstance; await fixture.whenStable(); mockMetricServiceHttpError('getPerThreadEvents'); const snackBar = TestBed.get(MatSnackBar) as MatSnackBar; const snackBarSpy = spyOn(snackBar, 'openFromComponent'); // Failed request should occur during thread expansion const threadToExpand = component.threads.value[0]; component.expandedThread.next(threadToExpand.label); expect(snackBarSpy).toHaveBeenCalledTimes(1); const actualError = snackBarSpy.calls.mostRecent().args[1].data.summary; expect(actualError) .toContain( `Failed to get thread events for PID: ${threadToExpand.pid}`); }); it('should surface error message upon failure of thread intervals request', async () => { const fixture = createSidebarWithMockData(); const component = fixture.componentInstance; await fixture.whenStable(); mockRenderDataServiceHttpError('getPidIntervals'); // Not deprecated until Angular 9.0.0, which isn't GA yet. // tslint:disable-next-line:deprecation const snackBar = TestBed.get(MatSnackBar) as MatSnackBar; const snackBarSpy = spyOn(snackBar, 'openFromComponent'); // Failed request should occur during thread expansion const threadToExpand = component.threads.value[2]; component.expandedThread.next(threadToExpand.label); expect(snackBarSpy).toHaveBeenCalledTimes(1); const actualError = snackBarSpy.calls.mostRecent().args[1].data.summary; expect(actualError) .toContain( `Failed to get thread intervals for PID: ${threadToExpand.pid}`); }); it('should surface error message upon failure of thread antagonists request', async () => { const fixture = createSidebarWithMockData(); const component = fixture.componentInstance; await fixture.whenStable(); mockMetricServiceHttpError('getThreadAntagonists'); const snackBar = TestBed.get(MatSnackBar) as MatSnackBar; const snackBarSpy = spyOn(snackBar, 'openFromComponent'); // Failed request should occur during thread expansion const threadToExpand = component.threads.value[2]; component.expandedThread.next(threadToExpand.label); expect(snackBarSpy).toHaveBeenCalledTimes(1); const actualError = snackBarSpy.calls.mostRecent().args[1].data.summary; expect(actualError) .toContain(`Failed to get thread antagonists for PID: ${ threadToExpand.pid}`); }); });
the_stack
import * as vscode from "vscode"; import { Position, TextDocument, Uri } from "vscode"; import { Bookmark, BookmarkQuickPickItem } from "../vscode-numbered-bookmarks-core/src/bookmark"; import { NO_BOOKMARK_DEFINED } from "../vscode-numbered-bookmarks-core/src/constants"; import { Controller } from "../vscode-numbered-bookmarks-core/src/controller"; import { clearBookmarks, hasBookmarks, indexOfBookmark, isBookmarkDefined, listBookmarks } from "../vscode-numbered-bookmarks-core/src/operations"; import { revealPosition, previewPositionInDocument, revealPositionInDocument } from "../vscode-numbered-bookmarks-core/src/utils/reveal"; import { Sticky } from "../vscode-numbered-bookmarks-core/src/stickyLegacy"; import { loadBookmarks, saveBookmarks } from "../vscode-numbered-bookmarks-core/src/workspaceState"; import { Container } from "../vscode-numbered-bookmarks-core/src/container"; import { registerWhatsNew } from "./whats-new/commands"; import { codicons } from "vscode-ext-codicons"; import { getRelativePath, parsePosition } from "../vscode-numbered-bookmarks-core/src/utils/fs"; import { File } from "../vscode-numbered-bookmarks-core/src/file"; import { updateBookmarkDecorationType, updateBookmarkSvg, updateDecorationsInActiveEditor, updateSvgVersion } from "./decoration"; import { pickController } from "../vscode-numbered-bookmarks-core/src/quickpick/controllerPicker"; import { updateStickyBookmarks } from "../vscode-numbered-bookmarks-core/src/sticky"; export async function activate(context: vscode.ExtensionContext) { Container.context = context; registerWhatsNew(); let activeController: Controller; let controllers: Controller[] = []; let activeEditorCountLine: number; let timeout = null; let activeEditor = vscode.window.activeTextEditor; let activeFile: File; const bookmarkDecorationType: vscode.TextEditorDecorationType[] = []; // load pre-saved bookmarks await loadWorkspaceState(); updateBookmarkSvg(triggerUpdateDecorations); updateBookmarkDecorationType(bookmarkDecorationType); // Connect it to the Editors Events if (activeEditor) { getActiveController(activeEditor.document); activeController.addFile(activeEditor.document.uri); activeEditorCountLine = activeEditor.document.lineCount; activeFile = activeController.fromUri(activeEditor.document.uri); triggerUpdateDecorations(); } // new docs // vscode.workspace.onDidOpenTextDocument(doc => { // // activeEditorCountLine = doc.lineCount; // getActiveController(doc); // activeController.addFile(doc.uri); // }); vscode.window.onDidChangeActiveTextEditor(editor => { activeEditor = editor; if (editor) { activeEditorCountLine = editor.document.lineCount; getActiveController(editor.document); activeController.addFile(editor.document.uri); activeFile = activeController.fromUri(editor.document.uri); triggerUpdateDecorations(); } }, null, context.subscriptions); vscode.workspace.onDidChangeTextDocument(event => { if (activeEditor && event.document === activeEditor.document) { let updatedBookmark = true; // call sticky function when the activeEditor is changed if (activeFile && activeFile.bookmarks.length > 0) { if (vscode.workspace.getConfiguration("numberedBookmarks").get<boolean>("experimental.enableNewStickyEngine", true)) { updatedBookmark = updateStickyBookmarks(event, activeFile, activeEditor, activeController); } else { updatedBookmark = Sticky.stickyBookmarks(event, activeEditorCountLine, activeFile, activeEditor); } } activeEditorCountLine = event.document.lineCount; updateDecorations(); if (updatedBookmark) { saveWorkspaceState(); } } }, null, context.subscriptions); vscode.workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration("numberedBookmarks.gutterIconFillColor") || event.affectsConfiguration("numberedBookmarks.gutterIconNumberColor") ) { updateSvgVersion(); updateBookmarkSvg(triggerUpdateDecorations); updateBookmarkDecorationType(bookmarkDecorationType); } }, null, context.subscriptions); // Timeout function triggerUpdateDecorations() { if (timeout) { clearTimeout(timeout); } timeout = setTimeout(updateDecorations, 100); } function getDecoration(n: number): vscode.TextEditorDecorationType { return bookmarkDecorationType[ n ]; } // Evaluate (prepare the list) and DRAW function updateDecorations() { updateDecorationsInActiveEditor(activeEditor, activeFile, getDecoration); } // other commands for (let i = 0; i <= 9; i++) { vscode.commands.registerCommand( `numberedBookmarks.toggleBookmark${i}`, () => toggleBookmark(i, vscode.window.activeTextEditor.selection.active) ); vscode.commands.registerCommand( `numberedBookmarks.jumpToBookmark${i}`, () => jumpToBookmark(i) ); } vscode.commands.registerCommand("numberedBookmarks.clear", () => { clearBookmarks(activeFile); saveWorkspaceState(); updateDecorations(); }); vscode.commands.registerCommand("numberedBookmarks.clearFromAllFiles", async () => { const controller = await pickController(controllers, activeController); if (!controller) { return } for (const file of controller.files) { clearBookmarks(file); } saveWorkspaceState(); updateDecorations(); }); vscode.commands.registerCommand("numberedBookmarks.list", () => { // no bookmark if (!hasBookmarks(activeFile)) { vscode.window.showInformationMessage("No Bookmarks found"); return; } // push the items const items: vscode.QuickPickItem[] = []; for (const bookmark of activeFile.bookmarks) { if (isBookmarkDefined(bookmark)) { const bookmarkLine = bookmark.line + 1; const bookmarkColumn = bookmark.column + 1; const lineText = vscode.window.activeTextEditor.document.lineAt(bookmarkLine - 1).text.trim(); items.push({ label: lineText, description: "(Ln " + bookmarkLine.toString() + ", Col " + bookmarkColumn.toString() + ")" }); } } // pick one const currentPosition: Position = vscode.window.activeTextEditor.selection.active; const options = <vscode.QuickPickOptions> { placeHolder: "Type a line number or a piece of code to navigate to", matchOnDescription: true, matchOnDetail: true, onDidSelectItem: item => { const itemT = <vscode.QuickPickItem> item; const point: Bookmark = parsePosition(itemT.description); if (point) { revealPosition(point.line - 1, point.column - 1); } } }; vscode.window.showQuickPick(items, options).then(selection => { if (typeof selection === "undefined") { revealPosition(currentPosition.line, currentPosition.character); return; } const itemT = <vscode.QuickPickItem> selection; const point: Bookmark = parsePosition(itemT.description); if (point) { revealPosition(point.line - 1, point.column - 1); } }); }); vscode.commands.registerCommand("numberedBookmarks.listFromAllFiles", async () => { const controller = await pickController(controllers, activeController); if (!controller) { return } // no bookmark let someFileHasBookmark: boolean; for (const file of controller.files) { someFileHasBookmark = someFileHasBookmark || hasBookmarks(file); if (someFileHasBookmark) break; } if (!someFileHasBookmark) { vscode.window.showInformationMessage("No Bookmarks found"); return; } // push the items const items: BookmarkQuickPickItem[] = []; const activeTextEditor = vscode.window.activeTextEditor; const promisses = []; const currentPosition: Position = vscode.window.activeTextEditor?.selection.active; // tslint:disable-next-line:prefer-for-of for (let index = 0; index < controller.files.length; index++) { const file = controller.files[ index ]; const pp = listBookmarks(file, controller.workspaceFolder); promisses.push(pp); } Promise.all(promisses).then( (values) => { // tslint:disable-next-line:prefer-for-of for (let index = 0; index < values.length; index++) { const element = values[ index ]; // tslint:disable-next-line:prefer-for-of for (let indexInside = 0; indexInside < element.length; indexInside++) { const elementInside = element[ indexInside ]; if (activeTextEditor && elementInside.detail.toString().toLocaleLowerCase() === getRelativePath(controller.workspaceFolder?.uri?.path, activeTextEditor.document.uri.path).toLocaleLowerCase()) { items.push( { label: elementInside.label, description: elementInside.description, uri: elementInside.uri } ); } else { items.push( { label: elementInside.label, description: elementInside.description, detail: elementInside.detail, uri: elementInside.uri } ); } } } // sort // - active document // - no octicon - document inside project // - with octicon - document outside project const itemsSorted: BookmarkQuickPickItem[] = items.sort(function(a: BookmarkQuickPickItem, b: BookmarkQuickPickItem): number { if (!a.detail && !b.detail) { return 0; } if (!a.detail && b.detail) { return -1; } if (a.detail && !b.detail) { return 1; } if ((a.detail.toString().indexOf(codicons.file_submodule + " ") === 0) && (b.detail.toString().indexOf(codicons.file_directory + " ") === 0)) { return -1; } if ((a.detail.toString().indexOf(codicons.file_directory + " ") === 0) && (b.detail.toString().indexOf(codicons.file_submodule + " ") === 0)) { return 1; } if ((a.detail.toString().indexOf(codicons.file_submodule + " ") === 0) && (b.detail.toString().indexOf(codicons.file_submodule + " ") === -1)) { return 1; } if ((a.detail.toString().indexOf(codicons.file_submodule + " ") === -1) && (b.detail.toString().indexOf(codicons.file_submodule + " ") === 0)) { return -1; } if ((a.detail.toString().indexOf(codicons.file_directory + " ") === 0) && (b.detail.toString().indexOf(codicons.file_directory + " ") === -1)) { return 1; } if ((a.detail.toString().indexOf(codicons.file_directory + " ") === -1) && (b.detail.toString().indexOf(codicons.file_directory + " ") === 0)) { return -1; } return 0; }); const options = <vscode.QuickPickOptions> { placeHolder: "Type a line number or a piece of code to navigate to", matchOnDescription: true, onDidSelectItem: item => { const itemT = <BookmarkQuickPickItem> item let fileUri: Uri; if (!itemT.detail) { fileUri = activeTextEditor.document.uri; } else { fileUri = itemT.uri; } const point: Bookmark = parsePosition(itemT.description); if (vscode.window.activeTextEditor && vscode.window.activeTextEditor.document.uri.fsPath.toLowerCase() === fileUri.fsPath.toLowerCase()) { revealPosition(point.line - 1, point.column - 1); } else { previewPositionInDocument(point, fileUri); } } }; vscode.window.showQuickPick(itemsSorted, options).then(async selection => { if (typeof selection === "undefined") { if (!activeTextEditor) { vscode.commands.executeCommand("workbench.action.closeActiveEditor"); return; } else { vscode.workspace.openTextDocument(activeTextEditor.document.uri).then(doc => { vscode.window.showTextDocument(doc).then(() => { revealPosition(currentPosition.line, currentPosition.character) return; }); }); } } if (typeof selection === "undefined") { return; } const point: Bookmark = parsePosition(selection.description); if (!selection.detail) { if (point) { revealPosition(point.line - 1, point.column - 1); } } }); } ); }); function getActiveController(document: TextDocument): void { // system files don't have workspace, so use the first one [0] if (!vscode.workspace.getWorkspaceFolder(document.uri)) { activeController = controllers[0]; return; } if (controllers.length > 1) { activeController = controllers.find(ctrl => ctrl.workspaceFolder.uri.path === vscode.workspace.getWorkspaceFolder(document.uri).uri.path); } } async function loadWorkspaceState(): Promise<void> { // no workspace, load as `undefined` and will always be from `workspaceState` if (!vscode.workspace.workspaceFolders) { const ctrl = await loadBookmarks(undefined); controllers.push(ctrl); activeController = ctrl; return; } // NOT `saveBookmarksInProject` if (!vscode.workspace.getConfiguration("numberedBookmarks").get("saveBookmarksInProject", false)) { //if (vscode.workspace.workspaceFolders.length > 1) { // no matter how many workspaceFolders exists, will always load from [0] because even with // multi-root, there would be no way to load state from different folders const ctrl = await loadBookmarks(vscode.workspace.workspaceFolders[0]); controllers.push(ctrl); activeController = ctrl; return; } // `saveBookmarksInProject` TRUE // single or multi-root, will load from each `workspaceFolder` controllers = await Promise.all( vscode.workspace.workspaceFolders!.map(async workspaceFolder => { const ctrl = await loadBookmarks(workspaceFolder); return ctrl; }) ); if (controllers.length === 1) { activeController = controllers[0]; } } function saveWorkspaceState(): void { // no workspace, there is only one `controller`, and will always be from `workspaceState` if (!vscode.workspace.workspaceFolders) { saveBookmarks(activeController); return; } // NOT `saveBookmarksInProject`, will load from `workspaceFolders[0]` - as before if (!vscode.workspace.getConfiguration("numberedBookmarks").get("saveBookmarksInProject", false)) { // no matter how many workspaceFolders exists, will always save to [0] because even with // multi-root, there would be no way to save state to different folders saveBookmarks(activeController); return; } // `saveBookmarksInProject` TRUE // single or multi-root, will save to each `workspaceFolder` controllers.forEach(controller => { saveBookmarks(controller); }); } function toggleBookmark(n: number, position: vscode.Position) { // fix issue emptyAtLaunch if (!activeFile) { activeController.addFile(vscode.window.activeTextEditor.document.uri); activeFile = activeController.fromUri(vscode.window.activeTextEditor.document.uri); } // there is another bookmark already set for this line? const index: number = indexOfBookmark(activeFile, position.line); if (index >= 0) { clearBookmark(index); } // if was myself, then I want to 'remove' if (index !== n) { activeFile.bookmarks[ n ] = { line: position.line, column: position.character } // when _toggling_ only "replace" differs, because it has to _invalidate_ that bookmark from other files const navigateThroughAllFiles: string = vscode.workspace.getConfiguration("numberedBookmarks").get("navigateThroughAllFiles", "false"); if (navigateThroughAllFiles === "replace") { for (const element of activeController.files) { if (element.path !== activeFile.path) { element.bookmarks[ n ] = NO_BOOKMARK_DEFINED; } } } } saveWorkspaceState(); updateDecorations(); } function clearBookmark(n: number) { activeFile.bookmarks[ n ] = NO_BOOKMARK_DEFINED; } async function jumpToBookmark(n: number) { if (!activeFile) { return; } // when _jumping_ each config has its own behavior const navigateThroughAllFiles: string = vscode.workspace.getConfiguration("numberedBookmarks").get("navigateThroughAllFiles", "false"); switch (navigateThroughAllFiles) { case "replace": // is it already set? if (activeFile.bookmarks[ n ].line < 0) { // no, look for another document that contains that bookmark // I can start from the first because _there is only one_ for (const element of activeController.files) { if ((element.path !== activeFile.path) && (isBookmarkDefined(element.bookmarks[ n ]))) { await revealPositionInDocument(element.bookmarks[n], activeController.getFileUri(element)); return; } } } else { revealPosition(activeFile.bookmarks[ n ].line, activeFile.bookmarks[ n ].column); } break; case "allowDuplicates": { // this file has, and I'm not in the line if ((isBookmarkDefined(activeFile.bookmarks[ n ])) && (activeFile.bookmarks[ n ].line !== vscode.window.activeTextEditor.selection.active.line)) { revealPosition(activeFile.bookmarks[ n ].line, activeFile.bookmarks[ n ].column); break; } // no, look for another document that contains that bookmark // I CAN'T start from the first because _there can be duplicates_ const currentFile: number = activeController.indexFromPath(activeFile.path); let found = false; // to the end for (let index = currentFile; index < activeController.files.length; index++) { const element = activeController.files[ index ]; if ((!found) && (element.path !== activeFile.path) && (isBookmarkDefined(element.bookmarks[ n ]))) { found = true; await revealPositionInDocument(element.bookmarks[n], activeController.getFileUri(element)); return; } } if (!found) { for (let index = 0; index < currentFile; index++) { const element = activeController.files[ index ]; if ((!found) && (element.path !== activeFile.path) && (isBookmarkDefined(element.bookmarks[ n ]))) { found = true; await revealPositionInDocument(element.bookmarks[n], activeController.getFileUri(element)); return; } } if (!found) { if (vscode.workspace.getConfiguration("numberedBookmarks").get<boolean>("showBookmarkNotDefinedWarning", false)) { vscode.window.showWarningMessage("The Bookmark " + n + " is not defined"); } return; } } break; } default: // "false" // is it already set? if (activeFile.bookmarks.length === 0) { vscode.window.showInformationMessage("No Bookmark found"); return; } if (activeFile.bookmarks[ n ].line < 0) { if (vscode.workspace.getConfiguration("numberedBookmarks").get<boolean>("showBookmarkNotDefinedWarning", false)) { vscode.window.showWarningMessage("The Bookmark " + n + " is not defined"); } return; } revealPosition(activeFile.bookmarks[ n ].line, activeFile.bookmarks[ n ].column); break; } } }
the_stack
import { Trans } from "@lingui/macro"; import { i18nMark } from "@lingui/react"; import classNames from "classnames"; import { Dropdown, Form, Table } from "reactjs-components"; import { Hooks } from "PluginSDK"; import { Link } from "react-router"; import mixin from "reactjs-mixin"; import PropTypes from "prop-types"; import * as React from "react"; import { ProductIcons } from "@dcos/ui-kit/dist/packages/icons/dist/product-icons-enum"; import StoreMixin from "#SRC/js/mixins/StoreMixin"; import Breadcrumb from "../../components/Breadcrumb"; import BreadcrumbTextContent from "../../components/BreadcrumbTextContent"; import BulkOptions from "../../constants/BulkOptions"; import FilterBar from "../../components/FilterBar"; import FilterHeadline from "../../components/FilterHeadline"; import FilterInputText from "../../components/FilterInputText"; import Page from "../../components/Page"; import ResourceTableUtil from "../../utils/ResourceTableUtil"; import StringUtil from "../../utils/StringUtil"; import TableUtil from "../../utils/TableUtil"; import UsersActionsModal from "../../components/modals/UsersActionsModal"; import UserFormModal from "../../components/modals/UserFormModal"; import UsersStore from "../../stores/UsersStore"; const USERS_CHANGE_EVENTS = [ "onUserStoreCreateSuccess", "onUserStoreDeleteSuccess", ]; const UsersBreadcrumbs = () => { const crumbs = [ <Breadcrumb key={0} title="Users"> <BreadcrumbTextContent> <Link to="/organization/users"> <Trans render="span">Users</Trans> </Link> </BreadcrumbTextContent> </Breadcrumb>, ]; return ( <Page.Header.Breadcrumbs iconID={ProductIcons.Users} breadcrumbs={crumbs} /> ); }; class OrganizationTab extends mixin(StoreMixin) { static propTypes = { items: PropTypes.array.isRequired, itemID: PropTypes.string.isRequired, itemName: PropTypes.string.isRequired, }; state = { checkableCount: 0, checkedCount: 0, openNewUserModal: false, showActionDropdown: false, searchString: "", selectedAction: null, usersStoreError: false, usersStoreSuccess: false, }; store_listeners = [ // prettier-ignore { name: "user", events: ["createSuccess", "deleteSuccess"], suppressUpdate: true }, ]; constructor(...args) { super(...args); Hooks.applyFilter( "organizationTabChangeEvents", USERS_CHANGE_EVENTS ).forEach((event) => { this[event] = this.onUsersChange; }); this.selectedIDSet = {}; } UNSAFE_componentWillMount() { this.resetTablewideCheckboxTabulations(); } UNSAFE_componentWillReceiveProps(nextProps) { if (nextProps.items.length !== this.props.items.length) { this.resetTablewideCheckboxTabulations(); } } componentDidUpdate(prevProps, prevState) { super.componentDidUpdate(...arguments); if ( prevState.searchString !== this.state.searchString || prevProps.items.length !== this.props.items.length ) { this.resetTablewideCheckboxTabulations(); } } onUsersChange() { UsersStore.fetchUsers(); } handleActionSelection = (dropdownItem) => { this.setState({ selectedAction: dropdownItem.id, }); }; handleActionSelectionClose = () => { this.setState({ selectedAction: null, }); this.bulkCheck(false); }; handleCheckboxChange = (prevCheckboxState, eventObject) => { const isChecked = eventObject.fieldValue; const checkedCount = this.state.checkedCount + (isChecked || -1); const selectedIDSet = this.selectedIDSet; selectedIDSet[eventObject.fieldName] = isChecked; this.selectedIDSet = selectedIDSet; this.setState({ checkedCount, showActionDropdown: checkedCount > 0, }); }; handleHeadingCheckboxChange = (prevCheckboxState, eventObject) => { const isChecked = eventObject.fieldValue; this.bulkCheck(isChecked); }; handleSearchStringChange = (searchString = "") => { this.setState({ searchString }); this.bulkCheck(false); }; handleNewUserClick = () => { this.setState({ openNewUserModal: true }); }; handleNewUserClose = () => { this.setState({ openNewUserModal: false }); }; renderFullName = (prop, subject) => { return subject.get("description"); }; renderUsername = (prop, subject) => { return ( <div className="row"> <div className="column-small-12 column-large-12 column-x-large-12 text-overflow"> {subject.get("uid")} </div> </div> ); }; renderCheckbox = (prop, row) => { const rowID = row[this.props.itemID]; const remoteIDSet = this.remoteIDSet; const { checkableCount, checkedCount } = this.state; const disabled = remoteIDSet[rowID] === true; let checked = null; if (disabled || checkedCount === 0) { checked = false; } else if (checkedCount === checkableCount) { checked = true; } else { checked = this.selectedIDSet[rowID]; } return ( <Form formGroupClass="form-group flush-bottom" definition={[ { checked, disabled, value: checked, fieldType: "checkbox", labelClass: "form-row-element form-element-checkbox", name: rowID, showLabel: false, }, ]} onChange={this.handleCheckboxChange} /> ); }; renderHeadingCheckbox = () => { let checked = false; let indeterminate = false; switch (this.state.checkedCount) { case 0: checked = false; break; case this.state.checkableCount: checked = true; break; default: indeterminate = true; break; } return ( <Form formGroupClass="form-group flush-bottom" definition={[ { checked, value: checked, fieldType: "checkbox", indeterminate, labelClass: "form-row-element form-element-checkbox", name: "headingCheckbox", showLabel: false, }, ]} onChange={this.handleHeadingCheckboxChange} /> ); }; getColGroup() { return ( <colgroup> <col style={{ width: "40px" }} /> <col /> </colgroup> ); } getClassName(prop, sortBy, row) { return classNames({ clickable: row == null, // this is a header }); } getColumns() { const { getClassName } = this; return [ { className: getClassName, headerClassName: getClassName, prop: "selected", render: this.renderCheckbox, sortable: false, heading: this.renderHeadingCheckbox, }, { cacheCell: true, className: getClassName, headerClassName: getClassName, prop: "uid", render: this.renderUsername, sortable: true, sortFunction: TableUtil.getSortFunction( this.props.itemID, (item, prop) => item.get(prop) ), heading: ResourceTableUtil.renderHeading({ uid: i18nMark("USERNAME") }), }, ]; } getActionDropdown(itemName) { if (!this.state.showActionDropdown) { return null; } const actionPhrases = BulkOptions[itemName]; let initialID = null; // Get first Action to set as initially selected option in dropdown. initialID = Object.keys(actionPhrases)[0] || null; const dropdownItems = this.getActionsDropdownItems(actionPhrases); if (dropdownItems.length === 1) { return ( <button className="button" onClick={this.handleActionSelection.bind(this, dropdownItems[0])} > {dropdownItems[0].html} </button> ); } return ( <li> <Dropdown buttonClassName="button dropdown-toggle" dropdownMenuClassName="dropdown-menu" dropdownMenuListClassName="dropdown-menu-list" dropdownMenuListItemClassName="clickable" initialID={initialID} items={dropdownItems} onItemSelection={this.handleActionSelection} scrollContainer=".gm-scroll-view" scrollContainerParentSelector=".gm-prevented" transition={true} transitionName="dropdown-menu" wrapperClassName="dropdown" /> </li> ); } getActionsDropdownItems(actionPhrases) { return Object.keys(actionPhrases).map((action) => ({ html: actionPhrases[action].dropdownOption, id: action, selectedHtml: "Actions", })); } getCheckedItemObjects(items, itemIDName) { if (this.state.selectedAction) { const checkboxStates = this.selectedIDSet; const selectedItems = {}; Object.keys(checkboxStates).forEach((id) => { if (checkboxStates[id] === true) { selectedItems[id] = true; } }); return items.filter((item) => { const itemID = item[itemIDName]; return selectedItems[itemID] || false; }); } return null; } getVisibleItems(items) { let { searchString } = this.state; searchString = searchString.toLowerCase(); if (searchString !== "") { return items.filter((item) => { const description = item.get("description").toLowerCase(); const id = item.get(this.props.itemID).toLowerCase(); return ( description.indexOf(searchString) > -1 || id.indexOf(searchString) > -1 ); }); } return items; } getActionsModal(action, items, itemID, itemName) { if (action === null) { return null; } const checkedItemObjects = this.getCheckedItemObjects(items, itemID) || []; return ( <UsersActionsModal action={action} actionText={BulkOptions[itemName][action]} bodyClass="modal-content allow-overflow" itemID={itemID} itemType={itemName} onClose={this.handleActionSelectionClose} selectedItems={checkedItemObjects} /> ); } getTableRowOptions = (row) => { const selectedIDSet = this.selectedIDSet; if (selectedIDSet[row[this.props.itemID]]) { return { className: "selected" }; } return {}; }; bulkCheck(isChecked) { let checkedCount = 0; const selectedIDSet = this.selectedIDSet; Object.keys(selectedIDSet).forEach((id) => { selectedIDSet[id] = isChecked; }); this.selectedIDSet = selectedIDSet; if (isChecked) { checkedCount = this.state.checkableCount; } this.setState({ checkedCount, showActionDropdown: checkedCount > 0, }); } resetTablewideCheckboxTabulations() { let { items, itemID } = this.props; items = this.getVisibleItems(items); const selectedIDSet = {}; const remoteIDSet = {}; let checkableCount = 0; // Initializing hash of items' IDs and corresponding checkbox state. items.forEach((item) => { const id = item.get(itemID); checkableCount += 1; selectedIDSet[id] = false; }); this.selectedIDSet = selectedIDSet; this.remoteIDSet = remoteIDSet; this.setState({ checkableCount }); } resetFilter = () => { this.setState({ searchString: "" }); }; render() { const { items, itemID, itemName } = this.props; const state = this.state; const action = state.selectedAction; const capitalizedItemName = StringUtil.capitalize(itemName); const visibleItems = this.getVisibleItems(items); const actionDropdown = this.getActionDropdown(itemName); const actionsModal = this.getActionsModal(action, items, itemID, itemName); const sortProp = itemID; return ( <Page> <Page.Header breadcrumbs={<UsersBreadcrumbs />} addButton={{ onItemSelect: this.handleNewUserClick, label: `New ${capitalizedItemName}`, }} /> <div className="flex-container-col"> <div className={`${itemName}s-table-header`}> <FilterHeadline onReset={this.resetFilter} name={capitalizedItemName} currentLength={visibleItems.length} totalLength={items.length} /> <FilterBar> <FilterInputText className="flush-bottom" searchString={this.state.searchString} handleFilterChange={this.handleSearchStringChange} /> {actionDropdown} {actionsModal} </FilterBar> </div> <div className="page-body-content-fill flex-grow flex-container-col"> <Table buildRowOptions={this.getTableRowOptions} className="table table-flush table-borderless-outer table-borderless-inner-columns table-hover flush-bottom" columns={this.getColumns()} colGroup={this.getColGroup()} containerSelector=".gm-scrollbar-container-fluid-view-width" data={visibleItems} itemHeight={TableUtil.getRowHeight()} sortBy={{ prop: sortProp, order: "asc" }} /> </div> </div> <UserFormModal open={this.state.openNewUserModal} onClose={this.handleNewUserClose} /> </Page> ); } } export default OrganizationTab;
the_stack
"use strict"; import { ArgumentListCtx, ArrayAccessSuffixCtx, ArrayCreationDefaultInitSuffixCtx, ArrayCreationExplicitInitSuffixCtx, ArrayCreationExpressionCtx, BinaryExpressionCtx, CastExpressionCtx, ClassLiteralSuffixCtx, ClassOrInterfaceTypeToInstantiateCtx, DiamondCtx, DimExprCtx, DimExprsCtx, ExplicitLambdaParameterListCtx, ExpressionCtx, FqnOrRefTypeCtx, FqnOrRefTypePartCommonCtx, FqnOrRefTypePartFirstCtx, FqnOrRefTypePartRestCtx, InferredLambdaParameterListCtx, IToken, LambdaBodyCtx, LambdaExpressionCtx, LambdaParameterCtx, LambdaParameterListCtx, LambdaParametersCtx, LambdaParametersWithBracesCtx, LambdaParameterTypeCtx, MethodInvocationSuffixCtx, MethodReferenceSuffixCtx, NewExpressionCtx, ParenthesisExpressionCtx, PatternCtx, PrimaryCtx, PrimaryPrefixCtx, PrimarySuffixCtx, PrimitiveCastExpressionCtx, ReferenceTypeCastExpressionCtx, RegularLambdaParameterCtx, TernaryExpressionCtx, TypeArgumentListCtx, TypeArgumentsOrDiamondCtx, TypePatternCtx, UnaryExpressionCtx, UnaryExpressionNotPlusMinusCtx, UnqualifiedClassInstanceCreationExpressionCtx } from "java-parser/api"; import forEach from "lodash/forEach"; import { Doc } from "prettier"; import { builders } from "prettier/doc"; import { BaseCstPrettierPrinter } from "../base-cst-printer"; import { isAnnotationCstNode } from "../types/utils"; import { isArgumentListSingleLambda } from "../utils/expressions-utils"; import { printSingleLambdaInvocation, printArgumentListWithBraces } from "../utils"; import { printTokenWithComments } from "./comments/format-comments"; import { handleCommentsBinaryExpression } from "./comments/handle-comments"; import { concat, dedent, group, indent } from "./prettier-builder"; import { findDeepElementInPartsArray, isExplicitLambdaParameter, isShiftOperator, isUniqueMethodInvocation, matchCategory, putIntoBraces, rejectAndConcat, rejectAndJoin, rejectAndJoinSeps, separateTokensIntoGroups, sortAnnotationIdentifier, sortNodes } from "./printer-utils"; const { ifBreak, line, softline, indentIfBreak } = builders; export class ExpressionsPrettierVisitor extends BaseCstPrettierPrinter { expression(ctx: ExpressionCtx, params: any) { return this.visitSingle(ctx, params); } lambdaExpression( ctx: LambdaExpressionCtx, params?: { lambdaParametersGroupId: symbol; isInsideMethodInvocationSuffix: boolean; } ) { const lambdaParameters = group( this.visit(ctx.lambdaParameters, params), params ? { id: params.lambdaParametersGroupId } : undefined ); const lambdaBody = this.visit(ctx.lambdaBody); const isLambdaBodyABlock = ctx.lambdaBody[0].children.block !== undefined; if (isLambdaBodyABlock) { return rejectAndJoin(" ", [ lambdaParameters, ctx.Arrow[0], params?.lambdaParametersGroupId !== undefined ? indentIfBreak(lambdaBody, { groupId: params.lambdaParametersGroupId }) : lambdaBody ]); } return group( indent( rejectAndJoin(line, [ rejectAndJoin(" ", [lambdaParameters, ctx.Arrow[0]]), lambdaBody ]) ) ); } lambdaParameters( ctx: LambdaParametersCtx, params?: { isInsideMethodInvocationSuffix: boolean } ) { if (ctx.lambdaParametersWithBraces) { return this.visitSingle(ctx, params); } return printTokenWithComments(this.getSingle(ctx) as IToken); } lambdaParametersWithBraces( ctx: LambdaParametersWithBracesCtx, params?: { isInsideMethodInvocationSuffix: boolean } ) { const lambdaParameterList = this.visit(ctx.lambdaParameterList); if (findDeepElementInPartsArray(lambdaParameterList, ",")) { const content = putIntoBraces( lambdaParameterList, softline, ctx.LBrace[0], ctx.RBrace[0] ); if (params?.isInsideMethodInvocationSuffix === true) { return indent(concat([softline, content])); } return content; } // removing braces when only no comments attached if ( (ctx.LBrace && ctx.RBrace && (!lambdaParameterList || isExplicitLambdaParameter(ctx))) || ctx.LBrace[0].leadingComments || ctx.LBrace[0].trailingComments || ctx.RBrace[0].leadingComments || ctx.RBrace[0].trailingComments ) { return rejectAndConcat([ ctx.LBrace[0], lambdaParameterList, ctx.RBrace[0] ]); } return lambdaParameterList; } lambdaParameterList(ctx: LambdaParameterListCtx) { return this.visitSingle(ctx); } inferredLambdaParameterList(ctx: InferredLambdaParameterListCtx) { const commas = ctx.Comma ? ctx.Comma.map(elt => { return concat([elt, line]); }) : []; return rejectAndJoinSeps(commas, ctx.Identifier); } explicitLambdaParameterList(ctx: ExplicitLambdaParameterListCtx) { const lambdaParameter = this.mapVisit(ctx.lambdaParameter); const commas = ctx.Comma ? ctx.Comma.map(elt => { return concat([elt, line]); }) : []; return rejectAndJoinSeps(commas, lambdaParameter); } lambdaParameter(ctx: LambdaParameterCtx) { return this.visitSingle(ctx); } regularLambdaParameter(ctx: RegularLambdaParameterCtx) { const variableModifier = this.mapVisit(ctx.variableModifier); const lambdaParameterType = this.visit(ctx.lambdaParameterType); const variableDeclaratorId = this.visit(ctx.variableDeclaratorId); return rejectAndJoin(" ", [ rejectAndJoin(" ", variableModifier), lambdaParameterType, variableDeclaratorId ]); } lambdaParameterType(ctx: LambdaParameterTypeCtx) { if (ctx.unannType) { return this.visitSingle(ctx); } return printTokenWithComments(this.getSingle(ctx) as IToken); } lambdaBody(ctx: LambdaBodyCtx) { return this.visitSingle(ctx); } ternaryExpression(ctx: TernaryExpressionCtx, params: any) { const binaryExpression = this.visit(ctx.binaryExpression, params); if (ctx.QuestionMark) { const expression1 = this.visit(ctx.expression![0]); const expression2 = this.visit(ctx.expression![1]); return indent( group( rejectAndConcat([ rejectAndJoin(line, [ binaryExpression, rejectAndJoin(" ", [ctx.QuestionMark[0], expression1]), rejectAndJoin(" ", [ctx.Colon![0], expression2]) ]) ]) ) ); } return binaryExpression; } binaryExpression(ctx: BinaryExpressionCtx, params: any) { handleCommentsBinaryExpression(ctx); const instanceofReferences = this.mapVisit( sortNodes([ctx.pattern, ctx.referenceType]) ); const expression = this.mapVisit(ctx.expression); const unaryExpression = this.mapVisit(ctx.unaryExpression); const { groupsOfOperator, sortedBinaryOperators } = separateTokensIntoGroups(ctx); const segmentsSplitByBinaryOperator: any[] = []; let currentSegment = []; if (groupsOfOperator.length === 1 && groupsOfOperator[0].length === 0) { return unaryExpression.shift(); } groupsOfOperator.forEach(subgroup => { currentSegment = [unaryExpression.shift()]; for (let i = 0; i < subgroup.length; i++) { const token = subgroup[i]; const shiftOperator = isShiftOperator(subgroup, i); if (token.tokenType.name === "Instanceof") { currentSegment.push( rejectAndJoin(" ", [ ctx.Instanceof![0], instanceofReferences.shift() ]) ); } else if (matchCategory(token, "'AssignmentOperator'")) { currentSegment.push( indent(rejectAndJoin(line, [token, expression.shift()])) ); } else if ( shiftOperator === "leftShift" || shiftOperator === "rightShift" ) { currentSegment.push( rejectAndJoin(" ", [ rejectAndConcat([token, subgroup[i + 1]]), unaryExpression.shift() ]) ); i++; } else if (shiftOperator === "doubleRightShift") { currentSegment.push( rejectAndJoin(" ", [ rejectAndConcat([token, subgroup[i + 1], subgroup[i + 2]]), unaryExpression.shift() ]) ); i += 2; } else if (matchCategory(token, "'BinaryOperator'")) { currentSegment.push( rejectAndJoin(line, [token, unaryExpression.shift()]) ); } } segmentsSplitByBinaryOperator.push( group(rejectAndJoin(" ", currentSegment)) ); }); if (params !== undefined && params.addParenthesisToWrapStatement) { return group( concat([ ifBreak("(", ""), indent( concat([ softline, group( rejectAndJoinSeps( sortedBinaryOperators.map(elt => concat([" ", elt, line])), segmentsSplitByBinaryOperator ) ) ]) ), softline, ifBreak(")") ]) ); } return group( rejectAndJoinSeps( sortedBinaryOperators.map(elt => concat([" ", elt, line])), segmentsSplitByBinaryOperator ) ); } unaryExpression(ctx: UnaryExpressionCtx) { const unaryPrefixOperator = ctx.UnaryPrefixOperator ? ctx.UnaryPrefixOperator : []; const primary = this.visit(ctx.primary); const unarySuffixOperator = ctx.UnarySuffixOperator ? ctx.UnarySuffixOperator : []; return rejectAndConcat([ rejectAndConcat(unaryPrefixOperator), primary, rejectAndConcat(unarySuffixOperator) ]); } unaryExpressionNotPlusMinus(ctx: UnaryExpressionNotPlusMinusCtx) { const unaryPrefixOperatorNotPlusMinus = ctx.UnaryPrefixOperatorNotPlusMinus // changed when moved to TS ? rejectAndJoin(" ", ctx.UnaryPrefixOperatorNotPlusMinus) // changed when moved to TS : ""; const primary = this.visit(ctx.primary); const unarySuffixOperator = ctx.UnarySuffixOperator // changed when moved to TS ? rejectAndJoin(" ", ctx.UnarySuffixOperator) // changed when moved to TS : ""; return rejectAndJoin(" ", [ unaryPrefixOperatorNotPlusMinus, primary, unarySuffixOperator ]); } primary(ctx: PrimaryCtx) { const countMethodInvocation = isUniqueMethodInvocation(ctx.primarySuffix); const primaryPrefix = this.visit(ctx.primaryPrefix, { shouldBreakBeforeFirstMethodInvocation: countMethodInvocation > 1 }); const suffixes = []; if (ctx.primarySuffix !== undefined) { // edge case: https://github.com/jhipster/prettier-java/issues/381 let hasFirstInvocationArg = true; if ( ctx.primarySuffix.length > 1 && ctx.primarySuffix[1].children.methodInvocationSuffix && Object.keys( ctx.primarySuffix[1].children.methodInvocationSuffix[0].children ).length === 2 ) { hasFirstInvocationArg = false; } if ( ctx.primarySuffix[0].children.Dot !== undefined && ctx.primaryPrefix[0].children.newExpression !== undefined ) { suffixes.push(softline); } suffixes.push( this.visit(ctx.primarySuffix[0], { shouldDedent: // dedent when simple method invocation countMethodInvocation !== 1 && // dedent when (chain) method invocation ctx.primaryPrefix[0] && ctx.primaryPrefix[0].children.fqnOrRefType && !( ctx.primaryPrefix[0].children.fqnOrRefType[0].children.Dot !== undefined ) && // indent when lambdaExpression ctx.primarySuffix[0].children.methodInvocationSuffix && ctx.primarySuffix[0].children.methodInvocationSuffix[0].children .argumentList && ctx.primarySuffix[0].children.methodInvocationSuffix[0].children .argumentList[0].children.expression && ctx.primarySuffix[0].children.methodInvocationSuffix[0].children .argumentList[0].children.expression[0].children .lambdaExpression === undefined }) ); for (let i = 1; i < ctx.primarySuffix.length; i++) { if ( ctx.primarySuffix[i].children.Dot !== undefined && ctx.primarySuffix[i - 1].children.methodInvocationSuffix !== undefined ) { suffixes.push(softline); } suffixes.push(this.visit(ctx.primarySuffix[i])); } if ( countMethodInvocation === 1 && ctx.primaryPrefix[0].children.newExpression === undefined ) { return group( rejectAndConcat([ primaryPrefix, hasFirstInvocationArg ? suffixes[0] : indent(suffixes[0]), indent(rejectAndConcat(suffixes.slice(1))) ]) ); } } return group( rejectAndConcat([primaryPrefix, indent(rejectAndConcat(suffixes))]) ); } primaryPrefix(ctx: PrimaryPrefixCtx, params: any) { if (ctx.This || ctx.Void) { return printTokenWithComments(this.getSingle(ctx) as IToken); } return this.visitSingle(ctx, params); } primarySuffix(ctx: PrimarySuffixCtx, params: any) { if (ctx.Dot) { if (ctx.This) { return rejectAndConcat([ctx.Dot[0], ctx.This[0]]); } else if (ctx.Identifier) { const typeArguments = this.visit(ctx.typeArguments); return rejectAndConcat([ctx.Dot[0], typeArguments, ctx.Identifier[0]]); } const unqualifiedClassInstanceCreationExpression = this.visit( ctx.unqualifiedClassInstanceCreationExpression ); return rejectAndConcat([ ctx.Dot[0], unqualifiedClassInstanceCreationExpression ]); } return this.visitSingle(ctx, params); } fqnOrRefType(ctx: FqnOrRefTypeCtx, params: any) { const fqnOrRefTypePartFirst = this.visit(ctx.fqnOrRefTypePartFirst); const fqnOrRefTypePartRest = this.mapVisit(ctx.fqnOrRefTypePartRest); const dims = this.visit(ctx.dims); const dots = ctx.Dot ? ctx.Dot : []; const isMethodInvocation = ctx.Dot && ctx.Dot.length === 1; if ( params !== undefined && params.shouldBreakBeforeFirstMethodInvocation === true ) { // when fqnOrRefType is a method call from an object if (isMethodInvocation) { return rejectAndConcat([ indent( rejectAndJoin(concat([softline, dots[0]]), [ fqnOrRefTypePartFirst, rejectAndJoinSeps(dots.slice(1), fqnOrRefTypePartRest), dims ]) ) ]); // otherwise it is a fully qualified name but we need to exclude when it is just a method call } else if (ctx.Dot) { return indent( rejectAndConcat([ rejectAndJoinSeps(dots.slice(0, dots.length - 1), [ fqnOrRefTypePartFirst, ...fqnOrRefTypePartRest.slice(0, fqnOrRefTypePartRest.length - 1) ]), softline, rejectAndConcat([ dots[dots.length - 1], fqnOrRefTypePartRest[fqnOrRefTypePartRest.length - 1] ]), dims ]) ); } } return rejectAndConcat([ rejectAndJoinSeps(dots, [fqnOrRefTypePartFirst, ...fqnOrRefTypePartRest]), dims ]); } fqnOrRefTypePartFirst(ctx: FqnOrRefTypePartFirstCtx) { const annotation = this.mapVisit(ctx.annotation); const fqnOrRefTypeCommon = this.visit(ctx.fqnOrRefTypePartCommon); return rejectAndJoin(" ", [ rejectAndJoin(" ", annotation), fqnOrRefTypeCommon ]); } fqnOrRefTypePartRest(ctx: FqnOrRefTypePartRestCtx) { const annotation = this.mapVisit(ctx.annotation); const fqnOrRefTypeCommon = this.visit(ctx.fqnOrRefTypePartCommon); const typeArguments = this.visit(ctx.typeArguments); return rejectAndJoin(" ", [ rejectAndJoin(" ", annotation), rejectAndConcat([typeArguments, fqnOrRefTypeCommon]) ]); } fqnOrRefTypePartCommon(ctx: FqnOrRefTypePartCommonCtx) { let keyWord = null; if (ctx.Identifier) { keyWord = ctx.Identifier[0]; } else { keyWord = ctx.Super![0]; } const typeArguments = this.visit(ctx.typeArguments); return rejectAndConcat([keyWord, typeArguments]); } parenthesisExpression(ctx: ParenthesisExpressionCtx) { const expression = this.visit(ctx.expression); return putIntoBraces(expression, softline, ctx.LBrace[0], ctx.RBrace[0]); } castExpression(ctx: CastExpressionCtx) { return this.visitSingle(ctx); } primitiveCastExpression(ctx: PrimitiveCastExpressionCtx) { const primitiveType = this.visit(ctx.primitiveType); const unaryExpression = this.visit(ctx.unaryExpression); return rejectAndJoin(" ", [ rejectAndConcat([ctx.LBrace[0], primitiveType, ctx.RBrace[0]]), unaryExpression ]); } referenceTypeCastExpression(ctx: ReferenceTypeCastExpressionCtx) { const referenceType = this.visit(ctx.referenceType); const additionalBound = this.mapVisit(ctx.additionalBound); const expression = ctx.lambdaExpression ? this.visit(ctx.lambdaExpression) : this.visit(ctx.unaryExpressionNotPlusMinus); return rejectAndJoin(" ", [ rejectAndConcat([ctx.LBrace[0], referenceType, ctx.RBrace[0]]), additionalBound, expression ]); } newExpression(ctx: NewExpressionCtx) { return this.visitSingle(ctx); } unqualifiedClassInstanceCreationExpression( ctx: UnqualifiedClassInstanceCreationExpressionCtx ) { const typeArguments = this.visit(ctx.typeArguments); const classOrInterfaceTypeToInstantiate = this.visit( ctx.classOrInterfaceTypeToInstantiate ); let content = printArgumentListWithBraces.call( this, ctx.argumentList, ctx.RBrace[0], ctx.LBrace[0] ); const classBody = this.visit(ctx.classBody); return rejectAndJoin(" ", [ ctx.New[0], rejectAndConcat([ typeArguments, classOrInterfaceTypeToInstantiate, content ]), classBody ]); } classOrInterfaceTypeToInstantiate(ctx: ClassOrInterfaceTypeToInstantiateCtx) { const tokens = sortAnnotationIdentifier(ctx.annotation, ctx.Identifier); const segments: any[] = []; let currentSegment: any[] = []; forEach(tokens, token => { if (isAnnotationCstNode(token)) { currentSegment.push(this.visit([token])); } else { currentSegment.push(token); segments.push(rejectAndJoin(" ", currentSegment)); currentSegment = []; } }); const typeArgumentsOrDiamond = this.visit(ctx.typeArgumentsOrDiamond); const dots = ctx.Dot ? ctx.Dot : []; return rejectAndConcat([ rejectAndJoinSeps(dots, segments), typeArgumentsOrDiamond ]); } typeArgumentsOrDiamond(ctx: TypeArgumentsOrDiamondCtx) { return this.visitSingle(ctx); } diamond(ctx: DiamondCtx) { return concat([ctx.Less[0], ctx.Greater[0]]); } methodInvocationSuffix(ctx: MethodInvocationSuffixCtx, params: any) { const isSingleLambda = isArgumentListSingleLambda(ctx.argumentList); if (isSingleLambda) { return printSingleLambdaInvocation.call( this, ctx.argumentList, ctx.RBrace[0], ctx.LBrace[0] ); } const argumentList = this.visit(ctx.argumentList); if (params && params.shouldDedent) { return dedent( putIntoBraces(argumentList, softline, ctx.LBrace[0], ctx.RBrace[0]) ); } return putIntoBraces(argumentList, softline, ctx.LBrace[0], ctx.RBrace[0]); } argumentList( ctx: ArgumentListCtx, params?: { lambdaParametersGroupId: symbol; isInsideMethodInvocationSuffix: boolean; } ) { const expressions = this.mapVisit(ctx.expression, params); const commas = ctx.Comma ? ctx.Comma.map(elt => concat([elt, line])) : []; return rejectAndJoinSeps(commas, expressions); } arrayCreationExpression(ctx: ArrayCreationExpressionCtx) { const type = ctx.primitiveType ? this.visit(ctx.primitiveType) : this.visit(ctx.classOrInterfaceType); const suffix = ctx.arrayCreationDefaultInitSuffix ? this.visit(ctx.arrayCreationDefaultInitSuffix) : this.visit(ctx.arrayCreationExplicitInitSuffix); return rejectAndConcat([concat([ctx.New[0], " "]), type, suffix]); } arrayCreationDefaultInitSuffix(ctx: ArrayCreationDefaultInitSuffixCtx) { const dimExprs = this.visit(ctx.dimExprs); const dims = this.visit(ctx.dims); return rejectAndConcat([dimExprs, dims]); } arrayCreationExplicitInitSuffix(ctx: ArrayCreationExplicitInitSuffixCtx) { const dims = this.visit(ctx.dims); const arrayInitializer = this.visit(ctx.arrayInitializer); return rejectAndJoin(" ", [dims, arrayInitializer]); } dimExprs(ctx: DimExprsCtx) { const dimExpr = this.mapVisit(ctx.dimExpr); return rejectAndConcat(dimExpr); } dimExpr(ctx: DimExprCtx) { const annotations = this.mapVisit(ctx.annotation); const expression = this.visit(ctx.expression); return rejectAndJoin(" ", [ rejectAndJoin(" ", annotations), rejectAndConcat([ctx.LSquare[0], expression, ctx.RSquare[0]]) ]); } classLiteralSuffix(ctx: ClassLiteralSuffixCtx) { const squares = []; if (ctx.LSquare) { for (let i = 0; i < ctx.LSquare.length; i++) { squares.push(concat([ctx.LSquare[i], ctx.RSquare![i]])); } } return rejectAndConcat([...squares, ctx.Dot[0], ctx.Class[0]]); } arrayAccessSuffix(ctx: ArrayAccessSuffixCtx) { const expression = this.visit(ctx.expression); return rejectAndConcat([ctx.LSquare[0], expression, ctx.RSquare[0]]); } methodReferenceSuffix(ctx: MethodReferenceSuffixCtx) { const typeArguments = this.visit(ctx.typeArguments); const identifierOrNew = ctx.New ? ctx.New[0] : ctx.Identifier![0]; return rejectAndConcat([ctx.ColonColon[0], typeArguments, identifierOrNew]); } pattern(ctx: PatternCtx) { return this.visitSingle(ctx); } typePattern(ctx: TypePatternCtx) { return this.visitSingle(ctx); } identifyNewExpressionType() { return "identifyNewExpressionType"; } isLambdaExpression() { return "isLambdaExpression"; } isCastExpression() { return "isCastExpression"; } isPrimitiveCastExpression() { return "isPrimitiveCastExpression"; } isReferenceTypeCastExpression() { return "isReferenceTypeCastExpression"; } isRefTypeInMethodRef() { return "isRefTypeInMethodRef"; } }
the_stack
import { assert, log, logIf, LogLevel } from './auxiliaries'; import { GLsizei2 } from './tuples'; import { ChangeLookup } from './changelookup'; import { Context } from './context'; import { Framebuffer } from './framebuffer'; import { Initializable } from './initializable'; import { NdcFillingTriangle } from './ndcfillingtriangle'; import { Program } from './program'; import { Shader } from './shader'; import { Texture2D } from './texture2d'; import { Wizard } from './wizard'; /* spellchecker: enable */ /** * This pass accumulates the color attachment 0 of a framebuffer, e.g., the result of an intermediate frame, into an * accumulation buffer. For accumulation the frame number is used to derive the accumulation weight. For rendering to * texture, a textured ndc-filling triangle is used. * * The accumulation pass can be used as follows: * ``` * this.accumulate.initialize(); * this.accumulate.texture = this.intermediateFBO.texture(gl2facade.COLOR_ATTACHMENT0); * this.accumulate.update(); * this.accumulate.frame(frameNumber); * ``` */ export class AccumulatePass extends Initializable { /** * Read-only access to the objects context, used to get context information and WebGL API access. */ protected _context: Context; /** * Alterable auxiliary object for tracking changes on this object's input and lazy updates. */ protected readonly _altered = Object.assign(new ChangeLookup(), { any: false, texture: false, precision: false, passThrough: false, }); /** @see {@link texture} */ protected _texture: Texture2D; /** @see {@link precision} */ protected _precision: Wizard.Precision = Wizard.Precision.half; /** @see {@link passThrough} */ protected _passThrough: boolean; /** * Two rgba-framebuffers used for accumulation (buffer ping-ponging is used for alternating the buffers for read * and write access due to a limitation in WebGL). */ protected _accumulationFBOs: [Framebuffer, Framebuffer]; protected _accumulationTextures: [Texture2D, Texture2D]; /** * Stores the index of the last buffer written to. */ protected _write: GLuint = 0; /** * Geometry used to draw on. This is not provided by default to allow for geometry sharing. If no triangle is given, * the ndc triangle will be created and managed internally. */ protected _ndcTriangle: NdcFillingTriangle; /** * Tracks ownership of the ndc-filling triangle. */ protected _ndcTriangleShared = false; protected _program: Program; protected _uWeight: WebGLUniformLocation; constructor(context: Context) { super(); this._context = context; } /** * Specializes this pass's initialization. This pass requires an ndc-filling triangle, a single accumulation * program, and two accumulation framebuffers for ping pong (simultaneous read and write is currently not allowed * by webgl). All attribute and dynamic uniform locations are cached. * @param ndcTriangle - If specified, assumed to be used as shared geometry. If none is specified, a ndc-filling * triangle will be created internally. */ @Initializable.initialize() initialize(ndcTriangle?: NdcFillingTriangle): boolean { const gl = this._context.gl; this._accumulationFBOs = [ new Framebuffer(this._context, 'AccumPingFBO'), new Framebuffer(this._context, 'AccumPongFBO')]; this._accumulationTextures = [ new Texture2D(this._context, 'AccumPingTexture'), new Texture2D(this._context, 'AccumPongTexture')]; if (ndcTriangle === undefined) { this._ndcTriangle = new NdcFillingTriangle(this._context, 'NdcFillingTriangle-Accumulate'); } else { this._ndcTriangle = ndcTriangle; this._ndcTriangleShared = true; } /* Configure program-based accumulate. */ const vert = new Shader(this._context, gl.VERTEX_SHADER, 'ndcvertices.vert (accumulate)'); // eslint-disable-next-line @typescript-eslint/no-var-requires vert.initialize(require('./shaders/ndcvertices.vert')); const frag = new Shader(this._context, gl.FRAGMENT_SHADER, 'accumulate.frag'); // eslint-disable-next-line @typescript-eslint/no-var-requires frag.initialize(require('./shaders/accumulate.frag')); this._program = new Program(this._context, 'AccumulateProgram'); this._program.initialize([vert, frag], false); if (!this._ndcTriangle.initialized) { this._ndcTriangle.initialize(); } this._program.attribute('a_vertex', this._ndcTriangle.vertexLocation); this._program.link(); this._uWeight = this._program.uniform('u_weight'); this._program.bind(); gl.uniform1f(this._uWeight, 0.0); gl.uniform1i(this._program.uniform('u_accumulationTexture'), 0); gl.uniform1i(this._program.uniform('u_currentFrameTexture'), 1); this._program.unbind(); return true; } /** * Specializes this pass's uninitialization. Program and geometry resources are released (if allocated). Cached * uniform and attribute locations are invalidated. */ @Initializable.uninitialize() uninitialize(): void { if (!this._ndcTriangleShared && this._ndcTriangle.initialized) { this._ndcTriangle.uninitialize(); } this._program.uninitialize(); this._accumulationFBOs[0].uninitialize(); this._accumulationFBOs[1].uninitialize(); this._accumulationTextures[0].uninitialize(); this._accumulationTextures[1].uninitialize(); this._write = 0; } /** * Initialize accumulation textures and FBOs (if not initialized yet). Then verifies if the texture's size has * changed, and if so, resizes the accumulation buffers. */ @Initializable.assert_initialized() update(): void { if (!this._texture || !this._texture.valid) { log(LogLevel.Warning, `valid texture for accumulation update expected, given ${this._texture}`); return; } if (this._passThrough) { return; } const sizeAltered = this._altered.texture || this._accumulationTextures[0].width !== this._texture.width || this._accumulationTextures[0].height !== this._texture.height; if (!this._altered.any && !sizeAltered) { assert(this._accumulationFBOs[0].valid && this._accumulationFBOs[1].valid, `valid accumulation framebuffers expected`); return; } const gl = this._context.gl; const gl2facade = this._context.gl2facade; /* Create and initialize accumulation texture and FBOs. */ const textureSize = this._texture.size; if (!this._accumulationTextures[0].initialized) { const internalFormat = Wizard.queryInternalTextureFormat(this._context, gl.RGBA, this._precision); this._accumulationTextures[0].initialize(textureSize[0], textureSize[1], internalFormat[0], gl.RGBA, internalFormat[1]); this._accumulationTextures[1].initialize(textureSize[0], textureSize[1], internalFormat[0], gl.RGBA, internalFormat[1]); } else { if (this._altered.texture || sizeAltered) { this._accumulationTextures[0].resize(this._texture.width, this._texture.height); this._accumulationTextures[1].resize(this._texture.width, this._texture.height); } if (this._altered.precision) { const internalFormat = Wizard.queryInternalTextureFormat(this._context, gl.RGBA, this._precision); this._accumulationTextures[0].reformat(internalFormat[0], gl.RGBA, internalFormat[1]); this._accumulationTextures[1].reformat(internalFormat[0], gl.RGBA, internalFormat[1]); } } if (!this._accumulationFBOs[0].initialized) { this._accumulationFBOs[0].initialize([[gl2facade.COLOR_ATTACHMENT0, this._accumulationTextures[0]]]); this._accumulationFBOs[1].initialize([[gl2facade.COLOR_ATTACHMENT0, this._accumulationTextures[1]]]); } assert(this._accumulationFBOs[0].valid && this._accumulationFBOs[1].valid, `valid accumulation framebuffers expected`); this._altered.reset(); } /** * An accumulation frame binds the two accumulation textures (ping-pong framebuffer), one for read, the other for * write/accumulating into. A screen-aligned triangle is used to fill the viewport and mix the input texture with * the weight of 1 / (frameNumber + 1) with the previous accumulation result. If no texture is specified, pass * through is used. * @param frameNumber - Frame number used to select the current read and write framebuffer as well as frame weight. * @param viewport - If specified, the viewport for accumulation will be set to the given width and height. If not, * the currently set viewport is used. */ @Initializable.assert_initialized() frame(frameNumber: number, viewport?: GLsizei2): void { assert(this._accumulationFBOs[0].valid && this._accumulationFBOs[1].valid, `valid framebuffer objects for accumulation expected (initialize or update was probably not called)`); if (this._passThrough || this._texture === undefined) { return; } logIf(!this._texture || !this._texture.valid, LogLevel.Warning, `valid texture for accumulation frame expected, given ${this._texture}`); const gl = this._context.gl; if (viewport !== undefined) { gl.viewport(0, 0, viewport[0], viewport[1]); } const readIndex = frameNumber % 2; const writeIndex = this._write = 1 - readIndex; const accumTexture = this._accumulationTextures[readIndex]; const frameTexture = this._texture; accumTexture.bind(gl.TEXTURE0); frameTexture.bind(gl.TEXTURE1); this._program.bind(); gl.uniform1f(this._uWeight, 1.0 / (frameNumber + 1)); this._accumulationFBOs[writeIndex].bind(gl.DRAW_FRAMEBUFFER); // bind draw only does not work for IE and EDGE this._ndcTriangle.bind(); this._ndcTriangle.draw(); this._ndcTriangle.unbind(); this._accumulationFBOs[writeIndex].unbind(gl.DRAW_FRAMEBUFFER); /** Every pass is expected to bind its own program when drawing, thus, unbinding is not necessary. */ // this.program.unbind(); accumTexture.unbind(gl.TEXTURE0); frameTexture.unbind(gl.TEXTURE1); } /** * Sets the texture that is to be accumulated. The ping and pong render textures will be resized on next frame * automatically if the texture size changed. * @param texture - Framebuffer that is to be accumulated. */ set texture(texture: Texture2D) { this.assertInitialized(); if (this._texture !== texture) { this._texture = texture; this._altered.alter('texture'); } } /** * Allows to specify the accumulation precision. */ set precision(precision: Wizard.Precision) { this.assertInitialized(); if (this._precision !== precision) { this._precision = precision; this._altered.alter('precision'); } } /** * Allows to skip accumulation. If pass through is enabled, nothing will be rendered on frame at all and the * ping pong render textures will be reduced to a minimum size of [1, 1] until pass through is disabled. */ set passThrough(passThrough: boolean) { this.assertInitialized(); if (this._passThrough === passThrough) { return; } if (this._passThrough && this._accumulationTextures[0].initialized) { this._accumulationTextures[0].uninitialize(); this._accumulationTextures[1].uninitialize(); } if (this._passThrough && this._accumulationFBOs[0].initialized) { this._accumulationFBOs[0].uninitialize(); this._accumulationFBOs[1].uninitialize(); } this._passThrough = passThrough; this._altered.alter('passThrough'); } /** * Returns the framebuffer last accumulated into. Note: the accumulation buffer is represented by two framebuffers * swapped for read and write every frame. The accumulation result is in the first color attachment. * @returns - The rgba framebuffer last accumulated into. */ get framebuffer(): Framebuffer | undefined { return this._passThrough ? undefined : this._accumulationFBOs[this._write]; } }
the_stack
import { utilities, negative } from './utilities'; import { flatColors } from './index'; import type { Attr, Completion } from '../interfaces'; import type { Processor } from 'windicss/lib'; import type { colorObject } from 'windicss/types/interfaces'; export function generateCompletions(processor: Processor, colors: colorObject, attributify = true, prefix = '') { const completions: Completion = { static: [], color: [], bracket: [], dynamic: [], attr: { static: {}, color: {}, bracket: {}, dynamic: {}, }, }; const staticUtilities = processor.resolveStaticUtilities(true); // generate normal utilities completions for (const [config, list] of Object.entries({ ...utilities, ...processor._plugin.completions })) { for (const utility of list) { const bracket = utility.indexOf('['); if (bracket !== -1) { completions.bracket.push(utility); continue; } const mark = utility.indexOf('{'); if (mark === -1) { completions.static.push(utility); } else { const key = prefix + utility.slice(0, mark - 1); const suffix = utility.slice(mark); switch (suffix) { case '{static}': for (const i of Object.keys(processor.theme(config, {}) as any)) { if (i === 'DEFAULT' && key === 'animate') continue; // animate not an available utility completions.static.push(i === 'DEFAULT' ? key : i.charAt(0) === '-' ? `-${key}${i}` : `${key}-${i}`); } break; case '{color}': for (const [k, v] of Object.entries(flatColors(processor.theme(config, colors) as colorObject))) { if (k === 'DEFAULT') continue; completions.color.push({ label: `${key}-${k}`, doc: v, }); } break; default: completions.dynamic.push({ label: prefix + utility, pos: utility.length - mark, }); if (config in negative) { completions.dynamic.push({ label: prefix + `-${utility}`, pos: utility.length + 1 - mark, }); } break; } } } } // generate attributify completions const attr: Attr = { static: {}, color: {}, bracket: {}, dynamic: {} }; if (attributify) { const attrDisable = processor.config('attributify.disable') as string[] | undefined; const addAttr = (key: string, value: any, type: 'static' | 'color' | 'bracket' | 'dynamic' = 'static') => { if (attrDisable && attrDisable.includes(key)) return; key in attr[type] ? attr[type][key].push(value) : attr[type][key] = [ value ]; }; addAttr('flex', '~'); addAttr('flex', 'inline'); addAttr('grid', '~'); addAttr('grid', 'inline'); addAttr('gradient', 'none'); addAttr('underline', '~'); addAttr('underline', 'line-through'); addAttr('underline', 'none'); addAttr('filter', '~'); addAttr('filter', 'none'); addAttr('backdrop', '~'); addAttr('backdrop', 'none'); for (const [key, style] of Object.entries(staticUtilities)) { if (!style[0]) continue; switch (style[0].meta.group) { case 'fontStyle': case 'fontSmoothing': case 'fontVariantNumeric': addAttr('font', key); break; case 'textAlign': addAttr('text', key.slice(5)); // text- break; case 'verticalAlign': addAttr('text', key.slice(6)); // align- break; case 'textDecoration': addAttr('text', key); break; case 'textTransform': case 'textOverflow': case 'wordBreak': case 'writingMode': case 'writingOrientation': case 'hyphens': addAttr('text', key); break; case 'whitespace': addAttr('text', key.slice(5)); // whitespace -> space break; case 'listStylePosition': addAttr('list', key.slice(5)); // list- break; case 'backgroundAttachment': case 'backgroundRepeat': case 'backgroundClip': case 'backgroundOrigin': case 'backgroundBlendMode': addAttr('bg', key.slice(3)); // bg- break; case 'borderStyle': addAttr('border', key.slice(7)); // border- addAttr('divide', key.slice(7)); // border- break; case 'borderCollapse': addAttr('border', key.slice(7)); // border- break; case 'strokeDashArray': case 'strokeDashOffset': case 'stroke': addAttr('icon', key); break; case 'flexWrap': case 'flexDirection': addAttr('flex', key.slice(5)); // flex- break; case 'gridAutoFlow': addAttr('grid', key.slice(5)); // grid- break; case 'display': if (key.startsWith('table') || key === 'inline-table') { addAttr('table', key.replace(/-?table-?/, '') || '~'); } else { addAttr('display', key); } break; case 'position': case 'float': case 'clear': addAttr('pos', key); break; case 'isolation': addAttr('pos', key); addAttr('isolation', key.replace('isolation-', '')); break; case 'visibility': case 'backfaceVisibility': addAttr('display', key); break; case 'tableLayout': addAttr('table', key.slice(6)); // table- break; case 'captionSide': case 'emptyCells': addAttr('table', key); break; case 'alignContent': case 'alignItems': case 'alignSelf': addAttr('align', key); break; case 'justifyContent': case 'justifyItems': case 'justifySelf': case 'placeContent': case 'placeItems': case 'placeSelf': case 'userSelect': case 'resize': case 'overflow': case 'appearance': case 'textDecorationStyle': case 'overscrollBehavior': const splits = split(key); if (!splits.key) break; addAttr(splits.key, splits.body); break; case 'boxDecorationBreak': addAttr('box', key); break; case 'boxSizing': addAttr('box', key.slice(4)); // box- break; case 'objectFit': addAttr('object', key.slice(7)); // object- break; case 'transform': if (key.startsWith('preserve')) { addAttr('transform', key); } else { addAttr('transform', key.slice(10) || '~'); // transform- } break; case 'perspectOrigin': addAttr('transform', key); break; case 'pointerEvents': addAttr('pointer', key.slice(15)); // pointer-events- break; case 'mixBlendMode': addAttr('blend', key.slice(10)); // mix-blend- break; case 'accessibility': addAttr('sr', key.replace(/sr-/, '')); break; case 'plugin': const [_, attr, value] = new RegExp(/(^[^-]+)-(.*)/).exec(key) || [] attr && addAttr(attr, value); break } } for (const utility of completions.static) { const { key, body } = split(utility); if (key) { if (key === 'underline') addAttr('text', utility); addAttr(key, body); } } for (const { label, doc } of completions.color) { const { key, body } = split(label); if (key) { addAttr(key, { label: body, doc }, 'color'); if (key === 'underline') addAttr('text', { label, doc }, 'color'); } } for (const utility of completions.bracket) { const { key, body } = split(utility); if (key) addAttr(key, body, 'bracket'); } for (const { label, pos } of completions.dynamic) { const { key, body } = split(label); if (key) addAttr(key, { label: body, pos }, 'dynamic'); } } completions.static.push(...Object.keys(staticUtilities).map((key) => prefix + key)); completions.attr = attr; return completions; } function split(utility: string) { if (utility.startsWith('bg-gradient')) return { key: 'gradient', body: utility.replace(/^bg-gradient-/, '') }; if (utility === 'w-min') return { key: 'w', body: 'min-content' }; if (utility === 'w-max') return { key: 'w', body: 'max-content' }; if (utility === 'h-min') return { key: 'h', body: 'min-content' }; if (utility === 'h-max') return { key: 'h', body: 'max-content' }; if (utility.startsWith('min-w')) return { key: 'w', body: utility.replace(/^min-w-/, 'min-') }; if (utility.startsWith('max-w')) return { key: 'w', body: utility.replace(/^max-w-/, 'max-') }; if (utility.startsWith('min-h')) return { key: 'h', body: utility.replace(/^min-h-/, 'min-') }; if (utility.startsWith('max-h')) return { key: 'h', body: utility.replace(/^max-h-/, 'max-') }; const key = utility.match(/[^-]+/)?.[0]; if (key) { if (['duration', 'ease', 'delay'].includes(key)) return { key: 'transition', body: utility }; if (['scale', 'rotate', 'translate', 'skew', 'origin', 'perspect'].includes(key)) return { key: 'transform', body: utility }; if (['blur', 'brightness', 'contrast', 'drop', 'grayscale', 'hue', 'invert', 'saturate', 'sepia'].includes(key)) return { key: 'filter', body: utility }; if (['inset', 'top', 'left', 'bottom', 'right'].includes(key)) return { key: 'pos', body: utility }; if (['py', 'px', 'pt', 'pl', 'pb', 'pr'].includes(key)) return { key: 'p', body: utility.slice(1,) }; if (['my', 'mx', 'mt', 'ml', 'mb', 'mr'].includes(key)) return { key: 'm', body: utility.charAt(0) === '-' ? '-' + utility.slice(2,): utility.slice(1,) }; if (['stroke', 'fill'].includes(key)) return { key: 'icon', body: utility }; if (['from', 'via', 'to'].includes(key)) return { key: 'gradient', body: utility }; if (['tracking', 'leading'].includes(key)) return { key: 'font', body: utility }; if (['tab', 'indent'].includes(key)) return { key: 'text', body: utility }; if (['col', 'row', 'auto', 'gap'].includes(key)) return { key: 'grid', body: utility }; if (key === 'placeholder') return { key: 'text', body: utility }; if (key === 'rounded') return { key: 'border', body: utility }; } const negative = utility.charAt(0) === '-'; const body = (negative ? utility.slice(1,): utility).match(/-.+/)?.[0].slice(1) || '~'; return { key, body: negative ? '-' + body : body }; }
the_stack
import { concat as observableConcat, defer as observableDefer, interval as observableInterval, mapTo, merge as observableMerge, Observable, of as observableOf, startWith, Subject, switchMapTo, takeUntil, } from "rxjs"; import { events, onHeightWidthChange, } from "../../../../../compat"; import config from "../../../../../config"; import log from "../../../../../log"; import { ITextTrackSegmentData } from "../../../../../transports"; import { IEndOfSegmentInfos, IPushChunkInfos, SegmentBuffer, } from "../../types"; import ManualTimeRanges from "../../utils/manual_time_ranges"; import parseTextTrackToElements from "./parsers"; import TextTrackCuesStore from "./text_track_cues_store"; import updateProportionalElements from "./update_proportional_elements"; const { onEnded$, onSeeked$, onSeeking$ } = events; const { MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL, TEXT_TRACK_SIZE_CHECKS_INTERVAL } = config; /** * Generate the clock at which TextTrack HTML Cues should be refreshed. * @param {HTMLMediaElement} videoElement * @returns {Observable} */ function generateClock(videoElement : HTMLMediaElement) : Observable<boolean> { const seeking$ = onSeeking$(videoElement); const seeked$ = onSeeked$(videoElement); const ended$ = onEnded$(videoElement); const manualRefresh$ = observableMerge(seeked$, ended$); const autoRefresh$ = observableInterval(MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL) .pipe(startWith(null)); return manualRefresh$.pipe( startWith(null), switchMapTo(observableConcat(autoRefresh$.pipe(mapTo(true), takeUntil(seeking$)), observableOf(false)))); } /** * @param {Element} element * @param {Element} child */ function safelyRemoveChild(element : Element, child : Element) { try { element.removeChild(child); } catch (_error) { log.warn("HTSB: Can't remove text track: not in the element."); } } /** * @param {HTMLElement} element * @returns {Object|null} */ function getElementResolution( element : HTMLElement ) : { rows : number; columns : number } | null { const strRows = element.getAttribute("data-resolution-rows"); const strColumns = element.getAttribute("data-resolution-columns"); if (strRows === null || strColumns === null) { return null; } const rows = parseInt(strRows, 10); const columns = parseInt(strColumns, 10); if (rows === null || columns === null) { return null; } return { rows, columns }; } /** * SegmentBuffer implementation which display buffered TextTracks in the given * HTML element. * @class HTMLTextSegmentBuffer */ export default class HTMLTextSegmentBuffer extends SegmentBuffer { readonly bufferType : "text"; /** * The video element the cues refer to. * Used to know when the user is seeking, for example. */ private readonly _videoElement : HTMLMediaElement; /** * When "nexting" that subject, every Observable declared here will be * unsubscribed. * Used for clean-up */ private readonly _destroy$ : Subject<void>; /** HTMLElement which will contain the cues */ private readonly _textTrackElement : HTMLElement; /** Buffer containing the data */ private readonly _buffer : TextTrackCuesStore; /** * We could need us to automatically update styling depending on * `_textTrackElement`'s size. This Subject allows to stop that * regular check. */ private _clearSizeUpdates$ : Subject<void>; /** Information on cues currently displayed. */ private _currentCues : Array<{ /** The HTMLElement containing the cues, appended to `_textTrackElement`. */ element : HTMLElement; /** * Announced resolution for this element. * Necessary to properly render proportional sizes. */ resolution : { columns : number; rows : number; } | null; }>; private _buffered : ManualTimeRanges; /** * @param {HTMLMediaElement} videoElement * @param {HTMLElement} textTrackElement */ constructor( videoElement : HTMLMediaElement, textTrackElement : HTMLElement ) { log.debug("HTSB: Creating HTMLTextSegmentBuffer"); super(); this.bufferType = "text"; this._buffered = new ManualTimeRanges(); this._videoElement = videoElement; this._textTrackElement = textTrackElement; this._clearSizeUpdates$ = new Subject(); this._destroy$ = new Subject(); this._buffer = new TextTrackCuesStore(); this._currentCues = []; // update text tracks generateClock(this._videoElement) .pipe(takeUntil(this._destroy$)) .subscribe((shouldDisplay) => { if (!shouldDisplay) { this._disableCurrentCues(); return; } // to spread the time error, we divide the regular chosen interval. const time = Math.max(this._videoElement.currentTime + (MAXIMUM_HTML_TEXT_TRACK_UPDATE_INTERVAL / 1000) / 2, 0); const cues = this._buffer.get(time); if (cues.length === 0) { this._disableCurrentCues(); } else { this._displayCues(cues); } }); } /** * Push segment on Subscription. * @param {Object} infos * @returns {Observable} */ public pushChunk(infos : IPushChunkInfos<unknown>) : Observable<void> { return observableDefer(() => { this.pushChunkSync(infos); return observableOf(undefined); }); } /** * Remove buffered data. * @param {number} start - start position, in seconds * @param {number} end - end position, in seconds * @returns {Observable} */ public removeBuffer(start : number, end : number) : Observable<void> { return observableDefer(() => { this.removeBufferSync(start, end); return observableOf(undefined); }); } /** * Indicate that every chunks from a Segment has been given to pushChunk so * far. * This will update our internal Segment inventory accordingly. * The returned Observable will emit and complete successively once the whole * segment has been pushed and this indication is acknowledged. * @param {Object} infos * @returns {Observable} */ public endOfSegment(_infos : IEndOfSegmentInfos) : Observable<void> { return observableDefer(() => { this._segmentInventory.completeSegment(_infos, this._buffered); return observableOf(undefined); }); } /** * Returns the currently buffered data, in a TimeRanges object. * @returns {TimeRanges} */ public getBufferedRanges() : ManualTimeRanges { return this._buffered; } public dispose() : void { log.debug("HTSB: Disposing HTMLTextSegmentBuffer"); this._disableCurrentCues(); this._buffer.remove(0, Infinity); this._buffered.remove(0, Infinity); this._destroy$.next(); this._destroy$.complete(); } /** * Push the text track contained in `data` to the HTMLTextSegmentBuffer * synchronously. * Returns a boolean: * - `true` if text tracks have been added the the HTMLTextSegmentBuffer's * buffer after that segment has been added. * - `false` if no text tracks have been added the the * HTMLTextSegmentBuffer's buffer (e.g. empty text-track, incoherent times * etc.) * * /!\ This method won't add any data to the linked inventory. * Please use the `pushChunk` method for most use-cases. * @param {Object} data * @returns {boolean} */ public pushChunkSync(infos : IPushChunkInfos<unknown>) : void { log.debug("HTSB: Appending new html text tracks"); const { timestampOffset, appendWindow, chunk } = infos.data; if (chunk === null) { return; } assertChunkIsTextTrackSegmentData(chunk); const { start: startTime, end: endTime, data: dataString, type, language } = chunk; const appendWindowStart = appendWindow[0] ?? 0; const appendWindowEnd = appendWindow[1] ?? Infinity; const cues = parseTextTrackToElements(type, dataString, timestampOffset, language); if (appendWindowStart !== 0 && appendWindowEnd !== Infinity) { // Removing before window start let i = 0; while (i < cues.length && cues[i].end <= appendWindowStart) { i++; } cues.splice(0, i); i = 0; while (i < cues.length && cues[i].start < appendWindowStart) { cues[i].start = appendWindowStart; i++; } // Removing after window end i = cues.length - 1; while (i >= 0 && cues[i].start >= appendWindowEnd) { i--; } cues.splice(i, cues.length); i = cues.length - 1; while (i >= 0 && cues[i].end > appendWindowEnd) { cues[i].end = appendWindowEnd; i--; } } let start : number; if (startTime !== undefined) { start = Math.max(appendWindowStart, startTime); } else { if (cues.length <= 0) { log.warn("HTSB: Current text tracks have no cues nor start time. Aborting"); return ; } log.warn("HTSB: No start time given. Guessing from cues."); start = cues[0].start; } let end : number; if (endTime !== undefined) { end = Math.min(appendWindowEnd, endTime); } else { if (cues.length <= 0) { log.warn("HTSB: Current text tracks have no cues nor end time. Aborting"); return ; } log.warn("HTSB: No end time given. Guessing from cues."); end = cues[cues.length - 1].end; } if (end <= start) { log.warn("HTSB: Invalid text track appended: ", "the start time is inferior or equal to the end time."); return ; } if (infos.inventoryInfos !== null) { this._segmentInventory.insertChunk(infos.inventoryInfos); } this._buffer.insert(cues, start, end); this._buffered.insert(start, end); } /** * Remove buffer data between the given start and end, synchronously. * @param {number} start * @param {number} end */ public removeBufferSync( start : number, end : number ) : void { log.debug("HTSB: Removing html text track data", start, end); this._buffer.remove(start, end); this._buffered.remove(start, end); } /** * Remove the current cue from being displayed. */ private _disableCurrentCues() : void { this._clearSizeUpdates$.next(); if (this._currentCues.length > 0) { for (let i = 0; i < this._currentCues.length; i++) { safelyRemoveChild(this._textTrackElement, this._currentCues[i].element); } this._currentCues = []; } } /** * Display a new Cue. If one was already present, it will be replaced. * @param {HTMLElement} element */ private _displayCues(elements : HTMLElement[]) : void { const nothingChanged = this._currentCues.length === elements.length && this._currentCues.every((current, index) => current.element === elements[index]); if (nothingChanged) { return; } // Remove and re-display everything // TODO More intelligent handling this._clearSizeUpdates$.next(); for (let i = 0; i < this._currentCues.length; i++) { safelyRemoveChild(this._textTrackElement, this._currentCues[i].element); } this._currentCues = []; for (let i = 0; i < elements.length; i++) { const element = elements[i]; const resolution = getElementResolution(element); this._currentCues.push({ element, resolution }); this._textTrackElement.appendChild(element); } const proportionalCues = this._currentCues .filter((cue) : cue is { resolution: { rows : number; columns : number; }; element : HTMLElement; } => cue.resolution !== null); if (proportionalCues.length > 0) { // update propertionally-sized elements periodically onHeightWidthChange(this._textTrackElement, TEXT_TRACK_SIZE_CHECKS_INTERVAL) .pipe(takeUntil(this._clearSizeUpdates$), takeUntil(this._destroy$)) .subscribe(({ height, width }) => { for (let i = 0; i < proportionalCues.length; i++) { const { resolution, element } = proportionalCues[i]; updateProportionalElements(height, width, resolution, element); } }); } } } /** Data of chunks that should be pushed to the NativeTextSegmentBuffer. */ export interface INativeTextTracksBufferSegmentData { /** The text track data, in the format indicated in `type`. */ data : string; /** The format of `data` (examples: "ttml", "srt" or "vtt") */ type : string; /** * Language in which the text track is, as a language code. * This is mostly needed for "sami" subtitles, to know which cues can / should * be parsed. */ language? : string; /** start time from which the segment apply, in seconds. */ start? : number; /** end time until which the segment apply, in seconds. */ end? : number; } /** * Throw if the given input is not in the expected format. * Allows to enforce runtime type-checking as compile-time type-checking here is * difficult to enforce. * @param {Object} chunk */ function assertChunkIsTextTrackSegmentData( chunk : unknown ) : asserts chunk is INativeTextTracksBufferSegmentData { if (!__DEV__) { return; } if ( typeof chunk !== "object" || chunk === null || typeof (chunk as INativeTextTracksBufferSegmentData).data !== "string" || typeof (chunk as INativeTextTracksBufferSegmentData).type !== "string" || ( (chunk as INativeTextTracksBufferSegmentData).language !== undefined && typeof (chunk as INativeTextTracksBufferSegmentData).language !== "string" ) || ( (chunk as INativeTextTracksBufferSegmentData).start !== undefined && typeof (chunk as INativeTextTracksBufferSegmentData).start !== "number" ) || ( (chunk as INativeTextTracksBufferSegmentData).end !== undefined && typeof (chunk as INativeTextTracksBufferSegmentData).end !== "number" ) ) { throw new Error("Invalid format given to a NativeTextSegmentBuffer"); } } /* * The following ugly code is here to provide a compile-time check that an * `INativeTextTracksBufferSegmentData` (type of data pushed to a * `NativeTextSegmentBuffer`) can be derived from a `ITextTrackSegmentData` * (text track data parsed from a segment). * * It doesn't correspond at all to real code that will be called. This is just * a hack to tell TypeScript to perform that check. */ if (__DEV__) { /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/ban-ts-comment */ // @ts-ignore function _checkType( input : ITextTrackSegmentData ) : void { function checkEqual(_arg : INativeTextTracksBufferSegmentData) : void { /* nothing */ } checkEqual(input); } /* eslint-enable @typescript-eslint/no-unused-vars */ /* eslint-enable @typescript-eslint/ban-ts-comment */ }
the_stack
import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql' export type Maybe<T> = T | null export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] } export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> } export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> } export type RequireFields<T, K extends keyof T> = { [X in Exclude<keyof T, K>]?: T[X] } & { [P in K]-?: NonNullable<T[P]> } /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string String: string Boolean: boolean Int: number Float: number DateTime: Date Json: unknown } export type ExecutedMigration = { readonly __typename?: 'ExecutedMigration' readonly version: Scalars['String'] readonly name: Scalars['String'] readonly executedAt: Scalars['DateTime'] readonly checksum: Scalars['String'] readonly formatVersion: Scalars['Int'] readonly modifications: ReadonlyArray<Scalars['Json']> } export type HistoryCreateEvent = HistoryEvent & { readonly __typename?: 'HistoryCreateEvent' readonly id: Scalars['String'] readonly transactionId: Scalars['String'] readonly identityId: Scalars['String'] readonly identityDescription: Scalars['String'] readonly description: Scalars['String'] readonly createdAt: Scalars['DateTime'] readonly type: HistoryEventType readonly tableName: Scalars['String'] readonly primaryKeys: ReadonlyArray<Scalars['String']> readonly newValues: Scalars['Json'] } export type HistoryDeleteEvent = HistoryEvent & { readonly __typename?: 'HistoryDeleteEvent' readonly id: Scalars['String'] readonly transactionId: Scalars['String'] readonly identityId: Scalars['String'] readonly identityDescription: Scalars['String'] readonly description: Scalars['String'] readonly createdAt: Scalars['DateTime'] readonly type: HistoryEventType readonly tableName: Scalars['String'] readonly primaryKeys: ReadonlyArray<Scalars['String']> readonly oldValues: Scalars['Json'] } export type HistoryError = { readonly __typename?: 'HistoryError' readonly code: HistoryErrorCode readonly developerMessage: Scalars['String'] } export enum HistoryErrorCode { StageNotFound = 'STAGE_NOT_FOUND' } export type HistoryEvent = { readonly id: Scalars['String'] readonly transactionId: Scalars['String'] readonly identityDescription: Scalars['String'] readonly identityId: Scalars['String'] readonly description: Scalars['String'] readonly createdAt: Scalars['DateTime'] readonly type: HistoryEventType } export enum HistoryEventType { Update = 'UPDATE', Delete = 'DELETE', Create = 'CREATE', RunMigration = 'RUN_MIGRATION' } export type HistoryFilter = { readonly entity: Scalars['String'] readonly id: Scalars['String'] } export type HistoryResponse = { readonly __typename?: 'HistoryResponse' readonly ok?: Maybe<Scalars['Boolean']> /** @deprecated Field no longer supported */ readonly errors: ReadonlyArray<HistoryErrorCode> readonly error?: Maybe<HistoryError> readonly result?: Maybe<HistoryResult> } export type HistoryResult = { readonly __typename?: 'HistoryResult' readonly events: ReadonlyArray<HistoryEvent> } export type HistoryRunMigrationEvent = HistoryEvent & { readonly __typename?: 'HistoryRunMigrationEvent' readonly id: Scalars['String'] readonly transactionId: Scalars['String'] readonly identityId: Scalars['String'] readonly identityDescription: Scalars['String'] readonly description: Scalars['String'] readonly createdAt: Scalars['DateTime'] readonly type: HistoryEventType } export type HistoryUpdateEvent = HistoryEvent & { readonly __typename?: 'HistoryUpdateEvent' readonly id: Scalars['String'] readonly transactionId: Scalars['String'] readonly identityId: Scalars['String'] readonly identityDescription: Scalars['String'] readonly description: Scalars['String'] readonly createdAt: Scalars['DateTime'] readonly type: HistoryEventType readonly tableName: Scalars['String'] readonly primaryKeys: ReadonlyArray<Scalars['String']> readonly oldValues: Scalars['Json'] readonly diffValues: Scalars['Json'] } export type MigrateError = { readonly __typename?: 'MigrateError' readonly code: MigrateErrorCode readonly migration: Scalars['String'] readonly developerMessage: Scalars['String'] } export enum MigrateErrorCode { MustFollowLatest = 'MUST_FOLLOW_LATEST', AlreadyExecuted = 'ALREADY_EXECUTED', InvalidFormat = 'INVALID_FORMAT', InvalidSchema = 'INVALID_SCHEMA', MigrationFailed = 'MIGRATION_FAILED' } export type MigrateResponse = { readonly __typename?: 'MigrateResponse' readonly ok: Scalars['Boolean'] /** @deprecated Field no longer supported */ readonly errors: ReadonlyArray<MigrateError> readonly error?: Maybe<MigrateError> readonly result?: Maybe<MigrateResult> } export type MigrateResult = { readonly __typename?: 'MigrateResult' readonly message: Scalars['String'] } export type Migration = { readonly version: Scalars['String'] readonly name: Scalars['String'] readonly formatVersion: Scalars['Int'] readonly modifications: ReadonlyArray<Scalars['Json']> } export type MigrationDeleteError = { readonly __typename?: 'MigrationDeleteError' readonly code: MigrationDeleteErrorCode readonly developerMessage: Scalars['String'] } export enum MigrationDeleteErrorCode { NotFound = 'NOT_FOUND', InvalidFormat = 'INVALID_FORMAT' } export type MigrationDeleteResponse = { readonly __typename?: 'MigrationDeleteResponse' readonly ok: Scalars['Boolean'] readonly error?: Maybe<MigrationDeleteError> } export type MigrationModification = { readonly version?: Maybe<Scalars['String']> readonly name?: Maybe<Scalars['String']> readonly formatVersion?: Maybe<Scalars['Int']> readonly modifications?: Maybe<ReadonlyArray<Scalars['Json']>> } export type MigrationModifyError = { readonly __typename?: 'MigrationModifyError' readonly code: MigrationModifyErrorCode readonly developerMessage: Scalars['String'] } export enum MigrationModifyErrorCode { NotFound = 'NOT_FOUND' } export type MigrationModifyResponse = { readonly __typename?: 'MigrationModifyResponse' readonly ok: Scalars['Boolean'] readonly error?: Maybe<MigrationModifyError> } export type Mutation = { readonly __typename?: 'Mutation' readonly forceMigrate: MigrateResponse readonly migrate: MigrateResponse readonly migrationDelete: MigrationDeleteResponse readonly migrationModify: MigrationModifyResponse readonly truncate: TruncateResponse } export type MutationForceMigrateArgs = { migrations: ReadonlyArray<Migration> } export type MutationMigrateArgs = { migrations: ReadonlyArray<Migration> } export type MutationMigrationDeleteArgs = { migration: Scalars['String'] } export type MutationMigrationModifyArgs = { migration: Scalars['String'] modification: MigrationModification } export type Query = { readonly __typename?: 'Query' readonly stages: ReadonlyArray<Stage> readonly executedMigrations: ReadonlyArray<ExecutedMigration> readonly history: HistoryResponse } export type QueryExecutedMigrationsArgs = { version?: Maybe<Scalars['String']> } export type QueryHistoryArgs = { stage: Scalars['String'] filter?: Maybe<ReadonlyArray<HistoryFilter>> sinceEvent?: Maybe<Scalars['String']> sinceTime?: Maybe<Scalars['DateTime']> } export type Stage = { readonly __typename?: 'Stage' readonly id: Scalars['String'] readonly name: Scalars['String'] readonly slug: Scalars['String'] } export type TruncateResponse = { readonly __typename?: 'TruncateResponse' readonly ok: Scalars['Boolean'] } export type ResolverTypeWrapper<T> = Promise<T> | T export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = { fragment: string resolve: ResolverFn<TResult, TParent, TContext, TArgs> } export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = { selectionSet: string resolve: ResolverFn<TResult, TParent, TContext, TArgs> } export type StitchingResolver<TResult, TParent, TContext, TArgs> = LegacyStitchingResolver<TResult, TParent, TContext, TArgs> | NewStitchingResolver<TResult, TParent, TContext, TArgs> export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> = | ResolverFn<TResult, TParent, TContext, TArgs> | StitchingResolver<TResult, TParent, TContext, TArgs> export type ResolverFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => Promise<TResult> | TResult export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>> export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = ( parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult> export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs> resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs> } export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> { subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs> resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs> } export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> = | SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs> | SubscriptionResolverObject<TResult, TParent, TContext, TArgs> export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> = | ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>) | SubscriptionObject<TResult, TKey, TParent, TContext, TArgs> export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = ( parent: TParent, context: TContext, info: GraphQLResolveInfo ) => Maybe<TTypes> | Promise<Maybe<TTypes>> export type IsTypeOfResolverFn<T = {}, TContext = {}> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean> export type NextResolverFn<T> = () => Promise<T> export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = ( next: NextResolverFn<TResult>, parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo ) => TResult | Promise<TResult> /** Mapping between all available schema types and the resolvers types */ export type ResolversTypes = { DateTime: ResolverTypeWrapper<Scalars['DateTime']> ExecutedMigration: ResolverTypeWrapper<ExecutedMigration> String: ResolverTypeWrapper<Scalars['String']> Int: ResolverTypeWrapper<Scalars['Int']> HistoryCreateEvent: ResolverTypeWrapper<HistoryCreateEvent> HistoryDeleteEvent: ResolverTypeWrapper<HistoryDeleteEvent> HistoryError: ResolverTypeWrapper<HistoryError> HistoryErrorCode: HistoryErrorCode HistoryEvent: ResolversTypes['HistoryCreateEvent'] | ResolversTypes['HistoryDeleteEvent'] | ResolversTypes['HistoryRunMigrationEvent'] | ResolversTypes['HistoryUpdateEvent'] HistoryEventType: HistoryEventType HistoryFilter: HistoryFilter HistoryResponse: ResolverTypeWrapper<HistoryResponse> Boolean: ResolverTypeWrapper<Scalars['Boolean']> HistoryResult: ResolverTypeWrapper<HistoryResult> HistoryRunMigrationEvent: ResolverTypeWrapper<HistoryRunMigrationEvent> HistoryUpdateEvent: ResolverTypeWrapper<HistoryUpdateEvent> Json: ResolverTypeWrapper<Scalars['Json']> MigrateError: ResolverTypeWrapper<MigrateError> MigrateErrorCode: MigrateErrorCode MigrateResponse: ResolverTypeWrapper<MigrateResponse> MigrateResult: ResolverTypeWrapper<MigrateResult> Migration: Migration MigrationDeleteError: ResolverTypeWrapper<MigrationDeleteError> MigrationDeleteErrorCode: MigrationDeleteErrorCode MigrationDeleteResponse: ResolverTypeWrapper<MigrationDeleteResponse> MigrationModification: MigrationModification MigrationModifyError: ResolverTypeWrapper<MigrationModifyError> MigrationModifyErrorCode: MigrationModifyErrorCode MigrationModifyResponse: ResolverTypeWrapper<MigrationModifyResponse> Mutation: ResolverTypeWrapper<{}> Query: ResolverTypeWrapper<{}> Stage: ResolverTypeWrapper<Stage> TruncateResponse: ResolverTypeWrapper<TruncateResponse> } /** Mapping between all available schema types and the resolvers parents */ export type ResolversParentTypes = { DateTime: Scalars['DateTime'] ExecutedMigration: ExecutedMigration String: Scalars['String'] Int: Scalars['Int'] HistoryCreateEvent: HistoryCreateEvent HistoryDeleteEvent: HistoryDeleteEvent HistoryError: HistoryError HistoryEvent: ResolversParentTypes['HistoryCreateEvent'] | ResolversParentTypes['HistoryDeleteEvent'] | ResolversParentTypes['HistoryRunMigrationEvent'] | ResolversParentTypes['HistoryUpdateEvent'] HistoryFilter: HistoryFilter HistoryResponse: HistoryResponse Boolean: Scalars['Boolean'] HistoryResult: HistoryResult HistoryRunMigrationEvent: HistoryRunMigrationEvent HistoryUpdateEvent: HistoryUpdateEvent Json: Scalars['Json'] MigrateError: MigrateError MigrateResponse: MigrateResponse MigrateResult: MigrateResult Migration: Migration MigrationDeleteError: MigrationDeleteError MigrationDeleteResponse: MigrationDeleteResponse MigrationModification: MigrationModification MigrationModifyError: MigrationModifyError MigrationModifyResponse: MigrationModifyResponse Mutation: {} Query: {} Stage: Stage TruncateResponse: TruncateResponse } export interface DateTimeScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['DateTime'], any> { name: 'DateTime' } export type ExecutedMigrationResolvers<ContextType = any, ParentType extends ResolversParentTypes['ExecutedMigration'] = ResolversParentTypes['ExecutedMigration']> = { version?: Resolver<ResolversTypes['String'], ParentType, ContextType> name?: Resolver<ResolversTypes['String'], ParentType, ContextType> executedAt?: Resolver<ResolversTypes['DateTime'], ParentType, ContextType> checksum?: Resolver<ResolversTypes['String'], ParentType, ContextType> formatVersion?: Resolver<ResolversTypes['Int'], ParentType, ContextType> modifications?: Resolver<ReadonlyArray<ResolversTypes['Json']>, ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type HistoryCreateEventResolvers<ContextType = any, ParentType extends ResolversParentTypes['HistoryCreateEvent'] = ResolversParentTypes['HistoryCreateEvent']> = { id?: Resolver<ResolversTypes['String'], ParentType, ContextType> transactionId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityDescription?: Resolver<ResolversTypes['String'], ParentType, ContextType> description?: Resolver<ResolversTypes['String'], ParentType, ContextType> createdAt?: Resolver<ResolversTypes['DateTime'], ParentType, ContextType> type?: Resolver<ResolversTypes['HistoryEventType'], ParentType, ContextType> tableName?: Resolver<ResolversTypes['String'], ParentType, ContextType> primaryKeys?: Resolver<ReadonlyArray<ResolversTypes['String']>, ParentType, ContextType> newValues?: Resolver<ResolversTypes['Json'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type HistoryDeleteEventResolvers<ContextType = any, ParentType extends ResolversParentTypes['HistoryDeleteEvent'] = ResolversParentTypes['HistoryDeleteEvent']> = { id?: Resolver<ResolversTypes['String'], ParentType, ContextType> transactionId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityDescription?: Resolver<ResolversTypes['String'], ParentType, ContextType> description?: Resolver<ResolversTypes['String'], ParentType, ContextType> createdAt?: Resolver<ResolversTypes['DateTime'], ParentType, ContextType> type?: Resolver<ResolversTypes['HistoryEventType'], ParentType, ContextType> tableName?: Resolver<ResolversTypes['String'], ParentType, ContextType> primaryKeys?: Resolver<ReadonlyArray<ResolversTypes['String']>, ParentType, ContextType> oldValues?: Resolver<ResolversTypes['Json'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type HistoryErrorResolvers<ContextType = any, ParentType extends ResolversParentTypes['HistoryError'] = ResolversParentTypes['HistoryError']> = { code?: Resolver<ResolversTypes['HistoryErrorCode'], ParentType, ContextType> developerMessage?: Resolver<ResolversTypes['String'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type HistoryEventResolvers<ContextType = any, ParentType extends ResolversParentTypes['HistoryEvent'] = ResolversParentTypes['HistoryEvent']> = { __resolveType: TypeResolveFn<'HistoryCreateEvent' | 'HistoryDeleteEvent' | 'HistoryRunMigrationEvent' | 'HistoryUpdateEvent', ParentType, ContextType> id?: Resolver<ResolversTypes['String'], ParentType, ContextType> transactionId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityDescription?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityId?: Resolver<ResolversTypes['String'], ParentType, ContextType> description?: Resolver<ResolversTypes['String'], ParentType, ContextType> createdAt?: Resolver<ResolversTypes['DateTime'], ParentType, ContextType> type?: Resolver<ResolversTypes['HistoryEventType'], ParentType, ContextType> } export type HistoryResponseResolvers<ContextType = any, ParentType extends ResolversParentTypes['HistoryResponse'] = ResolversParentTypes['HistoryResponse']> = { ok?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType> errors?: Resolver<ReadonlyArray<ResolversTypes['HistoryErrorCode']>, ParentType, ContextType> error?: Resolver<Maybe<ResolversTypes['HistoryError']>, ParentType, ContextType> result?: Resolver<Maybe<ResolversTypes['HistoryResult']>, ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type HistoryResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['HistoryResult'] = ResolversParentTypes['HistoryResult']> = { events?: Resolver<ReadonlyArray<ResolversTypes['HistoryEvent']>, ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type HistoryRunMigrationEventResolvers<ContextType = any, ParentType extends ResolversParentTypes['HistoryRunMigrationEvent'] = ResolversParentTypes['HistoryRunMigrationEvent']> = { id?: Resolver<ResolversTypes['String'], ParentType, ContextType> transactionId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityDescription?: Resolver<ResolversTypes['String'], ParentType, ContextType> description?: Resolver<ResolversTypes['String'], ParentType, ContextType> createdAt?: Resolver<ResolversTypes['DateTime'], ParentType, ContextType> type?: Resolver<ResolversTypes['HistoryEventType'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type HistoryUpdateEventResolvers<ContextType = any, ParentType extends ResolversParentTypes['HistoryUpdateEvent'] = ResolversParentTypes['HistoryUpdateEvent']> = { id?: Resolver<ResolversTypes['String'], ParentType, ContextType> transactionId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityId?: Resolver<ResolversTypes['String'], ParentType, ContextType> identityDescription?: Resolver<ResolversTypes['String'], ParentType, ContextType> description?: Resolver<ResolversTypes['String'], ParentType, ContextType> createdAt?: Resolver<ResolversTypes['DateTime'], ParentType, ContextType> type?: Resolver<ResolversTypes['HistoryEventType'], ParentType, ContextType> tableName?: Resolver<ResolversTypes['String'], ParentType, ContextType> primaryKeys?: Resolver<ReadonlyArray<ResolversTypes['String']>, ParentType, ContextType> oldValues?: Resolver<ResolversTypes['Json'], ParentType, ContextType> diffValues?: Resolver<ResolversTypes['Json'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export interface JsonScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['Json'], any> { name: 'Json' } export type MigrateErrorResolvers<ContextType = any, ParentType extends ResolversParentTypes['MigrateError'] = ResolversParentTypes['MigrateError']> = { code?: Resolver<ResolversTypes['MigrateErrorCode'], ParentType, ContextType> migration?: Resolver<ResolversTypes['String'], ParentType, ContextType> developerMessage?: Resolver<ResolversTypes['String'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type MigrateResponseResolvers<ContextType = any, ParentType extends ResolversParentTypes['MigrateResponse'] = ResolversParentTypes['MigrateResponse']> = { ok?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType> errors?: Resolver<ReadonlyArray<ResolversTypes['MigrateError']>, ParentType, ContextType> error?: Resolver<Maybe<ResolversTypes['MigrateError']>, ParentType, ContextType> result?: Resolver<Maybe<ResolversTypes['MigrateResult']>, ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type MigrateResultResolvers<ContextType = any, ParentType extends ResolversParentTypes['MigrateResult'] = ResolversParentTypes['MigrateResult']> = { message?: Resolver<ResolversTypes['String'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type MigrationDeleteErrorResolvers<ContextType = any, ParentType extends ResolversParentTypes['MigrationDeleteError'] = ResolversParentTypes['MigrationDeleteError']> = { code?: Resolver<ResolversTypes['MigrationDeleteErrorCode'], ParentType, ContextType> developerMessage?: Resolver<ResolversTypes['String'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type MigrationDeleteResponseResolvers<ContextType = any, ParentType extends ResolversParentTypes['MigrationDeleteResponse'] = ResolversParentTypes['MigrationDeleteResponse']> = { ok?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType> error?: Resolver<Maybe<ResolversTypes['MigrationDeleteError']>, ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type MigrationModifyErrorResolvers<ContextType = any, ParentType extends ResolversParentTypes['MigrationModifyError'] = ResolversParentTypes['MigrationModifyError']> = { code?: Resolver<ResolversTypes['MigrationModifyErrorCode'], ParentType, ContextType> developerMessage?: Resolver<ResolversTypes['String'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type MigrationModifyResponseResolvers<ContextType = any, ParentType extends ResolversParentTypes['MigrationModifyResponse'] = ResolversParentTypes['MigrationModifyResponse']> = { ok?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType> error?: Resolver<Maybe<ResolversTypes['MigrationModifyError']>, ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type MutationResolvers<ContextType = any, ParentType extends ResolversParentTypes['Mutation'] = ResolversParentTypes['Mutation']> = { forceMigrate?: Resolver<ResolversTypes['MigrateResponse'], ParentType, ContextType, RequireFields<MutationForceMigrateArgs, 'migrations'>> migrate?: Resolver<ResolversTypes['MigrateResponse'], ParentType, ContextType, RequireFields<MutationMigrateArgs, 'migrations'>> migrationDelete?: Resolver<ResolversTypes['MigrationDeleteResponse'], ParentType, ContextType, RequireFields<MutationMigrationDeleteArgs, 'migration'>> migrationModify?: Resolver<ResolversTypes['MigrationModifyResponse'], ParentType, ContextType, RequireFields<MutationMigrationModifyArgs, 'migration' | 'modification'>> truncate?: Resolver<ResolversTypes['TruncateResponse'], ParentType, ContextType> } export type QueryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = { stages?: Resolver<ReadonlyArray<ResolversTypes['Stage']>, ParentType, ContextType> executedMigrations?: Resolver<ReadonlyArray<ResolversTypes['ExecutedMigration']>, ParentType, ContextType, RequireFields<QueryExecutedMigrationsArgs, never>> history?: Resolver<ResolversTypes['HistoryResponse'], ParentType, ContextType, RequireFields<QueryHistoryArgs, 'stage'>> } export type StageResolvers<ContextType = any, ParentType extends ResolversParentTypes['Stage'] = ResolversParentTypes['Stage']> = { id?: Resolver<ResolversTypes['String'], ParentType, ContextType> name?: Resolver<ResolversTypes['String'], ParentType, ContextType> slug?: Resolver<ResolversTypes['String'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type TruncateResponseResolvers<ContextType = any, ParentType extends ResolversParentTypes['TruncateResponse'] = ResolversParentTypes['TruncateResponse']> = { ok?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType> __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType> } export type Resolvers<ContextType = any> = { DateTime?: GraphQLScalarType ExecutedMigration?: ExecutedMigrationResolvers<ContextType> HistoryCreateEvent?: HistoryCreateEventResolvers<ContextType> HistoryDeleteEvent?: HistoryDeleteEventResolvers<ContextType> HistoryError?: HistoryErrorResolvers<ContextType> HistoryEvent?: HistoryEventResolvers<ContextType> HistoryResponse?: HistoryResponseResolvers<ContextType> HistoryResult?: HistoryResultResolvers<ContextType> HistoryRunMigrationEvent?: HistoryRunMigrationEventResolvers<ContextType> HistoryUpdateEvent?: HistoryUpdateEventResolvers<ContextType> Json?: GraphQLScalarType MigrateError?: MigrateErrorResolvers<ContextType> MigrateResponse?: MigrateResponseResolvers<ContextType> MigrateResult?: MigrateResultResolvers<ContextType> MigrationDeleteError?: MigrationDeleteErrorResolvers<ContextType> MigrationDeleteResponse?: MigrationDeleteResponseResolvers<ContextType> MigrationModifyError?: MigrationModifyErrorResolvers<ContextType> MigrationModifyResponse?: MigrationModifyResponseResolvers<ContextType> Mutation?: MutationResolvers<ContextType> Query?: QueryResolvers<ContextType> Stage?: StageResolvers<ContextType> TruncateResponse?: TruncateResponseResolvers<ContextType> } /** * @deprecated * Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config. */ export type IResolvers<ContextType = any> = Resolvers<ContextType>
the_stack
import { throttle, each } from 'utils/underscore'; import { between } from 'utils/math'; import { style, transform } from 'utils/css'; import { timeFormat, timeFormatAria } from 'utils/parser'; import { addClass, removeClass, setAttribute, bounds } from 'utils/dom'; import { limit } from 'utils/function-wrappers'; import UI from 'utils/ui'; import Slider from 'view/controls/components/slider'; import TooltipIcon from 'view/controls/components/tooltipicon'; import ChaptersMixin, { ChaptersMixinInt, Cue } from 'view/controls/components/chapters.mixin'; import ThumbnailsMixin, { ThumbnailsMixinInt } from 'view/controls/components/thumbnails.mixin'; import type ViewModel from 'view/view-model'; import type { PlayerAPI, GenericObject, TextTrackLike } from 'types/generic.type'; import type Item from 'playlist/item'; export type TimeSliderWithMixins = TimeSlider & ChaptersMixinInt & ThumbnailsMixinInt; const SEEK_EVENT_UPDATE_INTERVAL_MS = 400; // Number of milliseconds minimum between aria updates const ARIA_TEXT_UPDATE_INTERVAL_MS = 1000; // Maximum number of times that the aria text is updated without // an event (focus & seek) reseting the count const ARIA_TEXT_UPDATE_TIMES = 4; class TimeTipIcon extends TooltipIcon { textChapter?: HTMLElement; textTime?: HTMLElement; img?: HTMLElement; containerWidth?: number; container?: HTMLElement; textLength?: number; dragJustReleased?: boolean; setup(): void { this.textChapter = document.createElement('span'); this.textChapter.className = 'jw-time-chapter jw-text jw-reset'; this.textChapter.style.display = 'none'; this.textTime = document.createElement('span'); this.textTime.className = 'jw-time-time jw-text jw-reset'; this.img = document.createElement('div'); this.img.className = 'jw-time-thumb jw-reset'; this.containerWidth = 0; this.textLength = 0; this.dragJustReleased = false; const wrapper = document.createElement('div'); wrapper.className = 'jw-time-tip jw-reset'; wrapper.appendChild(this.img); wrapper.appendChild(this.textChapter); wrapper.appendChild(this.textTime); this.addContent(wrapper); } image(styles: GenericObject): void { style(this.img, styles); } update(txtTime: string, txtChapter?: string): void { if (!this.textTime) { return; } this.textTime.textContent = txtTime; if (!txtChapter) { if (this.textChapter) { this.textChapter.style.display = 'none'; this.textChapter.textContent = ''; } return; } if (!this.textChapter) { return; } this.textChapter.textContent = txtChapter; this.textChapter.style.removeProperty('display'); } getWidth(): number { if (!this.containerWidth) { this.setWidth(); } return this.containerWidth as number; } setWidth(width?: number): void { const tolerance = 16; // add a little padding so the tooltip isn't flush against the edge if (width) { this.containerWidth = width + tolerance; return; } if (!this.tooltip) { return; } this.containerWidth = bounds(this.container).width + tolerance; } resetWidth(): void { this.containerWidth = 0; } } function reasonInteraction(): { reason: string } { return { reason: 'interaction' }; } class TimeSlider extends Slider { _model: ViewModel; _api: PlayerAPI; _updateAriaTextLimitedThrottled: any; timeUpdateKeeper: HTMLElement; timeTip: TimeTipIcon; cues: Cue[]; seekThrottled: Function; seekTo?: number; streamType?: string; activeCue?: Cue | null; textLength?: number; constructor(_model: ViewModel, _api: PlayerAPI, _timeUpdateKeeper: HTMLElement) { super('jw-slider-time', 'horizontal'); this._model = _model; this._api = _api; this.timeUpdateKeeper = _timeUpdateKeeper; this.timeTip = new TimeTipIcon('jw-tooltip-time', null, true); this.timeTip.setup(); this.cues = []; // Store the attempted seek, until the previous one completes this.seekThrottled = throttle(this.performSeek, SEEK_EVENT_UPDATE_INTERVAL_MS); this._updateAriaTextLimitedThrottled = limit( throttle( this.updateAriaText, ARIA_TEXT_UPDATE_INTERVAL_MS), ARIA_TEXT_UPDATE_TIMES); this.setup(); } // These overwrite Slider methods setup(): void { super.setup.call(this); this._model .on('change:duration', this.onDuration, this) .on('change:cues', this.updateCues, this) .on('seeked', () => { if (!this._model.get('scrubbing')) { this._updateAriaTextLimitedThrottled.reset(); this._updateAriaTextLimitedThrottled(); } }); this._model.change('position', this.onPosition, this) .change('buffer', this.onBuffer, this) .change('streamType', this.onStreamType, this); // Clear cues on player model's playlistItem change event this._model.player.change('playlistItem', this.onPlaylistItem, this); const sliderElement = this.el; setAttribute(sliderElement, 'tabindex', '0'); setAttribute(sliderElement, 'role', 'slider'); setAttribute(sliderElement, 'aria-label', this._model.get('localization').slider); sliderElement.removeAttribute('aria-hidden'); this.elementRail.appendChild(this.timeTip.element()); // Show the tooltip on while dragging (touch) moving(mouse), or moving over(mouse) this.ui = (this.ui || new UI(sliderElement)) .on('move drag', this.showTimeTooltip, this) .on('dragEnd out', this.hideTimeTooltip, this) .on('click', () => sliderElement.focus()) .on('focus', () => this._updateAriaTextLimitedThrottled.reset()) .on('blur', () => this._updateAriaTextLimitedThrottled.shush()); } update(percent: number): void { this.seekTo = percent; this.seekThrottled(); super.update.apply(this, [percent]); } dragStart(): void { this._model.set('scrubbing', true); super.dragStart.call(this); } dragEnd(evt: Event): void { super.dragEnd.apply(this, [evt]); this._model.set('scrubbing', false); } onBuffer(model: ViewModel, pct: number): void { this.updateBuffer(pct); } onPosition(model: ViewModel, position: number): void { this.updateTime(position, model.get('duration')); } onDuration(this: TimeSliderWithMixins, model: ViewModel, duration: number): void { this.updateTime(model.get('position'), duration); setAttribute(this.el, 'aria-valuemin', 0); setAttribute(this.el, 'aria-valuemax', Math.abs(duration)); this.drawCues(); } onStreamType(model: ViewModel, streamType: string): void { this.streamType = streamType; } updateTime(position: number, duration: number): void { let pct = 0; if (duration) { if (this.streamType === 'DVR') { const dvrSeekLimit = this._model.get('dvrSeekLimit'); const diff = duration + dvrSeekLimit; const pos = position + dvrSeekLimit; pct = (diff - pos) / diff * 100; } else if (this.streamType === 'VOD' || !this.streamType) { // Default to VOD behavior if streamType isn't set pct = position / duration * 100; } } this._updateAriaTextLimitedThrottled(); this.render(pct); } onPlaylistItem(this: TimeSliderWithMixins, model: ViewModel, playlistItem: Item): void { this.reset(); // If cues have been cleared from slider but exist on model, update cues. const cues = model.get('cues'); if (!this.cues.length && cues.length) { this.updateCues(null, cues); } const tracks: TextTrackList = playlistItem.tracks; each(tracks, function (this: TimeSliderWithMixins, track: TextTrackLike): void { if (track && track.kind && track.kind.toLowerCase() === 'thumbnails') { this.loadThumbnails(track.file as string); } else if (track && track.kind && track.kind.toLowerCase() === 'chapters') { this.loadChapters(track.file as string); } }, this); } performSeek(): void { const percent = this.seekTo as number; const duration = this._model.get('duration'); let position; if (duration === 0) { this._api.play(reasonInteraction()); } else if (this.streamType === 'DVR') { const seekRange = this._model.get('seekRange') || { start: 0 }; const dvrSeekLimit = this._model.get('dvrSeekLimit'); position = seekRange.start + (-duration - dvrSeekLimit) * percent / 100; this._api.seek(position, reasonInteraction()); } else { position = percent / 100 * duration; this._api.seek(Math.min(position, duration - 0.25), reasonInteraction()); } } showTimeTooltip(this: TimeSliderWithMixins, evt: GenericObject): void { let duration = this._model.get('duration'); if (duration === 0) { return; } const playerWidth = this._model.get('containerWidth'); const railBounds = bounds(this.elementRail); let position = (evt.pageX ? (evt.pageX - railBounds.left) : evt.x); position = between(position, 0, railBounds.width); const pct: number = position / railBounds.width; let time = duration * pct; // For DVR we need to swap it around if (duration < 0) { const dvrSeekLimit = this._model.get('dvrSeekLimit'); duration += dvrSeekLimit; time = (duration * pct); time = duration - time; } let timetipTextLength; const timeText = timeFormat(time, true); const timeTip = this.timeTip; this.setActiveCue(time); if (this.activeCue) { timeTip.update(timeText, this.activeCue.text); timetipTextLength = this.activeCue.text.length + timeText.length; } else { let timetipText = timeText; // If DVR and within live buffer if (duration < 0 && time > -1) { timetipText = 'Live'; } timeTip.update(timetipText); timetipTextLength = timetipText.length; } if (this.textLength !== timetipTextLength) { // An activeCue may cause the width of the timeTip container to change this.textLength = timetipTextLength; timeTip.resetWidth(); } this.showThumbnail(time); addClass(timeTip.el, 'jw-open'); const timeTipWidth = timeTip.getWidth(); const tolerance = playerWidth - railBounds.width; let timeTipPixels = 0; if (timeTipWidth > tolerance) { // timeTip may go outside the bounds of the player. Determine the amount of tolerance needed in pixels. timeTipPixels = (timeTipWidth - tolerance) / 2; } const safePixels: number = Math.round(Math.min(railBounds.width - timeTipPixels, Math.max(timeTipPixels, position)) * 4) / 4; transform(timeTip.el, `translateX(${safePixels}px)`); } hideTimeTooltip(): void { removeClass(this.timeTip.el, 'jw-open'); } updateCues(this: TimeSliderWithMixins, model: ViewModel | null, cues: Cue[]): void { this.resetCues(); if (cues && cues.length) { cues.forEach((ele) => { this.addCue(ele); }); this.drawCues(); } } updateAriaText(): void { const model = this._model; const sliderElement = this.el; let position = model.get('position'); let duration = model.get('duration'); if (this.streamType === 'DVR') { duration = Math.abs(duration); position = duration + position; } const ariaPositionText = timeFormatAria(position); const ariaDurationText = timeFormatAria(duration); const ariaString = `${ariaPositionText} of ${ariaDurationText}`; this.timeUpdateKeeper.textContent = ariaString; setAttribute(sliderElement, 'aria-valuetext', ariaString); setAttribute(sliderElement, 'aria-valuenow', position); } reset(this: TimeSliderWithMixins): void { this.resetThumbnails(); this.timeTip.resetWidth(); this.textLength = 0; this._updateAriaTextLimitedThrottled.reset(); } } Object.assign(TimeSlider.prototype, ChaptersMixin, ThumbnailsMixin); export default TimeSlider;
the_stack
import { Action, AnyAction, isAllOf, isPlainObject } from '@reduxjs/toolkit'; import { QueryStatus } from '@reduxjs/toolkit/query'; import { QueryInfo, RtkQueryMonitorState, RtkQueryApiState, RTKQuerySubscribers, RtkQueryTag, RTKStatusFlags, RtkQueryState, MutationInfo, ApiStats, QueryTally, RtkQueryProvided, ApiTimings, QueryTimings, SelectorsSource, RtkMutationState, RtkResourceInfo, RtkRequest, RtkRequestTiming, } from '../types'; import { missingTagId } from '../monitor-config'; import { Comparator, compareJSONPrimitive } from './comparators'; import { emptyArray } from './object'; import { formatMs } from './formatters'; import * as statistics from './statistics'; const rtkqueryApiStateKeys: ReadonlyArray<keyof RtkQueryApiState> = [ 'queries', 'mutations', 'config', 'provided', 'subscriptions', ]; /** * Type guard used to select apis from the user store state. * @param val * @returns {boolean} */ export function isApiSlice(val: unknown): val is RtkQueryApiState { if (!isPlainObject(val)) { return false; } for (let i = 0, len = rtkqueryApiStateKeys.length; i < len; i++) { if ( !isPlainObject((val as Record<string, unknown>)[rtkqueryApiStateKeys[i]]) ) { return false; } } return true; } /** * Indexes api states by their `reducerPath`. * * Returns `null` if there are no api slice or `reduxStoreState` * is not an object. * * @param reduxStoreState * @returns */ export function getApiStatesOf( reduxStoreState: unknown ): null | Readonly<Record<string, RtkQueryApiState>> { if (!isPlainObject(reduxStoreState)) { return null; } const output: null | Record<string, RtkQueryApiState> = {}; const keys = Object.keys(reduxStoreState); for (let i = 0, len = keys.length; i < len; i++) { const key = keys[i]; const value = (reduxStoreState as Record<string, unknown>)[key]; if (isApiSlice(value)) { output[key] = value; } } if (Object.keys(output).length === 0) { return null; } return output; } export function extractAllApiQueries( apiStatesByReducerPath: null | Readonly<Record<string, RtkQueryApiState>> ): ReadonlyArray<QueryInfo> { if (!apiStatesByReducerPath) { return emptyArray; } const reducerPaths = Object.keys(apiStatesByReducerPath); const output: QueryInfo[] = []; for (let i = 0, len = reducerPaths.length; i < len; i++) { const reducerPath = reducerPaths[i]; const api = apiStatesByReducerPath[reducerPath]; const queryKeys = Object.keys(api.queries); for (let j = 0, qKeysLen = queryKeys.length; j < qKeysLen; j++) { const queryKey = queryKeys[j]; const state = api.queries[queryKey]; if (state) { output.push({ type: 'query', reducerPath, queryKey, state, }); } } } return output; } export function extractAllApiMutations( apiStatesByReducerPath: null | Readonly<Record<string, RtkQueryApiState>> ): ReadonlyArray<MutationInfo> { if (!apiStatesByReducerPath) { return emptyArray; } const reducerPaths = Object.keys(apiStatesByReducerPath); const output: MutationInfo[] = []; for (let i = 0, len = reducerPaths.length; i < len; i++) { const reducerPath = reducerPaths[i]; const api = apiStatesByReducerPath[reducerPath]; const mutationKeys = Object.keys(api.mutations); for (let j = 0, mKeysLen = mutationKeys.length; j < mKeysLen; j++) { const queryKey = mutationKeys[j]; const state = api.mutations[queryKey]; if (state) { output.push({ type: 'mutation', reducerPath, queryKey, state, }); } } } return output; } function computeQueryTallyOf( queryState: RtkQueryApiState['queries'] | RtkQueryApiState['mutations'] ): QueryTally { const queries = Object.values(queryState); const output: QueryTally = { count: 0, }; for (let i = 0, len = queries.length; i < len; i++) { const query = queries[i]; if (query) { output.count++; if (!output[query.status]) { output[query.status] = 1; } else { (output[query.status] as number)++; } } } return output; } function tallySubscriptions( subsState: RtkQueryApiState['subscriptions'] ): number { const subsOfQueries = Object.values(subsState); let output = 0; for (let i = 0, len = subsOfQueries.length; i < len; i++) { const subsOfQuery = subsOfQueries[i]; if (subsOfQuery) { output += Object.keys(subsOfQuery).length; } } return output; } function computeRtkQueryRequests( type: 'queries' | 'mutations', api: RtkQueryApiState, sortedActions: AnyAction[], currentStateIndex: SelectorsSource<unknown>['currentStateIndex'] ): Readonly<Record<string, RtkRequest>> { const requestById: Record<string, RtkRequest> = {}; const matcher = type === 'queries' ? matchesExecuteQuery(api.config.reducerPath) : matchesExecuteMutation(api.config.reducerPath); for ( let i = 0, len = sortedActions.length; i < len && i <= currentStateIndex; i++ ) { const action = sortedActions[i]; if (matcher(action)) { let requestRecord: RtkRequest | undefined = requestById[action.meta.requestId]; if (!requestRecord) { const queryCacheKey: string | undefined = ( action.meta as Record<string, any> )?.arg?.queryCacheKey; const queryKey = typeof queryCacheKey === 'string' ? queryCacheKey : action.meta.requestId; const endpointName: string = (action.meta as any)?.arg?.endpointName ?? '-'; requestById[action.meta.requestId] = requestRecord = { queryKey, requestId: action.meta.requestId, endpointName, status: action.meta.requestStatus, }; } requestRecord.status = action.meta.requestStatus; if ( action.meta.requestStatus === QueryStatus.pending && typeof (action.meta as any).startedTimeStamp === 'number' ) { requestRecord.startedTimeStamp = (action.meta as any).startedTimeStamp; } if ( action.meta.requestStatus === QueryStatus.fulfilled && typeof (action.meta as any).fulfilledTimeStamp === 'number' ) { requestRecord.fulfilledTimeStamp = ( action.meta as any ).fulfilledTimeStamp; } } } const requestIds = Object.keys(requestById); // Patch queries that have pending actions that are committed for (let i = 0, len = requestIds.length; i < len; i++) { const requestId = requestIds[i]; const request = requestById[requestId]; if ( typeof request.startedTimeStamp === 'undefined' && typeof request.fulfilledTimeStamp === 'number' ) { const startedTimeStampFromCache = api[type][request.queryKey]?.startedTimeStamp; if (typeof startedTimeStampFromCache === 'number') { request.startedTimeStamp = startedTimeStampFromCache; } } } // Add queries that have pending and fulfilled actions committed const queryCacheEntries = Object.entries(api[type] ?? {}); for (let i = 0, len = queryCacheEntries.length; i < len; i++) { const [queryCacheKey, queryCache] = queryCacheEntries[i]; const requestId: string = type === 'queries' ? (queryCache as typeof api['queries'][string])?.requestId ?? '' : queryCacheKey; if ( queryCache && !Object.prototype.hasOwnProperty.call(requestById, requestId) ) { const startedTimeStamp = queryCache?.startedTimeStamp; const fulfilledTimeStamp = queryCache?.fulfilledTimeStamp; if ( typeof startedTimeStamp === 'number' && typeof fulfilledTimeStamp === 'number' ) { requestById[requestId] = { queryKey: queryCacheKey, requestId, endpointName: queryCache.endpointName ?? '', startedTimeStamp, fulfilledTimeStamp, status: queryCache.status, }; } } } return requestById; } function formatRtkRequest( rtkRequest: RtkRequest | null ): RtkRequestTiming | null { if (!rtkRequest) { return null; } const fulfilledTimeStamp = rtkRequest.fulfilledTimeStamp; const startedTimeStamp = rtkRequest.startedTimeStamp; const output: RtkRequestTiming = { queryKey: rtkRequest.queryKey, requestId: rtkRequest.requestId, endpointName: rtkRequest.endpointName, startedAt: '-', completedAt: '-', duration: '-', }; if ( typeof fulfilledTimeStamp === 'number' && typeof startedTimeStamp === 'number' ) { output.startedAt = new Date(startedTimeStamp).toISOString(); output.completedAt = new Date(fulfilledTimeStamp).toISOString(); output.duration = formatMs(fulfilledTimeStamp - startedTimeStamp); } return output; } function computeQueryApiTimings( requestById: Readonly<Record<string, RtkRequest>> ): QueryTimings { const requests = Object.values(requestById); let latestRequest: RtkRequest | null = null; let oldestRequest: null | RtkRequest = null; let slowestRequest: RtkRequest | null = null; let fastestRequest: RtkRequest | null = null; let slowestDuration = 0; let fastestDuration = Number.MAX_SAFE_INTEGER; const pendingDurations: number[] = []; for (let i = 0, len = requests.length; i < len; i++) { const request = requests[i]; const { fulfilledTimeStamp, startedTimeStamp } = request; if (typeof fulfilledTimeStamp === 'number') { const latestFulfilledTimeStamp = latestRequest?.fulfilledTimeStamp || 0; const oldestFulfilledTimeStamp = oldestRequest?.fulfilledTimeStamp || Number.MAX_SAFE_INTEGER; if (fulfilledTimeStamp > latestFulfilledTimeStamp) { latestRequest = request; } if (fulfilledTimeStamp < oldestFulfilledTimeStamp) { oldestRequest = request; } if ( typeof startedTimeStamp === 'number' && startedTimeStamp <= fulfilledTimeStamp ) { const pendingDuration = fulfilledTimeStamp - startedTimeStamp; pendingDurations.push(pendingDuration); if (pendingDuration > slowestDuration) { slowestDuration = pendingDuration; slowestRequest = request; } if (pendingDuration < fastestDuration) { fastestDuration = pendingDuration; fastestRequest = request; } } } } const average = pendingDurations.length > 0 ? formatMs(statistics.mean(pendingDurations)) : '-'; const median = pendingDurations.length > 0 ? formatMs(statistics.median(pendingDurations)) : '-'; return { latest: formatRtkRequest(latestRequest), oldest: formatRtkRequest(oldestRequest), slowest: formatRtkRequest(slowestRequest), fastest: formatRtkRequest(fastestRequest), average, median, }; } function computeApiTimings( api: RtkQueryApiState, actionsById: SelectorsSource<unknown>['actionsById'], currentStateIndex: SelectorsSource<unknown>['currentStateIndex'] ): ApiTimings { const sortedActions = Object.entries(actionsById) .sort((thisAction, thatAction) => compareJSONPrimitive(Number(thisAction[0]), Number(thatAction[0])) ) .map((entry) => entry[1].action); const queryRequestsById = computeRtkQueryRequests( 'queries', api, sortedActions, currentStateIndex ); const mutationRequestsById = computeRtkQueryRequests( 'mutations', api, sortedActions, currentStateIndex ); return { queries: computeQueryApiTimings(queryRequestsById), mutations: computeQueryApiTimings(mutationRequestsById), }; } export function generateApiStatsOfCurrentQuery( api: RtkQueryApiState | null, actionsById: SelectorsSource<unknown>['actionsById'], currentStateIndex: SelectorsSource<unknown>['currentStateIndex'] ): ApiStats | null { if (!api) { return null; } return { timings: computeApiTimings(api, actionsById, currentStateIndex), tally: { cachedQueries: computeQueryTallyOf(api.queries), cachedMutations: computeQueryTallyOf(api.mutations), tagTypes: Object.keys(api.provided).length, subscriptions: tallySubscriptions(api.subscriptions), }, }; } export function flipComparator<T>(comparator: Comparator<T>): Comparator<T> { return function flipped(a: T, b: T) { return comparator(b, a); }; } export function isQuerySelected( selectedQueryKey: RtkQueryMonitorState['selectedQueryKey'], queryInfo: RtkResourceInfo ): boolean { return ( !!selectedQueryKey && selectedQueryKey.queryKey === queryInfo.queryKey && selectedQueryKey.reducerPath === queryInfo.reducerPath ); } export function getApiStateOf( queryInfo: RtkResourceInfo | null, apiStates: ReturnType<typeof getApiStatesOf> ): RtkQueryApiState | null { if (!apiStates || !queryInfo) { return null; } return apiStates[queryInfo.reducerPath] ?? null; } export function getQuerySubscriptionsOf( queryInfo: QueryInfo | null, apiStates: ReturnType<typeof getApiStatesOf> ): RTKQuerySubscribers | null { if (!apiStates || !queryInfo) { return null; } return ( apiStates[queryInfo.reducerPath]?.subscriptions?.[queryInfo.queryKey] ?? null ); } export function getProvidedOf( queryInfo: QueryInfo | null, apiStates: ReturnType<typeof getApiStatesOf> ): RtkQueryApiState['provided'] | null { if (!apiStates || !queryInfo) { return null; } return apiStates[queryInfo.reducerPath]?.provided ?? null; } export function getQueryTagsOf( resInfo: RtkResourceInfo | null, provided: RtkQueryProvided | null ): RtkQueryTag[] { if (!resInfo || resInfo.type === 'mutation' || !provided) { return emptyArray; } const tagTypes = Object.keys(provided); if (tagTypes.length < 1) { return emptyArray; } const output: RtkQueryTag[] = []; for (const [type, tagIds] of Object.entries(provided)) { if (tagIds) { for (const [id, queryKeys] of Object.entries(tagIds)) { if ((queryKeys as unknown[]).includes(resInfo.queryKey)) { const tag: RtkQueryTag = { type }; if (id !== missingTagId) { tag.id = id; } output.push(tag); } } } } return output; } /** * Computes query status flags. * @param status * @see https://redux-toolkit.js.org/rtk-query/usage/queries#frequently-used-query-hook-return-values * @see https://github.com/reduxjs/redux-toolkit/blob/b718e01d323d3ab4b913e5d88c9b90aa790bb975/src/query/core/apiState.ts#L63 */ export function getQueryStatusFlags({ status, data, }: RtkQueryState | RtkMutationState): RTKStatusFlags { return { isUninitialized: status === QueryStatus.uninitialized, isFetching: status === QueryStatus.pending, isSuccess: status === QueryStatus.fulfilled && !!data, isError: status === QueryStatus.rejected, }; } /** * endpoint matcher * @param endpointName * @see https://github.com/reduxjs/redux-toolkit/blob/b718e01d323d3ab4b913e5d88c9b90aa790bb975/src/query/core/buildThunks.ts#L415 */ export function matchesEndpoint(endpointName: unknown) { return (action: any): action is Action => endpointName != null && action?.meta?.arg?.endpointName === endpointName; } function matchesQueryKey(queryKey: string) { return (action: any): action is Action => action?.meta?.arg?.queryCacheKey === queryKey; } function macthesRequestId(requestId: string) { return (action: any): action is Action => action?.meta?.requestId === requestId; } function matchesReducerPath(reducerPath: string) { return (action: any): action is Action<string> => typeof action?.type === 'string' && action.type.startsWith(reducerPath); } function matchesExecuteQuery(reducerPath: string) { return ( action: any ): action is Action<string> & { meta: { requestId: string; requestStatus: QueryStatus }; } => { return ( typeof action?.type === 'string' && action.type.startsWith(`${reducerPath}/executeQuery`) && typeof action.meta?.requestId === 'string' && typeof action.meta?.requestStatus === 'string' ); }; } function matchesExecuteMutation(reducerPath: string) { return ( action: any ): action is Action<string> & { meta: { requestId: string; requestStatus: QueryStatus }; } => typeof action?.type === 'string' && action.type.startsWith(`${reducerPath}/executeMutation`) && typeof action.meta?.requestId === 'string' && typeof action.meta?.requestStatus === 'string'; } export function getActionsOfCurrentQuery( currentQuery: RtkResourceInfo | null, actionById: SelectorsSource<unknown>['actionsById'] ): Action[] { if (!currentQuery) { return emptyArray; } let matcher: ReturnType<typeof macthesRequestId>; if (currentQuery.type === 'mutation') { matcher = isAllOf( matchesReducerPath(currentQuery.reducerPath), macthesRequestId(currentQuery.queryKey) ); } else { matcher = isAllOf( matchesReducerPath(currentQuery.reducerPath), matchesQueryKey(currentQuery.queryKey) ); } const output: AnyAction[] = []; for (const [, liftedAction] of Object.entries(actionById)) { if (matcher(liftedAction?.action)) { output.push(liftedAction.action); } } return output.length === 0 ? emptyArray : output; }
the_stack
namespace Pandyle { export class VM<T> { protected _data: T; private _root: JQuery<HTMLElement>; public _methods: object; private _variables: object; private _defaultAlias: object; public _relationCollection: IRelationCollection; private _util: Util<T>; private _renderer: Renderer<T> constructor(element: JQuery<HTMLElement>, data: T, autoRun: boolean = true) { this._data = $.extend({}, data); this._root = element; this._methods = {}; this._variables = {}; this._defaultAlias = { root: { data: this._data, property: '' }, window: { data: window, property: '@window' } } this._util = Util.CreateUtil(this); this._relationCollection = RelationCollection.CreateRelationCollection(this._util); this._renderer = new Renderer(this); if (autoRun) { this.run(); } } public set(newData: string, value: any); public set(newData: object); public set(newData: any, value?: any) { let _newData = {}; if (arguments.length === 2) { _newData[newData] = value; } else { _newData = newData; } let elementsToRerender = this.updateDataAndGetElementToRerender(_newData); elementsToRerender.forEach(item => { this.render(item); }) } public get(param?: any) { if (!param) { return $.extend({}, this._data); } switch ($.type(param)) { case 'array': return param.map(value => this.get(value)); case 'string': return this._util.getValue(this._root, param, this._data); case 'object': let result = {}; for (let key in param) { result[key] = this._util.getValue(this._root, param[key], this._data); } return result; default: return null; } } /** * * @param target 目标 * @param value 要添加的数据 */ public append(target: string | JQuery<HTMLElement>, value: any) { if (typeof target === 'string') { let lastProperty = this.getLastProperty(target); let targetData = this.getTargetData(target); let array: any[] = targetData[lastProperty]; array.push(value); let relations = this._relationCollection.findSelf(target); relations.forEach(relation => { relation.elements.forEach(element => { let domData = Pandyle.getDomData(element); let newChildren = iteratorBase.generateChild(domData, element.children().length, value, target); if (domData.binding['For']) { domData.children.last().after(newChildren); var arr = []; arr.push.call(domData.children, newChildren); } else { element.append(newChildren); } this.render($(newChildren)); }) }) } else { target.each((index, item) => { let domData = Pandyle.getDomData($(item)); let context = domData.context; if (domData.binding['For']) { let arrayName = domData.binding['For'].pattern; context[arrayName].push(value); let newChildren = iteratorBase.generateChild(domData, $(item).children().length, value, `${domData.parentProperty}.${arrayName}`); domData.children.last().after(newChildren); var arr = []; arr.push.call(domData.children, newChildren); this.render($(newChildren)); } else { let arrayName = domData.binding['Each'].pattern; context[arrayName].push(value); let newChildren = iteratorBase.generateChild(domData, $(item).children().length, value, `${domData.parentProperty}.${arrayName}`); $(item).append(newChildren); this.render($(newChildren)); } }) } } public appendArray(target: string | JQuery<HTMLElement>, value: any[]) { if (typeof target == 'string') { let lastProperty = this.getLastProperty(target); let targetData = this.getTargetData(target); let array: any[] = targetData[lastProperty]; value.forEach((item) => { array.push(item); }) let relations = this._relationCollection.findSelf(target); relations.forEach(relation => { relation.elements.forEach(element => { let domData = Pandyle.getDomData(element); value.forEach((currentValue) => { let newChildren = iteratorBase.generateChild(domData, element.children().length, currentValue, target); if (domData.binding['For']) { domData.children.last().after(newChildren); var arr = []; arr.push.call(domData.children, newChildren); } else { element.append(newChildren); } this.render($(newChildren)); }) }) }) } else { target.each((index, item) => { let domData = Pandyle.getDomData($(item)); let context = domData.context; if (domData.binding['For']) { let arrayName = domData.binding['For'].pattern; value.forEach(val => { context[arrayName].push(val); let newChildren = iteratorBase.generateChild(domData, $(item).children().length, val, `${domData.parentProperty}.${arrayName}`); domData.children.last().after(newChildren); var arr = []; arr.push.call(domData.children, newChildren); this.render($(newChildren)); }) } else { let arrayName = domData.binding['Each'].pattern; value.forEach(val => { context[arrayName].push(val); let newChildren = iteratorBase.generateChild(domData, $(item).children().length, val, `${domData.parentProperty}.${arrayName}`); $(item).append(newChildren); this.render($(newChildren)); }) } }) } } public run() { this.render(this._root, this._data, '', this._defaultAlias); } /** * 渲染指定的元素 * @param element 渲染对象 * @param data 数据上下文 * @param parentProperty 父级字段的名称 * @param alias 别名对象 */ public render(element: JQuery<HTMLElement>, data?: any, parentProperty?: string, alias?: any) { element.each((index, ele) => { this._renderer.renderSingle(ele, data, parentProperty, $.extend({}, alias)); }) } public getMethod(name: string): Function { return this._methods[name]; } public transfer(method: string, data: any[]) { return this._methods[method](data); } public register(name: string, value: any) { if ($.isFunction(value)) { this._methods[name] = value; } else { this._variables[name] = value; } } private updateDataAndGetElementToRerender(_newData: any) { var elementsToRerender: JQuery<HTMLElement>[] = []; for (let key in _newData) { let lastProperty = this.getLastProperty(key); let target = this.getTargetData(key); target[lastProperty] = _newData[key]; let relation = this._relationCollection.findSelfOrChild(key); for (let i = 0; i < relation.length; i++) { let item = relation[i]; let itemKey = item.property; if ($.isArray(this.getDataByKey(itemKey))) { this._relationCollection.removeChildren(itemKey); } } relation = this._relationCollection.findSelfOrChild(key); if (relation.length > 0) { for (let i = 0; i < relation.length; i++) { let item = relation[i]; for (let j = 0; j < item.elements.length; j++) { let item2 = item.elements[j]; if (Pandyle.getDomData(item2).alias) { if (elementsToRerender.indexOf(item2) < 0) { elementsToRerender.push(item2); } } else { item.elements.splice(j, 1); j--; } } } } } return elementsToRerender; } private getTargetData(key: string) { let properties = key.split(/[\[\]\.]/).filter(s => s != ''); properties.pop(); let target = this._data; if (properties.length > 0) { target = properties.reduce((obj, current) => { return obj[current]; }, this._data); } return target; } private getDataByKey(key: string) { let properties = key.split(/[\[\]\.]/).filter(s => s != ''); let target = this._data; if (properties.length > 0) { target = properties.reduce((obj, current) => { if (!obj) { return null; } return obj[current]; }, this._data); } return target; } private getLastProperty(key: string) { let properties = key.split(/[\[\]\.]/).filter(s => s != ''); let lastProperty = properties.pop(); return lastProperty; } } }
the_stack
import * as path from 'path'; import * as fs from 'fs-extra'; import * as Debug from 'debug'; import { MetadataType } from '../metadataType'; import { TypeDefObj } from '../typeDefObj'; import { WorkspaceElement } from '../workspaceElement'; import * as PathUtil from '../sourcePathUtil'; import { DecompositionConfig } from '../decompositionStrategy/decompositionConfig'; import MetadataRegistry = require('../metadataRegistry'); import srcDevUtil = require('../../core/srcDevUtil'); import Messages = require('../../messages'); const messages = Messages(); /** * Default type obj is any atomic (non-decomposed) metadata type */ export class DefaultMetadataType implements MetadataType { protected typeDefObj: TypeDefObj; private _debug = Debug(`sfdx:${this.constructor.name}`); constructor(typeDefObj: TypeDefObj) { this.typeDefObj = typeDefObj; } getAggregateMetadataName(): string { return this.getMetadataName(); } getMetadataName(): string { return this.typeDefObj.metadataName; } getBaseTypeName(): string { return this.typeDefObj.metadataName; } isAddressable(): boolean { return this.typeDefObj.isAddressable; } getDecompositionConfig(): DecompositionConfig { return this.typeDefObj.decompositionConfig; } resolveSourcePath(sourcePath: string): string { return sourcePath; } getFullNameFromFilePath(filePath: string): string { return PathUtil.getFileName(filePath); } getAggregateFullNameFromFilePath(filePath: string): string { return PathUtil.getFileName(filePath); } getAggregateMetadataFilePathFromWorkspacePath(filePath): string { return DefaultMetadataType.getPathWithMetadataExtension(filePath); } getDefaultAggregateMetadataPath(fullName: string, defaultSourceDir: string, bundleFileProperties): string { return this.getAggregateMetadataPathInDir(defaultSourceDir, fullName); } getAggregateMetadataPathInDir(dirName: string, fullName: string): string { const pathToDir = path.join(dirName, this.typeDefObj.defaultDirectory); const fileName = `${fullName}.${this.typeDefObj.ext}${MetadataRegistry.getMetadataFileExt()}`; return path.join(pathToDir, fileName); } getAggregateFullNameFromSourceMemberName(sourceMemberName: string): string { return PathUtil.encodeMetadataString(sourceMemberName); } getAggregateFullNameFromWorkspaceFullName(workspaceFullName: string): string { return workspaceFullName; } getAggregateFullNameFromFileProperty(fileProperty, namespace: string): string { return fileProperty.fullName; } getMdapiMetadataPath(metadataFilePath: string, aggregateFullName: string, mdDir: string): string { const mdapiSourceDir = this.getPathToMdapiSourceDir(aggregateFullName, mdDir); const mdapiMetadataFileName = this.getMdapiFormattedMetadataFileName(metadataFilePath); return path.join(mdapiSourceDir, mdapiMetadataFileName); } protected getPathToMdapiSourceDir(aggregateFullName: string, mdDir: string): string { return path.join(mdDir, this.typeDefObj.defaultDirectory); } private static getPathWithMetadataExtension(filePath: string): string { if (!filePath.endsWith(MetadataRegistry.getMetadataFileExt())) { return `${filePath}${MetadataRegistry.getMetadataFileExt()}`; } return filePath; } protected getMdapiFormattedMetadataFileName(metadataFilePath: string): string { const fileName = path.basename(metadataFilePath); if (!this.typeDefObj.hasContent) { return PathUtil.removeMetadataFileExtFrom(fileName); } return fileName; } hasIndividuallyAddressableChildWorkspaceElements(): boolean { return false; } requiresIndividuallyAddressableMembersInPackage(): boolean { return false; } isStandardMember(workspaceFullName: string): boolean { return this.typeDefObj.hasStandardMembers && !workspaceFullName.includes('__'); } getWorkspaceElementsToDelete(aggregateMetadataPath: string, fileProperty): WorkspaceElement[] { return []; } getRetrievedMetadataPath(fileProperty, retrieveRoot: string, bundlefileProperties): string { const retrievedMetadataPath = this.getRetrievedMetadataPathFromFileProperty(fileProperty, retrieveRoot); return this.validateRetrievedMetadataPathExists(retrievedMetadataPath); } protected validateRetrievedMetadataPathExists(retrievedMetadataPath: string): string { if (srcDevUtil.pathExistsSync(retrievedMetadataPath)) { return retrievedMetadataPath; } else { const err = new Error(); err['name'] = 'Missing metadata file'; err['message'] = messages.getMessage('MissingMetadataFile', retrievedMetadataPath); throw err; } } protected getRetrievedMetadataPathFromFileProperty(fileProperty, retrieveRoot: string): string { let fileName = fileProperty.fileName; if (this.typeDefObj.hasContent) { fileName = `${fileName}${MetadataRegistry.getMetadataFileExt()}`; } return path.join(retrieveRoot, fileName); } getRetrievedContentPath(fileProperty, retrieveRoot: string): string { if (this.typeDefObj.hasContent) { const retrievedContentPath = path.join(retrieveRoot, fileProperty.fileName); if (srcDevUtil.pathExistsSync(retrievedContentPath)) { return retrievedContentPath; } } return null; } getWorkspaceContentFilePath(metadataFilePath, retrievedContentFilePath): string { const workspaceDir = path.dirname(metadataFilePath); const fileName = path.basename(retrievedContentFilePath); return path.join(workspaceDir, fileName); } getOriginContentPathsForSourceConvert( metadataFilePath: string, workspaceVersion: string, unsupportedMimeTypes: string[], forceIgnore ): Promise<string[]> { return Promise.resolve([metadataFilePath.replace(MetadataRegistry.getMetadataFileExt(), '')]); } getMdapiContentPathForSourceConvert(originContentPath: string, aggregateFullName: string, mdDir: string): string { const mdapiSourceDir = this.getPathToMdapiSourceDir(aggregateFullName, mdDir); const mdapiContentFileName = this.getMdapiFormattedContentFileName(originContentPath, aggregateFullName); return this.getMdapiFormattedContentPath(mdapiSourceDir, mdapiContentFileName); } protected getMdapiFormattedContentPath(mdapiSourceDir: string, contentFileName: string): string { return path.join(mdapiSourceDir, contentFileName); } protected getMdapiFormattedContentFileName(originContentPath: string, aggregateFullName: string): string { return path.basename(originContentPath); } isFolderType(): boolean { return false; } /** * @param {string} metadataFilePath * @returns {boolean} */ mainContentFileExists(metadataFilePath: string): boolean { const contentFilePath = PathUtil.removeMetadataFileExtFrom(metadataFilePath); return srcDevUtil.pathExistsSync(contentFilePath); } displayAggregateRemoteChangesOnly(): boolean { return false; } getExt(): string { return this.typeDefObj.ext; } sourceMemberFullNameCorrespondsWithWorkspaceFullName( sourceMemberFullName: string, workspaceFullName: string ): boolean { return PathUtil.encodeMetadataString(sourceMemberFullName) === workspaceFullName; } protected sourceMemberFullNameConflictsWithWorkspaceFullName( sourceMemberFullName: string, workspaceFullName: string ): boolean { return sourceMemberFullName === workspaceFullName; } handleSlashesForSourceMemberName(sourceMemberFullName: string): string { return sourceMemberFullName; } conflictDetected(remoteChangeType: string, remoteChangeFullName: string, workspaceFullName: string): boolean { return ( this.sourceMemberFullNameConflictsWithWorkspaceFullName(remoteChangeFullName, workspaceFullName) && remoteChangeType === this.typeDefObj.metadataName ); } trackRemoteChangeForSourceMemberName(sourceMemberName: string): boolean { return true; } onlyDisplayOneConflictPerAggregate(): boolean { return false; } getDisplayPathForLocalConflict(workspaceFilePath: string): string { return workspaceFilePath; } hasContent(): boolean { return this.typeDefObj.hasContent; } hasParent(): boolean { return !!this.typeDefObj.parent; } getAggregateFullNameFromComponentFailure(componentFailure): string { return componentFailure.fullName; } getAggregateFullNameFromMdapiPackagePath(mdapiPackagePath: string): string { return PathUtil.getFileName(mdapiPackagePath); } getDisplayNameForRemoteChange(sourceMemberType: string): string { return this.typeDefObj.metadataName; } deleteSupported(workspaceFullName: string): boolean { return this.typeDefObj.deleteSupported && !this.isStandardMember(workspaceFullName); } getChildMetadataTypes(): string[] { if (this.typeDefObj.childXmlNames) { return this.typeDefObj.childXmlNames; } return []; } entityExistsInWorkspace(metadataFilePath: string): boolean { return fs.existsSync(metadataFilePath); } validateDeletedContentPath(deletedContentPath: string, contentPaths: string[], metadataRegistry): void { return; } isContentPath(sourcePath: string): boolean { return this.typeDefObj.hasContent && !sourcePath.endsWith(MetadataRegistry.getMetadataFileExt()); } getComponentFailureWorkspaceContentPath(metadataFilePath: string, workspaceContentPaths: string[]): string { return workspaceContentPaths[0]; } getWorkspaceFullNameFromComponentFailure(componentFailure): string { return this.getAggregateFullNameFromComponentFailure(componentFailure); } getDeprecationMessage(fullName?: string): string { return; } componentFailureIsInMetadataFile(componentFileName: string): boolean { return componentFileName.endsWith(MetadataRegistry.getMetadataFileExt()) || !this.typeDefObj.hasContent; } parseSourceMemberForMetadataRetrieve( sourceMemberName: string, sourceMemberType: string, isNameObsolete: boolean ): any { return { fullName: sourceMemberName, type: sourceMemberType, isNameObsolete, }; } isContainerValid(container): boolean { return true; } shouldGetMetadataTranslation(): boolean { return true; } shouldDeleteWorkspaceAggregate(metadataType: string): boolean { return metadataType === this.getAggregateMetadataName(); } protected debug(message: () => string) { if (this._debug.enabled) { this._debug(message()); } } }
the_stack
import { workspace, extensions, window, WorkspaceFolder, commands } from "vscode"; import { MUSIC_TIME_EXT_ID, launch_url, MUSIC_TIME_PLUGIN_ID, MUSIC_TIME_TYPE, SOFTWARE_FOLDER, CODE_TIME_EXT_ID } from "./Constants"; import { CodyResponse, CodyResponseType } from "cody-music"; import { getItem } from "./managers/FileManager"; import { isGitProject } from "./repo/GitUtil"; import { execCmd } from "./managers/ExecManager"; const fileIt = require("file-it"); const moment = require("moment-timezone"); const open = require("open"); const fs = require("fs"); const os = require("os"); const crypto = require("crypto"); export const alpha = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; export const MARKER_WIDTH = 4; const NUMBER_IN_EMAIL_REGEX = new RegExp("^\\d+\\+"); const dayFormat = "YYYY-MM-DD"; const dayTimeFormat = "LLLL"; export function getPluginId() { return MUSIC_TIME_PLUGIN_ID; } export function getPluginName() { return MUSIC_TIME_EXT_ID; } export function getEditorName() { return 'vscode'; } export function getPluginType() { return MUSIC_TIME_TYPE; } export function getVersion() { const extension = extensions.getExtension(MUSIC_TIME_EXT_ID); return extension.packageJSON.version; } export function isCodeTimeMetricsFile(fileName) { fileName = fileName || ""; if (fileName.includes(SOFTWARE_FOLDER) && fileName.includes("CodeTime")) { return true; } return false; } export function isCodeTimeTimeInstalled() { const codeTimeExt = extensions.getExtension(CODE_TIME_EXT_ID); return !!codeTimeExt; } export function musicTimeExtInstalled() { const musicTimeExt = extensions.getExtension(MUSIC_TIME_EXT_ID); return musicTimeExt ? true : false; } /** * These will return the workspace folders. * use the uri.fsPath to get the full path * use the name to get the folder name */ export function getWorkspaceFolders(): WorkspaceFolder[] { let folders = []; if (workspace.workspaceFolders && workspace.workspaceFolders.length > 0) { for (let i = 0; i < workspace.workspaceFolders.length; i++) { let workspaceFolder = workspace.workspaceFolders[i]; let folderUri = workspaceFolder.uri; if (folderUri && folderUri.fsPath) { folders.push(workspaceFolder); } } } return folders; } export function getActiveProjectWorkspace(): WorkspaceFolder { const activeDocPath = findFirstActiveDirectoryOrWorkspaceDirectory(); if (activeDocPath) { if (workspace.workspaceFolders && workspace.workspaceFolders.length > 0) { for (let i = 0; i < workspace.workspaceFolders.length; i++) { const workspaceFolder = workspace.workspaceFolders[i]; const folderPath = workspaceFolder.uri.fsPath; if (activeDocPath.indexOf(folderPath) !== -1) { return workspaceFolder; } } } } return null; } export function findFirstActiveDirectoryOrWorkspaceDirectory(): string { if (getNumberOfTextDocumentsOpen() > 0) { // check if the .software/CodeTime has already been opened for (let i = 0; i < workspace.textDocuments.length; i++) { let docObj = workspace.textDocuments[i]; if (docObj.fileName) { const dir = getRootPathForFile(docObj.fileName); if (dir) { return dir; } } } } const folder: WorkspaceFolder = getFirstWorkspaceFolder(); if (folder) { return folder.uri.fsPath; } return ""; } export function getFirstWorkspaceFolder(): WorkspaceFolder { const workspaceFolders: WorkspaceFolder[] = getWorkspaceFolders(); if (workspaceFolders && workspaceFolders.length) { return workspaceFolders[0]; } return null; } export function getRootPaths() { let paths = []; if (workspace.workspaceFolders && workspace.workspaceFolders.length > 0) { for (let i = 0; i < workspace.workspaceFolders.length; i++) { let workspaceFolder = workspace.workspaceFolders[i]; let folderUri = workspaceFolder.uri; if (folderUri && folderUri.fsPath) { paths.push(folderUri.fsPath); } } } return paths; } export function getNumberOfTextDocumentsOpen() { return workspace.textDocuments ? workspace.textDocuments.length : 0; } export function getRootPathForFile(fileName) { let folder = getProjectFolder(fileName); if (folder) { return folder.uri.fsPath; } return null; } export function getProjectFolder(fileName) { let liveshareFolder = null; if (workspace.workspaceFolders && workspace.workspaceFolders.length > 0) { for (let i = 0; i < workspace.workspaceFolders.length; i++) { let workspaceFolder = workspace.workspaceFolders[i]; if (workspaceFolder.uri) { let isVslsScheme = workspaceFolder.uri.scheme === "vsls" ? true : false; if (isVslsScheme) { liveshareFolder = workspaceFolder; } let folderUri = workspaceFolder.uri; if (folderUri && folderUri.fsPath && !isVslsScheme && fileName.includes(folderUri.fsPath)) { return workspaceFolder; } } } } // wasn't found but if liveshareFolder was found, return that if (liveshareFolder) { return liveshareFolder; } return null; } export function isLinux() { return isWindows() || isMac() ? false : true; } // process.platform return the following... // -> 'darwin', 'freebsd', 'linux', 'sunos' or 'win32' export function isWindows() { return process.platform.indexOf("win32") !== -1; } export function isMac() { return process.platform.indexOf("darwin") !== -1; } export async function getHostname() { let hostname = execCmd("hostname"); return hostname; } export function getOs() { let parts = []; let osType = os.type(); if (osType) { parts.push(osType); } let osRelease = os.release(); if (osRelease) { parts.push(osRelease); } let platform = os.platform(); if (platform) { parts.push(platform); } if (parts.length > 0) { return parts.join("_"); } return ""; } export async function getOsUsername() { let username = os.userInfo().username; if (!username || username.trim() === "") { username = execCmd("whoami"); } return username; } export async function showOfflinePrompt(addReconnectMsg = false) { // shows a prompt that we're not able to communicate with the app server let infoMsg = "Our service is temporarily unavailable. "; if (addReconnectMsg) { infoMsg += "We will try to reconnect again in 10 minutes. Your status bar will not update at this time."; } else { infoMsg += "Please try again later."; } // set the last update time so we don't try to ask too frequently window.showInformationMessage(infoMsg, ...["OK"]); } export function nowInSecs() { return Math.round(Date.now() / 1000); } export function getOffsetSeconds() { let d = new Date(); return d.getTimezoneOffset() * 60; } export function getNowTimes() { const now = moment.utc(); const now_in_sec = now.unix(); const offset_in_sec = moment().utcOffset() * 60; const local_now_in_sec = now_in_sec + offset_in_sec; const utcDay = now.format(dayFormat); const day = moment().format(dayFormat); const localDayTime = moment().format(dayTimeFormat); return { now, now_in_sec, offset_in_sec, local_now_in_sec, utcDay, day, localDayTime, }; } export function getFormattedDay(unixSeconds) { return moment.unix(unixSeconds).format(dayFormat); } export function coalesceNumber(val, defaultVal = 0) { if (val === null || val === undefined || isNaN(val)) { return defaultVal; } return val; } export function randomCode() { return crypto .randomBytes(16) .map((value) => alpha.charCodeAt(Math.floor((value * alpha.length) / 256))) .toString(); } export function deleteFile(file) { // if the file exists, get it if (fs.existsSync(file)) { fs.unlinkSync(file); } } /** * Format pathString if it is on Windows. Convert `c:\` like string to `C:\` * @param pathString */ export function formatPathIfNecessary(pathString: string) { if (process.platform === "win32") { pathString = pathString.replace(/^([a-zA-Z])\:\\/, (_, $1) => `${$1.toUpperCase()}:\\`); } return pathString; } export function normalizeGithubEmail(email: string, filterOutNonEmails = true) { if (email) { if (filterOutNonEmails && (email.endsWith("github.com") || email.includes("users.noreply"))) { return null; } else { const found = email.match(NUMBER_IN_EMAIL_REGEX); if (found && email.includes("users.noreply")) { // filter out the ones that look like // 2342353345+username@users.noreply.github.com" return null; } } } return email; } export function getSongDisplayName(name) { if (!name) { return ""; } let displayName = ""; name = name.trim(); if (name.length > 14) { const parts = name.split(" "); for (let i = 0; i < parts.length; i++) { displayName = `${displayName} ${parts[i]}`; if (displayName.length >= 12) { if (displayName.length > 14) { // trim it down to at least 14 displayName = `${displayName.substring(0, 14)}`; } displayName = `${displayName}..`; break; } } } else { displayName = name; } return displayName.trim(); } export async function getGitEmail() { let projectDirs = getRootPaths(); if (!projectDirs || projectDirs.length === 0) { return null; } for (let i = 0; i < projectDirs.length; i++) { let projectDir = projectDirs[i]; if (projectDir && isGitProject(projectDir)) { let email = execCmd("git config user.email", projectDir); if (email) { /** * // normalize the email, possible github email types * shupac@users.noreply.github.com * 37358488+rick-software@users.noreply.github.com */ email = normalizeGithubEmail(email); return email; } } } return null; } export function launchWebUrl(url) { open(url); } export function launchMusicAnalytics() { const isRegistered = checkRegistration(); if (!isRegistered) { return; } open(`${launch_url}/music`); } export function checkRegistration(showSignup = true) { if (!getItem("name")) { if (showSignup) { showModalSignupPrompt("Sign up or register for a web.com account at Software.com to view your most productive music."); } return false; } return true; } export function showModalSignupPrompt(msg: string) { window .showInformationMessage( msg, { modal: true, }, "Sign up" ) .then(async (selection) => { if (selection === "Sign up") { commands.executeCommand("musictime.signUpAccount"); } }); } /** * humanize the minutes */ export function humanizeMinutes(min) { min = parseInt(min, 0) || 0; let str = ""; if (min === 60) { str = "1 hr"; } else if (min > 60) { let hrs = parseFloat(min) / 60; if (hrs % 1 === 0) { str = hrs.toFixed(0) + " hrs"; } else { str = (Math.round(hrs * 10) / 10).toFixed(1) + " hrs"; } } else if (min === 1) { str = "1 min"; } else { // less than 60 seconds str = min.toFixed(0) + " min"; } return str; } export function showInformationMessage(message: string) { return window.showInformationMessage(`${message}`); } export function showWarningMessage(message: string) { return window.showWarningMessage(`${message}`); } export function createUriFromTrackId(track_id: string) { if (track_id && !track_id.includes("spotify:track:")) { track_id = `spotify:track:${track_id}`; } return track_id; } export function createUriFromPlaylistId(playlist_id: string) { if (playlist_id && !playlist_id.includes("spotify:playlist:")) { playlist_id = `spotify:playlist:${playlist_id}`; } return playlist_id; } export function createSpotifyIdFromUri(id: string) { if (id && id.indexOf("spotify:") === 0) { return id.substring(id.lastIndexOf(":") + 1); } return id; } export function getCodyErrorMessage(response: CodyResponse) { if (response && response.error && response.error.response) { return response.error.response.data.error.message; } else if (response.state === CodyResponseType.Failed) { return response.message; } return ""; } export function getFileDataArray(file) { let payloads: any[] = fileIt.readJsonArraySync(file); return payloads; }
the_stack
import { _, DefaultDialogs, Dialogs, Mustache, StringUtils } from "./brackets-modules"; import * as ErrorHandler from "./ErrorHandler"; import * as Events from "./Events"; import EventEmitter from "./EventEmitter"; import * as Git from "./git/GitCli"; import * as Git2 from "./git/Git"; import * as Preferences from "./Preferences"; import * as ProgressDialog from "./dialogs/Progress"; import * as Promise from "bluebird"; import * as PullDialog from "./dialogs/Pull"; import * as PushDialog from "./dialogs/Push"; import * as Strings from "strings"; import * as Utils from "./Utils"; const gitRemotesPickerTemplate = require("text!templates/git-remotes-picker.html"); let $selectedRemote = null; let $remotesDropdown = null; let $gitPanel = null; let $gitPush = null; function initVariables() { $gitPanel = $("#git-panel"); $selectedRemote = $gitPanel.find(".git-selected-remote"); $remotesDropdown = $gitPanel.find(".git-remotes-dropdown"); $gitPush = $gitPanel.find(".git-push"); } function getDefaultRemote(allRemotes) { const defaultRemotes = Preferences.get("defaultRemotes") || {}; let candidate = defaultRemotes[Preferences.get("currentGitRoot")]; const exists = _.find(allRemotes, (remote) => remote.name === candidate); if (!exists) { candidate = null; if (allRemotes.length > 0) { candidate = _.first(allRemotes).name; } } return candidate; } function setDefaultRemote(remoteName) { const defaultRemotes = Preferences.get("defaultRemotes") || {}; defaultRemotes[Preferences.get("currentGitRoot")] = remoteName; Preferences.persist("defaultRemotes", defaultRemotes); } function clearRemotePicker() { $selectedRemote .html("&mdash;") .data("remote", null); } function selectRemote(remoteName, type) { if (!remoteName) { return clearRemotePicker(); } // Set as default remote only if is a normal git remote if (type === "git") { setDefaultRemote(remoteName); } // Disable pull if it is not a normal git remote $gitPanel.find(".git-pull").prop("disabled", type !== "git"); // Enable push and set selected-remote-type to Git push button by type of remote $gitPush .prop("disabled", false) .attr("x-selected-remote-type", type); // Update remote name of $selectedRemote $selectedRemote .text(remoteName) .attr("data-type", type) // use attr to apply CSS styles .data("remote", remoteName); } function refreshRemotesPicker() { Git.getRemotes().then((remotes) => { // Set default remote name and cache the remotes dropdown menu const defaultRemoteName = getDefaultRemote(remotes); // Disable Git-push and Git-pull if there are not remotes defined $gitPanel .find(".git-pull, .git-push, .git-fetch") .prop("disabled", remotes.length === 0); // Add options to change remote remotes.forEach((remote) => remote.deletable = remote.name !== "origin"); // Pass to Mustache the needed data const compiledTemplate = Mustache.render(gitRemotesPickerTemplate, { Strings, remotes }); // Inject the rendered template inside the $remotesDropdown $remotesDropdown.html(compiledTemplate); // Notify others that they may add more stuff to this dropdown EventEmitter.emit(Events.REMOTES_REFRESH_PICKER); // TODO: is it possible to wait for listeners to finish? // TODO: if there're no remotes but there are some ftp remotes // we need to adjust that something other may be put as default // low priority if (remotes.length > 0) { selectRemote(defaultRemoteName, "git"); } else { clearRemotePicker(); } }).catch((err) => ErrorHandler.showError(err, "Getting remotes failed!")); } function handleRemoteCreation() { return Utils.askQuestion(Strings.CREATE_NEW_REMOTE, Strings.ENTER_REMOTE_NAME) .then((name) => { return Utils.askQuestion(Strings.CREATE_NEW_REMOTE, Strings.ENTER_REMOTE_URL).then((url) => { return [name, url]; }); }) .spread((name, url) => { return Git.createRemote(name, url).then(() => { return refreshRemotesPicker(); }); }) .catch((err) => { if (!ErrorHandler.equals(err, Strings.USER_ABORTED)) { ErrorHandler.showError(err, "Remote creation failed"); } }); } function deleteRemote(remoteName) { return Utils.askQuestion( Strings.DELETE_REMOTE, StringUtils.format(Strings.DELETE_REMOTE_NAME, remoteName), { booleanResponse: true } ) .then((response) => { if (response === true) { return Git.deleteRemote(remoteName).then(() => refreshRemotesPicker()); } return null; }) .catch((err) => ErrorHandler.logError(err)); } function showPushResult(result) { if (typeof result.remoteUrl === "string") { result.remoteUrl = Utils.encodeSensitiveInformation(result.remoteUrl); } const template = [ "<h3>{{flagDescription}}</h3>", "Info:", "Remote url - {{remoteUrl}}", "Local branch - {{from}}", "Remote branch - {{to}}", "Summary - {{summary}}", "<h4>Status - {{status}}</h4>" ].join("<br>"); Dialogs.showModalDialog( DefaultDialogs.DIALOG_ID_INFO, Strings.GIT_PUSH_RESPONSE, // title Mustache.render(template, result) // message ); } function pushToRemote(remote) { if (!remote) { const msg = "No remote has been selected for push!"; return ErrorHandler.showError(new Error(msg), msg); } return PushDialog.show({ remote }) .then((pushConfig) => { let q: Promise<any> = Promise.resolve(); const additionalArgs = []; if (pushConfig.tags) { additionalArgs.push("--tags"); } // set a new tracking branch if desired if (pushConfig.branch && pushConfig.setBranchAsTracking) { q = q.then(() => Git.setUpstreamBranch(pushConfig.remote, pushConfig.branch)); } // put username and password into remote url if (pushConfig.remoteUrlNew) { q = q.then(() => Git2.setRemoteUrl(pushConfig.remote, pushConfig.remoteUrlNew)); } // do the pull itself (we are not using pull command) q = q.then(() => { let op; if (pushConfig.pushToNew) { op = Git2.pushToNewUpstream(pushConfig.remote, pushConfig.branch); } else if (pushConfig.strategy === "DEFAULT") { op = Git.push(pushConfig.remote, pushConfig.branch, additionalArgs); } else if (pushConfig.strategy === "FORCED") { op = Git2.pushForced(pushConfig.remote, pushConfig.branch); } else if (pushConfig.strategy === "DELETE_BRANCH") { op = Git2.deleteRemoteBranch(pushConfig.remote, pushConfig.branch); } return ProgressDialog.show(op) .then((result) => { return ProgressDialog.waitForClose().then(() => { showPushResult(result); }); }) .catch((err) => ErrorHandler.showError(err, "Pushing to remote failed")); }); // restore original url if desired if (pushConfig.remoteUrlRestore) { q = q.finally(() => Git2.setRemoteUrl(pushConfig.remote, pushConfig.remoteUrlRestore)); } return q.finally(() => EventEmitter.emit(Events.REFRESH_ALL)); }) .catch((err) => { // when dialog is cancelled, there's no error if (err) { ErrorHandler.showError(err, "Pushing operation failed"); } }); } function pullFromRemote(remote) { if (!remote) { const msg = "No remote has been selected for pull!"; return ErrorHandler.showError(new Error(msg), msg); } return PullDialog.show({ remote }) .then((pullConfig) => { let q: Promise<any> = Promise.resolve(); // set a new tracking branch if desired if (pullConfig.branch && pullConfig.setBranchAsTracking) { q = q.then(() => Git.setUpstreamBranch(pullConfig.remote, pullConfig.branch)); } // put username and password into remote url if (pullConfig.remoteUrlNew) { q = q.then(() => Git2.setRemoteUrl(pullConfig.remote, pullConfig.remoteUrlNew)); } // do the pull itself (we are not using pull command) q = q.then(() => { // fetch the remote first return ProgressDialog.show(Git.fetchRemote(pullConfig.remote)) .then(() => { if (pullConfig.strategy === "DEFAULT") { return Git.mergeRemote(pullConfig.remote, pullConfig.branch); } else if (pullConfig.strategy === "AVOID_MERGING") { return Git.mergeRemote(pullConfig.remote, pullConfig.branch, true); } else if (pullConfig.strategy === "MERGE_NOCOMMIT") { return Git.mergeRemote(pullConfig.remote, pullConfig.branch, false, true); } else if (pullConfig.strategy === "REBASE") { return Git.rebaseRemote(pullConfig.remote, pullConfig.branch); } else if (pullConfig.strategy === "RESET") { return Git.resetRemote(pullConfig.remote, pullConfig.branch); } throw new Error(`Unexpected pullConfig.strategy: ${pullConfig.strategy}`); }) .then((result) => { return ProgressDialog.waitForClose().then(() => { return Utils.showOutput(result, Strings.GIT_PULL_RESPONSE); }); }) .catch((err) => ErrorHandler.showError(err, "Pulling from remote failed")); }); // restore original url if desired if (pullConfig.remoteUrlRestore) { q = q.finally(() => Git2.setRemoteUrl(pullConfig.remote, pullConfig.remoteUrlRestore)); } return q.finally(() => EventEmitter.emit(Events.REFRESH_ALL)); }) .catch((err) => { // when dialog is cancelled, there's no error if (err) { ErrorHandler.showError(err, "Pulling operation failed"); } }); } function handleFetch(silent = false) { // Tell the rest of the plugin that the fetch has started EventEmitter.emit(Events.FETCH_STARTED); let q; if (!silent) { // If it's not a silent fetch show a progress window q = ProgressDialog.show(Git.fetchAllRemotes()) .catch((err) => ErrorHandler.showError(err)) .then(ProgressDialog.waitForClose); } else { // Else fetch in the background q = Git.fetchAllRemotes() .catch((err) => ErrorHandler.logError(err)); } // Tell the rest of the plugin that the fetch has completed return q.finally(() => EventEmitter.emit(Events.FETCH_COMPLETE)); } // Event subscriptions EventEmitter.on(Events.GIT_ENABLED, () => { initVariables(); refreshRemotesPicker(); }); EventEmitter.on(Events.HANDLE_REMOTE_PICK, (event) => { const $remote = $(event.target).closest(".remote-name"); const remoteName = $remote.data("remote-name"); const type = $remote.data("type"); selectRemote(remoteName, type); EventEmitter.emit(Events.REFRESH_COUNTERS); }); EventEmitter.on(Events.HANDLE_REMOTE_CREATE, () => { handleRemoteCreation(); }); EventEmitter.on(Events.HANDLE_REMOTE_DELETE, (event) => { const remoteName = $(event.target).closest(".remote-name").data("remote-name"); deleteRemote(remoteName); }); EventEmitter.on(Events.HANDLE_PULL, () => { const remoteName = $selectedRemote.data("remote"); pullFromRemote(remoteName); }); EventEmitter.on(Events.HANDLE_PUSH, () => { const remoteName = $selectedRemote.data("remote"); pushToRemote(remoteName); }); EventEmitter.on(Events.HANDLE_FETCH, () => { handleFetch(); });
the_stack
import { debounce, includes } from 'lodash'; import { Models } from 'omnisharp-client'; import { Observable, Subject, Subscription } from 'rxjs'; import { CompositeDisposable, Disposable, IDisposable } from 'ts-disposables'; import { Omni } from '../server/omni'; interface IDecoration { destroy(): any; getMarker(): Atom.Marker; getProperties(): any; setProperties(props: any): any; } class CodeLens implements IFeature { public required = false; public title = 'Code Lens'; public description = 'Adds support for displaying references in the editor.'; private disposable: CompositeDisposable; private decorations = new WeakMap<Atom.TextEditor, Set<Lens>>(); public activate() { this.disposable = new CompositeDisposable(); this.disposable.add(Omni.eachEditor((editor, cd) => { cd.add(Disposable.create(() => { const markers = this.decorations.get(editor); if (markers) { markers.forEach(marker => marker.dispose()); } this.decorations.delete(editor); })); cd.add(atom.config.observe('editor.fontSize', (size: number) => { const decorations = this.decorations.get(editor); const lineHeight = editor.getLineHeightInPixels(); if (decorations && lineHeight) { decorations.forEach(decoration => decoration.updateTop(lineHeight)); } })); })); this.disposable.add(Omni.switchActiveEditor((editor, cd) => { const items = this.decorations.get(editor); if (!items) { this.decorations.set(editor, new Set<Lens>()); } const subject = new Subject<boolean>(); cd.add(subject .filter(x => !!x && !editor.isDestroyed()) .distinctUntilChanged(x => !!x) .debounceTime(500) .switchMap(() => this.updateCodeLens(editor)) .subscribe() ); const bindDidChange = () => { const didChange = editor.getBuffer().onDidChange(() => { didChange.dispose(); cd.remove(didChange); subject.next(false); }); cd.add(didChange); }; cd.add(editor.getBuffer().onDidStopChanging(debounce(() => { if (!subject.closed) { subject.next(true); } bindDidChange(); }, 5000))); cd.add(editor.getBuffer().onDidSave(() => subject.next(true))); cd.add(editor.getBuffer().onDidReload(() => subject.next(true))); cd.add(Observable.timer(1000).subscribe(() => subject.next(true))); cd.add(editor.onDidChangeScrollTop(() => this.updateDecoratorVisiblility(editor))); cd.add(atom.commands.onWillDispatch((event: Event) => { if (includes(['omnisharp-atom:toggle-dock', 'omnisharp-atom:show-dock', 'omnisharp-atom:hide-dock'], event.type)) { this.updateDecoratorVisiblility(editor); } })); cd.add(subject); this.updateDecoratorVisiblility(editor); })); } public updateDecoratorVisiblility(editor: Atom.TextEditor) { if (!this.decorations.has(editor)) { this.decorations.set(editor, new Set<Lens>()); } const decorations = this.decorations.get(editor); decorations.forEach(decoration => decoration.updateVisible()); } public dispose() { this.disposable.dispose(); } public updateCodeLens(editor: Atom.TextEditor) { if (!this.decorations.has(editor)) { this.decorations.set(editor, new Set<Lens>()); } const decorations = this.decorations.get(editor); const updated = new WeakSet<Lens>(); if (editor.isDestroyed()) { return Observable.empty<number>(); } return Omni.request(editor, solution => solution.currentfilemembersasflat({ Buffer: null, Changes: null })) .filter(fileMembers => !!fileMembers) .flatMap(fileMembers => fileMembers) .concatMap(fileMember => { const range: TextBuffer.Range = <any>editor.getBuffer().rangeForRow(fileMember.Line, false); // TODO: Block decorations // const marker: Atom.Marker = (<any>editor).markScreenPosition([fileMember.Line, 0]); const marker: Atom.Marker = (<any>editor).markBufferRange(range, { invalidate: 'inside' }); let lens: Lens; const iteratee = decorations.values(); let decoration = iteratee.next(); while (!decoration.done) { if (decoration.value.isEqual(marker)) { lens = decoration.value; break; } decoration = iteratee.next(); } if (lens) { updated.add(lens); lens.invalidate(); } else { lens = new Lens(editor, fileMember, marker, range, Disposable.create(() => { decorations.delete(lens); })); updated.add(lens); decorations.add(lens); } return lens.updateVisible(); }) .do({ complete: () => { // Remove all old/missing decorations decorations.forEach(lens => { if (lens && !updated.has(lens)) { lens.dispose(); } }); } }); } } function isLineVisible(editor: Atom.TextEditor, line: number) { const element: any = atom.views.getView(editor); const top = element.getFirstVisibleScreenRow(); const bottom = element.getLastVisibleScreenRow(); if (line <= top || line >= bottom) { return false; } return true; } // tslint:disable-next-line:max-classes-per-file export class Lens implements IDisposable { public loaded: boolean = false; private _update: Subject<boolean>; private _row: number; private _decoration: IDecoration; private _disposable = new CompositeDisposable(); private _element: HTMLDivElement; private _updateObservable: Observable<number>; private _path: string; private _issueUpdate = debounce((isVisible: boolean) => { if (!this._update.closed) { this._update.next(isVisible); } }, 250); public constructor( private _editor: Atom.TextEditor, private _member: Models.QuickFix, private _marker: Atom.Marker, private _range: TextBuffer.Range, disposer: IDisposable) { this._row = _range.getRows()[0]; this._update = new Subject<any>(); this._disposable.add(this._update); this._path = _editor.getPath(); this._updateObservable = this._update .filter(x => !!x) .flatMap(() => Omni.request(this._editor, solution => solution.findusages({ FileName: this._path, Column: this._member.Column + 1, Line: this._member.Line, Buffer: null, Changes: null }, { silent: true })) ) .filter(x => x && x.QuickFixes && !!x.QuickFixes.length) .map(x => x && x.QuickFixes && x.QuickFixes.length - 1) .share(); this._disposable.add(this._updateObservable .take(1) .filter(x => x > 0) .do(() => this.loaded = true) .subscribe(x => this._decorate(x))); this._disposable.add(disposer); this._disposable.add(this._marker.onDidDestroy(() => { this.dispose(); })); } public updateVisible() { const isVisible = this._isVisible(); this._updateDecoration(isVisible); let result: Observable<number>; if (isVisible) { result = this._updateObservable.take(1); } else { result = Observable.empty<number>(); } this._issueUpdate(isVisible); return result; } public updateTop(lineHeight: number) { if (this._element) { this._element.style.top = `-${lineHeight}px`; } } public invalidate() { const self: Subscription = this._updateObservable .take(1) .do(() => this._disposable.remove(self)) .subscribe(x => { if (x <= 0) { this.dispose(); } else { if (this._element) { (this._element.textContent = x.toString()); } } }); this._disposable.add(self); } public isEqual(marker: Atom.Marker) { return this._marker.isEqual(<any>marker); } public dispose() { return this._disposable.dispose(); } private _isVisible() { return isLineVisible(this._editor, this._row); } private _updateDecoration(isVisible: boolean) { if (this._decoration && this._element) { const element = this._element; if (isVisible && element.style.display === 'none') { element.style.display = ''; } else if (element.style.display !== 'none') { element.style.display = 'none'; } } } private _decorate(count: number) { const lineHeight = this._editor.getLineHeightInPixels(); const element = this._element = document.createElement('div'); element.style.position = 'relative'; element.style.top = `-${lineHeight}px`; element.style.left = '16px'; element.classList.add('highlight-info', 'badge', 'badge-small'); element.textContent = count.toString(); element.onclick = () => Omni.request( this._editor, s => s.findusages({ FileName: this._path, Column: this._member.Column + 1, Line: this._member.Line, Buffer: null, Changes: null })); // TODO: Block decorations // this._decoration = <any>this._editor.decorateMarker(this._marker, { type: "block", class: `codelens`, item: this._element, position: "before" }); this._decoration = <any>this._editor.decorateMarker(this._marker, { type: 'overlay', class: `codelens`, item: this._element, position: 'head' }); this._disposable.add(Disposable.create(() => { this._element.remove(); if (this._decoration) { this._decoration.destroy(); } this._element = null; })); const isVisible = isLineVisible(this._editor, this._row); if (!isVisible) { element.style.display = 'none'; } return this._decoration; } } export const codeLens = new CodeLens();
the_stack
export type RecoveryId = 0 | 1 | 2 | 3; export interface RecoverableSignature { recoveryId: RecoveryId; signature: Uint8Array; } /** * An object which exposes a set of purely-functional Secp256k1 methods. * * Under the hood, this object uses a [[Secp256k1Wasm]] instance to provide it's * functionality. Because WebAssembly modules are dynamically-instantiated at * runtime, this object must be created and awaited from `instantiateSecp256k1` * or `instantiateSecp256k1Bytes`. * * **These methods do not check the length of provided parameters. Calling them * with improperly-sized parameters will likely cause incorrect behavior or * runtime errors.** * * ## Example * * ```typescript * import { instantiateSecp256k1 } from 'libauth'; * import { msgHash, pubkey, sig } from './somewhere'; * * (async () => { * const secp256k1 = await instantiateSecp256k1(); * secp256k1.verifySignatureDERLowS(sig, pubkey, msgHash) * ? console.log('🚀 Signature valid') * : console.log('❌ Signature invalid'); * })(); * ``` */ export interface Secp256k1 { /** * Tweak a privateKey by adding `tweakValue` to it. * * Throws if the private key is invalid or if the addition failed. * * @param privateKey - a valid secp256k1 private key * @param tweakValue - 256 bit value to tweak by (BE) */ readonly addTweakPrivateKey: ( privateKey: Uint8Array, tweakValue: Uint8Array ) => Uint8Array; /** * Tweak a `publicKey` by adding `tweakValue` times the generator to it. * * Throws if the provided public key could not be parsed, is not valid or if * the addition failed. * * The returned public key will be in compressed format. * * @param publicKey - a public key. * @param tweakValue - 256 bit value to tweak by (BE) */ readonly addTweakPublicKeyCompressed: ( publicKey: Uint8Array, tweakValue: Uint8Array ) => Uint8Array; /** * Tweak a `publicKey` by adding `tweakValue` times the generator to it. * * Throws if the provided public key could not be parsed, is not valid or if * the addition failed. * * The returned public key will be in uncompressed format. * * @param publicKey - a public key. * @param tweakValue - 256 bit value to tweak by (BE) */ readonly addTweakPublicKeyUncompressed: ( publicKey: Uint8Array, tweakValue: Uint8Array ) => Uint8Array; /** * Compress a valid ECDSA public key. Returns a public key in compressed * format (33 bytes, header byte 0x02 or 0x03). * * This function supports parsing compressed (33 bytes, header byte 0x02 or * 0x03), uncompressed (65 bytes, header byte 0x04), or hybrid (65 bytes, * header byte 0x06 or 0x07) format public keys. * * Throws if the provided public key could not be parsed or is not valid. * * @param privateKey - a public key to compress */ readonly compressPublicKey: (publicKey: Uint8Array) => Uint8Array; /** * Derive a compressed public key from a valid secp256k1 private key. * * Throws if the provided private key is too large (see `validatePrivateKey`). * * @param privateKey - a valid secp256k1, 32-byte private key */ readonly derivePublicKeyCompressed: (privateKey: Uint8Array) => Uint8Array; /** * Derive an uncompressed public key from a valid secp256k1 private key. * * Throws if the provided private key is too large (see `validatePrivateKey`). * * @param privateKey - a valid secp256k1, 32-byte private key */ readonly derivePublicKeyUncompressed: (privateKey: Uint8Array) => Uint8Array; /** * Malleate a compact-encoded ECDSA signature. * * This is done by negating the S value modulo the order of the curve, * "flipping" the sign of the random point R which is not included in the * signature. * * Throws if compact-signature parsing fails. * * @param signature - a compact-encoded ECDSA signature to malleate, max 72 * bytes */ readonly malleateSignatureCompact: (signature: Uint8Array) => Uint8Array; /** * Malleate a DER-encoded ECDSA signature. * * This is done by negating the S value modulo the order of the curve, * "flipping" the sign of the random point R which is not included in the * signature. * * Throws if DER-signature parsing fails. * * @param signature - a DER-encoded ECDSA signature to malleate, max 72 bytes */ readonly malleateSignatureDER: (signature: Uint8Array) => Uint8Array; /** * Tweak a privateKey by multiplying it by a `tweakValue`. * * @param privateKey - a valid secp256k1 private key * @param tweakValue - 256 bit value to tweak by (BE) * */ readonly mulTweakPrivateKey: ( privateKey: Uint8Array, tweakValue: Uint8Array ) => Uint8Array; /** * Tweak a `publicKey` by multiplying `tweakValue` to it. * * Throws if the provided public key could not be parsed, is not valid or if * the multiplication failed. * The returned public key will be in compressed format. * * @param publicKey - a public key. * @param tweakValue - 256 bit value to tweak by (BE) */ readonly mulTweakPublicKeyCompressed: ( publicKey: Uint8Array, tweakValue: Uint8Array ) => Uint8Array; /** * Tweak a `publicKey` by multiplying `tweakValue` to it. * * Throws if the provided public key could not be parsed, is not valid or if * the multiplication failed. * The returned public key will be in uncompressed format. * * @param publicKey - a public key. * @param tweakValue - 256 bit value to tweak by (BE) */ readonly mulTweakPublicKeyUncompressed: ( publicKey: Uint8Array, tweakValue: Uint8Array ) => Uint8Array; /** * Normalize a compact-encoded ECDSA signature to lower-S form. * * Throws if compact-signature parsing fails. * * @param signature - a compact-encoded ECDSA signature to normalize to * lower-S form, max 72 bytes */ readonly normalizeSignatureCompact: (signature: Uint8Array) => Uint8Array; /** * Normalize a DER-encoded ECDSA signature to lower-S form. * * Throws if DER-signature parsing fails. * * @param signature - a DER-encoded ECDSA signature to normalize to lower-S * form, max 72 bytes */ readonly normalizeSignatureDER: (signature: Uint8Array) => Uint8Array; /** * Compute a compressed public key from a valid signature, recovery number, * and the `messageHash` used to generate them. * * Throws if the provided arguments are mismatched. * * @param signature - an ECDSA signature in compact format * @param recovery - the recovery number * @param messageHash - the hash used to generate the signature and recovery * number */ readonly recoverPublicKeyCompressed: ( signature: Uint8Array, recoveryId: RecoveryId, messageHash: Uint8Array ) => Uint8Array; /** * Compute an uncompressed public key from a valid signature, recovery * number, and the `messageHash` used to generate them. * * Throws if the provided arguments are mismatched. * * @param signature - an ECDSA signature in compact format * @param recovery - the recovery number * @param messageHash - the hash used to generate the signature and recovery * number */ readonly recoverPublicKeyUncompressed: ( signature: Uint8Array, recoveryId: RecoveryId, messageHash: Uint8Array ) => Uint8Array; /** * Convert a compact-encoded ECDSA signature to DER encoding. * * Throws if parsing of compact-encoded signature fails. * * @param signature - a compact-encoded ECDSA signature to convert */ readonly signatureCompactToDER: (signature: Uint8Array) => Uint8Array; /** * Convert a DER-encoded ECDSA signature to compact encoding. * * Throws if parsing of DER-encoded signature fails. * * @param signature - a DER-encoded ECDSA signature to convert */ readonly signatureDERToCompact: (signature: Uint8Array) => Uint8Array; /** * Create an ECDSA signature in compact format. The created signature is * always in lower-S form and follows RFC 6979. * * Throws if the provided private key is too large (see `validatePrivateKey`). * * @param privateKey - a valid secp256k1 private key * @param messageHash - the 32-byte message hash to be signed */ readonly signMessageHashCompact: ( privateKey: Uint8Array, messageHash: Uint8Array ) => Uint8Array; /** * Create an ECDSA signature in DER format. The created signature is always in * lower-S form and follows RFC 6979. * * Throws if the provided private key is too large (see `validatePrivateKey`). * * @param privateKey - a valid secp256k1, 32-byte private key * @param messageHash - the 32-byte message hash to be signed */ readonly signMessageHashDER: ( privateKey: Uint8Array, messageHash: Uint8Array ) => Uint8Array; /** * Create an ECDSA signature in compact format. The created signature is * always in lower-S form and follows RFC 6979. * * Also returns a recovery number for use in the `recoverPublicKey*` * functions * * Throws if the provided private key is too large (see `validatePrivateKey`). * * @param privateKey - a valid secp256k1, 32-byte private key * @param messageHash - the 32-byte message hash to be signed */ readonly signMessageHashRecoverableCompact: ( privateKey: Uint8Array, messageHash: Uint8Array ) => RecoverableSignature; /** * Create a Secp256k1 EC-Schnorr-SHA256 signature (BCH construction). * * Signatures are 64-bytes, non-malleable, and support both batch validation * and multiparty signing. Nonces are generated using RFC6979, where the * Section 3.6, 16-byte ASCII "additional data" is set to `Schnorr+SHA256 `. * This avoids leaking a private key by inadvertently creating both an ECDSA * signature and a Schnorr signature using the same nonce. * * Throws if the provided private key is too large (see `validatePrivateKey`). * * @param privateKey - a valid secp256k1, 32-byte private key * @param messageHash - the 32-byte message hash to be signed */ readonly signMessageHashSchnorr: ( privateKey: Uint8Array, messageHash: Uint8Array ) => Uint8Array; /** * Uncompress a valid ECDSA public key. Returns a public key in uncompressed * format (65 bytes, header byte 0x04). * * This function supports parsing compressed (33 bytes, header byte 0x02 or * 0x03), uncompressed (65 bytes, header byte 0x04), or hybrid (65 bytes, * header byte 0x06 or 0x07) format public keys. * * Throws if the provided public key could not be parsed or is not valid. * * @param publicKey - a public key to uncompress */ readonly uncompressPublicKey: (publicKey: Uint8Array) => Uint8Array; /** * Verify that a private key is valid for secp256k1. Note, this library * requires all public keys to be provided as 32-byte Uint8Arrays (an array * length of 32). * * Nearly every 256-bit number is a valid secp256k1 private key. Specifically, * any 256-bit number greater than or equal to `0x01` and less than * `0xFFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFE BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140` * is a valid private key. This range is part of the definition of the * secp256k1 elliptic curve parameters. * * This method returns true if the private key is valid or false if it isn't. * * @param privateKey - a 32-byte private key to validate */ readonly validatePrivateKey: (privateKey: Uint8Array) => boolean; /** * Normalize a signature to lower-S form, then `verifySignatureCompactLowS`. * * @param signature - a compact-encoded ECDSA signature to verify, max 72 bytes * @param publicKey - a public key, in either compressed (33-byte) or * uncompressed (65-byte) format * @param messageHash - the 32-byte message hash signed by the signature */ readonly verifySignatureCompact: ( signature: Uint8Array, publicKey: Uint8Array, messageHash: Uint8Array ) => boolean; /** * Verify a compact-encoded ECDSA `signature` using the provided `publicKey` * and `messageHash`. This method also returns false if the signature is not * in normalized lower-S form. * * @param signature - a compact-encoded ECDSA signature to verify, max 72 bytes * @param publicKey - a public key, in either compressed (33-byte) or * uncompressed (65-byte) format * @param messageHash - the 32-byte message hash signed by the signature */ readonly verifySignatureCompactLowS: ( signature: Uint8Array, publicKey: Uint8Array, messageHash: Uint8Array ) => boolean; /** * Normalize a signature to lower-S form, then `verifySignatureDERLowS`. * * @param signature - a DER-encoded ECDSA signature to verify, max 72 bytes * @param publicKey - a public key, in either compressed (33-byte) or * uncompressed (65-byte) format * @param messageHash - the 32-byte message hash signed by the signature */ readonly verifySignatureDER: ( signature: Uint8Array, publicKey: Uint8Array, messageHash: Uint8Array ) => boolean; /** * Verify a DER-encoded ECDSA `signature` using the provided `publicKey` and * `messageHash`. This method also returns false if the signature is not in * normalized lower-S form. * * @param signature - a DER-encoded ECDSA signature to verify, max 72 bytes * @param publicKey - a public key, in either compressed (33-byte) or * uncompressed (65-byte) format * @param messageHash - the 32-byte message hash signed by the signature */ readonly verifySignatureDERLowS: ( signature: Uint8Array, publicKey: Uint8Array, messageHash: Uint8Array ) => boolean; /** * Verify a Secp256k1 EC-Schnorr-SHA256 signature (BCH construction). * * @param signature - a 64-byte schnorr signature to verify * @param publicKey - a public key, in either compressed (33-byte) or * uncompressed (65-byte) format * @param messageHash - the 32-byte message hash signed by the signature */ readonly verifySignatureSchnorr: ( signature: Uint8Array, publicKey: Uint8Array, messageHash: Uint8Array ) => boolean; }
the_stack
import inRange from 'lodash/inRange'; import isUndefined from 'lodash/isUndefined'; import get from 'lodash/get'; import has from 'lodash/has'; import slice from 'lodash/slice'; import { Option } from 'baseui/select'; import { isWithinInterval } from 'date-fns'; import { ALL_FIELD_TYPES, flattenObject, } from '../../redux/graph/processors/data'; import { styleEdges } from '../style-utils/style-edges'; import { styleNodes } from '../style-utils/style-nodes'; import { unixTimeConverter } from '../data-utils/data-utils'; import { Edge, EdgeNode, Field, FilterCriteria, FilterOptions, GraphAttribute, GraphData, ItemProperties, Node, SearchOptPagination, StyleOptions, TimeRange, TimeSeries, GraphList, } from '../../redux/graph/types'; import { ITEM_PER_PAGE } from '../../constants/widget-units'; type MinMax = { min: number; max: number; }; /** * Check edge.data.value is array to determine if it is grouped * * @param {Edge} edge * @param {string} edgeWidth accesor function that maps to edge width */ export const isGroupEdges = (edge: Edge, edgeWidth: string) => Array.isArray(get(edge, edgeWidth)); /** * Get minimum and maximum value of attribute that maps to edge width * * @param {GraphData} data * @param {string} edgeWidth accesor string that maps to edge width * @return {*} {MinMax} */ export const getMinMaxValue = (data: GraphData, edgeWidth: string): MinMax => { const arrValue = []; for (const edge of data.edges) { if (isGroupEdges(edge, edgeWidth)) { // isGroupEdges ensures that it is of type number[]. Sum all values in array arrValue.push( (get(edge, edgeWidth) as number[]).reduce((a, b) => a + b, 0), ); } else { arrValue.push(get(edge, edgeWidth)); } } return { min: Math.min(...(arrValue as number[])), max: Math.max(...(arrValue as number[])), }; }; /** * Filter dataset by timerange based on time attribute on the edges * * @param {GraphData} data * @param {number[]} timerange * @param {string} edgeTime * @return {*} {GraphData} */ export const filterDataByTime = ( data: GraphData, timerange: number[], edgeTime: string, ): GraphData => { if (isUndefined(edgeTime)) return data; const { nodes, edges } = data; // Because our time data is on links, the timebar's filteredData object only contains links. // But we need to show nodes in the chart too: so for each link, track the connected nodes const filteredEdges = edges.filter((edge) => inRange(Number(get(edge, edgeTime)), timerange[0], timerange[1]), ); // Filter nodes which are connected to the edges const filteredNodesId: any[] = []; filteredEdges.forEach((edge) => { filteredNodesId.push(edge.source); filteredNodesId.push(edge.target); }); const filteredNodes = nodes.filter((node) => filteredNodesId.includes(node.id), ); const newFilteredData = { nodes: [...filteredNodes], edges: [...filteredEdges], }; return newFilteredData; }; /** * Helper function to replace graph data with modified edges * * @param {GraphData} oldData * @param {Edge[]} newEdges * @return {*} {GraphData} */ export const replaceEdges = ( oldData: GraphData, newEdges: Edge[], ): GraphData => { const modData = { ...oldData }; modData.edges = [...newEdges]; return modData; }; /** * Helper function to replace graph data with modified nodes and edges * * @param {GraphData} oldData * @param {Node[]} newNodes * @param {Edge[]} newEdges * @return {*} {GraphData} */ export const replaceData = ( oldData: GraphData, newNodes: Node[], newEdges: Edge[], ): GraphData => { const modData = { ...oldData }; modData.edges = [...newEdges]; modData.nodes = [...newNodes]; return modData; }; /** * Aggregates a given edge time attribute in the to time series counts, sorted based on time * * @param {GraphData} data * @param {string} edgeTime * @return {*} {TimeSeries} */ export const datatoTS = (data: GraphData, edgeTime: string): TimeSeries => // @ts-ignore isUndefined(edgeTime) ? [] : data.edges .map((edge) => [get(edge, edgeTime), 1]) .sort((a, b) => Number(a[0]) - Number(b[0])); /** * Gets time series range * * @param {TimeRange} timeRange * @return {*} {TimeRange} */ export const chartRange = (timeRange: TimeRange): TimeRange => { const range = Math.max((timeRange[1] - timeRange[0]) / 8, 1000 * 60 * 60); return [timeRange[0] - range, timeRange[1] + range]; }; /** * Main function to apply style. * Check if the graph is of group edges or non-group and apply the appropriate styling based on options. * * @param {GraphData} data * @param {StyleOptions} options * @return {void} */ export const applyStyle = (data: GraphData, options: StyleOptions): void => { styleNodes(data, options.nodeStyle); styleEdges(data, options.edgeStyle); }; /** * Get visible graph by applying appropriate style * * @param {GraphData} graphData * @param {StyleOptions} styleOptions * @return {*} {GraphData} */ export const deriveVisibleGraph = ( graphData: GraphData, styleOptions: StyleOptions, ): GraphData => { applyStyle(graphData, styleOptions); return graphData; }; /** * Check is value is truthy and if it is an array, it should be length > 0 * * @param {*} value * @return {*} {boolean} */ export const isValidValue = (value: any): boolean => (Array.isArray(value) && value.length > 0) || (!Array.isArray(value) && value); /** * Helper function to retrieve relevant node properties. * Also removes non-truthy values and arrays of length 0 * * @param {Node} node * @param {('all' | 'style' | 'data')} [kind='all'] set to 'style' to get only style fields and 'data' to exclude style fields * @param {string[]} filter list of items to filter out * @return {*} object sorted by id, data fields followed by style fields */ export const getNodeProperties = ( node: Node, kind: 'all' | 'style' | 'data' = 'all', filter: string[], ) => { const flattenInfo = flattenObject(node); const dataKeys = Object.keys(flattenInfo).filter( (k) => k !== 'id' && !k.includes('style.') && !k.includes('defaultStyle.'), ); const styleKeys = Object.keys(flattenInfo).filter( (k) => k !== 'id' && (k.includes('style.') || k.includes('defaultStyle.')), ); const newObj = {}; // @ts-ignore newObj.id = flattenInfo.id; if (kind === 'data' || kind === 'all') { dataKeys.forEach((k) => { if (isValidValue(flattenInfo[k]) && !filter.includes(k)) newObj[k] = flattenInfo[k]; }); } if (kind === 'style' || kind === 'all') { styleKeys.forEach((k) => { if (isValidValue(flattenInfo[k]) && !filter.includes(k)) newObj[k] = flattenInfo[k]; }); } return newObj; }; /** * Helper function to retrieve relevant edge properties. * Also removes non-truthy values and arrays of length 0 * * @param {Edge} edge * @param {('all' | 'style' | 'data')} [kind='all'] set to 'style' to get only style fields and 'data' to exclude style fields * @param {string[]} filter list of items to filter out * @return {*} object sorted by id, source, target, data fields followed by style fields */ export const getEdgeProperties = ( edge: Edge, kind: 'all' | 'style' | 'data' = 'all', filter: string[], ) => { const flattenInfo = flattenObject(edge); const restrictedTerms = ['id', 'source', 'target']; const dataKeys = Object.keys(flattenInfo).filter( (k) => !restrictedTerms.includes(k) && !k.includes('style.') && !k.includes('defaultStyle.'), ); const styleKeys = Object.keys(flattenInfo).filter( (k) => !restrictedTerms.includes(k) && (k.includes('style.') || k.includes('defaultStyle.')), ); const newObj = {}; // @ts-ignore newObj.id = flattenInfo.id; // @ts-ignore newObj.source = flattenInfo.source; // @ts-ignore newObj.target = flattenInfo.target; if (kind === 'data' || kind === 'all') { dataKeys.forEach((k) => { if (!filter.includes(k)) newObj[k] = flattenInfo[k]; }); } if (kind === 'style' || kind === 'all') { styleKeys.forEach((k) => { if (!filter.includes(k)) newObj[k] = flattenInfo[k]; }); } return newObj; }; /** * For a given accessor and node / edge dataset, the function creates a dictionary of value / count pairs * * @param {(Node[] | Edge[])} data * @param {string} accessor * @return {*} map of property: counts */ export const countProperty = (data: Node[] | Edge[], accessor: string) => { const map = {}; data.forEach((o: any) => { if (!Object.prototype.hasOwnProperty.call(map, get(o, accessor))) { map[get(o, accessor)] = 1; } else { map[get(o, accessor)] = map[get(o, accessor)] + 1; } }); return map; }; type FieldTypes = (keyof typeof ALL_FIELD_TYPES)[]; const allFields = Object.keys(ALL_FIELD_TYPES) as FieldTypes; /** * Returns field which has type which matches the given type array * * @param {Field[]} fields * @param {FieldTypes} [typeArray=allFields] * * @return {Field[]} */ export const getField = ( fields: Field[], typeArray: FieldTypes = allFields, ): Field[] => // @ts-ignore fields.filter((f) => typeArray.includes(f.type)); type FilterArray = [string, FilterCriteria]; /** * Filter graph with given dynamic options on graph data * * @param {GraphData} graphFlatten * @param {FilterOptions} filterOptions * * @return {GraphData} */ export const filterGraph = ( graphFlatten: GraphData, filterOptions: FilterOptions, ): GraphData => { if (Object.keys(filterOptions).length === 0) { return graphFlatten; } const filtersArray: FilterArray[] = Object.entries(filterOptions); const hasNodeFilters: FilterArray | undefined = filtersArray.find( (value: FilterArray) => hasGraphFilters(value, 'nodes'), ); const hasEdgeFilters: FilterArray | undefined = filtersArray.find( (value: FilterArray) => hasGraphFilters(value, 'edges'), ); if (hasNodeFilters === undefined && hasEdgeFilters === undefined) { return graphFlatten; } if (hasNodeFilters) { const { nodes, edges } = graphFlatten; const filteredNodes: EdgeNode[] = filterGraphEdgeNodes( nodes, filtersArray, 'nodes', ); const connectedEdges: Edge[] = connectEdges(filteredNodes as Node[], edges); Object.assign(graphFlatten, { nodes: filteredNodes, edges: connectedEdges, }); } if (hasEdgeFilters) { const { nodes, edges } = graphFlatten; const filteredEdges = filterGraphEdgeNodes( edges, filtersArray, 'edges', ) as Edge[]; const connectedNodes: Node[] = connectNodes(filteredEdges, nodes); Object.assign(graphFlatten, { nodes: connectedNodes, edges: filteredEdges, }); } return graphFlatten; }; const hasGraphFilters = (value: FilterArray, type: GraphAttribute): boolean => { const { 1: criteria } = value; const { isFilterReady, from } = criteria as FilterCriteria; return from === type && isFilterReady; }; /** * Filter Edges and Nodes in graph with given dynamic filters * 1. construct filter objects * 2. preform filtering with dynamic options in OR conditions * * @param {EdgeNode[]} nodes * @param {FilterArray[]} filtersArray * @param {GraphAttribute} type * * @return {Node[]} */ const filterGraphEdgeNodes = ( nodes: EdgeNode[], filtersArray: FilterArray[], type: GraphAttribute, ): EdgeNode[] => { const dynamicFilters: any[] = []; // 1. construct filter objects filtersArray .filter((value: FilterArray) => hasGraphFilters(value, type)) .reduce((accFilter: any[], value: FilterArray) => { const { 1: criteria } = value; const { id, caseSearch, analyzerType, range, format } = criteria as FilterCriteria; if (analyzerType === 'STRING') { const stringCases: (string | number)[] = caseSearch.map( (option: Option) => option.id, ); accFilter.push((node: EdgeNode) => stringCases.includes(get(node, id) as string | number), ); return accFilter; } if (analyzerType === 'DATETIME' || analyzerType === 'DATE') { const isDateTimeWithinRange = (node: EdgeNode): boolean => { const [startDate, endDate] = range; const dateTime: Date = new Date(get(node, id) as number); const startInterval: Date = new Date(startDate); const endInterval: Date = new Date(endDate); const isWithinRange: boolean = isWithinInterval(dateTime, { start: startInterval, end: endInterval, }); return isWithinRange; }; accFilter.push(isDateTimeWithinRange); return accFilter; } if (analyzerType === 'TIME') { const isTimeWithinRange = (node: EdgeNode): boolean => { const [startDate, endDate] = range; const timeInUnix: number = unixTimeConverter( get(node, id) as string, analyzerType, format, ); const dateTime: Date = new Date(timeInUnix); const startInterval: Date = new Date(startDate); const endInterval: Date = new Date(endDate); const isWithinRange: boolean = isWithinInterval(dateTime, { start: startInterval, end: endInterval, }); return isWithinRange; }; accFilter.push(isTimeWithinRange); return accFilter; } // analyzerType ("INT", "FLOAT", "NUMBER") const isNumericWithinRange = (node: EdgeNode): boolean => { const [min, max] = range; return min <= get(node, id) && max >= get(node, id); }; accFilter.push(isNumericWithinRange); return accFilter; }, dynamicFilters); // 2. perform filtering with dynamic options in AND conditions const filteredGraphNodes: EdgeNode[] = nodes.filter((node: EdgeNode) => dynamicFilters.every((f) => f(node)), ); return filteredGraphNodes; }; /** * Connect edges on the filtered nodes to establish relationships * 1. perform nothing if nodes is empty * 2. find edges if source and target are presents * * @param {Node[]} filteredNodes * @param {Edge[]} edges * @return {Edge[]} */ const connectEdges = (filteredNodes: Node[], edges: Edge[]): Edge[] => { if (filteredNodes.length === 0) return []; const idsArr: string[] = filteredNodes.map((nodes: Node) => nodes.id); const associatedEdges: Edge[] = edges.filter((edge: Edge) => { const { source, target } = edge; return idsArr.includes(source) && idsArr.includes(target); }); return associatedEdges; }; /** * Obtain the associated nodes with the given edges. * 1. obtain nodes based on source and targets * * @param {Edge[]} filteredEdges * @param {Node[]} nodes * * @return {Node[]} */ const connectNodes = (filteredEdges: Edge[], nodes: Node[]): Node[] => { if (filteredEdges.length === 0) return []; const sourceTargetIds: Set<string> = new Set(); filteredEdges.reduce((acc: Set<string>, edge: Edge) => { const { source, target } = edge; if (acc.has(source) === false) acc.add(source); if (acc.has(target) === false) acc.add(target); return acc; }, sourceTargetIds); const sourceTargetIdArr: string[] = [...sourceTargetIds]; const associatedNodes = nodes.filter((node: Node) => sourceTargetIdArr.includes(node.id), ); return associatedNodes; }; /** * Format label style in order to fix the node label bugs. * @param {EdgeNode} obj * @return {void} */ export const formatLabelStyle = (obj: EdgeNode): void => { const LABEL_KEY = 'label'; const isObjHasLabel: boolean = has(obj, LABEL_KEY); if (isObjHasLabel) { Object.assign(obj.style, { label: { value: obj[LABEL_KEY], }, }); } }; let nodeStartIndex = 0; /** * Prioritize display edges in search panel with pagination's payload * @param {ItemProperties} selectedItems * @param {SearchOptPagination} pagination * @return {ItemProperties} */ export const paginateItems = ( selectedItems: ItemProperties, pagination: SearchOptPagination, ): ItemProperties => { const { nodes, edges } = selectedItems; const { currentPage } = pagination; const edgesLength = edges.length; const nodesLength = nodes.length; const lastRange = currentPage * ITEM_PER_PAGE; const firstRange = lastRange - ITEM_PER_PAGE; const edgePages = Math.ceil(edgesLength / ITEM_PER_PAGE); // return paginated nodes if no edges are selected if (edgesLength === 0) { const currentNodes = slice(nodes, firstRange, lastRange); return { nodes: currentNodes, edges: [], }; } const currentEdges = slice(edges, firstRange, lastRange); // return edges if no nodes are selected if (nodesLength === 0) { return { nodes: [], edges: currentEdges, }; } const remainingNodeSlotAfterDisplayEdge = lastRange - edgesLength; const isEdgesFinishDisplay = remainingNodeSlotAfterDisplayEdge > 0; // return edges if yet to finish display all the edges if (isEdgesFinishDisplay === false) { return { nodes: [], edges: currentEdges }; } // display remaining number of nodes based on the remaining slots of item per page. if (remainingNodeSlotAfterDisplayEdge < ITEM_PER_PAGE) { nodeStartIndex = remainingNodeSlotAfterDisplayEdge; const currentNodes = slice(nodes, 0, nodeStartIndex); return { nodes: currentNodes, edges: currentEdges, }; } // display only nodes after all the edges are display const endNodeRange = nodeStartIndex * (ITEM_PER_PAGE * (currentPage - edgePages)); const startNodeRange = endNodeRange - ITEM_PER_PAGE; const currentNodes = slice(nodes, startNodeRange, endNodeRange); return { nodes: currentNodes, edges: [], }; }; /** * Combines processed data by removing duplicate nodes and edges * * @param {GraphData} newData * @param {GraphData} oldData * @return {*} {GraphData} */ export const combineProcessedData = ( newData: GraphData, oldData: GraphData, ): GraphData => { if (oldData) { const modData = { ...oldData }; modData.nodes = removeDuplicates( [...newData.nodes, ...oldData.nodes], 'id', ) as Node[]; modData.edges = removeDuplicates( [...newData.edges, ...oldData.edges], 'id', ) as Edge[]; // Get unique fields metadata modData.metadata.fields.nodes = removeDuplicates( [...newData.metadata.fields.nodes, ...oldData.metadata.fields.nodes], 'name', ) as Field[]; modData.metadata.fields.edges = removeDuplicates( [...newData.metadata.fields.edges, ...oldData.metadata.fields.edges], 'name', ) as Field[]; return modData; } return newData; }; /** * Remove duplicate nodes, edges, node fields and edge fields from a single graph. * * @param {GraphData} graphData */ export const removeGraphDuplicates = (graphData: GraphData) => { graphData.nodes = removeDuplicates(graphData.nodes, 'id') as Node[]; graphData.edges = removeDuplicates(graphData.edges, 'id') as Edge[]; graphData.metadata.fields.nodes = removeDuplicates( graphData.metadata.fields.nodes, 'name', ) as Field[]; graphData.metadata.fields.edges = removeDuplicates( graphData.metadata.fields.edges, 'name', ) as Field[]; return graphData; }; /** * Combine list of graphs into a single graph without remove duplicate. * * @param {GraphList} graphList * @return {GraphData} */ export const combineGraphs = (graphList: GraphList): GraphData => { const initial: GraphData = { nodes: [], edges: [], metadata: { fields: { nodes: [], edges: [], }, }, }; if (graphList.length === 0) return initial; if (graphList.length === 1) { const [graphData] = graphList; return graphData; } const mergedGraph = graphList .filter((graphData) => { const { visible = true } = graphData.metadata; return visible === true; }) .reduce((graphFlatten, graphData) => { const { nodes, edges, metadata: { fields: { nodes: nodeFields, edges: edgeFields }, }, } = graphData; const combinedNodes = graphFlatten.nodes.concat(nodes); const combinedEdges = graphFlatten.edges.concat(edges); const combineNodeFields = graphFlatten.metadata.fields.nodes.concat(nodeFields); const combineEdgeFields = graphFlatten.metadata.fields.edges.concat(edgeFields); Object.assign(graphFlatten, { nodes: combinedNodes, edges: combinedEdges, metadata: { ...graphData.metadata, visible: true, fields: { nodes: combineNodeFields, edges: combineEdgeFields, }, }, }); return graphFlatten; }, initial); return mergedGraph; }; export const combineDataWithDuplicates = ( newData: GraphData, oldData: GraphData, ): GraphData => { if (oldData) { const modData = { ...oldData }; modData.nodes = [...newData.nodes, ...oldData.nodes] as Node[]; modData.edges = [...newData.edges, ...oldData.edges] as Edge[]; // Get unique fields metadata modData.metadata.fields.nodes = removeDuplicates( [...newData.metadata.fields.nodes, ...oldData.metadata.fields.nodes], 'name', ) as Field[]; modData.metadata.fields.edges = removeDuplicates( [...newData.metadata.fields.edges, ...oldData.metadata.fields.edges], 'name', ) as Field[]; return modData; } return newData; }; /** * Remove duplicates from array by checking on prop * * @see https://github.com/cylynx/motif.gl/issues/173 * - the attributes should be merged after remove the duplicates * * @param {(Node[] | Edge[] | Field[] | [])} myArr * @return {Node[] | Edge[] | Field[]} */ export const removeDuplicates = ( myArr: Node[] | Edge[] | Field[] | any[], prop: string, ): Node[] | Edge[] | Field[] => { const seen = {}; const filteredArr = myArr .filter((el) => { const duplicate = has(seen, [el[prop]]); seen[el[prop]] = el; return !duplicate; }) .map((el) => { const duplicate = has(seen, [el[prop]]); if (!duplicate) return el; const propAttributes = seen[el[prop]]; return { ...el, ...propAttributes, }; }); return filteredArr; };
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { EncryptionScopes } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { StorageManagementClient } from "../storageManagementClient"; import { EncryptionScope, EncryptionScopesListNextOptionalParams, EncryptionScopesListOptionalParams, EncryptionScopesPutOptionalParams, EncryptionScopesPutResponse, EncryptionScopesPatchOptionalParams, EncryptionScopesPatchResponse, EncryptionScopesGetOptionalParams, EncryptionScopesGetResponse, EncryptionScopesListResponse, EncryptionScopesListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing EncryptionScopes operations. */ export class EncryptionScopesImpl implements EncryptionScopes { private readonly client: StorageManagementClient; /** * Initialize a new instance of the class EncryptionScopes class. * @param client Reference to the service client */ constructor(client: StorageManagementClient) { this.client = client; } /** * Lists all the encryption scopes available under the specified storage account. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ public list( resourceGroupName: string, accountName: string, options?: EncryptionScopesListOptionalParams ): PagedAsyncIterableIterator<EncryptionScope> { const iter = this.listPagingAll(resourceGroupName, accountName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, accountName, options); } }; } private async *listPagingPage( resourceGroupName: string, accountName: string, options?: EncryptionScopesListOptionalParams ): AsyncIterableIterator<EncryptionScope[]> { let result = await this._list(resourceGroupName, accountName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, accountName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, accountName: string, options?: EncryptionScopesListOptionalParams ): AsyncIterableIterator<EncryptionScope> { for await (const page of this.listPagingPage( resourceGroupName, accountName, options )) { yield* page; } } /** * Synchronously creates or updates an encryption scope under the specified storage account. If an * encryption scope is already created and a subsequent request is issued with different properties, * the encryption scope properties will be updated per the specified request. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param encryptionScopeName The name of the encryption scope within the specified storage account. * Encryption scope names must be between 3 and 63 characters in length and use numbers, lower-case * letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a * letter or number. * @param encryptionScope Encryption scope properties to be used for the create or update. * @param options The options parameters. */ put( resourceGroupName: string, accountName: string, encryptionScopeName: string, encryptionScope: EncryptionScope, options?: EncryptionScopesPutOptionalParams ): Promise<EncryptionScopesPutResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, encryptionScopeName, encryptionScope, options }, putOperationSpec ); } /** * Update encryption scope properties as specified in the request body. Update fails if the specified * encryption scope does not already exist. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param encryptionScopeName The name of the encryption scope within the specified storage account. * Encryption scope names must be between 3 and 63 characters in length and use numbers, lower-case * letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a * letter or number. * @param encryptionScope Encryption scope properties to be used for the update. * @param options The options parameters. */ patch( resourceGroupName: string, accountName: string, encryptionScopeName: string, encryptionScope: EncryptionScope, options?: EncryptionScopesPatchOptionalParams ): Promise<EncryptionScopesPatchResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, encryptionScopeName, encryptionScope, options }, patchOperationSpec ); } /** * Returns the properties for the specified encryption scope. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param encryptionScopeName The name of the encryption scope within the specified storage account. * Encryption scope names must be between 3 and 63 characters in length and use numbers, lower-case * letters and dash (-) only. Every dash (-) character must be immediately preceded and followed by a * letter or number. * @param options The options parameters. */ get( resourceGroupName: string, accountName: string, encryptionScopeName: string, options?: EncryptionScopesGetOptionalParams ): Promise<EncryptionScopesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, encryptionScopeName, options }, getOperationSpec ); } /** * Lists all the encryption scopes available under the specified storage account. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param options The options parameters. */ private _list( resourceGroupName: string, accountName: string, options?: EncryptionScopesListOptionalParams ): Promise<EncryptionScopesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, options }, listOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param accountName The name of the storage account within the specified resource group. Storage * account names must be between 3 and 24 characters in length and use numbers and lower-case letters * only. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, accountName: string, nextLink: string, options?: EncryptionScopesListNextOptionalParams ): Promise<EncryptionScopesListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, accountName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const putOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes/{encryptionScopeName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.EncryptionScope }, 201: { bodyMapper: Mappers.EncryptionScope }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.encryptionScope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName1, Parameters.encryptionScopeName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const patchOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes/{encryptionScopeName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.EncryptionScope }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.encryptionScope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName1, Parameters.encryptionScopeName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes/{encryptionScopeName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.EncryptionScope }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName1, Parameters.encryptionScopeName ], headerParameters: [Parameters.accept], serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/encryptionScopes", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.EncryptionScopeListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName1 ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.EncryptionScopeListResult } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.accountName1, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import { _ } from 'lodash' import { REQUEST } from '@nestjs/core' import { Injectable, Scope, Inject } from '@nestjs/common' import { QueryService } from '@nestjs-query/core' import * as tldExtract from 'tld-extract' import { createECKey } from 'ec-key' import { ConfigService } from '@nestjs/config' import { renderChatbotJs } from './chatbot' import { BaseService } from '../utilities/base.service' import { ValidationService } from '../validator/validation.service' import { SettingsEntity, SettingsWebsiteJson, SettingsAdminJson, SettingsKeysJson, SettingsUserJson, SettingsModulesJson } from './settings.entity' const __IS_DEV__ = (process.env.NODE_ENV === 'development') // eslint-disable-line const escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&#34;', "'": '&#39;' } const unescapeMap = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&#34;': '"', '&#39;': "'" } export function escape (str: string): string { return str.replace(/&|<|>|"|'/g, m => escapeMap[m]) } function unescape (str: string): string { return str.replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m]) } // escapeOnce from liquidjs export function escapeOnce (str: string): string { return escape(unescape(str)) } export function htmlEncode (s: string): string { return s != null && s !== '' ? escapeOnce(s) : '' } export function mergeAll (entity: SettingsEntity, update): SettingsEntity { for (const key in update) { if (update[key] != null) { entity[key] = update[key] } else { delete entity[key] // eslint-disable-line } } entity.setJsonFromValues() return entity } @QueryService(SettingsEntity) @Injectable({ scope: Scope.REQUEST }) export class SettingsService extends BaseService<SettingsEntity> { data: any = null constructor ( // TODO req should be "private readonly" but tests won't work @Inject(REQUEST) public req, private readonly configService: ConfigService, private readonly validationService: ValidationService ) { super(req, 'SettingsEntity') // const _merge = this.repo.merge this.repo.merge = mergeAll this.req = req?.req != null ? req.req : req } async validateSettings (data: any): Promise<any> { // website if (data.website == null) { const entity = new SettingsEntity() entity.category = 'website' entity.json = new SettingsWebsiteJson() data.website = await this.createOne(entity) } // keys if (data.keys == null) { const entity = new SettingsEntity() entity.category = 'keys' entity.json = new SettingsKeysJson() data.keys = await this.createOne(entity) } if (data.keys.jwt_private_key == null) { // openssl ecparam -genkey -name secp256k1 -noout -out private.pem // openssl ec -in private.pem -pubout -out public.pem const key = createECKey('secp256k1') data.keys.jwt_private_key = key.toString('pem') data.keys.jwt_public_key = key.asPublicECKey().toString('pem') const { id, ...entity } = data.keys data.keys = await this.updateOne(id, entity) } if (data.user == null) { const entity = new SettingsEntity() entity.category = 'user' entity.json = new SettingsUserJson() data.user = await this.createOne(entity) } if (data.admin == null) { const entity = new SettingsEntity() entity.category = 'admin' entity.json = new SettingsAdminJson() data.admin = await this.createOne(entity) } } async getSettings (category: string): Promise<SettingsEntity> { // TODO cache if (this.data == null) { let records: SettingsEntity[] = [] try { records = await this.query({}) } catch (e) { // pass if (e.code != null && e.code === 'ER_NO_SUCH_TABLE') { // TODO: handle missing table, i.e. message "run migrations" } // console.log(e) } this.data = {} for (const r of records) { this.data[r.category] = r } try { await this.validateSettings(this.data) } catch (e) { // pass } } return this.data[category] ?? {} } async getUserSettings (): Promise<SettingsUserJson> { const result = this.getSettings('user') return result as unknown as SettingsUserJson } async getModulesSettings (): Promise<SettingsModulesJson> { const result = this.getSettings('modules') return result as unknown as SettingsModulesJson } async getWebsiteSettings (): Promise<SettingsWebsiteJson> { const result = this.getSettings('website') return result as unknown as SettingsWebsiteJson } async getKeysSettings (): Promise<SettingsKeysJson> { const result = this.getSettings('keys') return result as unknown as SettingsKeysJson } async getAzureAdStrategyConfig (): Promise<any | null> { const keys = await this.getKeysSettings() const tenantIdOrName = keys.oauth_azure_ad_tenant_id ?? this.configService.get('OAUTH_AZURE_AD_TENANT_ID') ?? '' const clientID = keys.oauth_azure_ad_client_id ?? this.configService.get('OAUTH_AZURE_AD_CLIENT_ID') ?? '' const clientSecret = keys.oauth_azure_ad_client_secret_value ?? this.configService.get('OAUTH_AZURE_AD_CLIENT_SECRET_VALUE') ?? '' const scope = keys.oauth_azure_ad_scope ?? this.configService.get('OAUTH_AZURE_AD_SCOPE') ?? '' const baseUrl: string = await this.getBaseUrl() return (clientID !== '' && !clientID.endsWith('xxx')) ? { // configurable tenantIdOrName, clientID, clientSecret, scope, redirectUrl: `${baseUrl}/auth/azure/callback`, allowHttpForRedirectUrl: (process.env.NODE_ENV === 'development'), // fixed identityMetadata: 'https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration', responseType: 'code', responseMode: 'form_post', // TODO replace cookies with sessions useCookieInsteadOfSession: true, cookieEncryptionKeys: [ { key: '12345678901234567890123456789013', iv: '123456789013' }, { key: 'abcdefghijklmnopqrstuvwxyzabcdeg', iv: 'abcdefghijkm' } ] } : null } async getMiraclStrategyConfig (): Promise<any | null> { const keys = await this.getKeysSettings() const clientID = keys.oidc_miracl_client_id ?? this.configService.get('OIDC_MIRACL_CLIENT_ID') ?? '' const clientSecret = keys.oidc_miracl_client_secret ?? this.configService.get('OIDC_MIRACL_CLIENT_SECRET') ?? '' const baseUrl = await this.getBaseUrl() return (clientID !== '' && !clientID.endsWith('xxx')) ? { clientID, clientSecret, callbackURL: `${baseUrl}/auth/miracl/callback` } : null } async getGoogleStrategyConfig (): Promise<any | null> { const keys = await this.getKeysSettings() const clientID = keys.oauth_google_signin_client_id ?? this.configService.get('OAUTH_GOOGLE_SIGNIN_CLIENT_ID') ?? '' const clientSecret = keys.oauth_google_signin_client_secret ?? this.configService.get('OAUTH_GOOGLE_SIGNIN_CLIENT_SECRET') ?? '' const baseUrl = await this.getBaseUrl() return (clientID !== '' && !clientID.endsWith('xxx')) ? { clientID, clientSecret, redirectURI: baseUrl } : null } async getAdminSettings (): Promise<SettingsAdminJson> { const result = await this.getSettings('admin') as unknown as SettingsAdminJson if (this.validationService.isNilOrEmpty(result.trial_expiring_cron) === true) { result.trial_expiring_cron = this.configService.get<string>('TRIAL_EXPIRING_CRON') ?? '0 0 2 * * *' } if (this.validationService.isNilOrEmpty(result.trial_expiring_days) === true) { result.trial_expiring_days = this.configService.get<number>('TRIAL_EXPIRING_DAYS') ?? 3 } return result } async getJWTPublicKey (): Promise<string> { const keys = await this.getKeysSettings() return keys.jwt_public_key } async getJWTPrivateKey (): Promise<string> { const keys = await this.getKeysSettings() return keys.jwt_private_key } async getHomepageRedirectUrl (): Promise<string | null> { const moduleHomepageConfig = this.configService.get<string>('MODULE_HOMEPAGE') ?? 'saasform' const moduleHomepage = (await this.getModulesSettings())?.homepage ?? moduleHomepageConfig if (moduleHomepage === 'redirect') { return await this.getConfiguredRedirectAfterLogin() } return null } async getUserPageSections (): Promise<string[]> { const moduleUserConfig = this.configService.get<string[]>('MODULE_USER') ?? ['general', 'security'] const moduleUser = (await this.getModulesSettings())?.user ?? moduleUserConfig return moduleUser } async getBaseUrl (cachedSettings?): Promise<string> { const configuredBaseUrl = this.configService.get<string>('SAASFORM_BASE_URL') ?? '' const settings = cachedSettings ?? await this.getWebsiteSettings() if (settings.domain_primary != null) { return `https://${settings.domain_primary as string}` } else if (configuredBaseUrl !== '') { return `${configuredBaseUrl}` } return '/' } async getTrialLength (cachedSettings?): Promise<number> { const settings = cachedSettings ?? await this.getWebsiteSettings() return settings.pricing_free_trial ?? 7 } async getTopLevelUrl (cachedSettings?): Promise<string> { const baseUrl = await this.getBaseUrl(cachedSettings) let domain try { domain = tldExtract(baseUrl) } catch (err) { // pass } const topLevel: string = domain?.domain return topLevel != null ? `https://${topLevel}` : '/' } // TODO: TDD this /* The redirect after login, aka app url as it comes from config. */ async getConfiguredRedirectAfterLogin (cachedSettings?): Promise<string> { const configuredRedirectUrl = this.configService.get<string>('SAAS_REDIRECT_URL') ?? '' const settings = cachedSettings ?? await this.getWebsiteSettings() if (settings.domain_app != null) { return `https://${settings.domain_app as string}` } else if (settings.domain_primary != null) { return `https://app.${settings.domain_primary as string}` } else if (settings.insecure_domain_app != null) { console.warn('USING INSECURE REDIRECT:', settings.insecure_domain_app) return `${settings.insecure_domain_app as string}` } else if (configuredRedirectUrl !== '') { return `${configuredRedirectUrl}` } return '/' } async getNextUrl (queryNext): Promise<string | null> { const baseUrl = await this.getBaseUrl() const appUrl = await this.getConfiguredRedirectAfterLogin() const homeUrl = await this.getHomepageRedirectUrl() // prevent open redirects const next: string = queryNext if (next != null) { if ( // relative path next[0] === '/' || // absolute url to Saasform next.startsWith(baseUrl) || // absolute url to SaaS next.startsWith(appUrl) ) { // when home is not managed by saasform, make relative url absolute if (homeUrl !== null && next[0] === '/') { return `${homeUrl}${next}` } return next } } return null } /* The actual redirect after login, combining app url, req.query.next, sign flows etc. */ async getActualRedirectAfterLogin (requestUser, queryNext, jwt: string|null = null): Promise<string> { switch (requestUser.status) { case 'no_payment_method': return '/payment' case 'unpaid': return '/user/billing' } const next = await this.getNextUrl(queryNext) if (next != null) { return next } let append = '' const settings = await this.getWebsiteSettings() if (settings.unsafe_redirect_with_jwt === 'query' && jwt != null) { append = `?token=${jwt}` } if (settings.unsafe_redirect_with_jwt === 'hash' && jwt != null) { append = `#token=${jwt}` } const redirect = await this.getConfiguredRedirectAfterLogin() return `${redirect}${append}` } async getAssetsRoot (): Promise<{themeRoot: string, assetsRoot: string}> { const themeRoot: string = this.req.themeRoot ?? this.configService.get('SAASFORM_THEME', 'default') const assetsRoot: string = `/${themeRoot}` return { themeRoot, assetsRoot } } async getWebsiteRenderingVariables (): Promise<any> { const { themeRoot, assetsRoot } = await this.getAssetsRoot() const settings = await this.getWebsiteSettings() const htmlAsset: (asset: string) => string = (asset: string) => (asset === '' || asset.startsWith('https://') ? asset : `${assetsRoot}/${asset}`) // TODO type const res = { name: '', title: '', description: '', domain_primary: '', domain_app: '', domain_home: '', email: '', // integrations app_google_analytics: '', app_google_tag_manager: '', app_facebook_pixel_id: '', app_google_signin_client_id: '', app_google_signin_scope: '', app_google_signin_access_type: 'offline', app_chatbot_provider: '', app_chatbot_id: '', app_chatbot_domain: '', // footer legal_company_name: '', made_with_love: '', socials: [ { name: '', url: '' } ], // nav nav_links: { login_text: '', login_link: '', signup_text: '', signup_link: '' }, // home hero_title: '', hero_subtitle: '', hero_cta: '', hero_image_url: '', hero_video_url: '', benefits: [ { image_url: '', title: '', text: '' } ], logos: [ { name: '', image_url: '' } ], features: [ { title: '', text: '', image_url: '' } ], testimonials_title: '', testimonials_text: '', testimonials: [ { name: '', image_url: '', quote: '' } ], pricing_title: '', pricing_text: '', pricing_free_trial: '', pricing_credit_card_required: '', pricing_plans: [ { name: '', image_url: '', quote: '' } ], faq: [ { title: '', text: '' } ], cta_badge: '', cta_title: '', cta_text: '', cta_button: '', // footer footer: [ { title: '', links: [ { name: '', url: '' } ] } ], // prelaunch page, if enabled prelaunch_enabled: '', prelaunch_cleartext_password: '', prelaunch_message: '', prelaunch_background_url: '', // autogenerated, can override seo_fb_app_id: '', seo_title: '', seo_description: '', seo_og_url: '', seo_og_title: '', seo_og_description: '', seo_og_image_url: '', seo_twitter_title: '', seo_twitter_description: '', seo_twitter_image_url: '', legal_website_url: '', legal_email: '', // auto added, can't override root_assets: '', root_theme: '', saas_redirect_url: '', html_google_signin_header: '', html_google_analytics: '', html_google_tag_manager_header: '', html_google_tag_manager_body: '', html_facebook_pixel: '', html_chatbot: '', subscription_optional: true, // signup fields signup_show_google: false, signup_show_azure: false, signup_show_miracl: false, signup_show_username: false, signup_force_payment: false, security_two_factor_auth: false, // page /user user_page_sections: [''], // dynamic layout layout_nav: '', logo: { name: '', url: '' }, // unsafe config unsafe_disable_csp: false, unsafe_redirect_with_jwt: false } const encodedPaths = [ 'name', 'title', 'description', 'domain_primary', 'domain_app', 'email', 'logo_url', 'app_google_analytics', 'app_google_tag_manager', 'app_facebook_pixel_id', 'app_google_signin_client_id', 'app_google_signin_scope', 'app_chatbot_provider', 'app_chatbot_id', 'app_chatbot_domain', 'legal_company_name', 'nav_links', 'hero_title', 'hero_subtitle', 'hero_cta', 'hero_image_url', 'hero_video_url', 'testimonials_title', 'testimonials_text', 'pricing_title', 'pricing_text', 'pricing_free_trial', 'pricing_credit_card_required', 'cta_badge', 'cta_title', 'cta_text', 'cta_button', 'prelaunch_enabled', 'prelaunch_cleartext_password', 'prelaunch_message', 'prelaunch_background_url', 'signup_show_username', 'signup_force_payment', 'security_two_factor_auth', 'unsafe_disable_csp', 'unsafe_redirect_with_jwt' ] for (const key of encodedPaths) { const finalFunc = key.endsWith('url') ? htmlAsset : htmlEncode const value = _.get(settings, key) ?? this.configService.get(key) ?? '' const finalValue = (typeof value === 'string') ? finalFunc(value) : value _.set(res, key, finalValue) } const arrayPaths = [ 'benefits', 'logos', 'features', 'testimonials', 'pricing_plans', 'faq', 'socials', 'footer' ] for (const key of arrayPaths) { const arrayFromSettings = _.get(settings, key) ?? [] const arrayFromConfig = this.configService.get(key) ?? [] const arrayValue = settings[key] !== undefined ? arrayFromSettings : arrayFromConfig const finalArrayValue = arrayValue.map(item => { const ret = {} for (const key in item) { const value = item[key] const finalFunc = key.endsWith('url') ? htmlAsset : htmlEncode const finalValue = (typeof value === 'string') ? finalFunc(value) : value ret[key] = finalValue } return ret }) // TODO encode _.set(res, key, finalArrayValue) } // autogenerated, can override const homeUrl = await this.getHomepageRedirectUrl() ?? res.domain_primary const homeDomain = homeUrl.replace('http://', '').replace('https://', '') const renderedUrl = `https://${homeDomain}` const redirectAfterLogin = await this.getConfiguredRedirectAfterLogin(settings) res.domain_home = homeDomain res.seo_fb_app_id = '' res.seo_title = `${res.name} - ${res.title}` res.seo_description = res.description res.seo_og_url = renderedUrl res.seo_og_title = res.seo_title res.seo_og_description = res.seo_description res.seo_og_image_url = res.hero_image_url res.seo_twitter_title = res.seo_title res.seo_twitter_description = res.seo_description res.seo_twitter_image_url = res.hero_image_url res.legal_website_url = renderedUrl res.legal_email = res.email const overridePaths = [ 'seo_fb_app_id', 'seo_title', 'seo_description', 'seo_og_url', 'seo_og_title', 'seo_og_description', 'seo_og_image_url', 'seo_twitter_title', 'seo_twitter_description', 'seo_twitter_image_url', 'legal_website_url', 'legal_email', 'made_with_love' ] for (const key of overridePaths) { const value = _.get(settings, key) ?? this.configService.get(key, '') if (value !== '') { _.set(res, key, value) } } // auto added, can't override res.root_theme = themeRoot res.root_assets = assetsRoot res.saas_redirect_url = redirectAfterLogin res.user_page_sections = await this.getUserPageSections() // dynamic layout res.layout_nav = themeRoot + '/nav' res.logo = { url: await this.getHomepageRedirectUrl() ?? '/', name: res.name } // unsafe config if (res.unsafe_disable_csp) { this.req.unsafeDisableCsp = res.unsafe_disable_csp } // keys const keys = await this.getKeysSettings() res.app_google_signin_client_id = keys.oauth_google_signin_client_id ?? this.configService.get('OAUTH_GOOGLE_SIGNIN_CLIENT_ID') ?? '' res.app_google_signin_scope = keys.oauth_google_signin_scope ?? this.configService.get('OAUTH_GOOGLE_SIGNIN_SCOPE') ?? 'email profile' const azureAdConfig = await this.getAzureAdStrategyConfig() const miraclConfig = await this.getMiraclStrategyConfig() // html // Google Sign-In // https://developers.google.com/identity/sign-in/web/sign-in res.signup_show_google = !!((res.app_google_signin_client_id !== '' && !res.app_google_signin_client_id.endsWith('xxx'))) res.signup_show_azure = !!(azureAdConfig != null) res.signup_show_miracl = !!(miraclConfig != null) res.html_google_signin_header = res.app_google_signin_client_id !== '' && !res.app_google_signin_client_id.endsWith('xxx') ? ` <meta name="google-signin-client_id" content="${res.app_google_signin_client_id}"> <meta name="google-signin-scope" content="${res.app_google_signin_scope}"> <script src="https://apis.google.com/js/platform.js?onload=onGoogleStart" defer></script> ` : '' res.html_google_tag_manager_header = res.app_google_tag_manager !== '' && !res.app_google_tag_manager.endsWith('xxx') ? ` <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','${res.app_google_tag_manager}');</script> <!-- End Google Tag Manager --> ` : '' res.html_google_tag_manager_body = res.app_google_tag_manager !== '' && !res.app_google_tag_manager.endsWith('xxx') ? ` <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=${res.app_google_tag_manager}" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) --> ` : '' res.html_google_analytics = res.app_google_analytics !== '' && !res.app_google_analytics.endsWith('xxx') ? ` <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=${res.app_google_analytics}"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '${res.app_google_analytics}'); </script> ` : '' res.html_facebook_pixel = res.app_facebook_pixel_id !== '' && !String(res.app_facebook_pixel_id).endsWith('xxx') ? ` <!-- Facebook Pixel Code --> <script> !function(f,b,e,v,n,t,s) {if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)}; if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0'; n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t,s)}(window, document,'script', 'https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '${res.app_facebook_pixel_id}'); fbq('track', 'PageView'); </script> <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=${res.app_facebook_pixel_id}&ev=PageView&noscript=1" /></noscript> <!-- End Facebook Pixel Code --> ` : '' res.html_chatbot = renderChatbotJs(res.app_chatbot_provider, res.app_chatbot_id, res.app_chatbot_domain, this.req) return res } }
the_stack
'use strict' import fs from 'fs' import _ from 'lodash' import path from 'path' import semver from 'semver' import { v4 as uuidv4 } from 'uuid' import { SelfIdentity, SignalKMessageHub, WithConfig } from '../app' import { createDebug } from '../debug' import DeltaEditor from '../deltaeditor' const debug = createDebug('signalk-server:config') let disableWriteSettings = false export interface Config { getExternalHostname: () => string getExternalPort: (config: Config) => number port: number appPath: string configPath: string name: string author: string contributors: string[] version: string description: string vesselName: string vesselUUID: string vesselMMSI: string baseDeltaEditor: DeltaEditor hasOldDefaults: boolean overrideTimestampWithNow: boolean security: boolean settings: { useBaseDeltas?: boolean pipedProviders: any[] interfaces?: { [ifaceName: string]: boolean } security?: any ssl?: boolean wsCompression?: boolean landingPage?: string proxy_host?: string proxy_port?: number hostname?: string pruneContextsMinutes?: number mdns?: boolean sslport?: number port?: number } defaults: object } export interface ConfigApp extends WithConfig, SelfIdentity, SignalKMessageHub { argv: any env: any } export function load(app: ConfigApp) { app.argv = require('minimist')(process.argv.slice(2)) const config = (app.config = app.config || {}) const env = (app.env = process.env) config.getExternalHostname = getExternalHostname.bind(config, config) config.getExternalPort = getExternalPort.bind(config, config) config.appPath = config.appPath || path.normalize(__dirname + '/../../') debug('appPath:' + config.appPath) try { const pkg = require('../../package.json') config.name = pkg.name config.author = pkg.author config.contributors = pkg.contributors config.version = pkg.version config.description = pkg.description checkPackageVersion('@signalk/server-admin-ui', pkg, app.config.appPath) } catch (err) { console.error('error parsing package.json', err) process.exit(1) } setConfigDirectory(app) app.config.baseDeltaEditor = new DeltaEditor() if (_.isObject(app.config.settings)) { debug('Using settings from constructor call, not reading defaults') disableWriteSettings = true if (config.defaults) { convertOldDefaultsToDeltas(app.config.baseDeltaEditor, config.defaults) } } else { readSettingsFile(app) if (!setBaseDeltas(app)) { const defaults = getFullDefaults(app) if (defaults) { convertOldDefaultsToDeltas(app.config.baseDeltaEditor, defaults) if ( typeof (app.config.settings as any).useBaseDeltas === 'undefined' || (app.config.settings as any).useBaseDeltas ) { writeBaseDeltasFileSync(app) } else { app.config.hasOldDefaults = true } } } } setSelfSettings(app) if (app.argv['sample-nmea0183-data']) { const sample = path.join(app.config.appPath, 'samples/plaka.log') console.log(`Using sample data from ${sample}`) app.config.settings.pipedProviders.push({ id: 'nmea0183-sample-data', pipeElements: [ { type: 'providers/simple', options: { logging: false, type: 'FileStream', subOptions: { dataType: 'NMEA0183', filename: sample } } } ], enabled: true }) } if (app.argv['sample-n2k-data']) { const sample = path.join(app.config.appPath, 'samples/aava-n2k.data') console.log(`Using sample data from ${sample}`) app.config.settings.pipedProviders.push({ id: 'n2k-sample-data', pipeElements: [ { type: 'providers/simple', options: { logging: false, type: 'FileStream', subOptions: { dataType: 'NMEA2000JS', filename: sample } } } ], enabled: true }) } if (app.argv['override-timestamps']) { app.config.overrideTimestampWithNow = true } if (app.argv.securityenabled && !app.config.security) { app.config.settings.security = { strategy: './tokensecurity' } } if (env.SSLPORT) { config.settings.ssl = true } if (!_.isUndefined(app.env.WSCOMPRESSION)) { config.settings.wsCompression = app.env.WSCOMPRESSION.toLowerCase() === 'true' } if ( config.settings.landingPage && config.settings.landingPage.charAt(0) !== '/' ) { console.error(`invalid rootUri: ${config.settings.landingPage}`) process.exit(1) } require('./development')(app) require('./production')(app) } function checkPackageVersion(name: string, pkg: any, appPath: string) { const expected = pkg.dependencies[name] let modulePackageJsonPath = path.join( appPath, 'node_modules', name, 'package.json' ) if (!fs.existsSync(modulePackageJsonPath)) { modulePackageJsonPath = path.join(appPath, '..', name, 'package.json') } const installed = require(modulePackageJsonPath) if (!semver.satisfies(installed.version, expected)) { console.error( `invalid version of the ${name} package is installed ${installed.version} !== ${expected}` ) process.exit(1) } } // Establish what the config directory path is. function getConfigDirectory({ argv, config, env }: any) { // Possible paths in order of priority. const configPaths = [ env.SIGNALK_NODE_CONDFIG_DIR, env.SIGNALK_NODE_CONFIG_DIR, config.configPath, argv.c, argv.s && config.appPath, env.HOME && path.join(env.HOME, '.signalk'), config.appPath ] // Find first config directory path that has a truthy value. const configPath = path.resolve(_.find(configPaths)) debug('configDirPath: ' + configPath) return configPath } // Create directories and set app.config.configPath. function setConfigDirectory(app: ConfigApp) { app.config.configPath = getConfigDirectory(app) if (app.config.configPath !== app.config.appPath) { if (!fs.existsSync(app.config.configPath)) { fs.mkdirSync(app.config.configPath) debug(`configDir Created: ${app.config.configPath}`) } const configPackage = path.join(app.config.configPath, 'package.json') if (!fs.existsSync(configPackage)) { fs.writeFileSync( configPackage, JSON.stringify(pluginsPackageJsonTemplate, null, 2) ) } const npmrcPath = path.join(app.config.configPath, '.npmrc') if (!fs.existsSync(npmrcPath)) { fs.writeFileSync(npmrcPath, 'package-lock=false\n') } else { const contents = fs.readFileSync(npmrcPath) if (contents.indexOf('package-lock=') === -1) { fs.appendFileSync(npmrcPath, '\npackage-lock=false\n') } } } } function getDefaultsPath(app: ConfigApp) { const defaultsFile = app.config.configPath !== app.config.appPath ? 'defaults.json' : 'settings/defaults.json' return path.join(app.config.configPath, defaultsFile) } function getBaseDeltasPath(app: ConfigApp) { const defaultsFile = app.config.configPath !== app.config.appPath ? 'baseDeltas.json' : 'settings/baseDeltas.json' return path.join(app.config.configPath, defaultsFile) } function readDefaultsFile(app: ConfigApp) { const defaultsPath = getDefaultsPath(app) const data = fs.readFileSync(defaultsPath) return JSON.parse(data.toString()) } function getFullDefaults(app: ConfigApp) { const defaultsPath = getDefaultsPath(app) try { const defaults = readDefaultsFile(app) debug(`Found defaults at ${defaultsPath.toString()}`) return defaults } catch (e) { if ((e as any)?.code === 'ENOENT') { return undefined } else { console.error(`unable to parse ${defaultsPath.toString()}`) console.error(e) process.exit(1) } } return undefined } function setBaseDeltas(app: ConfigApp) { const defaultsPath = getBaseDeltasPath(app) try { app.config.baseDeltaEditor.load(defaultsPath) debug(`Found default deltas at ${defaultsPath.toString()}`) } catch (e) { if ((e as any)?.code === 'ENOENT') { debug(`No default deltas found at ${defaultsPath.toString()}`) return } else { console.log(e) } } return true } export function sendBaseDeltas(app: ConfigApp) { const copy = JSON.parse(JSON.stringify(app.config.baseDeltaEditor.deltas)) copy.forEach((delta: any) => { app.handleMessage('defaults', delta) }) } function writeDefaultsFile(app: ConfigApp, defaults: any, cb: any) { fs.writeFile(getDefaultsPath(app), JSON.stringify(defaults, null, 2), cb) } function writeBaseDeltasFileSync(app: ConfigApp) { app.config.baseDeltaEditor.saveSync(getBaseDeltasPath(app)) } function writeBaseDeltasFile(app: ConfigApp) { return app.config.baseDeltaEditor.save(getBaseDeltasPath(app)) } function setSelfSettings(app: ConfigApp) { const name = app.config.baseDeltaEditor.getSelfValue('name') const mmsi = app.config.baseDeltaEditor.getSelfValue('mmsi') let uuid = app.config.baseDeltaEditor.getSelfValue('uuid') if (mmsi && !_.isString(mmsi)) { throw new Error(`invalid mmsi: ${mmsi}`) } if (uuid && !_.isString(uuid)) { throw new Error(`invalid uuid: ${uuid}`) } if (mmsi === null && uuid === null) { uuid = 'urn:mrn:signalk:uuid:' + uuidv4() app.config.baseDeltaEditor.setSelfValue('uuid', uuid) } app.config.vesselName = name if (mmsi) { app.selfType = 'mmsi' app.selfId = 'urn:mrn:imo:mmsi:' + mmsi app.config.vesselMMSI = mmsi } else if (uuid) { app.selfType = 'uuid' app.selfId = uuid app.config.vesselUUID = uuid } if (app.selfType) { debug(app.selfType.toUpperCase() + ': ' + app.selfId) } app.selfContext = 'vessels.' + app.selfId } function readSettingsFile(app: ConfigApp) { const settings = getSettingsFilename(app) if (!app.argv.s && !fs.existsSync(settings)) { console.log('Settings file does not exist, using empty settings') app.config.settings = { pipedProviders: [] } } else { debug('Using settings file: ' + settings) app.config.settings = require(settings) } if (_.isUndefined(app.config.settings.pipedProviders)) { app.config.settings.pipedProviders = [] } if (_.isUndefined(app.config.settings.interfaces)) { app.config.settings.interfaces = {} } } function writeSettingsFile(app: ConfigApp, settings: any, cb: any) { if (!disableWriteSettings) { const settingsPath = getSettingsFilename(app) fs.writeFile(settingsPath, JSON.stringify(settings, null, 2), cb) } else { cb() } } function getSettingsFilename(app: ConfigApp) { if (process.env.SIGNALK_NODE_SETTINGS) { debug( 'Settings filename was set in environment SIGNALK_NODE_SETTINGS, overriding all other options' ) return path.resolve(process.env.SIGNALK_NODE_SETTINGS) } const settingsFile = app.argv.s || 'settings.json' return path.join(app.config.configPath, settingsFile) } function getExternalHostname(config: Config) { if (process.env.EXTERNALHOST) { return process.env.EXTERNALHOST } if (config.settings.proxy_host) { return config.settings.proxy_host } else if (config.settings.hostname) { return config.settings.hostname } try { return require('os').hostname() } catch (ex) { return 'hostname_not_available' } } function getExternalPort(config: Config): any { if (process.env.EXTERNALPORT) { return process.env.EXTERNALPORT } if (config.settings.proxy_port) { return config.settings.proxy_port } else if (config.port) { return config.port } return '' } function scanDefaults(deltaEditor: DeltaEditor, vpath: string, item: any) { _.keys(item).forEach((key: string) => { const value = item[key] if (key === 'meta') { deltaEditor.setMeta('vessels.self', vpath, value) } else if (key === 'value') { deltaEditor.setSelfValue(vpath, value) } else if (_.isObject(value)) { const childPath = vpath.length > 0 ? `${vpath}.${key}` : key scanDefaults(deltaEditor, childPath, value) } }) } function convertOldDefaultsToDeltas( deltaEditor: DeltaEditor, defaults: object ) { const deltas: any[] = [] const self: any = _.get(defaults, 'vessels.self') if (self) { _.keys(self).forEach((key: any) => { const value = self[key] if (!_.isString(value)) { scanDefaults(deltaEditor, key, value) } else { deltaEditor.setSelfValue(key, value) } }) if (self.communication) { deltaEditor.setSelfValue('communication', self.communication) } } return deltas } const pluginsPackageJsonTemplate = { name: 'signalk-server-config', version: '0.0.1', description: 'This file is here to track your plugin and webapp installs.', repository: {}, license: 'Apache-2.0' } module.exports = { load, getConfigDirectory, writeSettingsFile, writeDefaultsFile, readDefaultsFile, sendBaseDeltas, writeBaseDeltasFile }
the_stack
export let UDOC:any = {}; UDOC.G = { concat : function(p:any,r:any) { for(var i=0; i<r.cmds.length; i++) p.cmds.push(r.cmds[i]); for(var i=0; i<r.crds.length; i++) p.crds.push(r.crds[i]); }, getBB : function(ps:any) { var x0=1e99, y0=1e99, x1=-x0, y1=-y0; for(var i=0; i<ps.length; i+=2) { var x=ps[i],y=ps[i+1]; if(x<x0)x0=x; else if(x>x1)x1=x; if(y<y0)y0=y; else if(y>y1)y1=y; } return [x0,y0,x1,y1]; }, rectToPath: function(r:any) { return {cmds:["M","L","L","L","Z"],crds:[r[0],r[1],r[2],r[1], r[2],r[3],r[0],r[3]]}; }, // a inside b insideBox: function(a:any,b:any) { return b[0]<=a[0] && b[1]<=a[1] && a[2]<=b[2] && a[3]<=b[3]; }, isBox : function(p:any, bb:any) { var sameCrd8 = function(pcrd:any, crds:any) { for(var o=0; o<8; o+=2) { var eq = true; for(var j=0; j<8; j++) if(Math.abs(crds[j]-pcrd[(j+o)&7])>=2) { eq = false; break; } if(eq) return true; } return false; }; if(p.cmds.length>10) return false; var cmds=p.cmds.join(""), crds=p.crds; var sameRect = false; if((cmds=="MLLLZ" && crds.length== 8) ||(cmds=="MLLLLZ" && crds.length==10) ) { if(crds.length==10) crds=crds.slice(0,8); var x0=bb[0],y0=bb[1],x1=bb[2],y1=bb[3]; if(!sameRect) sameRect = sameCrd8(crds, [x0,y0,x1,y0,x1,y1,x0,y1]); if(!sameRect) sameRect = sameCrd8(crds, [x0,y1,x1,y1,x1,y0,x0,y0]); } return sameRect; }, boxArea: function(a:any) { var w=a[2]-a[0], h=a[3]-a[1]; return w*h; }, newPath: function(gst:any ) { gst.pth = {cmds:[], crds:[]}; }, moveTo : function(gst:any,x:any,y:any) { var p=UDOC.M.multPoint(gst.ctm,[x,y]); //if(gst.cpos[0]==p[0] && gst.cpos[1]==p[1]) return; gst.pth.cmds.push("M"); gst.pth.crds.push(p[0],p[1]); gst.cpos = p; }, lineTo : function(gst:any,x:any,y:any) { var p=UDOC.M.multPoint(gst.ctm,[x,y]); if(gst.cpos[0]==p[0] && gst.cpos[1]==p[1]) return; gst.pth.cmds.push("L"); gst.pth.crds.push(p[0],p[1]); gst.cpos = p; }, curveTo: function(gst:any,x1:any,y1:any,x2:any,y2:any,x3:any,y3:any) { var p; p=UDOC.M.multPoint(gst.ctm,[x1,y1]); x1=p[0]; y1=p[1]; p=UDOC.M.multPoint(gst.ctm,[x2,y2]); x2=p[0]; y2=p[1]; p=UDOC.M.multPoint(gst.ctm,[x3,y3]); x3=p[0]; y3=p[1]; gst.cpos = p; gst.pth.cmds.push("C"); gst.pth.crds.push(x1,y1,x2,y2,x3,y3); }, closePath: function(gst:any ) { gst.pth.cmds.push("Z"); }, arc : function(gst:any,x:any,y:any,r:any,a0:any,a1:any, neg:any) { // circle from a0 counter-clock-wise to a1 if(neg) while(a1>a0) a1-=2*Math.PI; else while(a1<a0) a1+=2*Math.PI; var th = (a1-a0)/4; var x0 = Math.cos(th/2), y0 = -Math.sin(th/2); var x1 = (4-x0)/3, y1 = y0==0 ? y0 : (1-x0)*(3-x0)/(3*y0); var x2 = x1, y2 = -y1; var x3 = x0, y3 = -y0; var p0 = [x0,y0], p1 = [x1,y1], p2 = [x2,y2], p3 = [x3,y3]; var pth = {cmds:[(gst.pth.cmds.length==0)?"M":"L","C","C","C","C"], crds:[x0,y0,x1,y1,x2,y2,x3,y3]}; var rot = [1,0,0,1,0,0]; UDOC.M.rotate(rot,-th); for(var i=0; i<3; i++) { p1 = UDOC.M.multPoint(rot,p1); p2 = UDOC.M.multPoint(rot,p2); p3 = UDOC.M.multPoint(rot,p3); pth.crds.push(p1[0],p1[1],p2[0],p2[1],p3[0],p3[1]); } var sc = [r,0,0,r,x,y]; UDOC.M.rotate(rot, -a0+th/2); UDOC.M.concat(rot, sc); UDOC.M.multArray(rot, pth.crds); UDOC.M.multArray(gst.ctm, pth.crds); UDOC.G.concat(gst.pth, pth); var y:any=pth.crds.pop(); x=pth.crds.pop(); gst.cpos = [x,y]; }, toPoly : function(p:any) { if(p.cmds[0]!="M" || p.cmds[p.cmds.length-1]!="Z") return null; for(var i=1; i<p.cmds.length-1; i++) if(p.cmds[i]!="L") return null; var out = [], cl = p.crds.length; if(p.crds[0]==p.crds[cl-2] && p.crds[1]==p.crds[cl-1]) cl-=2; for(var i=0; i<cl; i+=2) out.push([p.crds[i],p.crds[i+1]]); if(UDOC.G.polyArea(p.crds)<0) out.reverse(); return out; }, fromPoly : function(p:any) { var o:any = {cmds:[],crds:[]}; for(var i=0; i<p.length; i++) { o.crds.push(p[i][0], p[i][1]); o.cmds.push(i==0?"M":"L"); } o.cmds.push("Z"); return o; }, polyArea : function(p:any) { if(p.length <6) return 0; var l = p.length - 2; var sum = (p[0]-p[l]) * (p[l+1]+p[1]); for(var i=0; i<l; i+=2) sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]); return - sum * 0.5; }, polyClip : function(p0:any, p1:any) { // p0 clipped by p1 var cp1:any, cp2:any, s:any, e:any; var inside = function (p:any) { return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]); }; var isc = function () { var dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ], dp = [ s[0] - e[0], s[1] - e[1] ], n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0], n2 = s[0] * e[1] - s[1] * e[0], n3 = 1.0 / (dc[0] * dp[1] - dc[1] * dp[0]); return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]; }; var out = p0; cp1 = p1[p1.length-1]; for (let j in p1) { var cp2 = p1[j]; var inp = out; out = []; s = inp[inp.length - 1]; //last on the input list for (let i in inp) { var e = inp[i]; if (inside(e)) { if (!inside(s)) { out.push(isc()); } out.push(e); } else if (inside(s)) { out.push(isc()); } s = e; } cp1 = cp2; } return out } } UDOC.M = { getScale : function(m:any) { return Math.sqrt(Math.abs(m[0]*m[3]-m[1]*m[2])); }, translate: function(m:any,x:any,y:any) { UDOC.M.concat(m, [1,0,0,1,x,y]); }, rotate : function(m:any,a:any ) { UDOC.M.concat(m, [Math.cos(a), -Math.sin(a), Math.sin(a), Math.cos(a),0,0]); }, scale : function(m:any,x:any,y:any) { UDOC.M.concat(m, [x,0,0,y,0,0]); }, concat : function(m:any,w:any ) { var a=m[0],b=m[1],c=m[2],d=m[3],tx=m[4],ty=m[5]; m[0] = (a *w[0])+(b *w[2]); m[1] = (a *w[1])+(b *w[3]); m[2] = (c *w[0])+(d *w[2]); m[3] = (c *w[1])+(d *w[3]); m[4] = (tx*w[0])+(ty*w[2])+w[4]; m[5] = (tx*w[1])+(ty*w[3])+w[5]; }, invert : function(m:any ) { var a=m[0],b=m[1],c=m[2],d=m[3],tx=m[4],ty=m[5], adbc=a*d-b*c; m[0] = d/adbc; m[1] = -b/adbc; m[2] =-c/adbc; m[3] = a/adbc; m[4] = (c*ty - d*tx)/adbc; m[5] = (b*tx - a*ty)/adbc; }, multPoint: function(m:any, p:any ) { var x=p[0],y=p[1]; return [x*m[0]+y*m[2]+m[4], x*m[1]+y*m[3]+m[5]]; }, multArray: function(m:any, a:any ) { for(var i=0; i<a.length; i+=2) { var x=a[i],y=a[i+1]; a[i]=x*m[0]+y*m[2]+m[4]; a[i+1]=x*m[1]+y*m[3]+m[5]; } } } UDOC.C = { srgbGamma : function(x:any) { return x < 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1.0 / 2.4) - 0.055; }, cmykToRgb : function(clr:any) { var c=clr[0], m=clr[1], y=clr[2], k=clr[3]; // return [1-Math.min(1,c+k), 1-Math.min(1, m+k), 1-Math.min(1,y+k)]; var r = 255 + c * (-4.387332384609988 * c + 54.48615194189176 * m + 18.82290502165302 * y + 212.25662451639585 * k + -285.2331026137004) + m * ( 1.7149763477362134 * m - 5.6096736904047315 * y + -17.873870861415444 * k - 5.497006427196366) + y * (-2.5217340131683033 * y - 21.248923337353073 * k + 17.5119270841813) + k * (-21.86122147463605 * k - 189.48180835922747); var g = 255 + c * (8.841041422036149 * c + 60.118027045597366 * m + 6.871425592049007 * y + 31.159100130055922 * k + -79.2970844816548) + m * (-15.310361306967817 * m + 17.575251261109482 * y + 131.35250912493976 * k - 190.9453302588951) + y * (4.444339102852739 * y + 9.8632861493405 * k - 24.86741582555878) + k * (-20.737325471181034 * k - 187.80453709719578); var b = 255 + c * (0.8842522430003296 * c + 8.078677503112928 * m + 30.89978309703729 * y - 0.23883238689178934 * k + -14.183576799673286) + m * (10.49593273432072 * m + 63.02378494754052 * y + 50.606957656360734 * k - 112.23884253719248) + y * (0.03296041114873217 * y + 115.60384449646641 * k + -193.58209356861505) + k * (-22.33816807309886 * k - 180.12613974708367); return [Math.max(0, Math.min(1, r/255)), Math.max(0, Math.min(1, g/255)), Math.max(0, Math.min(1, b/255))]; //var iK = 1-c[3]; //return [(1-c[0])*iK, (1-c[1])*iK, (1-c[2])*iK]; }, labToRgb : function(lab:any) { var k = 903.3, e = 0.008856, L = lab[0], a = lab[1], b = lab[2]; var fy = (L+16)/116, fy3 = fy*fy*fy; var fz = fy - b/200, fz3 = fz*fz*fz; var fx = a/500 + fy, fx3 = fx*fx*fx; var zr = fz3>e ? fz3 : (116*fz-16)/k; var yr = fy3>e ? fy3 : (116*fy-16)/k; var xr = fx3>e ? fx3 : (116*fx-16)/k; var X = xr*96.72, Y = yr*100, Z = zr*81.427, xyz = [X/100,Y/100,Z/100]; var x2s = [3.1338561, -1.6168667, -0.4906146, -0.9787684, 1.9161415, 0.0334540, 0.0719453, -0.2289914, 1.4052427]; var rgb = [ x2s[0]*xyz[0] + x2s[1]*xyz[1] + x2s[2]*xyz[2], x2s[3]*xyz[0] + x2s[4]*xyz[1] + x2s[5]*xyz[2], x2s[6]*xyz[0] + x2s[7]*xyz[1] + x2s[8]*xyz[2] ]; for(var i=0; i<3; i++) rgb[i] = Math.max(0, Math.min(1, UDOC.C.srgbGamma(rgb[i]))); return rgb; } } UDOC.getState = function(crds:any):any { return { font : UDOC.getFont(), dd: {flat:1}, // device-dependent space :"/DeviceGray", // fill ca: 1, colr : [0,0,0], sspace:"/DeviceGray", // stroke CA: 1, COLR : [0,0,0], bmode: "/Normal", SA:false, OPM:0, AIS:false, OP:false, op:false, SMask:"/None", lwidth : 1, lcap: 0, ljoin: 0, mlimit: 10, SM : 0.1, doff: 0, dash: [], ctm : [1,0,0,1,0,0], cpos: [0,0], pth : {cmds:[],crds:[]}, cpth: crds ? UDOC.G.rectToPath(crds) : null // clipping path }; } UDOC.getFont = function() { return { Tc: 0, // character spacing Tw: 0, // word spacing Th:100, // horizontal scale Tl: 0, // leading Tf:"Helvetica-Bold", Tfs:1, // font size Tmode:0, // rendering mode Trise:0, // rise Tk: 0, // knockout Tal:0, // align, 0: left, 1: right, 2: center Tun:0, // 0: no, 1: underline Tm :[1,0,0,1,0,0], Tlm:[1,0,0,1,0,0], Trm:[1,0,0,1,0,0] }; } export let FromEMF:any = function() { } FromEMF.Parse = function(buff:any, genv:any) { buff = new Uint8Array(buff); var off=0; //console.log(buff.slice(0,32)); var prms:any = {fill:false, strk:false, bb:[0,0,1,1], wbb:[0,0,1,1], fnt:{nam:"Arial",hgh:25,und:false,orn:0}, tclr:[0,0,0], talg:0}, gst, tab = [], sts=[]; var rI = FromEMF.B.readShort, rU = FromEMF.B.readUshort, rI32 = FromEMF.B.readInt, rU32 = FromEMF.B.readUint, rF32 = FromEMF.B.readFloat; var opn=0; while(true) { var fnc = rU32(buff, off); off+=4; var fnm = FromEMF.K[fnc]; var siz = rU32(buff, off); off+=4; //if(gst && isNaN(gst.ctm[0])) throw "e"; //console.log(fnc,fnm,siz); var loff = off; //if(opn++==253) break; var obj:any = null, oid = 0; //console.log(fnm, siz); if(false) {} else if(fnm=="EOF") { break; } else if(fnm=="HEADER") { prms.bb = FromEMF._readBox(buff,loff); loff+=16; //console.log(fnm, prms.bb); genv.StartPage(prms.bb[0],prms.bb[1],prms.bb[2],prms.bb[3]); gst = UDOC.getState(prms.bb); } else if(fnm=="SAVEDC") sts.push(JSON.stringify(gst), JSON.stringify(prms)); else if(fnm=="RESTOREDC") { var dif = rI32(buff, loff); loff+=4; while(dif<-1) { sts.pop(); sts.pop(); } prms = JSON.parse(sts.pop()); gst = JSON.parse(sts.pop()); } else if(fnm=="SELECTCLIPPATH") { gst.cpth = JSON.parse(JSON.stringify(gst.pth)); } else if(["SETMAPMODE","SETPOLYFILLMODE","SETBKMODE"/*,"SETVIEWPORTEXTEX"*/,"SETICMMODE","SETROP2","EXTSELECTCLIPRGN"].indexOf(fnm)!=-1) {} //else if(fnm=="INTERSECTCLIPRECT") { var r=prms.crct=FromEMF._readBox(buff, loff); /*var y0=r[1],y1=r[3]; if(y0>y1){r[1]=y1; r[3]=y0;}*/ console.log(prms.crct); } else if(fnm=="SETMITERLIMIT") gst.mlimit = rU32(buff, loff); else if(fnm=="SETTEXTCOLOR") prms.tclr = [buff[loff]/255, buff[loff+1]/255, buff[loff+2]/255]; else if(fnm=="SETTEXTALIGN") prms.talg = rU32(buff, loff); else if(fnm=="SETVIEWPORTEXTEX" || fnm=="SETVIEWPORTORGEX") { if(prms.vbb==null) prms.vbb=[]; var coff = fnm=="SETVIEWPORTORGEX" ? 0 : 2; prms.vbb[coff ] = rI32(buff, loff); loff+=4; prms.vbb[coff+1] = rI32(buff, loff); loff+=4; //console.log(prms.vbb); if(fnm=="SETVIEWPORTEXTEX") FromEMF._updateCtm(prms, gst); } else if(fnm=="SETWINDOWEXTEX" || fnm=="SETWINDOWORGEX") { var coff = fnm=="SETWINDOWORGEX" ? 0 : 2; prms.wbb[coff ] = rI32(buff, loff); loff+=4; prms.wbb[coff+1] = rI32(buff, loff); loff+=4; if(fnm=="SETWINDOWEXTEX") FromEMF._updateCtm(prms, gst); } //else if(fnm=="SETMETARGN") {} else if(fnm=="COMMENT") { var ds = rU32(buff, loff); loff+=4; } else if(fnm=="SELECTOBJECT") { var ind = rU32(buff, loff); loff+=4; //console.log(ind.toString(16), tab, tab[ind]); if (ind==0x80000000) { prms.fill=true ; gst.colr=[1,1,1]; } // white brush else if(ind==0x80000005) { prms.fill=false; } // null brush else if(ind==0x80000007) { prms.strk=true ; prms.lwidth=1; gst.COLR=[0,0,0]; } // black pen else if(ind==0x80000008) { prms.strk=false; } // null pen else if(ind==0x8000000d) {} // system font else if(ind==0x8000000e) {} // device default font else { var co:any = tab[ind]; //console.log(ind, co); if(co.t=="b") { prms.fill=co.stl!=1; if (co.stl==0) {} else if(co.stl==1) {} else throw co.stl+" e"; gst.colr=co.clr; } else if(co.t=="p") { prms.strk=co.stl!=5; gst.lwidth = co.wid; gst.COLR=co.clr; } else if(co.t=="f") { prms.fnt = co; gst.font.Tf = co.nam; gst.font.Tfs = Math.abs(co.hgh); gst.font.Tun = co.und; } else throw "e"; } } else if(fnm=="DELETEOBJECT") { var ind = rU32(buff, loff); loff+=4; if(tab[ind]!=null) tab[ind]=null; else throw "e"; } else if(fnm=="CREATEBRUSHINDIRECT") { oid = rU32(buff, loff); loff+=4; obj = {t:"b"}; obj.stl = rU32(buff, loff); loff+=4; obj.clr = [buff[loff]/255, buff[loff+1]/255, buff[loff+2]/255]; loff+=4; obj.htc = rU32(buff, loff); loff+=4; //console.log(oid, obj); } else if(fnm=="CREATEPEN" || fnm=="EXTCREATEPEN") { oid = rU32(buff, loff); loff+=4; obj = {t:"p"}; if(fnm=="EXTCREATEPEN") { loff+=16; obj.stl = rU32(buff, loff); loff+=4; obj.wid = rU32(buff, loff); loff+=4; //obj.stl = rU32(buff, loff); loff+=4; } else { obj.stl = rU32(buff, loff); loff+=4; obj.wid = rU32(buff, loff); loff+=4; loff+=4; } obj.clr = [buff[loff]/255, buff[loff+1]/255, buff[loff+2]/255]; loff+=4; } else if(fnm=="EXTCREATEFONTINDIRECTW") { oid = rU32(buff, loff); loff+=4; obj = {t:"f", nam:""}; obj.hgh = rI32(buff, loff); loff += 4; loff += 4*2; obj.orn = rI32(buff, loff)/10; loff+=4; var wgh = rU32(buff, loff); loff+=4; //console.log(fnm, obj.orn, wgh); //console.log(rU32(buff,loff), rU32(buff,loff+4), buff.slice(loff,loff+8)); obj.und = buff[loff+1]; obj.stk = buff[loff+2]; loff += 4*2; while(rU(buff,loff)!=0) { obj.nam+=String.fromCharCode(rU(buff,loff)); loff+=2; } if(wgh>500) obj.nam+="-Bold"; //console.log(wgh, obj.nam); } else if(fnm=="EXTTEXTOUTW") { //console.log(buff.slice(loff-8, loff-8+siz)); loff+=16; var mod = rU32(buff, loff); loff+=4; //console.log(mod); var scx = rF32(buff, loff); loff+=4; var scy = rF32(buff, loff); loff+=4; var rfx = rI32(buff, loff); loff+=4; var rfy = rI32(buff, loff); loff+=4; //console.log(mod, scx, scy,rfx,rfy); gst.font.Tm = [1,0,0,-1,0,0]; UDOC.M.rotate(gst.font.Tm, prms.fnt.orn*Math.PI/180); UDOC.M.translate(gst.font.Tm, rfx, rfy); var alg = prms.talg; //console.log(alg.toString(2)); if ((alg&6)==6) gst.font.Tal = 2; else if((alg&7)==0) gst.font.Tal = 0; else throw alg+" e"; if((alg&24)==24) {} // baseline else if((alg&24)==0) UDOC.M.translate(gst.font.Tm, 0, gst.font.Tfs); else throw "e"; var crs = rU32(buff, loff); loff+=4; var ofs = rU32(buff, loff); loff+=4; var ops = rU32(buff, loff); loff+=4; //if(ops!=0) throw "e"; //console.log(ofs,ops,crs); loff+=16; var ofD = rU32(buff, loff); loff+=4; //console.log(ops, ofD, loff, ofs+off-8); ofs += off-8; //console.log(crs, ops); var str = ""; for(var i=0; i<crs; i++) { var cc=rU(buff,ofs+i*2); str+=String.fromCharCode(cc); }; var oclr = gst.colr; gst.colr = prms.tclr; //console.log(str, gst.colr, gst.font.Tm); //var otfs = gst.font.Tfs; gst.font.Tfs *= 1/gst.ctm[0]; genv.PutText(gst, str, str.length*gst.font.Tfs*0.5); gst.colr=oclr; //gst.font.Tfs = otfs; //console.log(rfx, rfy, scx, ops, rcX, rcY, rcW, rcH, offDx, str); } else if(fnm=="BEGINPATH") { UDOC.G.newPath(gst); } else if(fnm=="ENDPATH" ) { } else if(fnm=="CLOSEFIGURE") UDOC.G.closePath(gst); else if(fnm=="MOVETOEX" ) { UDOC.G.moveTo(gst, rI32(buff,loff), rI32(buff,loff+4)); } else if(fnm=="LINETO" ) { if(gst.pth.cmds.length==0) { var im=gst.ctm.slice(0); UDOC.M.invert(im); var p = UDOC.M.multPoint(im, gst.cpos); UDOC.G.moveTo(gst, p[0], p[1]); } UDOC.G.lineTo(gst, rI32(buff,loff), rI32(buff,loff+4)); } else if(fnm=="POLYGON" || fnm=="POLYGON16" || fnm=="POLYLINE" || fnm=="POLYLINE16" || fnm=="POLYLINETO" || fnm=="POLYLINETO16") { loff+=16; var ndf = fnm.startsWith("POLYGON"), isTo = fnm.indexOf("TO")!=-1; var cnt = rU32(buff, loff); loff+=4; if(!isTo) UDOC.G.newPath(gst); loff = FromEMF._drawPoly(buff,loff,cnt,gst, fnm.endsWith("16")?2:4, ndf, isTo); if(!isTo) FromEMF._draw(genv,gst,prms, ndf); //console.log(prms, gst.lwidth); //console.log(JSON.parse(JSON.stringify(gst.pth))); } else if(fnm=="POLYPOLYGON16") { loff+=16; var ndf = fnm.startsWith("POLYPOLYGON"), isTo = fnm.indexOf("TO")!=-1; var nop = rU32(buff, loff); loff+=4; loff+=4; var pi = loff; loff+= nop*4; if(!isTo) UDOC.G.newPath(gst); for(var i=0; i<nop; i++) { var ppp = rU(buff, pi+i*4); loff = FromEMF._drawPoly(buff,loff,ppp,gst, fnm.endsWith("16")?2:4, ndf, isTo); } if(!isTo) FromEMF._draw(genv,gst,prms, ndf); } else if(fnm=="POLYBEZIER" || fnm=="POLYBEZIER16" || fnm=="POLYBEZIERTO" || fnm=="POLYBEZIERTO16") { loff+=16; var is16 = fnm.endsWith("16"), rC = is16?rI:rI32, nl = is16?2:4; var cnt = rU32(buff, loff); loff+=4; if(fnm.indexOf("TO")==-1) { UDOC.G.moveTo(gst, rC(buff,loff), rC(buff,loff+nl)); loff+=2*nl; cnt--; } while(cnt>0) { UDOC.G.curveTo(gst, rC(buff,loff), rC(buff,loff+nl), rC(buff,loff+2*nl), rC(buff,loff+3*nl), rC(buff,loff+4*nl), rC(buff,loff+5*nl) ); loff+=6*nl; cnt-=3; } //console.log(JSON.parse(JSON.stringify(gst.pth))); } else if(fnm=="RECTANGLE" || fnm=="ELLIPSE") { UDOC.G.newPath(gst); var bx = FromEMF._readBox(buff, loff); if(fnm=="RECTANGLE") { UDOC.G.moveTo(gst, bx[0],bx[1]); UDOC.G.lineTo(gst, bx[2],bx[1]); UDOC.G.lineTo(gst, bx[2],bx[3]); UDOC.G.lineTo(gst, bx[0],bx[3]); } else { var x = (bx[0]+bx[2])/2, y = (bx[1]+bx[3])/2; UDOC.G.arc(gst,x,y,(bx[2]-bx[0])/2,0,2*Math.PI, false); } UDOC.G.closePath(gst); FromEMF._draw(genv,gst,prms, true); //console.log(prms, gst.lwidth); } else if(fnm=="FILLPATH" ) genv.Fill(gst, false); else if(fnm=="STROKEPATH") genv.Stroke(gst); else if(fnm=="STROKEANDFILLPATH") { genv.Fill(gst, false); genv.Stroke(gst); } else if(fnm=="SETWORLDTRANSFORM" || fnm=="MODIFYWORLDTRANSFORM") { var mat = []; for(var i=0; i<6; i++) mat.push(rF32(buff,loff+i*4)); loff+=24; //console.log(fnm, gst.ctm.slice(0), mat); if(fnm=="SETWORLDTRANSFORM") gst.ctm=mat; else { var mod = rU32(buff,loff); loff+=4; if(mod==2) { var om=gst.ctm; gst.ctm=mat; UDOC.M.concat(gst.ctm, om); } else throw "e"; } } else if(fnm=="SETSTRETCHBLTMODE") { var sm = rU32(buff, loff); loff+=4; } else if(fnm=="STRETCHDIBITS") { var bx = FromEMF._readBox(buff, loff); loff+=16; var xD = rI32(buff, loff); loff+=4; var yD = rI32(buff, loff); loff+=4; var xS = rI32(buff, loff); loff+=4; var yS = rI32(buff, loff); loff+=4; var wS = rI32(buff, loff); loff+=4; var hS = rI32(buff, loff); loff+=4; var ofH = rU32(buff, loff)+off-8; loff+=4; var szH = rU32(buff, loff); loff+=4; var ofB = rU32(buff, loff)+off-8; loff+=4; var szB = rU32(buff, loff); loff+=4; var usg = rU32(buff, loff); loff+=4; if(usg!=0) throw "e"; var bop = rU32(buff, loff); loff+=4; var wD = rI32(buff, loff); loff+=4; var hD = rI32(buff, loff); loff+=4; //console.log(bop, wD, hD); //console.log(ofH, szH, ofB, szB, ofH+40); //console.log(bx, xD,yD,wD,hD); //console.log(xS,yS,wS,hS); //console.log(ofH,szH,ofB,szB,usg,bop); var hl = rU32(buff, ofH); ofH+=4; var w = rU32(buff, ofH); ofH+=4; var h = rU32(buff, ofH); ofH+=4; if(w!=wS || h!=hS) throw "e"; var ps = rU (buff, ofH); ofH+=2; var bc = rU (buff, ofH); ofH+=2; if(bc!=8 && bc!=24 && bc!=32) throw bc+" e"; var cpr= rU32(buff, ofH); ofH+=4; if(cpr!=0) throw cpr+" e"; var sz = rU32(buff, ofH); ofH+=4; var xpm= rU32(buff, ofH); ofH+=4; var ypm= rU32(buff, ofH); ofH+=4; var cu = rU32(buff, ofH); ofH+=4; var ci = rU32(buff, ofH); ofH+=4; //console.log(hl, w, h, ps, bc, cpr, sz, xpm, ypm, cu, ci); //console.log(hl,w,h,",",xS,yS,wS,hS,",",xD,yD,wD,hD,",",xpm,ypm); var rl = Math.floor(((w * ps * bc + 31) & ~31) / 8); var img = new Uint8Array(w*h*4); if(bc==8) { for(var y=0; y<h; y++) for(var x=0; x<w; x++) { var qi = (y*w+x)<<2, ind:any = buff[ofB+(h-1-y)*rl+x]<<2; img[qi ] = buff[ofH+ind+2]; img[qi+1] = buff[ofH+ind+1]; img[qi+2] = buff[ofH+ind+0]; img[qi+3] = 255; } } if(bc==24) { for(var y=0; y<h; y++) for(var x=0; x<w; x++) { var qi = (y*w+x)<<2, ti=ofB+(h-1-y)*rl+x*3; img[qi ] = buff[ti+2]; img[qi+1] = buff[ti+1]; img[qi+2] = buff[ti+0]; img[qi+3] = 255; } } if(bc==32) { for(var y=0; y<h; y++) for(var x=0; x<w; x++) { var qi = (y*w+x)<<2, ti=ofB+(h-1-y)*rl+x*4; img[qi ] = buff[ti+2]; img[qi+1] = buff[ti+1]; img[qi+2] = buff[ti+0]; img[qi+3] = buff[ti+3]; } } var ctm = gst.ctm.slice(0); gst.ctm = [1,0,0,1,0,0]; UDOC.M.scale(gst.ctm, wD, -hD); UDOC.M.translate(gst.ctm, xD, yD+hD); UDOC.M.concat(gst.ctm, ctm); genv.PutImage(gst, img, w, h); gst.ctm = ctm; } else { console.log(fnm, siz); } if(obj!=null) tab[oid]=obj; off+=siz-8; } //genv.Stroke(gst); genv.ShowPage(); genv.Done(); } FromEMF._readBox = function(buff:any, off:any) { var b=[]; for(var i=0; i<4; i++) b[i] = FromEMF.B.readInt(buff,off+i*4); return b; } FromEMF._updateCtm = function(prms:any, gst:any) { var mat = [1,0,0,1,0,0]; var wbb = prms.wbb, bb = prms.bb, vbb=(prms.vbb && prms.vbb.length==4) ? prms.vbb:prms.bb; //var y0 = bb[1], y1 = bb[3]; bb[1]=Math.min(y0,y1); bb[3]=Math.max(y0,y1); UDOC.M.translate(mat, -wbb[0],-wbb[1]); UDOC.M.scale(mat, 1/wbb[2], 1/wbb[3]); UDOC.M.scale(mat, vbb[2], vbb[3]); //UDOC.M.scale(mat, vbb[2]/(bb[2]-bb[0]), vbb[3]/(bb[3]-bb[1])); //UDOC.M.scale(mat, bb[2]-bb[0],bb[3]-bb[1]); gst.ctm = mat; } FromEMF._draw = function(genv:any, gst:any, prms:any, needFill:any) { if(prms.fill && needFill ) genv.Fill (gst, false); if(prms.strk && gst.lwidth!=0) genv.Stroke(gst); } FromEMF._drawPoly = function(buff:any, off:any, ppp:any, gst:any, nl:any, clos:any, justLine:any) { var rS = nl==2 ? FromEMF.B.readShort : FromEMF.B.readInt; for(var j=0; j<ppp; j++) { var px = rS(buff, off); off+=nl; var py = rS(buff, off); off+=nl; if(j==0 && !justLine) UDOC.G.moveTo(gst,px,py); else UDOC.G.lineTo(gst,px,py); } if(clos) UDOC.G.closePath(gst); return off; } FromEMF.B = { uint8 : new Uint8Array(4), readShort : function(buff:any,p:any):any { var u8=FromEMF.B.uint8; u8[0]=buff[p]; u8[1]=buff[p+1]; return FromEMF.B.int16 [0]; }, readUshort : function(buff:any,p:any):any { var u8=FromEMF.B.uint8; u8[0]=buff[p]; u8[1]=buff[p+1]; return FromEMF.B.uint16[0]; }, readInt : function(buff:any,p:any):any { var u8=FromEMF.B.uint8; u8[0]=buff[p]; u8[1]=buff[p+1]; u8[2]=buff[p+2]; u8[3]=buff[p+3]; return FromEMF.B.int32 [0]; }, readUint : function(buff:any,p:any):any { var u8=FromEMF.B.uint8; u8[0]=buff[p]; u8[1]=buff[p+1]; u8[2]=buff[p+2]; u8[3]=buff[p+3]; return FromEMF.B.uint32[0]; }, readFloat : function(buff:any,p:any):any { var u8=FromEMF.B.uint8; u8[0]=buff[p]; u8[1]=buff[p+1]; u8[2]=buff[p+2]; u8[3]=buff[p+3]; return FromEMF.B.flot32[0]; }, readASCII : function(buff:any,p:any,l:any):any { var s = ""; for(var i=0; i<l; i++) s += String.fromCharCode(buff[p+i]); return s; } } FromEMF.B.int16 = new Int16Array (FromEMF.B.uint8.buffer); FromEMF.B.uint16 = new Uint16Array(FromEMF.B.uint8.buffer); FromEMF.B.int32 = new Int32Array (FromEMF.B.uint8.buffer); FromEMF.B.uint32 = new Uint32Array(FromEMF.B.uint8.buffer); FromEMF.B.flot32 = new Float32Array(FromEMF.B.uint8.buffer); FromEMF.C = { EMR_HEADER : 0x00000001, EMR_POLYBEZIER : 0x00000002, EMR_POLYGON : 0x00000003, EMR_POLYLINE : 0x00000004, EMR_POLYBEZIERTO : 0x00000005, EMR_POLYLINETO : 0x00000006, EMR_POLYPOLYLINE : 0x00000007, EMR_POLYPOLYGON : 0x00000008, EMR_SETWINDOWEXTEX : 0x00000009, EMR_SETWINDOWORGEX : 0x0000000A, EMR_SETVIEWPORTEXTEX : 0x0000000B, EMR_SETVIEWPORTORGEX : 0x0000000C, EMR_SETBRUSHORGEX : 0x0000000D, EMR_EOF : 0x0000000E, EMR_SETPIXELV : 0x0000000F, EMR_SETMAPPERFLAGS : 0x00000010, EMR_SETMAPMODE : 0x00000011, EMR_SETBKMODE : 0x00000012, EMR_SETPOLYFILLMODE : 0x00000013, EMR_SETROP2 : 0x00000014, EMR_SETSTRETCHBLTMODE : 0x00000015, EMR_SETTEXTALIGN : 0x00000016, EMR_SETCOLORADJUSTMENT : 0x00000017, EMR_SETTEXTCOLOR : 0x00000018, EMR_SETBKCOLOR : 0x00000019, EMR_OFFSETCLIPRGN : 0x0000001A, EMR_MOVETOEX : 0x0000001B, EMR_SETMETARGN : 0x0000001C, EMR_EXCLUDECLIPRECT : 0x0000001D, EMR_INTERSECTCLIPRECT : 0x0000001E, EMR_SCALEVIEWPORTEXTEX : 0x0000001F, EMR_SCALEWINDOWEXTEX : 0x00000020, EMR_SAVEDC : 0x00000021, EMR_RESTOREDC : 0x00000022, EMR_SETWORLDTRANSFORM : 0x00000023, EMR_MODIFYWORLDTRANSFORM : 0x00000024, EMR_SELECTOBJECT : 0x00000025, EMR_CREATEPEN : 0x00000026, EMR_CREATEBRUSHINDIRECT : 0x00000027, EMR_DELETEOBJECT : 0x00000028, EMR_ANGLEARC : 0x00000029, EMR_ELLIPSE : 0x0000002A, EMR_RECTANGLE : 0x0000002B, EMR_ROUNDRECT : 0x0000002C, EMR_ARC : 0x0000002D, EMR_CHORD : 0x0000002E, EMR_PIE : 0x0000002F, EMR_SELECTPALETTE : 0x00000030, EMR_CREATEPALETTE : 0x00000031, EMR_SETPALETTEENTRIES : 0x00000032, EMR_RESIZEPALETTE : 0x00000033, EMR_REALIZEPALETTE : 0x00000034, EMR_EXTFLOODFILL : 0x00000035, EMR_LINETO : 0x00000036, EMR_ARCTO : 0x00000037, EMR_POLYDRAW : 0x00000038, EMR_SETARCDIRECTION : 0x00000039, EMR_SETMITERLIMIT : 0x0000003A, EMR_BEGINPATH : 0x0000003B, EMR_ENDPATH : 0x0000003C, EMR_CLOSEFIGURE : 0x0000003D, EMR_FILLPATH : 0x0000003E, EMR_STROKEANDFILLPATH : 0x0000003F, EMR_STROKEPATH : 0x00000040, EMR_FLATTENPATH : 0x00000041, EMR_WIDENPATH : 0x00000042, EMR_SELECTCLIPPATH : 0x00000043, EMR_ABORTPATH : 0x00000044, EMR_COMMENT : 0x00000046, EMR_FILLRGN : 0x00000047, EMR_FRAMERGN : 0x00000048, EMR_INVERTRGN : 0x00000049, EMR_PAINTRGN : 0x0000004A, EMR_EXTSELECTCLIPRGN : 0x0000004B, EMR_BITBLT : 0x0000004C, EMR_STRETCHBLT : 0x0000004D, EMR_MASKBLT : 0x0000004E, EMR_PLGBLT : 0x0000004F, EMR_SETDIBITSTODEVICE : 0x00000050, EMR_STRETCHDIBITS : 0x00000051, EMR_EXTCREATEFONTINDIRECTW : 0x00000052, EMR_EXTTEXTOUTA : 0x00000053, EMR_EXTTEXTOUTW : 0x00000054, EMR_POLYBEZIER16 : 0x00000055, EMR_POLYGON16 : 0x00000056, EMR_POLYLINE16 : 0x00000057, EMR_POLYBEZIERTO16 : 0x00000058, EMR_POLYLINETO16 : 0x00000059, EMR_POLYPOLYLINE16 : 0x0000005A, EMR_POLYPOLYGON16 : 0x0000005B, EMR_POLYDRAW16 : 0x0000005C, EMR_CREATEMONOBRUSH : 0x0000005D, EMR_CREATEDIBPATTERNBRUSHPT : 0x0000005E, EMR_EXTCREATEPEN : 0x0000005F, EMR_POLYTEXTOUTA : 0x00000060, EMR_POLYTEXTOUTW : 0x00000061, EMR_SETICMMODE : 0x00000062, EMR_CREATECOLORSPACE : 0x00000063, EMR_SETCOLORSPACE : 0x00000064, EMR_DELETECOLORSPACE : 0x00000065, EMR_GLSRECORD : 0x00000066, EMR_GLSBOUNDEDRECORD : 0x00000067, EMR_PIXELFORMAT : 0x00000068, EMR_DRAWESCAPE : 0x00000069, EMR_EXTESCAPE : 0x0000006A, EMR_SMALLTEXTOUT : 0x0000006C, EMR_FORCEUFIMAPPING : 0x0000006D, EMR_NAMEDESCAPE : 0x0000006E, EMR_COLORCORRECTPALETTE : 0x0000006F, EMR_SETICMPROFILEA : 0x00000070, EMR_SETICMPROFILEW : 0x00000071, EMR_ALPHABLEND : 0x00000072, EMR_SETLAYOUT : 0x00000073, EMR_TRANSPARENTBLT : 0x00000074, EMR_GRADIENTFILL : 0x00000076, EMR_SETLINKEDUFIS : 0x00000077, EMR_SETTEXTJUSTIFICATION : 0x00000078, EMR_COLORMATCHTOTARGETW : 0x00000079, EMR_CREATECOLORSPACEW : 0x0000007A }; FromEMF.K = []; // (function() { // var inp, out, stt; // inp = FromEMF.C; out = FromEMF.K; stt=4; // for(var p in inp) out[inp[p]] = p.slice(stt); // } )(); export let ToContext2D:any = function (needPage:any, scale:any) { this.canvas = document.createElement("canvas"); this.ctx = this.canvas.getContext("2d"); this.bb = null; this.currPage = 0; this.needPage = needPage; this.scale = scale; } ToContext2D.prototype.StartPage = function(x:any,y:any,w:any,h:any) { if(this.currPage!=this.needPage) return; this.bb = [x,y,w,h]; var scl = this.scale, dpr = window.devicePixelRatio; var cnv = this.canvas, ctx = this.ctx; cnv.width = Math.round(w*scl); cnv.height = Math.round(h*scl); ctx.translate(0,h*scl); ctx.scale(scl,-scl); cnv.setAttribute("style", "border:1px solid; width:"+(cnv.width/dpr)+"px; height:"+(cnv.height/dpr)+"px"); } ToContext2D.prototype.Fill = function(gst:any, evenOdd:any) { if(this.currPage!=this.needPage) return; var ctx = this.ctx; ctx.beginPath(); this._setStyle(gst, ctx); this._draw(gst.pth, ctx); ctx.fill(); } ToContext2D.prototype.Stroke = function(gst:any) { if(this.currPage!=this.needPage) return; var ctx = this.ctx; ctx.beginPath(); this._setStyle(gst, ctx); this._draw(gst.pth, ctx); ctx.stroke(); } ToContext2D.prototype.PutText = function(gst:any, str:any, stw:any) { if(this.currPage!=this.needPage) return; var scl = this._scale(gst.ctm); var ctx = this.ctx; this._setStyle(gst, ctx); ctx.save(); var m = [1,0,0,-1,0,0]; this._concat(m, gst.font.Tm); this._concat(m, gst.ctm); //console.log(str, m, gst); throw "e"; ctx.transform(m[0],m[1],m[2],m[3],m[4],m[5]); ctx.fillText(str,0,0); ctx.restore(); } ToContext2D.prototype.PutImage = function(gst:any, buff:any, w:any, h:any, msk:any) { if(this.currPage!=this.needPage) return; var ctx = this.ctx; if(buff.length==w*h*4) { buff = buff.slice(0); if(msk && msk.length==w*h*4) for(var i=0; i<buff.length; i+=4) buff[i+3] = msk[i+1]; var cnv = document.createElement("canvas"), cctx = cnv.getContext("2d"); cnv.width = w; cnv.height = h; var imgd = cctx.createImageData(w,h); for(var i=0; i<buff.length; i++) imgd.data[i]=buff[i]; cctx.putImageData(imgd,0,0); ctx.save(); var m = [1,0,0,1,0,0]; this._concat(m, [1/w,0,0,-1/h,0,1]); this._concat(m, gst.ctm); ctx.transform(m[0],m[1],m[2],m[3],m[4],m[5]); ctx.drawImage(cnv,0,0); ctx.restore(); } } ToContext2D.prototype.ShowPage = function() { this.currPage++; } ToContext2D.prototype.Done = function() {} function _flt(n:any) { return ""+parseFloat(n.toFixed(2)); } ToContext2D.prototype._setStyle = function(gst:any, ctx:any) { var scl = this._scale(gst.ctm); ctx.fillStyle = this._getFill(gst.colr, gst.ca, ctx); ctx.strokeStyle=this._getFill(gst.COLR, gst.CA, ctx); ctx.lineCap = ["butt","round","square"][gst.lcap]; ctx.lineJoin= ["miter","round","bevel"][gst.ljoin]; ctx.lineWidth=gst.lwidth*scl; var dsh = gst.dash.slice(0); for(var i=0; i<dsh.length; i++) dsh[i] = _flt(dsh[i]*scl); ctx.setLineDash(dsh); ctx.miterLimit = gst.mlimit*scl; var fn = gst.font.Tf, ln = fn.toLowerCase(); var p0 = ln.indexOf("bold")!=-1 ? "bold " : ""; var p1 = (ln.indexOf("italic")!=-1 || ln.indexOf("oblique")!=-1) ? "italic " : ""; ctx.font = p0+p1 + gst.font.Tfs+"px \""+fn+"\""; } ToContext2D.prototype._getFill = function(colr:any, ca:any, ctx:any) { if(colr.typ==null) return this._colr(colr,ca); else { var grd = colr, crd = grd.crds, mat = grd.mat, scl=this._scale(mat), gf; if (grd.typ=="lin") { var p0 = this._multPoint(mat,crd.slice(0,2)), p1 = this._multPoint(mat,crd.slice(2)); gf=ctx.createLinearGradient(p0[0],p0[1],p1[0],p1[1]); } else if(grd.typ=="rad") { var p0 = this._multPoint(mat,crd.slice(0,2)), p1 = this._multPoint(mat,crd.slice(3)); gf=ctx.createRadialGradient(p0[0],p0[1],crd[2]*scl,p1[0],p1[1],crd[5]*scl); } for(var i=0; i<grd.grad.length; i++) gf.addColorStop(grd.grad[i][0],this._colr(grd.grad[i][1], ca)); return gf; } } ToContext2D.prototype._colr = function(c:any,a:any) { return "rgba("+Math.round(c[0]*255)+","+Math.round(c[1]*255)+","+Math.round(c[2]*255)+","+a+")"; }; ToContext2D.prototype._scale = function(m:any) { return Math.sqrt(Math.abs(m[0]*m[3]-m[1]*m[2])); }; ToContext2D.prototype._concat= function(m:any,w:any ) { var a=m[0],b=m[1],c=m[2],d=m[3],tx=m[4],ty=m[5]; m[0] = (a *w[0])+(b *w[2]); m[1] = (a *w[1])+(b *w[3]); m[2] = (c *w[0])+(d *w[2]); m[3] = (c *w[1])+(d *w[3]); m[4] = (tx*w[0])+(ty*w[2])+w[4]; m[5] = (tx*w[1])+(ty*w[3])+w[5]; } ToContext2D.prototype._multPoint= function(m:any, p:any) { var x=p[0],y=p[1]; return [x*m[0]+y*m[2]+m[4], x*m[1]+y*m[3]+m[5]]; }, ToContext2D.prototype._draw = function(path:any, ctx:any) { var c = 0, crds = path.crds; for(var j=0; j<path.cmds.length; j++) { var cmd = path.cmds[j]; if (cmd=="M") { ctx.moveTo(crds[c], crds[c+1]); c+=2; } else if(cmd=="L") { ctx.lineTo(crds[c], crds[c+1]); c+=2; } else if(cmd=="C") { ctx.bezierCurveTo(crds[c], crds[c+1], crds[c+2], crds[c+3], crds[c+4], crds[c+5]); c+=6; } else if(cmd=="Q") { ctx.quadraticCurveTo(crds[c], crds[c+1], crds[c+2], crds[c+3]); c+=4; } else if(cmd=="Z") { ctx.closePath(); } } }
the_stack
import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3"; import Cartographic from "terriajs-cesium/Source/Core/Cartographic"; import DeveloperError from "terriajs-cesium/Source/Core/DeveloperError"; import Ellipsoid from "terriajs-cesium/Source/Core/Ellipsoid"; import HeadingPitchRange from "terriajs-cesium/Source/Core/HeadingPitchRange"; import HeadingPitchRoll from "terriajs-cesium/Source/Core/HeadingPitchRoll"; import CesiumMath from "terriajs-cesium/Source/Core/Math"; import Matrix3 from "terriajs-cesium/Source/Core/Matrix3"; import Matrix4 from "terriajs-cesium/Source/Core/Matrix4"; import Quaternion from "terriajs-cesium/Source/Core/Quaternion"; import Rectangle from "terriajs-cesium/Source/Core/Rectangle"; import Transforms from "terriajs-cesium/Source/Core/Transforms"; import JsonValue, { isJsonNumber, isJsonObject, JsonObject } from "../Core/Json"; import TerriaError from "../Core/TerriaError"; /** * Holds a camera's view parameters, expressed as a rectangular extent and/or as a camera position, direction, * and up vector. */ export default class CameraView { /** * Gets the rectangular extent of the view. If {@link CameraView#position}, {@link CameraView#direction}, * and {@link CameraView#up} are specified, this property will be ignored for viewers that support those parameters * (e.g. Cesium). This property must always be supplied, however, for the benefit of viewers that do not understand * these parameters (e.g. Leaflet). */ readonly rectangle: Readonly<Rectangle>; /** * Gets the position of the camera in the Earth-centered Fixed frame. */ readonly position: Readonly<Cartesian3> | undefined; /** * Gets the look direction of the camera in the Earth-centered Fixed frame. */ readonly direction: Readonly<Cartesian3> | undefined; /** * Gets the up vector direction of the camera in the Earth-centered Fixed frame. */ readonly up: Readonly<Cartesian3> | undefined; constructor( rectangle: Rectangle, position?: Cartesian3, direction?: Cartesian3, up?: Cartesian3 ) { this.rectangle = Rectangle.clone(rectangle); if (position !== undefined || direction !== undefined || up !== undefined) { if ( position === undefined || direction === undefined || up === undefined ) { throw new DeveloperError( "If any of position, direction, or up are specified, all must be specified." ); } this.position = Cartesian3.clone(position); this.direction = Cartesian3.clone(direction); this.up = Cartesian3.clone(up); } } toJson(): JsonObject { const result: JsonObject = { west: CesiumMath.toDegrees(this.rectangle.west), south: CesiumMath.toDegrees(this.rectangle.south), east: CesiumMath.toDegrees(this.rectangle.east), north: CesiumMath.toDegrees(this.rectangle.north) }; if (this.position && this.direction && this.up) { function vectorToJson(vector: Readonly<Cartesian3>) { return { x: vector.x, y: vector.y, z: vector.z }; } result.position = vectorToJson(this.position); result.direction = vectorToJson(this.direction); result.up = vectorToJson(this.up); } return result; } /** * Constructs a {@link CameraView} from json. All angles must be specified in degrees. * If neither json.lookAt nor json.positionHeadingPitchRoll is present, then json should have the keys position, direction, up, west, south, east, north. * @param {Object} json The JSON description. The JSON should be in the form of an object literal, not a string. * @param {Object} [json.lookAt] If present, must include keys targetLongitude, targetLatitude, targetHeight, heading, pitch, range. * @param {Object} [json.positionHeadingPitchRoll] If present, must include keys cameraLongitude, cameraLatitude, cameraHeight, heading, pitch, roll. * @return {CameraView} The camera view. */ static fromJson(json: JsonObject) { const lookAt = json.lookAt; const positionHeadingPitchRoll = json.positionHeadingPitchRoll; if (isJsonObject(lookAt)) { if ( !isJsonNumber(lookAt.targetLongitude) || !isJsonNumber(lookAt.targetLatitude) || !isJsonNumber(lookAt.targetHeight) || !isJsonNumber(lookAt.heading) || !isJsonNumber(lookAt.pitch) || !isJsonNumber(lookAt.range) ) { throw new TerriaError({ sender: CameraView, title: "Invalid CameraView", message: "`lookAt` must have `targetLongitude`, `targetLatitude`, " + "`targetHeight`, `heading`, `pitch`, and `range` properties, " + "and all must be numbers." }); } const targetPosition = Cartographic.fromDegrees( lookAt.targetLongitude, lookAt.targetLatitude, lookAt.targetHeight ); const headingPitchRange = new HeadingPitchRange( CesiumMath.toRadians(lookAt.heading), CesiumMath.toRadians(lookAt.pitch), lookAt.range ); return CameraView.fromLookAt(targetPosition, headingPitchRange); } else if (isJsonObject(positionHeadingPitchRoll)) { if ( !isJsonNumber(positionHeadingPitchRoll.cameraLongitude) || !isJsonNumber(positionHeadingPitchRoll.cameraLatitude) || !isJsonNumber(positionHeadingPitchRoll.cameraHeight) || !isJsonNumber(positionHeadingPitchRoll.heading) || !isJsonNumber(positionHeadingPitchRoll.pitch) || !isJsonNumber(positionHeadingPitchRoll.roll) ) { throw new TerriaError({ sender: CameraView, title: "Invalid CameraView", message: "`positionHeadingPitchRoll` must have `cameraLongitude`, " + "`cameraLatitude`, `cameraHeight`, `heading`, `pitch`, and " + "`roll` properties, and all must be numbers." }); } const cameraPosition = Cartographic.fromDegrees( positionHeadingPitchRoll.cameraLongitude, positionHeadingPitchRoll.cameraLatitude, positionHeadingPitchRoll.cameraHeight ); return CameraView.fromPositionHeadingPitchRoll( cameraPosition, CesiumMath.toRadians(positionHeadingPitchRoll.heading), CesiumMath.toRadians(positionHeadingPitchRoll.pitch), CesiumMath.toRadians(positionHeadingPitchRoll.roll) ); } else { if ( !isJsonNumber(json.west) || !isJsonNumber(json.south) || !isJsonNumber(json.east) || !isJsonNumber(json.north) ) { throw new TerriaError({ sender: CameraView, title: "Invalid CameraView", message: "The `west`, `south`, `east`, and `north` properties are " + "required and must be numbers, specified in degrees." }); } const rectangle = Rectangle.fromDegrees( json.west, json.south, json.east, json.north ); if ( isVector(json.position) && isVector(json.direction) && isVector(json.up) ) { return new CameraView( rectangle, new Cartesian3(json.position.x, json.position.y, json.position.z), new Cartesian3(json.direction.x, json.direction.y, json.direction.z), new Cartesian3(json.up.x, json.up.y, json.up.z) ); } else { return new CameraView(rectangle); } } } /** * Constructs a {@link CameraView} from a "look at" description. * @param targetPosition The position to look at. * @param headingPitchRange The offset of the camera from the target position. * @return The camera view. */ static fromLookAt = function( targetPosition: Readonly<Cartographic>, headingPitchRange: Readonly<HeadingPitchRange> ): CameraView { const positionENU = offsetFromHeadingPitchRange( headingPitchRange.heading, -headingPitchRange.pitch, headingPitchRange.range, scratchPosition ); const directionENU = Cartesian3.normalize( Cartesian3.negate(positionENU, scratchDirection), scratchDirection ); const rightENU = Cartesian3.cross( directionENU, Cartesian3.UNIT_Z, scratchRight ); if (Cartesian3.magnitudeSquared(rightENU) < CesiumMath.EPSILON10) { Cartesian3.clone(Cartesian3.UNIT_X, rightENU); } Cartesian3.normalize(rightENU, rightENU); var upENU = Cartesian3.cross(rightENU, directionENU, scratchUp); Cartesian3.normalize(upENU, upENU); const targetCartesian = Ellipsoid.WGS84.cartographicToCartesian( targetPosition, scratchTarget ); const transform = Transforms.eastNorthUpToFixedFrame( targetCartesian, Ellipsoid.WGS84, scratchMatrix4 ); const offsetECF = Matrix4.multiplyByPointAsVector( transform, positionENU, scratchOffset ); const position = Cartesian3.add( targetCartesian, offsetECF, new Cartesian3() ); const direction = Cartesian3.normalize( Cartesian3.negate(offsetECF, new Cartesian3()), new Cartesian3() ); const up = Matrix4.multiplyByPointAsVector( transform, upENU, new Cartesian3() ); // Estimate a rectangle for this view. const fieldOfViewHalfAngle = CesiumMath.toRadians(30); const groundDistance = Math.tan(fieldOfViewHalfAngle) * (headingPitchRange.range + targetPosition.height); const angle = groundDistance / Ellipsoid.WGS84.minimumRadius; const extent = new Rectangle( targetPosition.longitude - angle, targetPosition.latitude - angle, targetPosition.longitude + angle, targetPosition.latitude + angle ); return new CameraView(extent, position, direction, up); }; /** * Constructs a {@link CameraView} from a camera position and heading, pitch, and roll angles for the camera. * @param cameraPosition The position of the camera. * @param heading The heading of the camera in radians measured from North toward East. * @param pitch The pitch of the camera in radians measured from the local horizontal. Positive angles look up, negative angles look down. * @param roll The roll of the camera in radians counterclockwise. */ static fromPositionHeadingPitchRoll( cameraPosition: Readonly<Cartographic>, heading: number, pitch: number, roll: number ): CameraView { const hpr = new HeadingPitchRoll( heading - CesiumMath.PI_OVER_TWO, pitch, roll ); const rotQuat = Quaternion.fromHeadingPitchRoll(hpr, scratchQuaternion); const rotMat = Matrix3.fromQuaternion(rotQuat, scratchMatrix3); const directionENU = Matrix3.getColumn(rotMat, 0, scratchDirection); const upENU = Matrix3.getColumn(rotMat, 2, scratchUp); const positionECF = Ellipsoid.WGS84.cartographicToCartesian( cameraPosition, scratchTarget ); const transform = Transforms.eastNorthUpToFixedFrame( positionECF, Ellipsoid.WGS84, scratchMatrix4 ); const directionECF = Matrix4.multiplyByPointAsVector( transform, directionENU, new Cartesian3() ); const upECF = Matrix4.multiplyByPointAsVector( transform, upENU, new Cartesian3() ); // Estimate a rectangle for this view. const fieldOfViewHalfAngle = CesiumMath.toRadians(30); const groundDistance = Math.tan(fieldOfViewHalfAngle) * cameraPosition.height; const angle = groundDistance / Ellipsoid.WGS84.minimumRadius; const extent = new Rectangle( cameraPosition.longitude - angle, cameraPosition.latitude - angle, cameraPosition.longitude + angle, cameraPosition.latitude + angle ); return new CameraView(extent, positionECF, directionECF, upECF); } } function isVector( value: JsonValue ): value is { x: number; y: number; z: number } { return ( isJsonObject(value) && isJsonNumber(value.x) && isJsonNumber(value.y) && isJsonNumber(value.z) ); } const scratchPosition = new Cartesian3(); const scratchOffset = new Cartesian3(); const scratchDirection = new Cartesian3(); const scratchRight = new Cartesian3(); const scratchUp = new Cartesian3(); const scratchTarget = new Cartesian3(); const scratchMatrix4 = new Matrix4(); const scratchQuaternion = new Quaternion(); const scratchMatrix3 = new Matrix3(); const scratchLookAtHeadingPitchRangeQuaternion1 = new Quaternion(); const scratchLookAtHeadingPitchRangeQuaternion2 = new Quaternion(); const scratchHeadingPitchRangeMatrix3 = new Matrix3(); function offsetFromHeadingPitchRange( heading: number, pitch: number, range: number, result?: Cartesian3 ): Cartesian3 { pitch = CesiumMath.clamp( pitch, -CesiumMath.PI_OVER_TWO, CesiumMath.PI_OVER_TWO ); heading = CesiumMath.zeroToTwoPi(heading) - CesiumMath.PI_OVER_TWO; const pitchQuat = Quaternion.fromAxisAngle( Cartesian3.UNIT_Y, -pitch, scratchLookAtHeadingPitchRangeQuaternion1 ); const headingQuat = Quaternion.fromAxisAngle( Cartesian3.UNIT_Z, -heading, scratchLookAtHeadingPitchRangeQuaternion2 ); const rotQuat = Quaternion.multiply(headingQuat, pitchQuat, headingQuat); const rotMatrix = Matrix3.fromQuaternion( rotQuat, scratchHeadingPitchRangeMatrix3 ); const offset = Cartesian3.clone(Cartesian3.UNIT_X, result); Matrix3.multiplyByVector(rotMatrix, offset, offset); Cartesian3.negate(offset, offset); Cartesian3.multiplyByScalar(offset, range, offset); return offset; }
the_stack
import { flatbuffers } from "flatbuffers"; import ByteBuffer = flatbuffers.ByteBuffer; import { TypedArray, TypedArrayConstructor } from "../interfaces"; import { BigIntArray, BigIntArrayConstructor } from "../interfaces"; /** @ignore */ export declare function memcpy< TTarget extends ArrayBufferView, TSource extends ArrayBufferView >( target: TTarget, source: TSource, targetByteOffset?: number, sourceByteLength?: number ): TTarget; /** @ignore */ export declare function joinUint8Arrays( chunks: Uint8Array[], size?: number | null ): [Uint8Array, Uint8Array[], number]; /** @ignore */ export declare type ArrayBufferViewInput = | ArrayBufferView | ArrayBufferLike | ArrayBufferView | Iterable<number> | ArrayLike<number> | ByteBuffer | string | null | undefined | IteratorResult< | ArrayBufferView | ArrayBufferLike | ArrayBufferView | Iterable<number> | ArrayLike<number> | ByteBuffer | string | null | undefined > | ReadableStreamReadResult< | ArrayBufferView | ArrayBufferLike | ArrayBufferView | Iterable<number> | ArrayLike<number> | ByteBuffer | string | null | undefined >; /** @ignore */ export declare function toArrayBufferView<T extends TypedArray>( ArrayBufferViewCtor: TypedArrayConstructor<T>, input: ArrayBufferViewInput ): T; export declare function toArrayBufferView<T extends BigIntArray>( ArrayBufferViewCtor: BigIntArrayConstructor<T>, input: ArrayBufferViewInput ): T; /** @ignore */ export declare const toInt8Array: ( input: ArrayBufferViewInput ) => Int8Array; /** @ignore */ export declare const toInt16Array: ( input: ArrayBufferViewInput ) => Int16Array; /** @ignore */ export declare const toInt32Array: ( input: ArrayBufferViewInput ) => Int32Array; /** @ignore */ export declare const toBigInt64Array: ( input: ArrayBufferViewInput ) => BigInt64Array; /** @ignore */ export declare const toUint8Array: ( input: ArrayBufferViewInput ) => Uint8Array; /** @ignore */ export declare const toUint16Array: ( input: ArrayBufferViewInput ) => Uint16Array; /** @ignore */ export declare const toUint32Array: ( input: ArrayBufferViewInput ) => Uint32Array; /** @ignore */ export declare const toBigUint64Array: ( input: ArrayBufferViewInput ) => BigUint64Array; /** @ignore */ export declare const toFloat32Array: ( input: ArrayBufferViewInput ) => Float32Array; /** @ignore */ export declare const toFloat64Array: ( input: ArrayBufferViewInput ) => Float64Array; /** @ignore */ export declare const toUint8ClampedArray: ( input: ArrayBufferViewInput ) => Uint8ClampedArray; /** @ignore */ declare type ArrayBufferViewIteratorInput = | Iterable<ArrayBufferViewInput> | ArrayBufferViewInput; /** @ignore */ export declare function toArrayBufferViewIterator<T extends TypedArray>( ArrayCtor: TypedArrayConstructor<T>, source: ArrayBufferViewIteratorInput ): IterableIterator<T>; /** @ignore */ export declare const toInt8ArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Int8Array>; /** @ignore */ export declare const toInt16ArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Int16Array>; /** @ignore */ export declare const toInt32ArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Int32Array>; /** @ignore */ export declare const toUint8ArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Uint8Array>; /** @ignore */ export declare const toUint16ArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Uint16Array>; /** @ignore */ export declare const toUint32ArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Uint32Array>; /** @ignore */ export declare const toFloat32ArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Float32Array>; /** @ignore */ export declare const toFloat64ArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Float64Array>; /** @ignore */ export declare const toUint8ClampedArrayIterator: ( input: | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | IteratorResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | ReadableStreamReadResult< | string | ArrayBuffer | SharedArrayBuffer | ArrayBufferView | ArrayLike<number> | Iterable<number> | flatbuffers.ByteBuffer | null | undefined > | Iterable<ArrayBufferViewInput> | null | undefined ) => IterableIterator<Uint8ClampedArray>; /** @ignore */ declare type ArrayBufferViewAsyncIteratorInput = | AsyncIterable<ArrayBufferViewInput> | Iterable<ArrayBufferViewInput> | PromiseLike<ArrayBufferViewInput> | ArrayBufferViewInput; /** @ignore */ export declare function toArrayBufferViewAsyncIterator<T extends TypedArray>( ArrayCtor: TypedArrayConstructor<T>, source: ArrayBufferViewAsyncIteratorInput ): AsyncIterableIterator<T>; /** @ignore */ export declare const toInt8ArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Int8Array>; /** @ignore */ export declare const toInt16ArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Int16Array>; /** @ignore */ export declare const toInt32ArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Int32Array>; /** @ignore */ export declare const toUint8ArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Uint8Array>; /** @ignore */ export declare const toUint16ArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Uint16Array>; /** @ignore */ export declare const toUint32ArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Uint32Array>; /** @ignore */ export declare const toFloat32ArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Float32Array>; /** @ignore */ export declare const toFloat64ArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Float64Array>; /** @ignore */ export declare const toUint8ClampedArrayAsyncIterator: ( input: ArrayBufferViewAsyncIteratorInput ) => AsyncIterableIterator<Uint8ClampedArray>; /** @ignore */ export declare function rebaseValueOffsets( offset: number, length: number, valueOffsets: Int32Array ): Int32Array; /** @ignore */ export declare function compareArrayLike<T extends ArrayLike<any>>( a: T, b: T ): boolean; export {};
the_stack
* @packageDocumentation * @hidden */ import { DEV, EDITOR, SUPPORT_JIT, TEST } from 'internal:constants'; import { errorID, warnID, error } from '../platform/debug'; import * as js from '../utils/js'; import { getSuper } from '../utils/js'; import { BitMask } from '../value-types'; import { Enum } from '../value-types/enum'; import * as attributeUtils from './utils/attribute'; import { IAcceptableAttributes } from './utils/attribute-defines'; import { preprocessAttrs } from './utils/preprocess-class'; import * as RF from './utils/requiring-frame'; import { legacyCC } from '../global-exports'; const DELIMETER = attributeUtils.DELIMETER; function pushUnique (array, item) { if (array.indexOf(item) < 0) { array.push(item); } } const deferredInitializer: any = { // Configs for classes which needs deferred initialization datas: null, // register new class // data - {cls: cls, cb: properties, mixins: options.mixins} push (data) { if (this.datas) { this.datas.push(data); } else { this.datas = [data]; // start a new timer to initialize const self = this; setTimeout(() => { self.init(); }, 0); } }, init () { const datas = this.datas; if (datas) { for (let i = 0; i < datas.length; ++i) { const data = datas[i]; const cls = data.cls; let properties = data.props; if (typeof properties === 'function') { properties = properties(); } const name = js.getClassName(cls); if (properties) { declareProperties(cls, name, properties, cls.$super, data.mixins); } else { errorID(3633, name); } } this.datas = null; } }, }; // both getter and prop must register the name into __props__ array function appendProp (cls, name) { if (DEV) { // if (!IDENTIFIER_RE.test(name)) { // error('The property name "' + name + '" is not compliant with JavaScript naming standards'); // return; // } if (name.indexOf('.') !== -1) { errorID(3634); return; } } pushUnique(cls.__props__, name); } function defineProp (cls, className, propName, val) { if (DEV) { // check base prototype to avoid name collision if (CCClass.getInheritanceChain(cls) .some((x) => x.prototype.hasOwnProperty(propName))) { errorID(3637, className, propName, className); return; } } appendProp(cls, propName); // apply attributes parseAttributes(cls, val, className, propName, false); if ((EDITOR && !window.Build) || TEST) { for (let i = 0; i < onAfterProps_ET.length; i++) { onAfterProps_ET[i](cls, propName); } onAfterProps_ET.length = 0; } } function defineGetSet (cls, name, propName, val) { const getter = val.get; const setter = val.set; if (getter) { parseAttributes(cls, val, name, propName, true); if ((EDITOR && !window.Build) || TEST) { onAfterProps_ET.length = 0; } attributeUtils.setClassAttr(cls, propName, 'serializable', false); if (DEV) { // 不论是否 visible 都要添加到 props,否则 asset watcher 不能正常工作 appendProp(cls, propName); } if (EDITOR || DEV) { attributeUtils.setClassAttr(cls, propName, 'hasGetter', true); // 方便 editor 做判断 } } if (setter) { if (EDITOR || DEV) { attributeUtils.setClassAttr(cls, propName, 'hasSetter', true); // 方便 editor 做判断 } } } function getDefault (defaultVal) { if (typeof defaultVal === 'function') { if (EDITOR) { try { return defaultVal(); } catch (e) { legacyCC._throw(e); return undefined; } } else { return defaultVal(); } } return defaultVal; } function mixinWithInherited (dest, src, filter?) { for (const prop in src) { if (!dest.hasOwnProperty(prop) && (!filter || filter(prop))) { Object.defineProperty(dest, prop, js.getPropertyDescriptor(src, prop)!); } } } function doDefine (className, baseClass, mixins, options) { const ctor = options.ctor; if (DEV) { // check ctor if (CCClass._isCCClass(ctor)) { errorID(3618, className); } } const ctors = [ctor]; const fireClass = ctor; js.value(fireClass, '__ctors__', ctors.length > 0 ? ctors : null, true); const prototype = fireClass.prototype; if (baseClass) { fireClass.$super = baseClass; } if (mixins) { for (let m = mixins.length - 1; m >= 0; m--) { const mixin = mixins[m]; mixinWithInherited(prototype, mixin.prototype); // mixin attributes if (CCClass._isCCClass(mixin)) { mixinWithInherited(attributeUtils.getClassAttrs(fireClass), attributeUtils.getClassAttrs(mixin)); } } // restore constuctor overridden by mixin prototype.constructor = fireClass; } js.setClassName(className, fireClass); return fireClass; } function define (className, baseClass, mixins, options) { const Component = legacyCC.Component; const frame = RF.peek(); if (frame && js.isChildClassOf(baseClass, Component)) { // project component if (js.isChildClassOf(frame.cls, Component)) { errorID(3615); return null; } if (DEV && frame.uuid && className) { // warnID(3616, className); } className = className || frame.script; } const cls = doDefine(className, baseClass, mixins, options); if (EDITOR) { // for RenderPipeline, RenderFlow, RenderStage const isRenderPipeline = js.isChildClassOf(baseClass, legacyCC.RenderPipeline); const isRenderFlow = js.isChildClassOf(baseClass, legacyCC.RenderFlow); const isRenderStage = js.isChildClassOf(baseClass, legacyCC.RenderStage); const isRender = isRenderPipeline || isRenderFlow || isRenderStage; if (isRender) { let renderName = ''; if (isRenderPipeline) { renderName = 'render_pipeline'; } else if (isRenderFlow) { renderName = 'render_flow'; } else if (isRenderStage) { renderName = 'render_stage'; } // 增加了 hidden: 开头标识,使它最终不会显示在 Editor inspector 的添加组件列表里 window.EditorExtends && window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1); } // Note: `options.ctor` should be same as `cls` except if // cc-class is defined by `cc.Class({/* ... */})`. // In such case, `options.ctor` may be `undefined`. // So we can not use `options.ctor`. Instead we should use `cls` which is the "real" registered cc-class. EditorExtends.emit('class-registered', cls, frame, className); } if (frame) { // 基础的 ts, js 脚本组件 if (js.isChildClassOf(baseClass, Component)) { const uuid = frame.uuid; if (uuid) { js._setClassId(uuid, cls); if (EDITOR) { cls.prototype.__scriptUuid = EditorExtends.UuidUtils.decompressUuid(uuid); } } frame.cls = cls; } else if (!js.isChildClassOf(frame.cls, Component)) { frame.cls = cls; } } return cls; } function getNewValueTypeCodeJit (value) { const clsName = js.getClassName(value); const type = value.constructor; let res = `new ${clsName}(`; for (let i = 0; i < type.__props__.length; i++) { const prop = type.__props__[i]; const propVal = value[prop]; if (DEV && typeof propVal === 'object') { errorID(3641, clsName); return `new ${clsName}()`; } res += propVal; if (i < type.__props__.length - 1) { res += ','; } } return `${res})`; } // TODO - move escapeForJS, IDENTIFIER_RE, getNewValueTypeCodeJit to misc.js or a new source file // convert a normal string including newlines, quotes and unicode characters into a string literal // ready to use in JavaScript source function escapeForJS (s) { return JSON.stringify(s) // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029'); } // simple test variable name const IDENTIFIER_RE = /^[A-Za-z_$][0-9A-Za-z_$]*$/; function declareProperties (cls, className, properties, baseClass, mixins) { cls.__props__ = []; if (baseClass && baseClass.__props__) { cls.__props__ = baseClass.__props__.slice(); } if (mixins) { for (let m = 0; m < mixins.length; ++m) { const mixin = mixins[m]; if (mixin.__props__) { cls.__props__ = cls.__props__.concat(mixin.__props__.filter((x) => cls.__props__.indexOf(x) < 0)); } } } if (properties) { // 预处理属性 preprocessAttrs(properties, className, cls); for (const propName in properties) { const val = properties[propName]; if (!val.get && !val.set) { defineProp(cls, className, propName, val); } else { defineGetSet(cls, className, propName, val); } } } const attrs = attributeUtils.getClassAttrs(cls); cls.__values__ = cls.__props__.filter((prop) => attrs[`${prop + DELIMETER}serializable`] !== false); } export function CCClass<TFunction> (options: { name?: string; extends: null | (Function & { __props__?: any; _sealed?: boolean }); ctor: TFunction; properties?: any; mixins?: (Function & { __props__?: any })[]; editor?: any; }) { let name = options.name; const base = options.extends/* || CCObject */; const mixins = options.mixins; // create constructor const cls = define(name, base, mixins, options); if (!name) { name = legacyCC.js.getClassName(cls); } cls._sealed = true; if (base) { base._sealed = false; } // define Properties const properties = options.properties; if (typeof properties === 'function' || (base && base.__props__ === null) || (mixins && mixins.some((x) => x.__props__ === null)) ) { if (DEV) { error('not yet implement deferred properties.'); } else { deferredInitializer.push({ cls, props: properties, mixins }); cls.__props__ = cls.__values__ = null; } } else { declareProperties(cls, name, properties, base, options.mixins); } const editor = options.editor; if (editor) { if (js.isChildClassOf(base, legacyCC.Component)) { legacyCC.Component._registerEditorProps(cls, editor); } else if (DEV) { warnID(3623, name); } } return cls; } /** * @en * Checks whether the constructor is created by `Class`. * @zh * 检查构造函数是否由 `Class` 创建。 * @method _isCCClass * @param {Function} constructor * @return {Boolean} * @private */ CCClass._isCCClass = function isCCClass (constructor): boolean { // Does not support fastDefined class (ValueType). // Use `instanceof ValueType` if necessary. // eslint-disable-next-line no-prototype-builtins, @typescript-eslint/no-unsafe-return return constructor?.hasOwnProperty?.('__ctors__'); // __ctors__ is not inherited }; // // Optimized define function only for internal classes // // @method fastDefine // @param {String} className // @param {Function} constructor // @param {Object} serializableFields // @private // CCClass.fastDefine = function (className, constructor, serializableFields) { js.setClassName(className, constructor); // constructor.__ctors__ = constructor.__ctors__ || null; const props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields); const attrs = attributeUtils.getClassAttrs(constructor); for (let i = 0; i < props.length; i++) { const key = props[i]; attrs[`${key + DELIMETER}visible`] = false; attrs[`${key + DELIMETER}default`] = serializableFields[key]; } }; CCClass.Attr = attributeUtils; CCClass.attr = attributeUtils.attr; /** * Return all super classes. * @param constructor The Constructor. */ function getInheritanceChain (constructor) { const chain: any[] = []; for (; ;) { constructor = getSuper(constructor); if (!constructor) { break; } if (constructor !== Object) { chain.push(constructor); } } return chain; } CCClass.getInheritanceChain = getInheritanceChain; const PrimitiveTypes = { // Specify that the input value must be integer in Properties. // Also used to indicates that the type of elements in array or the type of value in dictionary is integer. Integer: 'Number', // Indicates that the type of elements in array or the type of value in dictionary is double. Float: 'Number', Boolean: 'Boolean', String: 'String', }; interface IParsedAttribute extends IAcceptableAttributes { ctor?: Function; enumList?: readonly any[]; bitmaskList?: any[]; } type OnAfterProp = (constructor: Function, mainPropertyName: string) => void; const onAfterProps_ET: OnAfterProp[] = []; interface AttributesRecord { get?: unknown; set?: unknown; default?: unknown; } function parseAttributes (constructor: Function, attributes: IAcceptableAttributes & AttributesRecord, className: string, propertyName: string, usedInGetter) { const ERR_Type = DEV ? 'The %s of %s must be type %s' : ''; let attrs: IParsedAttribute | null = null; let propertyNamePrefix = ''; function initAttrs () { propertyNamePrefix = propertyName + DELIMETER; return attrs = attributeUtils.getClassAttrs(constructor); } if ((EDITOR && !window.Build) || TEST) { onAfterProps_ET.length = 0; } if ('type' in attributes && typeof attributes.type === 'undefined') { warnID(3660, propertyName, className); } let warnOnNoDefault = true; const type = attributes.type; if (type) { const primitiveType = PrimitiveTypes[type]; if (primitiveType) { (attrs || initAttrs())[`${propertyNamePrefix}type`] = type; if (((EDITOR && !window.Build) || TEST) && !attributes._short) { onAfterProps_ET.push(attributeUtils.getTypeChecker_ET(primitiveType, `cc.${type}`)); } } else if (type === 'Object') { if (DEV) { errorID(3644, className, propertyName); } } // else if (type === Attr.ScriptUuid) { // (attrs || initAttrs())[propertyNamePrefix + 'type'] = 'Script'; // attrs[propertyNamePrefix + 'ctor'] = cc.ScriptAsset; // } else if (typeof type === 'object') { if (Enum.isEnum(type)) { (attrs || initAttrs())[`${propertyNamePrefix}type`] = 'Enum'; attrs![`${propertyNamePrefix}enumList`] = Enum.getList(type); } else if (BitMask.isBitMask(type)) { (attrs || initAttrs())[`${propertyNamePrefix}type`] = 'BitMask'; attrs![`${propertyNamePrefix}bitmaskList`] = BitMask.getList(type); } else if (DEV) { errorID(3645, className, propertyName, type); } } else if (typeof type === 'function') { // Do not warn missing-default if the type is object warnOnNoDefault = false; (attrs || initAttrs())[`${propertyNamePrefix}type`] = 'Object'; attrs![`${propertyNamePrefix}ctor`] = type; if (((EDITOR && !window.Build) || TEST) && !attributes._short) { onAfterProps_ET.push(attributeUtils.getObjTypeChecker_ET(type)); } } else if (DEV) { errorID(3646, className, propertyName, type); } } if ('default' in attributes) { (attrs || initAttrs())[`${propertyNamePrefix}default`] = attributes.default; } else if (((EDITOR && !window.Build) || TEST) && warnOnNoDefault && !(attributes.get || attributes.set)) { warnID(3654, className, propertyName); } const parseSimpleAttribute = (attributeName: keyof IAcceptableAttributes, expectType: string) => { if (attributeName in attributes) { const val = attributes[attributeName]; if (typeof val === expectType) { (attrs || initAttrs())[propertyNamePrefix + attributeName] = val; } else if (DEV) { error(ERR_Type, attributeName, className, propertyName, expectType); } } }; if (attributes.editorOnly) { if (DEV && usedInGetter) { errorID(3613, 'editorOnly', className, propertyName); } else { (attrs || initAttrs())[`${propertyNamePrefix}editorOnly`] = true; } } // parseSimpleAttr('preventDeferredLoad', 'boolean'); if (DEV) { parseSimpleAttribute('displayName', 'string'); parseSimpleAttribute('displayOrder', 'number'); parseSimpleAttribute('multiline', 'boolean'); parseSimpleAttribute('radian', 'boolean'); if (attributes.readonly) { (attrs || initAttrs())[`${propertyNamePrefix}readonly`] = attributes.readonly; } parseSimpleAttribute('tooltip', 'string'); if (attributes.group) { (attrs || initAttrs())[`${propertyNamePrefix}group`] = attributes.group; } parseSimpleAttribute('slide', 'boolean'); parseSimpleAttribute('unit', 'string'); } if (attributes.__noImplicit) { (attrs || initAttrs())[`${propertyNamePrefix}serializable`] = attributes.serializable ?? false; } else if (attributes.serializable === false) { if (DEV && usedInGetter) { errorID(3613, 'serializable', className, propertyName); } else { (attrs || initAttrs())[`${propertyNamePrefix}serializable`] = false; } } parseSimpleAttribute('formerlySerializedAs', 'string'); if (EDITOR) { if ('animatable' in attributes) { (attrs || initAttrs())[`${propertyNamePrefix}animatable`] = attributes.animatable; } } if (DEV) { if (attributes.__noImplicit) { (attrs || initAttrs())[`${propertyNamePrefix}visible`] = attributes.visible ?? false; } else { const visible = attributes.visible; if (typeof visible !== 'undefined') { if (!visible) { (attrs || initAttrs())[`${propertyNamePrefix}visible`] = false; } else if (typeof visible === 'function') { (attrs || initAttrs())[`${propertyNamePrefix}visible`] = visible; } } else { const startsWithUS = (propertyName.charCodeAt(0) === 95); if (startsWithUS) { (attrs || initAttrs())[`${propertyNamePrefix}visible`] = false; } } } } const range = attributes.range; if (range) { if (Array.isArray(range)) { if (range.length >= 2) { (attrs || initAttrs())[`${propertyNamePrefix}min`] = range[0]; attrs![`${propertyNamePrefix}max`] = range[1]; if (range.length > 2) { attrs![`${propertyNamePrefix}step`] = range[2]; } } else if (DEV) { errorID(3647); } } else if (DEV) { error(ERR_Type, 'range', className, propertyName, 'array'); } } parseSimpleAttribute('min', 'number'); parseSimpleAttribute('max', 'number'); parseSimpleAttribute('step', 'number'); } CCClass.isArray = function (defaultVal) { defaultVal = getDefault(defaultVal); return Array.isArray(defaultVal); }; CCClass.getDefault = getDefault; CCClass.escapeForJS = escapeForJS; CCClass.IDENTIFIER_RE = IDENTIFIER_RE; CCClass.getNewValueTypeCode = (SUPPORT_JIT && getNewValueTypeCodeJit) as ((value: any) => string); legacyCC.Class = CCClass;
the_stack
import Chart from './chart'; import dataRange from '@src/store/dataRange'; import scale from '@src/store/scale'; import gaugeAxesData from '@src/store/gaugeAxes'; import Tooltip from '@src/component/tooltip'; import GaugeSeries from '@src/component/gaugeSeries'; import Title from '@src/component/title'; import ExportMenu from '@src/component/exportMenu'; import HoveredSeries from '@src/component/hoveredSeries'; import DataLabels from '@src/component/dataLabels'; import AxisTitle from '@src/component/axisTitle'; import SelectedSeries from '@src/component/selectedSeries'; import Background from '@src/component/background'; import RadialAxis from '@src/component/radialAxis'; import RadialPlot from '@src/component/radialPlot'; import NoDataText from '@src/component/noDataText'; import * as basicBrush from '@src/brushes/basic'; import * as legendBrush from '@src/brushes/legend'; import * as labelBrush from '@src/brushes/label'; import * as exportMenuBrush from '@src/brushes/exportMenu'; import * as sectorBrush from '@src/brushes/sector'; import * as dataLabelBrush from '@src/brushes/dataLabel'; import * as axisBrush from '@src/brushes/axis'; import * as gaugeBrush from '@src/brushes/gauge'; import { GaugeChartOptions, GaugeSeriesData, GaugeSeriesDataType, GaugeSeriesInput, GaugePlotBand, } from '@t/options'; import { GaugeChartProps, SelectSeriesInfo } from '@t/charts'; /** * @class * @classdesc Gauge Chart * @param {Object} props * @param {HTMLElement} props.el - The target element to create chart. * @param {Object} props.data - Data for making Gauge Chart. * @param {Array<string>} [props.data.categories] - Categories. * @param {Array<Object>} props.data.series - Series data. * @param {string} props.data.series.name - Series name. * @param {number} props.data.series.data - Series data. * @param {Object} [props.options] - Options for making Gauge Chart. * @param {Object} [props.options.chart] * @param {string|Object} [props.options.chart.title] - Chart title text or options. * @param {string} [props.options.chart.title.text] - Chart title text. * @param {number} [props.options.chart.title.offsetX] - Offset value to move title horizontally. * @param {number} [props.options.chart.title.offsetY] - Offset value to move title vertically. * @param {string} [props.options.chart.title.align] - Chart text align. 'left', 'right', 'center' is available. * @param {boolean|Object} [props.options.chart.animation] - Whether to use animation and duration when rendering the initial chart. * @param {number|string} [props.options.chart.width] - Chart width. 'auto' or if not write, the width of the parent container is followed. 'auto' or if not created, the width of the parent container is followed. * @param {number|string} [props.options.chart.height] - Chart height. 'auto' or if not write, the width of the parent container is followed. 'auto' or if not created, the height of the parent container is followed. * @param {Object} [props.options.series] * @param {boolean} [props.options.series.selectable=false] - Whether to make selectable series or not. * @param {Object} [props.options.series.dataLabels] - Set the visibility, location, and formatting of dataLabel. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Gauge Chart guide} on github. * @param {Array<number>} [props.options.series.angleRange] - The range of angles to which the circle will be drawn. It is specified by putting number in start and end. * @param {boolean} [props.options.series.clockwise] - Whether it will be drawn clockwise. * @param {boolean | Object} [props.options.series.solid] - When this option is set, the radial bar is displayed. It can be used when there is one series data. The default value is 'false'. * @param {Object} [props.options.circularAxis] * @param {string|Object} [props.options.circularAxis.title] - Axis title. * @param {Object} [props.options.circularAxis.tick] - Option to adjust tick interval. * @param {Object} [props.options.circularAxis.label] - Option to adjust label interval. * @param {Object} [props.options.circularAxis.scale] - Option to adjust axis minimum, maximum, step size. * @param {Object} [props.options.plot] * @param {number} [props.options.plot.width] - Width of plot. * @param {number} [props.options.plot.height] - Height of plot. * @param {Array<Object>} [props.options.plot.bands] - Plot bands information. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Gauge Chart guide} on github. * @param {Object} [props.options.exportMenu] * @param {boolean} [props.options.exportMenu.visible] - Whether to show export menu. * @param {string} [props.options.exportMenu.filename] - File name applied when downloading. * @param {Object} [props.options.tooltip] * @param {number} [props.options.tooltip.offsetX] - Offset value to move title horizontally. * @param {number} [props.options.tooltip.offsetY] - Offset value to move title vertically. * @param {Function} [props.options.tooltip.formatter] - Function to format data value. * @param {Function} [props.options.tooltip.template] - Function to create custom template. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Tooltip guide} on github. * @param {Object} [props.options.responsive] - Rules for changing chart options. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Responsive guide} on github. * @param {boolean|Object} [props.options.responsive.animation] - Animation duration when the chart is modified. * @param {Array<Object>} [props.options.responsive.rules] - Rules for the Chart to Respond. * @param {Object} [props.options.theme] - Chart theme options. For specific information, refer to the {@link https://github.com/nhn/tui.chart|Gauge Chart guide} on github. * @param {Object} [props.options.theme.chart] - Chart font theme. * @param {Object} [props.options.theme.series] - Series theme. * @param {Object} [props.options.theme.title] - Title theme. * @param {Object} [props.options.theme.circularAxis] - Circular Axis theme. * @param {Object} [props.options.theme.tooltip] - Tooltip theme. * @param {Object} [props.options.theme.exportMenu] - ExportMenu theme. * @param {Object} [props.options.theme.plot] - Plot Theme. * @extends Chart */ export default class GaugeChart extends Chart<GaugeChartOptions> { constructor({ el, options, data }: GaugeChartProps) { super({ el, options, series: { gauge: data.series, }, categories: data.categories, modules: [dataRange, scale, gaugeAxesData], }); } protected initialize() { super.initialize(); this.componentManager.add(Background); this.componentManager.add(Title); this.componentManager.add(RadialPlot, { name: 'gauge' }); this.componentManager.add(RadialAxis, { name: 'gauge' }); this.componentManager.add(AxisTitle, { name: 'circularAxis' }); this.componentManager.add(GaugeSeries); this.componentManager.add(HoveredSeries); this.componentManager.add(SelectedSeries); this.componentManager.add(DataLabels); this.componentManager.add(ExportMenu, { chartEl: this.el }); this.componentManager.add(Tooltip, { chartEl: this.el }); this.componentManager.add(NoDataText); this.painter.addGroups([ basicBrush, legendBrush, labelBrush, exportMenuBrush, sectorBrush, dataLabelBrush, axisBrush, gaugeBrush, ]); } /** * Add series. * @param {Object} data - Data to be added. * @param {string} data.name - Series name. * @param {Array<number|Array<number>>} data.data - Array of data to be added. * @api * @example * chart.addSeries({ * name: 'newSeries', * data: [10, 20], * }); */ addSeries(data: GaugeSeriesInput) { this.resetSeries(); this.store.dispatch('addSeries', { data }); } /** * Add data. * @param {Array} data - Array of data to be added. * @param {string} [category] - Category to be added. * @api * @example * // without categories * chart.addData([10], '6'); * * // with categories * chart.addData([10], '6'); */ addData(data: GaugeSeriesDataType[], category?: string) { this.resetSeries(); this.animationControlFlag.updating = true; this.store.dispatch('addData', { data, category }); } /** * Convert the chart data to new data. * @param {Object} data - Data to be set. * @api * @example * chart.setData({ * categories: ['1', '2', '3'], * series: [ * { * name: 'new series', * data: [1, 2, 3], * }, * { * name: 'new series2', * data: [4, 5, 6], * } * ] * }); */ setData(data: GaugeSeriesData) { const { categories, series } = data; this.resetSeries(); this.store.dispatch('setData', { series: { gauge: series }, categories }); } /** * Hide series data label. * @api * @example * chart.hideSeriesDataLabel(); */ hideSeriesDataLabel() { this.store.dispatch('updateOptions', { options: { series: { dataLabels: { visible: false } } }, }); } /** * Show series data label. * @api * @example * chart.showSeriesDataLabel(); */ showSeriesDataLabel() { this.store.dispatch('updateOptions', { options: { series: { dataLabels: { visible: true } } }, }); } /** * Convert the chart options to new options. * @param {Object} options - Chart options. * @api * @example * chart.setOptions({ * chart: { * width: 500, * height: 500, * title: 'Olympic Medals', * }, * series: { * selectable: true * } * }); */ setOptions(options: GaugeChartOptions) { this.resetSeries(); this.dispatchOptionsEvent('initOptions', options); } /** * Update chart options. * @param {Object} options - Chart options. * @api * @example * chart.updateOptions({ * chart: { * title: 'Olympic Medals', * } * }); */ updateOptions(options: GaugeChartOptions) { this.resetSeries(); this.dispatchOptionsEvent('updateOptions', options); } /** * Show tooltip. * @param {Object} seriesInfo - Information of the series for the tooltip to be displayed. * @param {number} seriesInfo.index - Index of data within series. * @api * @example * chart.showTooltip({index: 1}); */ showTooltip(seriesInfo: SelectSeriesInfo) { this.eventBus.emit('showTooltip', { ...seriesInfo, state: this.store.state }); } /** * Hide tooltip. * @api * @example * chart.hideTooltip(); */ hideTooltip() { this.eventBus.emit('hideTooltip'); } /** * Add plot band. * @param {Object} data - Plot info. * @param {Array<string|number>} data.range - The range to be drawn. * @param {string} data.color - Plot band color. * @param {string} [data.id] - Plot id. The value on which the removePlotBand is based. * @api * @example * chart.addPlotBand({ * range: [10, 20], * color: '#00ff22', * id: 'plot-1', * }); */ addPlotBand(data: GaugePlotBand) { this.store.dispatch('addGaugePlotBand', { data }); } /** * Remove plot band with id. * @param {string} id - id of the plot band to be removed * @api * @example * chart.removePlotBand('plot-1'); */ removePlotBand(id: string) { this.store.dispatch('removeGaugePlotBand', { id }); } }
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { IconLoaderService } from '../../../index'; import { AmexioThemeSwitcherService } from '../../services/data/amexio.theme.service'; import { CommonIconComponent } from './../../base/components/common.icon.component'; // import { StepWizardComponent } from './stepwizard.component'; import { AmexioCardCEComponent } from '../../creative/card/amexio.cards.component'; import { AmexioCardCEHeaderComponent } from '../../creative/common/amexio.header.component'; import { AmexioImageComponent } from '../../media/image/image.component'; import { AmexioCardCEBodyComponent } from '../../creative/common/amexio.body.component'; import { AmexioCardCEActionComponent } from '../../creative/common/amexio.action.component'; import { AmexioFormActionCEComponent } from '../../creative/form/form.action.component' import { AmexioFormCEComponent } from '../../creative/form/amexio.form.component'; import { AmexiodialoguePaneComponent } from '../../panes/dialogue/dialogue.pane.component'; import { AmexioLabelComponent } from '../../forms/label/label.component'; import { AmexioCardComponent } from '../../layout/card/card.component'; import { AmexioHeaderComponent } from '../../panes/header/pane.action.header'; import { AmexioBodyComponent } from '../../panes/body/pane.action.body'; import { AmexioFooterComponent } from '../../panes/action/pane.action.footer'; import { AmexioButtonComponent } from '../../forms/buttons/button.component'; import { AmexioContextMenuComponent } from '../../base/base.contextmenu.component'; import { DeviceQueryService } from '../../services/device/device.query.service'; import { SpeechBubbleComponent } from '../../data/speech-bubble/speech-bubble.component'; import { AmexioNavDesktopMenuComponent } from '../../navigation/navbar/navdesktopmenu'; import { AmexioThemeSwitcherComponent } from './amexio.themeswitcher.component'; import { AmexioFloatingButtonComponent } from '../../forms/floatingbutton/floatingbutton.component'; import { AmexioToggleComponent } from '../../forms/toggle/toggle.component'; import { HttpClient, HttpHandler } from '@angular/common/http'; import { SimpleChange } from '@angular/core'; // import { CommonIconComponent} from '../../base/components/common.icon.component'; // import { } describe('theme switcher', () => { let comp1: AmexioThemeSwitcherComponent; let fixture1: ComponentFixture<AmexioThemeSwitcherComponent>; let service: AmexioThemeSwitcherService; beforeEach(() => { TestBed.configureTestingModule({ imports: [FormsModule], declarations: [AmexioNavDesktopMenuComponent, AmexioToggleComponent, AmexioFloatingButtonComponent, AmexioThemeSwitcherComponent, AmexioFormActionCEComponent, SpeechBubbleComponent, AmexioButtonComponent, AmexioFooterComponent, AmexioHeaderComponent, AmexioBodyComponent, AmexioCardComponent, AmexioLabelComponent, AmexioContextMenuComponent, AmexiodialoguePaneComponent, AmexioFormCEComponent, AmexioCardCEBodyComponent, AmexioCardCEActionComponent, AmexioImageComponent, AmexioCardCEComponent, AmexioCardCEHeaderComponent, CommonIconComponent], providers: [IconLoaderService, HttpClient, HttpHandler, DeviceQueryService, AmexioThemeSwitcherService], }); fixture1 = TestBed.createComponent(AmexioThemeSwitcherComponent); comp1 = fixture1.componentInstance; service = TestBed.get(AmexioThemeSwitcherService); }); it('ngOninit method if condition', () => { comp1.ngOnInit(); comp1.buttonType = 'floatingbutton' expect(comp1.buttonType).toEqual('floatingbutton'); comp1.isFloatingButton = true; comp1.buttonType = 'button' comp1.ngOnInit(); expect(comp1.buttonType).toEqual('button'); comp1.isSimpleButton = true; comp1.relative = true comp1.closeable = false; comp1.ngOnInit(); expect(comp1.relative).toEqual(true); expect(comp1.closeable).toEqual(false); comp1.show = true; service.themeData.subscribe((theme: any) => { theme = 'aaa'; expect(theme).not.toEqual(null); comp1.onThemeClick.emit(theme); }); }); it('ngOninit method else condition', () => { comp1.ngOnInit(); comp1.buttonType = ''; expect(comp1.buttonType).toEqual(''); comp1.buttonType = ''; comp1.ngOnInit(); expect(comp1.buttonType).toEqual(''); comp1.relative = false; comp1.closeable = true; comp1.ngOnInit(); expect(comp1.relative).toEqual(false); expect(comp1.closeable).toEqual(true); comp1.loadMDAThemes(); service.themeData.subscribe((theme: any) => { theme = ''; expect(theme).toEqual(''); comp1.onThemeClick.emit(theme); }); }); // it('ngOninit method else condition', () => { // comp1.ngOnInit(); // comp1.buttonType = '' // expect(comp1.buttonType).toEqual(''); // comp1.buttonType = '' // expect(comp1.buttonType).toEqual(''); // comp1.relative = false // comp1.closeable = true; // expect(comp1.relative).toEqual(false); // expect(comp1.closeable).toEqual(true); // comp1.loadMDAThemes(); // let theme: null; // service.themeData.subscribe((theme: any) => { // expect(theme).not.toEqual(null) // comp1.onThemeClick.emit(theme); // }); // }); it('loadMDAThemes method else block', () => { comp1.isMDA = false; comp1.loadMDAThemes(); expect(comp1.isMDA).toEqual(false); }); it('loadMDAThemes method', () => { comp1.loadMDAThemes(); expect(comp1.isMDA).toBeDefined(); let responseData = [ [ { "themeName": "Army Olive", "style": "Material Design", "releaseDate": "Jan 31, 2018", "version": 4, "algorithmName": "Classic Dual Color", "algorithmID": 0, "rgb": 4936480, "hue": 69, "themes": [ "#4B5320", "#708238", "#215429", "#215442", "#214d54", "#213354" ], "navBarBGColor": "#4b5320", "navBarFontColor": "#f8f9f0", "themeFilePath": "../node_modules/amexio-ng-extensions/styles/mda/at-md-army-olive.scss", "themeJSONFile": "at-md-army-olive.json", "themeCSS3File": "at-md-army-olive.scss", "themeImageFile": "AT-MD-Army-Olive.jpg" }, { "themeName": "Ash Stone Black", "style": "Material Design", "releaseDate": "Jan 31, 2018", "version": 4, "algorithmName": "Classic Dual Color", "algorithmID": 0, "rgb": 5524554, "hue": 12, "themes": [ "#544C4A", "#877f7d", "#52544a", "#4d544a", "#4a544c", "#4a5451" ], "navBarBGColor": "#544c4a", "navBarFontColor": "#f5f4f4", "themeFilePath": "../node_modules/amexio-ng-extensions/styles/mda/at-md-ash-stone-black.scss", "themeJSONFile": "at-md-ash-stone-black.json", "themeCSS3File": "at-md-ash-stone-black.scss", "themeImageFile": "AT-MD-Ash-Stone-Black.jpg" }, { "themeName": "Black", "style": "Material Design", "releaseDate": "Jan 31, 2018", "version": 4, "algorithmName": "Classic Dual Color", "algorithmID": 0, "rgb": 0, "hue": 0, "themes": [ "#000000", "#290500", "#000000", "#000000", "#000000", "#000000" ], "navBarBGColor": "#000000", "navBarFontColor": "#f5f5f5", "themeFilePath": "../node_modules/amexio-ng-extensions/styles/mda/at-md-black.scss", "themeJSONFile": "at-md-black.json", "themeCSS3File": "at-md-black.scss", "themeImageFile": "AT-MD-Black.jpg" } ], [ { "themeName": "Blue", "style": "Material Design", "releaseDate": "Jan 31, 2018", "version": 4, "algorithmName": "Classic Dual Color", "algorithmID": 0, "rgb": 1402304, "hue": 212, "themes": [ "#1565C0", "#2196f3", "#7115c1", "#c115bb", "#c11565", "#c11b15" ], "navBarBGColor": "#1565c0", "navBarFontColor": "#f1f7fd", "themeFilePath": "../node_modules/amexio-ng-extensions/styles/mda/at-md-blue.scss", "themeJSONFile": "at-md-blue.json", "themeCSS3File": "at-md-blue.scss", "themeImageFile": "AT-MD-Blue.jpg" }, { "themeName": "Blue Grey", "style": "Material Design", "releaseDate": "Jan 31, 2018", "version": 4, "algorithmName": "Classic Dual Color", "algorithmID": 0, "rgb": 1390406, "hue": 198, "themes": [ "#153746", "#455a64", "#241547", "#3d1547", "#471538", "#47151f" ], "navBarBGColor": "#153746", "navBarFontColor": "#f3f9fb", "themeFilePath": "../node_modules/amexio-ng-extensions/styles/mda/at-md-blue-grey.scss", "themeJSONFile": "at-md-blue-grey.json", "themeCSS3File": "at-md-blue-grey.scss", "themeImageFile": "AT-MD-Blue-Grey.jpg" }, { "themeName": "Bruntor Tangerine", "style": "Material Design", "releaseDate": "Jan 31, 2018", "version": 4, "algorithmName": "Classic Dual Color", "algorithmID": 0, "rgb": 9846784, "hue": 26, "themes": [ "#964000", "#cf912a", "#549400", "#0a9400", "#009440", "#00948a" ], "navBarBGColor": "#964000", "navBarFontColor": "#fff3eb", "themeFilePath": "../node_modules/amexio-ng-extensions/styles/mda/at-md-bruntor-tangerine.scss", "themeJSONFile": "at-md-bruntor-tangerine.json", "themeCSS3File": "at-md-bruntor-tangerine.scss", "themeImageFile": "AT-MD-Bruntor-Tangerine.jpg" } ] ]; service.loadThemes('assets/amexiomdathemes/json/amexio-mda.json') .subscribe((data: any) => { responseData = data; }, (error: any) => { }, () => { comp1.data = responseData; }); }); it('getPostion() if condition', () => { let style = {} comp1.closeable = false; comp1.getPostion(style); expect(comp1.closeable).toEqual(false); style['position'] = 'relative'; comp1.relative = true; comp1.closeable = true; comp1.getPostion(style); expect(comp1.closeable).toEqual(true); expect(comp1.relative).toEqual(true); style['position'] = 'absolute'; style['right'] = '0'; comp1.relative = false; comp1.closeable = false; expect(comp1.closeable).toEqual(false); expect(comp1.relative).toEqual(false); // } else { style['position'] = 'fixed'; // } // return style; }); it('getPostion() else condition', () => { let style = {} comp1.getPostion(style); comp1.relative = false; comp1.closeable = false; expect(comp1.closeable).toEqual(false); expect(comp1.relative).toEqual(false); style['position'] = 'fixed'; }); it('togglePanel()', () => { comp1.togglePanel(); comp1.show = true; comp1.show = !comp1.show; comp1.onclose.emit(comp1); }); it('onChange()', () => { let value = true; comp1.onChange(value); comp1.isMoreDetails = value; }); it('themeChange()', () => { let theme = 'red'; comp1.themeChange(theme); let service = AmexioThemeSwitcherService; // new AmexioThemeSwitcherService.switchTheme(theme); }); it('ngOnChanges()', () => { let changes: any; changes = { show: true, currentValue: 12 }; comp1.ngOnChanges(changes); // if (changes['show']) { expect(changes['show']).toEqual(true); comp1.show = changes.show.currentValue; // } }); it('ngOnChanges() else block', () => { let changes: any; changes = { show: false, currentValue: 12 }; comp1.ngOnChanges(changes); expect(changes['show']).toEqual(false); }); it('themeStyle()', () => { comp1.themeStyle(); const windowWidth = window.innerWidth; const perBlockWidth = ((windowWidth / 100) * 35) / 3; const style1 = {}; const style = comp1.getPostion(style1); style['display'] = 'block'; comp1.closeable = true; comp1.themeStyle(); expect(comp1.closeable).toEqual(true); style['z-index'] = '600'; comp1.closeable = false; comp1.themeStyle(); expect(comp1.closeable).toEqual(false); style['z-index'] = '0'; comp1.colsize = 3; comp1.themeStyle(); expect(comp1.colsize).toBeLessThanOrEqual(3) style['min-width'] = '250px'; comp1.colsize = 4; comp1.themeStyle(); expect(comp1.colsize).toBeGreaterThan(3) style['min-width'] = '200px'; return style; }); it('themeStyle() relative method if condition', () => { const windowWidth = window.innerWidth; const perBlockWidth = ((windowWidth / 100) * 35) / 3; comp1.relative = false; comp1.horizontalPosition = '50'; comp1.verticalPosition = '89' const style1 = {}; const style = comp1.getPostion(style1); comp1.themeStyle(); expect(comp1.relative).toEqual(false); const hpos = comp1.positionMapData['hpos-' + comp1.horizontalPosition]; const vpos = comp1.positionMapData['vpos-' + comp1.verticalPosition]; comp1.closeable = true; comp1.themeStyle(); expect(comp1.closeable).toEqual(true); style['width'] = (perBlockWidth * comp1.colsize) + 'px'; return style; }); it('themeStyle() relative method else condition', () => { comp1.relative = true; const style1 = {}; const style = comp1.getPostion(style1); comp1.themeStyle(); expect(comp1.relative).toEqual(true); style['margin-top'] = '10px'; comp1.closeable = false; comp1.themeStyle(); expect(comp1.closeable).toEqual(false); style['width'] = '100%'; return style; }); });
the_stack